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": 6,
"code_window": [
"\t\t\t\t// we only validate the first focused element\n",
"\t\t\t\tconst focusedElement = e.elements[0];\n",
"\n",
"\t\t\t\tcursorSelectionLisener = focusedElement.onDidChangeCursorSelection(() => {\n",
"\t\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcursorSelectionListener = focusedElement.onDidChangeCursorSelection(() => {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 87
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
//@ts-check
/**
* @param {NodeRequire} nodeRequire
* @param {typeof import('path')} path
* @param {typeof import('fs')} fs
* @param {typeof import('../common/performance')} perf
*/
function factory(nodeRequire, path, fs, perf) {
/**
* @param {string} file
* @returns {Promise<boolean>}
*/
function exists(file) {
return new Promise(c => fs.exists(file, c));
}
/**
* @param {string} file
* @returns {Promise<void>}
*/
function touch(file) {
return new Promise((c, e) => { const d = new Date(); fs.utimes(file, d, d, err => err ? e(err) : c()); });
}
/**
* @param {string} file
* @returns {Promise<object>}
*/
function lstat(file) {
return new Promise((c, e) => fs.lstat(file, (err, stats) => err ? e(err) : c(stats)));
}
/**
* @param {string} dir
* @returns {Promise<string[]>}
*/
function readdir(dir) {
return new Promise((c, e) => fs.readdir(dir, (err, files) => err ? e(err) : c(files)));
}
/**
* @param {string} dir
* @returns {Promise<string>}
*/
function mkdirp(dir) {
return new Promise((c, e) => fs.mkdir(dir, { recursive: true }, err => (err && err.code !== 'EEXIST') ? e(err) : c(dir)));
}
/**
* @param {string} dir
* @returns {Promise<void>}
*/
function rmdir(dir) {
return new Promise((c, e) => fs.rmdir(dir, err => err ? e(err) : c(undefined)));
}
/**
* @param {string} file
* @returns {Promise<void>}
*/
function unlink(file) {
return new Promise((c, e) => fs.unlink(file, err => err ? e(err) : c(undefined)));
}
/**
* @param {string} location
* @returns {Promise<void>}
*/
function rimraf(location) {
return lstat(location).then(stat => {
if (stat.isDirectory() && !stat.isSymbolicLink()) {
return readdir(location)
.then(children => Promise.all(children.map(child => rimraf(path.join(location, child)))))
.then(() => rmdir(location));
} else {
return unlink(location);
}
}, err => {
if (err.code === 'ENOENT') {
return undefined;
}
throw err;
});
}
function readFile(file) {
return new Promise(function (resolve, reject) {
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
reject(err);
return;
}
resolve(data);
});
});
}
/**
* @param {string} file
* @param {string} content
* @returns {Promise<void>}
*/
function writeFile(file, content) {
return new Promise(function (resolve, reject) {
fs.writeFile(file, content, 'utf8', function (err) {
if (err) {
reject(err);
return;
}
resolve();
});
});
}
/**
* @param {string} userDataPath
* @returns {object}
*/
function getLanguagePackConfigurations(userDataPath) {
const configFile = path.join(userDataPath, 'languagepacks.json');
try {
return nodeRequire(configFile);
} catch (err) {
// Do nothing. If we can't read the file we have no
// language pack config.
}
return undefined;
}
/**
* @param {object} config
* @param {string} locale
*/
function resolveLanguagePackLocale(config, locale) {
try {
while (locale) {
if (config[locale]) {
return locale;
} else {
const index = locale.lastIndexOf('-');
if (index > 0) {
locale = locale.substring(0, index);
} else {
return undefined;
}
}
}
} catch (err) {
console.error('Resolving language pack configuration failed.', err);
}
return undefined;
}
/**
* @param {string} commit
* @param {string} userDataPath
* @param {string} metaDataFile
* @param {string} locale
*/
function getNLSConfiguration(commit, userDataPath, metaDataFile, locale) {
if (locale === 'pseudo') {
return Promise.resolve({ locale: locale, availableLanguages: {}, pseudo: true });
}
if (process.env['VSCODE_DEV']) {
return Promise.resolve({ locale: locale, availableLanguages: {} });
}
// We have a built version so we have extracted nls file. Try to find
// the right file to use.
// Check if we have an English or English US locale. If so fall to default since that is our
// English translation (we don't ship *.nls.en.json files)
if (locale && (locale === 'en' || locale === 'en-us')) {
return Promise.resolve({ locale: locale, availableLanguages: {} });
}
const initialLocale = locale;
perf.mark('nlsGeneration:start');
const defaultResult = function (locale) {
perf.mark('nlsGeneration:end');
return Promise.resolve({ locale: locale, availableLanguages: {} });
};
try {
if (!commit) {
return defaultResult(initialLocale);
}
const configs = getLanguagePackConfigurations(userDataPath);
if (!configs) {
return defaultResult(initialLocale);
}
locale = resolveLanguagePackLocale(configs, locale);
if (!locale) {
return defaultResult(initialLocale);
}
const packConfig = configs[locale];
let mainPack;
if (!packConfig || typeof packConfig.hash !== 'string' || !packConfig.translations || typeof (mainPack = packConfig.translations['vscode']) !== 'string') {
return defaultResult(initialLocale);
}
return exists(mainPack).then(fileExists => {
if (!fileExists) {
return defaultResult(initialLocale);
}
const packId = packConfig.hash + '.' + locale;
const cacheRoot = path.join(userDataPath, 'clp', packId);
const coreLocation = path.join(cacheRoot, commit);
const translationsConfigFile = path.join(cacheRoot, 'tcf.json');
const corruptedFile = path.join(cacheRoot, 'corrupted.info');
const result = {
locale: initialLocale,
availableLanguages: { '*': locale },
_languagePackId: packId,
_translationsConfigFile: translationsConfigFile,
_cacheRoot: cacheRoot,
_resolvedLanguagePackCoreLocation: coreLocation,
_corruptedFile: corruptedFile
};
return exists(corruptedFile).then(corrupted => {
// The nls cache directory is corrupted.
let toDelete;
if (corrupted) {
toDelete = rimraf(cacheRoot);
} else {
toDelete = Promise.resolve(undefined);
}
return toDelete.then(() => {
return exists(coreLocation).then(fileExists => {
if (fileExists) {
// We don't wait for this. No big harm if we can't touch
touch(coreLocation).catch(() => { });
perf.mark('nlsGeneration:end');
return result;
}
return mkdirp(coreLocation).then(() => {
return Promise.all([readFile(metaDataFile), readFile(mainPack)]);
}).then(values => {
const metadata = JSON.parse(values[0]);
const packData = JSON.parse(values[1]).contents;
const bundles = Object.keys(metadata.bundles);
const writes = [];
for (const bundle of bundles) {
const modules = metadata.bundles[bundle];
const target = Object.create(null);
for (const module of modules) {
const keys = metadata.keys[module];
const defaultMessages = metadata.messages[module];
const translations = packData[module];
let targetStrings;
if (translations) {
targetStrings = [];
for (let i = 0; i < keys.length; i++) {
const elem = keys[i];
const key = typeof elem === 'string' ? elem : elem.key;
let translatedMessage = translations[key];
if (translatedMessage === undefined) {
translatedMessage = defaultMessages[i];
}
targetStrings.push(translatedMessage);
}
} else {
targetStrings = defaultMessages;
}
target[module] = targetStrings;
}
writes.push(writeFile(path.join(coreLocation, bundle.replace(/\//g, '!') + '.nls.json'), JSON.stringify(target)));
}
writes.push(writeFile(translationsConfigFile, JSON.stringify(packConfig.translations)));
return Promise.all(writes);
}).then(() => {
perf.mark('nlsGeneration:end');
return result;
}).catch(err => {
console.error('Generating translation files failed.', err);
return defaultResult(locale);
});
});
});
});
});
} catch (err) {
console.error('Generating translation files failed.', err);
return defaultResult(locale);
}
}
return {
getNLSConfiguration
};
}
if (typeof define === 'function') {
// amd
define(['path', 'fs', 'vs/base/common/performance'], function (path, fs, perf) { return factory(require.__$__nodeRequire, path, fs, perf); });
} else if (typeof module === 'object' && typeof module.exports === 'object') {
const path = require('path');
const fs = require('fs');
const perf = require('../common/performance');
module.exports = factory(require, path, fs, perf);
} else {
throw new Error('Unknown context');
}
| src/vs/base/node/languagePacks.js | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017727239173837006,
0.000172605796251446,
0.00016634113853797317,
0.00017257872968912125,
0.0000025555950742273126
] |
{
"id": 6,
"code_window": [
"\t\t\t\t// we only validate the first focused element\n",
"\t\t\t\tconst focusedElement = e.elements[0];\n",
"\n",
"\t\t\t\tcursorSelectionLisener = focusedElement.onDidChangeCursorSelection(() => {\n",
"\t\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcursorSelectionListener = focusedElement.onDidChangeCursorSelection(() => {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 87
} | /*---------------------------------------------------------------------------------------------
* 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!./welcomeOverlay';
import * as dom from 'vs/base/browser/dom';
import { Registry } from 'vs/platform/registry/common/platform';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ShowAllCommandsAction } from 'vs/workbench/contrib/quickopen/browser/commandsHandler';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ILayoutService } from 'vs/platform/layout/browser/layoutService';
import { localize } from 'vs/nls';
import { Action } from 'vs/base/common/actions';
import { IWorkbenchActionRegistry, Extensions } from 'vs/workbench/common/actions';
import { SyncActionDescriptor } from 'vs/platform/actions/common/actions';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { Disposable } from 'vs/base/common/lifecycle';
import { RawContextKey, IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { KeyCode } from 'vs/base/common/keyCodes';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { textPreformatForeground, foreground } from 'vs/platform/theme/common/colorRegistry';
import { Color } from 'vs/base/common/color';
const $ = dom.$;
interface Key {
id: string;
arrow?: string;
label: string;
command?: string;
arrowLast?: boolean;
withEditor?: boolean;
}
const keys: Key[] = [
{
id: 'explorer',
arrow: '←',
label: localize('welcomeOverlay.explorer', "File explorer"),
command: 'workbench.view.explorer'
},
{
id: 'search',
arrow: '←',
label: localize('welcomeOverlay.search', "Search across files"),
command: 'workbench.view.search'
},
{
id: 'git',
arrow: '←',
label: localize('welcomeOverlay.git', "Source code management"),
command: 'workbench.view.scm'
},
{
id: 'debug',
arrow: '←',
label: localize('welcomeOverlay.debug', "Launch and debug"),
command: 'workbench.view.debug'
},
{
id: 'extensions',
arrow: '←',
label: localize('welcomeOverlay.extensions', "Manage extensions"),
command: 'workbench.view.extensions'
},
// {
// id: 'watermark',
// arrow: '⤹',
// label: localize('welcomeOverlay.watermark', "Command Hints"),
// withEditor: false
// },
{
id: 'problems',
arrow: '⤹',
label: localize('welcomeOverlay.problems', "View errors and warnings"),
command: 'workbench.actions.view.problems'
},
{
id: 'terminal',
label: localize('welcomeOverlay.terminal', "Toggle integrated terminal"),
command: 'workbench.action.terminal.toggleTerminal'
},
// {
// id: 'openfile',
// arrow: '⤸',
// label: localize('welcomeOverlay.openfile', "File Properties"),
// arrowLast: true,
// withEditor: true
// },
{
id: 'commandPalette',
arrow: '↖',
label: localize('welcomeOverlay.commandPalette', "Find and run all commands"),
command: ShowAllCommandsAction.ID
},
{
id: 'notifications',
arrow: '⤵',
arrowLast: true,
label: localize('welcomeOverlay.notifications', "Show notifications"),
command: 'notifications.showList'
}
];
const OVERLAY_VISIBLE = new RawContextKey<boolean>('interfaceOverviewVisible', false);
let welcomeOverlay: WelcomeOverlay;
export class WelcomeOverlayAction extends Action {
public static readonly ID = 'workbench.action.showInterfaceOverview';
public static readonly LABEL = localize('welcomeOverlay', "User Interface Overview");
constructor(
id: string,
label: string,
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
super(id, label);
}
public run(): Promise<void> {
if (!welcomeOverlay) {
welcomeOverlay = this.instantiationService.createInstance(WelcomeOverlay);
}
welcomeOverlay.show();
return Promise.resolve();
}
}
export class HideWelcomeOverlayAction extends Action {
public static readonly ID = 'workbench.action.hideInterfaceOverview';
public static readonly LABEL = localize('hideWelcomeOverlay', "Hide Interface Overview");
constructor(
id: string,
label: string
) {
super(id, label);
}
public run(): Promise<void> {
if (welcomeOverlay) {
welcomeOverlay.hide();
}
return Promise.resolve();
}
}
class WelcomeOverlay extends Disposable {
private _overlayVisible: IContextKey<boolean>;
private _overlay!: HTMLElement;
constructor(
@ILayoutService private readonly layoutService: ILayoutService,
@IEditorService private readonly editorService: IEditorService,
@ICommandService private readonly commandService: ICommandService,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
@IKeybindingService private readonly keybindingService: IKeybindingService
) {
super();
this._overlayVisible = OVERLAY_VISIBLE.bindTo(this._contextKeyService);
this.create();
}
private create(): void {
const offset = this.layoutService.offset?.top ?? 0;
this._overlay = dom.append(this.layoutService.container, $('.welcomeOverlay'));
this._overlay.style.top = `${offset}px`;
this._overlay.style.height = `calc(100% - ${offset}px)`;
this._overlay.style.display = 'none';
this._overlay.tabIndex = -1;
this._register(dom.addStandardDisposableListener(this._overlay, 'click', () => this.hide()));
this.commandService.onWillExecuteCommand(() => this.hide());
dom.append(this._overlay, $('.commandPalettePlaceholder'));
const editorOpen = !!this.editorService.visibleEditors.length;
keys.filter(key => !('withEditor' in key) || key.withEditor === editorOpen)
.forEach(({ id, arrow, label, command, arrowLast }) => {
const div = dom.append(this._overlay, $(`.key.${id}`));
if (arrow && !arrowLast) {
dom.append(div, $('span.arrow')).innerHTML = arrow;
}
dom.append(div, $('span.label')).textContent = label;
if (command) {
const shortcut = this.keybindingService.lookupKeybinding(command);
if (shortcut) {
dom.append(div, $('span.shortcut')).textContent = shortcut.getLabel();
}
}
if (arrow && arrowLast) {
dom.append(div, $('span.arrow')).innerHTML = arrow;
}
});
}
public show() {
if (this._overlay.style.display !== 'block') {
this._overlay.style.display = 'block';
const workbench = document.querySelector('.monaco-workbench') as HTMLElement;
dom.addClass(workbench, 'blur-background');
this._overlayVisible.set(true);
this.updateProblemsKey();
this.updateActivityBarKeys();
this._overlay.focus();
}
}
private updateProblemsKey() {
const problems = document.querySelector('div[id="workbench.parts.statusbar"] .statusbar-item.left .codicon.codicon-warning');
const key = this._overlay.querySelector('.key.problems') as HTMLElement;
if (problems instanceof HTMLElement) {
const target = problems.getBoundingClientRect();
const bounds = this._overlay.getBoundingClientRect();
const bottom = bounds.bottom - target.top + 3;
const left = (target.left + target.right) / 2 - bounds.left;
key.style.bottom = bottom + 'px';
key.style.left = left + 'px';
} else {
key.style.bottom = '';
key.style.left = '';
}
}
private updateActivityBarKeys() {
const ids = ['explorer', 'search', 'git', 'debug', 'extensions'];
const activityBar = document.querySelector('.activitybar .composite-bar');
if (activityBar instanceof HTMLElement) {
const target = activityBar.getBoundingClientRect();
const bounds = this._overlay.getBoundingClientRect();
for (let i = 0; i < ids.length; i++) {
const key = this._overlay.querySelector(`.key.${ids[i]}`) as HTMLElement;
const top = target.top - bounds.top + 50 * i + 13;
key.style.top = top + 'px';
}
} else {
for (let i = 0; i < ids.length; i++) {
const key = this._overlay.querySelector(`.key.${ids[i]}`) as HTMLElement;
key.style.top = '';
}
}
}
public hide() {
if (this._overlay.style.display !== 'none') {
this._overlay.style.display = 'none';
const workbench = document.querySelector('.monaco-workbench') as HTMLElement;
dom.removeClass(workbench, 'blur-background');
this._overlayVisible.reset();
}
}
}
Registry.as<IWorkbenchActionRegistry>(Extensions.WorkbenchActions)
.registerWorkbenchAction(SyncActionDescriptor.create(WelcomeOverlayAction, WelcomeOverlayAction.ID, WelcomeOverlayAction.LABEL), 'Help: User Interface Overview', localize('help', "Help"));
Registry.as<IWorkbenchActionRegistry>(Extensions.WorkbenchActions)
.registerWorkbenchAction(SyncActionDescriptor.create(HideWelcomeOverlayAction, HideWelcomeOverlayAction.ID, HideWelcomeOverlayAction.LABEL, { primary: KeyCode.Escape }, OVERLAY_VISIBLE), 'Help: Hide Interface Overview', localize('help', "Help"));
// theming
registerThemingParticipant((theme, collector) => {
const key = theme.getColor(foreground);
if (key) {
collector.addRule(`.monaco-workbench > .welcomeOverlay > .key { color: ${key}; }`);
}
const backgroundColor = Color.fromHex(theme.type === 'light' ? '#FFFFFF85' : '#00000085');
if (backgroundColor) {
collector.addRule(`.monaco-workbench > .welcomeOverlay { background: ${backgroundColor}; }`);
}
const shortcut = theme.getColor(textPreformatForeground);
if (shortcut) {
collector.addRule(`.monaco-workbench > .welcomeOverlay > .key > .shortcut { color: ${shortcut}; }`);
}
});
| src/vs/workbench/contrib/welcome/overlay/browser/welcomeOverlay.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0001789497910067439,
0.00017286653746850789,
0.00016661608242429793,
0.00017280274187214673,
0.0000032441405437566573
] |
{
"id": 7,
"code_window": [
"\t\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\t});\n",
"\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\treturn;\n",
"\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\t\t\ttextEditorAttachListener = focusedElement.onDidChangeEditorAttachState(() => {\n",
"\t\t\t\t\tif (focusedElement.editorAttached) {\n",
"\t\t\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t});\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "add",
"edit_start_line_idx": 90
} | /*---------------------------------------------------------------------------------------------
* 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 { IListRenderer, IListVirtualDelegate, ListError } from 'vs/base/browser/ui/list/list';
import { Event } from 'vs/base/common/event';
import { ScrollEvent } from 'vs/base/common/scrollable';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IListService, IWorkbenchListOptions, WorkbenchList } from 'vs/platform/list/browser/listService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { isMacintosh } from 'vs/base/common/platform';
import { NOTEBOOK_EDITOR_CURSOR_BOUNDARY } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { Range } from 'vs/editor/common/core/range';
import { CellRevealType, CellRevealPosition, CursorAtBoundary } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';
import { EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable {
get onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }
get rowsContainer(): HTMLElement {
return this.view.containerDomNode;
}
private _previousSelectedElements: CellViewModel[] = [];
private _localDisposableStore = new DisposableStore();
constructor(
private listUser: string,
container: HTMLElement,
delegate: IListVirtualDelegate<CellViewModel>,
renderers: IListRenderer<CellViewModel, any>[],
contextKeyService: IContextKeyService,
options: IWorkbenchListOptions<CellViewModel>,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService
) {
super(listUser, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService);
this._previousSelectedElements = this.getSelectedElements();
this._localDisposableStore.add(this.onDidChangeSelection((e) => {
this._previousSelectedElements.forEach(element => {
if (e.elements.indexOf(element) < 0) {
element.onDeselect();
}
});
this._previousSelectedElements = e.elements;
}));
const notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);
notebookEditorCursorAtBoundaryContext.set('none');
let cursorSelectionLisener: IDisposable | null = null;
const recomputeContext = (element: CellViewModel) => {
switch (element.cursorAtBoundary()) {
case CursorAtBoundary.Both:
notebookEditorCursorAtBoundaryContext.set('both');
break;
case CursorAtBoundary.Top:
notebookEditorCursorAtBoundaryContext.set('top');
break;
case CursorAtBoundary.Bottom:
notebookEditorCursorAtBoundaryContext.set('bottom');
break;
default:
notebookEditorCursorAtBoundaryContext.set('none');
break;
}
return;
};
// Cursor Boundary context
this._localDisposableStore.add(this.onDidChangeFocus((e) => {
cursorSelectionLisener?.dispose();
if (e.elements.length) {
// we only validate the first focused element
const focusedElement = e.elements[0];
cursorSelectionLisener = focusedElement.onDidChangeCursorSelection(() => {
recomputeContext(focusedElement);
});
recomputeContext(focusedElement);
return;
}
// reset context
notebookEditorCursorAtBoundaryContext.set('none');
}));
}
domElementAtIndex(index: number): HTMLElement | null {
return this.view.domElement(index);
}
focusView() {
this.view.domNode.focus();
}
getAbsoluteTop(index: number): number {
if (index < 0 || index >= this.length) {
throw new ListError(this.listUser, `Invalid index ${index}`);
}
return this.view.elementTop(index);
}
triggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {
this.view.triggerScrollFromMouseWheelEvent(browserEvent);
}
updateElementHeight(index: number, size: number): void {
const focused = this.getSelection();
this.view.updateElementHeight(index, size, focused.length ? focused[0] : null);
// this.view.updateElementHeight(index, size, null);
}
// override
domFocus() {
if (document.activeElement && this.view.domNode.contains(document.activeElement)) {
// for example, when focus goes into monaco editor, if we refocus the list view, the editor will lose focus.
return;
}
if (!isMacintosh && document.activeElement && isContextMenuFocused()) {
return;
}
super.domFocus();
}
private _revealRange(index: number, range: Range, revealType: CellRevealType, newlyCreated: boolean, alignToBottom: boolean) {
const element = this.view.element(index);
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const startLineNumber = range.startLineNumber;
const lineOffset = element.getLineScrollTopOffset(startLineNumber);
const elementTop = this.view.elementTop(index);
const lineTop = elementTop + lineOffset + EDITOR_TOP_PADDING;
// TODO@rebornix 30 ---> line height * 1.5
if (lineTop < scrollTop) {
this.view.setScrollTop(lineTop - 30);
} else if (lineTop > wrapperBottom) {
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else if (newlyCreated) {
// newly scrolled into view
if (alignToBottom) {
// align to the bottom
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else {
// align to to top
this.view.setScrollTop(lineTop - 30);
}
}
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
}
// TODO@rebornix TEST & Fix potential bugs
// List items have real dynamic heights, which means after we set `scrollTop` based on the `elementTop(index)`, the element at `index` might still be removed from the view once all relayouting tasks are done.
// For example, we scroll item 10 into the view upwards, in the first round, items 7, 8, 9, 10 are all in the viewport. Then item 7 and 8 resize themselves to be larger and finally item 10 is removed from the view.
// To ensure that item 10 is always there, we need to scroll item 10 to the top edge of the viewport.
private _revealRangeInternal(index: number, range: Range, revealType: CellRevealType) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const element = this.view.element(index);
if (element.editorAttached) {
this._revealRange(index, range, revealType, false, false);
} else {
const elementHeight = this.view.elementHeight(index);
let upwards = false;
if (elementTop + elementHeight < scrollTop) {
// scroll downwards
this.view.setScrollTop(elementTop);
upwards = false;
} else if (elementTop > wrapperBottom) {
// scroll upwards
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
upwards = true;
}
const editorAttachedPromise = new Promise((resolve, reject) => {
element.onDidChangeEditorAttachState(state => state ? resolve() : reject());
});
editorAttachedPromise.then(() => {
this._revealRange(index, range, revealType, true, upwards);
});
}
}
revealLineInView(index: number, line: number) {
this._revealRangeInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInView(index: number, range: Range): void {
this._revealRangeInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
};
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
const element = this.view.element(index);
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
reveal(index, range, revealType);
}
}
revealLineInCenter(index: number, line: number) {
this._revealRangeInCenterInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenter(index: number, range: Range): void {
this._revealRangeInCenterInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterIfOutsideViewportInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
setTimeout(() => {
element.revealRangeInCenter(range);
}, 240);
}
};
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
const element = this.view.element(index);
if (viewItemOffset < scrollTop || viewItemOffset > wrapperBottom) {
// let it render
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
// after rendering, it might be pushed down due to markdown cell dynamic height
const elementTop = this.view.elementTop(index);
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
// reveal editor
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
// for example markdown
}
} else {
if (element.editorAttached) {
element.revealRangeInCenter(range);
} else {
// for example, markdown cell in preview mode
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
}
}
}
revealLineInCenterIfOutsideViewport(index: number, line: number) {
this._revealRangeInCenterIfOutsideViewportInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenterIfOutsideViewport(index: number, range: Range): void {
this._revealRangeInCenterIfOutsideViewportInternal(index, range, CellRevealType.Range);
}
private _revealInternal(index: number, ignoreIfInsideViewport: boolean, revealPosition: CellRevealPosition) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
if (ignoreIfInsideViewport && elementTop >= scrollTop && elementTop < wrapperBottom) {
// inside the viewport
return;
}
// first render
const viewItemOffset = revealPosition === CellRevealPosition.Top ? elementTop : (elementTop - this.view.renderHeight / 2);
this.view.setScrollTop(viewItemOffset);
// second scroll as markdown cell is dynamic
const newElementTop = this.view.elementTop(index);
const newViewItemOffset = revealPosition === CellRevealPosition.Top ? newElementTop : (newElementTop - this.view.renderHeight / 2);
this.view.setScrollTop(newViewItemOffset);
}
revealInView(index: number) {
this._revealInternal(index, true, CellRevealPosition.Top);
}
revealInCenter(index: number) {
this._revealInternal(index, false, CellRevealPosition.Center);
}
revealInCenterIfOutsideViewport(index: number) {
this._revealInternal(index, true, CellRevealPosition.Center);
}
setCellSelection(index: number, range: Range) {
const element = this.view.element(index);
if (element.editorAttached) {
element.setSelection(range);
} else {
getEditorAttachedPromise(element).then(() => { element.setSelection(range); });
}
}
dispose() {
this._localDisposableStore.dispose();
super.dispose();
}
}
function getEditorAttachedPromise(element: CellViewModel) {
return new Promise((resolve, reject) => {
Event.once(element.onDidChangeEditorAttachState)(state => state ? resolve() : reject());
});
}
function isContextMenuFocused() {
return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
}
| src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.069901242852211,
0.0023319858592003584,
0.0001646867167437449,
0.00017063489940483123,
0.01144732628017664
] |
{
"id": 7,
"code_window": [
"\t\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\t});\n",
"\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\treturn;\n",
"\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\t\t\ttextEditorAttachListener = focusedElement.onDidChangeEditorAttachState(() => {\n",
"\t\t\t\t\tif (focusedElement.editorAttached) {\n",
"\t\t\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t});\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "add",
"edit_start_line_idx": 90
} | /*---------------------------------------------------------------------------------------------
* 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 { debug, workspace, Disposable, commands, window } from 'vscode';
import { disposeAll } from '../utils';
import { basename } from 'path';
suite('Debug', function () {
test('breakpoints', async function () {
assert.equal(debug.breakpoints.length, 0);
let onDidChangeBreakpointsCounter = 0;
const toDispose: Disposable[] = [];
toDispose.push(debug.onDidChangeBreakpoints(() => {
onDidChangeBreakpointsCounter++;
}));
debug.addBreakpoints([{ id: '1', enabled: true }, { id: '2', enabled: false, condition: '2 < 5' }]);
assert.equal(onDidChangeBreakpointsCounter, 1);
assert.equal(debug.breakpoints.length, 2);
assert.equal(debug.breakpoints[0].id, '1');
assert.equal(debug.breakpoints[1].id, '2');
assert.equal(debug.breakpoints[1].condition, '2 < 5');
debug.removeBreakpoints([{ id: '1', enabled: true }]);
assert.equal(onDidChangeBreakpointsCounter, 2);
assert.equal(debug.breakpoints.length, 1);
debug.removeBreakpoints([{ id: '2', enabled: false }]);
assert.equal(onDidChangeBreakpointsCounter, 3);
assert.equal(debug.breakpoints.length, 0);
disposeAll(toDispose);
});
test.skip('start debugging', async function () {
let stoppedEvents = 0;
let variablesReceived: () => void;
let initializedReceived: () => void;
let configurationDoneReceived: () => void;
const toDispose: Disposable[] = [];
if (debug.activeDebugSession) {
// We are re-running due to flakyness, make sure to clear out state
let sessionTerminatedRetry: () => void;
toDispose.push(debug.onDidTerminateDebugSession(() => {
sessionTerminatedRetry();
}));
const sessionTerminatedPromise = new Promise<void>(resolve => sessionTerminatedRetry = resolve);
await commands.executeCommand('workbench.action.debug.stop');
await sessionTerminatedPromise;
}
const firstVariablesRetrieved = new Promise<void>(resolve => variablesReceived = resolve);
toDispose.push(debug.registerDebugAdapterTrackerFactory('*', {
createDebugAdapterTracker: () => ({
onDidSendMessage: m => {
if (m.event === 'stopped') {
stoppedEvents++;
}
if (m.type === 'response' && m.command === 'variables') {
variablesReceived();
}
if (m.event === 'initialized') {
initializedReceived();
}
if (m.command === 'configurationDone') {
configurationDoneReceived();
}
}
})
}));
const initializedPromise = new Promise<void>(resolve => initializedReceived = resolve);
const configurationDonePromise = new Promise<void>(resolve => configurationDoneReceived = resolve);
const success = await debug.startDebugging(workspace.workspaceFolders![0], 'Launch debug.js');
assert.equal(success, true);
await initializedPromise;
await configurationDonePromise;
await firstVariablesRetrieved;
assert.notEqual(debug.activeDebugSession, undefined);
assert.equal(stoppedEvents, 1);
const secondVariablesRetrieved = new Promise<void>(resolve => variablesReceived = resolve);
await commands.executeCommand('workbench.action.debug.stepOver');
await secondVariablesRetrieved;
assert.equal(stoppedEvents, 2);
const editor = window.activeTextEditor;
assert.notEqual(editor, undefined);
assert.equal(basename(editor!.document.fileName), 'debug.js');
const thirdVariablesRetrieved = new Promise<void>(resolve => variablesReceived = resolve);
await commands.executeCommand('workbench.action.debug.stepOver');
await thirdVariablesRetrieved;
assert.equal(stoppedEvents, 3);
const fourthVariablesRetrieved = new Promise<void>(resolve => variablesReceived = resolve);
await commands.executeCommand('workbench.action.debug.stepInto');
await fourthVariablesRetrieved;
assert.equal(stoppedEvents, 4);
const fifthVariablesRetrieved = new Promise<void>(resolve => variablesReceived = resolve);
await commands.executeCommand('workbench.action.debug.stepOut');
await fifthVariablesRetrieved;
assert.equal(stoppedEvents, 5);
let sessionTerminated: () => void;
toDispose.push(debug.onDidTerminateDebugSession(() => {
sessionTerminated();
}));
const sessionTerminatedPromise = new Promise<void>(resolve => sessionTerminated = resolve);
await commands.executeCommand('workbench.action.debug.stop');
await sessionTerminatedPromise;
disposeAll(toDispose);
});
test('start debugging failure', async function () {
let errorCount = 0;
try {
await debug.startDebugging(workspace.workspaceFolders![0], 'non existent');
} catch (e) {
errorCount++;
}
assert.equal(errorCount, 1);
});
});
| extensions/vscode-api-tests/src/singlefolder-tests/debug.test.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00018861588614527136,
0.0001738519931677729,
0.00016586518904659897,
0.00017292085976805538,
0.000005694562787539326
] |
{
"id": 7,
"code_window": [
"\t\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\t});\n",
"\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\treturn;\n",
"\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\t\t\ttextEditorAttachListener = focusedElement.onDidChangeEditorAttachState(() => {\n",
"\t\t\t\t\tif (focusedElement.editorAttached) {\n",
"\t\t\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t});\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "add",
"edit_start_line_idx": 90
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { createHash } from 'crypto';
import { stat } from 'vs/base/node/pfs';
import { Schemas } from 'vs/base/common/network';
import { URI } from 'vs/base/common/uri';
import { isLinux, isMacintosh, isWindows } from 'vs/base/common/platform';
import { IResourceIdentityService } from 'vs/platform/resource/common/resourceIdentityService';
import { Disposable } from 'vs/base/common/lifecycle';
import { ResourceMap } from 'vs/base/common/map';
export class NativeResourceIdentityService extends Disposable implements IResourceIdentityService {
_serviceBrand: undefined;
private readonly cache: ResourceMap<Promise<string>> = new ResourceMap<Promise<string>>();
resolveResourceIdentity(resource: URI): Promise<string> {
let promise = this.cache.get(resource);
if (!promise) {
promise = this.createIdentity(resource);
this.cache.set(resource, promise);
}
return promise;
}
private async createIdentity(resource: URI): Promise<string> {
// Return early the folder is not local
if (resource.scheme !== Schemas.file) {
return createHash('md5').update(resource.toString()).digest('hex');
}
const fileStat = await stat(resource.fsPath);
let ctime: number | undefined;
if (isLinux) {
ctime = fileStat.ino; // Linux: birthtime is ctime, so we cannot use it! We use the ino instead!
} else if (isMacintosh) {
ctime = fileStat.birthtime.getTime(); // macOS: birthtime is fine to use as is
} else if (isWindows) {
if (typeof fileStat.birthtimeMs === 'number') {
ctime = Math.floor(fileStat.birthtimeMs); // Windows: fix precision issue in node.js 8.x to get 7.x results (see https://github.com/nodejs/node/issues/19897)
} else {
ctime = fileStat.birthtime.getTime();
}
}
// we use the ctime as extra salt to the ID so that we catch the case of a folder getting
// deleted and recreated. in that case we do not want to carry over previous state
return createHash('md5').update(resource.fsPath).update(ctime ? String(ctime) : '').digest('hex');
}
}
| src/vs/platform/resource/node/resourceIdentityServiceImpl.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017587012553121895,
0.00017360107449349016,
0.0001712010707706213,
0.0001738406135700643,
0.0000014050195886738948
] |
{
"id": 7,
"code_window": [
"\t\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\t});\n",
"\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\treturn;\n",
"\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\t\t\ttextEditorAttachListener = focusedElement.onDidChangeEditorAttachState(() => {\n",
"\t\t\t\t\tif (focusedElement.editorAttached) {\n",
"\t\t\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t});\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "add",
"edit_start_line_idx": 90
} | /*---------------------------------------------------------------------------------------------
* 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 { CharCode } from 'vs/base/common/charCode';
import { FIN } from './iterator';
/**
* @deprecated ES6: use `[...SetOrMap.values()]`
*/
export function values<V = any>(set: Set<V>): V[];
export function values<K = any, V = any>(map: Map<K, V>): V[];
export function values<V>(forEachable: { forEach(callback: (value: V, ...more: any[]) => any): void }): V[] {
const result: V[] = [];
forEachable.forEach(value => result.push(value));
return result;
}
/**
* @deprecated ES6: use `[...map.keys()]`
*/
export function keys<K, V>(map: Map<K, V>): K[] {
const result: K[] = [];
map.forEach((_value, key) => result.push(key));
return result;
}
export function getOrSet<K, V>(map: Map<K, V>, key: K, value: V): V {
let result = map.get(key);
if (result === undefined) {
result = value;
map.set(key, result);
}
return result;
}
export function mapToString<K, V>(map: Map<K, V>): string {
const entries: string[] = [];
map.forEach((value, key) => {
entries.push(`${key} => ${value}`);
});
return `Map(${map.size}) {${entries.join(', ')}}`;
}
export function setToString<K>(set: Set<K>): string {
const entries: K[] = [];
set.forEach(value => {
entries.push(value);
});
return `Set(${set.size}) {${entries.join(', ')}}`;
}
/**
* @deprecated ES6: use `...Map.entries()`
*/
export function mapToSerializable(map: Map<string, string>): [string, string][] {
const serializable: [string, string][] = [];
map.forEach((value, key) => {
serializable.push([key, value]);
});
return serializable;
}
/**
* @deprecated ES6: use `new Map([[key1, value1],[key2, value2]])`
*/
export function serializableToMap(serializable: [string, string][]): Map<string, string> {
const items = new Map<string, string>();
for (const [key, value] of serializable) {
items.set(key, value);
}
return items;
}
export interface IKeyIterator {
reset(key: string): this;
next(): this;
hasNext(): boolean;
cmp(a: string): number;
value(): string;
}
export class StringIterator implements IKeyIterator {
private _value: string = '';
private _pos: number = 0;
reset(key: string): this {
this._value = key;
this._pos = 0;
return this;
}
next(): this {
this._pos += 1;
return this;
}
hasNext(): boolean {
return this._pos < this._value.length - 1;
}
cmp(a: string): number {
const aCode = a.charCodeAt(0);
const thisCode = this._value.charCodeAt(this._pos);
return aCode - thisCode;
}
value(): string {
return this._value[this._pos];
}
}
export class PathIterator implements IKeyIterator {
private _value!: string;
private _from!: number;
private _to!: number;
constructor(private _splitOnBackslash: boolean = true) { }
reset(key: string): this {
this._value = key.replace(/\\$|\/$/, '');
this._from = 0;
this._to = 0;
return this.next();
}
hasNext(): boolean {
return this._to < this._value.length;
}
next(): this {
// this._data = key.split(/[\\/]/).filter(s => !!s);
this._from = this._to;
let justSeps = true;
for (; this._to < this._value.length; this._to++) {
const ch = this._value.charCodeAt(this._to);
if (ch === CharCode.Slash || this._splitOnBackslash && ch === CharCode.Backslash) {
if (justSeps) {
this._from++;
} else {
break;
}
} else {
justSeps = false;
}
}
return this;
}
cmp(a: string): number {
let aPos = 0;
const aLen = a.length;
let thisPos = this._from;
while (aPos < aLen && thisPos < this._to) {
const cmp = a.charCodeAt(aPos) - this._value.charCodeAt(thisPos);
if (cmp !== 0) {
return cmp;
}
aPos += 1;
thisPos += 1;
}
if (aLen === this._to - this._from) {
return 0;
} else if (aPos < aLen) {
return -1;
} else {
return 1;
}
}
value(): string {
return this._value.substring(this._from, this._to);
}
}
class TernarySearchTreeNode<E> {
segment!: string;
value: E | undefined;
key!: string;
left: TernarySearchTreeNode<E> | undefined;
mid: TernarySearchTreeNode<E> | undefined;
right: TernarySearchTreeNode<E> | undefined;
isEmpty(): boolean {
return !this.left && !this.mid && !this.right && !this.value;
}
}
export class TernarySearchTree<E> {
static forPaths<E>(): TernarySearchTree<E> {
return new TernarySearchTree<E>(new PathIterator());
}
static forStrings<E>(): TernarySearchTree<E> {
return new TernarySearchTree<E>(new StringIterator());
}
private _iter: IKeyIterator;
private _root: TernarySearchTreeNode<E> | undefined;
constructor(segments: IKeyIterator) {
this._iter = segments;
}
clear(): void {
this._root = undefined;
}
set(key: string, element: E): E | undefined {
const iter = this._iter.reset(key);
let node: TernarySearchTreeNode<E>;
if (!this._root) {
this._root = new TernarySearchTreeNode<E>();
this._root.segment = iter.value();
}
node = this._root;
while (true) {
const val = iter.cmp(node.segment);
if (val > 0) {
// left
if (!node.left) {
node.left = new TernarySearchTreeNode<E>();
node.left.segment = iter.value();
}
node = node.left;
} else if (val < 0) {
// right
if (!node.right) {
node.right = new TernarySearchTreeNode<E>();
node.right.segment = iter.value();
}
node = node.right;
} else if (iter.hasNext()) {
// mid
iter.next();
if (!node.mid) {
node.mid = new TernarySearchTreeNode<E>();
node.mid.segment = iter.value();
}
node = node.mid;
} else {
break;
}
}
const oldElement = node.value;
node.value = element;
node.key = key;
return oldElement;
}
get(key: string): E | undefined {
const iter = this._iter.reset(key);
let node = this._root;
while (node) {
const val = iter.cmp(node.segment);
if (val > 0) {
// left
node = node.left;
} else if (val < 0) {
// right
node = node.right;
} else if (iter.hasNext()) {
// mid
iter.next();
node = node.mid;
} else {
break;
}
}
return node ? node.value : undefined;
}
delete(key: string): void {
const iter = this._iter.reset(key);
const stack: [-1 | 0 | 1, TernarySearchTreeNode<E>][] = [];
let node = this._root;
// find and unset node
while (node) {
const val = iter.cmp(node.segment);
if (val > 0) {
// left
stack.push([1, node]);
node = node.left;
} else if (val < 0) {
// right
stack.push([-1, node]);
node = node.right;
} else if (iter.hasNext()) {
// mid
iter.next();
stack.push([0, node]);
node = node.mid;
} else {
// remove element
node.value = undefined;
// clean up empty nodes
while (stack.length > 0 && node.isEmpty()) {
let [dir, parent] = stack.pop()!;
switch (dir) {
case 1: parent.left = undefined; break;
case 0: parent.mid = undefined; break;
case -1: parent.right = undefined; break;
}
node = parent;
}
break;
}
}
}
findSubstr(key: string): E | undefined {
const iter = this._iter.reset(key);
let node = this._root;
let candidate: E | undefined = undefined;
while (node) {
const val = iter.cmp(node.segment);
if (val > 0) {
// left
node = node.left;
} else if (val < 0) {
// right
node = node.right;
} else if (iter.hasNext()) {
// mid
iter.next();
candidate = node.value || candidate;
node = node.mid;
} else {
break;
}
}
return node && node.value || candidate;
}
findSuperstr(key: string): Iterator<E> | undefined {
const iter = this._iter.reset(key);
let node = this._root;
while (node) {
const val = iter.cmp(node.segment);
if (val > 0) {
// left
node = node.left;
} else if (val < 0) {
// right
node = node.right;
} else if (iter.hasNext()) {
// mid
iter.next();
node = node.mid;
} else {
// collect
if (!node.mid) {
return undefined;
} else {
return this._nodeIterator(node.mid);
}
}
}
return undefined;
}
private _nodeIterator(node: TernarySearchTreeNode<E>): Iterator<E> {
let res: { done: false; value: E; };
let idx: number;
let data: E[];
const next = (): IteratorResult<E> => {
if (!data) {
// lazy till first invocation
data = [];
idx = 0;
this._forEach(node, value => data.push(value));
}
if (idx >= data.length) {
return FIN;
}
if (!res) {
res = { done: false, value: data[idx++] };
} else {
res.value = data[idx++];
}
return res;
};
return { next };
}
forEach(callback: (value: E, index: string) => any) {
this._forEach(this._root, callback);
}
private _forEach(node: TernarySearchTreeNode<E> | undefined, callback: (value: E, index: string) => any) {
if (node) {
// left
this._forEach(node.left, callback);
// node
if (node.value) {
// callback(node.value, this._iter.join(parts));
callback(node.value, node.key);
}
// mid
this._forEach(node.mid, callback);
// right
this._forEach(node.right, callback);
}
}
}
export class ResourceMap<T> {
protected readonly map: Map<string, T>;
protected readonly ignoreCase?: boolean;
constructor() {
this.map = new Map<string, T>();
this.ignoreCase = false; // in the future this should be an uri-comparator
}
set(resource: URI, value: T): void {
this.map.set(this.toKey(resource), value);
}
get(resource: URI): T | undefined {
return this.map.get(this.toKey(resource));
}
has(resource: URI): boolean {
return this.map.has(this.toKey(resource));
}
get size(): number {
return this.map.size;
}
clear(): void {
this.map.clear();
}
delete(resource: URI): boolean {
return this.map.delete(this.toKey(resource));
}
forEach(clb: (value: T, key: URI) => void): void {
this.map.forEach((value, index) => clb(value, URI.parse(index)));
}
values(): T[] {
return values(this.map);
}
private toKey(resource: URI): string {
let key = resource.toString();
if (this.ignoreCase) {
key = key.toLowerCase();
}
return key;
}
keys(): URI[] {
return keys(this.map).map(k => URI.parse(k));
}
clone(): ResourceMap<T> {
const resourceMap = new ResourceMap<T>();
this.map.forEach((value, key) => resourceMap.map.set(key, value));
return resourceMap;
}
}
interface Item<K, V> {
previous: Item<K, V> | undefined;
next: Item<K, V> | undefined;
key: K;
value: V;
}
export const enum Touch {
None = 0,
AsOld = 1,
AsNew = 2
}
export class LinkedMap<K, V> {
private _map: Map<K, Item<K, V>>;
private _head: Item<K, V> | undefined;
private _tail: Item<K, V> | undefined;
private _size: number;
constructor() {
this._map = new Map<K, Item<K, V>>();
this._head = undefined;
this._tail = undefined;
this._size = 0;
}
clear(): void {
this._map.clear();
this._head = undefined;
this._tail = undefined;
this._size = 0;
}
isEmpty(): boolean {
return !this._head && !this._tail;
}
get size(): number {
return this._size;
}
get first(): V | undefined {
return this._head?.value;
}
get last(): V | undefined {
return this._tail?.value;
}
has(key: K): boolean {
return this._map.has(key);
}
get(key: K, touch: Touch = Touch.None): V | undefined {
const item = this._map.get(key);
if (!item) {
return undefined;
}
if (touch !== Touch.None) {
this.touch(item, touch);
}
return item.value;
}
set(key: K, value: V, touch: Touch = Touch.None): void {
let item = this._map.get(key);
if (item) {
item.value = value;
if (touch !== Touch.None) {
this.touch(item, touch);
}
} else {
item = { key, value, next: undefined, previous: undefined };
switch (touch) {
case Touch.None:
this.addItemLast(item);
break;
case Touch.AsOld:
this.addItemFirst(item);
break;
case Touch.AsNew:
this.addItemLast(item);
break;
default:
this.addItemLast(item);
break;
}
this._map.set(key, item);
this._size++;
}
}
delete(key: K): boolean {
return !!this.remove(key);
}
remove(key: K): V | undefined {
const item = this._map.get(key);
if (!item) {
return undefined;
}
this._map.delete(key);
this.removeItem(item);
this._size--;
return item.value;
}
shift(): V | undefined {
if (!this._head && !this._tail) {
return undefined;
}
if (!this._head || !this._tail) {
throw new Error('Invalid list');
}
const item = this._head;
this._map.delete(item.key);
this.removeItem(item);
this._size--;
return item.value;
}
forEach(callbackfn: (value: V, key: K, map: LinkedMap<K, V>) => void, thisArg?: any): void {
let current = this._head;
while (current) {
if (thisArg) {
callbackfn.bind(thisArg)(current.value, current.key, this);
} else {
callbackfn(current.value, current.key, this);
}
current = current.next;
}
}
values(): V[] {
const result: V[] = [];
let current = this._head;
while (current) {
result.push(current.value);
current = current.next;
}
return result;
}
keys(): K[] {
const result: K[] = [];
let current = this._head;
while (current) {
result.push(current.key);
current = current.next;
}
return result;
}
/* VS Code / Monaco editor runs on es5 which has no Symbol.iterator
keys(): IterableIterator<K> {
const current = this._head;
const iterator: IterableIterator<K> = {
[Symbol.iterator]() {
return iterator;
},
next():IteratorResult<K> {
if (current) {
const result = { value: current.key, done: false };
current = current.next;
return result;
} else {
return { value: undefined, done: true };
}
}
};
return iterator;
}
values(): IterableIterator<V> {
const current = this._head;
const iterator: IterableIterator<V> = {
[Symbol.iterator]() {
return iterator;
},
next():IteratorResult<V> {
if (current) {
const result = { value: current.value, done: false };
current = current.next;
return result;
} else {
return { value: undefined, done: true };
}
}
};
return iterator;
}
*/
protected trimOld(newSize: number) {
if (newSize >= this.size) {
return;
}
if (newSize === 0) {
this.clear();
return;
}
let current = this._head;
let currentSize = this.size;
while (current && currentSize > newSize) {
this._map.delete(current.key);
current = current.next;
currentSize--;
}
this._head = current;
this._size = currentSize;
if (current) {
current.previous = undefined;
}
}
private addItemFirst(item: Item<K, V>): void {
// First time Insert
if (!this._head && !this._tail) {
this._tail = item;
} else if (!this._head) {
throw new Error('Invalid list');
} else {
item.next = this._head;
this._head.previous = item;
}
this._head = item;
}
private addItemLast(item: Item<K, V>): void {
// First time Insert
if (!this._head && !this._tail) {
this._head = item;
} else if (!this._tail) {
throw new Error('Invalid list');
} else {
item.previous = this._tail;
this._tail.next = item;
}
this._tail = item;
}
private removeItem(item: Item<K, V>): void {
if (item === this._head && item === this._tail) {
this._head = undefined;
this._tail = undefined;
}
else if (item === this._head) {
// This can only happend if size === 1 which is handle
// by the case above.
if (!item.next) {
throw new Error('Invalid list');
}
item.next.previous = undefined;
this._head = item.next;
}
else if (item === this._tail) {
// This can only happend if size === 1 which is handle
// by the case above.
if (!item.previous) {
throw new Error('Invalid list');
}
item.previous.next = undefined;
this._tail = item.previous;
}
else {
const next = item.next;
const previous = item.previous;
if (!next || !previous) {
throw new Error('Invalid list');
}
next.previous = previous;
previous.next = next;
}
item.next = undefined;
item.previous = undefined;
}
private touch(item: Item<K, V>, touch: Touch): void {
if (!this._head || !this._tail) {
throw new Error('Invalid list');
}
if ((touch !== Touch.AsOld && touch !== Touch.AsNew)) {
return;
}
if (touch === Touch.AsOld) {
if (item === this._head) {
return;
}
const next = item.next;
const previous = item.previous;
// Unlink the item
if (item === this._tail) {
// previous must be defined since item was not head but is tail
// So there are more than on item in the map
previous!.next = undefined;
this._tail = previous;
}
else {
// Both next and previous are not undefined since item was neither head nor tail.
next!.previous = previous;
previous!.next = next;
}
// Insert the node at head
item.previous = undefined;
item.next = this._head;
this._head.previous = item;
this._head = item;
} else if (touch === Touch.AsNew) {
if (item === this._tail) {
return;
}
const next = item.next;
const previous = item.previous;
// Unlink the item.
if (item === this._head) {
// next must be defined since item was not tail but is head
// So there are more than on item in the map
next!.previous = undefined;
this._head = next;
} else {
// Both next and previous are not undefined since item was neither head nor tail.
next!.previous = previous;
previous!.next = next;
}
item.next = undefined;
item.previous = this._tail;
this._tail.next = item;
this._tail = item;
}
}
toJSON(): [K, V][] {
const data: [K, V][] = [];
this.forEach((value, key) => {
data.push([key, value]);
});
return data;
}
fromJSON(data: [K, V][]): void {
this.clear();
for (const [key, value] of data) {
this.set(key, value);
}
}
}
export class LRUCache<K, V> extends LinkedMap<K, V> {
private _limit: number;
private _ratio: number;
constructor(limit: number, ratio: number = 1) {
super();
this._limit = limit;
this._ratio = Math.min(Math.max(0, ratio), 1);
}
get limit(): number {
return this._limit;
}
set limit(limit: number) {
this._limit = limit;
this.checkTrim();
}
get ratio(): number {
return this._ratio;
}
set ratio(ratio: number) {
this._ratio = Math.min(Math.max(0, ratio), 1);
this.checkTrim();
}
get(key: K): V | undefined {
return super.get(key, Touch.AsNew);
}
peek(key: K): V | undefined {
return super.get(key, Touch.None);
}
set(key: K, value: V): void {
super.set(key, value, Touch.AsNew);
this.checkTrim();
}
private checkTrim() {
if (this.size > this._limit) {
this.trimOld(Math.round(this._limit * this._ratio));
}
}
}
| src/vs/base/common/map.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00021162530174478889,
0.00017288925300817937,
0.0001651123457122594,
0.00017257007129956037,
0.000005208517450228101
] |
{
"id": 8,
"code_window": [
"\t\tconst wrapperBottom = scrollTop + this.view.renderHeight;\n",
"\t\tconst startLineNumber = range.startLineNumber;\n",
"\t\tconst lineOffset = element.getLineScrollTopOffset(startLineNumber);\n",
"\t\tconst elementTop = this.view.elementTop(index);\n",
"\t\tconst lineTop = elementTop + lineOffset + EDITOR_TOP_PADDING;\n",
"\n",
"\t\t// TODO@rebornix 30 ---> line height * 1.5\n",
"\t\tif (lineTop < scrollTop) {\n",
"\t\t\tthis.view.setScrollTop(lineTop - 30);\n",
"\t\t} else if (lineTop > wrapperBottom) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst lineTop = elementTop + lineOffset;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 147
} | /*---------------------------------------------------------------------------------------------
* 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 { IListRenderer, IListVirtualDelegate, ListError } from 'vs/base/browser/ui/list/list';
import { Event } from 'vs/base/common/event';
import { ScrollEvent } from 'vs/base/common/scrollable';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IListService, IWorkbenchListOptions, WorkbenchList } from 'vs/platform/list/browser/listService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { isMacintosh } from 'vs/base/common/platform';
import { NOTEBOOK_EDITOR_CURSOR_BOUNDARY } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { Range } from 'vs/editor/common/core/range';
import { CellRevealType, CellRevealPosition, CursorAtBoundary } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';
import { EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable {
get onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }
get rowsContainer(): HTMLElement {
return this.view.containerDomNode;
}
private _previousSelectedElements: CellViewModel[] = [];
private _localDisposableStore = new DisposableStore();
constructor(
private listUser: string,
container: HTMLElement,
delegate: IListVirtualDelegate<CellViewModel>,
renderers: IListRenderer<CellViewModel, any>[],
contextKeyService: IContextKeyService,
options: IWorkbenchListOptions<CellViewModel>,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService
) {
super(listUser, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService);
this._previousSelectedElements = this.getSelectedElements();
this._localDisposableStore.add(this.onDidChangeSelection((e) => {
this._previousSelectedElements.forEach(element => {
if (e.elements.indexOf(element) < 0) {
element.onDeselect();
}
});
this._previousSelectedElements = e.elements;
}));
const notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);
notebookEditorCursorAtBoundaryContext.set('none');
let cursorSelectionLisener: IDisposable | null = null;
const recomputeContext = (element: CellViewModel) => {
switch (element.cursorAtBoundary()) {
case CursorAtBoundary.Both:
notebookEditorCursorAtBoundaryContext.set('both');
break;
case CursorAtBoundary.Top:
notebookEditorCursorAtBoundaryContext.set('top');
break;
case CursorAtBoundary.Bottom:
notebookEditorCursorAtBoundaryContext.set('bottom');
break;
default:
notebookEditorCursorAtBoundaryContext.set('none');
break;
}
return;
};
// Cursor Boundary context
this._localDisposableStore.add(this.onDidChangeFocus((e) => {
cursorSelectionLisener?.dispose();
if (e.elements.length) {
// we only validate the first focused element
const focusedElement = e.elements[0];
cursorSelectionLisener = focusedElement.onDidChangeCursorSelection(() => {
recomputeContext(focusedElement);
});
recomputeContext(focusedElement);
return;
}
// reset context
notebookEditorCursorAtBoundaryContext.set('none');
}));
}
domElementAtIndex(index: number): HTMLElement | null {
return this.view.domElement(index);
}
focusView() {
this.view.domNode.focus();
}
getAbsoluteTop(index: number): number {
if (index < 0 || index >= this.length) {
throw new ListError(this.listUser, `Invalid index ${index}`);
}
return this.view.elementTop(index);
}
triggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {
this.view.triggerScrollFromMouseWheelEvent(browserEvent);
}
updateElementHeight(index: number, size: number): void {
const focused = this.getSelection();
this.view.updateElementHeight(index, size, focused.length ? focused[0] : null);
// this.view.updateElementHeight(index, size, null);
}
// override
domFocus() {
if (document.activeElement && this.view.domNode.contains(document.activeElement)) {
// for example, when focus goes into monaco editor, if we refocus the list view, the editor will lose focus.
return;
}
if (!isMacintosh && document.activeElement && isContextMenuFocused()) {
return;
}
super.domFocus();
}
private _revealRange(index: number, range: Range, revealType: CellRevealType, newlyCreated: boolean, alignToBottom: boolean) {
const element = this.view.element(index);
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const startLineNumber = range.startLineNumber;
const lineOffset = element.getLineScrollTopOffset(startLineNumber);
const elementTop = this.view.elementTop(index);
const lineTop = elementTop + lineOffset + EDITOR_TOP_PADDING;
// TODO@rebornix 30 ---> line height * 1.5
if (lineTop < scrollTop) {
this.view.setScrollTop(lineTop - 30);
} else if (lineTop > wrapperBottom) {
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else if (newlyCreated) {
// newly scrolled into view
if (alignToBottom) {
// align to the bottom
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else {
// align to to top
this.view.setScrollTop(lineTop - 30);
}
}
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
}
// TODO@rebornix TEST & Fix potential bugs
// List items have real dynamic heights, which means after we set `scrollTop` based on the `elementTop(index)`, the element at `index` might still be removed from the view once all relayouting tasks are done.
// For example, we scroll item 10 into the view upwards, in the first round, items 7, 8, 9, 10 are all in the viewport. Then item 7 and 8 resize themselves to be larger and finally item 10 is removed from the view.
// To ensure that item 10 is always there, we need to scroll item 10 to the top edge of the viewport.
private _revealRangeInternal(index: number, range: Range, revealType: CellRevealType) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const element = this.view.element(index);
if (element.editorAttached) {
this._revealRange(index, range, revealType, false, false);
} else {
const elementHeight = this.view.elementHeight(index);
let upwards = false;
if (elementTop + elementHeight < scrollTop) {
// scroll downwards
this.view.setScrollTop(elementTop);
upwards = false;
} else if (elementTop > wrapperBottom) {
// scroll upwards
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
upwards = true;
}
const editorAttachedPromise = new Promise((resolve, reject) => {
element.onDidChangeEditorAttachState(state => state ? resolve() : reject());
});
editorAttachedPromise.then(() => {
this._revealRange(index, range, revealType, true, upwards);
});
}
}
revealLineInView(index: number, line: number) {
this._revealRangeInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInView(index: number, range: Range): void {
this._revealRangeInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
};
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
const element = this.view.element(index);
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
reveal(index, range, revealType);
}
}
revealLineInCenter(index: number, line: number) {
this._revealRangeInCenterInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenter(index: number, range: Range): void {
this._revealRangeInCenterInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterIfOutsideViewportInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
setTimeout(() => {
element.revealRangeInCenter(range);
}, 240);
}
};
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
const element = this.view.element(index);
if (viewItemOffset < scrollTop || viewItemOffset > wrapperBottom) {
// let it render
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
// after rendering, it might be pushed down due to markdown cell dynamic height
const elementTop = this.view.elementTop(index);
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
// reveal editor
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
// for example markdown
}
} else {
if (element.editorAttached) {
element.revealRangeInCenter(range);
} else {
// for example, markdown cell in preview mode
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
}
}
}
revealLineInCenterIfOutsideViewport(index: number, line: number) {
this._revealRangeInCenterIfOutsideViewportInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenterIfOutsideViewport(index: number, range: Range): void {
this._revealRangeInCenterIfOutsideViewportInternal(index, range, CellRevealType.Range);
}
private _revealInternal(index: number, ignoreIfInsideViewport: boolean, revealPosition: CellRevealPosition) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
if (ignoreIfInsideViewport && elementTop >= scrollTop && elementTop < wrapperBottom) {
// inside the viewport
return;
}
// first render
const viewItemOffset = revealPosition === CellRevealPosition.Top ? elementTop : (elementTop - this.view.renderHeight / 2);
this.view.setScrollTop(viewItemOffset);
// second scroll as markdown cell is dynamic
const newElementTop = this.view.elementTop(index);
const newViewItemOffset = revealPosition === CellRevealPosition.Top ? newElementTop : (newElementTop - this.view.renderHeight / 2);
this.view.setScrollTop(newViewItemOffset);
}
revealInView(index: number) {
this._revealInternal(index, true, CellRevealPosition.Top);
}
revealInCenter(index: number) {
this._revealInternal(index, false, CellRevealPosition.Center);
}
revealInCenterIfOutsideViewport(index: number) {
this._revealInternal(index, true, CellRevealPosition.Center);
}
setCellSelection(index: number, range: Range) {
const element = this.view.element(index);
if (element.editorAttached) {
element.setSelection(range);
} else {
getEditorAttachedPromise(element).then(() => { element.setSelection(range); });
}
}
dispose() {
this._localDisposableStore.dispose();
super.dispose();
}
}
function getEditorAttachedPromise(element: CellViewModel) {
return new Promise((resolve, reject) => {
Event.once(element.onDidChangeEditorAttachState)(state => state ? resolve() : reject());
});
}
function isContextMenuFocused() {
return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
}
| src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.9985969662666321,
0.2331424355506897,
0.00016575719928368926,
0.00041241804137825966,
0.4065259099006653
] |
{
"id": 8,
"code_window": [
"\t\tconst wrapperBottom = scrollTop + this.view.renderHeight;\n",
"\t\tconst startLineNumber = range.startLineNumber;\n",
"\t\tconst lineOffset = element.getLineScrollTopOffset(startLineNumber);\n",
"\t\tconst elementTop = this.view.elementTop(index);\n",
"\t\tconst lineTop = elementTop + lineOffset + EDITOR_TOP_PADDING;\n",
"\n",
"\t\t// TODO@rebornix 30 ---> line height * 1.5\n",
"\t\tif (lineTop < scrollTop) {\n",
"\t\t\tthis.view.setScrollTop(lineTop - 30);\n",
"\t\t} else if (lineTop > wrapperBottom) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst lineTop = elementTop + lineOffset;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 147
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import * as glob from 'vs/base/common/glob';
import { IDisposable } from 'vs/base/common/lifecycle';
import { isWindows } from 'vs/base/common/platform';
import { ISplice } from 'vs/base/common/sequence';
import { URI } from 'vs/base/common/uri';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { PieceTreeTextBufferFactory } from 'vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
export enum CellKind {
Markdown = 1,
Code = 2
}
export enum CellOutputKind {
Text = 1,
Error = 2,
Rich = 3
}
export const NOTEBOOK_DISPLAY_ORDER = [
'application/json',
'application/javascript',
'text/html',
'image/svg+xml',
'text/markdown',
'image/png',
'image/jpeg',
'text/plain'
];
export interface INotebookDisplayOrder {
defaultOrder: string[];
userOrder?: string[];
}
export interface INotebookMimeTypeSelector {
type: string;
subTypes?: string[];
}
export interface INotebookRendererInfo {
id: ExtensionIdentifier;
extensionLocation: URI,
preloads: URI[]
}
export interface INotebookSelectors {
readonly filenamePattern?: string;
}
export interface IStreamOutput {
outputKind: CellOutputKind.Text;
text: string;
}
export interface IErrorOutput {
outputKind: CellOutputKind.Error;
/**
* Exception Name
*/
ename?: string;
/**
* Exception Value
*/
evalue?: string;
/**
* Exception call stacks
*/
traceback?: string[];
}
export interface IDisplayOutput {
outputKind: CellOutputKind.Rich;
/**
* { mime_type: value }
*/
data: { [key: string]: any; }
}
export enum MimeTypeRendererResolver {
Core,
Active,
Lazy
}
export interface IOrderedMimeType {
mimeType: string;
isResolved: boolean;
rendererId?: number;
output?: string;
}
export interface ITransformedDisplayOutputDto {
outputKind: CellOutputKind.Rich;
data: { [key: string]: any; }
orderedMimeTypes: IOrderedMimeType[];
pickedMimeTypeIndex: number;
}
export interface IGenericOutput {
outputKind: CellOutputKind;
pickedMimeType?: string;
pickedRenderer?: number;
transformedOutput?: { [key: string]: IDisplayOutput };
}
export type IOutput = ITransformedDisplayOutputDto | IStreamOutput | IErrorOutput;
export interface ICell {
readonly uri: URI;
handle: number;
source: string[];
language: string;
cellKind: CellKind;
outputs: IOutput[];
onDidChangeOutputs?: Event<NotebookCellOutputsSplice[]>;
resolveTextBufferFactory(): PieceTreeTextBufferFactory;
// TODO@rebornix it should be later on replaced by moving textmodel resolution into CellTextModel
contentChange(): void;
}
export interface LanguageInfo {
file_extension: string;
}
export interface IMetadata {
language_info: LanguageInfo;
}
export interface INotebookTextModel {
handle: number;
viewType: string;
// metadata: IMetadata;
readonly uri: URI;
languages: string[];
cells: ICell[];
renderers: Set<number>;
onDidChangeCells?: Event<NotebookCellsSplice[]>;
onDidChangeContent: Event<void>;
onWillDispose(listener: () => void): IDisposable;
}
export interface IRenderOutput {
shadowContent?: string;
hasDynamicHeight: boolean;
}
export type NotebookCellsSplice = [
number /* start */,
number /* delete count */,
ICell[]
];
export type NotebookCellOutputsSplice = [
number /* start */,
number /* delete count */,
IOutput[]
];
export namespace CellUri {
export const scheme = 'vscode-notebook';
export function generate(notebook: URI, handle: number): URI {
return notebook.with({
query: JSON.stringify({ cell: handle, notebook: notebook.toString() }),
scheme,
});
}
export function parse(cell: URI): { notebook: URI, handle: number } | undefined {
if (cell.scheme !== scheme) {
return undefined;
}
try {
const data = <{ cell: number, notebook: string }>JSON.parse(cell.query);
return {
handle: data.cell,
notebook: URI.parse(data.notebook)
};
} catch {
return undefined;
}
}
}
export function mimeTypeSupportedByCore(mimeType: string) {
if ([
'application/json',
'application/javascript',
'text/html',
'image/svg+xml',
'text/markdown',
'image/png',
'image/jpeg',
'text/plain',
'text/x-javascript'
].indexOf(mimeType) > -1) {
return true;
}
return false;
}
// if (isWindows) {
// value = value.replace(/\//g, '\\');
// }
function matchGlobUniversal(pattern: string, path: string) {
if (isWindows) {
pattern = pattern.replace(/\//g, '\\');
path = path.replace(/\//g, '\\');
}
return glob.match(pattern, path);
}
function getMimeTypeOrder(mimeType: string, userDisplayOrder: string[], documentDisplayOrder: string[], defaultOrder: string[]) {
let order = 0;
for (let i = 0; i < userDisplayOrder.length; i++) {
if (matchGlobUniversal(userDisplayOrder[i], mimeType)) {
return order;
}
order++;
}
for (let i = 0; i < documentDisplayOrder.length; i++) {
if (matchGlobUniversal(documentDisplayOrder[i], mimeType)) {
return order;
}
order++;
}
for (let i = 0; i < defaultOrder.length; i++) {
if (matchGlobUniversal(defaultOrder[i], mimeType)) {
return order;
}
order++;
}
return order;
}
export function sortMimeTypes(mimeTypes: string[], userDisplayOrder: string[], documentDisplayOrder: string[], defaultOrder: string[]) {
const sorted = mimeTypes.sort((a, b) => {
return getMimeTypeOrder(a, userDisplayOrder, documentDisplayOrder, defaultOrder) - getMimeTypeOrder(b, userDisplayOrder, documentDisplayOrder, defaultOrder);
});
return sorted;
}
interface IMutableSplice<T> extends ISplice<T> {
deleteCount: number;
}
export function diff<T>(before: T[], after: T[], contains: (a: T) => boolean): ISplice<T>[] {
const result: IMutableSplice<T>[] = [];
function pushSplice(start: number, deleteCount: number, toInsert: T[]): void {
if (deleteCount === 0 && toInsert.length === 0) {
return;
}
const latest = result[result.length - 1];
if (latest && latest.start + latest.deleteCount === start) {
latest.deleteCount += deleteCount;
latest.toInsert.push(...toInsert);
} else {
result.push({ start, deleteCount, toInsert });
}
}
let beforeIdx = 0;
let afterIdx = 0;
while (true) {
if (beforeIdx === before.length) {
pushSplice(beforeIdx, 0, after.slice(afterIdx));
break;
}
if (afterIdx === after.length) {
pushSplice(beforeIdx, before.length - beforeIdx, []);
break;
}
const beforeElement = before[beforeIdx];
const afterElement = after[afterIdx];
if (beforeElement === afterElement) {
// equal
beforeIdx += 1;
afterIdx += 1;
continue;
}
if (contains(afterElement)) {
// `afterElement` exists before, which means some elements before `afterElement` are deleted
pushSplice(beforeIdx, 1, []);
beforeIdx += 1;
} else {
// `afterElement` added
pushSplice(beforeIdx, 0, [afterElement]);
afterIdx += 1;
}
}
return result;
}
export interface ICellEditorViewState {
selections: editorCommon.ICursorState[];
}
export const NOTEBOOK_EDITOR_CURSOR_BOUNDARY = new RawContextKey<'none' | 'top' | 'bottom' | 'both'>('notebookEditorCursorAtBoundary', 'none');
| src/vs/workbench/contrib/notebook/common/notebookCommon.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00018637462926562876,
0.000172082131030038,
0.00016645615687593818,
0.00017175158427562565,
0.000003182980208293884
] |
{
"id": 8,
"code_window": [
"\t\tconst wrapperBottom = scrollTop + this.view.renderHeight;\n",
"\t\tconst startLineNumber = range.startLineNumber;\n",
"\t\tconst lineOffset = element.getLineScrollTopOffset(startLineNumber);\n",
"\t\tconst elementTop = this.view.elementTop(index);\n",
"\t\tconst lineTop = elementTop + lineOffset + EDITOR_TOP_PADDING;\n",
"\n",
"\t\t// TODO@rebornix 30 ---> line height * 1.5\n",
"\t\tif (lineTop < scrollTop) {\n",
"\t\t\tthis.view.setScrollTop(lineTop - 30);\n",
"\t\t} else if (lineTop > wrapperBottom) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst lineTop = elementTop + lineOffset;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 147
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*eslint-env mocha*/
/*global define,run*/
const assert = require('assert');
const path = require('path');
const glob = require('glob');
const jsdom = require('jsdom-no-contextify');
const TEST_GLOB = '**/test/**/*.test.js';
const coverage = require('../coverage');
const optimist = require('optimist')
.usage('Run the Code tests. All mocha options apply.')
.describe('build', 'Run from out-build').boolean('build')
.describe('run', 'Run a single file').string('run')
.describe('coverage', 'Generate a coverage report').boolean('coverage')
.describe('browser', 'Run tests in a browser').boolean('browser')
.alias('h', 'help').boolean('h')
.describe('h', 'Show help');
const argv = optimist.argv;
if (argv.help) {
optimist.showHelp();
process.exit(1);
}
const REPO_ROOT = path.join(__dirname, '../../../');
const out = argv.build ? 'out-build' : 'out';
const loader = require(`../../../${out}/vs/loader`);
const src = path.join(REPO_ROOT, out);
function main() {
process.on('uncaughtException', function (e) {
console.error(e.stack || e);
});
const loaderConfig = {
nodeRequire: require,
nodeMain: __filename,
baseUrl: path.join(REPO_ROOT, 'src'),
paths: {
'vs/css': '../test/unit/node/css.mock',
'vs': `../${out}/vs`,
'lib': `../${out}/lib`,
'bootstrap-fork': `../${out}/bootstrap-fork`
},
catchError: true
};
if (argv.coverage) {
coverage.initialize(loaderConfig);
process.on('exit', function (code) {
if (code !== 0) {
return;
}
coverage.createReport(argv.run || argv.runGlob);
});
}
loader.config(loaderConfig);
global.define = loader;
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.self = global.window = global.document.parentWindow;
global.Element = global.window.Element;
global.HTMLElement = global.window.HTMLElement;
global.Node = global.window.Node;
global.navigator = global.window.navigator;
global.XMLHttpRequest = global.window.XMLHttpRequest;
let didErr = false;
const write = process.stderr.write;
process.stderr.write = function (data) {
didErr = didErr || !!data;
write.apply(process.stderr, arguments);
};
let loadFunc = null;
if (argv.runGlob) {
loadFunc = (cb) => {
const doRun = tests => {
const modulesToLoad = tests.map(test => {
if (path.isAbsolute(test)) {
test = path.relative(src, path.resolve(test));
}
return test.replace(/(\.js)|(\.d\.ts)|(\.js\.map)$/, '');
});
define(modulesToLoad, () => cb(null), cb);
};
glob(argv.runGlob, { cwd: src }, function (err, files) { doRun(files); });
};
} else if (argv.run) {
const tests = (typeof argv.run === 'string') ? [argv.run] : argv.run;
const modulesToLoad = tests.map(function (test) {
test = test.replace(/^src/, 'out');
test = test.replace(/\.ts$/, '.js');
return path.relative(src, path.resolve(test)).replace(/(\.js)|(\.js\.map)$/, '').replace(/\\/g, '/');
});
loadFunc = (cb) => {
define(modulesToLoad, () => cb(null), cb);
};
} else {
loadFunc = (cb) => {
glob(TEST_GLOB, { cwd: src }, function (err, files) {
const modulesToLoad = files.map(function (file) {
return file.replace(/\.js$/, '');
});
define(modulesToLoad, function () { cb(null); }, cb);
});
};
}
loadFunc(function (err) {
if (err) {
console.error(err);
return process.exit(1);
}
process.stderr.write = write;
if (!argv.run && !argv.runGlob) {
// set up last test
suite('Loader', function () {
test('should not explode while loading', function () {
assert.ok(!didErr, 'should not explode while loading');
});
});
}
// report failing test for every unexpected error during any of the tests
let unexpectedErrors = [];
suite('Errors', function () {
test('should not have unexpected errors in tests', function () {
if (unexpectedErrors.length) {
unexpectedErrors.forEach(function (stack) {
console.error('');
console.error(stack);
});
assert.ok(false);
}
});
});
// replace the default unexpected error handler to be useful during tests
loader(['vs/base/common/errors'], function (errors) {
errors.setUnexpectedErrorHandler(function (err) {
const stack = (err && err.stack) || (new Error().stack);
unexpectedErrors.push((err && err.message ? err.message : err) + '\n' + stack);
});
// fire up mocha
run();
});
});
}
if (process.argv.some(function (a) { return /^--browser/.test(a); })) {
require('./browser');
} else {
main();
}
| test/unit/node/all.js | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017549104813952,
0.00017192964151035994,
0.00016932355356402695,
0.00017212642705999315,
0.0000016896664192245225
] |
{
"id": 8,
"code_window": [
"\t\tconst wrapperBottom = scrollTop + this.view.renderHeight;\n",
"\t\tconst startLineNumber = range.startLineNumber;\n",
"\t\tconst lineOffset = element.getLineScrollTopOffset(startLineNumber);\n",
"\t\tconst elementTop = this.view.elementTop(index);\n",
"\t\tconst lineTop = elementTop + lineOffset + EDITOR_TOP_PADDING;\n",
"\n",
"\t\t// TODO@rebornix 30 ---> line height * 1.5\n",
"\t\tif (lineTop < scrollTop) {\n",
"\t\t\tthis.view.setScrollTop(lineTop - 30);\n",
"\t\t} else if (lineTop > wrapperBottom) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst lineTop = elementTop + lineOffset;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 147
} | /*---------------------------------------------------------------------------------------------
* 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 { getDeepestNode, findNextWord, findPrevWord, getHtmlNode } from './util';
import { HtmlNode } from 'EmmetNode';
import { isNumber } from 'util';
export function nextItemHTML(selectionStart: vscode.Position, selectionEnd: vscode.Position, editor: vscode.TextEditor, rootNode: HtmlNode): vscode.Selection | undefined {
let currentNode = getHtmlNode(editor.document, rootNode, selectionEnd, false);
let nextNode: HtmlNode | undefined = undefined;
if (!currentNode) {
return;
}
if (currentNode.type !== 'comment') {
// If cursor is in the tag name, select tag
if (selectionEnd.isBefore(currentNode.open.start.translate(0, currentNode.name.length))) {
return getSelectionFromNode(currentNode);
}
// If cursor is in the open tag, look for attributes
if (selectionEnd.isBefore(currentNode.open.end)) {
let attrSelection = getNextAttribute(selectionStart, selectionEnd, currentNode);
if (attrSelection) {
return attrSelection;
}
}
// Get the first child of current node which is right after the cursor and is not a comment
nextNode = currentNode.firstChild;
while (nextNode && (selectionEnd.isAfterOrEqual(nextNode.end) || nextNode.type === 'comment')) {
nextNode = nextNode.nextSibling;
}
}
// Get next sibling of current node which is not a comment. If none is found try the same on the parent
while (!nextNode && currentNode) {
if (currentNode.nextSibling) {
if (currentNode.nextSibling.type !== 'comment') {
nextNode = currentNode.nextSibling;
} else {
currentNode = currentNode.nextSibling;
}
} else {
currentNode = currentNode.parent;
}
}
return nextNode && getSelectionFromNode(nextNode);
}
export function prevItemHTML(selectionStart: vscode.Position, selectionEnd: vscode.Position, editor: vscode.TextEditor, rootNode: HtmlNode): vscode.Selection | undefined {
let currentNode = getHtmlNode(editor.document, rootNode, selectionStart, false);
let prevNode: HtmlNode | undefined = undefined;
if (!currentNode) {
return;
}
if (currentNode.type !== 'comment' && selectionStart.translate(0, -1).isAfter(currentNode.open.start)) {
if (selectionStart.isBefore(currentNode.open.end) || !currentNode.firstChild || selectionEnd.isBeforeOrEqual(currentNode.firstChild.start)) {
prevNode = currentNode;
} else {
// Select the child that appears just before the cursor and is not a comment
prevNode = currentNode.firstChild;
let oldOption: HtmlNode | undefined = undefined;
while (prevNode.nextSibling && selectionStart.isAfterOrEqual(prevNode.nextSibling.end)) {
if (prevNode && prevNode.type !== 'comment') {
oldOption = prevNode;
}
prevNode = prevNode.nextSibling;
}
prevNode = <HtmlNode>getDeepestNode((prevNode && prevNode.type !== 'comment') ? prevNode : oldOption);
}
}
// Select previous sibling which is not a comment. If none found, then select parent
while (!prevNode && currentNode) {
if (currentNode.previousSibling) {
if (currentNode.previousSibling.type !== 'comment') {
prevNode = <HtmlNode>getDeepestNode(currentNode.previousSibling);
} else {
currentNode = currentNode.previousSibling;
}
} else {
prevNode = currentNode.parent;
}
}
if (!prevNode) {
return undefined;
}
let attrSelection = getPrevAttribute(selectionStart, selectionEnd, prevNode);
return attrSelection ? attrSelection : getSelectionFromNode(prevNode);
}
function getSelectionFromNode(node: HtmlNode): vscode.Selection | undefined {
if (node && node.open) {
let selectionStart = (<vscode.Position>node.open.start).translate(0, 1);
let selectionEnd = selectionStart.translate(0, node.name.length);
return new vscode.Selection(selectionStart, selectionEnd);
}
return undefined;
}
function getNextAttribute(selectionStart: vscode.Position, selectionEnd: vscode.Position, node: HtmlNode): vscode.Selection | undefined {
if (!node.attributes || node.attributes.length === 0 || node.type === 'comment') {
return;
}
for (const attr of node.attributes) {
if (selectionEnd.isBefore(attr.start)) {
// select full attr
return new vscode.Selection(attr.start, attr.end);
}
if (!attr.value || (<vscode.Position>attr.value.start).isEqual(attr.value.end)) {
// No attr value to select
continue;
}
if ((selectionStart.isEqual(attr.start) && selectionEnd.isEqual(attr.end)) || selectionEnd.isBefore(attr.value.start)) {
// cursor is in attr name, so select full attr value
return new vscode.Selection(attr.value.start, attr.value.end);
}
// Fetch the next word in the attr value
if (attr.value.toString().indexOf(' ') === -1) {
// attr value does not have space, so no next word to find
continue;
}
let pos: number | undefined = undefined;
if (selectionStart.isEqual(attr.value.start) && selectionEnd.isEqual(attr.value.end)) {
pos = -1;
}
if (pos === undefined && selectionEnd.isBefore(attr.end)) {
pos = selectionEnd.character - attr.value.start.character - 1;
}
if (pos !== undefined) {
let [newSelectionStartOffset, newSelectionEndOffset] = findNextWord(attr.value.toString(), pos);
if (!isNumber(newSelectionStartOffset) || !isNumber(newSelectionEndOffset)) {
return;
}
if (newSelectionStartOffset >= 0 && newSelectionEndOffset >= 0) {
const newSelectionStart = (<vscode.Position>attr.value.start).translate(0, newSelectionStartOffset);
const newSelectionEnd = (<vscode.Position>attr.value.start).translate(0, newSelectionEndOffset);
return new vscode.Selection(newSelectionStart, newSelectionEnd);
}
}
}
return;
}
function getPrevAttribute(selectionStart: vscode.Position, selectionEnd: vscode.Position, node: HtmlNode): vscode.Selection | undefined {
if (!node.attributes || node.attributes.length === 0 || node.type === 'comment') {
return;
}
for (let i = node.attributes.length - 1; i >= 0; i--) {
let attr = node.attributes[i];
if (selectionStart.isBeforeOrEqual(attr.start)) {
continue;
}
if (!attr.value || (<vscode.Position>attr.value.start).isEqual(attr.value.end) || selectionStart.isBefore(attr.value.start)) {
// select full attr
return new vscode.Selection(attr.start, attr.end);
}
if (selectionStart.isEqual(attr.value.start)) {
if (selectionEnd.isAfterOrEqual(attr.value.end)) {
// select full attr
return new vscode.Selection(attr.start, attr.end);
}
// select attr value
return new vscode.Selection(attr.value.start, attr.value.end);
}
// Fetch the prev word in the attr value
let pos = selectionStart.isAfter(attr.value.end) ? attr.value.toString().length : selectionStart.character - attr.value.start.character;
let [newSelectionStartOffset, newSelectionEndOffset] = findPrevWord(attr.value.toString(), pos);
if (!isNumber(newSelectionStartOffset) || !isNumber(newSelectionEndOffset)) {
return;
}
if (newSelectionStartOffset >= 0 && newSelectionEndOffset >= 0) {
const newSelectionStart = (<vscode.Position>attr.value.start).translate(0, newSelectionStartOffset);
const newSelectionEnd = (<vscode.Position>attr.value.start).translate(0, newSelectionEndOffset);
return new vscode.Selection(newSelectionStart, newSelectionEnd);
}
}
return;
} | extensions/emmet/src/selectItemHTML.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017356069292873144,
0.00017119408585131168,
0.00016907250392250717,
0.0001710262440610677,
0.000001150952357420465
] |
{
"id": 9,
"code_window": [
"\t\traceCancellation(viewCell.resolveTextModel(), cts.token).then(model => {\n",
"\t\t\tif (model && templateData.editor) {\n",
"\t\t\t\ttemplateData.editor.setModel(model);\n",
"\t\t\t\tviewCell.attachTextEditor(templateData.editor);\n",
"\t\t\t\tif (notebookEditor.getActiveCell() === viewCell) {\n",
"\t\t\t\t\ttemplateData.editor?.focus();\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (notebookEditor.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts",
"type": "replace",
"edit_start_line_idx": 59
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { getZoomLevel } from 'vs/base/browser/browser';
import * as DOM from 'vs/base/browser/dom';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { CancellationToken } from 'vs/base/common/cancellation';
import { DisposableStore, MutableDisposable } from 'vs/base/common/lifecycle';
import 'vs/css!./notebook';
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { contrastBorder, editorBackground, focusBorder, foreground, textBlockQuoteBackground, textBlockQuoteBorder, textLinkActiveForeground, textLinkForeground, textPreformatForeground } from 'vs/platform/theme/common/colorRegistry';
import { IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
import { EditorOptions, IEditorMemento, IEditorCloseEvent } from 'vs/workbench/common/editor';
import { INotebookEditor, NotebookLayoutInfo, CellState, NOTEBOOK_EDITOR_FOCUSED, CellFocusMode, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { NotebookEditorInput, NotebookEditorModel } from 'vs/workbench/contrib/notebook/browser/notebookEditorInput';
import { INotebookService } from 'vs/workbench/contrib/notebook/browser/notebookService';
import { OutputRenderer } from 'vs/workbench/contrib/notebook/browser/view/output/outputRenderer';
import { BackLayerWebView } from 'vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView';
import { CodeCellRenderer, MarkdownCellRenderer, NotebookCellListDelegate } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer';
import { IOutput, CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { IWebviewService } from 'vs/workbench/contrib/webview/browser/webview';
import { getExtraColor } from 'vs/workbench/contrib/welcome/walkThrough/common/walkThroughUtils';
import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { IEditor, ICompositeCodeEditor } from 'vs/editor/common/editorCommon';
import { IResourceEditorInput } from 'vs/platform/editor/common/editor';
import { Emitter, Event } from 'vs/base/common/event';
import { NotebookCellList } from 'vs/workbench/contrib/notebook/browser/view/notebookCellList';
import { NotebookFindWidget } from 'vs/workbench/contrib/notebook/browser/contrib/notebookFindWidget';
import { NotebookViewModel, INotebookEditorViewState, IModelDecorationsChangeAccessor } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel';
import { IEditorGroupView } from 'vs/workbench/browser/parts/editor/editor';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';
import { Range } from 'vs/editor/common/core/range';
import { CELL_MARGIN } from 'vs/workbench/contrib/notebook/browser/constants';
const $ = DOM.$;
const NOTEBOOK_EDITOR_VIEW_STATE_PREFERENCE_KEY = 'NotebookEditorViewState';
export class NotebookEditorOptions extends EditorOptions {
readonly cellOptions?: IResourceEditorInput;
constructor(options: Partial<NotebookEditorOptions>) {
super();
this.overwrite(options);
this.cellOptions = options.cellOptions;
}
with(options: Partial<NotebookEditorOptions>): NotebookEditorOptions {
return new NotebookEditorOptions({ ...this, ...options });
}
}
export class NotebookCodeEditors implements ICompositeCodeEditor {
private readonly _disposables = new DisposableStore();
private readonly _onDidChangeActiveEditor = new Emitter<this>();
readonly onDidChangeActiveEditor: Event<this> = this._onDidChangeActiveEditor.event;
constructor(
private _list: NotebookCellList,
private _renderedEditors: Map<ICellViewModel, ICodeEditor | undefined>
) {
_list.onDidChangeFocus(_e => this._onDidChangeActiveEditor.fire(this), undefined, this._disposables);
}
dispose(): void {
this._onDidChangeActiveEditor.dispose();
this._disposables.dispose();
}
get activeCodeEditor(): IEditor | undefined {
const [focused] = this._list.getFocusedElements();
return focused instanceof CellViewModel
? this._renderedEditors.get(focused)
: undefined;
}
}
export class NotebookEditor extends BaseEditor implements INotebookEditor {
static readonly ID: string = 'workbench.editor.notebook';
private rootElement!: HTMLElement;
private body!: HTMLElement;
private webview: BackLayerWebView | null = null;
private list: NotebookCellList | undefined;
private control: ICompositeCodeEditor | undefined;
private renderedEditors: Map<ICellViewModel, ICodeEditor | undefined> = new Map();
private notebookViewModel: NotebookViewModel | undefined;
private localStore: DisposableStore = this._register(new DisposableStore());
private editorMemento: IEditorMemento<INotebookEditorViewState>;
private readonly groupListener = this._register(new MutableDisposable());
private fontInfo: BareFontInfo | undefined;
private dimension: DOM.Dimension | null = null;
private editorFocus: IContextKey<boolean> | null = null;
private outputRenderer: OutputRenderer;
private findWidget: NotebookFindWidget;
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IThemeService themeService: IThemeService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IStorageService storageService: IStorageService,
@IWebviewService private webviewService: IWebviewService,
@INotebookService private notebookService: INotebookService,
@IEditorGroupsService editorGroupService: IEditorGroupsService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IEnvironmentService private readonly environmentSerice: IEnvironmentService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
) {
super(NotebookEditor.ID, telemetryService, themeService, storageService);
this.editorMemento = this.getEditorMemento<INotebookEditorViewState>(editorGroupService, NOTEBOOK_EDITOR_VIEW_STATE_PREFERENCE_KEY);
this.outputRenderer = new OutputRenderer(this, this.instantiationService);
this.findWidget = this.instantiationService.createInstance(NotebookFindWidget, this);
this.findWidget.updateTheme(this.themeService.getColorTheme());
}
get viewModel() {
return this.notebookViewModel;
}
get minimumWidth(): number { return 375; }
get maximumWidth(): number { return Number.POSITIVE_INFINITY; }
// these setters need to exist because this extends from BaseEditor
set minimumWidth(value: number) { /*noop*/ }
set maximumWidth(value: number) { /*noop*/ }
//#region Editor Core
public get isNotebookEditor() {
return true;
}
protected createEditor(parent: HTMLElement): void {
this.rootElement = DOM.append(parent, $('.notebook-editor'));
this.createBody(this.rootElement);
this.generateFontInfo();
this.editorFocus = NOTEBOOK_EDITOR_FOCUSED.bindTo(this.contextKeyService);
this._register(this.onDidFocus(() => {
this.editorFocus?.set(true);
}));
this._register(this.onDidBlur(() => {
this.editorFocus?.set(false);
}));
}
private generateFontInfo(): void {
const editorOptions = this.configurationService.getValue<IEditorOptions>('editor');
this.fontInfo = BareFontInfo.createFromRawSettings(editorOptions, getZoomLevel());
}
private createBody(parent: HTMLElement): void {
this.body = document.createElement('div');
DOM.addClass(this.body, 'cell-list-container');
this.createCellList();
DOM.append(parent, this.body);
DOM.append(parent, this.findWidget.getDomNode());
}
private createCellList(): void {
DOM.addClass(this.body, 'cell-list-container');
const renders = [
this.instantiationService.createInstance(CodeCellRenderer, this, this.renderedEditors),
this.instantiationService.createInstance(MarkdownCellRenderer, this),
];
this.list = <NotebookCellList>this.instantiationService.createInstance(
NotebookCellList,
'NotebookCellList',
this.body,
this.instantiationService.createInstance(NotebookCellListDelegate),
renders,
this.contextKeyService,
{
setRowLineHeight: false,
setRowHeight: false,
supportDynamicHeights: true,
horizontalScrolling: false,
keyboardSupport: false,
mouseSupport: true,
multipleSelectionSupport: false,
enableKeyboardNavigation: true,
overrideStyles: {
listBackground: editorBackground,
listActiveSelectionBackground: editorBackground,
listActiveSelectionForeground: foreground,
listFocusAndSelectionBackground: editorBackground,
listFocusAndSelectionForeground: foreground,
listFocusBackground: editorBackground,
listFocusForeground: foreground,
listHoverForeground: foreground,
listHoverBackground: editorBackground,
listHoverOutline: focusBorder,
listFocusOutline: focusBorder,
listInactiveSelectionBackground: editorBackground,
listInactiveSelectionForeground: foreground,
listInactiveFocusBackground: editorBackground,
listInactiveFocusOutline: editorBackground,
}
},
);
this.control = new NotebookCodeEditors(this.list, this.renderedEditors);
this.webview = new BackLayerWebView(this.webviewService, this.notebookService, this, this.environmentSerice);
this.list.rowsContainer.appendChild(this.webview.element);
this._register(this.list);
}
getControl() {
return this.control;
}
onHide() {
this.editorFocus?.set(false);
if (this.webview) {
this.localStore.clear();
this.list?.rowsContainer.removeChild(this.webview?.element);
this.webview?.dispose();
this.webview = null;
}
this.list?.splice(0, this.list?.length);
if (this.notebookViewModel && !this.notebookViewModel.isDirty()) {
this.notebookService.destoryNotebookDocument(this.notebookViewModel.viewType!, this.notebookViewModel!.notebookDocument);
this.notebookViewModel.dispose();
this.notebookViewModel = undefined;
}
super.onHide();
}
setEditorVisible(visible: boolean, group: IEditorGroup | undefined): void {
super.setEditorVisible(visible, group);
this.groupListener.value = ((group as IEditorGroupView).onWillCloseEditor(e => this.onWillCloseEditorInGroup(e)));
}
private onWillCloseEditorInGroup(e: IEditorCloseEvent): void {
const editor = e.editor;
if (!(editor instanceof NotebookEditorInput)) {
return; // only handle files
}
if (editor === this.input) {
this.saveTextEditorViewState(editor);
}
}
focus() {
super.focus();
this.editorFocus?.set(true);
}
async setInput(input: NotebookEditorInput, options: EditorOptions | undefined, token: CancellationToken): Promise<void> {
if (this.input instanceof NotebookEditorInput) {
this.saveTextEditorViewState(this.input);
}
await super.setInput(input, options, token);
const model = await input.resolve();
if (this.notebookViewModel === undefined || !this.notebookViewModel.equal(model) || this.webview === null) {
this.detachModel();
await this.attachModel(input, model);
}
// reveal cell if editor options tell to do so
if (options instanceof NotebookEditorOptions && options.cellOptions) {
const cellOptions = options.cellOptions;
const cell = this.notebookViewModel!.viewCells.find(cell => cell.uri.toString() === cellOptions.resource.toString());
if (cell) {
this.revealInCenterIfOutsideViewport(cell);
const editor = this.renderedEditors.get(cell)!;
if (editor) {
if (cellOptions.options?.selection) {
const { selection } = cellOptions.options;
editor.setSelection({
...selection,
endLineNumber: selection.endLineNumber || selection.startLineNumber,
endColumn: selection.endColumn || selection.startColumn
});
}
if (!cellOptions.options?.preserveFocus) {
editor.focus();
}
}
}
}
}
clearInput(): void {
if (this.input && this.input instanceof NotebookEditorInput && !this.input.isDisposed()) {
this.saveTextEditorViewState(this.input);
}
super.clearInput();
}
private detachModel() {
this.localStore.clear();
this.notebookViewModel?.dispose();
this.notebookViewModel = undefined;
this.webview?.clearInsets();
this.webview?.clearPreloadsCache();
this.findWidget.clear();
}
private async attachModel(input: NotebookEditorInput, model: NotebookEditorModel) {
if (!this.webview) {
this.webview = new BackLayerWebView(this.webviewService, this.notebookService, this, this.environmentSerice);
this.list?.rowsContainer.insertAdjacentElement('afterbegin', this.webview!.element);
}
this.notebookViewModel = this.instantiationService.createInstance(NotebookViewModel, input.viewType!, model);
const viewState = this.loadTextEditorViewState(input);
this.notebookViewModel.restoreEditorViewState(viewState);
this.localStore.add(this.notebookViewModel.onDidChangeViewCells((e) => {
if (e.synchronous) {
e.splices.reverse().forEach((diff) => {
this.list?.splice(diff[0], diff[1], diff[2]);
});
} else {
DOM.scheduleAtNextAnimationFrame(() => {
e.splices.reverse().forEach((diff) => {
this.list?.splice(diff[0], diff[1], diff[2]);
});
});
}
}));
this.webview?.updateRendererPreloads(this.notebookViewModel.renderers);
this.localStore.add(this.list!.onWillScroll(e => {
this.webview!.updateViewScrollTop(-e.scrollTop, []);
}));
this.localStore.add(this.list!.onDidChangeContentHeight(() => {
const scrollTop = this.list?.scrollTop || 0;
const scrollHeight = this.list?.scrollHeight || 0;
this.webview!.element.style.height = `${scrollHeight}px`;
let updateItems: { cell: CellViewModel, output: IOutput, cellTop: number }[] = [];
if (this.webview?.insetMapping) {
this.webview?.insetMapping.forEach((value, key) => {
let cell = value.cell;
let index = this.notebookViewModel!.getViewCellIndex(cell);
let cellTop = this.list?.getAbsoluteTop(index) || 0;
if (this.webview!.shouldUpdateInset(cell, key, cellTop)) {
updateItems.push({
cell: cell,
output: key,
cellTop: cellTop
});
}
});
if (updateItems.length) {
this.webview?.updateViewScrollTop(-scrollTop, updateItems);
}
}
}));
this.localStore.add(this.list!.onDidChangeFocus((e) => {
if (e.elements.length > 0) {
this.notebookService.updateNotebookActiveCell(input.viewType!, input.resource!, e.elements[0].handle);
}
}));
this.list?.splice(0, this.list?.length || 0);
this.list?.splice(0, 0, this.notebookViewModel!.viewCells as CellViewModel[]);
this.list?.layout();
}
private saveTextEditorViewState(input: NotebookEditorInput): void {
if (this.group && this.notebookViewModel) {
const state = this.notebookViewModel.saveEditorViewState();
this.editorMemento.saveEditorState(this.group, input.resource, state);
}
}
private loadTextEditorViewState(input: NotebookEditorInput): INotebookEditorViewState | undefined {
if (this.group) {
return this.editorMemento.loadEditorState(this.group, input.resource);
}
return;
}
layout(dimension: DOM.Dimension): void {
this.dimension = new DOM.Dimension(dimension.width, dimension.height);
DOM.toggleClass(this.rootElement, 'mid-width', dimension.width < 1000 && dimension.width >= 600);
DOM.toggleClass(this.rootElement, 'narrow-width', dimension.width < 600);
DOM.size(this.body, dimension.width, dimension.height);
this.list?.layout(dimension.height, dimension.width);
}
protected saveState(): void {
if (this.input instanceof NotebookEditorInput) {
this.saveTextEditorViewState(this.input);
}
super.saveState();
}
//#endregion
//#region Editor Features
selectElement(cell: ICellViewModel) {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.setSelection([index]);
this.list?.setFocus([index]);
}
}
revealInView(cell: ICellViewModel) {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealInView(index);
}
}
revealInCenterIfOutsideViewport(cell: ICellViewModel) {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealInCenterIfOutsideViewport(index);
}
}
revealInCenter(cell: ICellViewModel) {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealInCenter(index);
}
}
revealLineInView(cell: ICellViewModel, line: number): void {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealLineInView(index, line);
}
}
revealLineInCenter(cell: ICellViewModel, line: number) {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealLineInCenter(index, line);
}
}
revealLineInCenterIfOutsideViewport(cell: ICellViewModel, line: number) {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealLineInCenterIfOutsideViewport(index, line);
}
}
revealRangeInView(cell: ICellViewModel, range: Range): void {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealRangeInView(index, range);
}
}
revealRangeInCenter(cell: ICellViewModel, range: Range): void {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealRangeInCenter(index, range);
}
}
revealRangeInCenterIfOutsideViewport(cell: ICellViewModel, range: Range): void {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealRangeInCenterIfOutsideViewport(index, range);
}
}
setCellSelection(cell: ICellViewModel, range: Range): void {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.setCellSelection(index, range);
}
}
changeDecorations(callback: (changeAccessor: IModelDecorationsChangeAccessor) => any): any {
return this.notebookViewModel?.changeDecorations(callback);
}
//#endregion
//#region Find Delegate
public showFind() {
this.findWidget.reveal();
}
public hideFind() {
this.findWidget.hide();
this.focus();
}
//#endregion
//#region Cell operations
layoutNotebookCell(cell: ICellViewModel, height: number) {
let relayout = (cell: ICellViewModel, height: number) => {
let index = this.notebookViewModel!.getViewCellIndex(cell);
if (index >= 0) {
this.list?.updateElementHeight(index, height);
}
};
DOM.scheduleAtNextAnimationFrame(() => {
relayout(cell, height);
});
}
async insertNotebookCell(cell: ICellViewModel, type: CellKind, direction: 'above' | 'below', initialText: string = ''): Promise<void> {
const newLanguages = this.notebookViewModel!.languages;
const language = newLanguages && newLanguages.length ? newLanguages[0] : 'markdown';
const index = this.notebookViewModel!.getViewCellIndex(cell);
const insertIndex = direction === 'above' ? index : index + 1;
const newModeCell = await this.notebookService.createNotebookCell(this.notebookViewModel!.viewType, this.notebookViewModel!.uri, insertIndex, language, type);
newModeCell!.source = initialText.split(/\r?\n/g);
const newCell = this.notebookViewModel!.insertCell(insertIndex, newModeCell!, true);
this.list?.setFocus([insertIndex]);
if (type === CellKind.Markdown) {
newCell.state = CellState.Editing;
}
DOM.scheduleAtNextAnimationFrame(() => {
this.list?.revealInCenterIfOutsideViewport(insertIndex);
});
}
async deleteNotebookCell(cell: ICellViewModel): Promise<void> {
(cell as CellViewModel).save();
const index = this.notebookViewModel!.getViewCellIndex(cell);
await this.notebookService.deleteNotebookCell(this.notebookViewModel!.viewType, this.notebookViewModel!.uri, index);
this.notebookViewModel!.deleteCell(index, true);
}
moveCellDown(cell: ICellViewModel): void {
const index = this.notebookViewModel!.getViewCellIndex(cell);
const newIdx = index + 1;
this.moveCellToIndex(cell, index, newIdx);
}
moveCellUp(cell: ICellViewModel): void {
const index = this.notebookViewModel!.getViewCellIndex(cell);
const newIdx = index - 1;
this.moveCellToIndex(cell, index, newIdx);
}
private moveCellToIndex(cell: ICellViewModel, index: number, newIdx: number): void {
if (!this.notebookViewModel!.moveCellToIdx(index, newIdx, true)) {
return;
}
DOM.scheduleAtNextAnimationFrame(() => {
this.list?.revealInCenterIfOutsideViewport(index + 1);
});
}
editNotebookCell(cell: CellViewModel): void {
cell.state = CellState.Editing;
this.renderedEditors.get(cell)?.focus();
}
saveNotebookCell(cell: ICellViewModel): void {
cell.state = CellState.Preview;
}
getActiveCell() {
let elements = this.list?.getFocusedElements();
if (elements && elements.length) {
return elements[0];
}
return undefined;
}
focusNotebookCell(cell: ICellViewModel, focusEditor: boolean) {
const index = this.notebookViewModel!.getViewCellIndex(cell);
if (focusEditor) {
this.list?.setFocus([index]);
this.list?.setSelection([index]);
this.list?.focusView();
cell.state = CellState.Editing;
cell.focusMode = CellFocusMode.Editor;
} else {
let itemDOM = this.list?.domElementAtIndex(index);
if (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) {
(document.activeElement as HTMLElement).blur();
}
cell.state = CellState.Preview;
cell.focusMode = CellFocusMode.Editor;
this.list?.setFocus([index]);
this.list?.setSelection([index]);
this.list?.focusView();
}
}
//#endregion
//#region MISC
getLayoutInfo(): NotebookLayoutInfo {
if (!this.list) {
throw new Error('Editor is not initalized successfully');
}
return {
width: this.dimension!.width,
height: this.dimension!.height,
fontInfo: this.fontInfo!
};
}
getFontInfo(): BareFontInfo | undefined {
return this.fontInfo;
}
triggerScroll(event: IMouseWheelEvent) {
this.list?.triggerScrollFromMouseWheelEvent(event);
}
createInset(cell: CellViewModel, output: IOutput, shadowContent: string, offset: number) {
if (!this.webview) {
return;
}
let preloads = this.notebookViewModel!.renderers;
if (!this.webview!.insetMapping.has(output)) {
let index = this.notebookViewModel!.getViewCellIndex(cell);
let cellTop = this.list?.getAbsoluteTop(index) || 0;
this.webview!.createInset(cell, output, cellTop, offset, shadowContent, preloads);
} else {
let index = this.notebookViewModel!.getViewCellIndex(cell);
let cellTop = this.list?.getAbsoluteTop(index) || 0;
let scrollTop = this.list?.scrollTop || 0;
this.webview!.updateViewScrollTop(-scrollTop, [{ cell: cell, output: output, cellTop: cellTop }]);
}
}
removeInset(output: IOutput) {
if (!this.webview) {
return;
}
this.webview!.removeInset(output);
}
getOutputRenderer(): OutputRenderer {
return this.outputRenderer;
}
//#endregion
}
const embeddedEditorBackground = 'walkThrough.embeddedEditorBackground';
registerThemingParticipant((theme, collector) => {
const color = getExtraColor(theme, embeddedEditorBackground, { dark: 'rgba(0, 0, 0, .4)', extra_dark: 'rgba(200, 235, 255, .064)', light: '#f4f4f4', hc: null });
if (color) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell .monaco-editor-background,
.monaco-workbench .part.editor > .content .notebook-editor .cell .margin-view-overlays { background: ${color}; }`);
}
const link = theme.getColor(textLinkForeground);
if (link) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell a { color: ${link}; }`);
}
const activeLink = theme.getColor(textLinkActiveForeground);
if (activeLink) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell a:hover,
.monaco-workbench .part.editor > .content .notebook-editor .cell a:active { color: ${activeLink}; }`);
}
const shortcut = theme.getColor(textPreformatForeground);
if (shortcut) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor code,
.monaco-workbench .part.editor > .content .notebook-editor .shortcut { color: ${shortcut}; }`);
}
const border = theme.getColor(contrastBorder);
if (border) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-editor { border-color: ${border}; }`);
}
const quoteBackground = theme.getColor(textBlockQuoteBackground);
if (quoteBackground) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor blockquote { background: ${quoteBackground}; }`);
}
const quoteBorder = theme.getColor(textBlockQuoteBorder);
if (quoteBorder) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor blockquote { border-color: ${quoteBorder}; }`);
}
const inactiveListItem = theme.getColor('list.inactiveSelectionBackground');
if (inactiveListItem) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .output { background-color: ${inactiveListItem}; }`);
}
// Cell Margin
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row > div.cell { padding: 8px ${CELL_MARGIN}px 8px ${CELL_MARGIN}px; }`);
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .output { margin: 8px ${CELL_MARGIN}px; }`);
});
| src/vs/workbench/contrib/notebook/browser/notebookEditor.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.008992896415293217,
0.0006268963916227221,
0.0001623463031137362,
0.00018822713172994554,
0.001238493132404983
] |
{
"id": 9,
"code_window": [
"\t\traceCancellation(viewCell.resolveTextModel(), cts.token).then(model => {\n",
"\t\t\tif (model && templateData.editor) {\n",
"\t\t\t\ttemplateData.editor.setModel(model);\n",
"\t\t\t\tviewCell.attachTextEditor(templateData.editor);\n",
"\t\t\t\tif (notebookEditor.getActiveCell() === viewCell) {\n",
"\t\t\t\t\ttemplateData.editor?.focus();\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (notebookEditor.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts",
"type": "replace",
"edit_start_line_idx": 59
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as resources from 'vs/base/common/resources';
import * as dom from 'vs/base/browser/dom';
import { IAction, Action } from 'vs/base/common/actions';
import { IDebugService, IBreakpoint, CONTEXT_BREAKPOINTS_FOCUSED, State, DEBUG_SCHEME, IFunctionBreakpoint, IExceptionBreakpoint, IEnablement, BREAKPOINT_EDITOR_CONTRIBUTION_ID, IBreakpointEditorContribution, IDebugModel, IDataBreakpoint } from 'vs/workbench/contrib/debug/common/debug';
import { ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';
import { AddFunctionBreakpointAction, ToggleBreakpointsActivatedAction, RemoveAllBreakpointsAction, RemoveBreakpointAction, EnableAllBreakpointsAction, DisableAllBreakpointsAction, ReapplyBreakpointsAction } from 'vs/workbench/contrib/debug/browser/debugActions';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { Constants } from 'vs/base/common/uint';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { IListVirtualDelegate, IListContextMenuEvent, IListRenderer } from 'vs/base/browser/ui/list/list';
import { IEditorPane } from 'vs/workbench/common/editor';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { WorkbenchList } from 'vs/platform/list/browser/listService';
import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet';
import { attachInputBoxStyler } from 'vs/platform/theme/common/styler';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IEditorService, SIDE_GROUP, ACTIVE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { ViewPane } from 'vs/workbench/browser/parts/views/viewPaneContainer';
import { ILabelService } from 'vs/platform/label/common/label';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { Gesture } from 'vs/base/browser/touch';
import { IViewDescriptorService } from 'vs/workbench/common/views';
import { TextEditorSelectionRevealType } from 'vs/platform/editor/common/editor';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
const $ = dom.$;
function createCheckbox(): HTMLInputElement {
const checkbox = <HTMLInputElement>$('input');
checkbox.type = 'checkbox';
checkbox.tabIndex = -1;
Gesture.ignoreTarget(checkbox);
return checkbox;
}
const MAX_VISIBLE_BREAKPOINTS = 9;
export function getExpandedBodySize(model: IDebugModel): number {
const length = model.getBreakpoints().length + model.getExceptionBreakpoints().length + model.getFunctionBreakpoints().length + model.getDataBreakpoints().length;
return Math.min(MAX_VISIBLE_BREAKPOINTS, length) * 22;
}
export class BreakpointsView extends ViewPane {
private list!: WorkbenchList<IEnablement>;
private needsRefresh = false;
constructor(
options: IViewletViewOptions,
@IContextMenuService contextMenuService: IContextMenuService,
@IDebugService private readonly debugService: IDebugService,
@IKeybindingService keybindingService: IKeybindingService,
@IInstantiationService instantiationService: IInstantiationService,
@IThemeService themeService: IThemeService,
@IEditorService private readonly editorService: IEditorService,
@IContextViewService private readonly contextViewService: IContextViewService,
@IConfigurationService configurationService: IConfigurationService,
@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
@IContextKeyService contextKeyService: IContextKeyService,
@IOpenerService openerService: IOpenerService,
@ITelemetryService telemetryService: ITelemetryService,
) {
super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService);
this.minimumBodySize = this.maximumBodySize = getExpandedBodySize(this.debugService.getModel());
this._register(this.debugService.getModel().onDidChangeBreakpoints(() => this.onBreakpointsChange()));
}
public renderBody(container: HTMLElement): void {
super.renderBody(container);
dom.addClass(this.element, 'debug-pane');
dom.addClass(container, 'debug-breakpoints');
const delegate = new BreakpointsDelegate(this.debugService);
this.list = <WorkbenchList<IEnablement>>this.instantiationService.createInstance(WorkbenchList, 'Breakpoints', container, delegate, [
this.instantiationService.createInstance(BreakpointsRenderer),
new ExceptionBreakpointsRenderer(this.debugService),
this.instantiationService.createInstance(FunctionBreakpointsRenderer),
this.instantiationService.createInstance(DataBreakpointsRenderer),
new FunctionBreakpointInputRenderer(this.debugService, this.contextViewService, this.themeService)
], {
identityProvider: { getId: (element: IEnablement) => element.getId() },
multipleSelectionSupport: false,
keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e: IEnablement) => e },
ariaProvider: {
getSetSize: (_: IEnablement, index: number, listLength: number) => listLength,
getPosInSet: (_: IEnablement, index: number) => index,
getRole: (breakpoint: IEnablement) => 'checkbox',
isChecked: (breakpoint: IEnablement) => breakpoint.enabled
},
overrideStyles: {
listBackground: this.getBackgroundColor()
}
});
CONTEXT_BREAKPOINTS_FOCUSED.bindTo(this.list.contextKeyService);
this._register(this.list.onContextMenu(this.onListContextMenu, this));
this._register(this.list.onDidOpen(async e => {
let isSingleClick = false;
let isDoubleClick = false;
let isMiddleClick = false;
let openToSide = false;
const browserEvent = e.browserEvent;
if (browserEvent instanceof MouseEvent) {
isSingleClick = browserEvent.detail === 1;
isDoubleClick = browserEvent.detail === 2;
isMiddleClick = browserEvent.button === 1;
openToSide = (browserEvent.ctrlKey || browserEvent.metaKey || browserEvent.altKey);
}
const focused = this.list.getFocusedElements();
const element = focused.length ? focused[0] : undefined;
if (isMiddleClick) {
if (element instanceof Breakpoint) {
await this.debugService.removeBreakpoints(element.getId());
} else if (element instanceof FunctionBreakpoint) {
await this.debugService.removeFunctionBreakpoints(element.getId());
} else if (element instanceof DataBreakpoint) {
await this.debugService.removeDataBreakpoints(element.getId());
}
return;
}
if (element instanceof Breakpoint) {
openBreakpointSource(element, openToSide, isSingleClick, this.debugService, this.editorService);
}
if (isDoubleClick && element instanceof FunctionBreakpoint && element !== this.debugService.getViewModel().getSelectedFunctionBreakpoint()) {
this.debugService.getViewModel().setSelectedFunctionBreakpoint(element);
this.onBreakpointsChange();
}
}));
this.list.splice(0, this.list.length, this.elements);
this._register(this.onDidChangeBodyVisibility(visible => {
if (visible && this.needsRefresh) {
this.onBreakpointsChange();
}
}));
}
public focus(): void {
super.focus();
if (this.list) {
this.list.domFocus();
}
}
protected layoutBody(height: number, width: number): void {
if (this.list) {
this.list.layout(height, width);
}
}
private onListContextMenu(e: IListContextMenuEvent<IEnablement>): void {
if (!e.element) {
return;
}
const actions: IAction[] = [];
const element = e.element;
const breakpointType = element instanceof Breakpoint && element.logMessage ? nls.localize('Logpoint', "Logpoint") : nls.localize('Breakpoint', "Breakpoint");
if (element instanceof Breakpoint || element instanceof FunctionBreakpoint) {
actions.push(new Action('workbench.action.debug.openEditorAndEditBreakpoint', nls.localize('editBreakpoint', "Edit {0}...", breakpointType), '', true, async () => {
if (element instanceof Breakpoint) {
const editor = await openBreakpointSource(element, false, false, this.debugService, this.editorService);
if (editor) {
const codeEditor = editor.getControl();
if (isCodeEditor(codeEditor)) {
codeEditor.getContribution<IBreakpointEditorContribution>(BREAKPOINT_EDITOR_CONTRIBUTION_ID).showBreakpointWidget(element.lineNumber, element.column);
}
}
} else {
this.debugService.getViewModel().setSelectedFunctionBreakpoint(element);
this.onBreakpointsChange();
}
}));
actions.push(new Separator());
}
actions.push(new RemoveBreakpointAction(RemoveBreakpointAction.ID, nls.localize('removeBreakpoint', "Remove {0}", breakpointType), this.debugService));
if (this.debugService.getModel().getBreakpoints().length + this.debugService.getModel().getFunctionBreakpoints().length > 1) {
actions.push(new RemoveAllBreakpointsAction(RemoveAllBreakpointsAction.ID, RemoveAllBreakpointsAction.LABEL, this.debugService, this.keybindingService));
actions.push(new Separator());
actions.push(new EnableAllBreakpointsAction(EnableAllBreakpointsAction.ID, EnableAllBreakpointsAction.LABEL, this.debugService, this.keybindingService));
actions.push(new DisableAllBreakpointsAction(DisableAllBreakpointsAction.ID, DisableAllBreakpointsAction.LABEL, this.debugService, this.keybindingService));
}
actions.push(new Separator());
actions.push(new ReapplyBreakpointsAction(ReapplyBreakpointsAction.ID, ReapplyBreakpointsAction.LABEL, this.debugService, this.keybindingService));
this.contextMenuService.showContextMenu({
getAnchor: () => e.anchor,
getActions: () => actions,
getActionsContext: () => element,
onHide: () => dispose(actions)
});
}
public getActions(): IAction[] {
return [
new AddFunctionBreakpointAction(AddFunctionBreakpointAction.ID, AddFunctionBreakpointAction.LABEL, this.debugService, this.keybindingService),
new ToggleBreakpointsActivatedAction(ToggleBreakpointsActivatedAction.ID, ToggleBreakpointsActivatedAction.ACTIVATE_LABEL, this.debugService, this.keybindingService),
new RemoveAllBreakpointsAction(RemoveAllBreakpointsAction.ID, RemoveAllBreakpointsAction.LABEL, this.debugService, this.keybindingService)
];
}
private onBreakpointsChange(): void {
if (this.isBodyVisible()) {
this.minimumBodySize = getExpandedBodySize(this.debugService.getModel());
if (this.maximumBodySize < Number.POSITIVE_INFINITY) {
this.maximumBodySize = this.minimumBodySize;
}
if (this.list) {
this.list.splice(0, this.list.length, this.elements);
this.needsRefresh = false;
}
} else {
this.needsRefresh = true;
}
}
private get elements(): IEnablement[] {
const model = this.debugService.getModel();
const elements = (<ReadonlyArray<IEnablement>>model.getExceptionBreakpoints()).concat(model.getFunctionBreakpoints()).concat(model.getDataBreakpoints()).concat(model.getBreakpoints());
return elements;
}
}
class BreakpointsDelegate implements IListVirtualDelegate<IEnablement> {
constructor(private debugService: IDebugService) {
// noop
}
getHeight(element: IEnablement): number {
return 22;
}
getTemplateId(element: IEnablement): string {
if (element instanceof Breakpoint) {
return BreakpointsRenderer.ID;
}
if (element instanceof FunctionBreakpoint) {
const selected = this.debugService.getViewModel().getSelectedFunctionBreakpoint();
if (!element.name || (selected && selected.getId() === element.getId())) {
return FunctionBreakpointInputRenderer.ID;
}
return FunctionBreakpointsRenderer.ID;
}
if (element instanceof ExceptionBreakpoint) {
return ExceptionBreakpointsRenderer.ID;
}
if (element instanceof DataBreakpoint) {
return DataBreakpointsRenderer.ID;
}
return '';
}
}
interface IBaseBreakpointTemplateData {
breakpoint: HTMLElement;
name: HTMLElement;
checkbox: HTMLInputElement;
context: IEnablement;
toDispose: IDisposable[];
}
interface IBaseBreakpointWithIconTemplateData extends IBaseBreakpointTemplateData {
icon: HTMLElement;
}
interface IBreakpointTemplateData extends IBaseBreakpointWithIconTemplateData {
lineNumber: HTMLElement;
filePath: HTMLElement;
}
interface IInputTemplateData {
inputBox: InputBox;
checkbox: HTMLInputElement;
icon: HTMLElement;
breakpoint: IFunctionBreakpoint;
reactedOnEvent: boolean;
toDispose: IDisposable[];
}
class BreakpointsRenderer implements IListRenderer<IBreakpoint, IBreakpointTemplateData> {
constructor(
@IDebugService private readonly debugService: IDebugService,
@ILabelService private readonly labelService: ILabelService
) {
// noop
}
static readonly ID = 'breakpoints';
get templateId() {
return BreakpointsRenderer.ID;
}
renderTemplate(container: HTMLElement): IBreakpointTemplateData {
const data: IBreakpointTemplateData = Object.create(null);
data.breakpoint = dom.append(container, $('.breakpoint'));
data.icon = $('.icon');
data.checkbox = createCheckbox();
data.toDispose = [];
data.toDispose.push(dom.addStandardDisposableListener(data.checkbox, 'change', (e) => {
this.debugService.enableOrDisableBreakpoints(!data.context.enabled, data.context);
}));
dom.append(data.breakpoint, data.icon);
dom.append(data.breakpoint, data.checkbox);
data.name = dom.append(data.breakpoint, $('span.name'));
data.filePath = dom.append(data.breakpoint, $('span.file-path'));
const lineNumberContainer = dom.append(data.breakpoint, $('.line-number-container'));
data.lineNumber = dom.append(lineNumberContainer, $('span.line-number'));
return data;
}
renderElement(breakpoint: IBreakpoint, index: number, data: IBreakpointTemplateData): void {
data.context = breakpoint;
dom.toggleClass(data.breakpoint, 'disabled', !this.debugService.getModel().areBreakpointsActivated());
data.name.textContent = resources.basenameOrAuthority(breakpoint.uri);
data.lineNumber.textContent = breakpoint.lineNumber.toString();
if (breakpoint.column) {
data.lineNumber.textContent += `:${breakpoint.column}`;
}
data.filePath.textContent = this.labelService.getUriLabel(resources.dirname(breakpoint.uri), { relative: true });
data.checkbox.checked = breakpoint.enabled;
const { message, className } = getBreakpointMessageAndClassName(this.debugService.state, this.debugService.getModel().areBreakpointsActivated(), breakpoint);
data.icon.className = `codicon ${className}`;
data.breakpoint.title = breakpoint.message || message || '';
const debugActive = this.debugService.state === State.Running || this.debugService.state === State.Stopped;
if (debugActive && !breakpoint.verified) {
dom.addClass(data.breakpoint, 'disabled');
}
}
disposeTemplate(templateData: IBreakpointTemplateData): void {
dispose(templateData.toDispose);
}
}
class ExceptionBreakpointsRenderer implements IListRenderer<IExceptionBreakpoint, IBaseBreakpointTemplateData> {
constructor(
private debugService: IDebugService
) {
// noop
}
static readonly ID = 'exceptionbreakpoints';
get templateId() {
return ExceptionBreakpointsRenderer.ID;
}
renderTemplate(container: HTMLElement): IBaseBreakpointTemplateData {
const data: IBreakpointTemplateData = Object.create(null);
data.breakpoint = dom.append(container, $('.breakpoint'));
data.checkbox = createCheckbox();
data.toDispose = [];
data.toDispose.push(dom.addStandardDisposableListener(data.checkbox, 'change', (e) => {
this.debugService.enableOrDisableBreakpoints(!data.context.enabled, data.context);
}));
dom.append(data.breakpoint, data.checkbox);
data.name = dom.append(data.breakpoint, $('span.name'));
dom.addClass(data.breakpoint, 'exception');
return data;
}
renderElement(exceptionBreakpoint: IExceptionBreakpoint, index: number, data: IBaseBreakpointTemplateData): void {
data.context = exceptionBreakpoint;
data.name.textContent = exceptionBreakpoint.label || `${exceptionBreakpoint.filter} exceptions`;
data.breakpoint.title = data.name.textContent;
data.checkbox.checked = exceptionBreakpoint.enabled;
}
disposeTemplate(templateData: IBaseBreakpointTemplateData): void {
dispose(templateData.toDispose);
}
}
class FunctionBreakpointsRenderer implements IListRenderer<FunctionBreakpoint, IBaseBreakpointWithIconTemplateData> {
constructor(
@IDebugService private readonly debugService: IDebugService
) {
// noop
}
static readonly ID = 'functionbreakpoints';
get templateId() {
return FunctionBreakpointsRenderer.ID;
}
renderTemplate(container: HTMLElement): IBaseBreakpointWithIconTemplateData {
const data: IBreakpointTemplateData = Object.create(null);
data.breakpoint = dom.append(container, $('.breakpoint'));
data.icon = $('.icon');
data.checkbox = createCheckbox();
data.toDispose = [];
data.toDispose.push(dom.addStandardDisposableListener(data.checkbox, 'change', (e) => {
this.debugService.enableOrDisableBreakpoints(!data.context.enabled, data.context);
}));
dom.append(data.breakpoint, data.icon);
dom.append(data.breakpoint, data.checkbox);
data.name = dom.append(data.breakpoint, $('span.name'));
return data;
}
renderElement(functionBreakpoint: FunctionBreakpoint, _index: number, data: IBaseBreakpointWithIconTemplateData): void {
data.context = functionBreakpoint;
data.name.textContent = functionBreakpoint.name;
const { className, message } = getBreakpointMessageAndClassName(this.debugService.state, this.debugService.getModel().areBreakpointsActivated(), functionBreakpoint);
data.icon.className = `codicon ${className}`;
data.icon.title = message ? message : '';
data.checkbox.checked = functionBreakpoint.enabled;
data.breakpoint.title = message ? message : '';
// Mark function breakpoints as disabled if deactivated or if debug type does not support them #9099
const session = this.debugService.getViewModel().focusedSession;
dom.toggleClass(data.breakpoint, 'disabled', (session && !session.capabilities.supportsFunctionBreakpoints) || !this.debugService.getModel().areBreakpointsActivated());
if (session && !session.capabilities.supportsFunctionBreakpoints) {
data.breakpoint.title = nls.localize('functionBreakpointsNotSupported', "Function breakpoints are not supported by this debug type");
}
}
disposeTemplate(templateData: IBaseBreakpointWithIconTemplateData): void {
dispose(templateData.toDispose);
}
}
class DataBreakpointsRenderer implements IListRenderer<DataBreakpoint, IBaseBreakpointWithIconTemplateData> {
constructor(
@IDebugService private readonly debugService: IDebugService
) {
// noop
}
static readonly ID = 'databreakpoints';
get templateId() {
return DataBreakpointsRenderer.ID;
}
renderTemplate(container: HTMLElement): IBaseBreakpointWithIconTemplateData {
const data: IBreakpointTemplateData = Object.create(null);
data.breakpoint = dom.append(container, $('.breakpoint'));
data.icon = $('.icon');
data.checkbox = createCheckbox();
data.toDispose = [];
data.toDispose.push(dom.addStandardDisposableListener(data.checkbox, 'change', (e) => {
this.debugService.enableOrDisableBreakpoints(!data.context.enabled, data.context);
}));
dom.append(data.breakpoint, data.icon);
dom.append(data.breakpoint, data.checkbox);
data.name = dom.append(data.breakpoint, $('span.name'));
return data;
}
renderElement(dataBreakpoint: DataBreakpoint, _index: number, data: IBaseBreakpointWithIconTemplateData): void {
data.context = dataBreakpoint;
data.name.textContent = dataBreakpoint.description;
const { className, message } = getBreakpointMessageAndClassName(this.debugService.state, this.debugService.getModel().areBreakpointsActivated(), dataBreakpoint);
data.icon.className = `codicon ${className}`;
data.icon.title = message ? message : '';
data.checkbox.checked = dataBreakpoint.enabled;
data.breakpoint.title = message ? message : '';
// Mark function breakpoints as disabled if deactivated or if debug type does not support them #9099
const session = this.debugService.getViewModel().focusedSession;
dom.toggleClass(data.breakpoint, 'disabled', (session && !session.capabilities.supportsDataBreakpoints) || !this.debugService.getModel().areBreakpointsActivated());
if (session && !session.capabilities.supportsDataBreakpoints) {
data.breakpoint.title = nls.localize('dataBreakpointsNotSupported', "Data breakpoints are not supported by this debug type");
}
}
disposeTemplate(templateData: IBaseBreakpointWithIconTemplateData): void {
dispose(templateData.toDispose);
}
}
class FunctionBreakpointInputRenderer implements IListRenderer<IFunctionBreakpoint, IInputTemplateData> {
constructor(
private debugService: IDebugService,
private contextViewService: IContextViewService,
private themeService: IThemeService
) {
// noop
}
static readonly ID = 'functionbreakpointinput';
get templateId() {
return FunctionBreakpointInputRenderer.ID;
}
renderTemplate(container: HTMLElement): IInputTemplateData {
const template: IInputTemplateData = Object.create(null);
const breakpoint = dom.append(container, $('.breakpoint'));
template.icon = $('.icon');
template.checkbox = createCheckbox();
dom.append(breakpoint, template.icon);
dom.append(breakpoint, template.checkbox);
const inputBoxContainer = dom.append(breakpoint, $('.inputBoxContainer'));
const inputBox = new InputBox(inputBoxContainer, this.contextViewService, {
placeholder: nls.localize('functionBreakpointPlaceholder', "Function to break on"),
ariaLabel: nls.localize('functionBreakPointInputAriaLabel', "Type function breakpoint")
});
const styler = attachInputBoxStyler(inputBox, this.themeService);
const toDispose: IDisposable[] = [inputBox, styler];
const wrapUp = (renamed: boolean) => {
if (!template.reactedOnEvent) {
template.reactedOnEvent = true;
this.debugService.getViewModel().setSelectedFunctionBreakpoint(undefined);
if (inputBox.value && (renamed || template.breakpoint.name)) {
this.debugService.renameFunctionBreakpoint(template.breakpoint.getId(), renamed ? inputBox.value : template.breakpoint.name);
} else {
this.debugService.removeFunctionBreakpoints(template.breakpoint.getId());
}
}
};
toDispose.push(dom.addStandardDisposableListener(inputBox.inputElement, 'keydown', (e: IKeyboardEvent) => {
const isEscape = e.equals(KeyCode.Escape);
const isEnter = e.equals(KeyCode.Enter);
if (isEscape || isEnter) {
e.preventDefault();
e.stopPropagation();
wrapUp(isEnter);
}
}));
toDispose.push(dom.addDisposableListener(inputBox.inputElement, 'blur', () => {
// Need to react with a timeout on the blur event due to possible concurent splices #56443
setTimeout(() => {
if (!template.breakpoint.name) {
wrapUp(true);
}
});
}));
template.inputBox = inputBox;
template.toDispose = toDispose;
return template;
}
renderElement(functionBreakpoint: FunctionBreakpoint, _index: number, data: IInputTemplateData): void {
data.breakpoint = functionBreakpoint;
data.reactedOnEvent = false;
const { className, message } = getBreakpointMessageAndClassName(this.debugService.state, this.debugService.getModel().areBreakpointsActivated(), functionBreakpoint);
data.icon.className = `codicon ${className}`;
data.icon.title = message ? message : '';
data.checkbox.checked = functionBreakpoint.enabled;
data.checkbox.disabled = true;
data.inputBox.value = functionBreakpoint.name || '';
setTimeout(() => {
data.inputBox.focus();
data.inputBox.select();
}, 0);
}
disposeTemplate(templateData: IInputTemplateData): void {
dispose(templateData.toDispose);
}
}
export function openBreakpointSource(breakpoint: IBreakpoint, sideBySide: boolean, preserveFocus: boolean, debugService: IDebugService, editorService: IEditorService): Promise<IEditorPane | undefined> {
if (breakpoint.uri.scheme === DEBUG_SCHEME && debugService.state === State.Inactive) {
return Promise.resolve(undefined);
}
const selection = breakpoint.endLineNumber ? {
startLineNumber: breakpoint.lineNumber,
endLineNumber: breakpoint.endLineNumber,
startColumn: breakpoint.column || 1,
endColumn: breakpoint.endColumn || Constants.MAX_SAFE_SMALL_INTEGER
} : {
startLineNumber: breakpoint.lineNumber,
startColumn: breakpoint.column || 1,
endLineNumber: breakpoint.lineNumber,
endColumn: breakpoint.column || Constants.MAX_SAFE_SMALL_INTEGER
};
return editorService.openEditor({
resource: breakpoint.uri,
options: {
preserveFocus,
selection,
revealIfOpened: true,
selectionRevealType: TextEditorSelectionRevealType.CenterIfOutsideViewport,
pinned: !preserveFocus
}
}, sideBySide ? SIDE_GROUP : ACTIVE_GROUP);
}
export function getBreakpointMessageAndClassName(state: State, breakpointsActivated: boolean, breakpoint: IBreakpoint | IFunctionBreakpoint | IDataBreakpoint): { message?: string, className: string } {
const debugActive = state === State.Running || state === State.Stopped;
if (!breakpoint.enabled || !breakpointsActivated) {
return {
className: breakpoint instanceof DataBreakpoint ? 'codicon-debug-breakpoint-data-disabled' : breakpoint instanceof FunctionBreakpoint ? 'codicon-debug-breakpoint-function-disabled' : breakpoint.logMessage ? 'codicon-debug-breakpoint-log-disabled' : 'codicon-debug-breakpoint-disabled',
message: breakpoint.logMessage ? nls.localize('disabledLogpoint', "Disabled Logpoint") : nls.localize('disabledBreakpoint', "Disabled Breakpoint"),
};
}
const appendMessage = (text: string): string => {
return ('message' in breakpoint && breakpoint.message) ? text.concat(', ' + breakpoint.message) : text;
};
if (debugActive && !breakpoint.verified) {
return {
className: breakpoint instanceof DataBreakpoint ? 'codicon-debug-breakpoint-data-unverified' : breakpoint instanceof FunctionBreakpoint ? 'codicon-debug-breakpoint-function-unverified' : breakpoint.logMessage ? 'codicon-debug-breakpoint-log-unverified' : 'codicon-debug-breakpoint-unverified',
message: ('message' in breakpoint && breakpoint.message) ? breakpoint.message : (breakpoint.logMessage ? nls.localize('unverifiedLogpoint', "Unverified Logpoint") : nls.localize('unverifiedBreakopint', "Unverified Breakpoint")),
};
}
if (breakpoint instanceof FunctionBreakpoint) {
if (!breakpoint.supported) {
return {
className: 'codicon-debug-breakpoint-function-unverified',
message: nls.localize('functionBreakpointUnsupported', "Function breakpoints not supported by this debug type"),
};
}
return {
className: 'codicon-debug-breakpoint-function',
message: breakpoint.message || nls.localize('functionBreakpoint', "Function Breakpoint")
};
}
if (breakpoint instanceof DataBreakpoint) {
if (!breakpoint.supported) {
return {
className: 'codicon-debug-breakpoint-data-unverified',
message: nls.localize('dataBreakpointUnsupported', "Data breakpoints not supported by this debug type"),
};
}
return {
className: 'codicon-debug-breakpoint-data',
message: breakpoint.message || nls.localize('dataBreakpoint', "Data Breakpoint")
};
}
if (breakpoint.logMessage || breakpoint.condition || breakpoint.hitCondition) {
const messages: string[] = [];
if (!breakpoint.supported) {
return {
className: 'codicon-debug-breakpoint-unsupported',
message: nls.localize('breakpointUnsupported', "Breakpoints of this type are not supported by the debugger"),
};
}
if (breakpoint.logMessage) {
messages.push(nls.localize('logMessage', "Log Message: {0}", breakpoint.logMessage));
}
if (breakpoint.condition) {
messages.push(nls.localize('expression', "Expression: {0}", breakpoint.condition));
}
if (breakpoint.hitCondition) {
messages.push(nls.localize('hitCount', "Hit Count: {0}", breakpoint.hitCondition));
}
return {
className: breakpoint.logMessage ? 'codicon-debug-breakpoint-log' : 'codicon-debug-breakpoint-conditional',
message: appendMessage(messages.join('\n'))
};
}
return {
className: 'codicon-debug-breakpoint',
message: ('message' in breakpoint && breakpoint.message) ? breakpoint.message : nls.localize('breakpoint', "Breakpoint")
};
}
| src/vs/workbench/contrib/debug/browser/breakpointsView.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0007899852935224771,
0.00019945891108363867,
0.0001639797119423747,
0.00017372758884448558,
0.00010568378638708964
] |
{
"id": 9,
"code_window": [
"\t\traceCancellation(viewCell.resolveTextModel(), cts.token).then(model => {\n",
"\t\t\tif (model && templateData.editor) {\n",
"\t\t\t\ttemplateData.editor.setModel(model);\n",
"\t\t\t\tviewCell.attachTextEditor(templateData.editor);\n",
"\t\t\t\tif (notebookEditor.getActiveCell() === viewCell) {\n",
"\t\t\t\t\ttemplateData.editor?.focus();\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (notebookEditor.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts",
"type": "replace",
"edit_start_line_idx": 59
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as strings from 'vs/base/common/strings';
import { ILocalization } from 'vs/platform/localizations/common/localizations';
import { URI } from 'vs/base/common/uri';
export const MANIFEST_CACHE_FOLDER = 'CachedExtensions';
export const USER_MANIFEST_CACHE_FILE = 'user';
export const BUILTIN_MANIFEST_CACHE_FILE = 'builtin';
export interface ICommand {
command: string;
title: string;
category?: string;
}
export interface IConfigurationProperty {
description: string;
type: string | string[];
default?: any;
}
export interface IConfiguration {
properties: { [key: string]: IConfigurationProperty; };
}
export interface IDebugger {
label?: string;
type: string;
runtime?: string;
}
export interface IGrammar {
language: string;
}
export interface IJSONValidation {
fileMatch: string | string[];
url: string;
}
export interface IKeyBinding {
command: string;
key: string;
when?: string;
mac?: string;
linux?: string;
win?: string;
}
export interface ILanguage {
id: string;
extensions: string[];
aliases: string[];
}
export interface IMenu {
command: string;
alt?: string;
when?: string;
group?: string;
}
export interface ISnippet {
language: string;
}
export interface ITheme {
label: string;
}
export interface IViewContainer {
id: string;
title: string;
}
export interface IView {
id: string;
name: string;
}
export interface IColor {
id: string;
description: string;
defaults: { light: string, dark: string, highContrast: string };
}
export interface IWebviewEditor {
readonly viewType: string;
readonly priority: string;
readonly selector: readonly {
readonly filenamePattern?: string;
}[];
}
export interface ICodeActionContributionAction {
readonly kind: string;
readonly title: string;
readonly description?: string;
}
export interface ICodeActionContribution {
readonly languages: readonly string[];
readonly actions: readonly ICodeActionContributionAction[];
}
export interface IExtensionContributions {
commands?: ICommand[];
configuration?: IConfiguration | IConfiguration[];
debuggers?: IDebugger[];
grammars?: IGrammar[];
jsonValidation?: IJSONValidation[];
keybindings?: IKeyBinding[];
languages?: ILanguage[];
menus?: { [context: string]: IMenu[] };
snippets?: ISnippet[];
themes?: ITheme[];
iconThemes?: ITheme[];
viewsContainers?: { [location: string]: IViewContainer[] };
views?: { [location: string]: IView[] };
colors?: IColor[];
localizations?: ILocalization[];
readonly customEditors?: readonly IWebviewEditor[];
readonly codeActions?: readonly ICodeActionContribution[];
}
export type ExtensionKind = 'ui' | 'workspace' | 'web';
export function isIExtensionIdentifier(thing: any): thing is IExtensionIdentifier {
return thing
&& typeof thing === 'object'
&& typeof thing.id === 'string'
&& (!thing.uuid || typeof thing.uuid === 'string');
}
export interface IExtensionIdentifier {
id: string;
uuid?: string;
}
export interface IExtensionManifest {
readonly name: string;
readonly displayName?: string;
readonly publisher: string;
readonly version: string;
readonly engines: { vscode: string };
readonly description?: string;
readonly main?: string;
readonly icon?: string;
readonly categories?: string[];
readonly keywords?: string[];
readonly activationEvents?: string[];
readonly extensionDependencies?: string[];
readonly extensionPack?: string[];
readonly extensionKind?: ExtensionKind | ExtensionKind[];
readonly contributes?: IExtensionContributions;
readonly repository?: { url: string; };
readonly bugs?: { url: string; };
readonly enableProposedApi?: boolean;
readonly api?: string;
readonly scripts?: { [key: string]: string; };
}
export const enum ExtensionType {
System,
User
}
export interface IExtension {
readonly type: ExtensionType;
readonly identifier: IExtensionIdentifier;
readonly manifest: IExtensionManifest;
readonly location: URI;
}
/**
* **!Do not construct directly!**
*
* **!Only static methods because it gets serialized!**
*
* This represents the "canonical" version for an extension identifier. Extension ids
* have to be case-insensitive (due to the marketplace), but we must ensure case
* preservation because the extension API is already public at this time.
*
* For example, given an extension with the publisher `"Hello"` and the name `"World"`,
* its canonical extension identifier is `"Hello.World"`. This extension could be
* referenced in some other extension's dependencies using the string `"hello.world"`.
*
* To make matters more complicated, an extension can optionally have an UUID. When two
* extensions have the same UUID, they are considered equal even if their identifier is different.
*/
export class ExtensionIdentifier {
public readonly value: string;
private readonly _lower: string;
constructor(value: string) {
this.value = value;
this._lower = value.toLowerCase();
}
public static equals(a: ExtensionIdentifier | string | null | undefined, b: ExtensionIdentifier | string | null | undefined) {
if (typeof a === 'undefined' || a === null) {
return (typeof b === 'undefined' || b === null);
}
if (typeof b === 'undefined' || b === null) {
return false;
}
if (typeof a === 'string' || typeof b === 'string') {
// At least one of the arguments is an extension id in string form,
// so we have to use the string comparison which ignores case.
let aValue = (typeof a === 'string' ? a : a.value);
let bValue = (typeof b === 'string' ? b : b.value);
return strings.equalsIgnoreCase(aValue, bValue);
}
// Now we know both arguments are ExtensionIdentifier
return (a._lower === b._lower);
}
/**
* Gives the value by which to index (for equality).
*/
public static toKey(id: ExtensionIdentifier | string): string {
if (typeof id === 'string') {
return id.toLowerCase();
}
return id._lower;
}
}
export interface IExtensionDescription extends IExtensionManifest {
readonly identifier: ExtensionIdentifier;
readonly uuid?: string;
readonly isBuiltin: boolean;
readonly isUnderDevelopment: boolean;
readonly extensionLocation: URI;
enableProposedApi?: boolean;
}
export function isLanguagePackExtension(manifest: IExtensionManifest): boolean {
return manifest.contributes && manifest.contributes.localizations ? manifest.contributes.localizations.length > 0 : false;
}
| src/vs/platform/extensions/common/extensions.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00018150737741962075,
0.00017595636018086225,
0.00016807032807264477,
0.00017641311569605023,
0.000002681297473827726
] |
{
"id": 9,
"code_window": [
"\t\traceCancellation(viewCell.resolveTextModel(), cts.token).then(model => {\n",
"\t\t\tif (model && templateData.editor) {\n",
"\t\t\t\ttemplateData.editor.setModel(model);\n",
"\t\t\t\tviewCell.attachTextEditor(templateData.editor);\n",
"\t\t\t\tif (notebookEditor.getActiveCell() === viewCell) {\n",
"\t\t\t\t\ttemplateData.editor?.focus();\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (notebookEditor.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts",
"type": "replace",
"edit_start_line_idx": 59
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { MenuRegistry } from 'vs/platform/actions/common/actions';
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { Registry } from 'vs/platform/registry/common/platform';
import { Extensions, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions';
import { Extensions as Input, IEditorInputFactory, IEditorInputFactoryRegistry } from 'vs/workbench/common/editor';
import { PerfviewContrib, PerfviewInput } from 'vs/workbench/contrib/performance/electron-browser/perfviewEditor';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { StartupProfiler } from './startupProfiler';
import { StartupTimings } from './startupTimings';
// -- startup performance view
Registry.as<IWorkbenchContributionsRegistry>(Extensions.Workbench).registerWorkbenchContribution(
PerfviewContrib,
LifecyclePhase.Ready
);
Registry.as<IEditorInputFactoryRegistry>(Input.EditorInputFactories).registerEditorInputFactory(
PerfviewInput.Id,
class implements IEditorInputFactory {
canSerialize(): boolean {
return true;
}
serialize(): string {
return '';
}
deserialize(instantiationService: IInstantiationService): PerfviewInput {
return instantiationService.createInstance(PerfviewInput);
}
}
);
CommandsRegistry.registerCommand('perfview.show', accessor => {
const editorService = accessor.get(IEditorService);
const instaService = accessor.get(IInstantiationService);
return editorService.openEditor(instaService.createInstance(PerfviewInput));
});
MenuRegistry.addCommand({
id: 'perfview.show',
category: localize('show.cat', "Developer"),
title: localize('show.label', "Startup Performance")
});
// -- startup profiler
Registry.as<IWorkbenchContributionsRegistry>(Extensions.Workbench).registerWorkbenchContribution(
StartupProfiler,
LifecyclePhase.Restored
);
// -- startup timings
Registry.as<IWorkbenchContributionsRegistry>(Extensions.Workbench).registerWorkbenchContribution(
StartupTimings,
LifecyclePhase.Eventually
);
| src/vs/workbench/contrib/performance/electron-browser/performance.contribution.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017815930186770856,
0.00017646918422542512,
0.0001710261421976611,
0.0001771461684256792,
0.000002276081431773491
] |
{
"id": 10,
"code_window": [
"\t\t\t\t\t);\n",
"\n",
"\t\t\t\t\tviewCell.editorHeight = realContentHeight;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell) {\n",
"\t\t\t\t\ttemplateData.editor?.focus();\n",
"\t\t\t\t}\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts",
"type": "replace",
"edit_start_line_idx": 83
} | /*---------------------------------------------------------------------------------------------
* 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 { IListRenderer, IListVirtualDelegate, ListError } from 'vs/base/browser/ui/list/list';
import { Event } from 'vs/base/common/event';
import { ScrollEvent } from 'vs/base/common/scrollable';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IListService, IWorkbenchListOptions, WorkbenchList } from 'vs/platform/list/browser/listService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { isMacintosh } from 'vs/base/common/platform';
import { NOTEBOOK_EDITOR_CURSOR_BOUNDARY } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { Range } from 'vs/editor/common/core/range';
import { CellRevealType, CellRevealPosition, CursorAtBoundary } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';
import { EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable {
get onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }
get rowsContainer(): HTMLElement {
return this.view.containerDomNode;
}
private _previousSelectedElements: CellViewModel[] = [];
private _localDisposableStore = new DisposableStore();
constructor(
private listUser: string,
container: HTMLElement,
delegate: IListVirtualDelegate<CellViewModel>,
renderers: IListRenderer<CellViewModel, any>[],
contextKeyService: IContextKeyService,
options: IWorkbenchListOptions<CellViewModel>,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService
) {
super(listUser, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService);
this._previousSelectedElements = this.getSelectedElements();
this._localDisposableStore.add(this.onDidChangeSelection((e) => {
this._previousSelectedElements.forEach(element => {
if (e.elements.indexOf(element) < 0) {
element.onDeselect();
}
});
this._previousSelectedElements = e.elements;
}));
const notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);
notebookEditorCursorAtBoundaryContext.set('none');
let cursorSelectionLisener: IDisposable | null = null;
const recomputeContext = (element: CellViewModel) => {
switch (element.cursorAtBoundary()) {
case CursorAtBoundary.Both:
notebookEditorCursorAtBoundaryContext.set('both');
break;
case CursorAtBoundary.Top:
notebookEditorCursorAtBoundaryContext.set('top');
break;
case CursorAtBoundary.Bottom:
notebookEditorCursorAtBoundaryContext.set('bottom');
break;
default:
notebookEditorCursorAtBoundaryContext.set('none');
break;
}
return;
};
// Cursor Boundary context
this._localDisposableStore.add(this.onDidChangeFocus((e) => {
cursorSelectionLisener?.dispose();
if (e.elements.length) {
// we only validate the first focused element
const focusedElement = e.elements[0];
cursorSelectionLisener = focusedElement.onDidChangeCursorSelection(() => {
recomputeContext(focusedElement);
});
recomputeContext(focusedElement);
return;
}
// reset context
notebookEditorCursorAtBoundaryContext.set('none');
}));
}
domElementAtIndex(index: number): HTMLElement | null {
return this.view.domElement(index);
}
focusView() {
this.view.domNode.focus();
}
getAbsoluteTop(index: number): number {
if (index < 0 || index >= this.length) {
throw new ListError(this.listUser, `Invalid index ${index}`);
}
return this.view.elementTop(index);
}
triggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {
this.view.triggerScrollFromMouseWheelEvent(browserEvent);
}
updateElementHeight(index: number, size: number): void {
const focused = this.getSelection();
this.view.updateElementHeight(index, size, focused.length ? focused[0] : null);
// this.view.updateElementHeight(index, size, null);
}
// override
domFocus() {
if (document.activeElement && this.view.domNode.contains(document.activeElement)) {
// for example, when focus goes into monaco editor, if we refocus the list view, the editor will lose focus.
return;
}
if (!isMacintosh && document.activeElement && isContextMenuFocused()) {
return;
}
super.domFocus();
}
private _revealRange(index: number, range: Range, revealType: CellRevealType, newlyCreated: boolean, alignToBottom: boolean) {
const element = this.view.element(index);
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const startLineNumber = range.startLineNumber;
const lineOffset = element.getLineScrollTopOffset(startLineNumber);
const elementTop = this.view.elementTop(index);
const lineTop = elementTop + lineOffset + EDITOR_TOP_PADDING;
// TODO@rebornix 30 ---> line height * 1.5
if (lineTop < scrollTop) {
this.view.setScrollTop(lineTop - 30);
} else if (lineTop > wrapperBottom) {
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else if (newlyCreated) {
// newly scrolled into view
if (alignToBottom) {
// align to the bottom
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else {
// align to to top
this.view.setScrollTop(lineTop - 30);
}
}
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
}
// TODO@rebornix TEST & Fix potential bugs
// List items have real dynamic heights, which means after we set `scrollTop` based on the `elementTop(index)`, the element at `index` might still be removed from the view once all relayouting tasks are done.
// For example, we scroll item 10 into the view upwards, in the first round, items 7, 8, 9, 10 are all in the viewport. Then item 7 and 8 resize themselves to be larger and finally item 10 is removed from the view.
// To ensure that item 10 is always there, we need to scroll item 10 to the top edge of the viewport.
private _revealRangeInternal(index: number, range: Range, revealType: CellRevealType) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const element = this.view.element(index);
if (element.editorAttached) {
this._revealRange(index, range, revealType, false, false);
} else {
const elementHeight = this.view.elementHeight(index);
let upwards = false;
if (elementTop + elementHeight < scrollTop) {
// scroll downwards
this.view.setScrollTop(elementTop);
upwards = false;
} else if (elementTop > wrapperBottom) {
// scroll upwards
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
upwards = true;
}
const editorAttachedPromise = new Promise((resolve, reject) => {
element.onDidChangeEditorAttachState(state => state ? resolve() : reject());
});
editorAttachedPromise.then(() => {
this._revealRange(index, range, revealType, true, upwards);
});
}
}
revealLineInView(index: number, line: number) {
this._revealRangeInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInView(index: number, range: Range): void {
this._revealRangeInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
};
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
const element = this.view.element(index);
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
reveal(index, range, revealType);
}
}
revealLineInCenter(index: number, line: number) {
this._revealRangeInCenterInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenter(index: number, range: Range): void {
this._revealRangeInCenterInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterIfOutsideViewportInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
setTimeout(() => {
element.revealRangeInCenter(range);
}, 240);
}
};
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
const element = this.view.element(index);
if (viewItemOffset < scrollTop || viewItemOffset > wrapperBottom) {
// let it render
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
// after rendering, it might be pushed down due to markdown cell dynamic height
const elementTop = this.view.elementTop(index);
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
// reveal editor
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
// for example markdown
}
} else {
if (element.editorAttached) {
element.revealRangeInCenter(range);
} else {
// for example, markdown cell in preview mode
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
}
}
}
revealLineInCenterIfOutsideViewport(index: number, line: number) {
this._revealRangeInCenterIfOutsideViewportInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenterIfOutsideViewport(index: number, range: Range): void {
this._revealRangeInCenterIfOutsideViewportInternal(index, range, CellRevealType.Range);
}
private _revealInternal(index: number, ignoreIfInsideViewport: boolean, revealPosition: CellRevealPosition) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
if (ignoreIfInsideViewport && elementTop >= scrollTop && elementTop < wrapperBottom) {
// inside the viewport
return;
}
// first render
const viewItemOffset = revealPosition === CellRevealPosition.Top ? elementTop : (elementTop - this.view.renderHeight / 2);
this.view.setScrollTop(viewItemOffset);
// second scroll as markdown cell is dynamic
const newElementTop = this.view.elementTop(index);
const newViewItemOffset = revealPosition === CellRevealPosition.Top ? newElementTop : (newElementTop - this.view.renderHeight / 2);
this.view.setScrollTop(newViewItemOffset);
}
revealInView(index: number) {
this._revealInternal(index, true, CellRevealPosition.Top);
}
revealInCenter(index: number) {
this._revealInternal(index, false, CellRevealPosition.Center);
}
revealInCenterIfOutsideViewport(index: number) {
this._revealInternal(index, true, CellRevealPosition.Center);
}
setCellSelection(index: number, range: Range) {
const element = this.view.element(index);
if (element.editorAttached) {
element.setSelection(range);
} else {
getEditorAttachedPromise(element).then(() => { element.setSelection(range); });
}
}
dispose() {
this._localDisposableStore.dispose();
super.dispose();
}
}
function getEditorAttachedPromise(element: CellViewModel) {
return new Promise((resolve, reject) => {
Event.once(element.onDidChangeEditorAttachState)(state => state ? resolve() : reject());
});
}
function isContextMenuFocused() {
return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
}
| src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0007120557129383087,
0.00019995901675429195,
0.00016474687436129898,
0.0001699022832326591,
0.00011751813144655898
] |
{
"id": 10,
"code_window": [
"\t\t\t\t\t);\n",
"\n",
"\t\t\t\t\tviewCell.editorHeight = realContentHeight;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell) {\n",
"\t\t\t\t\ttemplateData.editor?.focus();\n",
"\t\t\t\t}\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts",
"type": "replace",
"edit_start_line_idx": 83
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Terminal as XTermTerminal } from 'xterm';
import { SearchAddon as XTermSearchAddon } from 'xterm-addon-search';
import { Unicode11Addon as XTermUnicode11Addon } from 'xterm-addon-unicode11';
import { WebLinksAddon as XTermWebLinksAddon } from 'xterm-addon-web-links';
import { WebglAddon as XTermWebglAddon } from 'xterm-addon-webgl';
import { IWindowsShellHelper, ITerminalConfigHelper, ITerminalChildProcess, IShellLaunchConfig, IDefaultShellAndArgsRequest, ISpawnExtHostProcessRequest, IStartExtensionTerminalRequest, IAvailableShellsRequest, ITerminalProcessExtHostProxy, ICommandTracker, INavigationMode, TitleEventSource, ITerminalDimensions } from 'vs/workbench/contrib/terminal/common/terminal';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IProcessEnvironment, Platform } from 'vs/base/common/platform';
import { Event } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { FindReplaceState } from 'vs/editor/contrib/find/findState';
import { URI } from 'vs/base/common/uri';
export const ITerminalService = createDecorator<ITerminalService>('terminalService');
export const ITerminalInstanceService = createDecorator<ITerminalInstanceService>('terminalInstanceService');
/**
* A service used by TerminalInstance (and components owned by it) that allows it to break its
* dependency on electron-browser and node layers, while at the same time avoiding a cyclic
* dependency on ITerminalService.
*/
export interface ITerminalInstanceService {
_serviceBrand: undefined;
// These events are optional as the requests they make are only needed on the browser side
onRequestDefaultShellAndArgs?: Event<IDefaultShellAndArgsRequest>;
getXtermConstructor(): Promise<typeof XTermTerminal>;
getXtermSearchConstructor(): Promise<typeof XTermSearchAddon>;
getXtermUnicode11Constructor(): Promise<typeof XTermUnicode11Addon>;
getXtermWebLinksConstructor(): Promise<typeof XTermWebLinksAddon>;
getXtermWebglConstructor(): Promise<typeof XTermWebglAddon>;
createWindowsShellHelper(shellProcessId: number, instance: ITerminalInstance, xterm: XTermTerminal): IWindowsShellHelper;
createTerminalProcess(shellLaunchConfig: IShellLaunchConfig, cwd: string, cols: number, rows: number, env: IProcessEnvironment, windowsEnableConpty: boolean): ITerminalChildProcess;
getDefaultShellAndArgs(useAutomationShell: boolean, platformOverride?: Platform): Promise<{ shell: string, args: string[] | string | undefined }>;
getMainProcessParentEnv(): Promise<IProcessEnvironment>;
}
export interface IBrowserTerminalConfigHelper extends ITerminalConfigHelper {
panelContainer: HTMLElement | undefined;
}
export const enum Direction {
Left = 0,
Right = 1,
Up = 2,
Down = 3
}
export interface ITerminalTab {
activeInstance: ITerminalInstance | null;
terminalInstances: ITerminalInstance[];
title: string;
onDisposed: Event<ITerminalTab>;
onInstancesChanged: Event<void>;
focusPreviousPane(): void;
focusNextPane(): void;
resizePane(direction: Direction): void;
setActiveInstanceByIndex(index: number): void;
attachToElement(element: HTMLElement): void;
setVisible(visible: boolean): void;
layout(width: number, height: number): void;
addDisposable(disposable: IDisposable): void;
split(shellLaunchConfig: IShellLaunchConfig): ITerminalInstance;
}
export interface ITerminalService {
_serviceBrand: undefined;
activeTabIndex: number;
configHelper: ITerminalConfigHelper;
terminalInstances: ITerminalInstance[];
terminalTabs: ITerminalTab[];
onActiveTabChanged: Event<void>;
onTabDisposed: Event<ITerminalTab>;
onInstanceCreated: Event<ITerminalInstance>;
onInstanceDisposed: Event<ITerminalInstance>;
onInstanceProcessIdReady: Event<ITerminalInstance>;
onInstanceDimensionsChanged: Event<ITerminalInstance>;
onInstanceMaximumDimensionsChanged: Event<ITerminalInstance>;
onInstanceRequestSpawnExtHostProcess: Event<ISpawnExtHostProcessRequest>;
onInstanceRequestStartExtensionTerminal: Event<IStartExtensionTerminalRequest>;
onInstancesChanged: Event<void>;
onInstanceTitleChanged: Event<ITerminalInstance>;
onActiveInstanceChanged: Event<ITerminalInstance | undefined>;
onRequestAvailableShells: Event<IAvailableShellsRequest>;
/**
* Creates a terminal.
* @param shell The shell launch configuration to use.
*/
createTerminal(shell?: IShellLaunchConfig): ITerminalInstance;
/**
* Creates a raw terminal instance, this should not be used outside of the terminal part.
*/
createInstance(container: HTMLElement | undefined, shellLaunchConfig: IShellLaunchConfig): ITerminalInstance;
getInstanceFromId(terminalId: number): ITerminalInstance | undefined;
getInstanceFromIndex(terminalIndex: number): ITerminalInstance;
getTabLabels(): string[];
getActiveInstance(): ITerminalInstance | null;
setActiveInstance(terminalInstance: ITerminalInstance): void;
setActiveInstanceByIndex(terminalIndex: number): void;
getActiveOrCreateInstance(): ITerminalInstance;
splitInstance(instance: ITerminalInstance, shell?: IShellLaunchConfig): ITerminalInstance | null;
getActiveTab(): ITerminalTab | null;
setActiveTabToNext(): void;
setActiveTabToPrevious(): void;
setActiveTabByIndex(tabIndex: number): void;
/**
* Fire the onActiveTabChanged event, this will trigger the terminal dropdown to be updated,
* among other things.
*/
refreshActiveTab(): void;
showPanel(focus?: boolean): Promise<void>;
hidePanel(): void;
focusFindWidget(): Promise<void>;
hideFindWidget(): void;
getFindState(): FindReplaceState;
findNext(): void;
findPrevious(): void;
/**
* Link handlers can be registered here to allow intercepting links clicked in the terminal.
* When a link is clicked, the link will be considered handled when the first interceptor
* resolves with true. It will be considered not handled when _all_ link handlers resolve with
* false, or 3 seconds have elapsed.
*/
addLinkHandler(key: string, callback: TerminalLinkHandlerCallback): IDisposable;
selectDefaultWindowsShell(): Promise<void>;
setContainers(panelContainer: HTMLElement, terminalContainer: HTMLElement): void;
manageWorkspaceShellPermissions(): void;
/**
* Takes a path and returns the properly escaped path to send to the terminal.
* On Windows, this included trying to prepare the path for WSL if needed.
*
* @param executable The executable off the shellLaunchConfig
* @param title The terminal's title
* @param path The path to be escaped and formatted.
* @returns An escaped version of the path to be execuded in the terminal.
*/
preparePathForTerminalAsync(path: string, executable: string | undefined, title: string, shellType: TerminalShellType): Promise<string>;
extHostReady(remoteAuthority: string): void;
requestSpawnExtHostProcess(proxy: ITerminalProcessExtHostProxy, shellLaunchConfig: IShellLaunchConfig, activeWorkspaceRootUri: URI | undefined, cols: number, rows: number, isWorkspaceShellAllowed: boolean): void;
requestStartExtensionTerminal(proxy: ITerminalProcessExtHostProxy, cols: number, rows: number): void;
}
export interface ISearchOptions {
/**
* Whether the find should be done as a regex.
*/
regex?: boolean;
/**
* Whether only whole words should match.
*/
wholeWord?: boolean;
/**
* Whether find should pay attention to case.
*/
caseSensitive?: boolean;
/**
* Whether the search should start at the current search position (not the next row)
*/
incremental?: boolean;
}
export enum WindowsShellType {
CommandPrompt,
PowerShell,
Wsl,
GitBash
}
export type TerminalShellType = WindowsShellType | undefined;
export const LINK_INTERCEPT_THRESHOLD = 3000;
export interface ITerminalBeforeHandleLinkEvent {
terminal?: ITerminalInstance;
/** The text of the link */
link: string;
/** Call with whether the link was handled by the interceptor */
resolve(wasHandled: boolean): void;
}
export type TerminalLinkHandlerCallback = (e: ITerminalBeforeHandleLinkEvent) => Promise<boolean>;
export interface ITerminalInstance {
/**
* The ID of the terminal instance, this is an arbitrary number only used to identify the
* terminal instance.
*/
readonly id: number;
readonly cols: number;
readonly rows: number;
readonly maxCols: number;
readonly maxRows: number;
/**
* The process ID of the shell process, this is undefined when there is no process associated
* with this terminal.
*/
processId: number | undefined;
/**
* An event that fires when the terminal instance's title changes.
*/
onTitleChanged: Event<ITerminalInstance>;
/**
* An event that fires when the terminal instance is disposed.
*/
onDisposed: Event<ITerminalInstance>;
onFocused: Event<ITerminalInstance>;
onProcessIdReady: Event<ITerminalInstance>;
onRequestExtHostProcess: Event<ITerminalInstance>;
onDimensionsChanged: Event<void>;
onMaximumDimensionsChanged: Event<void>;
onFocus: Event<ITerminalInstance>;
/**
* Attach a listener to the raw data stream coming from the pty, including ANSI escape
* sequences.
*/
onData: Event<string>;
/**
* Attach a listener to listen for new lines added to this terminal instance.
*
* @param listener The listener function which takes new line strings added to the terminal,
* excluding ANSI escape sequences. The line event will fire when an LF character is added to
* the terminal (ie. the line is not wrapped). Note that this means that the line data will
* not fire for the last line, until either the line is ended with a LF character of the process
* is exited. The lineData string will contain the fully wrapped line, not containing any LF/CR
* characters.
*/
onLineData: Event<string>;
/**
* Attach a listener that fires when the terminal's pty process exits. The number in the event
* is the processes' exit code, an exit code of null means the process was killed as a result of
* the ITerminalInstance being disposed.
*/
onExit: Event<number | undefined>;
/**
* Attach a listener to intercept and handle link clicks in the terminal.
*/
onBeforeHandleLink: Event<ITerminalBeforeHandleLinkEvent>;
readonly exitCode: number | undefined;
processReady: Promise<void>;
/**
* The title of the terminal. This is either title or the process currently running or an
* explicit name given to the terminal instance through the extension API.
*/
readonly title: string;
/**
* The shell type of the terminal.
*/
readonly shellType: TerminalShellType;
/**
* The focus state of the terminal before exiting.
*/
readonly hadFocusOnExit: boolean;
/**
* False when the title is set by an API or the user. We check this to make sure we
* do not override the title when the process title changes in the terminal.
*/
isTitleSetByProcess: boolean;
/**
* The shell launch config used to launch the shell.
*/
readonly shellLaunchConfig: IShellLaunchConfig;
/**
* Whether to disable layout for the terminal. This is useful when the size of the terminal is
* being manipulating (e.g. adding a split pane) and we want the terminal to ignore particular
* resize events.
*/
disableLayout: boolean;
/**
* An object that tracks when commands are run and enables navigating and selecting between
* them.
*/
readonly commandTracker: ICommandTracker | undefined;
readonly navigationMode: INavigationMode | undefined;
/**
* Dispose the terminal instance, removing it from the panel/service and freeing up resources.
*
* @param immediate Whether the kill should be immediate or not. Immediate should only be used
* when VS Code is shutting down or in cases where the terminal dispose was user initiated.
* The immediate===false exists to cover an edge case where the final output of the terminal can
* get cut off. If immediate kill any terminal processes immediately.
*/
dispose(immediate?: boolean): void;
/**
* Forces the terminal to redraw its viewport.
*/
forceRedraw(): void;
/**
* Registers a link matcher, allowing custom link patterns to be matched and handled.
* @param regex The regular expression the search for, specifically this searches the
* textContent of the rows. You will want to use \s to match a space ' ' character for example.
* @param handler The callback when the link is called.
* @param matchIndex The index of the link from the regex.match(html) call. This defaults to 0
* (for regular expressions without capture groups).
* @param validationCallback A callback which can be used to validate the link after it has been
* added to the DOM.
* @return The ID of the new matcher, this can be used to deregister.
*/
registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, callback: (isValid: boolean) => void) => void): number;
/**
* Deregisters a link matcher if it has been registered.
* @param matcherId The link matcher's ID (returned after register)
* @return Whether a link matcher was found and deregistered.
*/
deregisterLinkMatcher(matcherId: number): void;
/**
* Check if anything is selected in terminal.
*/
hasSelection(): boolean;
/**
* Copies the terminal selection to the clipboard.
*/
copySelection(): Promise<void>;
/**
* Current selection in the terminal.
*/
readonly selection: string | undefined;
/**
* Clear current selection.
*/
clearSelection(): void;
/**
* Select all text in the terminal.
*/
selectAll(): void;
/**
* Find the next instance of the term
*/
findNext(term: string, searchOptions: ISearchOptions): boolean;
/**
* Find the previous instance of the term
*/
findPrevious(term: string, searchOptions: ISearchOptions): boolean;
/**
* Notifies the terminal that the find widget's focus state has been changed.
*/
notifyFindWidgetFocusChanged(isFocused: boolean): void;
/**
* Focuses the terminal instance if it's able to (xterm.js instance exists).
*
* @param focus Force focus even if there is a selection.
*/
focus(force?: boolean): void;
/**
* Focuses the terminal instance when it's ready (the xterm.js instance is created). Use this
* when the terminal is being shown.
*
* @param focus Force focus even if there is a selection.
*/
focusWhenReady(force?: boolean): Promise<void>;
/**
* Focuses and pastes the contents of the clipboard into the terminal instance.
*/
paste(): Promise<void>;
/**
* Send text to the terminal instance. The text is written to the stdin of the underlying pty
* process (shell) of the terminal instance.
*
* @param text The text to send.
* @param addNewLine Whether to add a new line to the text being sent, this is normally
* required to run a command in the terminal. The character(s) added are \n or \r\n
* depending on the platform. This defaults to `true`.
*/
sendText(text: string, addNewLine: boolean): void;
/** Scroll the terminal buffer down 1 line. */
scrollDownLine(): void;
/** Scroll the terminal buffer down 1 page. */
scrollDownPage(): void;
/** Scroll the terminal buffer to the bottom. */
scrollToBottom(): void;
/** Scroll the terminal buffer up 1 line. */
scrollUpLine(): void;
/** Scroll the terminal buffer up 1 page. */
scrollUpPage(): void;
/** Scroll the terminal buffer to the top. */
scrollToTop(): void;
/**
* Clears the terminal buffer, leaving only the prompt line.
*/
clear(): void;
/**
* Attaches the terminal instance to an element on the DOM, before this is called the terminal
* instance process may run in the background but cannot be displayed on the UI.
*
* @param container The element to attach the terminal instance to.
*/
attachToElement(container: HTMLElement): void;
/**
* Configure the dimensions of the terminal instance.
*
* @param dimension The dimensions of the container.
*/
layout(dimension: { width: number, height: number }): void;
/**
* Sets whether the terminal instance's element is visible in the DOM.
*
* @param visible Whether the element is visible.
*/
setVisible(visible: boolean): void;
/**
* Immediately kills the terminal's current pty process and launches a new one to replace it.
*
* @param shell The new launch configuration.
*/
reuseTerminal(shell: IShellLaunchConfig): void;
/**
* Sets the title of the terminal instance.
*/
setTitle(title: string, eventSource: TitleEventSource): void;
/**
* Sets the shell type of the terminal instance.
*/
setShellType(shellType: TerminalShellType): void;
waitForTitle(): Promise<string>;
setDimensions(dimensions: ITerminalDimensions): void;
addDisposable(disposable: IDisposable): void;
toggleEscapeSequenceLogging(): void;
getInitialCwd(): Promise<string>;
getCwd(): Promise<string>;
}
| src/vs/workbench/contrib/terminal/browser/terminal.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0009973105043172836,
0.0001911720319185406,
0.00016096551553346217,
0.0001687743642833084,
0.0001202263665618375
] |
{
"id": 10,
"code_window": [
"\t\t\t\t\t);\n",
"\n",
"\t\t\t\t\tviewCell.editorHeight = realContentHeight;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell) {\n",
"\t\t\t\t\ttemplateData.editor?.focus();\n",
"\t\t\t\t}\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts",
"type": "replace",
"edit_start_line_idx": 83
} | /*---------------------------------------------------------------------------------------------
* 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 labels from 'vs/base/common/labels';
import * as platform from 'vs/base/common/platform';
suite('Labels', () => {
test('shorten - windows', () => {
if (!platform.isWindows) {
assert.ok(true);
return;
}
// nothing to shorten
assert.deepEqual(labels.shorten(['a']), ['a']);
assert.deepEqual(labels.shorten(['a', 'b']), ['a', 'b']);
assert.deepEqual(labels.shorten(['a', 'b', 'c']), ['a', 'b', 'c']);
// completely different paths
assert.deepEqual(labels.shorten(['a\\b', 'c\\d', 'e\\f']), ['…\\b', '…\\d', '…\\f']);
// same beginning
assert.deepEqual(labels.shorten(['a', 'a\\b']), ['a', '…\\b']);
assert.deepEqual(labels.shorten(['a\\b', 'a\\b\\c']), ['…\\b', '…\\c']);
assert.deepEqual(labels.shorten(['a', 'a\\b', 'a\\b\\c']), ['a', '…\\b', '…\\c']);
assert.deepEqual(labels.shorten(['x:\\a\\b', 'x:\\a\\c']), ['x:\\…\\b', 'x:\\…\\c']);
assert.deepEqual(labels.shorten(['\\\\a\\b', '\\\\a\\c']), ['\\\\a\\b', '\\\\a\\c']);
// same ending
assert.deepEqual(labels.shorten(['a', 'b\\a']), ['a', 'b\\…']);
assert.deepEqual(labels.shorten(['a\\b\\c', 'd\\b\\c']), ['a\\…', 'd\\…']);
assert.deepEqual(labels.shorten(['a\\b\\c\\d', 'f\\b\\c\\d']), ['a\\…', 'f\\…']);
assert.deepEqual(labels.shorten(['d\\e\\a\\b\\c', 'd\\b\\c']), ['…\\a\\…', 'd\\b\\…']);
assert.deepEqual(labels.shorten(['a\\b\\c\\d', 'a\\f\\b\\c\\d']), ['a\\b\\…', '…\\f\\…']);
assert.deepEqual(labels.shorten(['a\\b\\a', 'b\\b\\a']), ['a\\b\\…', 'b\\b\\…']);
assert.deepEqual(labels.shorten(['d\\f\\a\\b\\c', 'h\\d\\b\\c']), ['…\\a\\…', 'h\\…']);
assert.deepEqual(labels.shorten(['a\\b\\c', 'x:\\0\\a\\b\\c']), ['a\\b\\c', 'x:\\0\\…']);
assert.deepEqual(labels.shorten(['x:\\a\\b\\c', 'x:\\0\\a\\b\\c']), ['x:\\a\\…', 'x:\\0\\…']);
assert.deepEqual(labels.shorten(['x:\\a\\b', 'y:\\a\\b']), ['x:\\…', 'y:\\…']);
assert.deepEqual(labels.shorten(['x:\\a', 'x:\\c']), ['x:\\a', 'x:\\c']);
assert.deepEqual(labels.shorten(['x:\\a\\b', 'y:\\x\\a\\b']), ['x:\\…', 'y:\\…']);
assert.deepEqual(labels.shorten(['\\\\x\\b', '\\\\y\\b']), ['\\\\x\\…', '\\\\y\\…']);
assert.deepEqual(labels.shorten(['\\\\x\\a', '\\\\x\\b']), ['\\\\x\\a', '\\\\x\\b']);
// same name ending
assert.deepEqual(labels.shorten(['a\\b', 'a\\c', 'a\\e-b']), ['…\\b', '…\\c', '…\\e-b']);
// same in the middle
assert.deepEqual(labels.shorten(['a\\b\\c', 'd\\b\\e']), ['…\\c', '…\\e']);
// case-sensetive
assert.deepEqual(labels.shorten(['a\\b\\c', 'd\\b\\C']), ['…\\c', '…\\C']);
// empty or null
assert.deepEqual(labels.shorten(['', null!]), ['.\\', null]);
assert.deepEqual(labels.shorten(['a', 'a\\b', 'a\\b\\c', 'd\\b\\c', 'd\\b']), ['a', 'a\\b', 'a\\b\\c', 'd\\b\\c', 'd\\b']);
assert.deepEqual(labels.shorten(['a', 'a\\b', 'b']), ['a', 'a\\b', 'b']);
assert.deepEqual(labels.shorten(['', 'a', 'b', 'b\\c', 'a\\c']), ['.\\', 'a', 'b', 'b\\c', 'a\\c']);
assert.deepEqual(labels.shorten(['src\\vs\\workbench\\parts\\execution\\electron-browser', 'src\\vs\\workbench\\parts\\execution\\electron-browser\\something', 'src\\vs\\workbench\\parts\\terminal\\electron-browser']), ['…\\execution\\electron-browser', '…\\something', '…\\terminal\\…']);
});
test('shorten - not windows', () => {
if (platform.isWindows) {
assert.ok(true);
return;
}
// nothing to shorten
assert.deepEqual(labels.shorten(['a']), ['a']);
assert.deepEqual(labels.shorten(['a', 'b']), ['a', 'b']);
assert.deepEqual(labels.shorten(['a', 'b', 'c']), ['a', 'b', 'c']);
// completely different paths
assert.deepEqual(labels.shorten(['a/b', 'c/d', 'e/f']), ['…/b', '…/d', '…/f']);
// same beginning
assert.deepEqual(labels.shorten(['a', 'a/b']), ['a', '…/b']);
assert.deepEqual(labels.shorten(['a/b', 'a/b/c']), ['…/b', '…/c']);
assert.deepEqual(labels.shorten(['a', 'a/b', 'a/b/c']), ['a', '…/b', '…/c']);
assert.deepEqual(labels.shorten(['/a/b', '/a/c']), ['/a/b', '/a/c']);
// same ending
assert.deepEqual(labels.shorten(['a', 'b/a']), ['a', 'b/…']);
assert.deepEqual(labels.shorten(['a/b/c', 'd/b/c']), ['a/…', 'd/…']);
assert.deepEqual(labels.shorten(['a/b/c/d', 'f/b/c/d']), ['a/…', 'f/…']);
assert.deepEqual(labels.shorten(['d/e/a/b/c', 'd/b/c']), ['…/a/…', 'd/b/…']);
assert.deepEqual(labels.shorten(['a/b/c/d', 'a/f/b/c/d']), ['a/b/…', '…/f/…']);
assert.deepEqual(labels.shorten(['a/b/a', 'b/b/a']), ['a/b/…', 'b/b/…']);
assert.deepEqual(labels.shorten(['d/f/a/b/c', 'h/d/b/c']), ['…/a/…', 'h/…']);
assert.deepEqual(labels.shorten(['/x/b', '/y/b']), ['/x/…', '/y/…']);
// same name ending
assert.deepEqual(labels.shorten(['a/b', 'a/c', 'a/e-b']), ['…/b', '…/c', '…/e-b']);
// same in the middle
assert.deepEqual(labels.shorten(['a/b/c', 'd/b/e']), ['…/c', '…/e']);
// case-sensitive
assert.deepEqual(labels.shorten(['a/b/c', 'd/b/C']), ['…/c', '…/C']);
// empty or null
assert.deepEqual(labels.shorten(['', null!]), ['./', null]);
assert.deepEqual(labels.shorten(['a', 'a/b', 'a/b/c', 'd/b/c', 'd/b']), ['a', 'a/b', 'a/b/c', 'd/b/c', 'd/b']);
assert.deepEqual(labels.shorten(['a', 'a/b', 'b']), ['a', 'a/b', 'b']);
assert.deepEqual(labels.shorten(['', 'a', 'b', 'b/c', 'a/c']), ['./', 'a', 'b', 'b/c', 'a/c']);
});
test('template', () => {
// simple
assert.strictEqual(labels.template('Foo Bar'), 'Foo Bar');
assert.strictEqual(labels.template('Foo${}Bar'), 'FooBar');
assert.strictEqual(labels.template('$FooBar'), '');
assert.strictEqual(labels.template('}FooBar'), '}FooBar');
assert.strictEqual(labels.template('Foo ${one} Bar', { one: 'value' }), 'Foo value Bar');
assert.strictEqual(labels.template('Foo ${one} Bar ${two}', { one: 'value', two: 'other value' }), 'Foo value Bar other value');
// conditional separator
assert.strictEqual(labels.template('Foo${separator}Bar'), 'FooBar');
assert.strictEqual(labels.template('Foo${separator}Bar', { separator: { label: ' - ' } }), 'Foo - Bar');
assert.strictEqual(labels.template('${separator}Foo${separator}Bar', { value: 'something', separator: { label: ' - ' } }), 'Foo - Bar');
assert.strictEqual(labels.template('${value} Foo${separator}Bar', { value: 'something', separator: { label: ' - ' } }), 'something Foo - Bar');
// // real world example (macOS)
let t = '${activeEditorShort}${separator}${rootName}';
assert.strictEqual(labels.template(t, { activeEditorShort: '', rootName: '', separator: { label: ' - ' } }), '');
assert.strictEqual(labels.template(t, { activeEditorShort: '', rootName: 'root', separator: { label: ' - ' } }), 'root');
assert.strictEqual(labels.template(t, { activeEditorShort: 'markdown.txt', rootName: 'root', separator: { label: ' - ' } }), 'markdown.txt - root');
// // real world example (other)
t = '${dirty}${activeEditorShort}${separator}${rootName}${separator}${appName}';
assert.strictEqual(labels.template(t, { dirty: '', activeEditorShort: '', rootName: '', appName: '', separator: { label: ' - ' } }), '');
assert.strictEqual(labels.template(t, { dirty: '', activeEditorShort: '', rootName: '', appName: 'Visual Studio Code', separator: { label: ' - ' } }), 'Visual Studio Code');
assert.strictEqual(labels.template(t, { dirty: '', activeEditorShort: 'Untitled-1', rootName: '', appName: 'Visual Studio Code', separator: { label: ' - ' } }), 'Untitled-1 - Visual Studio Code');
assert.strictEqual(labels.template(t, { dirty: '', activeEditorShort: '', rootName: 'monaco', appName: 'Visual Studio Code', separator: { label: ' - ' } }), 'monaco - Visual Studio Code');
assert.strictEqual(labels.template(t, { dirty: '', activeEditorShort: 'somefile.txt', rootName: 'monaco', appName: 'Visual Studio Code', separator: { label: ' - ' } }), 'somefile.txt - monaco - Visual Studio Code');
assert.strictEqual(labels.template(t, { dirty: '* ', activeEditorShort: 'somefile.txt', rootName: 'monaco', appName: 'Visual Studio Code', separator: { label: ' - ' } }), '* somefile.txt - monaco - Visual Studio Code');
});
test('getBaseLabel - unix', () => {
if (platform.isWindows) {
assert.ok(true);
return;
}
assert.equal(labels.getBaseLabel('/some/folder/file.txt'), 'file.txt');
assert.equal(labels.getBaseLabel('/some/folder'), 'folder');
assert.equal(labels.getBaseLabel('/'), '/');
});
test('getBaseLabel - windows', () => {
if (!platform.isWindows) {
assert.ok(true);
return;
}
assert.equal(labels.getBaseLabel('c:'), 'C:');
assert.equal(labels.getBaseLabel('c:\\'), 'C:');
assert.equal(labels.getBaseLabel('c:\\some\\folder\\file.txt'), 'file.txt');
assert.equal(labels.getBaseLabel('c:\\some\\folder'), 'folder');
});
test('mnemonicButtonLabel', () => {
assert.equal(labels.mnemonicButtonLabel('Hello World'), 'Hello World');
assert.equal(labels.mnemonicButtonLabel(''), '');
if (platform.isWindows) {
assert.equal(labels.mnemonicButtonLabel('Hello & World'), 'Hello && World');
assert.equal(labels.mnemonicButtonLabel('Do &¬ Save & Continue'), 'Do ¬ Save && Continue');
} else if (platform.isMacintosh) {
assert.equal(labels.mnemonicButtonLabel('Hello & World'), 'Hello & World');
assert.equal(labels.mnemonicButtonLabel('Do &¬ Save & Continue'), 'Do not Save & Continue');
} else {
assert.equal(labels.mnemonicButtonLabel('Hello & World'), 'Hello & World');
assert.equal(labels.mnemonicButtonLabel('Do &¬ Save & Continue'), 'Do _not Save & Continue');
}
});
}); | src/vs/base/test/common/labels.test.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0001797756558516994,
0.0001744396286085248,
0.00017121853306889534,
0.0001735275873215869,
0.0000022837573396827793
] |
{
"id": 10,
"code_window": [
"\t\t\t\t\t);\n",
"\n",
"\t\t\t\t\tviewCell.editorHeight = realContentHeight;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell) {\n",
"\t\t\t\t\ttemplateData.editor?.focus();\n",
"\t\t\t\t}\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts",
"type": "replace",
"edit_start_line_idx": 83
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { OperatingSystem } from 'vs/base/common/platform';
import { illegalArgument } from 'vs/base/common/errors';
/**
* Virtual Key Codes, the value does not hold any inherent meaning.
* Inspired somewhat from https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
* But these are "more general", as they should work across browsers & OS`s.
*/
export const enum KeyCode {
/**
* Placed first to cover the 0 value of the enum.
*/
Unknown = 0,
Backspace = 1,
Tab = 2,
Enter = 3,
Shift = 4,
Ctrl = 5,
Alt = 6,
PauseBreak = 7,
CapsLock = 8,
Escape = 9,
Space = 10,
PageUp = 11,
PageDown = 12,
End = 13,
Home = 14,
LeftArrow = 15,
UpArrow = 16,
RightArrow = 17,
DownArrow = 18,
Insert = 19,
Delete = 20,
KEY_0 = 21,
KEY_1 = 22,
KEY_2 = 23,
KEY_3 = 24,
KEY_4 = 25,
KEY_5 = 26,
KEY_6 = 27,
KEY_7 = 28,
KEY_8 = 29,
KEY_9 = 30,
KEY_A = 31,
KEY_B = 32,
KEY_C = 33,
KEY_D = 34,
KEY_E = 35,
KEY_F = 36,
KEY_G = 37,
KEY_H = 38,
KEY_I = 39,
KEY_J = 40,
KEY_K = 41,
KEY_L = 42,
KEY_M = 43,
KEY_N = 44,
KEY_O = 45,
KEY_P = 46,
KEY_Q = 47,
KEY_R = 48,
KEY_S = 49,
KEY_T = 50,
KEY_U = 51,
KEY_V = 52,
KEY_W = 53,
KEY_X = 54,
KEY_Y = 55,
KEY_Z = 56,
Meta = 57,
ContextMenu = 58,
F1 = 59,
F2 = 60,
F3 = 61,
F4 = 62,
F5 = 63,
F6 = 64,
F7 = 65,
F8 = 66,
F9 = 67,
F10 = 68,
F11 = 69,
F12 = 70,
F13 = 71,
F14 = 72,
F15 = 73,
F16 = 74,
F17 = 75,
F18 = 76,
F19 = 77,
NumLock = 78,
ScrollLock = 79,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ';:' key
*/
US_SEMICOLON = 80,
/**
* For any country/region, the '+' key
* For the US standard keyboard, the '=+' key
*/
US_EQUAL = 81,
/**
* For any country/region, the ',' key
* For the US standard keyboard, the ',<' key
*/
US_COMMA = 82,
/**
* For any country/region, the '-' key
* For the US standard keyboard, the '-_' key
*/
US_MINUS = 83,
/**
* For any country/region, the '.' key
* For the US standard keyboard, the '.>' key
*/
US_DOT = 84,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '/?' key
*/
US_SLASH = 85,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '`~' key
*/
US_BACKTICK = 86,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '[{' key
*/
US_OPEN_SQUARE_BRACKET = 87,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '\|' key
*/
US_BACKSLASH = 88,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ']}' key
*/
US_CLOSE_SQUARE_BRACKET = 89,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ''"' key
*/
US_QUOTE = 90,
/**
* Used for miscellaneous characters; it can vary by keyboard.
*/
OEM_8 = 91,
/**
* Either the angle bracket key or the backslash key on the RT 102-key keyboard.
*/
OEM_102 = 92,
NUMPAD_0 = 93, // VK_NUMPAD0, 0x60, Numeric keypad 0 key
NUMPAD_1 = 94, // VK_NUMPAD1, 0x61, Numeric keypad 1 key
NUMPAD_2 = 95, // VK_NUMPAD2, 0x62, Numeric keypad 2 key
NUMPAD_3 = 96, // VK_NUMPAD3, 0x63, Numeric keypad 3 key
NUMPAD_4 = 97, // VK_NUMPAD4, 0x64, Numeric keypad 4 key
NUMPAD_5 = 98, // VK_NUMPAD5, 0x65, Numeric keypad 5 key
NUMPAD_6 = 99, // VK_NUMPAD6, 0x66, Numeric keypad 6 key
NUMPAD_7 = 100, // VK_NUMPAD7, 0x67, Numeric keypad 7 key
NUMPAD_8 = 101, // VK_NUMPAD8, 0x68, Numeric keypad 8 key
NUMPAD_9 = 102, // VK_NUMPAD9, 0x69, Numeric keypad 9 key
NUMPAD_MULTIPLY = 103, // VK_MULTIPLY, 0x6A, Multiply key
NUMPAD_ADD = 104, // VK_ADD, 0x6B, Add key
NUMPAD_SEPARATOR = 105, // VK_SEPARATOR, 0x6C, Separator key
NUMPAD_SUBTRACT = 106, // VK_SUBTRACT, 0x6D, Subtract key
NUMPAD_DECIMAL = 107, // VK_DECIMAL, 0x6E, Decimal key
NUMPAD_DIVIDE = 108, // VK_DIVIDE, 0x6F,
/**
* Cover all key codes when IME is processing input.
*/
KEY_IN_COMPOSITION = 109,
ABNT_C1 = 110, // Brazilian (ABNT) Keyboard
ABNT_C2 = 111, // Brazilian (ABNT) Keyboard
/**
* Placed last to cover the length of the enum.
* Please do not depend on this value!
*/
MAX_VALUE
}
class KeyCodeStrMap {
private _keyCodeToStr: string[];
private _strToKeyCode: { [str: string]: KeyCode; };
constructor() {
this._keyCodeToStr = [];
this._strToKeyCode = Object.create(null);
}
define(keyCode: KeyCode, str: string): void {
this._keyCodeToStr[keyCode] = str;
this._strToKeyCode[str.toLowerCase()] = keyCode;
}
keyCodeToStr(keyCode: KeyCode): string {
return this._keyCodeToStr[keyCode];
}
strToKeyCode(str: string): KeyCode {
return this._strToKeyCode[str.toLowerCase()] || KeyCode.Unknown;
}
}
const uiMap = new KeyCodeStrMap();
const userSettingsUSMap = new KeyCodeStrMap();
const userSettingsGeneralMap = new KeyCodeStrMap();
(function () {
function define(keyCode: KeyCode, uiLabel: string, usUserSettingsLabel: string = uiLabel, generalUserSettingsLabel: string = usUserSettingsLabel): void {
uiMap.define(keyCode, uiLabel);
userSettingsUSMap.define(keyCode, usUserSettingsLabel);
userSettingsGeneralMap.define(keyCode, generalUserSettingsLabel);
}
define(KeyCode.Unknown, 'unknown');
define(KeyCode.Backspace, 'Backspace');
define(KeyCode.Tab, 'Tab');
define(KeyCode.Enter, 'Enter');
define(KeyCode.Shift, 'Shift');
define(KeyCode.Ctrl, 'Ctrl');
define(KeyCode.Alt, 'Alt');
define(KeyCode.PauseBreak, 'PauseBreak');
define(KeyCode.CapsLock, 'CapsLock');
define(KeyCode.Escape, 'Escape');
define(KeyCode.Space, 'Space');
define(KeyCode.PageUp, 'PageUp');
define(KeyCode.PageDown, 'PageDown');
define(KeyCode.End, 'End');
define(KeyCode.Home, 'Home');
define(KeyCode.LeftArrow, 'LeftArrow', 'Left');
define(KeyCode.UpArrow, 'UpArrow', 'Up');
define(KeyCode.RightArrow, 'RightArrow', 'Right');
define(KeyCode.DownArrow, 'DownArrow', 'Down');
define(KeyCode.Insert, 'Insert');
define(KeyCode.Delete, 'Delete');
define(KeyCode.KEY_0, '0');
define(KeyCode.KEY_1, '1');
define(KeyCode.KEY_2, '2');
define(KeyCode.KEY_3, '3');
define(KeyCode.KEY_4, '4');
define(KeyCode.KEY_5, '5');
define(KeyCode.KEY_6, '6');
define(KeyCode.KEY_7, '7');
define(KeyCode.KEY_8, '8');
define(KeyCode.KEY_9, '9');
define(KeyCode.KEY_A, 'A');
define(KeyCode.KEY_B, 'B');
define(KeyCode.KEY_C, 'C');
define(KeyCode.KEY_D, 'D');
define(KeyCode.KEY_E, 'E');
define(KeyCode.KEY_F, 'F');
define(KeyCode.KEY_G, 'G');
define(KeyCode.KEY_H, 'H');
define(KeyCode.KEY_I, 'I');
define(KeyCode.KEY_J, 'J');
define(KeyCode.KEY_K, 'K');
define(KeyCode.KEY_L, 'L');
define(KeyCode.KEY_M, 'M');
define(KeyCode.KEY_N, 'N');
define(KeyCode.KEY_O, 'O');
define(KeyCode.KEY_P, 'P');
define(KeyCode.KEY_Q, 'Q');
define(KeyCode.KEY_R, 'R');
define(KeyCode.KEY_S, 'S');
define(KeyCode.KEY_T, 'T');
define(KeyCode.KEY_U, 'U');
define(KeyCode.KEY_V, 'V');
define(KeyCode.KEY_W, 'W');
define(KeyCode.KEY_X, 'X');
define(KeyCode.KEY_Y, 'Y');
define(KeyCode.KEY_Z, 'Z');
define(KeyCode.Meta, 'Meta');
define(KeyCode.ContextMenu, 'ContextMenu');
define(KeyCode.F1, 'F1');
define(KeyCode.F2, 'F2');
define(KeyCode.F3, 'F3');
define(KeyCode.F4, 'F4');
define(KeyCode.F5, 'F5');
define(KeyCode.F6, 'F6');
define(KeyCode.F7, 'F7');
define(KeyCode.F8, 'F8');
define(KeyCode.F9, 'F9');
define(KeyCode.F10, 'F10');
define(KeyCode.F11, 'F11');
define(KeyCode.F12, 'F12');
define(KeyCode.F13, 'F13');
define(KeyCode.F14, 'F14');
define(KeyCode.F15, 'F15');
define(KeyCode.F16, 'F16');
define(KeyCode.F17, 'F17');
define(KeyCode.F18, 'F18');
define(KeyCode.F19, 'F19');
define(KeyCode.NumLock, 'NumLock');
define(KeyCode.ScrollLock, 'ScrollLock');
define(KeyCode.US_SEMICOLON, ';', ';', 'OEM_1');
define(KeyCode.US_EQUAL, '=', '=', 'OEM_PLUS');
define(KeyCode.US_COMMA, ',', ',', 'OEM_COMMA');
define(KeyCode.US_MINUS, '-', '-', 'OEM_MINUS');
define(KeyCode.US_DOT, '.', '.', 'OEM_PERIOD');
define(KeyCode.US_SLASH, '/', '/', 'OEM_2');
define(KeyCode.US_BACKTICK, '`', '`', 'OEM_3');
define(KeyCode.ABNT_C1, 'ABNT_C1');
define(KeyCode.ABNT_C2, 'ABNT_C2');
define(KeyCode.US_OPEN_SQUARE_BRACKET, '[', '[', 'OEM_4');
define(KeyCode.US_BACKSLASH, '\\', '\\', 'OEM_5');
define(KeyCode.US_CLOSE_SQUARE_BRACKET, ']', ']', 'OEM_6');
define(KeyCode.US_QUOTE, '\'', '\'', 'OEM_7');
define(KeyCode.OEM_8, 'OEM_8');
define(KeyCode.OEM_102, 'OEM_102');
define(KeyCode.NUMPAD_0, 'NumPad0');
define(KeyCode.NUMPAD_1, 'NumPad1');
define(KeyCode.NUMPAD_2, 'NumPad2');
define(KeyCode.NUMPAD_3, 'NumPad3');
define(KeyCode.NUMPAD_4, 'NumPad4');
define(KeyCode.NUMPAD_5, 'NumPad5');
define(KeyCode.NUMPAD_6, 'NumPad6');
define(KeyCode.NUMPAD_7, 'NumPad7');
define(KeyCode.NUMPAD_8, 'NumPad8');
define(KeyCode.NUMPAD_9, 'NumPad9');
define(KeyCode.NUMPAD_MULTIPLY, 'NumPad_Multiply');
define(KeyCode.NUMPAD_ADD, 'NumPad_Add');
define(KeyCode.NUMPAD_SEPARATOR, 'NumPad_Separator');
define(KeyCode.NUMPAD_SUBTRACT, 'NumPad_Subtract');
define(KeyCode.NUMPAD_DECIMAL, 'NumPad_Decimal');
define(KeyCode.NUMPAD_DIVIDE, 'NumPad_Divide');
})();
export namespace KeyCodeUtils {
export function toString(keyCode: KeyCode): string {
return uiMap.keyCodeToStr(keyCode);
}
export function fromString(key: string): KeyCode {
return uiMap.strToKeyCode(key);
}
export function toUserSettingsUS(keyCode: KeyCode): string {
return userSettingsUSMap.keyCodeToStr(keyCode);
}
export function toUserSettingsGeneral(keyCode: KeyCode): string {
return userSettingsGeneralMap.keyCodeToStr(keyCode);
}
export function fromUserSettings(key: string): KeyCode {
return userSettingsUSMap.strToKeyCode(key) || userSettingsGeneralMap.strToKeyCode(key);
}
}
/**
* Binary encoding strategy:
* ```
* 1111 11
* 5432 1098 7654 3210
* ---- CSAW KKKK KKKK
* C = bit 11 = ctrlCmd flag
* S = bit 10 = shift flag
* A = bit 9 = alt flag
* W = bit 8 = winCtrl flag
* K = bits 0-7 = key code
* ```
*/
const enum BinaryKeybindingsMask {
CtrlCmd = (1 << 11) >>> 0,
Shift = (1 << 10) >>> 0,
Alt = (1 << 9) >>> 0,
WinCtrl = (1 << 8) >>> 0,
KeyCode = 0x000000FF
}
export const enum KeyMod {
CtrlCmd = (1 << 11) >>> 0,
Shift = (1 << 10) >>> 0,
Alt = (1 << 9) >>> 0,
WinCtrl = (1 << 8) >>> 0,
}
export function KeyChord(firstPart: number, secondPart: number): number {
const chordPart = ((secondPart & 0x0000FFFF) << 16) >>> 0;
return (firstPart | chordPart) >>> 0;
}
export function createKeybinding(keybinding: number, OS: OperatingSystem): Keybinding | null {
if (keybinding === 0) {
return null;
}
const firstPart = (keybinding & 0x0000FFFF) >>> 0;
const chordPart = (keybinding & 0xFFFF0000) >>> 16;
if (chordPart !== 0) {
return new ChordKeybinding([
createSimpleKeybinding(firstPart, OS),
createSimpleKeybinding(chordPart, OS)
]);
}
return new ChordKeybinding([createSimpleKeybinding(firstPart, OS)]);
}
export function createSimpleKeybinding(keybinding: number, OS: OperatingSystem): SimpleKeybinding {
const ctrlCmd = (keybinding & BinaryKeybindingsMask.CtrlCmd ? true : false);
const winCtrl = (keybinding & BinaryKeybindingsMask.WinCtrl ? true : false);
const ctrlKey = (OS === OperatingSystem.Macintosh ? winCtrl : ctrlCmd);
const shiftKey = (keybinding & BinaryKeybindingsMask.Shift ? true : false);
const altKey = (keybinding & BinaryKeybindingsMask.Alt ? true : false);
const metaKey = (OS === OperatingSystem.Macintosh ? ctrlCmd : winCtrl);
const keyCode = (keybinding & BinaryKeybindingsMask.KeyCode);
return new SimpleKeybinding(ctrlKey, shiftKey, altKey, metaKey, keyCode);
}
export class SimpleKeybinding {
public readonly ctrlKey: boolean;
public readonly shiftKey: boolean;
public readonly altKey: boolean;
public readonly metaKey: boolean;
public readonly keyCode: KeyCode;
constructor(ctrlKey: boolean, shiftKey: boolean, altKey: boolean, metaKey: boolean, keyCode: KeyCode) {
this.ctrlKey = ctrlKey;
this.shiftKey = shiftKey;
this.altKey = altKey;
this.metaKey = metaKey;
this.keyCode = keyCode;
}
public equals(other: SimpleKeybinding): boolean {
return (
this.ctrlKey === other.ctrlKey
&& this.shiftKey === other.shiftKey
&& this.altKey === other.altKey
&& this.metaKey === other.metaKey
&& this.keyCode === other.keyCode
);
}
public getHashCode(): string {
const ctrl = this.ctrlKey ? '1' : '0';
const shift = this.shiftKey ? '1' : '0';
const alt = this.altKey ? '1' : '0';
const meta = this.metaKey ? '1' : '0';
return `${ctrl}${shift}${alt}${meta}${this.keyCode}`;
}
public isModifierKey(): boolean {
return (
this.keyCode === KeyCode.Unknown
|| this.keyCode === KeyCode.Ctrl
|| this.keyCode === KeyCode.Meta
|| this.keyCode === KeyCode.Alt
|| this.keyCode === KeyCode.Shift
);
}
public toChord(): ChordKeybinding {
return new ChordKeybinding([this]);
}
/**
* Does this keybinding refer to the key code of a modifier and it also has the modifier flag?
*/
public isDuplicateModifierCase(): boolean {
return (
(this.ctrlKey && this.keyCode === KeyCode.Ctrl)
|| (this.shiftKey && this.keyCode === KeyCode.Shift)
|| (this.altKey && this.keyCode === KeyCode.Alt)
|| (this.metaKey && this.keyCode === KeyCode.Meta)
);
}
}
export class ChordKeybinding {
public readonly parts: SimpleKeybinding[];
constructor(parts: SimpleKeybinding[]) {
if (parts.length === 0) {
throw illegalArgument(`parts`);
}
this.parts = parts;
}
public getHashCode(): string {
let result = '';
for (let i = 0, len = this.parts.length; i < len; i++) {
if (i !== 0) {
result += ';';
}
result += this.parts[i].getHashCode();
}
return result;
}
public equals(other: ChordKeybinding | null): boolean {
if (other === null) {
return false;
}
if (this.parts.length !== other.parts.length) {
return false;
}
for (let i = 0; i < this.parts.length; i++) {
if (!this.parts[i].equals(other.parts[i])) {
return false;
}
}
return true;
}
}
export type Keybinding = ChordKeybinding;
export class ResolvedKeybindingPart {
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly keyLabel: string | null;
readonly keyAriaLabel: string | null;
constructor(ctrlKey: boolean, shiftKey: boolean, altKey: boolean, metaKey: boolean, kbLabel: string | null, kbAriaLabel: string | null) {
this.ctrlKey = ctrlKey;
this.shiftKey = shiftKey;
this.altKey = altKey;
this.metaKey = metaKey;
this.keyLabel = kbLabel;
this.keyAriaLabel = kbAriaLabel;
}
}
/**
* A resolved keybinding. Can be a simple keybinding or a chord keybinding.
*/
export abstract class ResolvedKeybinding {
/**
* This prints the binding in a format suitable for displaying in the UI.
*/
public abstract getLabel(): string | null;
/**
* This prints the binding in a format suitable for ARIA.
*/
public abstract getAriaLabel(): string | null;
/**
* This prints the binding in a format suitable for electron's accelerators.
* See https://github.com/electron/electron/blob/master/docs/api/accelerator.md
*/
public abstract getElectronAccelerator(): string | null;
/**
* This prints the binding in a format suitable for user settings.
*/
public abstract getUserSettingsLabel(): string | null;
/**
* Is the user settings label reflecting the label?
*/
public abstract isWYSIWYG(): boolean;
/**
* Is the binding a chord?
*/
public abstract isChord(): boolean;
/**
* Returns the parts that comprise of the keybinding.
* Simple keybindings return one element.
*/
public abstract getParts(): ResolvedKeybindingPart[];
/**
* Returns the parts that should be used for dispatching.
*/
public abstract getDispatchParts(): (string | null)[];
}
| src/vs/base/common/keyCodes.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00032992742490023375,
0.0001769369700923562,
0.00016460963524878025,
0.00017297682643402368,
0.00002252202102681622
] |
{
"id": 11,
"code_window": [
"\t\t\tthrow new Error('Invalid editor: model is missing');\n",
"\t\t}\n",
"\n",
"\t\tif (this._textEditor === editor) {\n",
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tthis._textEditor = editor;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (this._cursorChangeListener === null) {\n",
"\t\t\t\tthis._cursorChangeListener = this._textEditor.onDidChangeCursorSelection(() => this._onDidChangeCursorSelection.fire());\n",
"\t\t\t\tthis._onDidChangeCursorSelection.fire();\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 293
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as DOM from 'vs/base/browser/dom';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { getResizesObserver } from 'vs/workbench/contrib/notebook/browser/view/renderers/sizeObserver';
import { IOutput, ITransformedDisplayOutputDto, IRenderOutput, CellOutputKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { CellRenderTemplate, INotebookEditor, CellFocusMode } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { raceCancellation } from 'vs/base/common/async';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { INotebookService } from 'vs/workbench/contrib/notebook/browser/notebookService';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';
import { CELL_MARGIN, EDITOR_TOP_PADDING, EDITOR_BOTTOM_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
interface IMimeTypeRenderer extends IQuickPickItem {
index: number;
}
export class CodeCell extends Disposable {
private outputResizeListeners = new Map<IOutput, DisposableStore>();
private outputElements = new Map<IOutput, HTMLElement>();
constructor(
private notebookEditor: INotebookEditor,
private viewCell: CellViewModel,
private templateData: CellRenderTemplate,
@INotebookService private notebookService: INotebookService,
@IQuickInputService private readonly quickInputService: IQuickInputService
) {
super();
let width: number;
const listDimension = notebookEditor.getLayoutInfo();
width = listDimension.width - CELL_MARGIN * 2;
// if (listDimension) {
// } else {
// width = templateData.container.clientWidth - 24 /** for scrollbar and margin right */;
// }
const lineNum = viewCell.lineCount;
const lineHeight = notebookEditor.getLayoutInfo().fontInfo.lineHeight;
const totalHeight = lineNum * lineHeight + EDITOR_TOP_PADDING + EDITOR_BOTTOM_PADDING;
templateData.editor?.layout(
{
width: width,
height: totalHeight
}
);
viewCell.editorHeight = totalHeight;
const cts = new CancellationTokenSource();
this._register({ dispose() { cts.dispose(true); } });
raceCancellation(viewCell.resolveTextModel(), cts.token).then(model => {
if (model && templateData.editor) {
templateData.editor.setModel(model);
viewCell.attachTextEditor(templateData.editor);
if (notebookEditor.getActiveCell() === viewCell) {
templateData.editor?.focus();
}
let realContentHeight = templateData.editor?.getContentHeight();
let width: number;
const listDimension = notebookEditor.getLayoutInfo();
width = listDimension.width - CELL_MARGIN * 2;
// if (listDimension) {
// } else {
// width = templateData.container.clientWidth - 24 /** for scrollbar and margin right */;
// }
if (realContentHeight !== undefined && realContentHeight !== totalHeight) {
templateData.editor?.layout(
{
width: width,
height: realContentHeight
}
);
viewCell.editorHeight = realContentHeight;
}
if (this.notebookEditor.getActiveCell() === this.viewCell) {
templateData.editor?.focus();
}
}
});
this._register(viewCell.onDidChangeFocusMode(() => {
if (viewCell.focusMode === CellFocusMode.Editor) {
templateData.editor?.focus();
}
}));
let cellWidthResizeObserver = getResizesObserver(templateData.cellContainer, {
width: width,
height: totalHeight
}, () => {
let newWidth = cellWidthResizeObserver.getWidth();
let realContentHeight = templateData.editor!.getContentHeight();
templateData.editor?.layout(
{
width: newWidth,
height: realContentHeight
}
);
viewCell.editorHeight = realContentHeight;
});
cellWidthResizeObserver.startObserving();
this._register(cellWidthResizeObserver);
this._register(templateData.editor!.onDidContentSizeChange((e) => {
if (e.contentHeightChanged) {
if (this.viewCell.editorHeight !== e.contentHeight) {
let viewLayout = templateData.editor!.getLayoutInfo();
templateData.editor?.layout(
{
width: viewLayout.width,
height: e.contentHeight
}
);
this.viewCell.editorHeight = e.contentHeight;
notebookEditor.layoutNotebookCell(this.viewCell, viewCell.getCellTotalHeight());
}
}
}));
this._register(templateData.editor!.onDidChangeCursorSelection(() => {
const primarySelection = templateData.editor!.getSelection();
if (primarySelection) {
this.notebookEditor.revealLineInView(viewCell, primarySelection!.positionLineNumber);
}
}));
this._register(viewCell.onDidChangeOutputs((splices) => {
if (!splices.length) {
return;
}
if (this.viewCell.outputs.length) {
this.templateData.outputContainer!.style.display = 'block';
} else {
this.templateData.outputContainer!.style.display = 'none';
}
let reversedSplices = splices.reverse();
reversedSplices.forEach(splice => {
viewCell.spliceOutputHeights(splice[0], splice[1], splice[2].map(_ => 0));
});
let removedKeys: IOutput[] = [];
this.outputElements.forEach((value, key) => {
if (viewCell.outputs.indexOf(key) < 0) {
// already removed
removedKeys.push(key);
// remove element from DOM
this.templateData?.outputContainer?.removeChild(value);
this.notebookEditor.removeInset(key);
}
});
removedKeys.forEach(key => {
// remove element cache
this.outputElements.delete(key);
// remove elment resize listener if there is one
this.outputResizeListeners.delete(key);
});
let prevElement: HTMLElement | undefined = undefined;
this.viewCell.outputs.reverse().forEach(output => {
if (this.outputElements.has(output)) {
// already exist
prevElement = this.outputElements.get(output);
return;
}
// newly added element
let currIndex = this.viewCell.outputs.indexOf(output);
this.renderOutput(output, currIndex, prevElement);
prevElement = this.outputElements.get(output);
});
let editorHeight = templateData.editor!.getContentHeight();
viewCell.editorHeight = editorHeight;
notebookEditor.layoutNotebookCell(viewCell, viewCell.getCellTotalHeight());
}));
if (viewCell.outputs.length > 0) {
this.templateData.outputContainer!.style.display = 'block';
// there are outputs, we need to calcualte their sizes and trigger relayout
// @todo, if there is no resizable output, we should not check their height individually, which hurts the performance
for (let index = 0; index < this.viewCell.outputs.length; index++) {
const currOutput = this.viewCell.outputs[index];
// always add to the end
this.renderOutput(currOutput, index, undefined);
}
viewCell.editorHeight = totalHeight;
this.notebookEditor.layoutNotebookCell(viewCell, viewCell.getCellTotalHeight());
} else {
// noop
this.templateData.outputContainer!.style.display = 'none';
}
}
renderOutput(currOutput: IOutput, index: number, beforeElement?: HTMLElement) {
if (!this.outputResizeListeners.has(currOutput)) {
this.outputResizeListeners.set(currOutput, new DisposableStore());
}
let outputItemDiv = document.createElement('div');
let result: IRenderOutput | undefined = undefined;
if (currOutput.outputKind === CellOutputKind.Rich) {
let transformedDisplayOutput = currOutput as ITransformedDisplayOutputDto;
if (transformedDisplayOutput.orderedMimeTypes.length > 1) {
outputItemDiv.style.position = 'relative';
const mimeTypePicker = DOM.$('.multi-mimetype-output');
DOM.addClasses(mimeTypePicker, 'codicon', 'codicon-list-selection');
outputItemDiv.appendChild(mimeTypePicker);
this.outputResizeListeners.get(currOutput)!.add(DOM.addStandardDisposableListener(mimeTypePicker, 'mousedown', async e => {
e.preventDefault();
e.stopPropagation();
await this.pickActiveMimeTypeRenderer(transformedDisplayOutput);
}));
}
let pickedMimeTypeRenderer = currOutput.orderedMimeTypes[currOutput.pickedMimeTypeIndex];
if (pickedMimeTypeRenderer.isResolved) {
// html
result = this.notebookEditor.getOutputRenderer().render({ outputKind: CellOutputKind.Rich, data: { 'text/html': pickedMimeTypeRenderer.output! } } as any, outputItemDiv, 'text/html');
} else {
result = this.notebookEditor.getOutputRenderer().render(currOutput, outputItemDiv, pickedMimeTypeRenderer.mimeType);
}
} else {
// for text and error, there is no mimetype
result = this.notebookEditor.getOutputRenderer().render(currOutput, outputItemDiv, undefined);
}
if (!result) {
this.viewCell.updateOutputHeight(index, 0);
return;
}
this.outputElements.set(currOutput, outputItemDiv);
if (beforeElement) {
this.templateData.outputContainer?.insertBefore(outputItemDiv, beforeElement);
} else {
this.templateData.outputContainer?.appendChild(outputItemDiv);
}
if (result.shadowContent) {
this.viewCell.selfSizeMonitoring = true;
let editorHeight = this.viewCell.editorHeight;
this.notebookEditor.createInset(this.viewCell, currOutput, result.shadowContent, editorHeight + 8 + this.viewCell.getOutputOffset(index));
} else {
DOM.addClass(outputItemDiv, 'foreground');
}
let hasDynamicHeight = result.hasDynamicHeight;
if (hasDynamicHeight) {
let clientHeight = outputItemDiv.clientHeight;
let listDimension = this.notebookEditor.getLayoutInfo();
let dimension = listDimension ? {
width: listDimension.width - CELL_MARGIN * 2,
height: clientHeight
} : undefined;
const elementSizeObserver = getResizesObserver(outputItemDiv, dimension, () => {
if (this.templateData.outputContainer && document.body.contains(this.templateData.outputContainer!)) {
let height = elementSizeObserver.getHeight() + 8 * 2; // include padding
if (clientHeight === height) {
// console.log(this.viewCell.outputs);
return;
}
const currIndex = this.viewCell.outputs.indexOf(currOutput);
if (currIndex < 0) {
return;
}
this.viewCell.updateOutputHeight(currIndex, height);
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.getCellTotalHeight());
}
});
elementSizeObserver.startObserving();
this.outputResizeListeners.get(currOutput)!.add(elementSizeObserver);
this.viewCell.updateOutputHeight(index, clientHeight);
} else {
if (result.shadowContent) {
// webview
// noop
// let cachedHeight = this.viewCell.getOutputHeight(currOutput);
} else {
// static output
// @TODO, if we stop checking output height, we need to evaluate it later when checking the height of output container
let clientHeight = outputItemDiv.clientHeight;
this.viewCell.updateOutputHeight(index, clientHeight);
}
}
}
generateRendererInfo(renderId: number | undefined): string {
if (renderId === undefined || renderId === -1) {
return 'builtin';
}
let renderInfo = this.notebookService.getRendererInfo(renderId);
if (renderInfo) {
return renderInfo.id.value;
}
return 'builtin';
}
async pickActiveMimeTypeRenderer(output: ITransformedDisplayOutputDto) {
let currIndex = output.pickedMimeTypeIndex;
const items = output.orderedMimeTypes.map((mimeType, index): IMimeTypeRenderer => ({
label: mimeType.mimeType,
id: mimeType.mimeType,
index: index,
picked: index === currIndex,
description: this.generateRendererInfo(mimeType.rendererId) + (index === currIndex
? nls.localize('curruentActiveMimeType', " (Currently Active)")
: ''),
}));
const picker = this.quickInputService.createQuickPick();
picker.items = items;
picker.activeItems = items.filter(item => !!item.picked);
picker.placeholder = nls.localize('promptChooseMimeType.placeHolder', "Select output mimetype to render for current output");
const pick = await new Promise<number | undefined>(resolve => {
picker.onDidAccept(() => {
resolve(picker.selectedItems.length === 1 ? (picker.selectedItems[0] as IMimeTypeRenderer).index : undefined);
picker.dispose();
});
picker.show();
});
if (pick === undefined) {
return;
}
if (pick !== currIndex) {
// user chooses another mimetype
let index = this.viewCell.outputs.indexOf(output);
let nextElement = index + 1 < this.viewCell.outputs.length ? this.outputElements.get(this.viewCell.outputs[index + 1]) : undefined;
this.outputResizeListeners.get(output)?.clear();
let element = this.outputElements.get(output);
if (element) {
this.templateData?.outputContainer?.removeChild(element);
this.notebookEditor.removeInset(output);
}
output.pickedMimeTypeIndex = pick;
this.renderOutput(output, index, nextElement);
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.getCellTotalHeight());
}
}
dispose() {
this.viewCell.detachTextEditor();
this.outputResizeListeners.forEach((value) => {
value.dispose();
});
super.dispose();
}
}
| src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00035107191069982946,
0.00018672850274015218,
0.00016520086501259357,
0.00016903963114600629,
0.00004466441896511242
] |
{
"id": 11,
"code_window": [
"\t\t\tthrow new Error('Invalid editor: model is missing');\n",
"\t\t}\n",
"\n",
"\t\tif (this._textEditor === editor) {\n",
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tthis._textEditor = editor;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (this._cursorChangeListener === null) {\n",
"\t\t\t\tthis._cursorChangeListener = this._textEditor.onDidChangeCursorSelection(() => this._onDidChangeCursorSelection.fire());\n",
"\t\t\t\tthis._onDidChangeCursorSelection.fire();\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 293
} | #ifndef _UCRT
#define _UCRT
#endif | extensions/cpp/test/colorize-fixtures/test-23850.cpp | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017081902478821576,
0.00017081902478821576,
0.00017081902478821576,
0.00017081902478821576,
0
] |
{
"id": 11,
"code_window": [
"\t\t\tthrow new Error('Invalid editor: model is missing');\n",
"\t\t}\n",
"\n",
"\t\tif (this._textEditor === editor) {\n",
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tthis._textEditor = editor;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (this._cursorChangeListener === null) {\n",
"\t\t\t\tthis._cursorChangeListener = this._textEditor.onDidChangeCursorSelection(() => this._onDidChangeCursorSelection.fire());\n",
"\t\t\t\tthis._onDidChangeCursorSelection.fire();\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 293
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { matchesFuzzy, IMatch } from 'vs/base/common/filters';
import { ltrim } from 'vs/base/common/strings';
const codiconStartMarker = '$(';
export interface IParsedCodicons {
readonly text: string;
readonly codiconOffsets?: readonly number[];
}
export function parseCodicons(text: string): IParsedCodicons {
const firstCodiconIndex = text.indexOf(codiconStartMarker);
if (firstCodiconIndex === -1) {
return { text }; // return early if the word does not include an codicon
}
return doParseCodicons(text, firstCodiconIndex);
}
function doParseCodicons(text: string, firstCodiconIndex: number): IParsedCodicons {
const codiconOffsets: number[] = [];
let textWithoutCodicons: string = '';
function appendChars(chars: string) {
if (chars) {
textWithoutCodicons += chars;
for (const _ of chars) {
codiconOffsets.push(codiconsOffset); // make sure to fill in codicon offsets
}
}
}
let currentCodiconStart = -1;
let currentCodiconValue: string = '';
let codiconsOffset = 0;
let char: string;
let nextChar: string;
let offset = firstCodiconIndex;
const length = text.length;
// Append all characters until the first codicon
appendChars(text.substr(0, firstCodiconIndex));
// example: $(file-symlink-file) my cool $(other-codicon) entry
while (offset < length) {
char = text[offset];
nextChar = text[offset + 1];
// beginning of codicon: some value $( <--
if (char === codiconStartMarker[0] && nextChar === codiconStartMarker[1]) {
currentCodiconStart = offset;
// if we had a previous potential codicon value without
// the closing ')', it was actually not an codicon and
// so we have to add it to the actual value
appendChars(currentCodiconValue);
currentCodiconValue = codiconStartMarker;
offset++; // jump over '('
}
// end of codicon: some value $(some-codicon) <--
else if (char === ')' && currentCodiconStart !== -1) {
const currentCodiconLength = offset - currentCodiconStart + 1; // +1 to include the closing ')'
codiconsOffset += currentCodiconLength;
currentCodiconStart = -1;
currentCodiconValue = '';
}
// within codicon
else if (currentCodiconStart !== -1) {
// Make sure this is a real codicon name
if (/^[a-z0-9\-]$/i.test(char)) {
currentCodiconValue += char;
} else {
// This is not a real codicon, treat it as text
appendChars(currentCodiconValue);
currentCodiconStart = -1;
currentCodiconValue = '';
}
}
// any value outside of codicons
else {
appendChars(char);
}
offset++;
}
// if we had a previous potential codicon value without
// the closing ')', it was actually not an codicon and
// so we have to add it to the actual value
appendChars(currentCodiconValue);
return { text: textWithoutCodicons, codiconOffsets };
}
export function matchesFuzzyCodiconAware(query: string, target: IParsedCodicons, enableSeparateSubstringMatching = false): IMatch[] | null {
const { text, codiconOffsets } = target;
// Return early if there are no codicon markers in the word to match against
if (!codiconOffsets || codiconOffsets.length === 0) {
return matchesFuzzy(query, text, enableSeparateSubstringMatching);
}
// Trim the word to match against because it could have leading
// whitespace now if the word started with an codicon
const wordToMatchAgainstWithoutCodiconsTrimmed = ltrim(text, ' ');
const leadingWhitespaceOffset = text.length - wordToMatchAgainstWithoutCodiconsTrimmed.length;
// match on value without codicons
const matches = matchesFuzzy(query, wordToMatchAgainstWithoutCodiconsTrimmed, enableSeparateSubstringMatching);
// Map matches back to offsets with codicons and trimming
if (matches) {
for (const match of matches) {
const codiconOffset = codiconOffsets[match.start + leadingWhitespaceOffset] /* codicon offsets at index */ + leadingWhitespaceOffset /* overall leading whitespace offset */;
match.start += codiconOffset;
match.end += codiconOffset;
}
}
return matches;
}
| src/vs/base/common/codicon.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00019843000336550176,
0.00017261823813896626,
0.0001668421464273706,
0.0001715226680971682,
0.000007509193892474286
] |
{
"id": 11,
"code_window": [
"\t\t\tthrow new Error('Invalid editor: model is missing');\n",
"\t\t}\n",
"\n",
"\t\tif (this._textEditor === editor) {\n",
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tthis._textEditor = editor;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (this._cursorChangeListener === null) {\n",
"\t\t\t\tthis._cursorChangeListener = this._textEditor.onDidChangeCursorSelection(() => this._onDidChangeCursorSelection.fire());\n",
"\t\t\t\tthis._onDidChangeCursorSelection.fire();\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 293
} | /*---------------------------------------------------------------------------------------------
* 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 { OutlineElement, OutlineGroup, OutlineModel } from '../outlineModel';
import { SymbolKind, DocumentSymbol, DocumentSymbolProviderRegistry } from 'vs/editor/common/modes';
import { Range } from 'vs/editor/common/core/range';
import { IMarker, MarkerSeverity } from 'vs/platform/markers/common/markers';
import { createTextModel } from 'vs/editor/test/common/editorTestUtils';
import { URI } from 'vs/base/common/uri';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
suite('OutlineModel', function () {
test('OutlineModel#create, cached', async function () {
let model = createTextModel('foo', undefined, undefined, URI.file('/fome/path.foo'));
let count = 0;
let reg = DocumentSymbolProviderRegistry.register({ pattern: '**/path.foo' }, {
provideDocumentSymbols() {
count += 1;
return [];
}
});
await OutlineModel.create(model, CancellationToken.None);
assert.equal(count, 1);
// cached
await OutlineModel.create(model, CancellationToken.None);
assert.equal(count, 1);
// new version
model.applyEdits([{ text: 'XXX', range: new Range(1, 1, 1, 1) }]);
await OutlineModel.create(model, CancellationToken.None);
assert.equal(count, 2);
reg.dispose();
});
test('OutlineModel#create, cached/cancel', async function () {
let model = createTextModel('foo', undefined, undefined, URI.file('/fome/path.foo'));
let isCancelled = false;
let reg = DocumentSymbolProviderRegistry.register({ pattern: '**/path.foo' }, {
provideDocumentSymbols(d, token) {
return new Promise(resolve => {
token.onCancellationRequested(_ => {
isCancelled = true;
resolve(null);
});
});
}
});
assert.equal(isCancelled, false);
let s1 = new CancellationTokenSource();
OutlineModel.create(model, s1.token);
let s2 = new CancellationTokenSource();
OutlineModel.create(model, s2.token);
s1.cancel();
assert.equal(isCancelled, false);
s2.cancel();
assert.equal(isCancelled, true);
reg.dispose();
});
function fakeSymbolInformation(range: Range, name: string = 'foo'): DocumentSymbol {
return {
name,
detail: 'fake',
kind: SymbolKind.Boolean,
tags: [],
selectionRange: range,
range: range
};
}
function fakeMarker(range: Range): IMarker {
return { ...range, owner: 'ffff', message: 'test', severity: MarkerSeverity.Error, resource: null! };
}
test('OutlineElement - updateMarker', function () {
let e0 = new OutlineElement('foo1', null!, fakeSymbolInformation(new Range(1, 1, 1, 10)));
let e1 = new OutlineElement('foo2', null!, fakeSymbolInformation(new Range(2, 1, 5, 1)));
let e2 = new OutlineElement('foo3', null!, fakeSymbolInformation(new Range(6, 1, 10, 10)));
let group = new OutlineGroup('group', null!, null!, 1);
group.children[e0.id] = e0;
group.children[e1.id] = e1;
group.children[e2.id] = e2;
const data = [fakeMarker(new Range(6, 1, 6, 7)), fakeMarker(new Range(1, 1, 1, 4)), fakeMarker(new Range(10, 2, 14, 1))];
data.sort(Range.compareRangesUsingStarts); // model does this
group.updateMarker(data);
assert.equal(data.length, 0); // all 'stolen'
assert.equal(e0.marker!.count, 1);
assert.equal(e1.marker, undefined);
assert.equal(e2.marker!.count, 2);
group.updateMarker([]);
assert.equal(e0.marker, undefined);
assert.equal(e1.marker, undefined);
assert.equal(e2.marker, undefined);
});
test('OutlineElement - updateMarker, 2', function () {
let p = new OutlineElement('A', null!, fakeSymbolInformation(new Range(1, 1, 11, 1)));
let c1 = new OutlineElement('A/B', null!, fakeSymbolInformation(new Range(2, 4, 5, 4)));
let c2 = new OutlineElement('A/C', null!, fakeSymbolInformation(new Range(6, 4, 9, 4)));
let group = new OutlineGroup('group', null!, null!, 1);
group.children[p.id] = p;
p.children[c1.id] = c1;
p.children[c2.id] = c2;
let data = [
fakeMarker(new Range(2, 4, 5, 4))
];
group.updateMarker(data);
assert.equal(p.marker!.count, 0);
assert.equal(c1.marker!.count, 1);
assert.equal(c2.marker, undefined);
data = [
fakeMarker(new Range(2, 4, 5, 4)),
fakeMarker(new Range(2, 6, 2, 8)),
fakeMarker(new Range(7, 6, 7, 8)),
];
group.updateMarker(data);
assert.equal(p.marker!.count, 0);
assert.equal(c1.marker!.count, 2);
assert.equal(c2.marker!.count, 1);
data = [
fakeMarker(new Range(1, 4, 1, 11)),
fakeMarker(new Range(7, 6, 7, 8)),
];
group.updateMarker(data);
assert.equal(p.marker!.count, 1);
assert.equal(c1.marker, undefined);
assert.equal(c2.marker!.count, 1);
});
test('OutlineElement - updateMarker/multiple groups', function () {
let model = new class extends OutlineModel {
constructor() {
super(null!);
}
readyForTesting() {
this._groups = this.children as any;
}
};
model.children['g1'] = new OutlineGroup('g1', model, null!, 1);
model.children['g1'].children['c1'] = new OutlineElement('c1', model.children['g1'], fakeSymbolInformation(new Range(1, 1, 11, 1)));
model.children['g2'] = new OutlineGroup('g2', model, null!, 1);
model.children['g2'].children['c2'] = new OutlineElement('c2', model.children['g2'], fakeSymbolInformation(new Range(1, 1, 7, 1)));
model.children['g2'].children['c2'].children['c2.1'] = new OutlineElement('c2.1', model.children['g2'].children['c2'], fakeSymbolInformation(new Range(1, 3, 2, 19)));
model.children['g2'].children['c2'].children['c2.2'] = new OutlineElement('c2.2', model.children['g2'].children['c2'], fakeSymbolInformation(new Range(4, 1, 6, 10)));
model.readyForTesting();
const data = [
fakeMarker(new Range(1, 1, 2, 8)),
fakeMarker(new Range(6, 1, 6, 98)),
];
model.updateMarker(data);
assert.equal(model.children['g1']!.children['c1'].marker!.count, 2);
assert.equal(model.children['g2']!.children['c2'].children['c2.1'].marker!.count, 1);
assert.equal(model.children['g2']!.children['c2'].children['c2.2'].marker!.count, 1);
});
});
| src/vs/editor/contrib/documentSymbols/test/outlineModel.test.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0005945765879005194,
0.00022044010984245688,
0.00016267063620034605,
0.00017341296188533306,
0.00012006684846710414
] |
{
"id": 12,
"code_window": [
"\t\t});\n",
"\t\tthis._textEditor = undefined;\n",
"\t\tthis._cursorChangeListener?.dispose();\n",
"\t\tthis._onDidChangeEditorAttachState.fire(false);\n",
"\t}\n",
"\n",
"\trevealRangeInCenter(range: Range) {\n",
"\t\tthis._textEditor?.revealRangeInCenter(range, editorCommon.ScrollType.Immediate);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._cursorChangeListener = null;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 332
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import * as UUID from 'vs/base/common/uuid';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { Range } from 'vs/editor/common/core/range';
import * as editorCommon from 'vs/editor/common/editorCommon';
import * as model from 'vs/editor/common/model';
import { SearchParams } from 'vs/editor/common/model/textModelSearch';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { PrefixSumComputer } from 'vs/editor/common/viewModel/prefixSumComputer';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { MarkdownRenderer } from 'vs/workbench/contrib/notebook/browser/view/renderers/mdRenderer';
import { CellKind, ICell, IOutput, NotebookCellOutputsSplice } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { CellFindMatch, CellState, CursorAtBoundary, CellFocusMode, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { EDITOR_TOP_PADDING, EDITOR_BOTTOM_PADDING, EDITOR_TOOLBAR_HEIGHT } from 'vs/workbench/contrib/notebook/browser/constants';
export class CellViewModel extends Disposable implements ICellViewModel {
private _mdRenderer: MarkdownRenderer | null = null;
private _html: HTMLElement | null = null;
protected readonly _onDidDispose = new Emitter<void>();
readonly onDidDispose = this._onDidDispose.event;
protected readonly _onDidChangeCellState = new Emitter<void>();
readonly onDidChangeCellState = this._onDidChangeCellState.event;
protected readonly _onDidChangeFocusMode = new Emitter<void>();
readonly onDidChangeFocusMode = this._onDidChangeFocusMode.event;
protected readonly _onDidChangeOutputs = new Emitter<NotebookCellOutputsSplice[]>();
readonly onDidChangeOutputs = this._onDidChangeOutputs.event;
private _outputCollection: number[] = [];
protected _outputsTop: PrefixSumComputer | null = null;
get handle() {
return this.cell.handle;
}
get uri() {
return this.cell.uri;
}
get cellKind() {
return this.cell.cellKind;
}
get lineCount() {
return this.cell.source.length;
}
get outputs() {
return this.cell.outputs;
}
private _state: CellState = CellState.Preview;
get state(): CellState {
return this._state;
}
set state(newState: CellState) {
if (newState === this._state) {
return;
}
this._state = newState;
this._onDidChangeCellState.fire();
}
private _focusMode: CellFocusMode = CellFocusMode.Container;
get focusMode() {
return this._focusMode;
}
set focusMode(newMode: CellFocusMode) {
this._focusMode = newMode;
this._onDidChangeFocusMode.fire();
}
private _selfSizeMonitoring: boolean = false;
set selfSizeMonitoring(newVal: boolean) {
this._selfSizeMonitoring = newVal;
}
get selfSizeMonitoring() {
return this._selfSizeMonitoring;
}
private _editorHeight = 0;
set editorHeight(height: number) {
this._editorHeight = height;
}
get editorHeight(): number {
return this._editorHeight;
}
protected readonly _onDidChangeEditorAttachState = new Emitter<boolean>();
readonly onDidChangeEditorAttachState = this._onDidChangeEditorAttachState.event;
get editorAttached(): boolean {
return !!this._textEditor;
}
private _textModel?: model.ITextModel;
private _textEditor?: ICodeEditor;
private _buffer: model.ITextBuffer | null;
private _editorViewStates: editorCommon.ICodeEditorViewState | null;
private _lastDecorationId: number = 0;
private _resolvedDecorations = new Map<string, { id?: string, options: model.IModelDeltaDecoration }>();
private readonly _onDidChangeContent: Emitter<void> = this._register(new Emitter<void>());
public readonly onDidChangeContent: Event<void> = this._onDidChangeContent.event;
private readonly _onDidChangeCursorSelection: Emitter<void> = this._register(new Emitter<void>());
public readonly onDidChangeCursorSelection: Event<void> = this._onDidChangeCursorSelection.event;
private _cursorChangeListener: IDisposable | null = null;
readonly id: string = UUID.generateUuid();
constructor(
readonly viewType: string,
readonly notebookHandle: number,
readonly cell: ICell,
@IInstantiationService private readonly _instaService: IInstantiationService,
@ITextModelService private readonly _modelService: ITextModelService,
) {
super();
if (this.cell.onDidChangeOutputs) {
this._register(this.cell.onDidChangeOutputs((splices) => {
this._outputCollection = new Array(this.cell.outputs.length);
this._outputsTop = null;
this._onDidChangeOutputs.fire(splices);
}));
}
this._outputCollection = new Array(this.cell.outputs.length);
this._buffer = null;
this._editorViewStates = null;
}
restoreEditorViewState(editorViewStates: editorCommon.ICodeEditorViewState | null) {
this._editorViewStates = editorViewStates;
}
saveEditorViewState() {
if (this._textEditor) {
this._editorViewStates = this.saveViewState();
}
return this._editorViewStates;
}
//#region Search
private readonly _hasFindResult = this._register(new Emitter<boolean>());
public readonly hasFindResult: Event<boolean> = this._hasFindResult.event;
startFind(value: string): CellFindMatch | null {
let cellMatches: model.FindMatch[] = [];
if (this.assertTextModelAttached()) {
cellMatches = this._textModel!.findMatches(value, false, false, false, null, false);
} else {
if (!this._buffer) {
this._buffer = this.cell.resolveTextBufferFactory().create(model.DefaultEndOfLine.LF);
}
const lineCount = this._buffer.getLineCount();
const fullRange = new Range(1, 1, lineCount, this._buffer.getLineLength(lineCount) + 1);
const searchParams = new SearchParams(value, false, false, null);
const searchData = searchParams.parseSearchRequest();
if (!searchData) {
return null;
}
cellMatches = this._buffer.findMatchesLineByLine(fullRange, searchData, false, 1000);
}
return {
cell: this,
matches: cellMatches
};
}
assertTextModelAttached(): boolean {
if (this._textModel && this._textEditor && this._textEditor.getModel() === this._textModel) {
return true;
}
return false;
}
private saveViewState(): editorCommon.ICodeEditorViewState | null {
if (!this._textEditor) {
return null;
}
return this._textEditor.saveViewState();
}
private restoreViewState(state: editorCommon.ICodeEditorViewState | null): void {
if (state) {
this._textEditor?.restoreViewState(state);
}
}
//#endregion
hasDynamicHeight() {
if (this.selfSizeMonitoring) {
// if there is an output rendered in the webview, it should always be false
return false;
}
if (this.cellKind === CellKind.Code) {
if (this.outputs && this.outputs.length > 0) {
// if it contains output, it will be marked as dynamic height
// thus when it's being rendered, the list view will `probeHeight`
// inside which, we will check domNode's height directly instead of doing another `renderElement` with height undefined.
return true;
}
else {
return false;
}
}
return true;
}
getHeight(lineHeight: number) {
if (this.cellKind === CellKind.Markdown) {
return 100;
}
else {
return this.lineCount * lineHeight + 16 + EDITOR_TOP_PADDING + EDITOR_BOTTOM_PADDING;
}
}
setText(strs: string[]) {
this.cell.source = strs;
this._html = null;
}
save() {
if (this._textModel && !this._textModel.isDisposed() && this.state === CellState.Editing) {
let cnt = this._textModel.getLineCount();
this.cell.source = this._textModel.getLinesContent().map((str, index) => str + (index !== cnt - 1 ? '\n' : ''));
}
}
getText(): string {
if (this._textModel) {
return this._textModel.getValue();
}
return this.cell.source.join('\n');
}
getHTML(): HTMLElement | null {
if (this.cellKind === CellKind.Markdown) {
if (this._html) {
return this._html;
}
let renderer = this.getMarkdownRenderer();
this._html = renderer.render({ value: this.getText(), isTrusted: true }).element;
return this._html;
}
return null;
}
async resolveTextModel(): Promise<model.ITextModel> {
if (!this._textModel) {
const ref = await this._modelService.createModelReference(this.cell.uri);
this._textModel = ref.object.textEditorModel;
this._buffer = this._textModel.getTextBuffer();
this._register(ref);
this._register(this._textModel.onDidChangeContent(() => {
this.cell.contentChange();
this._html = null;
this._onDidChangeContent.fire();
}));
}
return this._textModel;
}
attachTextEditor(editor: ICodeEditor) {
if (!editor.hasModel()) {
throw new Error('Invalid editor: model is missing');
}
if (this._textEditor === editor) {
return;
}
this._textEditor = editor;
if (this._editorViewStates) {
this.restoreViewState(this._editorViewStates);
}
this._resolvedDecorations.forEach((value, key) => {
if (key.startsWith('_lazy_')) {
// lazy ones
const ret = this._textEditor!.deltaDecorations([], [value.options]);
this._resolvedDecorations.get(key)!.id = ret[0];
} else {
const ret = this._textEditor!.deltaDecorations([], [value.options]);
this._resolvedDecorations.get(key)!.id = ret[0];
}
});
this._cursorChangeListener = this._textEditor.onDidChangeCursorSelection(() => this._onDidChangeCursorSelection.fire());
this._onDidChangeCursorSelection.fire();
this._onDidChangeEditorAttachState.fire(true);
}
detachTextEditor() {
this._editorViewStates = this.saveViewState();
// decorations need to be cleared first as editors can be resued.
this._resolvedDecorations.forEach(value => {
let resolvedid = value.id;
if (resolvedid) {
this._textEditor?.deltaDecorations([resolvedid], []);
}
});
this._textEditor = undefined;
this._cursorChangeListener?.dispose();
this._onDidChangeEditorAttachState.fire(false);
}
revealRangeInCenter(range: Range) {
this._textEditor?.revealRangeInCenter(range, editorCommon.ScrollType.Immediate);
}
setSelection(range: Range) {
this._textEditor?.setSelection(range);
}
getLineScrollTopOffset(line: number): number {
if (!this._textEditor) {
return 0;
}
return this._textEditor.getTopForLineNumber(line);
}
addDecoration(decoration: model.IModelDeltaDecoration): string {
if (!this._textEditor) {
const id = ++this._lastDecorationId;
const decorationId = `_lazy_${this.id};${id}`;
this._resolvedDecorations.set(decorationId, { options: decoration });
return decorationId;
}
const result = this._textEditor.deltaDecorations([], [decoration]);
this._resolvedDecorations.set(result[0], { id: result[0], options: decoration });
return result[0];
}
removeDecoration(decorationId: string) {
const realDecorationId = this._resolvedDecorations.get(decorationId);
if (this._textEditor && realDecorationId && realDecorationId.id !== undefined) {
this._textEditor.deltaDecorations([realDecorationId.id!], []);
}
// lastly, remove all the cache
this._resolvedDecorations.delete(decorationId);
}
deltaDecorations(oldDecorations: string[], newDecorations: model.IModelDeltaDecoration[]): string[] {
oldDecorations.forEach(id => {
this.removeDecoration(id);
});
const ret = newDecorations.map(option => {
return this.addDecoration(option);
});
return ret;
}
onDeselect() {
this.state = CellState.Preview;
}
cursorAtBoundary(): CursorAtBoundary {
if (!this._textEditor) {
return CursorAtBoundary.None;
}
// only validate primary cursor
const selection = this._textEditor.getSelection();
// only validate empty cursor
if (!selection || !selection.isEmpty()) {
return CursorAtBoundary.None;
}
// we don't allow attaching text editor without a model
const lineCnt = this._textEditor.getModel()!.getLineCount();
if (selection.startLineNumber === lineCnt) {
// bottom
if (selection.startLineNumber === 1) {
return CursorAtBoundary.Both;
} else {
return CursorAtBoundary.Bottom;
}
}
if (selection.startLineNumber === 1) {
return CursorAtBoundary.Top;
}
return CursorAtBoundary.None;
}
getMarkdownRenderer() {
if (!this._mdRenderer) {
this._mdRenderer = this._instaService.createInstance(MarkdownRenderer);
}
return this._mdRenderer;
}
updateOutputHeight(index: number, height: number) {
if (index >= this._outputCollection.length) {
throw new Error('Output index out of range!');
}
this._outputCollection[index] = height;
this._ensureOutputsTop();
this._outputsTop!.changeValue(index, height);
}
getOutputOffset(index: number): number {
if (index >= this._outputCollection.length) {
throw new Error('Output index out of range!');
}
this._ensureOutputsTop();
return this._outputsTop!.getAccumulatedValue(index - 1);
}
getOutputHeight(output: IOutput): number | undefined {
let index = this.cell.outputs.indexOf(output);
if (index < 0) {
return undefined;
}
if (index < this._outputCollection.length) {
return this._outputCollection[index];
}
return undefined;
}
private getOutputTotalHeight(): number {
this._ensureOutputsTop();
return this._outputsTop!.getTotalValue();
}
spliceOutputHeights(start: number, deleteCnt: number, heights: number[]) {
this._ensureOutputsTop();
this._outputsTop!.removeValues(start, deleteCnt);
if (heights.length) {
const values = new Uint32Array(heights.length);
for (let i = 0; i < heights.length; i++) {
values[i] = heights[i];
}
this._outputsTop!.insertValues(start, values);
}
}
getCellTotalHeight(): number {
if (this.outputs.length) {
return EDITOR_TOOLBAR_HEIGHT + this.editorHeight + EDITOR_TOP_PADDING + EDITOR_BOTTOM_PADDING + 16 + this.getOutputTotalHeight();
} else {
return EDITOR_TOOLBAR_HEIGHT + this.editorHeight + EDITOR_TOP_PADDING + EDITOR_BOTTOM_PADDING + this.getOutputTotalHeight();
}
}
protected _ensureOutputsTop(): void {
if (!this._outputsTop) {
const values = new Uint32Array(this._outputCollection.length);
for (let i = 0; i < this._outputCollection.length; i++) {
values[i] = this._outputCollection[i];
}
this._outputsTop = new PrefixSumComputer(values);
}
}
}
| src/vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.9975329637527466,
0.023851430043578148,
0.00016339067951776087,
0.00022637027723249048,
0.13824597001075745
] |
{
"id": 12,
"code_window": [
"\t\t});\n",
"\t\tthis._textEditor = undefined;\n",
"\t\tthis._cursorChangeListener?.dispose();\n",
"\t\tthis._onDidChangeEditorAttachState.fire(false);\n",
"\t}\n",
"\n",
"\trevealRangeInCenter(range: Range) {\n",
"\t\tthis._textEditor?.revealRangeInCenter(range, editorCommon.ScrollType.Immediate);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._cursorChangeListener = null;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 332
} | {
"comments": {
"lineComment": "",
"blockComment": ["<!--", "-->"]
},
"brackets": [
["<", ">"]
]
// enhancedBrackets: [{
// tokenType: 'tag.tag-$1.xml',
// openTrigger: '>',
// open: /<(\w[\w\d]*)([^\/>]*(?!\/)>)[^<>]*$/i,
// closeComplete: '</$1>',
// closeTrigger: '>',
// close: /<\/(\w[\w\d]*)\s*>$/i
// }],
// autoClosingPairs: [['\'', '\''], ['"', '"'] ]
}
| extensions/xml/xsl.language-configuration.json | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017600097635295242,
0.00017522113921586424,
0.00017461874813307077,
0.0001750436786096543,
5.780753440376429e-7
] |
{
"id": 12,
"code_window": [
"\t\t});\n",
"\t\tthis._textEditor = undefined;\n",
"\t\tthis._cursorChangeListener?.dispose();\n",
"\t\tthis._onDidChangeEditorAttachState.fire(false);\n",
"\t}\n",
"\n",
"\trevealRangeInCenter(range: Range) {\n",
"\t\tthis._textEditor?.revealRangeInCenter(range, editorCommon.ScrollType.Immediate);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._cursorChangeListener = null;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 332
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { Registry } from 'vs/platform/registry/common/platform';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
// --- other interested parties
import { JSONValidationExtensionPoint } from 'vs/workbench/api/common/jsonValidationExtensionPoint';
import { ColorExtensionPoint } from 'vs/workbench/services/themes/common/colorExtensionPoint';
import { TokenClassificationExtensionPoints } from 'vs/workbench/services/themes/common/tokenClassificationExtensionPoint';
import { LanguageConfigurationFileHandler } from 'vs/workbench/contrib/codeEditor/browser/languageConfigurationExtensionPoint';
// --- mainThread participants
import './mainThreadCodeInsets';
import './mainThreadClipboard';
import './mainThreadCommands';
import './mainThreadConfiguration';
import './mainThreadConsole';
import './mainThreadDebugService';
import './mainThreadDecorations';
import './mainThreadDiagnostics';
import './mainThreadDialogs';
import './mainThreadDocumentContentProviders';
import './mainThreadDocuments';
import './mainThreadDocumentsAndEditors';
import './mainThreadEditor';
import './mainThreadEditors';
import './mainThreadErrors';
import './mainThreadExtensionService';
import './mainThreadFileSystem';
import './mainThreadFileSystemEventService';
import './mainThreadKeytar';
import './mainThreadLanguageFeatures';
import './mainThreadLanguages';
import './mainThreadLogService';
import './mainThreadMessageService';
import './mainThreadOutputService';
import './mainThreadProgress';
import './mainThreadQuickOpen';
import './mainThreadSaveParticipant';
import './mainThreadSCM';
import './mainThreadSearch';
import './mainThreadStatusBar';
import './mainThreadStorage';
import './mainThreadTelemetry';
import './mainThreadTerminalService';
import './mainThreadTheming';
import './mainThreadTreeViews';
import './mainThreadDownloadService';
import './mainThreadUrls';
import './mainThreadWindow';
import './mainThreadWebview';
import './mainThreadWorkspace';
import './mainThreadComments';
import './mainThreadNotebook';
import './mainThreadTask';
import './mainThreadLabelService';
import './mainThreadTunnelService';
import './mainThreadAuthentication';
import './mainThreadTimeline';
import 'vs/workbench/api/common/apiCommands';
export class ExtensionPoints implements IWorkbenchContribution {
constructor(
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
// Classes that handle extension points...
this.instantiationService.createInstance(JSONValidationExtensionPoint);
this.instantiationService.createInstance(ColorExtensionPoint);
this.instantiationService.createInstance(TokenClassificationExtensionPoints);
this.instantiationService.createInstance(LanguageConfigurationFileHandler);
}
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(ExtensionPoints, LifecyclePhase.Starting);
| src/vs/workbench/api/browser/extensionHost.contribution.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017693838162813336,
0.00017534891958348453,
0.00017214016406796873,
0.00017580976418685168,
0.0000015525665730820037
] |
{
"id": 12,
"code_window": [
"\t\t});\n",
"\t\tthis._textEditor = undefined;\n",
"\t\tthis._cursorChangeListener?.dispose();\n",
"\t\tthis._onDidChangeEditorAttachState.fire(false);\n",
"\t}\n",
"\n",
"\trevealRangeInCenter(range: Range) {\n",
"\t\tthis._textEditor?.revealRangeInCenter(range, editorCommon.ScrollType.Immediate);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._cursorChangeListener = null;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 332
} | // Type definitions for Lazy.js 0.3.2
// Project: https://github.com/dtao/lazy.js/
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare function Lazy(value: string): Lazy.StringLikeSequence;
declare function Lazy<T>(value: T[]): Lazy.ArrayLikeSequence<T>;
declare function Lazy(value: any[]): Lazy.ArrayLikeSequence<any>;
declare function Lazy<T>(value: Object): Lazy.ObjectLikeSequence<T>;
declare function Lazy(value: Object): Lazy.ObjectLikeSequence<any>;
declare module Lazy {
function strict(): StrictLazy;
function generate<T>(generatorFn: GeneratorCallback<T>, length?: number): GeneratedSequence<T>;
function range(to: number): GeneratedSequence<number>;
function range(from: number, to: number, step?: number): GeneratedSequence<number>;
function repeat<T>(value: T, count?: number): GeneratedSequence<T>;
function on<T>(eventType: string): Sequence<T>;
function readFile(path: string): StringLikeSequence;
function makeHttpRequest(path: string): StringLikeSequence;
interface StrictLazy {
(value: string): StringLikeSequence;
<T>(value: T[]): ArrayLikeSequence<T>;
(value: any[]): ArrayLikeSequence<any>;
<T>(value: Object): ObjectLikeSequence<T>;
(value: Object): ObjectLikeSequence<any>;
strict(): StrictLazy;
generate<T>(generatorFn: GeneratorCallback<T>, length?: number): GeneratedSequence<T>;
range(to: number): GeneratedSequence<number>;
range(from: number, to: number, step?: number): GeneratedSequence<number>;
repeat<T>(value: T, count?: number): GeneratedSequence<T>;
on<T>(eventType: string): Sequence<T>;
readFile(path: string): StringLikeSequence;
makeHttpRequest(path: string): StringLikeSequence;
}
interface ArrayLike<T> {
length: number;
[index: number]: T;
}
interface Callback {
(): void;
}
interface ErrorCallback {
(error: any): void;
}
interface ValueCallback<T> {
(value: T): void;
}
interface GetKeyCallback<T> {
(value: T): string;
}
interface TestCallback<T> {
(value: T): boolean;
}
interface MapCallback<T, U> {
(value: T): U;
}
interface MapStringCallback {
(value: string): string;
}
interface NumberCallback<T> {
(value: T): number;
}
interface MemoCallback<T, U> {
(memo: U, value: T): U;
}
interface GeneratorCallback<T> {
(index: number): T;
}
interface CompareCallback {
(x: any, y: any): number;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
interface Iterator<T> {
new(sequence: Sequence<T>): Iterator<T>;
current(): T;
moveNext(): boolean;
}
interface GeneratedSequence<T> extends Sequence<T> {
new(generatorFn: GeneratorCallback<T>, length: number): GeneratedSequence<T>;
length(): number;
}
interface AsyncSequence<T> extends SequenceBase<T> {
each(callback: ValueCallback<T>): AsyncHandle<T>;
}
interface AsyncHandle<T> {
cancel(): void;
onComplete(callback: Callback): void;
onError(callback: ErrorCallback): void;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module Sequence {
function define(methodName: string[], overrides: Object): Function;
}
interface Sequence<T> extends SequenceBase<T> {
each(eachFn: ValueCallback<T>): Sequence<T>;
}
interface ArraySequence<T> extends SequenceBase<T[]> {
flatten(): Sequence<T>;
}
interface SequenceBase<T> extends SequenceBaser<T> {
first(): any;
first(count: number): Sequence<T>;
indexOf(value: any, startIndex?: number): Sequence<T>;
last(): any;
last(count: number): Sequence<T>;
lastIndexOf(value: any): Sequence<T>;
reverse(): Sequence<T>;
}
interface SequenceBaser<T> {
// TODO improve define() (needs ugly overload)
async(interval: number): AsyncSequence<T>;
chunk(size: number): Sequence<T>;
compact(): Sequence<T>;
concat(var_args: T[]): Sequence<T>;
concat(sequence: Sequence<T>): Sequence<T>;
consecutive(length: number): Sequence<T>;
contains(value: T): boolean;
countBy(keyFn: GetKeyCallback<T>): ObjectLikeSequence<T>;
countBy(propertyName: string): ObjectLikeSequence<T>;
dropWhile(predicateFn: TestCallback<T>): Sequence<T>;
every(predicateFn: TestCallback<T>): boolean;
filter(predicateFn: TestCallback<T>): Sequence<T>;
find(predicateFn: TestCallback<T>): Sequence<T>;
findWhere(properties: Object): Sequence<T>;
groupBy(keyFn: GetKeyCallback<T>): ObjectLikeSequence<T>;
initial(count?: number): Sequence<T>;
intersection(var_args: T[]): Sequence<T>;
invoke(methodName: string): Sequence<T>;
isEmpty(): boolean;
join(delimiter?: string): string;
map<U>(mapFn: MapCallback<T, U[]>): ArraySequence<U>;
map<U>(mapFn: MapCallback<T, U>): Sequence<U>;
// TODO: vscode addition to workaround strict null errors
flatten(): Sequence<any>;
max(valueFn?: NumberCallback<T>): T;
min(valueFn?: NumberCallback<T>): T;
none(valueFn?: TestCallback<T>): boolean;
pluck(propertyName: string): Sequence<T>;
reduce<U>(aggregatorFn: MemoCallback<T, U>, memo?: U): U;
reduceRight<U>(aggregatorFn: MemoCallback<T, U>, memo: U): U;
reject(predicateFn: TestCallback<T>): Sequence<T>;
rest(count?: number): Sequence<T>;
shuffle(): Sequence<T>;
some(predicateFn?: TestCallback<T>): boolean;
sort(sortFn?: CompareCallback, descending?: boolean): Sequence<T>;
sortBy(sortFn: string, descending?: boolean): Sequence<T>;
sortBy(sortFn: NumberCallback<T>, descending?: boolean): Sequence<T>;
sortedIndex(value: T): Sequence<T>;
size(): number;
sum(valueFn?: NumberCallback<T>): Sequence<T>;
takeWhile(predicateFn: TestCallback<T>): Sequence<T>;
union(var_args: T[]): Sequence<T>;
uniq(): Sequence<T>;
where(properties: Object): Sequence<T>;
without(...var_args: T[]): Sequence<T>;
without(var_args: T[]): Sequence<T>;
zip(var_args: T[]): ArraySequence<T>;
toArray(): T[];
toObject(): Object;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module ArrayLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface ArrayLikeSequence<T> extends Sequence<T> {
// define()X;
concat(var_args: T[]): ArrayLikeSequence<T>;
concat(sequence: Sequence<T>): Sequence<T>;
first(count?: number): ArrayLikeSequence<T>;
get(index: number): T;
length(): number;
map<U>(mapFn: MapCallback<T, U[]>): ArraySequence<U>;
map<U>(mapFn: MapCallback<T, U>): ArrayLikeSequence<U>;
pop(): ArrayLikeSequence<T>;
rest(count?: number): ArrayLikeSequence<T>;
reverse(): ArrayLikeSequence<T>;
shift(): ArrayLikeSequence<T>;
slice(begin: number, end?: number): ArrayLikeSequence<T>;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module ObjectLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface ObjectLikeSequence<T> extends Sequence<T> {
assign(other: Object): ObjectLikeSequence<T>;
// throws error
//async(): X;
defaults(defaults: Object): ObjectLikeSequence<T>;
functions(): Sequence<T>;
get(property: string): ObjectLikeSequence<T>;
invert(): ObjectLikeSequence<T>;
keys(): Sequence<string>;
omit(properties: string[]): ObjectLikeSequence<T>;
pairs(): Sequence<T>;
pick(properties: string[]): ObjectLikeSequence<T>;
toArray(): T[];
toObject(): Object;
values(): Sequence<T>;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module StringLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface StringLikeSequence extends SequenceBaser<string> {
charAt(index: number): string;
charCodeAt(index: number): number;
contains(value: string): boolean;
endsWith(suffix: string): boolean;
first(): string;
first(count: number): StringLikeSequence;
indexOf(substring: string, startIndex?: number): number;
last(): string;
last(count: number): StringLikeSequence;
lastIndexOf(substring: string, startIndex?: number): number;
mapString(mapFn: MapStringCallback): StringLikeSequence;
match(pattern: RegExp): StringLikeSequence;
reverse(): StringLikeSequence;
split(delimiter: string): StringLikeSequence;
split(delimiter: RegExp): StringLikeSequence;
startsWith(prefix: string): boolean;
substring(start: number, stop?: number): StringLikeSequence;
toLowerCase(): StringLikeSequence;
toUpperCase(): StringLikeSequence;
}
}
declare module 'lazy.js' {
export = Lazy;
}
| build/lib/typings/lazy.js.d.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0026348598767071962,
0.0002619716397020966,
0.00016559686628170311,
0.00017436975031159818,
0.0004566754214465618
] |
{
"id": 13,
"code_window": [
"\t\tif (!this._textEditor) {\n",
"\t\t\treturn 0;\n",
"\t\t}\n",
"\n",
"\t\treturn this._textEditor.getTopForLineNumber(line);\n",
"\t}\n",
"\n",
"\taddDecoration(decoration: model.IModelDeltaDecoration): string {\n",
"\t\tif (!this._textEditor) {\n",
"\t\t\tconst id = ++this._lastDecorationId;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this._textEditor.getTopForLineNumber(line) + EDITOR_TOP_PADDING + EDITOR_TOOLBAR_HEIGHT;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel.ts",
"type": "replace",
"edit_start_line_idx": 348
} | /*---------------------------------------------------------------------------------------------
* 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 { IListRenderer, IListVirtualDelegate, ListError } from 'vs/base/browser/ui/list/list';
import { Event } from 'vs/base/common/event';
import { ScrollEvent } from 'vs/base/common/scrollable';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IListService, IWorkbenchListOptions, WorkbenchList } from 'vs/platform/list/browser/listService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { isMacintosh } from 'vs/base/common/platform';
import { NOTEBOOK_EDITOR_CURSOR_BOUNDARY } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { Range } from 'vs/editor/common/core/range';
import { CellRevealType, CellRevealPosition, CursorAtBoundary } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';
import { EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable {
get onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }
get rowsContainer(): HTMLElement {
return this.view.containerDomNode;
}
private _previousSelectedElements: CellViewModel[] = [];
private _localDisposableStore = new DisposableStore();
constructor(
private listUser: string,
container: HTMLElement,
delegate: IListVirtualDelegate<CellViewModel>,
renderers: IListRenderer<CellViewModel, any>[],
contextKeyService: IContextKeyService,
options: IWorkbenchListOptions<CellViewModel>,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService
) {
super(listUser, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService);
this._previousSelectedElements = this.getSelectedElements();
this._localDisposableStore.add(this.onDidChangeSelection((e) => {
this._previousSelectedElements.forEach(element => {
if (e.elements.indexOf(element) < 0) {
element.onDeselect();
}
});
this._previousSelectedElements = e.elements;
}));
const notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);
notebookEditorCursorAtBoundaryContext.set('none');
let cursorSelectionLisener: IDisposable | null = null;
const recomputeContext = (element: CellViewModel) => {
switch (element.cursorAtBoundary()) {
case CursorAtBoundary.Both:
notebookEditorCursorAtBoundaryContext.set('both');
break;
case CursorAtBoundary.Top:
notebookEditorCursorAtBoundaryContext.set('top');
break;
case CursorAtBoundary.Bottom:
notebookEditorCursorAtBoundaryContext.set('bottom');
break;
default:
notebookEditorCursorAtBoundaryContext.set('none');
break;
}
return;
};
// Cursor Boundary context
this._localDisposableStore.add(this.onDidChangeFocus((e) => {
cursorSelectionLisener?.dispose();
if (e.elements.length) {
// we only validate the first focused element
const focusedElement = e.elements[0];
cursorSelectionLisener = focusedElement.onDidChangeCursorSelection(() => {
recomputeContext(focusedElement);
});
recomputeContext(focusedElement);
return;
}
// reset context
notebookEditorCursorAtBoundaryContext.set('none');
}));
}
domElementAtIndex(index: number): HTMLElement | null {
return this.view.domElement(index);
}
focusView() {
this.view.domNode.focus();
}
getAbsoluteTop(index: number): number {
if (index < 0 || index >= this.length) {
throw new ListError(this.listUser, `Invalid index ${index}`);
}
return this.view.elementTop(index);
}
triggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {
this.view.triggerScrollFromMouseWheelEvent(browserEvent);
}
updateElementHeight(index: number, size: number): void {
const focused = this.getSelection();
this.view.updateElementHeight(index, size, focused.length ? focused[0] : null);
// this.view.updateElementHeight(index, size, null);
}
// override
domFocus() {
if (document.activeElement && this.view.domNode.contains(document.activeElement)) {
// for example, when focus goes into monaco editor, if we refocus the list view, the editor will lose focus.
return;
}
if (!isMacintosh && document.activeElement && isContextMenuFocused()) {
return;
}
super.domFocus();
}
private _revealRange(index: number, range: Range, revealType: CellRevealType, newlyCreated: boolean, alignToBottom: boolean) {
const element = this.view.element(index);
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const startLineNumber = range.startLineNumber;
const lineOffset = element.getLineScrollTopOffset(startLineNumber);
const elementTop = this.view.elementTop(index);
const lineTop = elementTop + lineOffset + EDITOR_TOP_PADDING;
// TODO@rebornix 30 ---> line height * 1.5
if (lineTop < scrollTop) {
this.view.setScrollTop(lineTop - 30);
} else if (lineTop > wrapperBottom) {
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else if (newlyCreated) {
// newly scrolled into view
if (alignToBottom) {
// align to the bottom
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else {
// align to to top
this.view.setScrollTop(lineTop - 30);
}
}
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
}
// TODO@rebornix TEST & Fix potential bugs
// List items have real dynamic heights, which means after we set `scrollTop` based on the `elementTop(index)`, the element at `index` might still be removed from the view once all relayouting tasks are done.
// For example, we scroll item 10 into the view upwards, in the first round, items 7, 8, 9, 10 are all in the viewport. Then item 7 and 8 resize themselves to be larger and finally item 10 is removed from the view.
// To ensure that item 10 is always there, we need to scroll item 10 to the top edge of the viewport.
private _revealRangeInternal(index: number, range: Range, revealType: CellRevealType) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const element = this.view.element(index);
if (element.editorAttached) {
this._revealRange(index, range, revealType, false, false);
} else {
const elementHeight = this.view.elementHeight(index);
let upwards = false;
if (elementTop + elementHeight < scrollTop) {
// scroll downwards
this.view.setScrollTop(elementTop);
upwards = false;
} else if (elementTop > wrapperBottom) {
// scroll upwards
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
upwards = true;
}
const editorAttachedPromise = new Promise((resolve, reject) => {
element.onDidChangeEditorAttachState(state => state ? resolve() : reject());
});
editorAttachedPromise.then(() => {
this._revealRange(index, range, revealType, true, upwards);
});
}
}
revealLineInView(index: number, line: number) {
this._revealRangeInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInView(index: number, range: Range): void {
this._revealRangeInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
};
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
const element = this.view.element(index);
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
reveal(index, range, revealType);
}
}
revealLineInCenter(index: number, line: number) {
this._revealRangeInCenterInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenter(index: number, range: Range): void {
this._revealRangeInCenterInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterIfOutsideViewportInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
setTimeout(() => {
element.revealRangeInCenter(range);
}, 240);
}
};
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
const element = this.view.element(index);
if (viewItemOffset < scrollTop || viewItemOffset > wrapperBottom) {
// let it render
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
// after rendering, it might be pushed down due to markdown cell dynamic height
const elementTop = this.view.elementTop(index);
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
// reveal editor
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
// for example markdown
}
} else {
if (element.editorAttached) {
element.revealRangeInCenter(range);
} else {
// for example, markdown cell in preview mode
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
}
}
}
revealLineInCenterIfOutsideViewport(index: number, line: number) {
this._revealRangeInCenterIfOutsideViewportInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenterIfOutsideViewport(index: number, range: Range): void {
this._revealRangeInCenterIfOutsideViewportInternal(index, range, CellRevealType.Range);
}
private _revealInternal(index: number, ignoreIfInsideViewport: boolean, revealPosition: CellRevealPosition) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
if (ignoreIfInsideViewport && elementTop >= scrollTop && elementTop < wrapperBottom) {
// inside the viewport
return;
}
// first render
const viewItemOffset = revealPosition === CellRevealPosition.Top ? elementTop : (elementTop - this.view.renderHeight / 2);
this.view.setScrollTop(viewItemOffset);
// second scroll as markdown cell is dynamic
const newElementTop = this.view.elementTop(index);
const newViewItemOffset = revealPosition === CellRevealPosition.Top ? newElementTop : (newElementTop - this.view.renderHeight / 2);
this.view.setScrollTop(newViewItemOffset);
}
revealInView(index: number) {
this._revealInternal(index, true, CellRevealPosition.Top);
}
revealInCenter(index: number) {
this._revealInternal(index, false, CellRevealPosition.Center);
}
revealInCenterIfOutsideViewport(index: number) {
this._revealInternal(index, true, CellRevealPosition.Center);
}
setCellSelection(index: number, range: Range) {
const element = this.view.element(index);
if (element.editorAttached) {
element.setSelection(range);
} else {
getEditorAttachedPromise(element).then(() => { element.setSelection(range); });
}
}
dispose() {
this._localDisposableStore.dispose();
super.dispose();
}
}
function getEditorAttachedPromise(element: CellViewModel) {
return new Promise((resolve, reject) => {
Event.once(element.onDidChangeEditorAttachState)(state => state ? resolve() : reject());
});
}
function isContextMenuFocused() {
return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
}
| src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0002775944594759494,
0.0001783370244083926,
0.00016767655324656516,
0.00017156958347186446,
0.00002221115937572904
] |
{
"id": 13,
"code_window": [
"\t\tif (!this._textEditor) {\n",
"\t\t\treturn 0;\n",
"\t\t}\n",
"\n",
"\t\treturn this._textEditor.getTopForLineNumber(line);\n",
"\t}\n",
"\n",
"\taddDecoration(decoration: model.IModelDeltaDecoration): string {\n",
"\t\tif (!this._textEditor) {\n",
"\t\t\tconst id = ++this._lastDecorationId;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this._textEditor.getTopForLineNumber(line) + EDITOR_TOP_PADDING + EDITOR_TOOLBAR_HEIGHT;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel.ts",
"type": "replace",
"edit_start_line_idx": 348
} | /*---------------------------------------------------------------------------------------------
* 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!./welcomeOverlay';
import * as dom from 'vs/base/browser/dom';
import { Registry } from 'vs/platform/registry/common/platform';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ShowAllCommandsAction } from 'vs/workbench/contrib/quickopen/browser/commandsHandler';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ILayoutService } from 'vs/platform/layout/browser/layoutService';
import { localize } from 'vs/nls';
import { Action } from 'vs/base/common/actions';
import { IWorkbenchActionRegistry, Extensions } from 'vs/workbench/common/actions';
import { SyncActionDescriptor } from 'vs/platform/actions/common/actions';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { Disposable } from 'vs/base/common/lifecycle';
import { RawContextKey, IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { KeyCode } from 'vs/base/common/keyCodes';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { textPreformatForeground, foreground } from 'vs/platform/theme/common/colorRegistry';
import { Color } from 'vs/base/common/color';
const $ = dom.$;
interface Key {
id: string;
arrow?: string;
label: string;
command?: string;
arrowLast?: boolean;
withEditor?: boolean;
}
const keys: Key[] = [
{
id: 'explorer',
arrow: '←',
label: localize('welcomeOverlay.explorer', "File explorer"),
command: 'workbench.view.explorer'
},
{
id: 'search',
arrow: '←',
label: localize('welcomeOverlay.search', "Search across files"),
command: 'workbench.view.search'
},
{
id: 'git',
arrow: '←',
label: localize('welcomeOverlay.git', "Source code management"),
command: 'workbench.view.scm'
},
{
id: 'debug',
arrow: '←',
label: localize('welcomeOverlay.debug', "Launch and debug"),
command: 'workbench.view.debug'
},
{
id: 'extensions',
arrow: '←',
label: localize('welcomeOverlay.extensions', "Manage extensions"),
command: 'workbench.view.extensions'
},
// {
// id: 'watermark',
// arrow: '⤹',
// label: localize('welcomeOverlay.watermark', "Command Hints"),
// withEditor: false
// },
{
id: 'problems',
arrow: '⤹',
label: localize('welcomeOverlay.problems', "View errors and warnings"),
command: 'workbench.actions.view.problems'
},
{
id: 'terminal',
label: localize('welcomeOverlay.terminal', "Toggle integrated terminal"),
command: 'workbench.action.terminal.toggleTerminal'
},
// {
// id: 'openfile',
// arrow: '⤸',
// label: localize('welcomeOverlay.openfile', "File Properties"),
// arrowLast: true,
// withEditor: true
// },
{
id: 'commandPalette',
arrow: '↖',
label: localize('welcomeOverlay.commandPalette', "Find and run all commands"),
command: ShowAllCommandsAction.ID
},
{
id: 'notifications',
arrow: '⤵',
arrowLast: true,
label: localize('welcomeOverlay.notifications', "Show notifications"),
command: 'notifications.showList'
}
];
const OVERLAY_VISIBLE = new RawContextKey<boolean>('interfaceOverviewVisible', false);
let welcomeOverlay: WelcomeOverlay;
export class WelcomeOverlayAction extends Action {
public static readonly ID = 'workbench.action.showInterfaceOverview';
public static readonly LABEL = localize('welcomeOverlay', "User Interface Overview");
constructor(
id: string,
label: string,
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
super(id, label);
}
public run(): Promise<void> {
if (!welcomeOverlay) {
welcomeOverlay = this.instantiationService.createInstance(WelcomeOverlay);
}
welcomeOverlay.show();
return Promise.resolve();
}
}
export class HideWelcomeOverlayAction extends Action {
public static readonly ID = 'workbench.action.hideInterfaceOverview';
public static readonly LABEL = localize('hideWelcomeOverlay', "Hide Interface Overview");
constructor(
id: string,
label: string
) {
super(id, label);
}
public run(): Promise<void> {
if (welcomeOverlay) {
welcomeOverlay.hide();
}
return Promise.resolve();
}
}
class WelcomeOverlay extends Disposable {
private _overlayVisible: IContextKey<boolean>;
private _overlay!: HTMLElement;
constructor(
@ILayoutService private readonly layoutService: ILayoutService,
@IEditorService private readonly editorService: IEditorService,
@ICommandService private readonly commandService: ICommandService,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
@IKeybindingService private readonly keybindingService: IKeybindingService
) {
super();
this._overlayVisible = OVERLAY_VISIBLE.bindTo(this._contextKeyService);
this.create();
}
private create(): void {
const offset = this.layoutService.offset?.top ?? 0;
this._overlay = dom.append(this.layoutService.container, $('.welcomeOverlay'));
this._overlay.style.top = `${offset}px`;
this._overlay.style.height = `calc(100% - ${offset}px)`;
this._overlay.style.display = 'none';
this._overlay.tabIndex = -1;
this._register(dom.addStandardDisposableListener(this._overlay, 'click', () => this.hide()));
this.commandService.onWillExecuteCommand(() => this.hide());
dom.append(this._overlay, $('.commandPalettePlaceholder'));
const editorOpen = !!this.editorService.visibleEditors.length;
keys.filter(key => !('withEditor' in key) || key.withEditor === editorOpen)
.forEach(({ id, arrow, label, command, arrowLast }) => {
const div = dom.append(this._overlay, $(`.key.${id}`));
if (arrow && !arrowLast) {
dom.append(div, $('span.arrow')).innerHTML = arrow;
}
dom.append(div, $('span.label')).textContent = label;
if (command) {
const shortcut = this.keybindingService.lookupKeybinding(command);
if (shortcut) {
dom.append(div, $('span.shortcut')).textContent = shortcut.getLabel();
}
}
if (arrow && arrowLast) {
dom.append(div, $('span.arrow')).innerHTML = arrow;
}
});
}
public show() {
if (this._overlay.style.display !== 'block') {
this._overlay.style.display = 'block';
const workbench = document.querySelector('.monaco-workbench') as HTMLElement;
dom.addClass(workbench, 'blur-background');
this._overlayVisible.set(true);
this.updateProblemsKey();
this.updateActivityBarKeys();
this._overlay.focus();
}
}
private updateProblemsKey() {
const problems = document.querySelector('div[id="workbench.parts.statusbar"] .statusbar-item.left .codicon.codicon-warning');
const key = this._overlay.querySelector('.key.problems') as HTMLElement;
if (problems instanceof HTMLElement) {
const target = problems.getBoundingClientRect();
const bounds = this._overlay.getBoundingClientRect();
const bottom = bounds.bottom - target.top + 3;
const left = (target.left + target.right) / 2 - bounds.left;
key.style.bottom = bottom + 'px';
key.style.left = left + 'px';
} else {
key.style.bottom = '';
key.style.left = '';
}
}
private updateActivityBarKeys() {
const ids = ['explorer', 'search', 'git', 'debug', 'extensions'];
const activityBar = document.querySelector('.activitybar .composite-bar');
if (activityBar instanceof HTMLElement) {
const target = activityBar.getBoundingClientRect();
const bounds = this._overlay.getBoundingClientRect();
for (let i = 0; i < ids.length; i++) {
const key = this._overlay.querySelector(`.key.${ids[i]}`) as HTMLElement;
const top = target.top - bounds.top + 50 * i + 13;
key.style.top = top + 'px';
}
} else {
for (let i = 0; i < ids.length; i++) {
const key = this._overlay.querySelector(`.key.${ids[i]}`) as HTMLElement;
key.style.top = '';
}
}
}
public hide() {
if (this._overlay.style.display !== 'none') {
this._overlay.style.display = 'none';
const workbench = document.querySelector('.monaco-workbench') as HTMLElement;
dom.removeClass(workbench, 'blur-background');
this._overlayVisible.reset();
}
}
}
Registry.as<IWorkbenchActionRegistry>(Extensions.WorkbenchActions)
.registerWorkbenchAction(SyncActionDescriptor.create(WelcomeOverlayAction, WelcomeOverlayAction.ID, WelcomeOverlayAction.LABEL), 'Help: User Interface Overview', localize('help', "Help"));
Registry.as<IWorkbenchActionRegistry>(Extensions.WorkbenchActions)
.registerWorkbenchAction(SyncActionDescriptor.create(HideWelcomeOverlayAction, HideWelcomeOverlayAction.ID, HideWelcomeOverlayAction.LABEL, { primary: KeyCode.Escape }, OVERLAY_VISIBLE), 'Help: Hide Interface Overview', localize('help', "Help"));
// theming
registerThemingParticipant((theme, collector) => {
const key = theme.getColor(foreground);
if (key) {
collector.addRule(`.monaco-workbench > .welcomeOverlay > .key { color: ${key}; }`);
}
const backgroundColor = Color.fromHex(theme.type === 'light' ? '#FFFFFF85' : '#00000085');
if (backgroundColor) {
collector.addRule(`.monaco-workbench > .welcomeOverlay { background: ${backgroundColor}; }`);
}
const shortcut = theme.getColor(textPreformatForeground);
if (shortcut) {
collector.addRule(`.monaco-workbench > .welcomeOverlay > .key > .shortcut { color: ${shortcut}; }`);
}
});
| src/vs/workbench/contrib/welcome/overlay/browser/welcomeOverlay.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017818922060541809,
0.0001721461594570428,
0.00016502925427630544,
0.00017250361270271242,
0.0000037443712699314347
] |
{
"id": 13,
"code_window": [
"\t\tif (!this._textEditor) {\n",
"\t\t\treturn 0;\n",
"\t\t}\n",
"\n",
"\t\treturn this._textEditor.getTopForLineNumber(line);\n",
"\t}\n",
"\n",
"\taddDecoration(decoration: model.IModelDeltaDecoration): string {\n",
"\t\tif (!this._textEditor) {\n",
"\t\t\tconst id = ++this._lastDecorationId;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this._textEditor.getTopForLineNumber(line) + EDITOR_TOP_PADDING + EDITOR_TOOLBAR_HEIGHT;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel.ts",
"type": "replace",
"edit_start_line_idx": 348
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as fs from 'fs';
import * as crypto from 'crypto';
import * as path from 'vs/base/common/path';
import * as platform from 'vs/base/common/platform';
import { writeFileSync, writeFile, readFile, readdir, exists, rimraf, rename, RimRafMode } from 'vs/base/node/pfs';
import * as arrays from 'vs/base/common/arrays';
import { IBackupMainService, IWorkspaceBackupInfo } from 'vs/platform/backup/electron-main/backup';
import { IBackupWorkspacesFormat, IEmptyWindowBackupInfo } from 'vs/platform/backup/node/backup';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IFilesConfiguration, HotExitConfiguration } from 'vs/platform/files/common/files';
import { ILogService } from 'vs/platform/log/common/log';
import { IWorkspaceIdentifier, isWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { URI } from 'vs/base/common/uri';
import { isEqual as areResourcesEquals, getComparisonKey, hasToIgnoreCase } from 'vs/base/common/resources';
import { isEqual } from 'vs/base/common/extpath';
import { Schemas } from 'vs/base/common/network';
export class BackupMainService implements IBackupMainService {
_serviceBrand: undefined;
protected backupHome: string;
protected workspacesJsonPath: string;
private rootWorkspaces: IWorkspaceBackupInfo[] = [];
private folderWorkspaces: URI[] = [];
private emptyWorkspaces: IEmptyWindowBackupInfo[] = [];
constructor(
@IEnvironmentService environmentService: IEnvironmentService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ILogService private readonly logService: ILogService
) {
this.backupHome = environmentService.backupHome.fsPath;
this.workspacesJsonPath = environmentService.backupWorkspacesPath;
}
async initialize(): Promise<void> {
let backups: IBackupWorkspacesFormat;
try {
backups = JSON.parse(await readFile(this.workspacesJsonPath, 'utf8')); // invalid JSON or permission issue can happen here
} catch (error) {
backups = Object.create(null);
}
// read empty workspaces backups first
if (backups.emptyWorkspaceInfos) {
this.emptyWorkspaces = await this.validateEmptyWorkspaces(backups.emptyWorkspaceInfos);
} else if (Array.isArray(backups.emptyWorkspaces)) {
// read legacy entries
this.emptyWorkspaces = await this.validateEmptyWorkspaces(backups.emptyWorkspaces.map(backupFolder => ({ backupFolder })));
}
// read workspace backups
let rootWorkspaces: IWorkspaceBackupInfo[] = [];
try {
if (Array.isArray(backups.rootURIWorkspaces)) {
rootWorkspaces = backups.rootURIWorkspaces.map(f => ({ workspace: { id: f.id, configPath: URI.parse(f.configURIPath) }, remoteAuthority: f.remoteAuthority }));
} else if (Array.isArray(backups.rootWorkspaces)) {
rootWorkspaces = backups.rootWorkspaces.map(f => ({ workspace: { id: f.id, configPath: URI.file(f.configPath) } }));
}
} catch (e) {
// ignore URI parsing exceptions
}
this.rootWorkspaces = await this.validateWorkspaces(rootWorkspaces);
// read folder backups
let workspaceFolders: URI[] = [];
try {
if (Array.isArray(backups.folderURIWorkspaces)) {
workspaceFolders = backups.folderURIWorkspaces.map(f => URI.parse(f));
} else if (Array.isArray(backups.folderWorkspaces)) {
// migrate legacy folder paths
workspaceFolders = [];
for (const folderPath of backups.folderWorkspaces) {
const oldFolderHash = this.getLegacyFolderHash(folderPath);
const folderUri = URI.file(folderPath);
const newFolderHash = this.getFolderHash(folderUri);
if (newFolderHash !== oldFolderHash) {
await this.moveBackupFolder(this.getBackupPath(newFolderHash), this.getBackupPath(oldFolderHash));
}
workspaceFolders.push(folderUri);
}
}
} catch (e) {
// ignore URI parsing exceptions
}
this.folderWorkspaces = await this.validateFolders(workspaceFolders);
// save again in case some workspaces or folders have been removed
await this.save();
}
getWorkspaceBackups(): IWorkspaceBackupInfo[] {
if (this.isHotExitOnExitAndWindowClose()) {
// Only non-folder windows are restored on main process launch when
// hot exit is configured as onExitAndWindowClose.
return [];
}
return this.rootWorkspaces.slice(0); // return a copy
}
getFolderBackupPaths(): URI[] {
if (this.isHotExitOnExitAndWindowClose()) {
// Only non-folder windows are restored on main process launch when
// hot exit is configured as onExitAndWindowClose.
return [];
}
return this.folderWorkspaces.slice(0); // return a copy
}
isHotExitEnabled(): boolean {
return this.getHotExitConfig() !== HotExitConfiguration.OFF;
}
private isHotExitOnExitAndWindowClose(): boolean {
return this.getHotExitConfig() === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE;
}
private getHotExitConfig(): string {
const config = this.configurationService.getValue<IFilesConfiguration>();
return config?.files?.hotExit || HotExitConfiguration.ON_EXIT;
}
getEmptyWindowBackupPaths(): IEmptyWindowBackupInfo[] {
return this.emptyWorkspaces.slice(0); // return a copy
}
registerWorkspaceBackupSync(workspaceInfo: IWorkspaceBackupInfo, migrateFrom?: string): string {
if (!this.rootWorkspaces.some(window => workspaceInfo.workspace.id === window.workspace.id)) {
this.rootWorkspaces.push(workspaceInfo);
this.saveSync();
}
const backupPath = this.getBackupPath(workspaceInfo.workspace.id);
if (migrateFrom) {
this.moveBackupFolderSync(backupPath, migrateFrom);
}
return backupPath;
}
private moveBackupFolderSync(backupPath: string, moveFromPath: string): void {
// Target exists: make sure to convert existing backups to empty window backups
if (fs.existsSync(backupPath)) {
this.convertToEmptyWindowBackupSync(backupPath);
}
// When we have data to migrate from, move it over to the target location
if (fs.existsSync(moveFromPath)) {
try {
fs.renameSync(moveFromPath, backupPath);
} catch (ex) {
this.logService.error(`Backup: Could not move backup folder to new location: ${ex.toString()}`);
}
}
}
private async moveBackupFolder(backupPath: string, moveFromPath: string): Promise<void> {
// Target exists: make sure to convert existing backups to empty window backups
if (await exists(backupPath)) {
await this.convertToEmptyWindowBackup(backupPath);
}
// When we have data to migrate from, move it over to the target location
if (await exists(moveFromPath)) {
try {
await rename(moveFromPath, backupPath);
} catch (ex) {
this.logService.error(`Backup: Could not move backup folder to new location: ${ex.toString()}`);
}
}
}
unregisterWorkspaceBackupSync(workspace: IWorkspaceIdentifier): void {
const id = workspace.id;
let index = arrays.firstIndex(this.rootWorkspaces, w => w.workspace.id === id);
if (index !== -1) {
this.rootWorkspaces.splice(index, 1);
this.saveSync();
}
}
registerFolderBackupSync(folderUri: URI): string {
if (!this.folderWorkspaces.some(uri => areResourcesEquals(folderUri, uri))) {
this.folderWorkspaces.push(folderUri);
this.saveSync();
}
return this.getBackupPath(this.getFolderHash(folderUri));
}
unregisterFolderBackupSync(folderUri: URI): void {
let index = arrays.firstIndex(this.folderWorkspaces, uri => areResourcesEquals(folderUri, uri));
if (index !== -1) {
this.folderWorkspaces.splice(index, 1);
this.saveSync();
}
}
registerEmptyWindowBackupSync(backupFolderCandidate?: string, remoteAuthority?: string): string {
// Generate a new folder if this is a new empty workspace
const backupFolder = backupFolderCandidate || this.getRandomEmptyWindowId();
if (!this.emptyWorkspaces.some(window => !!window.backupFolder && isEqual(window.backupFolder, backupFolder, !platform.isLinux))) {
this.emptyWorkspaces.push({ backupFolder, remoteAuthority });
this.saveSync();
}
return this.getBackupPath(backupFolder);
}
unregisterEmptyWindowBackupSync(backupFolder: string): void {
let index = arrays.firstIndex(this.emptyWorkspaces, w => !!w.backupFolder && isEqual(w.backupFolder, backupFolder, !platform.isLinux));
if (index !== -1) {
this.emptyWorkspaces.splice(index, 1);
this.saveSync();
}
}
private getBackupPath(oldFolderHash: string): string {
return path.join(this.backupHome, oldFolderHash);
}
private async validateWorkspaces(rootWorkspaces: IWorkspaceBackupInfo[]): Promise<IWorkspaceBackupInfo[]> {
if (!Array.isArray(rootWorkspaces)) {
return [];
}
const seenIds: Set<string> = new Set();
const result: IWorkspaceBackupInfo[] = [];
// Validate Workspaces
for (let workspaceInfo of rootWorkspaces) {
const workspace = workspaceInfo.workspace;
if (!isWorkspaceIdentifier(workspace)) {
return []; // wrong format, skip all entries
}
if (!seenIds.has(workspace.id)) {
seenIds.add(workspace.id);
const backupPath = this.getBackupPath(workspace.id);
const hasBackups = await this.hasBackups(backupPath);
// If the workspace has no backups, ignore it
if (hasBackups) {
if (workspace.configPath.scheme !== Schemas.file || await exists(workspace.configPath.fsPath)) {
result.push(workspaceInfo);
} else {
// If the workspace has backups, but the target workspace is missing, convert backups to empty ones
await this.convertToEmptyWindowBackup(backupPath);
}
} else {
await this.deleteStaleBackup(backupPath);
}
}
}
return result;
}
private async validateFolders(folderWorkspaces: URI[]): Promise<URI[]> {
if (!Array.isArray(folderWorkspaces)) {
return [];
}
const result: URI[] = [];
const seenIds: Set<string> = new Set();
for (let folderURI of folderWorkspaces) {
const key = getComparisonKey(folderURI);
if (!seenIds.has(key)) {
seenIds.add(key);
const backupPath = this.getBackupPath(this.getFolderHash(folderURI));
const hasBackups = await this.hasBackups(backupPath);
// If the folder has no backups, ignore it
if (hasBackups) {
if (folderURI.scheme !== Schemas.file || await exists(folderURI.fsPath)) {
result.push(folderURI);
} else {
// If the folder has backups, but the target workspace is missing, convert backups to empty ones
await this.convertToEmptyWindowBackup(backupPath);
}
} else {
await this.deleteStaleBackup(backupPath);
}
}
}
return result;
}
private async validateEmptyWorkspaces(emptyWorkspaces: IEmptyWindowBackupInfo[]): Promise<IEmptyWindowBackupInfo[]> {
if (!Array.isArray(emptyWorkspaces)) {
return [];
}
const result: IEmptyWindowBackupInfo[] = [];
const seenIds: Set<string> = new Set();
// Validate Empty Windows
for (let backupInfo of emptyWorkspaces) {
const backupFolder = backupInfo.backupFolder;
if (typeof backupFolder !== 'string') {
return [];
}
if (!seenIds.has(backupFolder)) {
seenIds.add(backupFolder);
const backupPath = this.getBackupPath(backupFolder);
if (await this.hasBackups(backupPath)) {
result.push(backupInfo);
} else {
await this.deleteStaleBackup(backupPath);
}
}
}
return result;
}
private async deleteStaleBackup(backupPath: string): Promise<void> {
try {
if (await exists(backupPath)) {
await rimraf(backupPath, RimRafMode.MOVE);
}
} catch (ex) {
this.logService.error(`Backup: Could not delete stale backup: ${ex.toString()}`);
}
}
private async convertToEmptyWindowBackup(backupPath: string): Promise<boolean> {
// New empty window backup
let newBackupFolder = this.getRandomEmptyWindowId();
while (this.emptyWorkspaces.some(window => !!window.backupFolder && isEqual(window.backupFolder, newBackupFolder, platform.isLinux))) {
newBackupFolder = this.getRandomEmptyWindowId();
}
// Rename backupPath to new empty window backup path
const newEmptyWindowBackupPath = this.getBackupPath(newBackupFolder);
try {
await rename(backupPath, newEmptyWindowBackupPath);
} catch (ex) {
this.logService.error(`Backup: Could not rename backup folder: ${ex.toString()}`);
return false;
}
this.emptyWorkspaces.push({ backupFolder: newBackupFolder });
return true;
}
private convertToEmptyWindowBackupSync(backupPath: string): boolean {
// New empty window backup
let newBackupFolder = this.getRandomEmptyWindowId();
while (this.emptyWorkspaces.some(window => !!window.backupFolder && isEqual(window.backupFolder, newBackupFolder, platform.isLinux))) {
newBackupFolder = this.getRandomEmptyWindowId();
}
// Rename backupPath to new empty window backup path
const newEmptyWindowBackupPath = this.getBackupPath(newBackupFolder);
try {
fs.renameSync(backupPath, newEmptyWindowBackupPath);
} catch (ex) {
this.logService.error(`Backup: Could not rename backup folder: ${ex.toString()}`);
return false;
}
this.emptyWorkspaces.push({ backupFolder: newBackupFolder });
return true;
}
private async hasBackups(backupPath: string): Promise<boolean> {
try {
const backupSchemas = await readdir(backupPath);
for (const backupSchema of backupSchemas) {
try {
const backupSchemaChildren = await readdir(path.join(backupPath, backupSchema));
if (backupSchemaChildren.length > 0) {
return true;
}
} catch (error) {
// invalid folder
}
}
} catch (error) {
// backup path does not exist
}
return false;
}
private saveSync(): void {
try {
writeFileSync(this.workspacesJsonPath, JSON.stringify(this.serializeBackups()));
} catch (ex) {
this.logService.error(`Backup: Could not save workspaces.json: ${ex.toString()}`);
}
}
private async save(): Promise<void> {
try {
await writeFile(this.workspacesJsonPath, JSON.stringify(this.serializeBackups()));
} catch (ex) {
this.logService.error(`Backup: Could not save workspaces.json: ${ex.toString()}`);
}
}
private serializeBackups(): IBackupWorkspacesFormat {
return {
rootURIWorkspaces: this.rootWorkspaces.map(f => ({ id: f.workspace.id, configURIPath: f.workspace.configPath.toString(), remoteAuthority: f.remoteAuthority })),
folderURIWorkspaces: this.folderWorkspaces.map(f => f.toString()),
emptyWorkspaceInfos: this.emptyWorkspaces,
emptyWorkspaces: this.emptyWorkspaces.map(info => info.backupFolder)
};
}
private getRandomEmptyWindowId(): string {
return (Date.now() + Math.round(Math.random() * 1000)).toString();
}
protected getFolderHash(folderUri: URI): string {
let key: string;
if (folderUri.scheme === Schemas.file) {
// for backward compatibility, use the fspath as key
key = platform.isLinux ? folderUri.fsPath : folderUri.fsPath.toLowerCase();
} else {
key = hasToIgnoreCase(folderUri) ? folderUri.toString().toLowerCase() : folderUri.toString();
}
return crypto.createHash('md5').update(key).digest('hex');
}
protected getLegacyFolderHash(folderPath: string): string {
return crypto.createHash('md5').update(platform.isLinux ? folderPath : folderPath.toLowerCase()).digest('hex');
}
}
| src/vs/platform/backup/electron-main/backupMainService.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0025708191096782684,
0.00022364103642757982,
0.00016582106763962656,
0.00017145214951597154,
0.0003499069716781378
] |
{
"id": 13,
"code_window": [
"\t\tif (!this._textEditor) {\n",
"\t\t\treturn 0;\n",
"\t\t}\n",
"\n",
"\t\treturn this._textEditor.getTopForLineNumber(line);\n",
"\t}\n",
"\n",
"\taddDecoration(decoration: model.IModelDeltaDecoration): string {\n",
"\t\tif (!this._textEditor) {\n",
"\t\t\tconst id = ++this._lastDecorationId;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this._textEditor.getTopForLineNumber(line) + EDITOR_TOP_PADDING + EDITOR_TOOLBAR_HEIGHT;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel.ts",
"type": "replace",
"edit_start_line_idx": 348
} | /*---------------------------------------------------------------------------------------------
* 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 { keychain } from './common/keychain';
import { GitHubServer } from './githubServer';
import Logger from './common/logger';
export const onDidChangeSessions = new vscode.EventEmitter<void>();
interface SessionData {
id: string;
accountName: string;
scopes: string[];
accessToken: string;
}
export class GitHubAuthenticationProvider {
private _sessions: vscode.AuthenticationSession[] = [];
private _githubServer = new GitHubServer();
public async initialize(): Promise<void> {
this._sessions = await this.readSessions();
this.pollForChange();
}
private pollForChange() {
setTimeout(async () => {
const storedSessions = await this.readSessions();
let didChange = false;
storedSessions.forEach(session => {
const matchesExisting = this._sessions.some(s => s.id === session.id);
// Another window added a session to the keychain, add it to our state as well
if (!matchesExisting) {
this._sessions.push(session);
didChange = true;
}
});
this._sessions.map(session => {
const matchesExisting = storedSessions.some(s => s.id === session.id);
// Another window has logged out, remove from our state
if (!matchesExisting) {
const sessionIndex = this._sessions.findIndex(s => s.id === session.id);
if (sessionIndex > -1) {
this._sessions.splice(sessionIndex, 1);
}
didChange = true;
}
});
if (didChange) {
onDidChangeSessions.fire();
}
this.pollForChange();
}, 1000 * 30);
}
private async readSessions(): Promise<vscode.AuthenticationSession[]> {
const storedSessions = await keychain.getToken();
if (storedSessions) {
try {
const sessionData: SessionData[] = JSON.parse(storedSessions);
return sessionData.map(session => {
return {
id: session.id,
accountName: session.accountName,
scopes: session.scopes,
getAccessToken: () => Promise.resolve(session.accessToken)
};
});
} catch (e) {
Logger.error(`Error reading sessions: ${e}`);
}
}
return [];
}
private async storeSessions(): Promise<void> {
const sessionData: SessionData[] = await Promise.all(this._sessions.map(async session => {
const resolvedAccessToken = await session.getAccessToken();
return {
id: session.id,
accountName: session.accountName,
scopes: session.scopes,
accessToken: resolvedAccessToken
};
}));
await keychain.setToken(JSON.stringify(sessionData));
}
get sessions(): vscode.AuthenticationSession[] {
return this._sessions;
}
public async login(scopes: string): Promise<vscode.AuthenticationSession> {
const token = await this._githubServer.login(scopes);
const session = await this.tokenToSession(token, scopes.split(' '));
await this.setToken(session);
return session;
}
private async tokenToSession(token: string, scopes: string[]): Promise<vscode.AuthenticationSession> {
const userInfo = await this._githubServer.getUserInfo(token);
return {
id: userInfo.id,
getAccessToken: () => Promise.resolve(token),
accountName: userInfo.accountName,
scopes: scopes
};
}
private async setToken(session: vscode.AuthenticationSession): Promise<void> {
const sessionIndex = this._sessions.findIndex(s => s.id === session.id);
if (sessionIndex > -1) {
this._sessions.splice(sessionIndex, 1, session);
} else {
this._sessions.push(session);
}
this.storeSessions();
}
public async logout(id: string) {
const sessionIndex = this._sessions.findIndex(session => session.id === id);
if (sessionIndex > -1) {
this._sessions.splice(sessionIndex, 1);
}
this.storeSessions();
}
}
| extensions/github-authentication/src/github.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0017378664342686534,
0.00028312343056313694,
0.00016847562801558524,
0.00017056716023944318,
0.0004034807498101145
] |
{
"id": 0,
"code_window": [
"\tfocus(): void {\n",
"\t\tthis._onFocus.fire();\n",
"\t}\n",
"\n",
"\tlayout(width: number): void {\n",
"\t\tif (width < 400) {\n",
"\t\t\tthis.class = 'markers-panel-action-filter small';\n",
"\t\t} else {\n",
"\t\t\tthis.class = 'markers-panel-action-filter';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (width > 600) {\n",
"\t\t\tthis.class = 'markers-panel-action-filter grow';\n",
"\t\t} else if (width < 400) {\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 118
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-action-bar .action-item.markers-panel-action-filter-container {
flex: 1;
cursor: default;
display: flex;
}
.monaco-action-bar .markers-panel-action-filter {
display: flex;
align-items: center;
flex: 1;
}
.monaco-action-bar .markers-panel-action-filter .monaco-inputbox {
height: 24px;
font-size: 12px;
flex: 1;
}
.vs .monaco-action-bar .markers-panel-action-filter .monaco-inputbox {
height: 25px;
border: 1px solid transparent;
}
.markers-panel-action-filter > .markers-panel-filter-controls {
position: absolute;
top: 0px;
bottom: 0;
right: 4px;
display: flex;
align-items: center;
}
.markers-panel-action-filter > .markers-panel-filter-controls > .markers-panel-filter-badge {
margin: 4px 0px;
padding: 0px 8px;
border-radius: 2px;
}
.markers-panel-action-filter > .markers-panel-filter-controls > .markers-panel-filter-badge.hidden,
.markers-panel-action-filter.small > .markers-panel-filter-controls > .markers-panel-filter-badge {
display: none;
}
.panel > .title .monaco-action-bar .action-item.markers-panel-action-filter-container {
max-width: 600px;
min-width: 300px;
margin-right: 10px;
}
.markers-panel .markers-panel-container {
height: 100%;
}
.markers-panel .hide {
display: none;
}
.markers-panel-container .monaco-action-bar.markers-panel-filter-container {
margin: 10px 20px;
}
.markers-panel .markers-panel-container .message-box-container {
line-height: 22px;
padding-left: 20px;
height: 100%;
}
.markers-panel .markers-panel-container .message-box-container .messageAction {
margin-left: 4px;
cursor: pointer;
text-decoration: underline;
}
.markers-panel .markers-panel-container .hidden {
display: none;
}
.markers-panel .markers-panel-container .tree-container.hidden {
display: none;
visibility: hidden;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents {
display: flex;
line-height: 22px;
padding-right: 10px;
}
.hc-black .markers-panel .markers-panel-container .tree-container .monaco-tl-contents {
line-height: 20px;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-stats {
display: inline-block;
margin-left: 10px;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .count-badge-wrapper {
margin-left: 10px;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-message-details-container {
flex: 1;
overflow: hidden;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-message-details-container > .marker-message-line {
overflow: hidden;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-message-details-container > .marker-message-line > .marker-message {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-message-details-container > .marker-message-line.details-container {
display: flex;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-code:before {
content: '(';
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-code:after {
content: ')';
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .details-container .marker-source,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .details-container .marker-line {
margin-left: 6px;
}
.markers-panel .monaco-tl-contents .marker-icon {
margin-right: 6px;
display: flex;
align-items: center;
justify-content: center;
}
.markers-panel .monaco-tl-contents .actions .action-item {
margin-right: 2px;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-source,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .related-info-resource,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .related-info-resource-separator,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-line,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-code {
opacity: 0.7;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .highlight {
font-weight: bold;
}
.markers-panel .monaco-tl-contents .marker-icon {
height: 22px;
}
.markers-panel .monaco-tl-contents .actions .monaco-action-bar {
display: none;
}
.markers-panel .monaco-list-row:hover .monaco-tl-contents > .marker-icon.quickFix,
.markers-panel .monaco-list-row.selected .monaco-tl-contents > .marker-icon.quickFix,
.markers-panel .monaco-list-row.focused .monaco-tl-contents > .marker-icon.quickFix {
display: none;
}
.markers-panel .monaco-list-row:hover .monaco-tl-contents .actions .monaco-action-bar,
.markers-panel .monaco-list-row.selected .monaco-tl-contents .actions .monaco-action-bar,
.markers-panel .monaco-list-row.focused .monaco-tl-contents .actions .monaco-action-bar {
display: block;
}
.markers-panel .monaco-tl-contents .multiline-actions .action-label,
.markers-panel .monaco-tl-contents .actions .action-label {
width: 16px;
height: 100%;
background-position: 50% 50%;
background-repeat: no-repeat;
}
.markers-panel .monaco-tl-contents .multiline-actions .action-label {
line-height: 22px;
}
.markers-panel .monaco-tl-contents .multiline-actions .action-item.disabled,
.markers-panel .monaco-tl-contents .actions .action-item.disabled {
display: none;
}
| src/vs/workbench/contrib/markers/browser/media/markers.css | 1 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00065355293918401,
0.0002480359689798206,
0.00016837734438013285,
0.00018581640324555337,
0.0001310294319409877
] |
{
"id": 0,
"code_window": [
"\tfocus(): void {\n",
"\t\tthis._onFocus.fire();\n",
"\t}\n",
"\n",
"\tlayout(width: number): void {\n",
"\t\tif (width < 400) {\n",
"\t\t\tthis.class = 'markers-panel-action-filter small';\n",
"\t\t} else {\n",
"\t\t\tthis.class = 'markers-panel-action-filter';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (width > 600) {\n",
"\t\t\tthis.class = 'markers-panel-action-filter grow';\n",
"\t\t} else if (width < 400) {\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 118
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* Interface types for Monarch language definitions
* These descriptions are really supposed to be JSON values but if using typescript
* to describe them, these type definitions can help check the validity.
*/
/**
* A Monarch language definition
*/
export interface IMonarchLanguage {
/**
* map from string to ILanguageRule[]
*/
tokenizer: { [name: string]: IMonarchLanguageRule[] };
/**
* is the language case insensitive?
*/
ignoreCase?: boolean;
/**
* if no match in the tokenizer assign this token class (default 'source')
*/
defaultToken?: string;
/**
* for example [['{','}','delimiter.curly']]
*/
brackets?: IMonarchLanguageBracket[];
/**
* start symbol in the tokenizer (by default the first entry is used)
*/
start?: string;
/**
* attach this to every token class (by default '.' + name)
*/
tokenPostfix?: string;
}
/**
* A rule is either a regular expression and an action
* shorthands: [reg,act] == { regex: reg, action: act}
* and : [reg,act,nxt] == { regex: reg, action: act{ next: nxt }}
*/
export type IShortMonarchLanguageRule1 = [RegExp, IMonarchLanguageAction];
export type IShortMonarchLanguageRule2 = [RegExp, IMonarchLanguageAction, string];
export interface IExpandedMonarchLanguageRule {
/**
* match tokens
*/
regex?: string | RegExp;
/**
* action to take on match
*/
action?: IMonarchLanguageAction;
/**
* or an include rule. include all rules from the included state
*/
include?: string;
}
export type IMonarchLanguageRule = IShortMonarchLanguageRule1
| IShortMonarchLanguageRule2
| IExpandedMonarchLanguageRule;
/**
* An action is either an array of actions...
* ... or a case statement with guards...
* ... or a basic action with a token value.
*/
export type IShortMonarchLanguageAction = string;
export interface IExpandedMonarchLanguageAction {
/**
* array of actions for each parenthesized match group
*/
group?: IMonarchLanguageAction[];
/**
* map from string to ILanguageAction
*/
cases?: Object;
/**
* token class (ie. css class) (or "@brackets" or "@rematch")
*/
token?: string;
/**
* the next state to push, or "@push", "@pop", "@popall"
*/
next?: string;
/**
* switch to this state
*/
switchTo?: string;
/**
* go back n characters in the stream
*/
goBack?: number;
/**
* @open or @close
*/
bracket?: string;
/**
* switch to embedded language (using the mimetype) or get out using "@pop"
*/
nextEmbedded?: string;
/**
* log a message to the browser console window
*/
log?: string;
}
export type IMonarchLanguageAction = IShortMonarchLanguageAction
| IExpandedMonarchLanguageAction
| IShortMonarchLanguageAction[]
| IExpandedMonarchLanguageAction[];
/**
* This interface can be shortened as an array, ie. ['{','}','delimiter.curly']
*/
export interface IMonarchLanguageBracket {
/**
* open bracket
*/
open: string;
/**
* closing bracket
*/
close: string;
/**
* token class
*/
token: string;
} | src/vs/editor/standalone/common/monarch/monarchTypes.ts | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.0001980393280973658,
0.0001723522727843374,
0.00016477091412525624,
0.0001698884298093617,
0.000009208959454554133
] |
{
"id": 0,
"code_window": [
"\tfocus(): void {\n",
"\t\tthis._onFocus.fire();\n",
"\t}\n",
"\n",
"\tlayout(width: number): void {\n",
"\t\tif (width < 400) {\n",
"\t\t\tthis.class = 'markers-panel-action-filter small';\n",
"\t\t} else {\n",
"\t\t\tthis.class = 'markers-panel-action-filter';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (width > 600) {\n",
"\t\t\tthis.class = 'markers-panel-action-filter grow';\n",
"\t\t} else if (width < 400) {\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 118
} | <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M1.01087 2.5L1.51087 2H6.50713L6.86068 2.14645L7.71349 2.99925H14.5011L15.0011 3.49925V8.99512L14.9903 9.00599V13.5021L14.4903 14.0021H1.5L1 13.5021V6.50735L1.01087 6.49648V2.5ZM14.0011 3.99925V5.00311H7.5005L7.14695 5.14956L6.28915 6.00735H2.01087V3H6.30002L7.15283 3.8528L7.50638 3.99925H14.0011ZM6.49626 7.00735H2.01087V7.49588H1.99963V11.4929H2V13.0021H13.9903V11.4929H13.9906V7.49588H13.9903V6.00311H7.70761L6.84981 6.8609L6.49626 7.00735Z" fill="#424242"/>
</svg>
| extensions/theme-defaults/fileicons/images/folder-light.svg | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00016860643518157303,
0.00016860643518157303,
0.00016860643518157303,
0.00016860643518157303,
0
] |
{
"id": 0,
"code_window": [
"\tfocus(): void {\n",
"\t\tthis._onFocus.fire();\n",
"\t}\n",
"\n",
"\tlayout(width: number): void {\n",
"\t\tif (width < 400) {\n",
"\t\t\tthis.class = 'markers-panel-action-filter small';\n",
"\t\t} else {\n",
"\t\t\tthis.class = 'markers-panel-action-filter';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (width > 600) {\n",
"\t\t\tthis.class = 'markers-panel-action-filter grow';\n",
"\t\t} else if (width < 400) {\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 118
} | {
"information_for_contributors": [
"This file has been converted from https://github.com/Ikuyadeu/vscode-R/blob/master/syntax/r.json",
"If you want to provide a fix or improvement, please create a pull request against the original repository.",
"Once accepted there, we are happy to receive an update request."
],
"version": "https://github.com/Ikuyadeu/vscode-R/commit/1cd3d42a6b2e54276ef2d71fe33bb3fefb1d6cff",
"name": "R",
"scopeName": "source.r",
"patterns": [
{
"include": "#roxygen"
},
{
"include": "#comments"
},
{
"include": "#constants"
},
{
"include": "#keywords"
},
{
"include": "#storage-type"
},
{
"include": "#strings"
},
{
"include": "#brackets"
},
{
"include": "#function-declarations"
},
{
"include": "#lambda-functions"
},
{
"include": "#builtin-functions"
},
{
"include": "#function-calls"
},
{
"include": "#general-variables"
}
],
"repository": {
"comments": {
"patterns": [
{
"captures": {
"1": {
"name": "comment.line.pragma.r"
},
"2": {
"name": "entity.name.pragma.name.r"
}
},
"match": "^(#pragma[ \\t]+mark)[ \\t](.*)",
"name": "comment.line.pragma-mark.r"
},
{
"begin": "(^[ \\t]+)?(?=#)",
"beginCaptures": {
"1": {
"name": "punctuation.whitespace.comment.leading.r"
}
},
"end": "(?!\\G)",
"patterns": [
{
"begin": "#",
"beginCaptures": {
"0": {
"name": "punctuation.definition.comment.r"
}
},
"end": "\\n",
"name": "comment.line.number-sign.r"
}
]
}
]
},
"constants": {
"patterns": [
{
"match": "\\b(pi|letters|LETTERS|month\\.abb|month\\.name)\\b",
"name": "support.constant.misc.r"
},
{
"match": "\\b(TRUE|FALSE|NULL|NA|NA_integer_|NA_real_|NA_complex_|NA_character_|Inf|NaN)\\b",
"name": "constant.language.r"
},
{
"match": "\\b0(x|X)[0-9a-fA-F]+i\\b",
"name": "constant.numeric.imaginary.hexadecimal.r"
},
{
"match": "\\b[0-9]+\\.?[0-9]*(?:(e|E)(\\+|-)?[0-9]+)?i\\b",
"name": "constant.numeric.imaginary.decimal.r"
},
{
"match": "\\.[0-9]+(?:(e|E)(\\+|-)?[0-9]+)?i\\b",
"name": "constant.numeric.imaginary.decimal.r"
},
{
"match": "\\b0(x|X)[0-9a-fA-F]+L\\b",
"name": "constant.numeric.integer.hexadecimal.r"
},
{
"match": "\\b(?:[0-9]+\\.?[0-9]*)L\\b",
"name": "constant.numeric.integer.decimal.r"
},
{
"match": "\\b0(x|X)[0-9a-fA-F]+\\b",
"name": "constant.numeric.float.hexadecimal.r"
},
{
"match": "\\b[0-9]+\\.?[0-9]*(?:(e|E)(\\+|-)?[0-9]+)?\\b",
"name": "constant.numeric.float.decimal.r"
},
{
"match": "\\.[0-9]+(?:(e|E)(\\+|-)?[0-9]+)?\\b",
"name": "constant.numeric.float.decimal.r"
}
]
},
"general-variables": {
"patterns": [
{
"captures": {
"1": {
"name": "variable.parameter.r"
},
"2": {
"name": "keyword.operator.assignment.r"
}
},
"match": "([[:alpha:].][[:alnum:]._]*)\\s*(=)(?=[^=])"
},
{
"match": "\\b([\\d_][[:alnum:]._]+)\\b",
"name": "invalid.illegal.variable.other.r"
},
{
"match": "\\b([[:alnum:]_]+)(?=::)",
"name": "entity.namespace.r"
},
{
"match": "\\b([[:alnum:]._]+)\\b",
"name": "variable.other.r"
}
]
},
"keywords": {
"patterns": [
{
"match": "\\b(break|next|repeat|else|in)\\b",
"name": "keyword.control.r"
},
{
"match": "\\b(ifelse|if|for|return|switch|while|invisible)\\b(?=\\s*\\()",
"name": "keyword.control.r"
},
{
"match": "(\\-|\\+|\\*|\\/|%\\/%|%%|%\\*%|%o%|%x%|\\^)",
"name": "keyword.operator.arithmetic.r"
},
{
"match": "<=|>=",
"name": "keyword.operator.comparison.r"
},
{
"match": "==",
"name": "keyword.operator.comarison.r"
},
{
"match": "(:=|<-|<<-|->|->>)",
"name": "keyword.operator.assignment.r"
},
{
"match": "(!=|<>|<|>|%in%)",
"name": "keyword.operator.comparison.r"
},
{
"match": "(!|&{1,2}|[|]{1,2})",
"name": "keyword.operator.logical.r"
},
{
"match": "(%between%|%chin%|%like%|%\\+%|%\\+replace%|%:%|%do%|%dopar%|%>%|%<>%|%T>%|%\\$%)",
"name": "keyword.operator.other.r"
},
{
"match": "(\\.\\.\\.|\\$|:|\\~|@)",
"name": "keyword.other.r"
}
]
},
"storage-type": {
"patterns": [
{
"match": "\\b(character|complex|double|expression|integer|list|logical|numeric|single|raw)\\b(?=\\s*\\()",
"name": "storage.type.r"
}
]
},
"strings": {
"patterns": [
{
"begin": "\"",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.r"
}
},
"end": "\"",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.r"
}
},
"name": "string.quoted.double.r",
"patterns": [
{
"match": "\\\\.",
"name": "constant.character.escape.r"
}
]
},
{
"begin": "'",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.r"
}
},
"end": "'",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.r"
}
},
"name": "string.quoted.single.r",
"patterns": [
{
"match": "\\\\.",
"name": "constant.character.escape.r"
}
]
}
]
},
"brackets": {
"patterns": [
{
"begin": "\\(",
"beginCaptures": {
"0": {
"name": "punctuation.section.parens.begin.r"
}
},
"end": "\\)",
"endCaptures": {
"0": {
"name": "punctuation.section.parens.end.r"
}
},
"patterns": [
{
"include": "source.r"
}
]
},
{
"begin": "\\[(?!\\[)",
"beginCaptures": {
"0": {
"name": "punctuation.section.brackets.single.begin.r"
}
},
"end": "\\]",
"endCaptures": {
"0": {
"name": "punctuation.section.brackets.single.end.r"
}
},
"patterns": [
{
"include": "source.r"
}
]
},
{
"begin": "\\[\\[",
"beginCaptures": {
"0": {
"name": "punctuation.section.brackets.double.begin.r"
}
},
"end": "\\]\\]",
"endCaptures": {
"0": {
"name": "punctuation.section.brackets.double.end.r"
}
},
"contentName": "meta.item-access.arguments.r",
"patterns": [
{
"include": "source.r"
}
]
},
{
"begin": "\\{",
"beginCaptures": {
"0": {
"name": "punctuation.section.braces.begin.r"
}
},
"end": "\\}",
"endCaptures": {
"0": {
"name": "punctuation.section.braces.end.r"
}
},
"patterns": [
{
"include": "source.r"
}
]
}
]
},
"function-declarations": {
"patterns": [
{
"begin": "^\\s*([a-zA-Z._][\\w.:]*)\\s*(<<?-|=)\\s*(?=function\\s*\\()",
"beginCaptures": {
"1": {
"name": "entity.name.function.r"
},
"2": {
"name": "keyword.operator.assignment.r"
},
"3": {
"name": "keyword.control.r"
}
},
"end": "(?<=\\))",
"name": "meta.function.r",
"patterns": [
{
"include": "#lambda-functions"
}
]
}
]
},
"lambda-functions": {
"patterns": [
{
"begin": "\\b(function)\\s*(\\()",
"beginCaptures": {
"1": {
"name": "keyword.control.r"
},
"2": {
"name": "punctuation.section.parens.begin.r"
}
},
"end": "\\)",
"endCaptures": {
"0": {
"name": "punctuation.section.parens.end.r"
}
},
"name": "meta.function.r",
"contentName": "meta.function.parameters.r",
"patterns": [
{
"include": "#comments"
},
{
"match": "(?:[a-zA-Z._][\\w.]*|`[^`]+`)",
"name": "variable.parameter.r"
},
{
"begin": "(?==)",
"end": "(?=[,)])",
"patterns": [
{
"include": "source.r"
}
]
},
{
"match": ",",
"name": "punctuation.separator.parameters.r"
}
]
}
]
},
"function-calls": {
"begin": "(?:\\b|(?=\\.))((?:[a-zA-Z._][\\w.]*|`[^`]+`))\\s*(\\()",
"beginCaptures": {
"1": {
"name": "variable.function.r"
},
"2": {
"name": "punctuation.section.parens.begin.r"
}
},
"contentName": "meta.function-call.arguments.r",
"end": "(\\))",
"endCaptures": {
"1": {
"name": "punctuation.definition.parameters.r"
}
},
"name": "meta.function-call.r",
"patterns": [
{
"include": "#function-parameters"
}
]
},
"function-parameters": {
"patterns": [
{
"name": "meta.function-call.r",
"contentName": "meta.function-call.parameters.r"
},
{
"match": "(?:[a-zA-Z._][\\w.]*|`[^`]+`)(?=\\s[^=])",
"name": "variable.parameter.r"
},
{
"begin": "(?==)",
"end": "(?=[,)])",
"patterns": [
{
"include": "source.r"
}
]
},
{
"match": ",",
"name": "punctuation.separator.parameters.r"
},
{
"end": "\\)",
"endCaptures": {
"0": "punctuation.section.parens.end.r"
}
},
{
"include": "source.r"
}
]
},
"roxygen": {
"patterns": [
{
"begin": "^(#')\\s*",
"beginCaptures": {
"1": {
"name": "punctuation.definition.comment.r"
}
},
"end": "$\\n?",
"name": "comment.line.roxygen.r",
"patterns": [
{
"captures": {
"1": {
"name": "keyword.other.r"
},
"2": {
"name": "variable.parameter.r"
}
},
"match": "(@param)\\s*((?:[a-zA-Z._][\\w.]*|`[^`]+`))"
},
{
"match": "@[a-zA-Z0-9]+",
"name": "keyword.other.r"
}
]
}
]
},
"builtin-functions": {
"patterns": [
{
"match": "\\b(abbreviate|abs|acos|acosh|addNA|addTaskCallback|agrep|agrepl|alist|all|all\\.equal|all\\.equal.character|all\\.equal.default|all\\.equal.environment|all\\.equal.envRefClass|all\\.equal.factor|all\\.equal.formula|all\\.equal.language|all\\.equal.list|all\\.equal.numeric|all\\.equal.POSIXt|all\\.equal.raw|all\\.names|all\\.vars|any|anyDuplicated|anyDuplicated\\.array|anyDuplicated\\.data.frame|anyDuplicated\\.default|anyDuplicated\\.matrix|anyNA|anyNA\\.numeric_version|anyNA\\.POSIXlt|aperm|aperm\\.default|aperm\\.table|append|apply|Arg|args|array|arrayInd|as\\.array|as\\.array.default|as\\.call|as\\.character|as\\.character.condition|as\\.character.Date|as\\.character.default|as\\.character.error|as\\.character.factor|as\\.character.hexmode|as\\.character.numeric_version|as\\.character.octmode|as\\.character.POSIXt|as\\.character.srcref|as\\.complex|as\\.data.frame|as\\.data.frame.array|as\\.data.frame.AsIs|as\\.data.frame.character|as\\.data.frame.complex|as\\.data.frame.data.frame|as\\.data.frame.Date|as\\.data.frame.default|as\\.data.frame.difftime|as\\.data.frame.factor|as\\.data.frame.integer|as\\.data.frame.list|as\\.data.frame.logical|as\\.data.frame.matrix|as\\.data.frame.model.matrix|as\\.data.frame.noquote|as\\.data.frame.numeric|as\\.data.frame.numeric_version|as\\.data.frame.ordered|as\\.data.frame.POSIXct|as\\.data.frame.POSIXlt|as\\.data.frame.raw|as\\.data.frame.table|as\\.data.frame.ts|as\\.data.frame.vector|as\\.Date|as\\.Date.character|as\\.Date.date|as\\.Date.dates|as\\.Date.default|as\\.Date.factor|as\\.Date.numeric|as\\.Date.POSIXct|as\\.Date.POSIXlt|as\\.difftime|as\\.double|as\\.double.difftime|as\\.double.POSIXlt|as\\.environment|as\\.expression|as\\.expression.default|as\\.factor|as\\.function|as\\.function.default|as\\.hexmode|as\\.integer|as\\.list|as\\.list.data.frame|as\\.list.Date|as\\.list.default|as\\.list.environment|as\\.list.factor|as\\.list.function|as\\.list.numeric_version|as\\.list.POSIXct|as\\.logical|as\\.logical.factor|as\\.matrix|as\\.matrix.data.frame|as\\.matrix.default|as\\.matrix.noquote|as\\.matrix.POSIXlt|as\\.name|as\\.null|as\\.null.default|as\\.numeric|as\\.numeric_version|as\\.octmode|as\\.ordered|as\\.package_version|as\\.pairlist|as\\.POSIXct|as\\.POSIXct.date|as\\.POSIXct.Date|as\\.POSIXct.dates|as\\.POSIXct.default|as\\.POSIXct.numeric|as\\.POSIXct.POSIXlt|as\\.POSIXlt|as\\.POSIXlt.character|as\\.POSIXlt.date|as\\.POSIXlt.Date|as\\.POSIXlt.dates|as\\.POSIXlt.default|as\\.POSIXlt.factor|as\\.POSIXlt.numeric|as\\.POSIXlt.POSIXct|as\\.qr|as\\.raw|as\\.single|as\\.single.default|as\\.symbol|as\\.table|as\\.table.default|as\\.vector|as\\.vector.factor|asin|asinh|asNamespace|asS3|asS4|assign|atan|atan2|atanh|attach|attachNamespace|attr|attr\\.all.equal|attributes|autoload|autoloader|backsolve|baseenv|basename|besselI|besselJ|besselK|besselY|beta|bindingIsActive|bindingIsLocked|bindtextdomain|bitwAnd|bitwNot|bitwOr|bitwShiftL|bitwShiftR|bitwXor|body|bquote|break|browser|browserCondition|browserSetDebug|browserText|builtins|by|by\\.data.frame|by\\.default|bzfile|c|c\\.Date|c\\.difftime|c\\.noquote|c\\.numeric_version|c\\.POSIXct|c\\.POSIXlt|c\\.warnings|call|callCC|capabilities|casefold|cat|cbind|cbind\\.data.frame|ceiling|char\\.expand|character|charmatch|charToRaw|chartr|check_tzones|chkDots|chol|chol\\.default|chol2inv|choose|class|clearPushBack|close|close\\.connection|close\\.srcfile|close\\.srcfilealias|closeAllConnections|col|colMeans|colnames|colSums|commandArgs|comment|complex|computeRestarts|conditionCall|conditionCall\\.condition|conditionMessage|conditionMessage\\.condition|conflicts|Conj|contributors|cos|cosh|cospi|crossprod|Cstack_info|cummax|cummin|cumprod|cumsum|curlGetHeaders|cut|cut\\.Date|cut\\.default|cut\\.POSIXt|data\\.class|data\\.frame|data\\.matrix|date|debug|debuggingState|debugonce|default\\.stringsAsFactors|delayedAssign|deparse|det|detach|determinant|determinant\\.matrix|dget|diag|diff|diff\\.Date|diff\\.default|diff\\.difftime|diff\\.POSIXt|difftime|digamma|dim|dim\\.data.frame|dimnames|dimnames\\.data.frame|dir|dir\\.create|dir\\.exists|dirname|do\\.call|dontCheck|double|dput|dQuote|drop|droplevels|droplevels\\.data.frame|droplevels\\.factor|dump|duplicated|duplicated\\.array|duplicated\\.data.frame|duplicated\\.default|duplicated\\.matrix|duplicated\\.numeric_version|duplicated\\.POSIXlt|duplicated\\.warnings|dyn\\.load|dyn\\.unload|dynGet|eapply|eigen|emptyenv|enc2native|enc2utf8|encodeString|Encoding|endsWith|enquote|env\\.profile|environment|environmentIsLocked|environmentName|eval|eval\\.parent|evalq|exists|exp|expand\\.grid|expm1|expression|extSoftVersion|factor|factorial|fifo|file|file\\.access|file\\.append|file\\.choose|file\\.copy|file\\.create|file\\.exists|file\\.info|file\\.link|file\\.mode|file\\.mtime|file\\.path|file\\.remove|file\\.rename|file\\.show|file\\.size|file\\.symlink|Filter|Find|find\\.package|findInterval|findPackageEnv|findRestart|floor|flush|flush\\.connection|for|force|forceAndCall|formals|format|format\\.AsIs|format\\.data.frame|format\\.Date|format\\.default|format\\.difftime|format\\.factor|format\\.hexmode|format\\.info|format\\.libraryIQR|format\\.numeric_version|format\\.octmode|format\\.packageInfo|format\\.POSIXct|format\\.POSIXlt|format\\.pval|format\\.summaryDefault|formatC|formatDL|forwardsolve|function|gamma|gc|gc\\.time|gcinfo|gctorture|gctorture2|get|get0|getAllConnections|getCallingDLL|getCallingDLLe|getConnection|getDLLRegisteredRoutines|getDLLRegisteredRoutines\\.character|getDLLRegisteredRoutines\\.DLLInfo|getElement|geterrmessage|getExportedValue|getHook|getLoadedDLLs|getNamespace|getNamespaceExports|getNamespaceImports|getNamespaceInfo|getNamespaceName|getNamespaceUsers|getNamespaceVersion|getNativeSymbolInfo|getOption|getRversion|getSrcLines|getTaskCallbackNames|gettext|gettextf|getwd|gl|globalenv|gregexpr|grep|grepl|grepRaw|grouping|gsub|gzcon|gzfile|I|iconv|iconvlist|icuGetCollate|icuSetCollate|identical|identity|if|ifelse|Im|importIntoEnv|inherits|integer|interaction|interactive|intersect|intToBits|intToUtf8|inverse\\.rle|invisible|invokeRestart|invokeRestartInteractively|is\\.array|is\\.atomic|is\\.call|is\\.character|is\\.complex|is\\.data.frame|is\\.double|is\\.element|is\\.environment|is\\.expression|is\\.factor|is\\.finite|is\\.function|is\\.infinite|is\\.integer|is\\.language|is\\.list|is\\.loaded|is\\.logical|is\\.matrix|is\\.na|is\\.na.data.frame|is\\.na.numeric_version|is\\.na.POSIXlt|is\\.name|is\\.nan|is\\.null|is\\.numeric|is\\.numeric_version|is\\.numeric.Date|is\\.numeric.difftime|is\\.numeric.POSIXt|is\\.object|is\\.ordered|is\\.package_version|is\\.pairlist|is\\.primitive|is\\.qr|is\\.R|is\\.raw|is\\.recursive|is\\.single|is\\.symbol|is\\.table|is\\.unsorted|is\\.vector|isatty|isBaseNamespace|isdebugged|isIncomplete|isNamespace|isNamespaceLoaded|ISOdate|ISOdatetime|isOpen|isRestart|isS4|isSeekable|isSymmetric|isSymmetric\\.matrix|isTRUE|jitter|julian|julian\\.Date|julian\\.POSIXt|kappa|kappa\\.default|kappa\\.lm|kappa\\.qr|kronecker|l10n_info|La_library|La_version|La\\.svd|labels|labels\\.default|lapply|lazyLoad|lazyLoadDBexec|lazyLoadDBfetch|lbeta|lchoose|length|length\\.POSIXlt|lengths|levels|levels\\.default|lfactorial|lgamma|libcurlVersion|library|library\\.dynam|library\\.dynam.unload|licence|license|list|list\\.dirs|list\\.files|list2env|load|loadedNamespaces|loadingNamespaceInfo|loadNamespace|local|lockBinding|lockEnvironment|log|log10|log1p|log2|logb|logical|lower\\.tri|ls|make\\.names|make\\.unique|makeActiveBinding|Map|mapply|margin\\.table|mat\\.or.vec|match|match\\.arg|match\\.call|match\\.fun|Math\\.data.frame|Math\\.Date|Math\\.difftime|Math\\.factor|Math\\.POSIXt|matrix|max|max\\.col|mean|mean\\.Date|mean\\.default|mean\\.difftime|mean\\.POSIXct|mean\\.POSIXlt|mem\\.limits|memCompress|memDecompress|memory\\.profile|merge|merge\\.data.frame|merge\\.default|message|mget|min|missing|Mod|mode|months|months\\.Date|months\\.POSIXt|names|names\\.POSIXlt|namespaceExport|namespaceImport|namespaceImportClasses|namespaceImportFrom|namespaceImportMethods|nargs|nchar|ncol|NCOL|Negate|new\\.env|next|NextMethod|ngettext|nlevels|noquote|norm|normalizePath|nrow|NROW|numeric|numeric_version|nzchar|objects|oldClass|OlsonNames|on\\.exit|open|open\\.connection|open\\.srcfile|open\\.srcfilealias|open\\.srcfilecopy|Ops\\.data.frame|Ops\\.Date|Ops\\.difftime|Ops\\.factor|Ops\\.numeric_version|Ops\\.ordered|Ops\\.POSIXt|options|order|ordered|outer|package_version|packageEvent|packageHasNamespace|packageStartupMessage|packBits|pairlist|parent\\.env|parent\\.frame|parse|parseNamespaceFile|paste|paste0|path\\.expand|path\\.package|pcre_config|pipe|pmatch|pmax|pmax\\.int|pmin|pmin\\.int|polyroot|pos\\.to.env|Position|pretty|pretty\\.default|prettyNum|print|print\\.AsIs|print\\.by|print\\.condition|print\\.connection|print\\.data.frame|print\\.Date|print\\.default|print\\.difftime|print\\.Dlist|print\\.DLLInfo|print\\.DLLInfoList|print\\.DLLRegisteredRoutines|print\\.eigen|print\\.factor|print\\.function|print\\.hexmode|print\\.libraryIQR|print\\.listof|print\\.NativeRoutineList|print\\.noquote|print\\.numeric_version|print\\.octmode|print\\.packageInfo|print\\.POSIXct|print\\.POSIXlt|print\\.proc_time|print\\.restart|print\\.rle|print\\.simple.list|print\\.srcfile|print\\.srcref|print\\.summary.table|print\\.summaryDefault|print\\.table|print\\.warnings|prmatrix|proc\\.time|prod|prop\\.table|provideDimnames|psigamma|pushBack|pushBackLength|q|qr|qr\\.coef|qr\\.default|qr\\.fitted|qr\\.Q|qr\\.qty|qr\\.qy|qr\\.R|qr\\.resid|qr\\.solve|qr\\.X|quarters|quarters\\.Date|quarters\\.POSIXt|quit|quote|R_system_version|R\\.home|R\\.Version|range|range\\.default|rank|rapply|raw|rawConnection|rawConnectionValue|rawShift|rawToBits|rawToChar|rbind|rbind\\.data.frame|rcond|Re|read\\.dcf|readBin|readChar|readline|readLines|readRDS|readRenviron|Recall|Reduce|reg\\.finalizer|regexec|regexpr|registerS3method|registerS3methods|regmatches|remove|removeTaskCallback|rep|rep_len|rep\\.Date|rep\\.factor|rep\\.int|rep\\.numeric_version|rep\\.POSIXct|rep\\.POSIXlt|repeat|replace|replicate|require|requireNamespace|restartDescription|restartFormals|retracemem|return|returnValue|rev|rev\\.default|rle|rm|RNGkind|RNGversion|round|round\\.Date|round\\.POSIXt|row|row\\.names|row\\.names.data.frame|row\\.names.default|rowMeans|rownames|rowsum|rowsum\\.data.frame|rowsum\\.default|rowSums|sample|sample\\.int|sapply|save|save\\.image|saveRDS|scale|scale\\.default|scan|search|searchpaths|seek|seek\\.connection|seq|seq_along|seq_len|seq\\.Date|seq\\.default|seq\\.int|seq\\.POSIXt|sequence|serialize|set\\.seed|setdiff|setequal|setHook|setNamespaceInfo|setSessionTimeLimit|setTimeLimit|setwd|showConnections|shQuote|sign|signalCondition|signif|simpleCondition|simpleError|simpleMessage|simpleWarning|simplify2array|sin|single|sinh|sink|sink\\.number|sinpi|slice\\.index|socketConnection|socketSelect|solve|solve\\.default|solve\\.qr|sort|sort\\.default|sort\\.int|sort\\.list|sort\\.POSIXlt|source|split|split\\.data.frame|split\\.Date|split\\.default|split\\.POSIXct|sprintf|sqrt|sQuote|srcfile|srcfilealias|srcfilecopy|srcref|standardGeneric|startsWith|stderr|stdin|stdout|stop|stopifnot|storage\\.mode|strftime|strptime|strrep|strsplit|strtoi|strtrim|structure|strwrap|sub|subset|subset\\.data.frame|subset\\.default|subset\\.matrix|substitute|substr|substring|sum|summary|summary\\.connection|summary\\.data.frame|Summary\\.data.frame|summary\\.Date|Summary\\.Date|summary\\.default|Summary\\.difftime|summary\\.factor|Summary\\.factor|summary\\.matrix|Summary\\.numeric_version|Summary\\.ordered|summary\\.POSIXct|Summary\\.POSIXct|summary\\.POSIXlt|Summary\\.POSIXlt|summary\\.proc_time|summary\\.srcfile|summary\\.srcref|summary\\.table|suppressMessages|suppressPackageStartupMessages|suppressWarnings|svd|sweep|switch|sys\\.call|sys\\.calls|Sys\\.chmod|Sys\\.Date|sys\\.frame|sys\\.frames|sys\\.function|Sys\\.getenv|Sys\\.getlocale|Sys\\.getpid|Sys\\.glob|Sys\\.info|sys\\.load.image|Sys\\.localeconv|sys\\.nframe|sys\\.on.exit|sys\\.parent|sys\\.parents|Sys\\.readlink|sys\\.save.image|Sys\\.setenv|Sys\\.setFileTime|Sys\\.setlocale|Sys\\.sleep|sys\\.source|sys\\.status|Sys\\.time|Sys\\.timezone|Sys\\.umask|Sys\\.unsetenv|Sys\\.which|system|system\\.file|system\\.time|system2|t|t\\.data.frame|t\\.default|table|tabulate|tan|tanh|tanpi|tapply|taskCallbackManager|tcrossprod|tempdir|tempfile|testPlatformEquivalence|textConnection|textConnectionValue|tolower|topenv|toString|toString\\.default|toupper|trace|traceback|tracemem|tracingState|transform|transform\\.data.frame|transform\\.default|trigamma|trimws|trunc|trunc\\.Date|trunc\\.POSIXt|truncate|truncate\\.connection|try|tryCatch|typeof|unclass|undebug|union|unique|unique\\.array|unique\\.data.frame|unique\\.default|unique\\.matrix|unique\\.numeric_version|unique\\.POSIXlt|unique\\.warnings|units|units\\.difftime|unix\\.time|unlink|unlist|unloadNamespace|unlockBinding|unname|unserialize|unsplit|untrace|untracemem|unz|upper\\.tri|url|UseMethod|utf8ToInt|validEnc|validUTF8|vapply|vector|Vectorize|warning|warnings|weekdays|weekdays\\.Date|weekdays\\.POSIXt|which|which\\.max|which\\.min|while|with|with\\.default|withAutoprint|withCallingHandlers|within|within\\.data.frame|within\\.list|withRestarts|withVisible|write|write\\.dcf|writeBin|writeChar|writeLines|xor|xor\\.hexmode|xor\\.octmode|xpdrows\\.data.frame|xtfrm|xtfrm\\.AsIs|xtfrm\\.Date|xtfrm\\.default|xtfrm\\.difftime|xtfrm\\.factor|xtfrm\\.numeric_version|xtfrm\\.POSIXct|xtfrm\\.POSIXlt|xtfrm\\.Surv|xzfile|zapsmall)\\s*(\\()",
"captures": {
"1": {
"name": "support.function.r"
}
}
},
{
"match": "\\b(abline|arrows|assocplot|axis|Axis|axis\\.Date|Axis\\.Date|Axis\\.default|axis\\.POSIXct|Axis\\.POSIXt|Axis\\.table|axTicks|barplot|barplot\\.default|box|boxplot|boxplot\\.default|boxplot\\.formula|boxplot\\.matrix|bxp|cdplot|cdplot\\.default|cdplot\\.formula|clip|close\\.screen|co\\.intervals|contour|contour\\.default|coplot|curve|dotchart|erase\\.screen|filled\\.contour|fourfoldplot|frame|grconvertX|grconvertY|grid|hist|hist\\.Date|hist\\.default|hist\\.POSIXt|identify|identify\\.default|image|image\\.default|layout|layout\\.show|lcm|legend|lines|lines\\.default|lines\\.formula|lines\\.histogram|lines\\.table|locator|matlines|matplot|matpoints|mosaicplot|mosaicplot\\.default|mosaicplot\\.formula|mtext|pairs|pairs\\.default|pairs\\.formula|panel\\.smooth|par|persp|persp\\.default|pie|piechart|plot|plot\\.data.frame|plot\\.default|plot\\.design|plot\\.factor|plot\\.formula|plot\\.function|plot\\.histogram|plot\\.new|plot\\.raster|plot\\.table|plot\\.window|plot\\.xy|plotHclust|points|points\\.default|points\\.formula|points\\.table|polygon|polypath|rasterImage|rect|rug|screen|segments|smoothScatter|spineplot|spineplot\\.default|spineplot\\.formula|split\\.screen|stars|stem|strheight|stripchart|stripchart\\.default|stripchart\\.formula|strwidth|sunflowerplot|sunflowerplot\\.default|sunflowerplot\\.formula|symbols|text|text\\.default|text\\.formula|title|xinch|xspline|xyinch|yinch)\\s*(\\()",
"captures": {
"1": {
"name": "support.function.r"
}
}
},
{
"match": "\\b(adjustcolor|anyNA\\.raster|as\\.graphicsAnnot|as\\.matrix.raster|as\\.raster|as\\.raster.array|as\\.raster.character|as\\.raster.logical|as\\.raster.matrix|as\\.raster.numeric|as\\.raster.raster|as\\.raster.raw|axisTicks|bitmap|bmp|boxplot\\.stats|c2to3|cairo_pdf|cairo_ps|cairoVersion|check_for_XQuartz|check_gs_type|check\\.options|checkFont|checkFont\\.CIDFont|checkFont\\.default|checkFont\\.Type1Font|checkFontInUse|checkIntFormat|checkQuartzFont|checkX11Font|chromaticAdaptation|chull|CIDFont|cm|cm\\.colors|col2rgb|colorConverter|colorRamp|colorRampPalette|colors|colours|contourLines|convertColor|densCols|dev\\.capabilities|dev\\.capture|dev\\.control|dev\\.copy|dev\\.copy2eps|dev\\.copy2pdf|dev\\.cur|dev\\.displaylist|dev\\.flush|dev\\.hold|dev\\.interactive|dev\\.list|dev\\.new|dev\\.next|dev\\.off|dev\\.prev|dev\\.print|dev\\.set|dev\\.size|dev2bitmap|devAskNewPage|deviceIsInteractive|embedFonts|extendrange|getGraphicsEvent|getGraphicsEventEnv|graphics\\.off|gray|gray\\.colors|grey|grey\\.colors|grSoftVersion|guessEncoding|hcl|heat\\.colors|hsv|initPSandPDFfonts|is\\.na.raster|is\\.raster|isPDF|jpeg|make\\.rgb|matchEncoding|matchEncoding\\.CIDFont|matchEncoding\\.Type1Font|matchFont|n2mfrow|nclass\\.FD|nclass\\.scott|nclass\\.Sturges|Ops\\.raster|palette|pdf|pdf\\.options|pdfFonts|pictex|png|postscript|postscriptFonts|prettyDate|print\\.colorConverter|print\\.raster|print\\.recordedplot|print\\.RGBcolorConverter|printFont|printFont\\.CIDFont|printFont\\.Type1Font|printFonts|ps\\.options|quartz|quartz\\.options|quartz\\.save|quartzFont|quartzFonts|rainbow|recordGraphics|recordPalette|recordPlot|replayPlot|restoreRecordedPlot|rgb|rgb2hsv|savePlot|seqDtime|setEPS|setFonts|setGraphicsEventEnv|setGraphicsEventHandlers|setPS|setQuartzFonts|setX11Fonts|svg|terrain\\.colors|tiff|topo\\.colors|trans3d|trunc_POSIXt|Type1Font|x11|X11|X11\\.options|X11Font|X11FontError|X11Fonts|xfig|xy\\.coords|xyTable|xyz\\.coords)\\s*(\\()",
"captures": {
"1": {
"name": "support.function.r"
}
}
},
{
"match": "\\b(addNextMethod|allGenerics|allNames|Arith|as|asMethodDefinition|assignClassDef|assignMethodsMetaData|balanceMethodsList|bind_activation|cacheGenericsMetaData|cacheMetaData|cacheMethod|cacheOnAssign|callGeneric|callNextMethod|canCoerce|cbind|cbind2|checkAtAssignment|checkSlotAssignment|classesToAM|classGeneratorFunction|classLabel|classMetaName|className|coerce|Compare|completeClassDefinition|completeExtends|completeSubclasses|Complex|conformMethod|defaultDumpName|defaultPrototype|dispatchIsInternal|doPrimitiveMethod|dumpMethod|dumpMethods|el|elNamed|empty\\.dump|emptyMethodsList|envRefInferField|envRefSetField|evalOnLoad|evalqOnLoad|evalSource|existsFunction|existsMethod|extends|externalRefMethod|finalDefaultMethod|findClass|findFunction|findMethod|findMethods|findMethodSignatures|findUnique|fixPre1\\.8|formalArgs|fromNextMethod|functionBody|generic\\.skeleton|genericForBasic|getAccess|getAllMethods|getAllSuperClasses|getClass|getClassDef|getClasses|getClassName|getClassPackage|getDataPart|getExtends|getFunction|getGeneric|getGenericFromCall|getGenerics|getGroup|getGroupMembers|getLoadActions|getMethod|getMethods|getMethodsAndAccessors|getMethodsForDispatch|getMethodsMetaData|getPackageName|getProperties|getPrototype|getRefClass|getRefSuperClasses|getSlots|getSubclasses|getValidity|getVirtual|hasArg|hasLoadAction|hasMethod|hasMethods|implicitGeneric|inBasicFuns|inferProperties|inheritedSlotNames|inheritedSubMethodLists|initFieldArgs|initialize|initMethodDispatch|initRefFields|insertClassMethods|insertMethod|insertMethodInEmptyList|insertSource|installClassMethod|is|isBaseFun|isClass|isClassDef|isClassUnion|isGeneric|isGrammarSymbol|isGroup|isMixin|isRematched|isS3Generic|isSealedClass|isSealedMethod|isVirtualClass|isXS3Class|kronecker|languageEl|linearizeMlist|listFromMethods|listFromMlist|loadMethod|Logic|makeClassMethod|makeClassRepresentation|makeEnvRefMethods|makeExtends|makeGeneric|makeMethodsList|makePrototypeFromClassDef|makeStandardGeneric|matchDefaults|matchSignature|Math|Math2|mergeMethods|metaNameUndo|method\\.skeleton|MethodAddCoerce|methodSignatureMatrix|MethodsList|MethodsListSelect|methodsPackageMetaName|missingArg|mlistMetaName|multipleClasses|new|newBasic|newClassRepresentation|newEmptyObject|Ops|outerLabels|packageSlot|possibleExtends|print\\.MethodsList|printClassRepresentation|printPropertiesList|prohibitGeneric|promptClass|promptMethods|prototype|Quote|rbind|rbind2|reconcilePropertiesAndPrototype|refClassFields|refClassInformation|refClassMethods|refClassPrompt|refObjectClass|registerImplicitGenerics|rematchDefinition|removeClass|removeGeneric|removeMethod|removeMethods|removeMethodsObject|representation|requireMethods|resetClass|resetGeneric|S3Class|S3forS4Methods|S3Part|sealClass|seemsS4Object|selectMethod|selectSuperClasses|setAs|setCacheOnAssign|setClass|setClassUnion|setDataPart|setGeneric|setGenericImplicit|setGroupGeneric|setIs|setLoadAction|setLoadActions|setMethod|setNames|setOldClass|setPackageName|setPrimitiveMethods|setRefClass|setReplaceMethod|setValidity|show|showClass|showClassMethod|showDefault|showExtends|showExtraSlots|showMethods|showMlist|showRefClassDef|signature|SignatureMethod|sigToEnv|slot|slotNames|slotsFromS3|substituteDirect|substituteFunctionArgs|Summary|superClassDepth|superClassMethodName|tableNames|testInheritedMethods|testVirtual|traceOff|traceOn|tryNew|unRematchDefinition|useMTable|validObject|validSlotNames)\\s*(\\()",
"captures": {
"1": {
"name": "support.function.r"
}
}
},
{
"match": "\\b(acf|acf2AR|add\\.name|add1|add1\\.default|add1\\.glm|add1\\.lm|add1\\.mlm|addmargins|aggregate|aggregate\\.data.frame|aggregate\\.default|aggregate\\.formula|aggregate\\.ts|AIC|AIC\\.default|AIC\\.logLik|alias|alias\\.formula|alias\\.lm|anova|anova\\.glm|anova\\.glmlist|anova\\.lm|anova\\.lmlist|anova\\.loess|anova\\.mlm|anova\\.mlmlist|anova\\.nls|anovalist\\.nls|ansari\\.test|ansari\\.test.default|ansari\\.test.formula|aov|approx|approxfun|ar|ar\\.burg|ar\\.burg.default|ar\\.burg.mts|ar\\.mle|ar\\.ols|ar\\.yw|ar\\.yw.default|ar\\.yw.mts|arima|arima\\.sim|arima0|arima0\\.diag|ARMAacf|ARMAtoMA|as\\.data.frame.aovproj|as\\.data.frame.ftable|as\\.data.frame.logLik|as\\.dendrogram|as\\.dendrogram.dendrogram|as\\.dendrogram.hclust|as\\.dist|as\\.dist.default|as\\.formula|as\\.hclust|as\\.hclust.default|as\\.hclust.dendrogram|as\\.hclust.twins|as\\.matrix.dist|as\\.matrix.ftable|as\\.stepfun|as\\.stepfun.default|as\\.stepfun.isoreg|as\\.table.ftable|as\\.ts|as\\.ts.default|asOneSidedFormula|ave|bandwidth\\.kernel|bartlett\\.test|bartlett\\.test.default|bartlett\\.test.formula|BIC|BIC\\.default|BIC\\.logLik|binom\\.test|binomial|biplot|biplot\\.default|biplot\\.prcomp|biplot\\.princomp|Box\\.test|bw_pair_cnts|bw\\.bcv|bw\\.nrd|bw\\.nrd0|bw\\.SJ|bw\\.ucv|C|cancor|case\\.names|case\\.names.default|case\\.names.lm|cbind\\.ts|ccf|check_exact|chisq\\.test|cmdscale|coef|coef\\.aov|coef\\.Arima|coef\\.default|coef\\.listof|coef\\.maov|coef\\.nls|coefficients|complete\\.cases|confint|confint\\.default|confint\\.glm|confint\\.lm|confint\\.nls|constrOptim|contr\\.helmert|contr\\.poly|contr\\.SAS|contr\\.sum|contr\\.treatment|contrasts|convolve|cooks\\.distance|cooks\\.distance.glm|cooks\\.distance.lm|cophenetic|cophenetic\\.default|cophenetic\\.dendrogram|cor|cor\\.test|cor\\.test.default|cor\\.test.formula|cov|cov\\.wt|cov2cor|covratio|cpgram|cut\\.dendrogram|cutree|cycle|cycle\\.default|cycle\\.ts|D|dbeta|dbinom|dcauchy|dchisq|decompose|delete\\.response|deltat|deltat\\.default|dendrapply|density|density\\.default|deriv|deriv\\.default|deriv\\.formula|deriv3|deriv3\\.default|deriv3\\.formula|deviance|deviance\\.default|deviance\\.glm|deviance\\.lm|deviance\\.mlm|deviance\\.nls|dexp|df|df\\.kernel|df\\.residual|df\\.residual.default|df\\.residual.nls|dfbeta|dfbeta\\.lm|dfbetas|dfbetas\\.lm|dffits|dgamma|dgeom|dhyper|diff\\.ts|diffinv|diffinv\\.default|diffinv\\.ts|diffinv\\.vector|dist|dlnorm|dlogis|dmultinom|dnbinom|dnorm|dpois|drop\\.name|drop\\.terms|drop1|drop1\\.default|drop1\\.glm|drop1\\.lm|drop1\\.mlm|dsignrank|dt|dummy\\.coef|dummy\\.coef.aovlist|dummy\\.coef.lm|dunif|dweibull|dwilcox|ecdf|eff\\.aovlist|effects|effects\\.glm|effects\\.lm|embed|end|end\\.default|estVar|estVar\\.mlm|estVar\\.SSD|expand\\.model.frame|extractAIC|extractAIC\\.aov|extractAIC\\.coxph|extractAIC\\.glm|extractAIC\\.lm|extractAIC\\.negbin|extractAIC\\.survreg|factanal|factanal\\.fit.mle|factor\\.name|family|family\\.glm|family\\.lm|fft|filter|fisher\\.test|fitted|fitted\\.default|fitted\\.isoreg|fitted\\.kmeans|fitted\\.nls|fitted\\.smooth.spline|fitted\\.values|fivenum|fligner\\.test|fligner\\.test.default|fligner\\.test.formula|format_perc|format\\.dist|format\\.ftable|format\\.perc|formula|formula\\.character|formula\\.data.frame|formula\\.default|formula\\.formula|formula\\.glm|formula\\.lm|formula\\.nls|formula\\.terms|frequency|frequency\\.default|friedman\\.test|friedman\\.test.default|friedman\\.test.formula|ftable|ftable\\.default|ftable\\.formula|Gamma|gaussian|get_all_vars|getCall|getCall\\.default|getInitial|getInitial\\.default|getInitial\\.formula|getInitial\\.selfStart|glm|glm\\.control|glm\\.fit|hasTsp|hat|hatvalues|hatvalues\\.lm|hatvalues\\.smooth.spline|hclust|heatmap|HL|HoltWinters|hyman_filter|identify\\.hclust|influence|influence\\.glm|influence\\.lm|influence\\.measures|integrate|interaction\\.plot|inverse\\.gaussian|IQR|is\\.empty.model|is\\.leaf|is\\.mts|is\\.stepfun|is\\.ts|is\\.tskernel|isoreg|KalmanForecast|KalmanLike|KalmanRun|KalmanSmooth|kernapply|kernapply\\.default|kernapply\\.ts|kernapply\\.tskernel|kernapply\\.vector|kernel|kmeans|knots|knots\\.stepfun|kruskal\\.test|kruskal\\.test.default|kruskal\\.test.formula|ks\\.test|ksmooth|labels\\.dendrogram|labels\\.dist|labels\\.lm|labels\\.terms|lag|lag\\.default|lag\\.plot|line|lines\\.isoreg|lines\\.stepfun|lines\\.ts|lm|lm\\.fit|lm\\.influence|lm\\.wfit|loadings|loess|loess\\.control|loess\\.smooth|logLik|logLik\\.Arima|logLik\\.glm|logLik\\.lm|logLik\\.logLik|logLik\\.nls|loglin|lowess|ls\\.diag|ls\\.print|lsfit|mad|mahalanobis|make\\.link|make\\.tables.aovproj|make\\.tables.aovprojlist|makeARIMA|makepredictcall|makepredictcall\\.default|makepredictcall\\.poly|manova|mantelhaen\\.test|mauchly\\.test|mauchly\\.test.mlm|mauchly\\.test.SSD|mcnemar\\.test|median|median\\.default|medpolish|merge\\.dendrogram|midcache\\.dendrogram|model\\.extract|model\\.frame|model\\.frame.aovlist|model\\.frame.default|model\\.frame.glm|model\\.frame.lm|model\\.matrix|model\\.matrix.default|model\\.matrix.lm|model\\.offset|model\\.response|model\\.tables|model\\.tables.aov|model\\.tables.aovlist|model\\.weights|monthplot|monthplot\\.default|monthplot\\.stl|monthplot\\.StructTS|monthplot\\.ts|mood\\.test|mood\\.test.default|mood\\.test.formula|mvfft|n\\.knots|na\\.action|na\\.action.default|na\\.contiguous|na\\.contiguous.default|na\\.exclude|na\\.exclude.data.frame|na\\.exclude.default|na\\.fail|na\\.fail.default|na\\.omit|na\\.omit.data.frame|na\\.omit.default|na\\.omit.ts|na\\.pass|napredict|napredict\\.default|napredict\\.exclude|naprint|naprint\\.default|naprint\\.exclude|naprint\\.omit|naresid|naresid\\.default|naresid\\.exclude|nextn|nleaves|nlm|nlminb|nls|nls_port_fit|nls\\.control|nlsModel|nlsModel\\.plinear|NLSstAsymptotic|NLSstAsymptotic\\.sortedXyData|NLSstClosestX|NLSstClosestX\\.sortedXyData|NLSstLfAsymptote|NLSstLfAsymptote\\.sortedXyData|NLSstRtAsymptote|NLSstRtAsymptote\\.sortedXyData|nobs|nobs\\.default|nobs\\.dendrogram|nobs\\.glm|nobs\\.lm|nobs\\.logLik|nobs\\.nls|numericDeriv|offset|oneway\\.test|Ops\\.ts|optim|optimHess|optimise|optimize|order\\.dendrogram|p\\.adjust|pacf|pacf\\.default|pairwise\\.prop.test|pairwise\\.t.test|pairwise\\.table|pairwise\\.wilcox.test|pbeta|pbinom|pbirthday|pcauchy|pchisq|pexp|pf|pgamma|pgeom|phyper|Pillai|plclust|plnorm|plogis|plot\\.acf|plot\\.decomposed.ts|plot\\.dendrogram|plot\\.density|plot\\.ecdf|plot\\.hclust|plot\\.HoltWinters|plot\\.isoreg|plot\\.lm|plot\\.medpolish|plot\\.mlm|plot\\.ppr|plot\\.prcomp|plot\\.princomp|plot\\.profile.nls|plot\\.spec|plot\\.spec.coherency|plot\\.spec.phase|plot\\.stepfun|plot\\.stl|plot\\.ts|plot\\.tskernel|plot\\.TukeyHSD|plotNode|plotNodeLimit|pnbinom|pnorm|pointwise|poisson|poisson\\.test|poly|polym|port_get_named_v|port_msg|power|power\\.anova.test|power\\.prop.test|power\\.t.test|PP\\.test|ppoints|ppois|ppr|ppr\\.default|ppr\\.formula|prcomp|prcomp\\.default|prcomp\\.formula|predict|predict\\.ar|predict\\.Arima|predict\\.arima0|predict\\.glm|predict\\.HoltWinters|predict\\.lm|predict\\.loess|predict\\.mlm|predict\\.nls|predict\\.poly|predict\\.ppr|predict\\.prcomp|predict\\.princomp|predict\\.smooth.spline|predict\\.smooth.spline.fit|predict\\.StructTS|predLoess|preplot|princomp|princomp\\.default|princomp\\.formula|print\\.acf|print\\.anova|print\\.aov|print\\.aovlist|print\\.ar|print\\.Arima|print\\.arima0|print\\.dendrogram|print\\.density|print\\.dist|print\\.dummy_coef|print\\.dummy_coef_list|print\\.ecdf|print\\.factanal|print\\.family|print\\.formula|print\\.ftable|print\\.glm|print\\.hclust|print\\.HoltWinters|print\\.htest|print\\.infl|print\\.integrate|print\\.isoreg|print\\.kmeans|print\\.lm|print\\.loadings|print\\.loess|print\\.logLik|print\\.medpolish|print\\.mtable|print\\.nls|print\\.pairwise.htest|print\\.power.htest|print\\.ppr|print\\.prcomp|print\\.princomp|print\\.smooth.spline|print\\.stepfun|print\\.stl|print\\.StructTS|print\\.summary.aov|print\\.summary.aovlist|print\\.summary.ecdf|print\\.summary.glm|print\\.summary.lm|print\\.summary.loess|print\\.summary.manova|print\\.summary.nls|print\\.summary.ppr|print\\.summary.prcomp|print\\.summary.princomp|print\\.tables_aov|print\\.terms|print\\.ts|print\\.tskernel|print\\.TukeyHSD|print\\.tukeyline|print\\.tukeysmooth|print\\.xtabs|printCoefmat|profile|profile\\.nls|profiler|profiler\\.nls|proj|proj\\.aov|proj\\.aovlist|proj\\.default|proj\\.lm|proj\\.matrix|promax|prop\\.test|prop\\.trend.test|psignrank|pt|ptukey|punif|pweibull|pwilcox|qbeta|qbinom|qbirthday|qcauchy|qchisq|qexp|qf|qgamma|qgeom|qhyper|qlnorm|qlogis|qnbinom|qnorm|qpois|qqline|qqnorm|qqnorm\\.default|qqplot|qr\\.lm|qsignrank|qt|qtukey|quade\\.test|quade\\.test.default|quade\\.test.formula|quantile|quantile\\.default|quantile\\.ecdf|quantile\\.POSIXt|quasi|quasibinomial|quasipoisson|qunif|qweibull|qwilcox|r2dtable|Rank|rbeta|rbinom|rcauchy|rchisq|read\\.ftable|rect\\.hclust|reformulate|regularize\\.values|relevel|relevel\\.default|relevel\\.factor|relevel\\.ordered|reorder|reorder\\.default|reorder\\.dendrogram|replications|reshape|resid|residuals|residuals\\.default|residuals\\.glm|residuals\\.HoltWinters|residuals\\.isoreg|residuals\\.lm|residuals\\.nls|residuals\\.smooth.spline|residuals\\.tukeyline|rev\\.dendrogram|rexp|rf|rgamma|rgeom|rhyper|rlnorm|rlogis|rmultinom|rnbinom|rnorm|Roy|rpois|rsignrank|rstandard|rstandard\\.glm|rstandard\\.lm|rstudent|rstudent\\.glm|rstudent\\.lm|rt|runif|runmed|rweibull|rwilcox|rWishart|safe_pchisq|safe_pf|scatter\\.smooth|screeplot|screeplot\\.default|sd|se\\.aov|se\\.aovlist|se\\.contrast|se\\.contrast.aov|se\\.contrast.aovlist|selfStart|selfStart\\.default|selfStart\\.formula|setNames|shapiro\\.test|sigma|sigma\\.default|sigma\\.mlm|simpleLoess|simulate|simulate\\.lm|smooth|smooth\\.spline|smoothEnds|sortedXyData|sortedXyData\\.default|spec\\.ar|spec\\.pgram|spec\\.taper|spectrum|sphericity|spl_coef_conv|spline|splinefun|splinefunH|splinefunH0|SSasymp|SSasympOff|SSasympOrig|SSbiexp|SSD|SSD\\.mlm|SSfol|SSfpl|SSgompertz|SSlogis|SSmicmen|SSweibull|start|start\\.default|stat\\.anova|step|stepfun|stl|str\\.dendrogram|str\\.logLik|StructTS|summary\\.aov|summary\\.aovlist|summary\\.ecdf|summary\\.glm|summary\\.infl|summary\\.lm|summary\\.loess|summary\\.manova|summary\\.mlm|summary\\.nls|summary\\.ppr|summary\\.prcomp|summary\\.princomp|summary\\.stepfun|summary\\.stl|summary\\.tukeysmooth|supsmu|symnum|t\\.test|t\\.test.default|t\\.test.formula|t\\.ts|termplot|terms|terms\\.aovlist|terms\\.default|terms\\.formula|terms\\.terms|Thin\\.col|Thin\\.row|time|time\\.default|time\\.ts|toeplitz|Tr|ts|ts\\.intersect|ts\\.plot|ts\\.union|tsdiag|tsdiag\\.Arima|tsdiag\\.arima0|tsdiag\\.StructTS|tsp|tsSmooth|tsSmooth\\.StructTS|TukeyHSD|TukeyHSD\\.aov|uniroot|update|update\\.default|update\\.formula|var|var\\.test|var\\.test.default|var\\.test.formula|variable\\.names|variable\\.names.default|variable\\.names.lm|varimax|vcov|vcov\\.Arima|vcov\\.glm|vcov\\.lm|vcov\\.mlm|vcov\\.nls|vcov\\.summary.glm|vcov\\.summary.lm|weighted\\.mean|weighted\\.mean.Date|weighted\\.mean.default|weighted\\.mean.difftime|weighted\\.mean.POSIXct|weighted\\.mean.POSIXlt|weighted\\.residuals|weights|weights\\.default|weights\\.glm|weights\\.nls|wilcox\\.test|wilcox\\.test.default|wilcox\\.test.formula|Wilks|window|window\\.default|window\\.ts|write\\.ftable|xtabs)\\s*(\\()",
"captures": {
"1": {
"name": "support.function.r"
}
}
},
{
"match": "\\b(adist|alarm|apropos|aregexec|argNames|argsAnywhere|as\\.bibentry|as\\.bibentry.bibentry|as\\.bibentry.citation|as\\.character.person|as\\.character.roman|as\\.person|as\\.person.default|as\\.personList|as\\.personList.default|as\\.personList.person|as\\.relistable|as\\.roman|aspell|aspell_find_dictionaries|aspell_find_program|aspell_inspect_context|aspell_package|aspell_package_C_files|aspell_package_description|aspell_package_pot_files|aspell_package_R_files|aspell_package_Rd_files|aspell_package_vignettes|aspell_R_C_files|aspell_R_manuals|aspell_R_R_files|aspell_R_Rd_files|aspell_R_vignettes|aspell_write_personal_dictionary_file|assignInMyNamespace|assignInNamespace|attachedPackageCompletions|available\\.packages|bibentry|blank_out_ignores_in_lines|blank_out_regexp_matches|browseEnv|browseURL|browseVignettes|bug\\.report|bug\\.report.info|c\\.bibentry|c\\.person|capture\\.output|changedFiles|check_for_XQuartz|checkCRAN|chooseBioCmirror|chooseCRANmirror|citation|cite|citeNatbib|citEntry|citFooter|citHeader|close\\.socket|close\\.txtProgressBar|combn|compareVersion|contrib\\.url|correctFilenameToken|count\\.fields|CRAN\\.packages|create\\.post|data|data\\.entry|dataentry|de|de\\.ncols|de\\.restore|de\\.setup|debugcall|debugger|defaultUserAgent|demo|download\\.file|download\\.packages|dump\\.frames|edit|edit\\.data.frame|edit\\.default|edit\\.matrix|edit\\.vignette|emacs|example|expr2token|file_test|file\\.edit|fileCompletionPreferred|fileCompletions|fileSnapshot|filter_packages_by_depends_predicates|find|find_files_in_directories|findExactMatches|findFuzzyMatches|findGeneric|findLineNum|findMatches|fix|fixInNamespace|flush\\.console|fnLineNum|format\\.aspell|format\\.bibentry|format\\.citation|format\\.news_db|format\\.object_size|format\\.person|format\\.roman|formatOL|formatUL|functionArgs|fuzzyApropos|get_parse_data_for_message_strings|getAnywhere|getCRANmirrors|getDependencies|getFromNamespace|getIsFirstArg|getKnownS3generics|getParseData|getParseText|getRcode|getRcode\\.vignette|getS3method|getSrcDirectory|getSrcfile|getSrcFilename|getSrcLocation|getSrcref|getTxtProgressBar|glob2rx|globalVariables|hasName|head|head\\.data.frame|head\\.default|head\\.ftable|head\\.function|head\\.matrix|head\\.table|help|help\\.request|help\\.search|help\\.start|helpCompletions|history|hsearch_db|hsearch_db_concepts|hsearch_db_keywords|index\\.search|inFunction|install\\.packages|installed\\.packages|is\\.relistable|isBasePkg|isInsideQuotes|isS3method|isS3stdGeneric|keywordCompletions|limitedLabels|loadedPackageCompletions|loadhistory|localeToCharset|ls\\.str|lsf\\.str|maintainer|make_sysdata_rda|make\\.packages.html|make\\.socket|makeRegexpSafe|makeRweaveLatexCodeRunner|makeUserAgent|matchAvailableTopics|memory\\.limit|memory\\.size|menu|merge_demo_index|merge_vignette_index|methods|mirror2html|modifyList|new\\.packages|news|normalCompletions|nsl|object\\.size|offline_help_helper|old\\.packages|Ops\\.roman|package\\.skeleton|packageDescription|packageName|packageStatus|packageVersion|page|person|personList|pico|print\\.aspell|print\\.aspell_inspect_context|print\\.bibentry|print\\.Bibtex|print\\.browseVignettes|print\\.changedFiles|print\\.citation|print\\.fileSnapshot|print\\.findLineNumResult|print\\.getAnywhere|print\\.help_files_with_topic|print\\.hsearch|print\\.hsearch_db|print\\.Latex|print\\.ls_str|print\\.MethodsFunction|print\\.news_db|print\\.object_size|print\\.packageDescription|print\\.packageIQR|print\\.packageStatus|print\\.person|print\\.roman|print\\.sessionInfo|print\\.socket|print\\.summary.packageStatus|print\\.vignette|printhsearchInternal|process\\.events|prompt|prompt\\.data.frame|prompt\\.default|promptData|promptImport|promptPackage|rc\\.getOption|rc\\.options|rc\\.settings|rc\\.status|read\\.csv|read\\.csv2|read\\.delim|read\\.delim2|read\\.DIF|read\\.fortran|read\\.fwf|read\\.socket|read\\.table|readCitationFile|recover|registerNames|regquote|relist|relist\\.default|relist\\.factor|relist\\.list|relist\\.matrix|remove\\.packages|removeSource|rep\\.bibentry|rep\\.roman|resolvePkgType|Rprof|Rprof_memory_summary|Rprofmem|RShowDoc|RSiteSearch|rtags|rtags\\.file|Rtangle|RtangleFinish|RtangleRuncode|RtangleSetup|RtangleWritedoc|RweaveChunkPrefix|RweaveEvalWithOpt|RweaveLatex|RweaveLatexFinish|RweaveLatexOptions|RweaveLatexRuncode|RweaveLatexSetup|RweaveLatexWritedoc|RweaveTryStop|savehistory|select\\.list|sessionInfo|setBreakpoint|setIsFirstArg|setRepositories|setTxtProgressBar|shorten\\.to.string|simplifyRepos|sort\\.bibentry|specialCompletions|specialFunctionArgs|specialOpCompletionsHelper|specialOpLocs|stack|stack\\.data.frame|stack\\.default|Stangle|str|str\\.data.frame|str\\.Date|str\\.default|str\\.POSIXt|strcapture|strextract|strOptions|substr_with_tabs|summary\\.aspell|summary\\.packageStatus|summaryRprof|suppressForeignCheck|Sweave|SweaveGetSyntax|SweaveHooks|SweaveParseOptions|SweaveReadFile|SweaveSyntConv|tail|tail\\.data.frame|tail\\.default|tail\\.ftable|tail\\.function|tail\\.matrix|tail\\.table|tar|timestamp|toBibtex|toBibtex\\.bibentry|toBibtex\\.person|toLatex|toLatex\\.sessionInfo|topicName|txtProgressBar|type\\.convert|undebugcall|unique\\.bibentry|unlist\\.relistable|unstack|unstack\\.data.frame|unstack\\.default|untar|untar2|unzip|update\\.packages|update\\.packageStatus|upgrade|upgrade\\.packageStatus|url\\.show|URLdecode|URLencode|vi|View|vignette|write\\.csv|write\\.csv2|write\\.etags|write\\.socket|write\\.table|wsbrowser|xedit|xemacs|zip)\\s*(\\()",
"captures": {
"1": {
"name": "support.function.r"
}
}
}
]
}
}
} | extensions/r/syntaxes/r.tmLanguage.json | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00017587834736332297,
0.00017257225408684462,
0.0001648050092626363,
0.000172869986272417,
0.0000019422825516812736
] |
{
"id": 1,
"code_window": [
"export class MarkersFilterActionViewItem extends BaseActionViewItem {\n",
"\n",
"\tprivate delayedFilterUpdate: Delayer<void>;\n",
"\tprivate filterInputBox: HistoryInputBox | null = null;\n",
"\tprivate filterBadge: HTMLElement | null = null;\n",
"\tprivate focusContextKey: IContextKey<boolean>;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate container: HTMLElement | null = null;\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "add",
"edit_start_line_idx": 135
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-action-bar .action-item.markers-panel-action-filter-container {
flex: 1;
cursor: default;
display: flex;
}
.monaco-action-bar .markers-panel-action-filter {
display: flex;
align-items: center;
flex: 1;
}
.monaco-action-bar .markers-panel-action-filter .monaco-inputbox {
height: 24px;
font-size: 12px;
flex: 1;
}
.vs .monaco-action-bar .markers-panel-action-filter .monaco-inputbox {
height: 25px;
border: 1px solid transparent;
}
.markers-panel-action-filter > .markers-panel-filter-controls {
position: absolute;
top: 0px;
bottom: 0;
right: 4px;
display: flex;
align-items: center;
}
.markers-panel-action-filter > .markers-panel-filter-controls > .markers-panel-filter-badge {
margin: 4px 0px;
padding: 0px 8px;
border-radius: 2px;
}
.markers-panel-action-filter > .markers-panel-filter-controls > .markers-panel-filter-badge.hidden,
.markers-panel-action-filter.small > .markers-panel-filter-controls > .markers-panel-filter-badge {
display: none;
}
.panel > .title .monaco-action-bar .action-item.markers-panel-action-filter-container {
max-width: 600px;
min-width: 300px;
margin-right: 10px;
}
.markers-panel .markers-panel-container {
height: 100%;
}
.markers-panel .hide {
display: none;
}
.markers-panel-container .monaco-action-bar.markers-panel-filter-container {
margin: 10px 20px;
}
.markers-panel .markers-panel-container .message-box-container {
line-height: 22px;
padding-left: 20px;
height: 100%;
}
.markers-panel .markers-panel-container .message-box-container .messageAction {
margin-left: 4px;
cursor: pointer;
text-decoration: underline;
}
.markers-panel .markers-panel-container .hidden {
display: none;
}
.markers-panel .markers-panel-container .tree-container.hidden {
display: none;
visibility: hidden;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents {
display: flex;
line-height: 22px;
padding-right: 10px;
}
.hc-black .markers-panel .markers-panel-container .tree-container .monaco-tl-contents {
line-height: 20px;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-stats {
display: inline-block;
margin-left: 10px;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .count-badge-wrapper {
margin-left: 10px;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-message-details-container {
flex: 1;
overflow: hidden;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-message-details-container > .marker-message-line {
overflow: hidden;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-message-details-container > .marker-message-line > .marker-message {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-message-details-container > .marker-message-line.details-container {
display: flex;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-code:before {
content: '(';
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-code:after {
content: ')';
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .details-container .marker-source,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .details-container .marker-line {
margin-left: 6px;
}
.markers-panel .monaco-tl-contents .marker-icon {
margin-right: 6px;
display: flex;
align-items: center;
justify-content: center;
}
.markers-panel .monaco-tl-contents .actions .action-item {
margin-right: 2px;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-source,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .related-info-resource,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .related-info-resource-separator,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-line,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-code {
opacity: 0.7;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .highlight {
font-weight: bold;
}
.markers-panel .monaco-tl-contents .marker-icon {
height: 22px;
}
.markers-panel .monaco-tl-contents .actions .monaco-action-bar {
display: none;
}
.markers-panel .monaco-list-row:hover .monaco-tl-contents > .marker-icon.quickFix,
.markers-panel .monaco-list-row.selected .monaco-tl-contents > .marker-icon.quickFix,
.markers-panel .monaco-list-row.focused .monaco-tl-contents > .marker-icon.quickFix {
display: none;
}
.markers-panel .monaco-list-row:hover .monaco-tl-contents .actions .monaco-action-bar,
.markers-panel .monaco-list-row.selected .monaco-tl-contents .actions .monaco-action-bar,
.markers-panel .monaco-list-row.focused .monaco-tl-contents .actions .monaco-action-bar {
display: block;
}
.markers-panel .monaco-tl-contents .multiline-actions .action-label,
.markers-panel .monaco-tl-contents .actions .action-label {
width: 16px;
height: 100%;
background-position: 50% 50%;
background-repeat: no-repeat;
}
.markers-panel .monaco-tl-contents .multiline-actions .action-label {
line-height: 22px;
}
.markers-panel .monaco-tl-contents .multiline-actions .action-item.disabled,
.markers-panel .monaco-tl-contents .actions .action-item.disabled {
display: none;
}
| src/vs/workbench/contrib/markers/browser/media/markers.css | 1 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00020081432012375444,
0.0001713797973934561,
0.00016642315313220024,
0.00016816075367387384,
0.000009080488780455198
] |
{
"id": 1,
"code_window": [
"export class MarkersFilterActionViewItem extends BaseActionViewItem {\n",
"\n",
"\tprivate delayedFilterUpdate: Delayer<void>;\n",
"\tprivate filterInputBox: HistoryInputBox | null = null;\n",
"\tprivate filterBadge: HTMLElement | null = null;\n",
"\tprivate focusContextKey: IContextKey<boolean>;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate container: HTMLElement | null = null;\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "add",
"edit_start_line_idx": 135
} | pat | build/azure-pipelines/linux/.gitignore | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.0001763369218679145,
0.0001763369218679145,
0.0001763369218679145,
0.0001763369218679145,
0
] |
{
"id": 1,
"code_window": [
"export class MarkersFilterActionViewItem extends BaseActionViewItem {\n",
"\n",
"\tprivate delayedFilterUpdate: Delayer<void>;\n",
"\tprivate filterInputBox: HistoryInputBox | null = null;\n",
"\tprivate filterBadge: HTMLElement | null = null;\n",
"\tprivate focusContextKey: IContextKey<boolean>;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate container: HTMLElement | null = null;\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "add",
"edit_start_line_idx": 135
} | /*---------------------------------------------------------------------------------------------
* 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 { IDisposable } from 'vs/base/common/lifecycle';
import { ExtHostStorage } from 'vs/workbench/api/common/extHostStorage';
export class ExtensionMemento implements vscode.Memento {
private readonly _id: string;
private readonly _shared: boolean;
private readonly _storage: ExtHostStorage;
private readonly _init: Promise<ExtensionMemento>;
private _value?: { [n: string]: any; };
private readonly _storageListener: IDisposable;
constructor(id: string, global: boolean, storage: ExtHostStorage) {
this._id = id;
this._shared = global;
this._storage = storage;
this._init = this._storage.getValue(this._shared, this._id, Object.create(null)).then(value => {
this._value = value;
return this;
});
this._storageListener = this._storage.onDidChangeStorage(e => {
if (e.shared === this._shared && e.key === this._id) {
this._value = e.value;
}
});
}
get whenReady(): Promise<ExtensionMemento> {
return this._init;
}
get<T>(key: string): T | undefined;
get<T>(key: string, defaultValue: T): T;
get<T>(key: string, defaultValue?: T): T {
let value = this._value![key];
if (typeof value === 'undefined') {
value = defaultValue;
}
return value;
}
update(key: string, value: any): Promise<void> {
this._value![key] = value;
return this._storage.setValue(this._shared, this._id, this._value!);
}
dispose(): void {
this._storageListener.dispose();
}
}
| src/vs/workbench/api/common/extHostMemento.ts | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00017604931781534106,
0.0001718089188216254,
0.00016863054770510644,
0.00017167370242532343,
0.0000023399966266879346
] |
{
"id": 1,
"code_window": [
"export class MarkersFilterActionViewItem extends BaseActionViewItem {\n",
"\n",
"\tprivate delayedFilterUpdate: Delayer<void>;\n",
"\tprivate filterInputBox: HistoryInputBox | null = null;\n",
"\tprivate filterBadge: HTMLElement | null = null;\n",
"\tprivate focusContextKey: IContextKey<boolean>;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate container: HTMLElement | null = null;\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "add",
"edit_start_line_idx": 135
} | var ToggleText = React.createClass({
getInitialState: function () {
return {
showDefault: true
}
},
toggle: function (e) {
// Prevent following the link.
e.preventDefault();
// Invert the chosen default.
// This will trigger an intelligent re-render of the component.
this.setState({ showDefault: !this.state.showDefault })
},
render: function () {
// Default to the default message.
var message = this.props.default;
// If toggled, show the alternate message.
if (!this.state.showDefault) {
message = this.props.alt;
}
return (
<div>
<h1>Hello {message}!</h1>
<a href="" onClick={this.toggle}>Toggle</a>
</div>
);
}
});
React.render(<ToggleText default="World" alt="Mars" />, document.body); | extensions/javascript/test/colorize-fixtures/test.jsx | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00017522902635391802,
0.00017389460117556155,
0.00017224770272150636,
0.0001740508305374533,
0.0000012127186437282944
] |
{
"id": 2,
"code_window": [
"\t\tthis._register(action.onFocus(() => this.focus()));\n",
"\t}\n",
"\n",
"\trender(container: HTMLElement): void {\n",
"\t\tDOM.addClass(container, 'markers-panel-action-filter-container');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tthis.container = container;\n",
"\t\tDOM.addClass(this.container, 'markers-panel-action-filter-container');\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 156
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Delayer } from 'vs/base/common/async';
import * as DOM from 'vs/base/browser/dom';
import { Action, IActionChangeEvent, IAction } from 'vs/base/common/actions';
import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { KeyCode } from 'vs/base/common/keyCodes';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { TogglePanelAction } from 'vs/workbench/browser/panel';
import Messages from 'vs/workbench/contrib/markers/browser/messages';
import Constants from 'vs/workbench/contrib/markers/browser/constants';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { attachInputBoxStyler, attachStylerCallback, attachCheckboxStyler } from 'vs/platform/theme/common/styler';
import { IMarkersWorkbenchService } from 'vs/workbench/contrib/markers/browser/markers';
import { toDisposable } from 'vs/base/common/lifecycle';
import { BaseActionViewItem, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar';
import { badgeBackground, badgeForeground, contrastBorder } from 'vs/platform/theme/common/colorRegistry';
import { localize } from 'vs/nls';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ContextScopedHistoryInputBox } from 'vs/platform/browser/contextScopedHistoryWidget';
import { Marker } from 'vs/workbench/contrib/markers/browser/markersModel';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { Event, Emitter } from 'vs/base/common/event';
import { FilterOptions } from 'vs/workbench/contrib/markers/browser/markersFilterOptions';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
export class ToggleMarkersPanelAction extends TogglePanelAction {
public static readonly ID = 'workbench.actions.view.problems';
public static readonly LABEL = Messages.MARKERS_PANEL_TOGGLE_LABEL;
constructor(id: string, label: string,
@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
@IPanelService panelService: IPanelService,
@IMarkersWorkbenchService markersWorkbenchService: IMarkersWorkbenchService
) {
super(id, label, Constants.MARKERS_PANEL_ID, panelService, layoutService);
}
}
export class ShowProblemsPanelAction extends Action {
public static readonly ID = 'workbench.action.problems.focus';
public static readonly LABEL = Messages.MARKERS_PANEL_SHOW_LABEL;
constructor(id: string, label: string,
@IPanelService private readonly panelService: IPanelService
) {
super(id, label);
}
public run(): Promise<any> {
this.panelService.openPanel(Constants.MARKERS_PANEL_ID, true);
return Promise.resolve();
}
}
export interface IMarkersFilterActionChangeEvent extends IActionChangeEvent {
filterText?: boolean;
useFilesExclude?: boolean;
}
export interface IMarkersFilterActionOptions {
filterText: string;
filterHistory: string[];
useFilesExclude: boolean;
}
export class MarkersFilterAction extends Action {
public static readonly ID: string = 'workbench.actions.problems.filter';
private readonly _onFocus: Emitter<void> = this._register(new Emitter<void>());
readonly onFocus: Event<void> = this._onFocus.event;
constructor(options: IMarkersFilterActionOptions) {
super(MarkersFilterAction.ID, Messages.MARKERS_PANEL_ACTION_TOOLTIP_FILTER, 'markers-panel-action-filter', true);
this._filterText = options.filterText;
this._useFilesExclude = options.useFilesExclude;
this.filterHistory = options.filterHistory;
}
private _filterText: string;
get filterText(): string {
return this._filterText;
}
set filterText(filterText: string) {
if (this._filterText !== filterText) {
this._filterText = filterText;
this._onDidChange.fire(<IMarkersFilterActionChangeEvent>{ filterText: true });
}
}
filterHistory: string[];
private _useFilesExclude: boolean;
get useFilesExclude(): boolean {
return this._useFilesExclude;
}
set useFilesExclude(filesExclude: boolean) {
if (this._useFilesExclude !== filesExclude) {
this._useFilesExclude = filesExclude;
this._onDidChange.fire(<IMarkersFilterActionChangeEvent>{ useFilesExclude: true });
}
}
focus(): void {
this._onFocus.fire();
}
layout(width: number): void {
if (width < 400) {
this.class = 'markers-panel-action-filter small';
} else {
this.class = 'markers-panel-action-filter';
}
}
}
export interface IMarkerFilterController {
onDidFilter: Event<void>;
getFilterOptions(): FilterOptions;
getFilterStats(): { total: number, filtered: number };
}
export class MarkersFilterActionViewItem extends BaseActionViewItem {
private delayedFilterUpdate: Delayer<void>;
private filterInputBox: HistoryInputBox | null = null;
private filterBadge: HTMLElement | null = null;
private focusContextKey: IContextKey<boolean>;
constructor(
readonly action: MarkersFilterAction,
private filterController: IMarkerFilterController,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IContextViewService private readonly contextViewService: IContextViewService,
@IThemeService private readonly themeService: IThemeService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IContextKeyService contextKeyService: IContextKeyService
) {
super(null, action);
this.focusContextKey = Constants.MarkerPanelFilterFocusContextKey.bindTo(contextKeyService);
this.delayedFilterUpdate = new Delayer<void>(200);
this._register(toDisposable(() => this.delayedFilterUpdate.cancel()));
this._register(action.onFocus(() => this.focus()));
}
render(container: HTMLElement): void {
DOM.addClass(container, 'markers-panel-action-filter-container');
this.element = DOM.append(container, DOM.$(''));
this.element.className = this.action.class || '';
this.createInput(this.element);
this.createControls(this.element);
this.adjustInputBox();
}
focus(): void {
if (this.filterInputBox) {
this.filterInputBox.focus();
}
}
private createInput(container: HTMLElement): void {
this.filterInputBox = this._register(this.instantiationService.createInstance(ContextScopedHistoryInputBox, container, this.contextViewService, {
placeholder: Messages.MARKERS_PANEL_FILTER_PLACEHOLDER,
ariaLabel: Messages.MARKERS_PANEL_FILTER_ARIA_LABEL,
history: this.action.filterHistory
}));
this.filterInputBox.inputElement.setAttribute('aria-labelledby', 'markers-panel-arialabel');
this._register(attachInputBoxStyler(this.filterInputBox, this.themeService));
this.filterInputBox.value = this.action.filterText;
this._register(this.filterInputBox.onDidChange(filter => this.delayedFilterUpdate.trigger(() => this.onDidInputChange(this.filterInputBox!))));
this._register(this.action.onDidChange((event: IMarkersFilterActionChangeEvent) => {
if (event.filterText) {
this.filterInputBox!.value = this.action.filterText;
}
}));
this._register(DOM.addStandardDisposableListener(this.filterInputBox.inputElement, DOM.EventType.KEY_DOWN, (e: any) => this.onInputKeyDown(e, this.filterInputBox!)));
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_DOWN, this.handleKeyboardEvent));
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_UP, this.handleKeyboardEvent));
const focusTracker = this._register(DOM.trackFocus(this.filterInputBox.inputElement));
this._register(focusTracker.onDidFocus(() => this.focusContextKey.set(true)));
this._register(focusTracker.onDidBlur(() => this.focusContextKey.set(false)));
this._register(toDisposable(() => this.focusContextKey.reset()));
}
private createControls(container: HTMLElement): void {
const controlsContainer = DOM.append(container, DOM.$('.markers-panel-filter-controls'));
this.createBadge(controlsContainer);
this.createFilesExcludeCheckbox(controlsContainer);
}
private createBadge(container: HTMLElement): void {
const filterBadge = this.filterBadge = DOM.append(container, DOM.$('.markers-panel-filter-badge'));
this._register(attachStylerCallback(this.themeService, { badgeBackground, badgeForeground, contrastBorder }, colors => {
const background = colors.badgeBackground ? colors.badgeBackground.toString() : '';
const foreground = colors.badgeForeground ? colors.badgeForeground.toString() : '';
const border = colors.contrastBorder ? colors.contrastBorder.toString() : '';
filterBadge.style.backgroundColor = background;
filterBadge.style.borderWidth = border ? '1px' : '';
filterBadge.style.borderStyle = border ? 'solid' : '';
filterBadge.style.borderColor = border;
filterBadge.style.color = foreground;
}));
this.updateBadge();
this._register(this.filterController.onDidFilter(() => this.updateBadge()));
}
private createFilesExcludeCheckbox(container: HTMLElement): void {
const filesExcludeFilter = this._register(new Checkbox({
actionClassName: 'codicon codicon-exclude',
title: this.action.useFilesExclude ? Messages.MARKERS_PANEL_ACTION_TOOLTIP_DO_NOT_USE_FILES_EXCLUDE : Messages.MARKERS_PANEL_ACTION_TOOLTIP_USE_FILES_EXCLUDE,
isChecked: this.action.useFilesExclude
}));
this._register(filesExcludeFilter.onChange(() => {
filesExcludeFilter.domNode.title = filesExcludeFilter.checked ? Messages.MARKERS_PANEL_ACTION_TOOLTIP_DO_NOT_USE_FILES_EXCLUDE : Messages.MARKERS_PANEL_ACTION_TOOLTIP_USE_FILES_EXCLUDE;
this.action.useFilesExclude = filesExcludeFilter.checked;
this.focus();
}));
this._register(this.action.onDidChange((event: IMarkersFilterActionChangeEvent) => {
if (event.useFilesExclude) {
filesExcludeFilter.checked = this.action.useFilesExclude;
}
}));
this._register(attachCheckboxStyler(filesExcludeFilter, this.themeService));
container.appendChild(filesExcludeFilter.domNode);
}
private onDidInputChange(inputbox: HistoryInputBox) {
inputbox.addToHistory();
this.action.filterText = inputbox.value;
this.action.filterHistory = inputbox.getHistory();
this.reportFilteringUsed();
}
private updateBadge(): void {
if (this.filterBadge) {
const { total, filtered } = this.filterController.getFilterStats();
DOM.toggleClass(this.filterBadge, 'hidden', total === filtered || filtered === 0);
this.filterBadge.textContent = localize('showing filtered problems', "Showing {0} of {1}", filtered, total);
this.adjustInputBox();
}
}
private adjustInputBox(): void {
if (this.element && this.filterInputBox && this.filterBadge) {
this.filterInputBox.inputElement.style.paddingRight = DOM.hasClass(this.element, 'small') || DOM.hasClass(this.filterBadge, 'hidden') ? '25px' : '150px';
}
}
// Action toolbar is swallowing some keys for action items which should not be for an input box
private handleKeyboardEvent(event: StandardKeyboardEvent) {
if (event.equals(KeyCode.Space)
|| event.equals(KeyCode.LeftArrow)
|| event.equals(KeyCode.RightArrow)
|| event.equals(KeyCode.Escape)
) {
event.stopPropagation();
}
}
private onInputKeyDown(event: StandardKeyboardEvent, filterInputBox: HistoryInputBox) {
let handled = false;
if (event.equals(KeyCode.Escape)) {
filterInputBox.value = '';
handled = true;
}
if (handled) {
event.stopPropagation();
event.preventDefault();
}
}
private reportFilteringUsed(): void {
const filterOptions = this.filterController.getFilterOptions();
const data = {
errors: filterOptions.filterErrors,
warnings: filterOptions.filterWarnings,
infos: filterOptions.filterInfos,
};
/* __GDPR__
"problems.filter" : {
"errors" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"warnings": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"infos": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
this.telemetryService.publicLog('problems.filter', data);
}
protected updateClass(): void {
if (this.element) {
this.element.className = this.action.class || '';
this.adjustInputBox();
}
}
}
export class QuickFixAction extends Action {
public static readonly ID: string = 'workbench.actions.problems.quickfix';
private static readonly CLASS: string = 'markers-panel-action-quickfix codicon-lightbulb';
private static readonly AUTO_FIX_CLASS: string = QuickFixAction.CLASS + ' autofixable';
private readonly _onShowQuickFixes = this._register(new Emitter<void>());
readonly onShowQuickFixes: Event<void> = this._onShowQuickFixes.event;
private _quickFixes: IAction[] = [];
get quickFixes(): IAction[] {
return this._quickFixes;
}
set quickFixes(quickFixes: IAction[]) {
this._quickFixes = quickFixes;
this.enabled = this._quickFixes.length > 0;
}
autoFixable(autofixable: boolean) {
this.class = autofixable ? QuickFixAction.AUTO_FIX_CLASS : QuickFixAction.CLASS;
}
constructor(
readonly marker: Marker,
) {
super(QuickFixAction.ID, Messages.MARKERS_PANEL_ACTION_TOOLTIP_QUICKFIX, QuickFixAction.CLASS, false);
}
run(): Promise<void> {
this._onShowQuickFixes.fire();
return Promise.resolve();
}
}
export class QuickFixActionViewItem extends ActionViewItem {
constructor(action: QuickFixAction,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super(null, action, { icon: true, label: false });
}
public onClick(event: DOM.EventLike): void {
DOM.EventHelper.stop(event, true);
this.showQuickFixes();
}
public showQuickFixes(): void {
if (!this.element) {
return;
}
if (!this.isEnabled()) {
return;
}
const elementPosition = DOM.getDomNodePagePosition(this.element);
const quickFixes = (<QuickFixAction>this.getAction()).quickFixes;
if (quickFixes.length) {
this.contextMenuService.showContextMenu({
getAnchor: () => ({ x: elementPosition.left + 10, y: elementPosition.top + elementPosition.height + 4 }),
getActions: () => quickFixes
});
}
}
}
| src/vs/workbench/contrib/markers/browser/markersPanelActions.ts | 1 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.20280498266220093,
0.012873428873717785,
0.00016478645557072014,
0.000496662687510252,
0.03631030023097992
] |
{
"id": 2,
"code_window": [
"\t\tthis._register(action.onFocus(() => this.focus()));\n",
"\t}\n",
"\n",
"\trender(container: HTMLElement): void {\n",
"\t\tDOM.addClass(container, 'markers-panel-action-filter-container');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tthis.container = container;\n",
"\t\tDOM.addClass(this.container, 'markers-panel-action-filter-container');\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 156
} | /*---------------------------------------------------------------------------------------------
* 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 objects from 'vs/base/common/objects';
let check = (one: any, other: any, msg: string) => {
assert(objects.equals(one, other), msg);
assert(objects.equals(other, one), '[reverse] ' + msg);
};
let checkNot = (one: any, other: any, msg: string) => {
assert(!objects.equals(one, other), msg);
assert(!objects.equals(other, one), '[reverse] ' + msg);
};
suite('Objects', () => {
test('equals', () => {
check(null, null, 'null');
check(undefined, undefined, 'undefined');
check(1234, 1234, 'numbers');
check('', '', 'empty strings');
check('1234', '1234', 'strings');
check([], [], 'empty arrays');
// check(['', 123], ['', 123], 'arrays');
check([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]], 'nested arrays');
check({}, {}, 'empty objects');
check({ a: 1, b: '123' }, { a: 1, b: '123' }, 'objects');
check({ a: 1, b: '123' }, { b: '123', a: 1 }, 'objects (key order)');
check({ a: { b: 1, c: 2 }, b: 3 }, { a: { b: 1, c: 2 }, b: 3 }, 'nested objects');
checkNot(null, undefined, 'null != undefined');
checkNot(null, '', 'null != empty string');
checkNot(null, [], 'null != empty array');
checkNot(null, {}, 'null != empty object');
checkNot(null, 0, 'null != zero');
checkNot(undefined, '', 'undefined != empty string');
checkNot(undefined, [], 'undefined != empty array');
checkNot(undefined, {}, 'undefined != empty object');
checkNot(undefined, 0, 'undefined != zero');
checkNot('', [], 'empty string != empty array');
checkNot('', {}, 'empty string != empty object');
checkNot('', 0, 'empty string != zero');
checkNot([], {}, 'empty array != empty object');
checkNot([], 0, 'empty array != zero');
checkNot(0, [], 'zero != empty array');
checkNot('1234', 1234, 'string !== number');
checkNot([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6000]], 'arrays');
checkNot({ a: { b: 1, c: 2 }, b: 3 }, { b: 3, a: { b: 9, c: 2 } }, 'objects');
});
test('mixin - array', function () {
let foo: any = {};
objects.mixin(foo, { bar: [1, 2, 3] });
assert(foo.bar);
assert(Array.isArray(foo.bar));
assert.equal(foo.bar.length, 3);
assert.equal(foo.bar[0], 1);
assert.equal(foo.bar[1], 2);
assert.equal(foo.bar[2], 3);
});
test('mixin - no overwrite', function () {
let foo: any = {
bar: '123'
};
let bar: any = {
bar: '456'
};
objects.mixin(foo, bar, false);
assert.equal(foo.bar, '123');
});
test('cloneAndChange', () => {
let o1 = { something: 'hello' };
let o = {
o1: o1,
o2: o1
};
assert.deepEqual(objects.cloneAndChange(o, () => { }), o);
});
test('safeStringify', () => {
let obj1: any = {
friend: null
};
let obj2: any = {
friend: null
};
obj1.friend = obj2;
obj2.friend = obj1;
let arr: any = [1];
arr.push(arr);
let circular: any = {
a: 42,
b: null,
c: [
obj1, obj2
],
d: null
};
arr.push(circular);
circular.b = circular;
circular.d = arr;
let result = objects.safeStringify(circular);
assert.deepEqual(JSON.parse(result), {
a: 42,
b: '[Circular]',
c: [
{
friend: {
friend: '[Circular]'
}
},
'[Circular]'
],
d: [1, '[Circular]', '[Circular]']
});
});
test('distinct', () => {
let base = {
one: 'one',
two: 2,
three: {
3: true
},
four: false
};
let diff = objects.distinct(base, base);
assert.deepEqual(diff, {});
let obj = {};
diff = objects.distinct(base, obj);
assert.deepEqual(diff, {});
obj = {
one: 'one',
two: 2
};
diff = objects.distinct(base, obj);
assert.deepEqual(diff, {});
obj = {
three: {
3: true
},
four: false
};
diff = objects.distinct(base, obj);
assert.deepEqual(diff, {});
obj = {
one: 'two',
two: 2,
three: {
3: true
},
four: true
};
diff = objects.distinct(base, obj);
assert.deepEqual(diff, {
one: 'two',
four: true
});
obj = {
one: null,
two: 2,
three: {
3: true
},
four: undefined
};
diff = objects.distinct(base, obj);
assert.deepEqual(diff, {
one: null,
four: undefined
});
obj = {
one: 'two',
two: 3,
three: { 3: false },
four: true
};
diff = objects.distinct(base, obj);
assert.deepEqual(diff, obj);
});
}); | src/vs/base/test/common/objects.test.ts | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.0001737458078423515,
0.0001711174991214648,
0.00016879400936886668,
0.00017099996330216527,
0.0000012893145822090446
] |
{
"id": 2,
"code_window": [
"\t\tthis._register(action.onFocus(() => this.focus()));\n",
"\t}\n",
"\n",
"\trender(container: HTMLElement): void {\n",
"\t\tDOM.addClass(container, 'markers-panel-action-filter-container');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tthis.container = container;\n",
"\t\tDOM.addClass(this.container, 'markers-panel-action-filter-container');\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 156
} | /*---------------------------------------------------------------------------------------------
* 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 * as resources from 'vs/base/common/resources';
import * as nls from 'vs/nls';
import * as platform from 'vs/base/common/platform';
import severity from 'vs/base/common/severity';
import { Event, Emitter } from 'vs/base/common/event';
import { CompletionItem, completionKindFromString } from 'vs/editor/common/modes';
import { Position, IPosition } from 'vs/editor/common/core/position';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { IDebugSession, IConfig, IThread, IRawModelUpdate, IDebugService, IRawStoppedDetails, State, LoadedSourceEvent, IFunctionBreakpoint, IExceptionBreakpoint, IBreakpoint, IExceptionInfo, AdapterEndEvent, IDebugger, VIEWLET_ID, IDebugConfiguration, IReplElement, IStackFrame, IExpression, IReplElementSource, IDataBreakpoint, IDebugSessionOptions } from 'vs/workbench/contrib/debug/common/debug';
import { Source } from 'vs/workbench/contrib/debug/common/debugSource';
import { mixin } from 'vs/base/common/objects';
import { Thread, ExpressionContainer, DebugModel } from 'vs/workbench/contrib/debug/common/debugModel';
import { RawDebugSession } from 'vs/workbench/contrib/debug/browser/rawDebugSession';
import { IProductService } from 'vs/platform/product/common/productService';
import { IWorkspaceFolder, IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { RunOnceScheduler } from 'vs/base/common/async';
import { generateUuid } from 'vs/base/common/uuid';
import { IHostService } from 'vs/workbench/services/host/browser/host';
import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { normalizeDriveLetter } from 'vs/base/common/labels';
import { Range } from 'vs/editor/common/core/range';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { ReplModel } from 'vs/workbench/contrib/debug/common/replModel';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { variableSetEmitter } from 'vs/workbench/contrib/debug/browser/variablesView';
import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation';
import { distinct } from 'vs/base/common/arrays';
export class DebugSession implements IDebugSession {
private id: string;
private _subId: string | undefined;
private raw: RawDebugSession | undefined;
private initialized = false;
private _options: IDebugSessionOptions;
private sources = new Map<string, Source>();
private threads = new Map<number, Thread>();
private cancellationMap = new Map<number, CancellationTokenSource[]>();
private rawListeners: IDisposable[] = [];
private fetchThreadsScheduler: RunOnceScheduler | undefined;
private repl: ReplModel;
private readonly _onDidChangeState = new Emitter<void>();
private readonly _onDidEndAdapter = new Emitter<AdapterEndEvent>();
private readonly _onDidLoadedSource = new Emitter<LoadedSourceEvent>();
private readonly _onDidCustomEvent = new Emitter<DebugProtocol.Event>();
private readonly _onDidChangeREPLElements = new Emitter<void>();
private name: string | undefined;
private readonly _onDidChangeName = new Emitter<string>();
constructor(
private _configuration: { resolved: IConfig, unresolved: IConfig | undefined },
public root: IWorkspaceFolder | undefined,
private model: DebugModel,
options: IDebugSessionOptions | undefined,
@IDebugService private readonly debugService: IDebugService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IHostService private readonly hostService: IHostService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IViewletService private readonly viewletService: IViewletService,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@IProductService private readonly productService: IProductService,
@IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService,
@IOpenerService private readonly openerService: IOpenerService
) {
this.id = generateUuid();
this._options = options || {};
if (this.hasSeparateRepl()) {
this.repl = new ReplModel();
} else {
this.repl = (this.parentSession as DebugSession).repl;
}
this.repl.onDidChangeElements(() => this._onDidChangeREPLElements.fire());
}
getId(): string {
return this.id;
}
setSubId(subId: string | undefined) {
this._subId = subId;
}
get subId(): string | undefined {
return this._subId;
}
get configuration(): IConfig {
return this._configuration.resolved;
}
get unresolvedConfiguration(): IConfig | undefined {
return this._configuration.unresolved;
}
get parentSession(): IDebugSession | undefined {
return this._options.parentSession;
}
setConfiguration(configuration: { resolved: IConfig, unresolved: IConfig | undefined }) {
this._configuration = configuration;
}
getLabel(): string {
const includeRoot = this.workspaceContextService.getWorkspace().folders.length > 1;
const name = this.name || this.configuration.name;
return includeRoot && this.root ? `${name} (${resources.basenameOrAuthority(this.root.uri)})` : name;
}
setName(name: string): void {
this.name = name;
this._onDidChangeName.fire(name);
}
get state(): State {
if (!this.initialized) {
return State.Initializing;
}
if (!this.raw) {
return State.Inactive;
}
const focusedThread = this.debugService.getViewModel().focusedThread;
if (focusedThread && focusedThread.session === this) {
return focusedThread.stopped ? State.Stopped : State.Running;
}
if (this.getAllThreads().some(t => t.stopped)) {
return State.Stopped;
}
return State.Running;
}
get capabilities(): DebugProtocol.Capabilities {
return this.raw ? this.raw.capabilities : Object.create(null);
}
//---- events
get onDidChangeState(): Event<void> {
return this._onDidChangeState.event;
}
get onDidEndAdapter(): Event<AdapterEndEvent> {
return this._onDidEndAdapter.event;
}
get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
get onDidChangeName(): Event<string> {
return this._onDidChangeName.event;
}
//---- DAP events
get onDidCustomEvent(): Event<DebugProtocol.Event> {
return this._onDidCustomEvent.event;
}
get onDidLoadedSource(): Event<LoadedSourceEvent> {
return this._onDidLoadedSource.event;
}
//---- DAP requests
/**
* create and initialize a new debug adapter for this session
*/
async initialize(dbgr: IDebugger): Promise<void> {
if (this.raw) {
// if there was already a connection make sure to remove old listeners
this.shutdown();
}
try {
const customTelemetryService = await dbgr.getCustomTelemetryService();
const debugAdapter = await dbgr.createDebugAdapter(this);
this.raw = new RawDebugSession(debugAdapter, dbgr, this.telemetryService, customTelemetryService, this.extensionHostDebugService, this.openerService);
await this.raw.start();
this.registerListeners();
await this.raw!.initialize({
clientID: 'vscode',
clientName: this.productService.nameLong,
adapterID: this.configuration.type,
pathFormat: 'path',
linesStartAt1: true,
columnsStartAt1: true,
supportsVariableType: true, // #8858
supportsVariablePaging: true, // #9537
supportsRunInTerminalRequest: true, // #10574
locale: platform.locale
});
this.initialized = true;
this._onDidChangeState.fire();
this.model.setExceptionBreakpoints(this.raw!.capabilities.exceptionBreakpointFilters || []);
} catch (err) {
this.initialized = true;
this._onDidChangeState.fire();
throw err;
}
}
/**
* launch or attach to the debuggee
*/
async launchOrAttach(config: IConfig): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
// __sessionID only used for EH debugging (but we add it always for now...)
config.__sessionId = this.getId();
await this.raw.launchOrAttach(config);
}
/**
* end the current debug adapter session
*/
async terminate(restart = false): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
this.cancelAllRequests();
if (this.raw.capabilities.supportsTerminateRequest && this._configuration.resolved.request === 'launch') {
await this.raw.terminate(restart);
} else {
await this.raw.disconnect(restart);
}
}
/**
* end the current debug adapter session
*/
async disconnect(restart = false): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
this.cancelAllRequests();
await this.raw.disconnect(restart);
}
/**
* restart debug adapter session
*/
async restart(): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
this.cancelAllRequests();
await this.raw.restart();
}
async sendBreakpoints(modelUri: URI, breakpointsToSend: IBreakpoint[], sourceModified: boolean): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
if (!this.raw.readyForBreakpoints) {
return Promise.resolve(undefined);
}
const rawSource = this.getRawSource(modelUri);
if (breakpointsToSend.length && !rawSource.adapterData) {
rawSource.adapterData = breakpointsToSend[0].adapterData;
}
// Normalize all drive letters going out from vscode to debug adapters so we are consistent with our resolving #43959
if (rawSource.path) {
rawSource.path = normalizeDriveLetter(rawSource.path);
}
const response = await this.raw.setBreakpoints({
source: rawSource,
lines: breakpointsToSend.map(bp => bp.sessionAgnosticData.lineNumber),
breakpoints: breakpointsToSend.map(bp => ({ line: bp.sessionAgnosticData.lineNumber, column: bp.sessionAgnosticData.column, condition: bp.condition, hitCondition: bp.hitCondition, logMessage: bp.logMessage })),
sourceModified
});
if (response && response.body) {
const data = new Map<string, DebugProtocol.Breakpoint>();
for (let i = 0; i < breakpointsToSend.length; i++) {
data.set(breakpointsToSend[i].getId(), response.body.breakpoints[i]);
}
this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
}
}
async sendFunctionBreakpoints(fbpts: IFunctionBreakpoint[]): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
if (this.raw.readyForBreakpoints) {
const response = await this.raw.setFunctionBreakpoints({ breakpoints: fbpts });
if (response && response.body) {
const data = new Map<string, DebugProtocol.Breakpoint>();
for (let i = 0; i < fbpts.length; i++) {
data.set(fbpts[i].getId(), response.body.breakpoints[i]);
}
this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
}
}
}
async sendExceptionBreakpoints(exbpts: IExceptionBreakpoint[]): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
if (this.raw.readyForBreakpoints) {
await this.raw.setExceptionBreakpoints({ filters: exbpts.map(exb => exb.filter) });
}
}
async dataBreakpointInfo(name: string, variablesReference?: number): Promise<{ dataId: string | null, description: string, canPersist?: boolean }> {
if (!this.raw) {
throw new Error('no debug adapter');
}
if (!this.raw.readyForBreakpoints) {
throw new Error(nls.localize('sessionNotReadyForBreakpoints', "Session is not ready for breakpoints"));
}
const response = await this.raw.dataBreakpointInfo({ name, variablesReference });
return response.body;
}
async sendDataBreakpoints(dataBreakpoints: IDataBreakpoint[]): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
if (this.raw.readyForBreakpoints) {
const response = await this.raw.setDataBreakpoints({ breakpoints: dataBreakpoints });
if (response && response.body) {
const data = new Map<string, DebugProtocol.Breakpoint>();
for (let i = 0; i < dataBreakpoints.length; i++) {
data.set(dataBreakpoints[i].getId(), response.body.breakpoints[i]);
}
this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
}
}
}
async breakpointsLocations(uri: URI, lineNumber: number): Promise<IPosition[]> {
if (!this.raw) {
throw new Error('no debug adapter');
}
const source = this.getRawSource(uri);
const response = await this.raw.breakpointLocations({ source, line: lineNumber });
if (!response.body || !response.body.breakpoints) {
return [];
}
const positions = response.body.breakpoints.map(bp => ({ lineNumber: bp.line, column: bp.column || 1 }));
return distinct(positions, p => `${p.lineNumber}:${p.column}`);
}
customRequest(request: string, args: any): Promise<DebugProtocol.Response> {
if (!this.raw) {
throw new Error('no debug adapter');
}
return this.raw.custom(request, args);
}
stackTrace(threadId: number, startFrame: number, levels: number): Promise<DebugProtocol.StackTraceResponse> {
if (!this.raw) {
throw new Error('no debug adapter');
}
const token = this.getNewCancellationToken(threadId);
return this.raw.stackTrace({ threadId, startFrame, levels }, token);
}
async exceptionInfo(threadId: number): Promise<IExceptionInfo | undefined> {
if (!this.raw) {
throw new Error('no debug adapter');
}
const response = await this.raw.exceptionInfo({ threadId });
if (response) {
return {
id: response.body.exceptionId,
description: response.body.description,
breakMode: response.body.breakMode,
details: response.body.details
};
}
return undefined;
}
scopes(frameId: number, threadId: number): Promise<DebugProtocol.ScopesResponse> {
if (!this.raw) {
throw new Error('no debug adapter');
}
const token = this.getNewCancellationToken(threadId);
return this.raw.scopes({ frameId }, token);
}
variables(variablesReference: number, threadId: number | undefined, filter: 'indexed' | 'named' | undefined, start: number | undefined, count: number | undefined): Promise<DebugProtocol.VariablesResponse> {
if (!this.raw) {
throw new Error('no debug adapter');
}
const token = threadId ? this.getNewCancellationToken(threadId) : undefined;
return this.raw.variables({ variablesReference, filter, start, count }, token);
}
evaluate(expression: string, frameId: number, context?: string): Promise<DebugProtocol.EvaluateResponse> {
if (!this.raw) {
throw new Error('no debug adapter');
}
return this.raw.evaluate({ expression, frameId, context });
}
async restartFrame(frameId: number, threadId: number): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
await this.raw.restartFrame({ frameId }, threadId);
}
async next(threadId: number): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
await this.raw.next({ threadId });
}
async stepIn(threadId: number): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
await this.raw.stepIn({ threadId });
}
async stepOut(threadId: number): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
await this.raw.stepOut({ threadId });
}
async stepBack(threadId: number): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
await this.raw.stepBack({ threadId });
}
async continue(threadId: number): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
await this.raw.continue({ threadId });
}
async reverseContinue(threadId: number): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
await this.raw.reverseContinue({ threadId });
}
async pause(threadId: number): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
await this.raw.pause({ threadId });
}
async terminateThreads(threadIds?: number[]): Promise<void> {
if (!this.raw) {
throw new Error('no debug adapter');
}
await this.raw.terminateThreads({ threadIds });
}
setVariable(variablesReference: number, name: string, value: string): Promise<DebugProtocol.SetVariableResponse> {
if (!this.raw) {
throw new Error('no debug adapter');
}
return this.raw.setVariable({ variablesReference, name, value });
}
gotoTargets(source: DebugProtocol.Source, line: number, column?: number): Promise<DebugProtocol.GotoTargetsResponse> {
if (!this.raw) {
throw new Error('no debug adapter');
}
return this.raw.gotoTargets({ source, line, column });
}
goto(threadId: number, targetId: number): Promise<DebugProtocol.GotoResponse> {
if (!this.raw) {
throw new Error('no debug adapter');
}
return this.raw.goto({ threadId, targetId });
}
loadSource(resource: URI): Promise<DebugProtocol.SourceResponse> {
if (!this.raw) {
return Promise.reject(new Error('no debug adapter'));
}
const source = this.getSourceForUri(resource);
let rawSource: DebugProtocol.Source;
if (source) {
rawSource = source.raw;
} else {
// create a Source
const data = Source.getEncodedDebugData(resource);
rawSource = { path: data.path, sourceReference: data.sourceReference };
}
return this.raw.source({ sourceReference: rawSource.sourceReference || 0, source: rawSource });
}
async getLoadedSources(): Promise<Source[]> {
if (!this.raw) {
return Promise.reject(new Error('no debug adapter'));
}
const response = await this.raw.loadedSources({});
if (response.body && response.body.sources) {
return response.body.sources.map(src => this.getSource(src));
} else {
return [];
}
}
async completions(frameId: number | undefined, text: string, position: Position, overwriteBefore: number, token: CancellationToken): Promise<CompletionItem[]> {
if (!this.raw) {
return Promise.reject(new Error('no debug adapter'));
}
const response = await this.raw.completions({
frameId,
text,
column: position.column,
line: position.lineNumber,
}, token);
const result: CompletionItem[] = [];
if (response && response.body && response.body.targets) {
response.body.targets.forEach(item => {
if (item && item.label) {
result.push({
label: item.label,
insertText: item.text || item.label,
kind: completionKindFromString(item.type || 'property'),
filterText: (item.start && item.length) ? text.substr(item.start, item.length).concat(item.label) : undefined,
range: Range.fromPositions(position.delta(0, -(item.length || overwriteBefore)), position),
sortText: item.sortText
});
}
});
}
return result;
}
//---- threads
getThread(threadId: number): Thread | undefined {
return this.threads.get(threadId);
}
getAllThreads(): IThread[] {
const result: IThread[] = [];
this.threads.forEach(t => result.push(t));
return result;
}
clearThreads(removeThreads: boolean, reference: number | undefined = undefined): void {
if (reference !== undefined && reference !== null) {
const thread = this.threads.get(reference);
if (thread) {
thread.clearCallStack();
thread.stoppedDetails = undefined;
thread.stopped = false;
if (removeThreads) {
this.threads.delete(reference);
}
}
} else {
this.threads.forEach(thread => {
thread.clearCallStack();
thread.stoppedDetails = undefined;
thread.stopped = false;
});
if (removeThreads) {
this.threads.clear();
ExpressionContainer.allValues.clear();
}
}
}
rawUpdate(data: IRawModelUpdate): void {
const threadIds: number[] = [];
data.threads.forEach(thread => {
threadIds.push(thread.id);
if (!this.threads.has(thread.id)) {
// A new thread came in, initialize it.
this.threads.set(thread.id, new Thread(this, thread.name, thread.id));
} else if (thread.name) {
// Just the thread name got updated #18244
const oldThread = this.threads.get(thread.id);
if (oldThread) {
oldThread.name = thread.name;
}
}
});
this.threads.forEach(t => {
// Remove all old threads which are no longer part of the update #75980
if (threadIds.indexOf(t.threadId) === -1) {
this.threads.delete(t.threadId);
}
});
const stoppedDetails = data.stoppedDetails;
if (stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (stoppedDetails.allThreadsStopped) {
this.threads.forEach(thread => {
thread.stoppedDetails = thread.threadId === stoppedDetails.threadId ? stoppedDetails : { reason: undefined };
thread.stopped = true;
thread.clearCallStack();
});
} else {
const thread = typeof stoppedDetails.threadId === 'number' ? this.threads.get(stoppedDetails.threadId) : undefined;
if (thread) {
// One thread is stopped, only update that thread.
thread.stoppedDetails = stoppedDetails;
thread.clearCallStack();
thread.stopped = true;
}
}
}
}
private async fetchThreads(stoppedDetails?: IRawStoppedDetails): Promise<void> {
if (this.raw) {
const response = await this.raw.threads();
if (response && response.body && response.body.threads) {
this.model.rawUpdate({
sessionId: this.getId(),
threads: response.body.threads,
stoppedDetails
});
}
}
}
//---- private
private registerListeners(): void {
if (!this.raw) {
return;
}
this.rawListeners.push(this.raw.onDidInitialize(async () => {
aria.status(nls.localize('debuggingStarted', "Debugging started."));
const sendConfigurationDone = async () => {
if (this.raw && this.raw.capabilities.supportsConfigurationDoneRequest) {
try {
await this.raw.configurationDone();
} catch (e) {
// Disconnect the debug session on configuration done error #10596
if (this.raw) {
this.raw.disconnect();
}
}
}
return undefined;
};
// Send all breakpoints
try {
await this.debugService.sendAllBreakpoints(this);
} finally {
await sendConfigurationDone();
}
await this.fetchThreads();
}));
this.rawListeners.push(this.raw.onDidStop(async event => {
await this.fetchThreads(event.body);
const thread = typeof event.body.threadId === 'number' ? this.getThread(event.body.threadId) : undefined;
if (thread) {
// Call fetch call stack twice, the first only return the top stack frame.
// Second retrieves the rest of the call stack. For performance reasons #25605
const promises = this.model.fetchCallStack(<Thread>thread);
const focus = async () => {
if (!event.body.preserveFocusHint && thread.getCallStack().length) {
await this.debugService.focusStackFrame(undefined, thread);
if (thread.stoppedDetails) {
if (this.configurationService.getValue<IDebugConfiguration>('debug').openDebug === 'openOnDebugBreak') {
this.viewletService.openViewlet(VIEWLET_ID);
}
if (this.configurationService.getValue<IDebugConfiguration>('debug').focusWindowOnBreak) {
this.hostService.focus();
}
}
}
};
await promises.topCallStack;
focus();
await promises.wholeCallStack;
if (!this.debugService.getViewModel().focusedStackFrame) {
// The top stack frame can be deemphesized so try to focus again #68616
focus();
}
}
this._onDidChangeState.fire();
}));
this.rawListeners.push(this.raw.onDidThread(event => {
if (event.body.reason === 'started') {
// debounce to reduce threadsRequest frequency and improve performance
if (!this.fetchThreadsScheduler) {
this.fetchThreadsScheduler = new RunOnceScheduler(() => {
this.fetchThreads();
}, 100);
this.rawListeners.push(this.fetchThreadsScheduler);
}
if (!this.fetchThreadsScheduler.isScheduled()) {
this.fetchThreadsScheduler.schedule();
}
} else if (event.body.reason === 'exited') {
this.model.clearThreads(this.getId(), true, event.body.threadId);
const viewModel = this.debugService.getViewModel();
const focusedThread = viewModel.focusedThread;
if (focusedThread && event.body.threadId === focusedThread.threadId) {
// De-focus the thread in case it was focused
this.debugService.focusStackFrame(undefined, undefined, viewModel.focusedSession, false);
}
}
}));
this.rawListeners.push(this.raw.onDidTerminateDebugee(async event => {
aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
if (event.body && event.body.restart) {
await this.debugService.restartSession(this, event.body.restart);
} else if (this.raw) {
await this.raw.disconnect();
}
}));
this.rawListeners.push(this.raw.onDidContinued(event => {
const threadId = event.body.allThreadsContinued !== false ? undefined : event.body.threadId;
if (threadId) {
const tokens = this.cancellationMap.get(threadId);
this.cancellationMap.delete(threadId);
if (tokens) {
tokens.forEach(t => t.cancel());
}
} else {
this.cancelAllRequests();
}
this.model.clearThreads(this.getId(), false, threadId);
this._onDidChangeState.fire();
}));
let outpuPromises: Promise<void>[] = [];
this.rawListeners.push(this.raw.onDidOutput(async event => {
if (!event.body || !this.raw) {
return;
}
const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info;
if (event.body.category === 'telemetry') {
// only log telemetry events from debug adapter if the debug extension provided the telemetry key
// and the user opted in telemetry
if (this.raw.customTelemetryService && this.telemetryService.isOptedIn) {
// __GDPR__TODO__ We're sending events in the name of the debug extension and we can not ensure that those are declared correctly.
this.raw.customTelemetryService.publicLog(event.body.output, event.body.data);
}
return;
}
// Make sure to append output in the correct order by properly waiting on preivous promises #33822
const waitFor = outpuPromises.slice();
const source = event.body.source && event.body.line ? {
lineNumber: event.body.line,
column: event.body.column ? event.body.column : 1,
source: this.getSource(event.body.source)
} : undefined;
if (event.body.variablesReference) {
const container = new ExpressionContainer(this, undefined, event.body.variablesReference, generateUuid());
outpuPromises.push(container.getChildren().then(async children => {
await Promise.all(waitFor);
children.forEach(child => {
// Since we can not display multiple trees in a row, we are displaying these variables one after the other (ignoring their names)
(<any>child).name = null;
this.appendToRepl(child, outputSeverity, source);
});
}));
} else if (typeof event.body.output === 'string') {
await Promise.all(waitFor);
this.appendToRepl(event.body.output, outputSeverity, source);
}
await Promise.all(outpuPromises);
outpuPromises = [];
}));
this.rawListeners.push(this.raw.onDidBreakpoint(event => {
const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
const breakpoint = this.model.getBreakpoints().filter(bp => bp.getIdFromAdapter(this.getId()) === id).pop();
const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.getIdFromAdapter(this.getId()) === id).pop();
if (event.body.reason === 'new' && event.body.breakpoint.source && event.body.breakpoint.line) {
const source = this.getSource(event.body.breakpoint.source);
const bps = this.model.addBreakpoints(source.uri, [{
column: event.body.breakpoint.column,
enabled: true,
lineNumber: event.body.breakpoint.line,
}], false);
if (bps.length === 1) {
const data = new Map<string, DebugProtocol.Breakpoint>([[bps[0].getId(), event.body.breakpoint]]);
this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
}
}
if (event.body.reason === 'removed') {
if (breakpoint) {
this.model.removeBreakpoints([breakpoint]);
}
if (functionBreakpoint) {
this.model.removeFunctionBreakpoints(functionBreakpoint.getId());
}
}
if (event.body.reason === 'changed') {
if (breakpoint) {
if (!breakpoint.column) {
event.body.breakpoint.column = undefined;
}
const data = new Map<string, DebugProtocol.Breakpoint>([[breakpoint.getId(), event.body.breakpoint]]);
this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
}
if (functionBreakpoint) {
const data = new Map<string, DebugProtocol.Breakpoint>([[functionBreakpoint.getId(), event.body.breakpoint]]);
this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
}
}
}));
this.rawListeners.push(this.raw.onDidLoadedSource(event => {
this._onDidLoadedSource.fire({
reason: event.body.reason,
source: this.getSource(event.body.source)
});
}));
this.rawListeners.push(this.raw.onDidCustomEvent(event => {
this._onDidCustomEvent.fire(event);
}));
this.rawListeners.push(this.raw.onDidExitAdapter(event => {
this.initialized = true;
this.model.setBreakpointSessionData(this.getId(), this.capabilities, undefined);
this._onDidEndAdapter.fire(event);
}));
}
shutdown(): void {
dispose(this.rawListeners);
if (this.raw) {
this.raw.disconnect();
this.raw.dispose();
}
this.raw = undefined;
this.model.clearThreads(this.getId(), true);
this._onDidChangeState.fire();
}
//---- sources
getSourceForUri(uri: URI): Source | undefined {
return this.sources.get(this.getUriKey(uri));
}
getSource(raw?: DebugProtocol.Source): Source {
let source = new Source(raw, this.getId());
const uriKey = this.getUriKey(source.uri);
const found = this.sources.get(uriKey);
if (found) {
source = found;
// merge attributes of new into existing
source.raw = mixin(source.raw, raw);
if (source.raw && raw) {
// Always take the latest presentation hint from adapter #42139
source.raw.presentationHint = raw.presentationHint;
}
} else {
this.sources.set(uriKey, source);
}
return source;
}
private getRawSource(uri: URI): DebugProtocol.Source {
const source = this.getSourceForUri(uri);
if (source) {
return source.raw;
} else {
const data = Source.getEncodedDebugData(uri);
return { name: data.name, path: data.path, sourceReference: data.sourceReference };
}
}
private getNewCancellationToken(threadId: number): CancellationToken {
const tokenSource = new CancellationTokenSource();
const tokens = this.cancellationMap.get(threadId) || [];
tokens.push(tokenSource);
this.cancellationMap.set(threadId, tokens);
return tokenSource.token;
}
private cancelAllRequests(): void {
this.cancellationMap.forEach(tokens => tokens.forEach(t => t.cancel()));
this.cancellationMap.clear();
}
private getUriKey(uri: URI): string {
// TODO: the following code does not make sense if uri originates from a different platform
return platform.isLinux ? uri.toString() : uri.toString().toLowerCase();
}
// REPL
getReplElements(): IReplElement[] {
return this.repl.getReplElements();
}
hasSeparateRepl(): boolean {
return !this.parentSession || this._options.repl !== 'mergeWithParent';
}
removeReplExpressions(): void {
this.repl.removeReplExpressions();
}
async addReplExpression(stackFrame: IStackFrame | undefined, name: string): Promise<void> {
await this.repl.addReplExpression(this, stackFrame, name);
// Evaluate all watch expressions and fetch variables again since repl evaluation might have changed some.
variableSetEmitter.fire();
}
appendToRepl(data: string | IExpression, severity: severity, source?: IReplElementSource): void {
this.repl.appendToRepl(this, data, severity, source);
}
logToRepl(sev: severity, args: any[], frame?: { uri: URI, line: number, column: number }) {
this.repl.logToRepl(this, sev, args, frame);
}
}
| src/vs/workbench/contrib/debug/browser/debugSession.ts | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.0024105440825223923,
0.00021799963724333793,
0.00016243828576989472,
0.000169160237419419,
0.0002755408058874309
] |
{
"id": 2,
"code_window": [
"\t\tthis._register(action.onFocus(() => this.focus()));\n",
"\t}\n",
"\n",
"\trender(container: HTMLElement): void {\n",
"\t\tDOM.addClass(container, 'markers-panel-action-filter-container');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tthis.container = container;\n",
"\t\tDOM.addClass(this.container, 'markers-panel-action-filter-container');\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 156
} | <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M13.6172 3.84375C13.5169 3.5293 13.3665 3.23991 13.166 2.97559L14.5195 1.61523L13.9043 1L12.5439 2.35352C12.2796 2.15299 11.9902 2.0026 11.6758 1.90234C11.3659 1.79753 11.0446 1.74512 10.7119 1.74512C10.3063 1.74512 9.91439 1.82259 9.53613 1.97754C9.16243 2.13249 8.83203 2.35352 8.54492 2.64062L7 4.19238L11.3271 8.51953L12.8789 6.97461C13.166 6.6875 13.387 6.3571 13.542 5.9834C13.6969 5.60514 13.7744 5.21322 13.7744 4.80762C13.7744 4.47493 13.722 4.15365 13.6172 3.84375ZM12.7285 5.64844C12.6191 5.91276 12.4619 6.14746 12.2568 6.35254L11.3271 7.28223L8.2373 4.19238L9.16699 3.2627C9.37207 3.05762 9.60677 2.90039 9.87109 2.79102C10.14 2.67708 10.4202 2.62012 10.7119 2.62012C11.0127 2.62012 11.2952 2.67936 11.5596 2.79785C11.8239 2.91178 12.054 3.06901 12.25 3.26953C12.4505 3.46549 12.6077 3.69564 12.7217 3.95996C12.8402 4.22428 12.8994 4.50684 12.8994 4.80762C12.8994 5.09928 12.8424 5.37956 12.7285 5.64844ZM7.9043 10.6416L9.3877 9.09668L8.77246 8.47461L7.28223 10.0264L5.42285 8.16699L6.91309 6.61523L6.29102 6L4.80762 7.54492L4.19238 6.92969L2.64062 8.47461C2.35352 8.76172 2.13249 9.0944 1.97754 9.47266C1.82259 9.84635 1.74512 10.236 1.74512 10.6416C1.74512 10.9743 1.79525 11.2979 1.89551 11.6123C2.00033 11.9222 2.15299 12.2093 2.35352 12.4736L1 13.834L1.61523 14.4492L2.97559 13.0957C3.23991 13.2962 3.52702 13.4489 3.83691 13.5537C4.15137 13.654 4.47493 13.7041 4.80762 13.7041C5.21322 13.7041 5.60286 13.6266 5.97656 13.4717C6.35482 13.3167 6.6875 13.0957 6.97461 12.8086L8.51953 11.2568L7.9043 10.6416ZM5.6416 12.665C5.37728 12.7744 5.09928 12.8291 4.80762 12.8291C4.50684 12.8291 4.22201 12.7721 3.95312 12.6582C3.6888 12.5443 3.45638 12.3893 3.25586 12.1934C3.0599 11.9928 2.90495 11.7604 2.79102 11.4961C2.67708 11.2272 2.62012 10.9424 2.62012 10.6416C2.62012 10.3499 2.6748 10.0719 2.78418 9.80762C2.89811 9.53874 3.05762 9.30176 3.2627 9.09668L4.19238 8.16699L7.28223 11.2568L6.35254 12.1865C6.14746 12.3916 5.91048 12.5511 5.6416 12.665Z" fill="#F48771"/>
</svg>
| src/vs/workbench/contrib/debug/browser/media/disconnect-dark.svg | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.0033726319670677185,
0.0033726319670677185,
0.0033726319670677185,
0.0033726319670677185,
0
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tthis.element = DOM.append(container, DOM.$(''));\n",
"\t\tthis.element.className = this.action.class || '';\n",
"\t\tthis.createInput(this.element);\n",
"\t\tthis.createControls(this.element);\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.element = DOM.append(this.container, DOM.$(''));\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 158
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Delayer } from 'vs/base/common/async';
import * as DOM from 'vs/base/browser/dom';
import { Action, IActionChangeEvent, IAction } from 'vs/base/common/actions';
import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { KeyCode } from 'vs/base/common/keyCodes';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { TogglePanelAction } from 'vs/workbench/browser/panel';
import Messages from 'vs/workbench/contrib/markers/browser/messages';
import Constants from 'vs/workbench/contrib/markers/browser/constants';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { attachInputBoxStyler, attachStylerCallback, attachCheckboxStyler } from 'vs/platform/theme/common/styler';
import { IMarkersWorkbenchService } from 'vs/workbench/contrib/markers/browser/markers';
import { toDisposable } from 'vs/base/common/lifecycle';
import { BaseActionViewItem, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar';
import { badgeBackground, badgeForeground, contrastBorder } from 'vs/platform/theme/common/colorRegistry';
import { localize } from 'vs/nls';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ContextScopedHistoryInputBox } from 'vs/platform/browser/contextScopedHistoryWidget';
import { Marker } from 'vs/workbench/contrib/markers/browser/markersModel';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { Event, Emitter } from 'vs/base/common/event';
import { FilterOptions } from 'vs/workbench/contrib/markers/browser/markersFilterOptions';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
export class ToggleMarkersPanelAction extends TogglePanelAction {
public static readonly ID = 'workbench.actions.view.problems';
public static readonly LABEL = Messages.MARKERS_PANEL_TOGGLE_LABEL;
constructor(id: string, label: string,
@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
@IPanelService panelService: IPanelService,
@IMarkersWorkbenchService markersWorkbenchService: IMarkersWorkbenchService
) {
super(id, label, Constants.MARKERS_PANEL_ID, panelService, layoutService);
}
}
export class ShowProblemsPanelAction extends Action {
public static readonly ID = 'workbench.action.problems.focus';
public static readonly LABEL = Messages.MARKERS_PANEL_SHOW_LABEL;
constructor(id: string, label: string,
@IPanelService private readonly panelService: IPanelService
) {
super(id, label);
}
public run(): Promise<any> {
this.panelService.openPanel(Constants.MARKERS_PANEL_ID, true);
return Promise.resolve();
}
}
export interface IMarkersFilterActionChangeEvent extends IActionChangeEvent {
filterText?: boolean;
useFilesExclude?: boolean;
}
export interface IMarkersFilterActionOptions {
filterText: string;
filterHistory: string[];
useFilesExclude: boolean;
}
export class MarkersFilterAction extends Action {
public static readonly ID: string = 'workbench.actions.problems.filter';
private readonly _onFocus: Emitter<void> = this._register(new Emitter<void>());
readonly onFocus: Event<void> = this._onFocus.event;
constructor(options: IMarkersFilterActionOptions) {
super(MarkersFilterAction.ID, Messages.MARKERS_PANEL_ACTION_TOOLTIP_FILTER, 'markers-panel-action-filter', true);
this._filterText = options.filterText;
this._useFilesExclude = options.useFilesExclude;
this.filterHistory = options.filterHistory;
}
private _filterText: string;
get filterText(): string {
return this._filterText;
}
set filterText(filterText: string) {
if (this._filterText !== filterText) {
this._filterText = filterText;
this._onDidChange.fire(<IMarkersFilterActionChangeEvent>{ filterText: true });
}
}
filterHistory: string[];
private _useFilesExclude: boolean;
get useFilesExclude(): boolean {
return this._useFilesExclude;
}
set useFilesExclude(filesExclude: boolean) {
if (this._useFilesExclude !== filesExclude) {
this._useFilesExclude = filesExclude;
this._onDidChange.fire(<IMarkersFilterActionChangeEvent>{ useFilesExclude: true });
}
}
focus(): void {
this._onFocus.fire();
}
layout(width: number): void {
if (width < 400) {
this.class = 'markers-panel-action-filter small';
} else {
this.class = 'markers-panel-action-filter';
}
}
}
export interface IMarkerFilterController {
onDidFilter: Event<void>;
getFilterOptions(): FilterOptions;
getFilterStats(): { total: number, filtered: number };
}
export class MarkersFilterActionViewItem extends BaseActionViewItem {
private delayedFilterUpdate: Delayer<void>;
private filterInputBox: HistoryInputBox | null = null;
private filterBadge: HTMLElement | null = null;
private focusContextKey: IContextKey<boolean>;
constructor(
readonly action: MarkersFilterAction,
private filterController: IMarkerFilterController,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IContextViewService private readonly contextViewService: IContextViewService,
@IThemeService private readonly themeService: IThemeService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IContextKeyService contextKeyService: IContextKeyService
) {
super(null, action);
this.focusContextKey = Constants.MarkerPanelFilterFocusContextKey.bindTo(contextKeyService);
this.delayedFilterUpdate = new Delayer<void>(200);
this._register(toDisposable(() => this.delayedFilterUpdate.cancel()));
this._register(action.onFocus(() => this.focus()));
}
render(container: HTMLElement): void {
DOM.addClass(container, 'markers-panel-action-filter-container');
this.element = DOM.append(container, DOM.$(''));
this.element.className = this.action.class || '';
this.createInput(this.element);
this.createControls(this.element);
this.adjustInputBox();
}
focus(): void {
if (this.filterInputBox) {
this.filterInputBox.focus();
}
}
private createInput(container: HTMLElement): void {
this.filterInputBox = this._register(this.instantiationService.createInstance(ContextScopedHistoryInputBox, container, this.contextViewService, {
placeholder: Messages.MARKERS_PANEL_FILTER_PLACEHOLDER,
ariaLabel: Messages.MARKERS_PANEL_FILTER_ARIA_LABEL,
history: this.action.filterHistory
}));
this.filterInputBox.inputElement.setAttribute('aria-labelledby', 'markers-panel-arialabel');
this._register(attachInputBoxStyler(this.filterInputBox, this.themeService));
this.filterInputBox.value = this.action.filterText;
this._register(this.filterInputBox.onDidChange(filter => this.delayedFilterUpdate.trigger(() => this.onDidInputChange(this.filterInputBox!))));
this._register(this.action.onDidChange((event: IMarkersFilterActionChangeEvent) => {
if (event.filterText) {
this.filterInputBox!.value = this.action.filterText;
}
}));
this._register(DOM.addStandardDisposableListener(this.filterInputBox.inputElement, DOM.EventType.KEY_DOWN, (e: any) => this.onInputKeyDown(e, this.filterInputBox!)));
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_DOWN, this.handleKeyboardEvent));
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_UP, this.handleKeyboardEvent));
const focusTracker = this._register(DOM.trackFocus(this.filterInputBox.inputElement));
this._register(focusTracker.onDidFocus(() => this.focusContextKey.set(true)));
this._register(focusTracker.onDidBlur(() => this.focusContextKey.set(false)));
this._register(toDisposable(() => this.focusContextKey.reset()));
}
private createControls(container: HTMLElement): void {
const controlsContainer = DOM.append(container, DOM.$('.markers-panel-filter-controls'));
this.createBadge(controlsContainer);
this.createFilesExcludeCheckbox(controlsContainer);
}
private createBadge(container: HTMLElement): void {
const filterBadge = this.filterBadge = DOM.append(container, DOM.$('.markers-panel-filter-badge'));
this._register(attachStylerCallback(this.themeService, { badgeBackground, badgeForeground, contrastBorder }, colors => {
const background = colors.badgeBackground ? colors.badgeBackground.toString() : '';
const foreground = colors.badgeForeground ? colors.badgeForeground.toString() : '';
const border = colors.contrastBorder ? colors.contrastBorder.toString() : '';
filterBadge.style.backgroundColor = background;
filterBadge.style.borderWidth = border ? '1px' : '';
filterBadge.style.borderStyle = border ? 'solid' : '';
filterBadge.style.borderColor = border;
filterBadge.style.color = foreground;
}));
this.updateBadge();
this._register(this.filterController.onDidFilter(() => this.updateBadge()));
}
private createFilesExcludeCheckbox(container: HTMLElement): void {
const filesExcludeFilter = this._register(new Checkbox({
actionClassName: 'codicon codicon-exclude',
title: this.action.useFilesExclude ? Messages.MARKERS_PANEL_ACTION_TOOLTIP_DO_NOT_USE_FILES_EXCLUDE : Messages.MARKERS_PANEL_ACTION_TOOLTIP_USE_FILES_EXCLUDE,
isChecked: this.action.useFilesExclude
}));
this._register(filesExcludeFilter.onChange(() => {
filesExcludeFilter.domNode.title = filesExcludeFilter.checked ? Messages.MARKERS_PANEL_ACTION_TOOLTIP_DO_NOT_USE_FILES_EXCLUDE : Messages.MARKERS_PANEL_ACTION_TOOLTIP_USE_FILES_EXCLUDE;
this.action.useFilesExclude = filesExcludeFilter.checked;
this.focus();
}));
this._register(this.action.onDidChange((event: IMarkersFilterActionChangeEvent) => {
if (event.useFilesExclude) {
filesExcludeFilter.checked = this.action.useFilesExclude;
}
}));
this._register(attachCheckboxStyler(filesExcludeFilter, this.themeService));
container.appendChild(filesExcludeFilter.domNode);
}
private onDidInputChange(inputbox: HistoryInputBox) {
inputbox.addToHistory();
this.action.filterText = inputbox.value;
this.action.filterHistory = inputbox.getHistory();
this.reportFilteringUsed();
}
private updateBadge(): void {
if (this.filterBadge) {
const { total, filtered } = this.filterController.getFilterStats();
DOM.toggleClass(this.filterBadge, 'hidden', total === filtered || filtered === 0);
this.filterBadge.textContent = localize('showing filtered problems', "Showing {0} of {1}", filtered, total);
this.adjustInputBox();
}
}
private adjustInputBox(): void {
if (this.element && this.filterInputBox && this.filterBadge) {
this.filterInputBox.inputElement.style.paddingRight = DOM.hasClass(this.element, 'small') || DOM.hasClass(this.filterBadge, 'hidden') ? '25px' : '150px';
}
}
// Action toolbar is swallowing some keys for action items which should not be for an input box
private handleKeyboardEvent(event: StandardKeyboardEvent) {
if (event.equals(KeyCode.Space)
|| event.equals(KeyCode.LeftArrow)
|| event.equals(KeyCode.RightArrow)
|| event.equals(KeyCode.Escape)
) {
event.stopPropagation();
}
}
private onInputKeyDown(event: StandardKeyboardEvent, filterInputBox: HistoryInputBox) {
let handled = false;
if (event.equals(KeyCode.Escape)) {
filterInputBox.value = '';
handled = true;
}
if (handled) {
event.stopPropagation();
event.preventDefault();
}
}
private reportFilteringUsed(): void {
const filterOptions = this.filterController.getFilterOptions();
const data = {
errors: filterOptions.filterErrors,
warnings: filterOptions.filterWarnings,
infos: filterOptions.filterInfos,
};
/* __GDPR__
"problems.filter" : {
"errors" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"warnings": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"infos": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
this.telemetryService.publicLog('problems.filter', data);
}
protected updateClass(): void {
if (this.element) {
this.element.className = this.action.class || '';
this.adjustInputBox();
}
}
}
export class QuickFixAction extends Action {
public static readonly ID: string = 'workbench.actions.problems.quickfix';
private static readonly CLASS: string = 'markers-panel-action-quickfix codicon-lightbulb';
private static readonly AUTO_FIX_CLASS: string = QuickFixAction.CLASS + ' autofixable';
private readonly _onShowQuickFixes = this._register(new Emitter<void>());
readonly onShowQuickFixes: Event<void> = this._onShowQuickFixes.event;
private _quickFixes: IAction[] = [];
get quickFixes(): IAction[] {
return this._quickFixes;
}
set quickFixes(quickFixes: IAction[]) {
this._quickFixes = quickFixes;
this.enabled = this._quickFixes.length > 0;
}
autoFixable(autofixable: boolean) {
this.class = autofixable ? QuickFixAction.AUTO_FIX_CLASS : QuickFixAction.CLASS;
}
constructor(
readonly marker: Marker,
) {
super(QuickFixAction.ID, Messages.MARKERS_PANEL_ACTION_TOOLTIP_QUICKFIX, QuickFixAction.CLASS, false);
}
run(): Promise<void> {
this._onShowQuickFixes.fire();
return Promise.resolve();
}
}
export class QuickFixActionViewItem extends ActionViewItem {
constructor(action: QuickFixAction,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super(null, action, { icon: true, label: false });
}
public onClick(event: DOM.EventLike): void {
DOM.EventHelper.stop(event, true);
this.showQuickFixes();
}
public showQuickFixes(): void {
if (!this.element) {
return;
}
if (!this.isEnabled()) {
return;
}
const elementPosition = DOM.getDomNodePagePosition(this.element);
const quickFixes = (<QuickFixAction>this.getAction()).quickFixes;
if (quickFixes.length) {
this.contextMenuService.showContextMenu({
getAnchor: () => ({ x: elementPosition.left + 10, y: elementPosition.top + elementPosition.height + 4 }),
getActions: () => quickFixes
});
}
}
}
| src/vs/workbench/contrib/markers/browser/markersPanelActions.ts | 1 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.9953805208206177,
0.027284681797027588,
0.00016450858674943447,
0.00018237682525068521,
0.15916691720485687
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tthis.element = DOM.append(container, DOM.$(''));\n",
"\t\tthis.element.className = this.action.class || '';\n",
"\t\tthis.createInput(this.element);\n",
"\t\tthis.createControls(this.element);\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.element = DOM.append(this.container, DOM.$(''));\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 158
} | {
"name": "jake",
"publisher": "vscode",
"description": "%description%",
"displayName": "%displayName%",
"icon": "images/cowboy_hat.png",
"version": "1.0.0",
"license": "MIT",
"engines": {
"vscode": "*"
},
"categories": [
"Other"
],
"scripts": {
"compile": "gulp compile-extension:jake",
"watch": "gulp watch-extension:jake"
},
"dependencies": {
"vscode-nls": "^4.0.0"
},
"devDependencies": {
"@types/node": "^12.11.7"
},
"main": "./out/main",
"activationEvents": [
"onCommand:workbench.action.tasks.runTask"
],
"contributes": {
"configuration": {
"id": "jake",
"type": "object",
"title": "Jake",
"properties": {
"jake.autoDetect": {
"scope": "resource",
"type": "string",
"enum": [
"off",
"on"
],
"default": "on",
"description": "%config.jake.autoDetect%"
}
}
},
"taskDefinitions": [
{
"type": "jake",
"required": [
"task"
],
"properties": {
"task": {
"type": "string",
"description": "%jake.taskDefinition.type.description%"
},
"file": {
"type": "string",
"description": "%jake.taskDefinition.file.description%"
}
}
}
]
}
}
| extensions/jake/package.json | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.0001759078586474061,
0.00017317004676442593,
0.00016660208348184824,
0.0001748670038068667,
0.0000030533888093486894
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tthis.element = DOM.append(container, DOM.$(''));\n",
"\t\tthis.element.className = this.action.class || '';\n",
"\t\tthis.createInput(this.element);\n",
"\t\tthis.createControls(this.element);\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.element = DOM.append(this.container, DOM.$(''));\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 158
} | /*---------------------------------------------------------------------------------------------
* 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 { IssueReporterData } from 'vs/platform/issue/node/issue';
export const IWorkbenchIssueService = createDecorator<IWorkbenchIssueService>('workbenchIssueService');
export interface IWorkbenchIssueService {
_serviceBrand: undefined;
openReporter(dataOverrides?: Partial<IssueReporterData>): Promise<void>;
openProcessExplorer(): Promise<void>;
}
| src/vs/workbench/contrib/issue/electron-browser/issue.ts | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00017498525267001241,
0.00017105508595705032,
0.00016712493379600346,
0.00017105508595705032,
0.000003930159437004477
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tthis.element = DOM.append(container, DOM.$(''));\n",
"\t\tthis.element.className = this.action.class || '';\n",
"\t\tthis.createInput(this.element);\n",
"\t\tthis.createControls(this.element);\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.element = DOM.append(this.container, DOM.$(''));\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 158
} | /*---------------------------------------------------------------------------------------------
* 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!./panelview';
import { IDisposable, Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
import { domEvent } from 'vs/base/browser/event';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { $, append, addClass, removeClass, toggleClass, trackFocus, EventHelper } from 'vs/base/browser/dom';
import { firstIndex } from 'vs/base/common/arrays';
import { Color, RGBA } from 'vs/base/common/color';
import { SplitView, IView } from './splitview';
import { isFirefox } from 'vs/base/browser/browser';
import { DataTransfers } from 'vs/base/browser/dnd';
export interface IPanelOptions {
ariaHeaderLabel?: string;
minimumBodySize?: number;
maximumBodySize?: number;
expanded?: boolean;
}
export interface IPanelStyles {
dropBackground?: Color;
headerForeground?: Color;
headerBackground?: Color;
headerBorder?: Color;
}
/**
* A Panel is a structured SplitView view.
*
* WARNING: You must call `render()` after you contruct it.
* It can't be done automatically at the end of the ctor
* because of the order of property initialization in TypeScript.
* Subclasses wouldn't be able to set own properties
* before the `render()` call, thus forbiding their use.
*/
export abstract class Panel extends Disposable implements IView {
private static readonly HEADER_SIZE = 22;
readonly element: HTMLElement;
private header!: HTMLElement;
private body!: HTMLElement;
protected _expanded: boolean;
private expandedSize: number | undefined = undefined;
private _headerVisible = true;
private _minimumBodySize: number;
private _maximumBodySize: number;
private ariaHeaderLabel: string;
private styles: IPanelStyles = {};
private animationTimer: number | undefined = undefined;
private readonly _onDidChange = this._register(new Emitter<number | undefined>());
readonly onDidChange: Event<number | undefined> = this._onDidChange.event;
private readonly _onDidChangeExpansionState = this._register(new Emitter<boolean>());
readonly onDidChangeExpansionState: Event<boolean> = this._onDidChangeExpansionState.event;
get draggableElement(): HTMLElement {
return this.header;
}
get dropTargetElement(): HTMLElement {
return this.element;
}
private _dropBackground: Color | undefined;
get dropBackground(): Color | undefined {
return this._dropBackground;
}
get minimumBodySize(): number {
return this._minimumBodySize;
}
set minimumBodySize(size: number) {
this._minimumBodySize = size;
this._onDidChange.fire(undefined);
}
get maximumBodySize(): number {
return this._maximumBodySize;
}
set maximumBodySize(size: number) {
this._maximumBodySize = size;
this._onDidChange.fire(undefined);
}
private get headerSize(): number {
return this.headerVisible ? Panel.HEADER_SIZE : 0;
}
get minimumSize(): number {
const headerSize = this.headerSize;
const expanded = !this.headerVisible || this.isExpanded();
const minimumBodySize = expanded ? this._minimumBodySize : 0;
return headerSize + minimumBodySize;
}
get maximumSize(): number {
const headerSize = this.headerSize;
const expanded = !this.headerVisible || this.isExpanded();
const maximumBodySize = expanded ? this._maximumBodySize : 0;
return headerSize + maximumBodySize;
}
width: number = 0;
constructor(options: IPanelOptions = {}) {
super();
this._expanded = typeof options.expanded === 'undefined' ? true : !!options.expanded;
this.ariaHeaderLabel = options.ariaHeaderLabel || '';
this._minimumBodySize = typeof options.minimumBodySize === 'number' ? options.minimumBodySize : 120;
this._maximumBodySize = typeof options.maximumBodySize === 'number' ? options.maximumBodySize : Number.POSITIVE_INFINITY;
this.element = $('.panel');
}
isExpanded(): boolean {
return this._expanded;
}
setExpanded(expanded: boolean): boolean {
if (this._expanded === !!expanded) {
return false;
}
this._expanded = !!expanded;
this.updateHeader();
if (expanded) {
if (typeof this.animationTimer === 'number') {
clearTimeout(this.animationTimer);
}
append(this.element, this.body);
} else {
this.animationTimer = window.setTimeout(() => {
this.body.remove();
}, 200);
}
this._onDidChangeExpansionState.fire(expanded);
this._onDidChange.fire(expanded ? this.expandedSize : undefined);
return true;
}
get headerVisible(): boolean {
return this._headerVisible;
}
set headerVisible(visible: boolean) {
if (this._headerVisible === !!visible) {
return;
}
this._headerVisible = !!visible;
this.updateHeader();
this._onDidChange.fire(undefined);
}
render(): void {
this.header = $('.panel-header');
append(this.element, this.header);
this.header.setAttribute('tabindex', '0');
this.header.setAttribute('role', 'toolbar');
this.header.setAttribute('aria-label', this.ariaHeaderLabel);
this.renderHeader(this.header);
const focusTracker = trackFocus(this.header);
this._register(focusTracker);
this._register(focusTracker.onDidFocus(() => addClass(this.header, 'focused'), null));
this._register(focusTracker.onDidBlur(() => removeClass(this.header, 'focused'), null));
this.updateHeader();
const onHeaderKeyDown = Event.chain(domEvent(this.header, 'keydown'))
.map(e => new StandardKeyboardEvent(e));
this._register(onHeaderKeyDown.filter(e => e.keyCode === KeyCode.Enter || e.keyCode === KeyCode.Space)
.event(() => this.setExpanded(!this.isExpanded()), null));
this._register(onHeaderKeyDown.filter(e => e.keyCode === KeyCode.LeftArrow)
.event(() => this.setExpanded(false), null));
this._register(onHeaderKeyDown.filter(e => e.keyCode === KeyCode.RightArrow)
.event(() => this.setExpanded(true), null));
this._register(domEvent(this.header, 'click')
(() => this.setExpanded(!this.isExpanded()), null));
this.body = append(this.element, $('.panel-body'));
this.renderBody(this.body);
}
layout(height: number): void {
const headerSize = this.headerVisible ? Panel.HEADER_SIZE : 0;
if (this.isExpanded()) {
this.layoutBody(height - headerSize, this.width);
this.expandedSize = height;
}
}
style(styles: IPanelStyles): void {
this.styles = styles;
if (!this.header) {
return;
}
this.updateHeader();
}
protected updateHeader(): void {
const expanded = !this.headerVisible || this.isExpanded();
this.header.style.height = `${this.headerSize}px`;
this.header.style.lineHeight = `${this.headerSize}px`;
toggleClass(this.header, 'hidden', !this.headerVisible);
toggleClass(this.header, 'expanded', expanded);
this.header.setAttribute('aria-expanded', String(expanded));
this.header.style.color = this.styles.headerForeground ? this.styles.headerForeground.toString() : null;
this.header.style.backgroundColor = this.styles.headerBackground ? this.styles.headerBackground.toString() : '';
this.header.style.borderTop = this.styles.headerBorder ? `1px solid ${this.styles.headerBorder}` : '';
this._dropBackground = this.styles.dropBackground;
}
protected abstract renderHeader(container: HTMLElement): void;
protected abstract renderBody(container: HTMLElement): void;
protected abstract layoutBody(height: number, width: number): void;
}
interface IDndContext {
draggable: PanelDraggable | null;
}
class PanelDraggable extends Disposable {
private static readonly DefaultDragOverBackgroundColor = new Color(new RGBA(128, 128, 128, 0.5));
private dragOverCounter = 0; // see https://github.com/Microsoft/vscode/issues/14470
private _onDidDrop = this._register(new Emitter<{ from: Panel, to: Panel }>());
readonly onDidDrop = this._onDidDrop.event;
constructor(private panel: Panel, private dnd: IPanelDndController, private context: IDndContext) {
super();
panel.draggableElement.draggable = true;
this._register(domEvent(panel.draggableElement, 'dragstart')(this.onDragStart, this));
this._register(domEvent(panel.dropTargetElement, 'dragenter')(this.onDragEnter, this));
this._register(domEvent(panel.dropTargetElement, 'dragleave')(this.onDragLeave, this));
this._register(domEvent(panel.dropTargetElement, 'dragend')(this.onDragEnd, this));
this._register(domEvent(panel.dropTargetElement, 'drop')(this.onDrop, this));
}
private onDragStart(e: DragEvent): void {
if (!this.dnd.canDrag(this.panel) || !e.dataTransfer) {
e.preventDefault();
e.stopPropagation();
return;
}
e.dataTransfer.effectAllowed = 'move';
if (isFirefox) {
// Firefox: requires to set a text data transfer to get going
e.dataTransfer?.setData(DataTransfers.TEXT, this.panel.draggableElement.textContent || '');
}
const dragImage = append(document.body, $('.monaco-drag-image', {}, this.panel.draggableElement.textContent || ''));
e.dataTransfer.setDragImage(dragImage, -10, -10);
setTimeout(() => document.body.removeChild(dragImage), 0);
this.context.draggable = this;
}
private onDragEnter(e: DragEvent): void {
if (!this.context.draggable || this.context.draggable === this) {
return;
}
if (!this.dnd.canDrop(this.context.draggable.panel, this.panel)) {
return;
}
this.dragOverCounter++;
this.render();
}
private onDragLeave(e: DragEvent): void {
if (!this.context.draggable || this.context.draggable === this) {
return;
}
if (!this.dnd.canDrop(this.context.draggable.panel, this.panel)) {
return;
}
this.dragOverCounter--;
if (this.dragOverCounter === 0) {
this.render();
}
}
private onDragEnd(e: DragEvent): void {
if (!this.context.draggable) {
return;
}
this.dragOverCounter = 0;
this.render();
this.context.draggable = null;
}
private onDrop(e: DragEvent): void {
if (!this.context.draggable) {
return;
}
EventHelper.stop(e);
this.dragOverCounter = 0;
this.render();
if (this.dnd.canDrop(this.context.draggable.panel, this.panel) && this.context.draggable !== this) {
this._onDidDrop.fire({ from: this.context.draggable.panel, to: this.panel });
}
this.context.draggable = null;
}
private render(): void {
let backgroundColor: string | null = null;
if (this.dragOverCounter > 0) {
backgroundColor = (this.panel.dropBackground || PanelDraggable.DefaultDragOverBackgroundColor).toString();
}
this.panel.dropTargetElement.style.backgroundColor = backgroundColor || '';
}
}
export interface IPanelDndController {
canDrag(panel: Panel): boolean;
canDrop(panel: Panel, overPanel: Panel): boolean;
}
export class DefaultPanelDndController implements IPanelDndController {
canDrag(panel: Panel): boolean {
return true;
}
canDrop(panel: Panel, overPanel: Panel): boolean {
return true;
}
}
export interface IPanelViewOptions {
dnd?: IPanelDndController;
}
interface IPanelItem {
panel: Panel;
disposable: IDisposable;
}
export class PanelView extends Disposable {
private dnd: IPanelDndController | undefined;
private dndContext: IDndContext = { draggable: null };
private el: HTMLElement;
private panelItems: IPanelItem[] = [];
private width: number = 0;
private splitview: SplitView;
private animationTimer: number | undefined = undefined;
private _onDidDrop = this._register(new Emitter<{ from: Panel, to: Panel }>());
readonly onDidDrop: Event<{ from: Panel, to: Panel }> = this._onDidDrop.event;
readonly onDidSashChange: Event<number>;
constructor(container: HTMLElement, options: IPanelViewOptions = {}) {
super();
this.dnd = options.dnd;
this.el = append(container, $('.monaco-panel-view'));
this.splitview = this._register(new SplitView(this.el));
this.onDidSashChange = this.splitview.onDidSashChange;
}
addPanel(panel: Panel, size: number, index = this.splitview.length): void {
const disposables = new DisposableStore();
panel.onDidChangeExpansionState(this.setupAnimation, this, disposables);
const panelItem = { panel, disposable: disposables };
this.panelItems.splice(index, 0, panelItem);
panel.width = this.width;
this.splitview.addView(panel, size, index);
if (this.dnd) {
const draggable = new PanelDraggable(panel, this.dnd, this.dndContext);
disposables.add(draggable);
disposables.add(draggable.onDidDrop(this._onDidDrop.fire, this._onDidDrop));
}
}
removePanel(panel: Panel): void {
const index = firstIndex(this.panelItems, item => item.panel === panel);
if (index === -1) {
return;
}
this.splitview.removeView(index);
const panelItem = this.panelItems.splice(index, 1)[0];
panelItem.disposable.dispose();
}
movePanel(from: Panel, to: Panel): void {
const fromIndex = firstIndex(this.panelItems, item => item.panel === from);
const toIndex = firstIndex(this.panelItems, item => item.panel === to);
if (fromIndex === -1 || toIndex === -1) {
return;
}
const [panelItem] = this.panelItems.splice(fromIndex, 1);
this.panelItems.splice(toIndex, 0, panelItem);
this.splitview.moveView(fromIndex, toIndex);
}
resizePanel(panel: Panel, size: number): void {
const index = firstIndex(this.panelItems, item => item.panel === panel);
if (index === -1) {
return;
}
this.splitview.resizeView(index, size);
}
getPanelSize(panel: Panel): number {
const index = firstIndex(this.panelItems, item => item.panel === panel);
if (index === -1) {
return -1;
}
return this.splitview.getViewSize(index);
}
layout(height: number, width: number): void {
this.width = width;
for (const panelItem of this.panelItems) {
panelItem.panel.width = width;
}
this.splitview.layout(height);
}
private setupAnimation(): void {
if (typeof this.animationTimer === 'number') {
window.clearTimeout(this.animationTimer);
}
addClass(this.el, 'animated');
this.animationTimer = window.setTimeout(() => {
this.animationTimer = undefined;
removeClass(this.el, 'animated');
}, 200);
}
dispose(): void {
super.dispose();
this.panelItems.forEach(i => i.disposable.dispose());
}
}
| src/vs/base/browser/ui/splitview/panelview.ts | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.0008860175730660558,
0.00020109709294047207,
0.0001616527297301218,
0.0001683621812844649,
0.00011332245048834011
] |
{
"id": 4,
"code_window": [
"\t\tthis.telemetryService.publicLog('problems.filter', data);\n",
"\t}\n",
"\n",
"\tprotected updateClass(): void {\n",
"\t\tif (this.element) {\n",
"\t\t\tthis.element.className = this.action.class || '';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tif (this.element && this.container) {\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 305
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Delayer } from 'vs/base/common/async';
import * as DOM from 'vs/base/browser/dom';
import { Action, IActionChangeEvent, IAction } from 'vs/base/common/actions';
import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { KeyCode } from 'vs/base/common/keyCodes';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { TogglePanelAction } from 'vs/workbench/browser/panel';
import Messages from 'vs/workbench/contrib/markers/browser/messages';
import Constants from 'vs/workbench/contrib/markers/browser/constants';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { attachInputBoxStyler, attachStylerCallback, attachCheckboxStyler } from 'vs/platform/theme/common/styler';
import { IMarkersWorkbenchService } from 'vs/workbench/contrib/markers/browser/markers';
import { toDisposable } from 'vs/base/common/lifecycle';
import { BaseActionViewItem, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar';
import { badgeBackground, badgeForeground, contrastBorder } from 'vs/platform/theme/common/colorRegistry';
import { localize } from 'vs/nls';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ContextScopedHistoryInputBox } from 'vs/platform/browser/contextScopedHistoryWidget';
import { Marker } from 'vs/workbench/contrib/markers/browser/markersModel';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { Event, Emitter } from 'vs/base/common/event';
import { FilterOptions } from 'vs/workbench/contrib/markers/browser/markersFilterOptions';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
export class ToggleMarkersPanelAction extends TogglePanelAction {
public static readonly ID = 'workbench.actions.view.problems';
public static readonly LABEL = Messages.MARKERS_PANEL_TOGGLE_LABEL;
constructor(id: string, label: string,
@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
@IPanelService panelService: IPanelService,
@IMarkersWorkbenchService markersWorkbenchService: IMarkersWorkbenchService
) {
super(id, label, Constants.MARKERS_PANEL_ID, panelService, layoutService);
}
}
export class ShowProblemsPanelAction extends Action {
public static readonly ID = 'workbench.action.problems.focus';
public static readonly LABEL = Messages.MARKERS_PANEL_SHOW_LABEL;
constructor(id: string, label: string,
@IPanelService private readonly panelService: IPanelService
) {
super(id, label);
}
public run(): Promise<any> {
this.panelService.openPanel(Constants.MARKERS_PANEL_ID, true);
return Promise.resolve();
}
}
export interface IMarkersFilterActionChangeEvent extends IActionChangeEvent {
filterText?: boolean;
useFilesExclude?: boolean;
}
export interface IMarkersFilterActionOptions {
filterText: string;
filterHistory: string[];
useFilesExclude: boolean;
}
export class MarkersFilterAction extends Action {
public static readonly ID: string = 'workbench.actions.problems.filter';
private readonly _onFocus: Emitter<void> = this._register(new Emitter<void>());
readonly onFocus: Event<void> = this._onFocus.event;
constructor(options: IMarkersFilterActionOptions) {
super(MarkersFilterAction.ID, Messages.MARKERS_PANEL_ACTION_TOOLTIP_FILTER, 'markers-panel-action-filter', true);
this._filterText = options.filterText;
this._useFilesExclude = options.useFilesExclude;
this.filterHistory = options.filterHistory;
}
private _filterText: string;
get filterText(): string {
return this._filterText;
}
set filterText(filterText: string) {
if (this._filterText !== filterText) {
this._filterText = filterText;
this._onDidChange.fire(<IMarkersFilterActionChangeEvent>{ filterText: true });
}
}
filterHistory: string[];
private _useFilesExclude: boolean;
get useFilesExclude(): boolean {
return this._useFilesExclude;
}
set useFilesExclude(filesExclude: boolean) {
if (this._useFilesExclude !== filesExclude) {
this._useFilesExclude = filesExclude;
this._onDidChange.fire(<IMarkersFilterActionChangeEvent>{ useFilesExclude: true });
}
}
focus(): void {
this._onFocus.fire();
}
layout(width: number): void {
if (width < 400) {
this.class = 'markers-panel-action-filter small';
} else {
this.class = 'markers-panel-action-filter';
}
}
}
export interface IMarkerFilterController {
onDidFilter: Event<void>;
getFilterOptions(): FilterOptions;
getFilterStats(): { total: number, filtered: number };
}
export class MarkersFilterActionViewItem extends BaseActionViewItem {
private delayedFilterUpdate: Delayer<void>;
private filterInputBox: HistoryInputBox | null = null;
private filterBadge: HTMLElement | null = null;
private focusContextKey: IContextKey<boolean>;
constructor(
readonly action: MarkersFilterAction,
private filterController: IMarkerFilterController,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IContextViewService private readonly contextViewService: IContextViewService,
@IThemeService private readonly themeService: IThemeService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IContextKeyService contextKeyService: IContextKeyService
) {
super(null, action);
this.focusContextKey = Constants.MarkerPanelFilterFocusContextKey.bindTo(contextKeyService);
this.delayedFilterUpdate = new Delayer<void>(200);
this._register(toDisposable(() => this.delayedFilterUpdate.cancel()));
this._register(action.onFocus(() => this.focus()));
}
render(container: HTMLElement): void {
DOM.addClass(container, 'markers-panel-action-filter-container');
this.element = DOM.append(container, DOM.$(''));
this.element.className = this.action.class || '';
this.createInput(this.element);
this.createControls(this.element);
this.adjustInputBox();
}
focus(): void {
if (this.filterInputBox) {
this.filterInputBox.focus();
}
}
private createInput(container: HTMLElement): void {
this.filterInputBox = this._register(this.instantiationService.createInstance(ContextScopedHistoryInputBox, container, this.contextViewService, {
placeholder: Messages.MARKERS_PANEL_FILTER_PLACEHOLDER,
ariaLabel: Messages.MARKERS_PANEL_FILTER_ARIA_LABEL,
history: this.action.filterHistory
}));
this.filterInputBox.inputElement.setAttribute('aria-labelledby', 'markers-panel-arialabel');
this._register(attachInputBoxStyler(this.filterInputBox, this.themeService));
this.filterInputBox.value = this.action.filterText;
this._register(this.filterInputBox.onDidChange(filter => this.delayedFilterUpdate.trigger(() => this.onDidInputChange(this.filterInputBox!))));
this._register(this.action.onDidChange((event: IMarkersFilterActionChangeEvent) => {
if (event.filterText) {
this.filterInputBox!.value = this.action.filterText;
}
}));
this._register(DOM.addStandardDisposableListener(this.filterInputBox.inputElement, DOM.EventType.KEY_DOWN, (e: any) => this.onInputKeyDown(e, this.filterInputBox!)));
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_DOWN, this.handleKeyboardEvent));
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_UP, this.handleKeyboardEvent));
const focusTracker = this._register(DOM.trackFocus(this.filterInputBox.inputElement));
this._register(focusTracker.onDidFocus(() => this.focusContextKey.set(true)));
this._register(focusTracker.onDidBlur(() => this.focusContextKey.set(false)));
this._register(toDisposable(() => this.focusContextKey.reset()));
}
private createControls(container: HTMLElement): void {
const controlsContainer = DOM.append(container, DOM.$('.markers-panel-filter-controls'));
this.createBadge(controlsContainer);
this.createFilesExcludeCheckbox(controlsContainer);
}
private createBadge(container: HTMLElement): void {
const filterBadge = this.filterBadge = DOM.append(container, DOM.$('.markers-panel-filter-badge'));
this._register(attachStylerCallback(this.themeService, { badgeBackground, badgeForeground, contrastBorder }, colors => {
const background = colors.badgeBackground ? colors.badgeBackground.toString() : '';
const foreground = colors.badgeForeground ? colors.badgeForeground.toString() : '';
const border = colors.contrastBorder ? colors.contrastBorder.toString() : '';
filterBadge.style.backgroundColor = background;
filterBadge.style.borderWidth = border ? '1px' : '';
filterBadge.style.borderStyle = border ? 'solid' : '';
filterBadge.style.borderColor = border;
filterBadge.style.color = foreground;
}));
this.updateBadge();
this._register(this.filterController.onDidFilter(() => this.updateBadge()));
}
private createFilesExcludeCheckbox(container: HTMLElement): void {
const filesExcludeFilter = this._register(new Checkbox({
actionClassName: 'codicon codicon-exclude',
title: this.action.useFilesExclude ? Messages.MARKERS_PANEL_ACTION_TOOLTIP_DO_NOT_USE_FILES_EXCLUDE : Messages.MARKERS_PANEL_ACTION_TOOLTIP_USE_FILES_EXCLUDE,
isChecked: this.action.useFilesExclude
}));
this._register(filesExcludeFilter.onChange(() => {
filesExcludeFilter.domNode.title = filesExcludeFilter.checked ? Messages.MARKERS_PANEL_ACTION_TOOLTIP_DO_NOT_USE_FILES_EXCLUDE : Messages.MARKERS_PANEL_ACTION_TOOLTIP_USE_FILES_EXCLUDE;
this.action.useFilesExclude = filesExcludeFilter.checked;
this.focus();
}));
this._register(this.action.onDidChange((event: IMarkersFilterActionChangeEvent) => {
if (event.useFilesExclude) {
filesExcludeFilter.checked = this.action.useFilesExclude;
}
}));
this._register(attachCheckboxStyler(filesExcludeFilter, this.themeService));
container.appendChild(filesExcludeFilter.domNode);
}
private onDidInputChange(inputbox: HistoryInputBox) {
inputbox.addToHistory();
this.action.filterText = inputbox.value;
this.action.filterHistory = inputbox.getHistory();
this.reportFilteringUsed();
}
private updateBadge(): void {
if (this.filterBadge) {
const { total, filtered } = this.filterController.getFilterStats();
DOM.toggleClass(this.filterBadge, 'hidden', total === filtered || filtered === 0);
this.filterBadge.textContent = localize('showing filtered problems', "Showing {0} of {1}", filtered, total);
this.adjustInputBox();
}
}
private adjustInputBox(): void {
if (this.element && this.filterInputBox && this.filterBadge) {
this.filterInputBox.inputElement.style.paddingRight = DOM.hasClass(this.element, 'small') || DOM.hasClass(this.filterBadge, 'hidden') ? '25px' : '150px';
}
}
// Action toolbar is swallowing some keys for action items which should not be for an input box
private handleKeyboardEvent(event: StandardKeyboardEvent) {
if (event.equals(KeyCode.Space)
|| event.equals(KeyCode.LeftArrow)
|| event.equals(KeyCode.RightArrow)
|| event.equals(KeyCode.Escape)
) {
event.stopPropagation();
}
}
private onInputKeyDown(event: StandardKeyboardEvent, filterInputBox: HistoryInputBox) {
let handled = false;
if (event.equals(KeyCode.Escape)) {
filterInputBox.value = '';
handled = true;
}
if (handled) {
event.stopPropagation();
event.preventDefault();
}
}
private reportFilteringUsed(): void {
const filterOptions = this.filterController.getFilterOptions();
const data = {
errors: filterOptions.filterErrors,
warnings: filterOptions.filterWarnings,
infos: filterOptions.filterInfos,
};
/* __GDPR__
"problems.filter" : {
"errors" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"warnings": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"infos": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
this.telemetryService.publicLog('problems.filter', data);
}
protected updateClass(): void {
if (this.element) {
this.element.className = this.action.class || '';
this.adjustInputBox();
}
}
}
export class QuickFixAction extends Action {
public static readonly ID: string = 'workbench.actions.problems.quickfix';
private static readonly CLASS: string = 'markers-panel-action-quickfix codicon-lightbulb';
private static readonly AUTO_FIX_CLASS: string = QuickFixAction.CLASS + ' autofixable';
private readonly _onShowQuickFixes = this._register(new Emitter<void>());
readonly onShowQuickFixes: Event<void> = this._onShowQuickFixes.event;
private _quickFixes: IAction[] = [];
get quickFixes(): IAction[] {
return this._quickFixes;
}
set quickFixes(quickFixes: IAction[]) {
this._quickFixes = quickFixes;
this.enabled = this._quickFixes.length > 0;
}
autoFixable(autofixable: boolean) {
this.class = autofixable ? QuickFixAction.AUTO_FIX_CLASS : QuickFixAction.CLASS;
}
constructor(
readonly marker: Marker,
) {
super(QuickFixAction.ID, Messages.MARKERS_PANEL_ACTION_TOOLTIP_QUICKFIX, QuickFixAction.CLASS, false);
}
run(): Promise<void> {
this._onShowQuickFixes.fire();
return Promise.resolve();
}
}
export class QuickFixActionViewItem extends ActionViewItem {
constructor(action: QuickFixAction,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super(null, action, { icon: true, label: false });
}
public onClick(event: DOM.EventLike): void {
DOM.EventHelper.stop(event, true);
this.showQuickFixes();
}
public showQuickFixes(): void {
if (!this.element) {
return;
}
if (!this.isEnabled()) {
return;
}
const elementPosition = DOM.getDomNodePagePosition(this.element);
const quickFixes = (<QuickFixAction>this.getAction()).quickFixes;
if (quickFixes.length) {
this.contextMenuService.showContextMenu({
getAnchor: () => ({ x: elementPosition.left + 10, y: elementPosition.top + elementPosition.height + 4 }),
getActions: () => quickFixes
});
}
}
}
| src/vs/workbench/contrib/markers/browser/markersPanelActions.ts | 1 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.9974448680877686,
0.02806341089308262,
0.00016640681133139879,
0.00021041985019110143,
0.1594362109899521
] |
{
"id": 4,
"code_window": [
"\t\tthis.telemetryService.publicLog('problems.filter', data);\n",
"\t}\n",
"\n",
"\tprotected updateClass(): void {\n",
"\t\tif (this.element) {\n",
"\t\t\tthis.element.className = this.action.class || '';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tif (this.element && this.container) {\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 305
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'mocha';
import * as assert from 'assert';
import { withRandomFileEditor } from './testUtils';
import * as vscode from 'vscode';
import { parsePartialStylesheet, getNode } from '../util';
import { isValidLocationForEmmetAbbreviation } from '../abbreviationActions';
suite('Tests for partial parse of Stylesheets', () => {
function isValid(doc: vscode.TextDocument, range: vscode.Range, syntax: string): boolean {
const rootNode = parsePartialStylesheet(doc, range.end);
const currentNode = getNode(rootNode, range.end, true);
return isValidLocationForEmmetAbbreviation(doc, rootNode, currentNode, syntax, range.end, range);
}
test('Ignore block comment inside rule', function (): any {
const cssContents = `
p {
margin: p ;
/*dn: none; p */ p
p
p.
} p
`;
return withRandomFileEditor(cssContents, '.css', (_, doc) => {
let rangesForEmmet = [
new vscode.Range(3, 18, 3, 19), // Same line after block comment
new vscode.Range(4, 1, 4, 2), // p after block comment
new vscode.Range(5, 1, 5, 3) // p. after block comment
];
let rangesNotEmmet = [
new vscode.Range(1, 0, 1, 1), // Selector
new vscode.Range(2, 9, 2, 10), // Property value
new vscode.Range(3, 3, 3, 5), // dn inside block comment
new vscode.Range(3, 13, 3, 14), // p just before ending of block comment
new vscode.Range(6, 2, 6, 3) // p after ending of block
]
rangesForEmmet.forEach(range => {
assert.equal(isValid(doc, range, 'css'), true);
});
rangesNotEmmet.forEach(range => {
assert.equal(isValid(doc, range, 'css'), false);
});
return Promise.resolve();
});
});
test('Ignore commented braces', function (): any {
const sassContents = `
.foo
// .foo { brs
/* .foo { op.3
dn {
*/
@
} bg
`;
return withRandomFileEditor(sassContents, '.scss', (_, doc) => {
let rangesNotEmmet = [
new vscode.Range(1, 0, 1, 4), // Selector
new vscode.Range(2, 3, 2, 7), // Line commented selector
new vscode.Range(3, 3, 3, 7), // Block commented selector
new vscode.Range(4, 0, 4, 2), // dn inside block comment
new vscode.Range(6, 1, 6, 2), // @ inside a rule whose opening brace is commented
new vscode.Range(7, 2, 7, 4) // bg after ending of badly constructed block
];
rangesNotEmmet.forEach(range => {
assert.equal(isValid(doc, range, 'scss'), false);
});
return Promise.resolve();
});
});
test('Block comment between selector and open brace', function (): any {
const cssContents = `
p
/* First line
of a multiline
comment */
{
margin: p ;
/*dn: none; p */ p
p
p.
} p
`;
return withRandomFileEditor(cssContents, '.css', (_, doc) => {
let rangesForEmmet = [
new vscode.Range(7, 18, 7, 19), // Same line after block comment
new vscode.Range(8, 1, 8, 2), // p after block comment
new vscode.Range(9, 1, 9, 3) // p. after block comment
];
let rangesNotEmmet = [
new vscode.Range(1, 2, 1, 3), // Selector
new vscode.Range(3, 3, 3, 4), // Inside multiline comment
new vscode.Range(5, 0, 5, 1), // Opening Brace
new vscode.Range(6, 9, 6, 10), // Property value
new vscode.Range(7, 3, 7, 5), // dn inside block comment
new vscode.Range(7, 13, 7, 14), // p just before ending of block comment
new vscode.Range(10, 2, 10, 3) // p after ending of block
];
rangesForEmmet.forEach(range => {
assert.equal(isValid(doc, range, 'css'), true);
});
rangesNotEmmet.forEach(range => {
assert.equal(isValid(doc, range, 'css'), false);
});
return Promise.resolve();
});
});
test('Nested and consecutive rulesets with errors', function (): any {
const sassContents = `
.foo{
a
a
}}{ p
}
.bar{
@
.rudi {
@
}
}}}
`;
return withRandomFileEditor(sassContents, '.scss', (_, doc) => {
let rangesForEmmet = [
new vscode.Range(2, 1, 2, 2), // Inside a ruleset before errors
new vscode.Range(3, 1, 3, 2), // Inside a ruleset after no serious error
new vscode.Range(7, 1, 7, 2), // @ inside a so far well structured ruleset
new vscode.Range(9, 2, 9, 3), // @ inside a so far well structured nested ruleset
];
let rangesNotEmmet = [
new vscode.Range(4, 4, 4, 5), // p inside ruleset without proper selector
new vscode.Range(6, 3, 6, 4) // In selector
];
rangesForEmmet.forEach(range => {
assert.equal(isValid(doc, range, 'scss'), true);
});
rangesNotEmmet.forEach(range => {
assert.equal(isValid(doc, range, 'scss'), false);
});
return Promise.resolve();
});
});
test('One liner sass', function (): any {
const sassContents = `
.foo{dn}.bar{.boo{dn}dn}.comd{/*{dn*/p{div{dn}} }.foo{.other{dn}} dn
`;
return withRandomFileEditor(sassContents, '.scss', (_, doc) => {
let rangesForEmmet = [
new vscode.Range(1, 5, 1, 7), // Inside a ruleset
new vscode.Range(1, 18, 1, 20), // Inside a nested ruleset
new vscode.Range(1, 21, 1, 23), // Inside ruleset after nested one.
new vscode.Range(1, 43, 1, 45), // Inside nested ruleset after comment
new vscode.Range(1, 61, 1, 63) // Inside nested ruleset
];
let rangesNotEmmet = [
new vscode.Range(1, 3, 1, 4), // In foo selector
new vscode.Range(1, 10, 1, 11), // In bar selector
new vscode.Range(1, 15, 1, 16), // In boo selector
new vscode.Range(1, 28, 1, 29), // In comd selector
new vscode.Range(1, 33, 1, 34), // In commented dn
new vscode.Range(1, 37, 1, 38), // In p selector
new vscode.Range(1, 39, 1, 42), // In div selector
new vscode.Range(1, 66, 1, 68) // Outside any ruleset
];
rangesForEmmet.forEach(range => {
assert.equal(isValid(doc, range, 'scss'), true);
});
rangesNotEmmet.forEach(range => {
assert.equal(isValid(doc, range, 'scss'), false);
});
return Promise.resolve();
});
});
test('Variables and interpolation', function (): any {
const sassContents = `
p.#{dn} {
p.3
#{$attr}-color: blue;
dn
} op
.foo{nes{ted}} {
dn
}
`;
return withRandomFileEditor(sassContents, '.scss', (_, doc) => {
let rangesForEmmet = [
new vscode.Range(2, 1, 2, 4), // p.3 inside a ruleset whose selector uses interpolation
new vscode.Range(4, 1, 4, 3) // dn inside ruleset after property with variable
];
let rangesNotEmmet = [
new vscode.Range(1, 0, 1, 1), // In p in selector
new vscode.Range(1, 2, 1, 3), // In # in selector
new vscode.Range(1, 4, 1, 6), // In dn inside variable in selector
new vscode.Range(3, 7, 3, 8), // r of attr inside variable
new vscode.Range(5, 2, 5, 4), // op after ruleset
new vscode.Range(7, 1, 7, 3), // dn inside ruleset whose selector uses nested interpolation
new vscode.Range(3, 1, 3, 2), // # inside ruleset
];
rangesForEmmet.forEach(range => {
assert.equal(isValid(doc, range, 'scss'), true);
});
rangesNotEmmet.forEach(range => {
assert.equal(isValid(doc, range, 'scss'), false);
});
return Promise.resolve();
});
});
test('Comments in sass', function (): any {
const sassContents = `
.foo{
/* p // p */ brs6-2p
dn
}
p
/* c
om
ment */{
m10
}
.boo{
op.3
}
`;
return withRandomFileEditor(sassContents, '.scss', (_, doc) => {
let rangesForEmmet = [
new vscode.Range(2, 14, 2, 21), // brs6-2p with a block commented line comment ('/* */' overrides '//')
new vscode.Range(3, 1, 3, 3), // dn after a line with combined comments inside a ruleset
new vscode.Range(9, 1, 9, 4), // m10 inside ruleset whose selector is before a comment
new vscode.Range(12, 1, 12, 5) // op3 inside a ruleset with commented extra braces
];
let rangesNotEmmet = [
new vscode.Range(2, 4, 2, 5), // In p inside block comment
new vscode.Range(2, 9, 2, 10), // In p inside block comment and after line comment
new vscode.Range(6, 3, 6, 4) // In c inside block comment
];
rangesForEmmet.forEach(range => {
assert.equal(isValid(doc, range, 'scss'), true);
});
rangesNotEmmet.forEach(range => {
assert.equal(isValid(doc, range, 'scss'), false);
});
return Promise.resolve();
});
});
}); | extensions/emmet/src/test/partialParsingStylesheet.test.ts | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00017784415103960782,
0.0001734174002194777,
0.00016686155868228525,
0.00017352940631099045,
0.0000026125703698198777
] |
{
"id": 4,
"code_window": [
"\t\tthis.telemetryService.publicLog('problems.filter', data);\n",
"\t}\n",
"\n",
"\tprotected updateClass(): void {\n",
"\t\tif (this.element) {\n",
"\t\t\tthis.element.className = this.action.class || '';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tif (this.element && this.container) {\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 305
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI as uri } from 'vs/base/common/uri';
import { normalize, isAbsolute } from 'vs/base/common/path';
import * as resources from 'vs/base/common/resources';
import { DEBUG_SCHEME } from 'vs/workbench/contrib/debug/common/debug';
import { IRange } from 'vs/editor/common/core/range';
import { IEditorService, SIDE_GROUP, ACTIVE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { Schemas } from 'vs/base/common/network';
import { isUri } from 'vs/workbench/contrib/debug/common/debugUtils';
import { ITextEditor } from 'vs/workbench/common/editor';
export const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
/**
* Debug URI format
*
* a debug URI represents a Source object and the debug session where the Source comes from.
*
* debug:arbitrary_path?session=123e4567-e89b-12d3-a456-426655440000&ref=1016
* \___/ \____________/ \__________________________________________/ \______/
* | | | |
* scheme source.path session id source.reference
*
*
*/
export class Source {
readonly uri: uri;
available: boolean;
raw: DebugProtocol.Source;
constructor(raw_: DebugProtocol.Source | undefined, sessionId: string) {
let path: string;
if (raw_) {
this.raw = raw_;
path = this.raw.path || this.raw.name || '';
this.available = true;
} else {
this.raw = { name: UNKNOWN_SOURCE_LABEL };
this.available = false;
path = `${DEBUG_SCHEME}:${UNKNOWN_SOURCE_LABEL}`;
}
if (typeof this.raw.sourceReference === 'number' && this.raw.sourceReference > 0) {
this.uri = uri.from({
scheme: DEBUG_SCHEME,
path,
query: `session=${sessionId}&ref=${this.raw.sourceReference}`
});
} else {
if (isUri(path)) { // path looks like a uri
this.uri = uri.parse(path);
} else {
// assume a filesystem path
if (isAbsolute(path)) {
this.uri = uri.file(path);
} else {
// path is relative: since VS Code cannot deal with this by itself
// create a debug url that will result in a DAP 'source' request when the url is resolved.
this.uri = uri.from({
scheme: DEBUG_SCHEME,
path,
query: `session=${sessionId}`
});
}
}
}
}
get name() {
return this.raw.name || resources.basenameOrAuthority(this.uri);
}
get origin() {
return this.raw.origin;
}
get presentationHint() {
return this.raw.presentationHint;
}
get reference() {
return this.raw.sourceReference;
}
get inMemory() {
return this.uri.scheme === DEBUG_SCHEME;
}
openInEditor(editorService: IEditorService, selection: IRange, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): Promise<ITextEditor | undefined> {
return !this.available ? Promise.resolve(undefined) : editorService.openEditor({
resource: this.uri,
description: this.origin,
options: {
preserveFocus,
selection,
revealIfOpened: true,
revealInCenterIfOutsideViewport: true,
pinned: pinned || (!preserveFocus && !this.inMemory)
}
}, sideBySide ? SIDE_GROUP : ACTIVE_GROUP);
}
static getEncodedDebugData(modelUri: uri): { name: string, path: string, sessionId?: string, sourceReference?: number } {
let path: string;
let sourceReference: number | undefined;
let sessionId: string | undefined;
switch (modelUri.scheme) {
case Schemas.file:
path = normalize(modelUri.fsPath);
break;
case DEBUG_SCHEME:
path = modelUri.path;
if (modelUri.query) {
const keyvalues = modelUri.query.split('&');
for (let keyvalue of keyvalues) {
const pair = keyvalue.split('=');
if (pair.length === 2) {
switch (pair[0]) {
case 'session':
sessionId = pair[1];
break;
case 'ref':
sourceReference = parseInt(pair[1]);
break;
}
}
}
}
break;
default:
path = modelUri.toString();
break;
}
return {
name: resources.basenameOrAuthority(modelUri),
path,
sourceReference,
sessionId
};
}
}
| src/vs/workbench/contrib/debug/common/debugSource.ts | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00017633053357712924,
0.00017183501040562987,
0.00016488235269207507,
0.00017237200518138707,
0.0000027587304884946207
] |
{
"id": 4,
"code_window": [
"\t\tthis.telemetryService.publicLog('problems.filter', data);\n",
"\t}\n",
"\n",
"\tprotected updateClass(): void {\n",
"\t\tif (this.element) {\n",
"\t\t\tthis.element.className = this.action.class || '';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tif (this.element && this.container) {\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "replace",
"edit_start_line_idx": 305
} | /*---------------------------------------------------------------------------------------------
* 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 'vscode-nls';
import * as vscode from 'vscode';
import {
detectNpmScriptsForFolder,
findScriptAtPosition,
runScript,
FolderTaskItem
} from './tasks';
const localize = nls.loadMessageBundle();
export function runSelectedScript() {
let editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
let document = editor.document;
let contents = document.getText();
let selection = editor.selection;
let offset = document.offsetAt(selection.anchor);
let script = findScriptAtPosition(contents, offset);
if (script) {
runScript(script, document);
} else {
let message = localize('noScriptFound', 'Could not find a valid npm script at the selection.');
vscode.window.showErrorMessage(message);
}
}
export async function selectAndRunScriptFromFolder(selectedFolder: vscode.Uri) {
let taskList: FolderTaskItem[] = await detectNpmScriptsForFolder(selectedFolder);
if (taskList && taskList.length > 0) {
const quickPick = vscode.window.createQuickPick<FolderTaskItem>();
quickPick.title = 'Run NPM script in Folder';
quickPick.placeholder = 'Select an npm script';
quickPick.items = taskList;
const toDispose: vscode.Disposable[] = [];
let pickPromise = new Promise<FolderTaskItem | undefined>((c) => {
toDispose.push(quickPick.onDidAccept(() => {
toDispose.forEach(d => d.dispose());
c(quickPick.selectedItems[0]);
}));
toDispose.push(quickPick.onDidHide(() => {
toDispose.forEach(d => d.dispose());
c(undefined);
}));
});
quickPick.show();
let result = await pickPromise;
quickPick.dispose();
if (result) {
vscode.tasks.executeTask(result.task);
}
}
else {
vscode.window.showInformationMessage(`No npm scripts found in ${selectedFolder.fsPath}`, { modal: true });
}
}
| extensions/npm/src/commands.ts | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00017702358309179544,
0.0001736289559630677,
0.00017015445337165147,
0.00017411248700227588,
0.00000242296277974674
] |
{
"id": 5,
"code_window": [
"\t\t\tthis.element.className = this.action.class || '';\n",
"\t\t\tthis.adjustInputBox();\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tDOM.toggleClass(this.container, 'grow', DOM.hasClass(this.element, 'grow'));\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "add",
"edit_start_line_idx": 307
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Delayer } from 'vs/base/common/async';
import * as DOM from 'vs/base/browser/dom';
import { Action, IActionChangeEvent, IAction } from 'vs/base/common/actions';
import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { KeyCode } from 'vs/base/common/keyCodes';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { TogglePanelAction } from 'vs/workbench/browser/panel';
import Messages from 'vs/workbench/contrib/markers/browser/messages';
import Constants from 'vs/workbench/contrib/markers/browser/constants';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { attachInputBoxStyler, attachStylerCallback, attachCheckboxStyler } from 'vs/platform/theme/common/styler';
import { IMarkersWorkbenchService } from 'vs/workbench/contrib/markers/browser/markers';
import { toDisposable } from 'vs/base/common/lifecycle';
import { BaseActionViewItem, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar';
import { badgeBackground, badgeForeground, contrastBorder } from 'vs/platform/theme/common/colorRegistry';
import { localize } from 'vs/nls';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ContextScopedHistoryInputBox } from 'vs/platform/browser/contextScopedHistoryWidget';
import { Marker } from 'vs/workbench/contrib/markers/browser/markersModel';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { Event, Emitter } from 'vs/base/common/event';
import { FilterOptions } from 'vs/workbench/contrib/markers/browser/markersFilterOptions';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
export class ToggleMarkersPanelAction extends TogglePanelAction {
public static readonly ID = 'workbench.actions.view.problems';
public static readonly LABEL = Messages.MARKERS_PANEL_TOGGLE_LABEL;
constructor(id: string, label: string,
@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
@IPanelService panelService: IPanelService,
@IMarkersWorkbenchService markersWorkbenchService: IMarkersWorkbenchService
) {
super(id, label, Constants.MARKERS_PANEL_ID, panelService, layoutService);
}
}
export class ShowProblemsPanelAction extends Action {
public static readonly ID = 'workbench.action.problems.focus';
public static readonly LABEL = Messages.MARKERS_PANEL_SHOW_LABEL;
constructor(id: string, label: string,
@IPanelService private readonly panelService: IPanelService
) {
super(id, label);
}
public run(): Promise<any> {
this.panelService.openPanel(Constants.MARKERS_PANEL_ID, true);
return Promise.resolve();
}
}
export interface IMarkersFilterActionChangeEvent extends IActionChangeEvent {
filterText?: boolean;
useFilesExclude?: boolean;
}
export interface IMarkersFilterActionOptions {
filterText: string;
filterHistory: string[];
useFilesExclude: boolean;
}
export class MarkersFilterAction extends Action {
public static readonly ID: string = 'workbench.actions.problems.filter';
private readonly _onFocus: Emitter<void> = this._register(new Emitter<void>());
readonly onFocus: Event<void> = this._onFocus.event;
constructor(options: IMarkersFilterActionOptions) {
super(MarkersFilterAction.ID, Messages.MARKERS_PANEL_ACTION_TOOLTIP_FILTER, 'markers-panel-action-filter', true);
this._filterText = options.filterText;
this._useFilesExclude = options.useFilesExclude;
this.filterHistory = options.filterHistory;
}
private _filterText: string;
get filterText(): string {
return this._filterText;
}
set filterText(filterText: string) {
if (this._filterText !== filterText) {
this._filterText = filterText;
this._onDidChange.fire(<IMarkersFilterActionChangeEvent>{ filterText: true });
}
}
filterHistory: string[];
private _useFilesExclude: boolean;
get useFilesExclude(): boolean {
return this._useFilesExclude;
}
set useFilesExclude(filesExclude: boolean) {
if (this._useFilesExclude !== filesExclude) {
this._useFilesExclude = filesExclude;
this._onDidChange.fire(<IMarkersFilterActionChangeEvent>{ useFilesExclude: true });
}
}
focus(): void {
this._onFocus.fire();
}
layout(width: number): void {
if (width < 400) {
this.class = 'markers-panel-action-filter small';
} else {
this.class = 'markers-panel-action-filter';
}
}
}
export interface IMarkerFilterController {
onDidFilter: Event<void>;
getFilterOptions(): FilterOptions;
getFilterStats(): { total: number, filtered: number };
}
export class MarkersFilterActionViewItem extends BaseActionViewItem {
private delayedFilterUpdate: Delayer<void>;
private filterInputBox: HistoryInputBox | null = null;
private filterBadge: HTMLElement | null = null;
private focusContextKey: IContextKey<boolean>;
constructor(
readonly action: MarkersFilterAction,
private filterController: IMarkerFilterController,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IContextViewService private readonly contextViewService: IContextViewService,
@IThemeService private readonly themeService: IThemeService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IContextKeyService contextKeyService: IContextKeyService
) {
super(null, action);
this.focusContextKey = Constants.MarkerPanelFilterFocusContextKey.bindTo(contextKeyService);
this.delayedFilterUpdate = new Delayer<void>(200);
this._register(toDisposable(() => this.delayedFilterUpdate.cancel()));
this._register(action.onFocus(() => this.focus()));
}
render(container: HTMLElement): void {
DOM.addClass(container, 'markers-panel-action-filter-container');
this.element = DOM.append(container, DOM.$(''));
this.element.className = this.action.class || '';
this.createInput(this.element);
this.createControls(this.element);
this.adjustInputBox();
}
focus(): void {
if (this.filterInputBox) {
this.filterInputBox.focus();
}
}
private createInput(container: HTMLElement): void {
this.filterInputBox = this._register(this.instantiationService.createInstance(ContextScopedHistoryInputBox, container, this.contextViewService, {
placeholder: Messages.MARKERS_PANEL_FILTER_PLACEHOLDER,
ariaLabel: Messages.MARKERS_PANEL_FILTER_ARIA_LABEL,
history: this.action.filterHistory
}));
this.filterInputBox.inputElement.setAttribute('aria-labelledby', 'markers-panel-arialabel');
this._register(attachInputBoxStyler(this.filterInputBox, this.themeService));
this.filterInputBox.value = this.action.filterText;
this._register(this.filterInputBox.onDidChange(filter => this.delayedFilterUpdate.trigger(() => this.onDidInputChange(this.filterInputBox!))));
this._register(this.action.onDidChange((event: IMarkersFilterActionChangeEvent) => {
if (event.filterText) {
this.filterInputBox!.value = this.action.filterText;
}
}));
this._register(DOM.addStandardDisposableListener(this.filterInputBox.inputElement, DOM.EventType.KEY_DOWN, (e: any) => this.onInputKeyDown(e, this.filterInputBox!)));
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_DOWN, this.handleKeyboardEvent));
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_UP, this.handleKeyboardEvent));
const focusTracker = this._register(DOM.trackFocus(this.filterInputBox.inputElement));
this._register(focusTracker.onDidFocus(() => this.focusContextKey.set(true)));
this._register(focusTracker.onDidBlur(() => this.focusContextKey.set(false)));
this._register(toDisposable(() => this.focusContextKey.reset()));
}
private createControls(container: HTMLElement): void {
const controlsContainer = DOM.append(container, DOM.$('.markers-panel-filter-controls'));
this.createBadge(controlsContainer);
this.createFilesExcludeCheckbox(controlsContainer);
}
private createBadge(container: HTMLElement): void {
const filterBadge = this.filterBadge = DOM.append(container, DOM.$('.markers-panel-filter-badge'));
this._register(attachStylerCallback(this.themeService, { badgeBackground, badgeForeground, contrastBorder }, colors => {
const background = colors.badgeBackground ? colors.badgeBackground.toString() : '';
const foreground = colors.badgeForeground ? colors.badgeForeground.toString() : '';
const border = colors.contrastBorder ? colors.contrastBorder.toString() : '';
filterBadge.style.backgroundColor = background;
filterBadge.style.borderWidth = border ? '1px' : '';
filterBadge.style.borderStyle = border ? 'solid' : '';
filterBadge.style.borderColor = border;
filterBadge.style.color = foreground;
}));
this.updateBadge();
this._register(this.filterController.onDidFilter(() => this.updateBadge()));
}
private createFilesExcludeCheckbox(container: HTMLElement): void {
const filesExcludeFilter = this._register(new Checkbox({
actionClassName: 'codicon codicon-exclude',
title: this.action.useFilesExclude ? Messages.MARKERS_PANEL_ACTION_TOOLTIP_DO_NOT_USE_FILES_EXCLUDE : Messages.MARKERS_PANEL_ACTION_TOOLTIP_USE_FILES_EXCLUDE,
isChecked: this.action.useFilesExclude
}));
this._register(filesExcludeFilter.onChange(() => {
filesExcludeFilter.domNode.title = filesExcludeFilter.checked ? Messages.MARKERS_PANEL_ACTION_TOOLTIP_DO_NOT_USE_FILES_EXCLUDE : Messages.MARKERS_PANEL_ACTION_TOOLTIP_USE_FILES_EXCLUDE;
this.action.useFilesExclude = filesExcludeFilter.checked;
this.focus();
}));
this._register(this.action.onDidChange((event: IMarkersFilterActionChangeEvent) => {
if (event.useFilesExclude) {
filesExcludeFilter.checked = this.action.useFilesExclude;
}
}));
this._register(attachCheckboxStyler(filesExcludeFilter, this.themeService));
container.appendChild(filesExcludeFilter.domNode);
}
private onDidInputChange(inputbox: HistoryInputBox) {
inputbox.addToHistory();
this.action.filterText = inputbox.value;
this.action.filterHistory = inputbox.getHistory();
this.reportFilteringUsed();
}
private updateBadge(): void {
if (this.filterBadge) {
const { total, filtered } = this.filterController.getFilterStats();
DOM.toggleClass(this.filterBadge, 'hidden', total === filtered || filtered === 0);
this.filterBadge.textContent = localize('showing filtered problems', "Showing {0} of {1}", filtered, total);
this.adjustInputBox();
}
}
private adjustInputBox(): void {
if (this.element && this.filterInputBox && this.filterBadge) {
this.filterInputBox.inputElement.style.paddingRight = DOM.hasClass(this.element, 'small') || DOM.hasClass(this.filterBadge, 'hidden') ? '25px' : '150px';
}
}
// Action toolbar is swallowing some keys for action items which should not be for an input box
private handleKeyboardEvent(event: StandardKeyboardEvent) {
if (event.equals(KeyCode.Space)
|| event.equals(KeyCode.LeftArrow)
|| event.equals(KeyCode.RightArrow)
|| event.equals(KeyCode.Escape)
) {
event.stopPropagation();
}
}
private onInputKeyDown(event: StandardKeyboardEvent, filterInputBox: HistoryInputBox) {
let handled = false;
if (event.equals(KeyCode.Escape)) {
filterInputBox.value = '';
handled = true;
}
if (handled) {
event.stopPropagation();
event.preventDefault();
}
}
private reportFilteringUsed(): void {
const filterOptions = this.filterController.getFilterOptions();
const data = {
errors: filterOptions.filterErrors,
warnings: filterOptions.filterWarnings,
infos: filterOptions.filterInfos,
};
/* __GDPR__
"problems.filter" : {
"errors" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"warnings": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"infos": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
this.telemetryService.publicLog('problems.filter', data);
}
protected updateClass(): void {
if (this.element) {
this.element.className = this.action.class || '';
this.adjustInputBox();
}
}
}
export class QuickFixAction extends Action {
public static readonly ID: string = 'workbench.actions.problems.quickfix';
private static readonly CLASS: string = 'markers-panel-action-quickfix codicon-lightbulb';
private static readonly AUTO_FIX_CLASS: string = QuickFixAction.CLASS + ' autofixable';
private readonly _onShowQuickFixes = this._register(new Emitter<void>());
readonly onShowQuickFixes: Event<void> = this._onShowQuickFixes.event;
private _quickFixes: IAction[] = [];
get quickFixes(): IAction[] {
return this._quickFixes;
}
set quickFixes(quickFixes: IAction[]) {
this._quickFixes = quickFixes;
this.enabled = this._quickFixes.length > 0;
}
autoFixable(autofixable: boolean) {
this.class = autofixable ? QuickFixAction.AUTO_FIX_CLASS : QuickFixAction.CLASS;
}
constructor(
readonly marker: Marker,
) {
super(QuickFixAction.ID, Messages.MARKERS_PANEL_ACTION_TOOLTIP_QUICKFIX, QuickFixAction.CLASS, false);
}
run(): Promise<void> {
this._onShowQuickFixes.fire();
return Promise.resolve();
}
}
export class QuickFixActionViewItem extends ActionViewItem {
constructor(action: QuickFixAction,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super(null, action, { icon: true, label: false });
}
public onClick(event: DOM.EventLike): void {
DOM.EventHelper.stop(event, true);
this.showQuickFixes();
}
public showQuickFixes(): void {
if (!this.element) {
return;
}
if (!this.isEnabled()) {
return;
}
const elementPosition = DOM.getDomNodePagePosition(this.element);
const quickFixes = (<QuickFixAction>this.getAction()).quickFixes;
if (quickFixes.length) {
this.contextMenuService.showContextMenu({
getAnchor: () => ({ x: elementPosition.left + 10, y: elementPosition.top + elementPosition.height + 4 }),
getActions: () => quickFixes
});
}
}
}
| src/vs/workbench/contrib/markers/browser/markersPanelActions.ts | 1 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.9976045489311218,
0.05496020242571831,
0.00016370959929190576,
0.0005270250840112567,
0.22012674808502197
] |
{
"id": 5,
"code_window": [
"\t\t\tthis.element.className = this.action.class || '';\n",
"\t\t\tthis.adjustInputBox();\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tDOM.toggleClass(this.container, 'grow', DOM.hasClass(this.element, 'grow'));\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "add",
"edit_start_line_idx": 307
} | /*---------------------------------------------------------------------------------------------
* 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';
import * as minimatch from 'minimatch';
import { AbstractGlobalsRuleWalker } from './abstractGlobalsRule';
interface NoNodejsGlobalsConfig {
target: string;
allowed: string[];
}
export class Rule extends Lint.Rules.TypedRule {
applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
const configs = <NoNodejsGlobalsConfig[]>this.getOptions().ruleArguments;
for (const config of configs) {
if (minimatch(sourceFile.fileName, config.target)) {
return this.applyWithWalker(new NoNodejsGlobalsRuleWalker(sourceFile, program, this.getOptions(), config));
}
}
return [];
}
}
class NoNodejsGlobalsRuleWalker extends AbstractGlobalsRuleWalker {
getDefinitionPattern(): string {
return '@types/node';
}
getDisallowedGlobals(): string[] {
// https://nodejs.org/api/globals.html#globals_global_objects
return [
"NodeJS",
"Buffer",
"__dirname",
"__filename",
"clearImmediate",
"exports",
"global",
"module",
"process",
"setImmediate"
];
}
}
| build/lib/tslint/noNodejsGlobalsRule.ts | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.0005547275650314987,
0.0002472449268680066,
0.00016801824676804245,
0.0001748835202306509,
0.0001397495943820104
] |
{
"id": 5,
"code_window": [
"\t\t\tthis.element.className = this.action.class || '';\n",
"\t\t\tthis.adjustInputBox();\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tDOM.toggleClass(this.container, 'grow', DOM.hasClass(this.element, 'grow'));\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "add",
"edit_start_line_idx": 307
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { UriComponents } from 'vs/base/common/uri';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
export interface TaskDefinitionDTO {
type: string;
[name: string]: any;
}
export interface TaskPresentationOptionsDTO {
reveal?: number;
echo?: boolean;
focus?: boolean;
panel?: number;
showReuseMessage?: boolean;
clear?: boolean;
group?: string;
}
export interface RunOptionsDTO {
reevaluateOnRerun?: boolean;
}
export interface ExecutionOptionsDTO {
cwd?: string;
env?: { [key: string]: string };
}
export interface ProcessExecutionOptionsDTO extends ExecutionOptionsDTO {
}
export interface ProcessExecutionDTO {
process: string;
args: string[];
options?: ProcessExecutionOptionsDTO;
}
export interface ShellQuotingOptionsDTO {
escape?: string | {
escapeChar: string;
charsToEscape: string;
};
strong?: string;
weak?: string;
}
export interface ShellExecutionOptionsDTO extends ExecutionOptionsDTO {
executable?: string;
shellArgs?: string[];
shellQuoting?: ShellQuotingOptionsDTO;
}
export interface ShellQuotedStringDTO {
value: string;
quoting: number;
}
export interface ShellExecutionDTO {
commandLine?: string;
command?: string | ShellQuotedStringDTO;
args?: Array<string | ShellQuotedStringDTO>;
options?: ShellExecutionOptionsDTO;
}
export interface CustomExecutionDTO {
customExecution: 'customExecution';
}
export interface TaskSourceDTO {
label: string;
extensionId?: string;
scope?: number | UriComponents;
}
export interface TaskHandleDTO {
id: string;
workspaceFolder: UriComponents;
}
export interface TaskDTO {
_id: string;
name?: string;
execution: ProcessExecutionDTO | ShellExecutionDTO | CustomExecutionDTO | undefined;
definition: TaskDefinitionDTO;
isBackground?: boolean;
source: TaskSourceDTO;
group?: string;
detail?: string;
presentationOptions?: TaskPresentationOptionsDTO;
problemMatchers: string[];
hasDefinedMatchers: boolean;
runOptions?: RunOptionsDTO;
}
export interface TaskSetDTO {
tasks: TaskDTO[];
extension: IExtensionDescription;
}
export interface TaskExecutionDTO {
id: string;
task: TaskDTO | undefined;
}
export interface TaskProcessStartedDTO {
id: string;
processId: number;
}
export interface TaskProcessEndedDTO {
id: string;
exitCode: number;
}
export interface TaskFilterDTO {
version?: string;
type?: string;
}
export interface TaskSystemInfoDTO {
scheme: string;
authority: string;
platform: string;
}
| src/vs/workbench/api/common/shared/tasks.ts | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.0006400768761523068,
0.00023461236560251564,
0.00016643840353935957,
0.00017485534772276878,
0.00013129836588632315
] |
{
"id": 5,
"code_window": [
"\t\t\tthis.element.className = this.action.class || '';\n",
"\t\t\tthis.adjustInputBox();\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tDOM.toggleClass(this.container, 'grow', DOM.hasClass(this.element, 'grow'));\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/markersPanelActions.ts",
"type": "add",
"edit_start_line_idx": 307
} | /*---------------------------------------------------------------------------------------------
* 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 { computeRanges } from 'vs/editor/contrib/folding/indentRangeProvider';
import { TextModel } from 'vs/editor/common/model/textModel';
interface IndentRange {
start: number;
end: number;
}
suite('Indentation Folding', () => {
function r(start: number, end: number): IndentRange {
return { start, end };
}
test('Limit by indent', () => {
let lines = [
/* 1*/ 'A',
/* 2*/ ' A',
/* 3*/ ' A',
/* 4*/ ' A',
/* 5*/ ' A',
/* 6*/ ' A',
/* 7*/ ' A',
/* 8*/ ' A',
/* 9*/ ' A',
/* 10*/ ' A',
/* 11*/ ' A',
/* 12*/ ' A',
/* 13*/ ' A',
/* 14*/ ' A',
/* 15*/ 'A',
/* 16*/ ' A'
];
let r1 = r(1, 14); //0
let r2 = r(3, 11); //1
let r3 = r(4, 5); //2
let r4 = r(6, 11); //2
let r5 = r(8, 9); //3
let r6 = r(10, 11); //3
let r7 = r(12, 14); //1
let r8 = r(13, 14);//4
let r9 = r(15, 16);//0
let model = TextModel.createFromString(lines.join('\n'));
function assertLimit(maxEntries: number, expectedRanges: IndentRange[], message: string) {
let indentRanges = computeRanges(model, true, undefined, maxEntries);
assert.ok(indentRanges.length <= maxEntries, 'max ' + message);
let actual: IndentRange[] = [];
for (let i = 0; i < indentRanges.length; i++) {
actual.push({ start: indentRanges.getStartLineNumber(i), end: indentRanges.getEndLineNumber(i) });
}
assert.deepEqual(actual, expectedRanges, message);
}
assertLimit(1000, [r1, r2, r3, r4, r5, r6, r7, r8, r9], '1000');
assertLimit(9, [r1, r2, r3, r4, r5, r6, r7, r8, r9], '9');
assertLimit(8, [r1, r2, r3, r4, r5, r6, r7, r9], '8');
assertLimit(7, [r1, r2, r3, r4, r5, r7, r9], '7');
assertLimit(6, [r1, r2, r3, r4, r7, r9], '6');
assertLimit(5, [r1, r2, r3, r7, r9], '5');
assertLimit(4, [r1, r2, r7, r9], '4');
assertLimit(3, [r1, r2, r9], '3');
assertLimit(2, [r1, r9], '2');
assertLimit(1, [r1], '1');
assertLimit(0, [], '0');
});
});
| src/vs/editor/contrib/folding/test/indentFold.test.ts | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00017897351062856615,
0.00017197913257405162,
0.00016780580335762352,
0.0001714482350507751,
0.000003186120238751755
] |
{
"id": 6,
"code_window": [
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
".monaco-action-bar .action-item.markers-panel-action-filter-container {\n",
"\tflex: 1;\n",
"\tcursor: default;\n",
"\tdisplay: flex;\n",
"}\n",
"\n",
".monaco-action-bar .markers-panel-action-filter {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/markers/browser/media/markers.css",
"type": "replace",
"edit_start_line_idx": 6
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Delayer } from 'vs/base/common/async';
import * as DOM from 'vs/base/browser/dom';
import { Action, IActionChangeEvent, IAction } from 'vs/base/common/actions';
import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { KeyCode } from 'vs/base/common/keyCodes';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { TogglePanelAction } from 'vs/workbench/browser/panel';
import Messages from 'vs/workbench/contrib/markers/browser/messages';
import Constants from 'vs/workbench/contrib/markers/browser/constants';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { attachInputBoxStyler, attachStylerCallback, attachCheckboxStyler } from 'vs/platform/theme/common/styler';
import { IMarkersWorkbenchService } from 'vs/workbench/contrib/markers/browser/markers';
import { toDisposable } from 'vs/base/common/lifecycle';
import { BaseActionViewItem, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar';
import { badgeBackground, badgeForeground, contrastBorder } from 'vs/platform/theme/common/colorRegistry';
import { localize } from 'vs/nls';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ContextScopedHistoryInputBox } from 'vs/platform/browser/contextScopedHistoryWidget';
import { Marker } from 'vs/workbench/contrib/markers/browser/markersModel';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { Event, Emitter } from 'vs/base/common/event';
import { FilterOptions } from 'vs/workbench/contrib/markers/browser/markersFilterOptions';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
export class ToggleMarkersPanelAction extends TogglePanelAction {
public static readonly ID = 'workbench.actions.view.problems';
public static readonly LABEL = Messages.MARKERS_PANEL_TOGGLE_LABEL;
constructor(id: string, label: string,
@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
@IPanelService panelService: IPanelService,
@IMarkersWorkbenchService markersWorkbenchService: IMarkersWorkbenchService
) {
super(id, label, Constants.MARKERS_PANEL_ID, panelService, layoutService);
}
}
export class ShowProblemsPanelAction extends Action {
public static readonly ID = 'workbench.action.problems.focus';
public static readonly LABEL = Messages.MARKERS_PANEL_SHOW_LABEL;
constructor(id: string, label: string,
@IPanelService private readonly panelService: IPanelService
) {
super(id, label);
}
public run(): Promise<any> {
this.panelService.openPanel(Constants.MARKERS_PANEL_ID, true);
return Promise.resolve();
}
}
export interface IMarkersFilterActionChangeEvent extends IActionChangeEvent {
filterText?: boolean;
useFilesExclude?: boolean;
}
export interface IMarkersFilterActionOptions {
filterText: string;
filterHistory: string[];
useFilesExclude: boolean;
}
export class MarkersFilterAction extends Action {
public static readonly ID: string = 'workbench.actions.problems.filter';
private readonly _onFocus: Emitter<void> = this._register(new Emitter<void>());
readonly onFocus: Event<void> = this._onFocus.event;
constructor(options: IMarkersFilterActionOptions) {
super(MarkersFilterAction.ID, Messages.MARKERS_PANEL_ACTION_TOOLTIP_FILTER, 'markers-panel-action-filter', true);
this._filterText = options.filterText;
this._useFilesExclude = options.useFilesExclude;
this.filterHistory = options.filterHistory;
}
private _filterText: string;
get filterText(): string {
return this._filterText;
}
set filterText(filterText: string) {
if (this._filterText !== filterText) {
this._filterText = filterText;
this._onDidChange.fire(<IMarkersFilterActionChangeEvent>{ filterText: true });
}
}
filterHistory: string[];
private _useFilesExclude: boolean;
get useFilesExclude(): boolean {
return this._useFilesExclude;
}
set useFilesExclude(filesExclude: boolean) {
if (this._useFilesExclude !== filesExclude) {
this._useFilesExclude = filesExclude;
this._onDidChange.fire(<IMarkersFilterActionChangeEvent>{ useFilesExclude: true });
}
}
focus(): void {
this._onFocus.fire();
}
layout(width: number): void {
if (width < 400) {
this.class = 'markers-panel-action-filter small';
} else {
this.class = 'markers-panel-action-filter';
}
}
}
export interface IMarkerFilterController {
onDidFilter: Event<void>;
getFilterOptions(): FilterOptions;
getFilterStats(): { total: number, filtered: number };
}
export class MarkersFilterActionViewItem extends BaseActionViewItem {
private delayedFilterUpdate: Delayer<void>;
private filterInputBox: HistoryInputBox | null = null;
private filterBadge: HTMLElement | null = null;
private focusContextKey: IContextKey<boolean>;
constructor(
readonly action: MarkersFilterAction,
private filterController: IMarkerFilterController,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IContextViewService private readonly contextViewService: IContextViewService,
@IThemeService private readonly themeService: IThemeService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IContextKeyService contextKeyService: IContextKeyService
) {
super(null, action);
this.focusContextKey = Constants.MarkerPanelFilterFocusContextKey.bindTo(contextKeyService);
this.delayedFilterUpdate = new Delayer<void>(200);
this._register(toDisposable(() => this.delayedFilterUpdate.cancel()));
this._register(action.onFocus(() => this.focus()));
}
render(container: HTMLElement): void {
DOM.addClass(container, 'markers-panel-action-filter-container');
this.element = DOM.append(container, DOM.$(''));
this.element.className = this.action.class || '';
this.createInput(this.element);
this.createControls(this.element);
this.adjustInputBox();
}
focus(): void {
if (this.filterInputBox) {
this.filterInputBox.focus();
}
}
private createInput(container: HTMLElement): void {
this.filterInputBox = this._register(this.instantiationService.createInstance(ContextScopedHistoryInputBox, container, this.contextViewService, {
placeholder: Messages.MARKERS_PANEL_FILTER_PLACEHOLDER,
ariaLabel: Messages.MARKERS_PANEL_FILTER_ARIA_LABEL,
history: this.action.filterHistory
}));
this.filterInputBox.inputElement.setAttribute('aria-labelledby', 'markers-panel-arialabel');
this._register(attachInputBoxStyler(this.filterInputBox, this.themeService));
this.filterInputBox.value = this.action.filterText;
this._register(this.filterInputBox.onDidChange(filter => this.delayedFilterUpdate.trigger(() => this.onDidInputChange(this.filterInputBox!))));
this._register(this.action.onDidChange((event: IMarkersFilterActionChangeEvent) => {
if (event.filterText) {
this.filterInputBox!.value = this.action.filterText;
}
}));
this._register(DOM.addStandardDisposableListener(this.filterInputBox.inputElement, DOM.EventType.KEY_DOWN, (e: any) => this.onInputKeyDown(e, this.filterInputBox!)));
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_DOWN, this.handleKeyboardEvent));
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_UP, this.handleKeyboardEvent));
const focusTracker = this._register(DOM.trackFocus(this.filterInputBox.inputElement));
this._register(focusTracker.onDidFocus(() => this.focusContextKey.set(true)));
this._register(focusTracker.onDidBlur(() => this.focusContextKey.set(false)));
this._register(toDisposable(() => this.focusContextKey.reset()));
}
private createControls(container: HTMLElement): void {
const controlsContainer = DOM.append(container, DOM.$('.markers-panel-filter-controls'));
this.createBadge(controlsContainer);
this.createFilesExcludeCheckbox(controlsContainer);
}
private createBadge(container: HTMLElement): void {
const filterBadge = this.filterBadge = DOM.append(container, DOM.$('.markers-panel-filter-badge'));
this._register(attachStylerCallback(this.themeService, { badgeBackground, badgeForeground, contrastBorder }, colors => {
const background = colors.badgeBackground ? colors.badgeBackground.toString() : '';
const foreground = colors.badgeForeground ? colors.badgeForeground.toString() : '';
const border = colors.contrastBorder ? colors.contrastBorder.toString() : '';
filterBadge.style.backgroundColor = background;
filterBadge.style.borderWidth = border ? '1px' : '';
filterBadge.style.borderStyle = border ? 'solid' : '';
filterBadge.style.borderColor = border;
filterBadge.style.color = foreground;
}));
this.updateBadge();
this._register(this.filterController.onDidFilter(() => this.updateBadge()));
}
private createFilesExcludeCheckbox(container: HTMLElement): void {
const filesExcludeFilter = this._register(new Checkbox({
actionClassName: 'codicon codicon-exclude',
title: this.action.useFilesExclude ? Messages.MARKERS_PANEL_ACTION_TOOLTIP_DO_NOT_USE_FILES_EXCLUDE : Messages.MARKERS_PANEL_ACTION_TOOLTIP_USE_FILES_EXCLUDE,
isChecked: this.action.useFilesExclude
}));
this._register(filesExcludeFilter.onChange(() => {
filesExcludeFilter.domNode.title = filesExcludeFilter.checked ? Messages.MARKERS_PANEL_ACTION_TOOLTIP_DO_NOT_USE_FILES_EXCLUDE : Messages.MARKERS_PANEL_ACTION_TOOLTIP_USE_FILES_EXCLUDE;
this.action.useFilesExclude = filesExcludeFilter.checked;
this.focus();
}));
this._register(this.action.onDidChange((event: IMarkersFilterActionChangeEvent) => {
if (event.useFilesExclude) {
filesExcludeFilter.checked = this.action.useFilesExclude;
}
}));
this._register(attachCheckboxStyler(filesExcludeFilter, this.themeService));
container.appendChild(filesExcludeFilter.domNode);
}
private onDidInputChange(inputbox: HistoryInputBox) {
inputbox.addToHistory();
this.action.filterText = inputbox.value;
this.action.filterHistory = inputbox.getHistory();
this.reportFilteringUsed();
}
private updateBadge(): void {
if (this.filterBadge) {
const { total, filtered } = this.filterController.getFilterStats();
DOM.toggleClass(this.filterBadge, 'hidden', total === filtered || filtered === 0);
this.filterBadge.textContent = localize('showing filtered problems', "Showing {0} of {1}", filtered, total);
this.adjustInputBox();
}
}
private adjustInputBox(): void {
if (this.element && this.filterInputBox && this.filterBadge) {
this.filterInputBox.inputElement.style.paddingRight = DOM.hasClass(this.element, 'small') || DOM.hasClass(this.filterBadge, 'hidden') ? '25px' : '150px';
}
}
// Action toolbar is swallowing some keys for action items which should not be for an input box
private handleKeyboardEvent(event: StandardKeyboardEvent) {
if (event.equals(KeyCode.Space)
|| event.equals(KeyCode.LeftArrow)
|| event.equals(KeyCode.RightArrow)
|| event.equals(KeyCode.Escape)
) {
event.stopPropagation();
}
}
private onInputKeyDown(event: StandardKeyboardEvent, filterInputBox: HistoryInputBox) {
let handled = false;
if (event.equals(KeyCode.Escape)) {
filterInputBox.value = '';
handled = true;
}
if (handled) {
event.stopPropagation();
event.preventDefault();
}
}
private reportFilteringUsed(): void {
const filterOptions = this.filterController.getFilterOptions();
const data = {
errors: filterOptions.filterErrors,
warnings: filterOptions.filterWarnings,
infos: filterOptions.filterInfos,
};
/* __GDPR__
"problems.filter" : {
"errors" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"warnings": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"infos": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
this.telemetryService.publicLog('problems.filter', data);
}
protected updateClass(): void {
if (this.element) {
this.element.className = this.action.class || '';
this.adjustInputBox();
}
}
}
export class QuickFixAction extends Action {
public static readonly ID: string = 'workbench.actions.problems.quickfix';
private static readonly CLASS: string = 'markers-panel-action-quickfix codicon-lightbulb';
private static readonly AUTO_FIX_CLASS: string = QuickFixAction.CLASS + ' autofixable';
private readonly _onShowQuickFixes = this._register(new Emitter<void>());
readonly onShowQuickFixes: Event<void> = this._onShowQuickFixes.event;
private _quickFixes: IAction[] = [];
get quickFixes(): IAction[] {
return this._quickFixes;
}
set quickFixes(quickFixes: IAction[]) {
this._quickFixes = quickFixes;
this.enabled = this._quickFixes.length > 0;
}
autoFixable(autofixable: boolean) {
this.class = autofixable ? QuickFixAction.AUTO_FIX_CLASS : QuickFixAction.CLASS;
}
constructor(
readonly marker: Marker,
) {
super(QuickFixAction.ID, Messages.MARKERS_PANEL_ACTION_TOOLTIP_QUICKFIX, QuickFixAction.CLASS, false);
}
run(): Promise<void> {
this._onShowQuickFixes.fire();
return Promise.resolve();
}
}
export class QuickFixActionViewItem extends ActionViewItem {
constructor(action: QuickFixAction,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super(null, action, { icon: true, label: false });
}
public onClick(event: DOM.EventLike): void {
DOM.EventHelper.stop(event, true);
this.showQuickFixes();
}
public showQuickFixes(): void {
if (!this.element) {
return;
}
if (!this.isEnabled()) {
return;
}
const elementPosition = DOM.getDomNodePagePosition(this.element);
const quickFixes = (<QuickFixAction>this.getAction()).quickFixes;
if (quickFixes.length) {
this.contextMenuService.showContextMenu({
getAnchor: () => ({ x: elementPosition.left + 10, y: elementPosition.top + elementPosition.height + 4 }),
getActions: () => quickFixes
});
}
}
}
| src/vs/workbench/contrib/markers/browser/markersPanelActions.ts | 1 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.0008309257682412863,
0.00023003248497843742,
0.00016369303921237588,
0.00016985906404443085,
0.0001297912822337821
] |
{
"id": 6,
"code_window": [
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
".monaco-action-bar .action-item.markers-panel-action-filter-container {\n",
"\tflex: 1;\n",
"\tcursor: default;\n",
"\tdisplay: flex;\n",
"}\n",
"\n",
".monaco-action-bar .markers-panel-action-filter {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/markers/browser/media/markers.css",
"type": "replace",
"edit_start_line_idx": 6
} | # cleanup rules for native node modules, .gitignore style
nan/**
*/node_modules/nan/**
fsevents/binding.gyp
fsevents/fsevents.cc
fsevents/build/**
fsevents/src/**
fsevents/test/**
!fsevents/**/*.node
vscode-sqlite3/binding.gyp
vscode-sqlite3/benchmark/**
vscode-sqlite3/cloudformation/**
vscode-sqlite3/deps/**
vscode-sqlite3/test/**
vscode-sqlite3/build/**
vscode-sqlite3/src/**
!vscode-sqlite3/build/Release/*.node
oniguruma/binding.gyp
oniguruma/build/**
oniguruma/src/**
oniguruma/deps/**
!oniguruma/build/Release/*.node
!oniguruma/src/*.js
windows-mutex/binding.gyp
windows-mutex/build/**
windows-mutex/src/**
!windows-mutex/**/*.node
native-keymap/binding.gyp
native-keymap/build/**
native-keymap/src/**
native-keymap/deps/**
!native-keymap/build/Release/*.node
native-is-elevated/binding.gyp
native-is-elevated/build/**
native-is-elevated/src/**
native-is-elevated/deps/**
!native-is-elevated/build/Release/*.node
native-watchdog/binding.gyp
native-watchdog/build/**
native-watchdog/src/**
!native-watchdog/build/Release/*.node
spdlog/binding.gyp
spdlog/build/**
spdlog/deps/**
spdlog/src/**
spdlog/test/**
!spdlog/build/Release/*.node
jschardet/dist/**
windows-foreground-love/binding.gyp
windows-foreground-love/build/**
windows-foreground-love/src/**
!windows-foreground-love/**/*.node
windows-process-tree/binding.gyp
windows-process-tree/build/**
windows-process-tree/src/**
!windows-process-tree/**/*.node
keytar/binding.gyp
keytar/build/**
keytar/src/**
keytar/script/**
keytar/node_modules/**
!keytar/**/*.node
node-pty/binding.gyp
node-pty/build/**
node-pty/src/**
node-pty/tools/**
node-pty/deps/**
!node-pty/build/Release/*.exe
!node-pty/build/Release/*.dll
!node-pty/build/Release/*.node
nsfw/binding.gyp
nsfw/build/**
nsfw/src/**
nsfw/openpa/**
nsfw/includes/**
!nsfw/build/Release/*.node
!nsfw/**/*.a
vsda/build/**
vsda/ci/**
vsda/src/**
vsda/.gitignore
vsda/binding.gyp
vsda/README.md
vsda/targets
!vsda/build/Release/vsda.node
vscode-windows-ca-certs/**/*
!vscode-windows-ca-certs/package.json
!vscode-windows-ca-certs/**/*.node
node-addon-api/**/*
| build/.nativeignore | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00017555565864313394,
0.00017426592239644378,
0.00017270605894736946,
0.00017435869085602462,
8.27345616016828e-7
] |
{
"id": 6,
"code_window": [
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
".monaco-action-bar .action-item.markers-panel-action-filter-container {\n",
"\tflex: 1;\n",
"\tcursor: default;\n",
"\tdisplay: flex;\n",
"}\n",
"\n",
".monaco-action-bar .markers-panel-action-filter {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/markers/browser/media/markers.css",
"type": "replace",
"edit_start_line_idx": 6
} | 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/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.0001728413044475019,
0.0001723958266666159,
0.0001719754363875836,
0.00017238326836377382,
3.1115774845602573e-7
] |
{
"id": 6,
"code_window": [
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
".monaco-action-bar .action-item.markers-panel-action-filter-container {\n",
"\tflex: 1;\n",
"\tcursor: default;\n",
"\tdisplay: flex;\n",
"}\n",
"\n",
".monaco-action-bar .markers-panel-action-filter {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/markers/browser/media/markers.css",
"type": "replace",
"edit_start_line_idx": 6
} | {
"registrations": [
{
"component": {
"type": "git",
"git": {
"name": "daaain/Handlebars",
"repositoryUrl": "https://github.com/daaain/Handlebars",
"commitHash": "85a153a6f759df4e8da7533e1b3651f007867c51"
}
},
"licenseDetail": [
"-- Credits",
"",
"Adapted from the great sublime-text-handlebars package by Nicholas Westlake.",
"",
"Thanks a lot to all the generous contributors (in alphabetical order): @bittersweetryan, @bradcliffe, @calumbrodie, @duncanbeevers, @hlvnst, @jonschlinkert, @Krutius, @samselikoff, @utkarshkukreti, @zeppelin",
"",
"-- License",
"",
"(The MIT License)",
"",
"Copyright (c) daaain/Handlebars project authors",
"",
"Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:",
"",
"The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.",
"",
"THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."
],
"license": "MIT",
"version": "1.8.0"
}
],
"version": 1
} | extensions/handlebars/cgmanifest.json | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00017480649694334716,
0.0001718299899948761,
0.0001684223097981885,
0.00017204559117089957,
0.0000027239466362516396
] |
{
"id": 7,
"code_window": [
"\tmax-width: 600px;\n",
"\tmin-width: 300px;\n",
"\tmargin-right: 10px;\n",
"}\n",
"\n",
".markers-panel .markers-panel-container {\n",
"\theight: 100%;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".markers-panel-container .monaco-action-bar.markers-panel-filter-container .action-item.markers-panel-action-filter-container,\n",
".panel > .title .monaco-action-bar .action-item.markers-panel-action-filter-container.grow {\n",
"\tflex: 1;\n",
"}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/media/markers.css",
"type": "add",
"edit_start_line_idx": 54
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Delayer } from 'vs/base/common/async';
import * as DOM from 'vs/base/browser/dom';
import { Action, IActionChangeEvent, IAction } from 'vs/base/common/actions';
import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { KeyCode } from 'vs/base/common/keyCodes';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { TogglePanelAction } from 'vs/workbench/browser/panel';
import Messages from 'vs/workbench/contrib/markers/browser/messages';
import Constants from 'vs/workbench/contrib/markers/browser/constants';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { attachInputBoxStyler, attachStylerCallback, attachCheckboxStyler } from 'vs/platform/theme/common/styler';
import { IMarkersWorkbenchService } from 'vs/workbench/contrib/markers/browser/markers';
import { toDisposable } from 'vs/base/common/lifecycle';
import { BaseActionViewItem, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar';
import { badgeBackground, badgeForeground, contrastBorder } from 'vs/platform/theme/common/colorRegistry';
import { localize } from 'vs/nls';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ContextScopedHistoryInputBox } from 'vs/platform/browser/contextScopedHistoryWidget';
import { Marker } from 'vs/workbench/contrib/markers/browser/markersModel';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { Event, Emitter } from 'vs/base/common/event';
import { FilterOptions } from 'vs/workbench/contrib/markers/browser/markersFilterOptions';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
export class ToggleMarkersPanelAction extends TogglePanelAction {
public static readonly ID = 'workbench.actions.view.problems';
public static readonly LABEL = Messages.MARKERS_PANEL_TOGGLE_LABEL;
constructor(id: string, label: string,
@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
@IPanelService panelService: IPanelService,
@IMarkersWorkbenchService markersWorkbenchService: IMarkersWorkbenchService
) {
super(id, label, Constants.MARKERS_PANEL_ID, panelService, layoutService);
}
}
export class ShowProblemsPanelAction extends Action {
public static readonly ID = 'workbench.action.problems.focus';
public static readonly LABEL = Messages.MARKERS_PANEL_SHOW_LABEL;
constructor(id: string, label: string,
@IPanelService private readonly panelService: IPanelService
) {
super(id, label);
}
public run(): Promise<any> {
this.panelService.openPanel(Constants.MARKERS_PANEL_ID, true);
return Promise.resolve();
}
}
export interface IMarkersFilterActionChangeEvent extends IActionChangeEvent {
filterText?: boolean;
useFilesExclude?: boolean;
}
export interface IMarkersFilterActionOptions {
filterText: string;
filterHistory: string[];
useFilesExclude: boolean;
}
export class MarkersFilterAction extends Action {
public static readonly ID: string = 'workbench.actions.problems.filter';
private readonly _onFocus: Emitter<void> = this._register(new Emitter<void>());
readonly onFocus: Event<void> = this._onFocus.event;
constructor(options: IMarkersFilterActionOptions) {
super(MarkersFilterAction.ID, Messages.MARKERS_PANEL_ACTION_TOOLTIP_FILTER, 'markers-panel-action-filter', true);
this._filterText = options.filterText;
this._useFilesExclude = options.useFilesExclude;
this.filterHistory = options.filterHistory;
}
private _filterText: string;
get filterText(): string {
return this._filterText;
}
set filterText(filterText: string) {
if (this._filterText !== filterText) {
this._filterText = filterText;
this._onDidChange.fire(<IMarkersFilterActionChangeEvent>{ filterText: true });
}
}
filterHistory: string[];
private _useFilesExclude: boolean;
get useFilesExclude(): boolean {
return this._useFilesExclude;
}
set useFilesExclude(filesExclude: boolean) {
if (this._useFilesExclude !== filesExclude) {
this._useFilesExclude = filesExclude;
this._onDidChange.fire(<IMarkersFilterActionChangeEvent>{ useFilesExclude: true });
}
}
focus(): void {
this._onFocus.fire();
}
layout(width: number): void {
if (width < 400) {
this.class = 'markers-panel-action-filter small';
} else {
this.class = 'markers-panel-action-filter';
}
}
}
export interface IMarkerFilterController {
onDidFilter: Event<void>;
getFilterOptions(): FilterOptions;
getFilterStats(): { total: number, filtered: number };
}
export class MarkersFilterActionViewItem extends BaseActionViewItem {
private delayedFilterUpdate: Delayer<void>;
private filterInputBox: HistoryInputBox | null = null;
private filterBadge: HTMLElement | null = null;
private focusContextKey: IContextKey<boolean>;
constructor(
readonly action: MarkersFilterAction,
private filterController: IMarkerFilterController,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IContextViewService private readonly contextViewService: IContextViewService,
@IThemeService private readonly themeService: IThemeService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IContextKeyService contextKeyService: IContextKeyService
) {
super(null, action);
this.focusContextKey = Constants.MarkerPanelFilterFocusContextKey.bindTo(contextKeyService);
this.delayedFilterUpdate = new Delayer<void>(200);
this._register(toDisposable(() => this.delayedFilterUpdate.cancel()));
this._register(action.onFocus(() => this.focus()));
}
render(container: HTMLElement): void {
DOM.addClass(container, 'markers-panel-action-filter-container');
this.element = DOM.append(container, DOM.$(''));
this.element.className = this.action.class || '';
this.createInput(this.element);
this.createControls(this.element);
this.adjustInputBox();
}
focus(): void {
if (this.filterInputBox) {
this.filterInputBox.focus();
}
}
private createInput(container: HTMLElement): void {
this.filterInputBox = this._register(this.instantiationService.createInstance(ContextScopedHistoryInputBox, container, this.contextViewService, {
placeholder: Messages.MARKERS_PANEL_FILTER_PLACEHOLDER,
ariaLabel: Messages.MARKERS_PANEL_FILTER_ARIA_LABEL,
history: this.action.filterHistory
}));
this.filterInputBox.inputElement.setAttribute('aria-labelledby', 'markers-panel-arialabel');
this._register(attachInputBoxStyler(this.filterInputBox, this.themeService));
this.filterInputBox.value = this.action.filterText;
this._register(this.filterInputBox.onDidChange(filter => this.delayedFilterUpdate.trigger(() => this.onDidInputChange(this.filterInputBox!))));
this._register(this.action.onDidChange((event: IMarkersFilterActionChangeEvent) => {
if (event.filterText) {
this.filterInputBox!.value = this.action.filterText;
}
}));
this._register(DOM.addStandardDisposableListener(this.filterInputBox.inputElement, DOM.EventType.KEY_DOWN, (e: any) => this.onInputKeyDown(e, this.filterInputBox!)));
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_DOWN, this.handleKeyboardEvent));
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_UP, this.handleKeyboardEvent));
const focusTracker = this._register(DOM.trackFocus(this.filterInputBox.inputElement));
this._register(focusTracker.onDidFocus(() => this.focusContextKey.set(true)));
this._register(focusTracker.onDidBlur(() => this.focusContextKey.set(false)));
this._register(toDisposable(() => this.focusContextKey.reset()));
}
private createControls(container: HTMLElement): void {
const controlsContainer = DOM.append(container, DOM.$('.markers-panel-filter-controls'));
this.createBadge(controlsContainer);
this.createFilesExcludeCheckbox(controlsContainer);
}
private createBadge(container: HTMLElement): void {
const filterBadge = this.filterBadge = DOM.append(container, DOM.$('.markers-panel-filter-badge'));
this._register(attachStylerCallback(this.themeService, { badgeBackground, badgeForeground, contrastBorder }, colors => {
const background = colors.badgeBackground ? colors.badgeBackground.toString() : '';
const foreground = colors.badgeForeground ? colors.badgeForeground.toString() : '';
const border = colors.contrastBorder ? colors.contrastBorder.toString() : '';
filterBadge.style.backgroundColor = background;
filterBadge.style.borderWidth = border ? '1px' : '';
filterBadge.style.borderStyle = border ? 'solid' : '';
filterBadge.style.borderColor = border;
filterBadge.style.color = foreground;
}));
this.updateBadge();
this._register(this.filterController.onDidFilter(() => this.updateBadge()));
}
private createFilesExcludeCheckbox(container: HTMLElement): void {
const filesExcludeFilter = this._register(new Checkbox({
actionClassName: 'codicon codicon-exclude',
title: this.action.useFilesExclude ? Messages.MARKERS_PANEL_ACTION_TOOLTIP_DO_NOT_USE_FILES_EXCLUDE : Messages.MARKERS_PANEL_ACTION_TOOLTIP_USE_FILES_EXCLUDE,
isChecked: this.action.useFilesExclude
}));
this._register(filesExcludeFilter.onChange(() => {
filesExcludeFilter.domNode.title = filesExcludeFilter.checked ? Messages.MARKERS_PANEL_ACTION_TOOLTIP_DO_NOT_USE_FILES_EXCLUDE : Messages.MARKERS_PANEL_ACTION_TOOLTIP_USE_FILES_EXCLUDE;
this.action.useFilesExclude = filesExcludeFilter.checked;
this.focus();
}));
this._register(this.action.onDidChange((event: IMarkersFilterActionChangeEvent) => {
if (event.useFilesExclude) {
filesExcludeFilter.checked = this.action.useFilesExclude;
}
}));
this._register(attachCheckboxStyler(filesExcludeFilter, this.themeService));
container.appendChild(filesExcludeFilter.domNode);
}
private onDidInputChange(inputbox: HistoryInputBox) {
inputbox.addToHistory();
this.action.filterText = inputbox.value;
this.action.filterHistory = inputbox.getHistory();
this.reportFilteringUsed();
}
private updateBadge(): void {
if (this.filterBadge) {
const { total, filtered } = this.filterController.getFilterStats();
DOM.toggleClass(this.filterBadge, 'hidden', total === filtered || filtered === 0);
this.filterBadge.textContent = localize('showing filtered problems', "Showing {0} of {1}", filtered, total);
this.adjustInputBox();
}
}
private adjustInputBox(): void {
if (this.element && this.filterInputBox && this.filterBadge) {
this.filterInputBox.inputElement.style.paddingRight = DOM.hasClass(this.element, 'small') || DOM.hasClass(this.filterBadge, 'hidden') ? '25px' : '150px';
}
}
// Action toolbar is swallowing some keys for action items which should not be for an input box
private handleKeyboardEvent(event: StandardKeyboardEvent) {
if (event.equals(KeyCode.Space)
|| event.equals(KeyCode.LeftArrow)
|| event.equals(KeyCode.RightArrow)
|| event.equals(KeyCode.Escape)
) {
event.stopPropagation();
}
}
private onInputKeyDown(event: StandardKeyboardEvent, filterInputBox: HistoryInputBox) {
let handled = false;
if (event.equals(KeyCode.Escape)) {
filterInputBox.value = '';
handled = true;
}
if (handled) {
event.stopPropagation();
event.preventDefault();
}
}
private reportFilteringUsed(): void {
const filterOptions = this.filterController.getFilterOptions();
const data = {
errors: filterOptions.filterErrors,
warnings: filterOptions.filterWarnings,
infos: filterOptions.filterInfos,
};
/* __GDPR__
"problems.filter" : {
"errors" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"warnings": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"infos": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
this.telemetryService.publicLog('problems.filter', data);
}
protected updateClass(): void {
if (this.element) {
this.element.className = this.action.class || '';
this.adjustInputBox();
}
}
}
export class QuickFixAction extends Action {
public static readonly ID: string = 'workbench.actions.problems.quickfix';
private static readonly CLASS: string = 'markers-panel-action-quickfix codicon-lightbulb';
private static readonly AUTO_FIX_CLASS: string = QuickFixAction.CLASS + ' autofixable';
private readonly _onShowQuickFixes = this._register(new Emitter<void>());
readonly onShowQuickFixes: Event<void> = this._onShowQuickFixes.event;
private _quickFixes: IAction[] = [];
get quickFixes(): IAction[] {
return this._quickFixes;
}
set quickFixes(quickFixes: IAction[]) {
this._quickFixes = quickFixes;
this.enabled = this._quickFixes.length > 0;
}
autoFixable(autofixable: boolean) {
this.class = autofixable ? QuickFixAction.AUTO_FIX_CLASS : QuickFixAction.CLASS;
}
constructor(
readonly marker: Marker,
) {
super(QuickFixAction.ID, Messages.MARKERS_PANEL_ACTION_TOOLTIP_QUICKFIX, QuickFixAction.CLASS, false);
}
run(): Promise<void> {
this._onShowQuickFixes.fire();
return Promise.resolve();
}
}
export class QuickFixActionViewItem extends ActionViewItem {
constructor(action: QuickFixAction,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super(null, action, { icon: true, label: false });
}
public onClick(event: DOM.EventLike): void {
DOM.EventHelper.stop(event, true);
this.showQuickFixes();
}
public showQuickFixes(): void {
if (!this.element) {
return;
}
if (!this.isEnabled()) {
return;
}
const elementPosition = DOM.getDomNodePagePosition(this.element);
const quickFixes = (<QuickFixAction>this.getAction()).quickFixes;
if (quickFixes.length) {
this.contextMenuService.showContextMenu({
getAnchor: () => ({ x: elementPosition.left + 10, y: elementPosition.top + elementPosition.height + 4 }),
getActions: () => quickFixes
});
}
}
}
| src/vs/workbench/contrib/markers/browser/markersPanelActions.ts | 1 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.031600769609212875,
0.0019024843350052834,
0.00016523362137377262,
0.00019950651039835066,
0.005279285833239555
] |
{
"id": 7,
"code_window": [
"\tmax-width: 600px;\n",
"\tmin-width: 300px;\n",
"\tmargin-right: 10px;\n",
"}\n",
"\n",
".markers-panel .markers-panel-container {\n",
"\theight: 100%;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".markers-panel-container .monaco-action-bar.markers-panel-filter-container .action-item.markers-panel-action-filter-container,\n",
".panel > .title .monaco-action-bar .action-item.markers-panel-action-filter-container.grow {\n",
"\tflex: 1;\n",
"}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/media/markers.css",
"type": "add",
"edit_start_line_idx": 54
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/// <reference path='../../../../src/vs/vscode.d.ts'/>
/// <reference path='../../../../src/vs/vscode.proposed.d.ts'/>
/// <reference types='@types/node'/>
| extensions/markdown-language-features/src/typings/ref.d.ts | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.0001757283171173185,
0.0001757283171173185,
0.0001757283171173185,
0.0001757283171173185,
0
] |
{
"id": 7,
"code_window": [
"\tmax-width: 600px;\n",
"\tmin-width: 300px;\n",
"\tmargin-right: 10px;\n",
"}\n",
"\n",
".markers-panel .markers-panel-container {\n",
"\theight: 100%;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".markers-panel-container .monaco-action-bar.markers-panel-filter-container .action-item.markers-panel-action-filter-container,\n",
".panel > .title .monaco-action-bar .action-item.markers-panel-action-filter-container.grow {\n",
"\tflex: 1;\n",
"}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/media/markers.css",
"type": "add",
"edit_start_line_idx": 54
} | <!-- Copyright (C) Microsoft Corporation. All rights reserved. -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Manage Built-in Extensions</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="browser-main.js"></script>
<style>
body {
font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
font-size: 10pt;
}
code {
font-family: 'Menlo', 'Courier New', 'Courier', monospace;
}
ul {
padding-left: 1em;
}
li {
list-style: none;
padding: 0.3em 0;
}
label {
margin-right: 1em;
}
form {
padding: 0.3em 0 0.3em 0.3em;
}
</style>
</head>
<body>
<h1>Built-in Extensions</h1>
<div id="extensions"></div>
</body>
</html> | build/builtin/index.html | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00017406318511348218,
0.00017033351468853652,
0.00016914604930207133,
0.00016953388694673777,
0.000001872915163403377
] |
{
"id": 7,
"code_window": [
"\tmax-width: 600px;\n",
"\tmin-width: 300px;\n",
"\tmargin-right: 10px;\n",
"}\n",
"\n",
".markers-panel .markers-panel-container {\n",
"\theight: 100%;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".markers-panel-container .monaco-action-bar.markers-panel-filter-container .action-item.markers-panel-action-filter-container,\n",
".panel > .title .monaco-action-bar .action-item.markers-panel-action-filter-container.grow {\n",
"\tflex: 1;\n",
"}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/markers/browser/media/markers.css",
"type": "add",
"edit_start_line_idx": 54
} | # Merge Conflict
**Notice:** This extension is bundled with Visual Studio Code. It can be disabled but not uninstalled.
## Features
See [Merge Conflicts in VS Code](https://code.visualstudio.com/docs/editor/versioncontrol#_merge-conflicts) to learn about features of this extension.
| extensions/merge-conflict/README.md | 0 | https://github.com/microsoft/vscode/commit/5d4e856d40eb2c6e09cc4cc31ab38d7d201c05c9 | [
0.00016901787603273988,
0.00016901787603273988,
0.00016901787603273988,
0.00016901787603273988,
0
] |
{
"id": 0,
"code_window": [
"\tgetFunctionBreakpoints(): ReadonlyArray<IFunctionBreakpoint>;\n",
"\tgetExceptionBreakpoints(): ReadonlyArray<IExceptionBreakpoint>;\n",
"\tgetWatchExpressions(): ReadonlyArray<IExpression & IEvaluate>;\n",
"\n",
"\tonDidChangeBreakpoints: Event<IBreakpointsChangeEvent>;\n",
"\tonDidChangeCallStack: Event<void>;\n",
"\tonDidChangeWatchExpressions: Event<IExpression>;\n",
"}\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tonDidChangeCallStack: Event<IThread | undefined>;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debug.ts",
"type": "replace",
"edit_start_line_idx": 395
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI as uri } from 'vs/base/common/uri';
import * as resources from 'vs/base/common/resources';
import * as lifecycle from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
import { generateUuid } from 'vs/base/common/uuid';
import { RunOnceScheduler } from 'vs/base/common/async';
import severity from 'vs/base/common/severity';
import { isObject, isString, isUndefinedOrNull } from 'vs/base/common/types';
import { distinct } from 'vs/base/common/arrays';
import { Range, IRange } from 'vs/editor/common/core/range';
import {
ITreeElement, IExpression, IExpressionContainer, IDebugSession, IStackFrame, IExceptionBreakpoint, IBreakpoint, IFunctionBreakpoint, IDebugModel, IReplElementSource,
IThread, IRawModelUpdate, IScope, IRawStoppedDetails, IEnablement, IBreakpointData, IExceptionInfo, IReplElement, IBreakpointsChangeEvent, IBreakpointUpdateData, IBaseBreakpoint, State
} from 'vs/workbench/parts/debug/common/debug';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { commonSuffixLength } from 'vs/base/common/strings';
import { sep } from 'vs/base/common/paths';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
export class SimpleReplElement implements IReplElement {
constructor(
private id: string,
public value: string,
public severity: severity,
public sourceData: IReplElementSource,
) { }
toString(): string {
return this.value;
}
getId(): string {
return this.id;
}
}
export class RawObjectReplElement implements IExpression {
private static readonly MAX_CHILDREN = 1000; // upper bound of children per value
constructor(private id: string, public name: string, public valueObj: any, public sourceData?: IReplElementSource, public annotation?: string) { }
getId(): string {
return this.id;
}
get value(): string {
if (this.valueObj === null) {
return 'null';
} else if (Array.isArray(this.valueObj)) {
return `Array[${this.valueObj.length}]`;
} else if (isObject(this.valueObj)) {
return 'Object';
} else if (isString(this.valueObj)) {
return `"${this.valueObj}"`;
}
return String(this.valueObj) || '';
}
get hasChildren(): boolean {
return (Array.isArray(this.valueObj) && this.valueObj.length > 0) || (isObject(this.valueObj) && Object.getOwnPropertyNames(this.valueObj).length > 0);
}
getChildren(): Promise<IExpression[]> {
let result: IExpression[] = [];
if (Array.isArray(this.valueObj)) {
result = (<any[]>this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN)
.map((v, index) => new RawObjectReplElement(`${this.id}:${index}`, String(index), v));
} else if (isObject(this.valueObj)) {
result = Object.getOwnPropertyNames(this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN)
.map((key, index) => new RawObjectReplElement(`${this.id}:${index}`, key, this.valueObj[key]));
}
return Promise.resolve(result);
}
toString(): string {
return `${this.name}\n${this.value}`;
}
}
export class ExpressionContainer implements IExpressionContainer {
public static allValues: Map<string, string> = new Map<string, string>();
// Use chunks to support variable paging #9537
private static readonly BASE_CHUNK_SIZE = 100;
public valueChanged: boolean;
private _value: string;
protected children: Promise<IExpression[]>;
constructor(
protected session: IDebugSession,
private _reference: number,
private id: string,
public namedVariables = 0,
public indexedVariables = 0,
private startOfVariables = 0
) { }
get reference(): number {
return this._reference;
}
set reference(value: number) {
this._reference = value;
this.children = undefined; // invalidate children cache
}
getChildren(): Promise<IExpression[]> {
if (!this.children) {
this.children = this.doGetChildren();
}
return this.children;
}
private doGetChildren(): Promise<IExpression[]> {
if (!this.hasChildren) {
return Promise.resolve([]);
}
if (!this.getChildrenInChunks) {
return this.fetchVariables(undefined, undefined, undefined);
}
// Check if object has named variables, fetch them independent from indexed variables #9670
const childrenThenable = !!this.namedVariables ? this.fetchVariables(undefined, undefined, 'named') : Promise.resolve([]);
return childrenThenable.then(childrenArray => {
// Use a dynamic chunk size based on the number of elements #9774
let chunkSize = ExpressionContainer.BASE_CHUNK_SIZE;
while (this.indexedVariables > chunkSize * ExpressionContainer.BASE_CHUNK_SIZE) {
chunkSize *= ExpressionContainer.BASE_CHUNK_SIZE;
}
if (this.indexedVariables > chunkSize) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const numberOfChunks = Math.ceil(this.indexedVariables / chunkSize);
for (let i = 0; i < numberOfChunks; i++) {
const start = this.startOfVariables + i * chunkSize;
const count = Math.min(chunkSize, this.indexedVariables - i * chunkSize);
childrenArray.push(new Variable(this.session, this, this.reference, `[${start}..${start + count - 1}]`, '', '', null, count, { kind: 'virtual' }, null, true, start));
}
return childrenArray;
}
return this.fetchVariables(this.startOfVariables, this.indexedVariables, 'indexed')
.then(variables => childrenArray.concat(variables));
});
}
getId(): string {
return this.id;
}
get value(): string {
return this._value;
}
get hasChildren(): boolean {
// only variables with reference > 0 have children.
return this.reference > 0;
}
private fetchVariables(start: number, count: number, filter: 'indexed' | 'named'): Promise<Variable[]> {
return this.session.variables(this.reference, filter, start, count).then(response => {
return response && response.body && response.body.variables
? distinct(response.body.variables.filter(v => !!v && isString(v.name)), v => v.name).map(
v => new Variable(this.session, this, v.variablesReference, v.name, v.evaluateName, v.value, v.namedVariables, v.indexedVariables, v.presentationHint, v.type))
: [];
}, (e: Error) => [new Variable(this.session, this, 0, e.message, e.message, '', 0, 0, { kind: 'virtual' }, null, false)]);
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.indexedVariables;
}
set value(value: string) {
this._value = value;
this.valueChanged = ExpressionContainer.allValues.get(this.getId()) &&
ExpressionContainer.allValues.get(this.getId()) !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues.get(this.getId()) !== value;
ExpressionContainer.allValues.set(this.getId(), value);
}
toString(): string {
return this.value;
}
}
export class Expression extends ExpressionContainer implements IExpression {
static DEFAULT_VALUE = nls.localize('notAvailable', "not available");
public available: boolean;
public type: string;
constructor(public name: string, id = generateUuid()) {
super(null, 0, id);
this.available = false;
// name is not set if the expression is just being added
// in that case do not set default value to prevent flashing #14499
if (name) {
this.value = Expression.DEFAULT_VALUE;
}
}
evaluate(session: IDebugSession, stackFrame: IStackFrame, context: string): Promise<void> {
if (!session || (!stackFrame && context !== 'repl')) {
this.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate expressions") : Expression.DEFAULT_VALUE;
this.available = false;
this.reference = 0;
return Promise.resolve(void 0);
}
this.session = session;
return session.evaluate(this.name, stackFrame ? stackFrame.frameId : undefined, context).then(response => {
this.available = !!(response && response.body);
if (response && response.body) {
this.value = response.body.result;
this.reference = response.body.variablesReference;
this.namedVariables = response.body.namedVariables;
this.indexedVariables = response.body.indexedVariables;
this.type = response.body.type;
}
}, err => {
this.value = err.message;
this.available = false;
this.reference = 0;
});
}
toString(): string {
return `${this.name}\n${this.value}`;
}
}
export class Variable extends ExpressionContainer implements IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
session: IDebugSession,
public parent: IExpressionContainer,
reference: number,
public name: string,
public evaluateName: string,
value: string,
namedVariables: number,
indexedVariables: number,
public presentationHint: DebugProtocol.VariablePresentationHint,
public type: string | null = null,
public available = true,
startOfVariables = 0
) {
super(session, reference, `variable:${parent.getId()}:${name}`, namedVariables, indexedVariables, startOfVariables);
this.value = value;
}
setVariable(value: string): Promise<any> {
return this.session.setVariable((<ExpressionContainer>this.parent).reference, this.name, value).then(response => {
if (response && response.body) {
this.value = response.body.value;
this.type = response.body.type || this.type;
this.reference = response.body.variablesReference;
this.namedVariables = response.body.namedVariables;
this.indexedVariables = response.body.indexedVariables;
}
}, err => {
this.errorMessage = err.message;
});
}
toString(): string {
return `${this.name}: ${this.value}`;
}
}
export class Scope extends ExpressionContainer implements IScope {
constructor(
stackFrame: IStackFrame,
index: number,
public name: string,
reference: number,
public expensive: boolean,
namedVariables: number,
indexedVariables: number,
public range?: IRange
) {
super(stackFrame.thread.session, reference, `scope:${stackFrame.getId()}:${name}:${index}`, namedVariables, indexedVariables);
}
toString(): string {
return this.name;
}
}
export class StackFrame implements IStackFrame {
private scopes: Promise<Scope[]>;
constructor(
public thread: IThread,
public frameId: number,
public source: Source,
public name: string,
public presentationHint: string,
public range: IRange,
private index: number
) {
this.scopes = null;
}
getId(): string {
return `stackframe:${this.thread.getId()}:${this.frameId}:${this.index}`;
}
getScopes(): Promise<IScope[]> {
if (!this.scopes) {
this.scopes = this.thread.session.scopes(this.frameId).then(response => {
return response && response.body && response.body.scopes ?
response.body.scopes.map((rs, index) => new Scope(this, index, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables,
rs.line && rs.column && rs.endLine && rs.endColumn ? new Range(rs.line, rs.column, rs.endLine, rs.endColumn) : null)) : [];
}, err => []);
}
return this.scopes;
}
getSpecificSourceName(): 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>this.thread).getStaleCallStack();
callStack = callStack.length > 0 ? callStack : this.thread.getCallStack();
const otherSources = callStack.map(sf => sf.source).filter(s => s !== this.source);
let suffixLength = 0;
otherSources.forEach(s => {
if (s.name === this.source.name) {
suffixLength = Math.max(suffixLength, commonSuffixLength(this.source.uri.path, s.uri.path));
}
});
if (suffixLength === 0) {
return this.source.name;
}
const from = Math.max(0, this.source.uri.path.lastIndexOf(sep, this.source.uri.path.length - suffixLength - 1));
return (from > 0 ? '...' : '') + this.source.uri.path.substr(from);
}
getMostSpecificScopes(range: IRange): Promise<IScope[]> {
return this.getScopes().then(scopes => {
scopes = scopes.filter(s => !s.expensive);
const haveRangeInfo = scopes.some(s => !!s.range);
if (!haveRangeInfo) {
return scopes;
}
const scopesContainingRange = scopes.filter(scope => scope.range && Range.containsRange(scope.range, range))
.sort((first, second) => (first.range.endLineNumber - first.range.startLineNumber) - (second.range.endLineNumber - second.range.startLineNumber));
return scopesContainingRange.length ? scopesContainingRange : scopes;
});
}
restart(): Promise<void> {
return this.thread.session.restartFrame(this.frameId, this.thread.threadId);
}
toString(): string {
return `${this.name} (${this.source.inMemory ? this.source.name : this.source.uri.fsPath}:${this.range.startLineNumber})`;
}
openInEditor(editorService: IEditorService, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): Promise<any> {
return !this.source.available ? Promise.resolve(null) :
this.source.openInEditor(editorService, this.range, preserveFocus, sideBySide, pinned);
}
}
export class Thread implements IThread {
private callStack: IStackFrame[];
private staleCallStack: IStackFrame[];
public stoppedDetails: IRawStoppedDetails;
public stopped: boolean;
constructor(public session: IDebugSession, public name: string, public threadId: number) {
this.stoppedDetails = null;
this.callStack = [];
this.staleCallStack = [];
this.stopped = false;
}
getId(): string {
return `thread:${this.session.getId()}:${this.threadId}`;
}
clearCallStack(): void {
if (this.callStack.length) {
this.staleCallStack = this.callStack;
}
this.callStack = [];
}
getCallStack(): IStackFrame[] {
return this.callStack;
}
getStaleCallStack(): ReadonlyArray<IStackFrame> {
return this.staleCallStack;
}
/**
* Queries the debug adapter for the callstack and returns a promise
* which completes once the call stack has been retrieved.
* If the thread is not stopped, it returns a promise to an empty array.
* Only fetches the first stack frame for performance reasons. Calling this method consecutive times
* gets the remainder of the call stack.
*/
fetchCallStack(levels = 20): Promise<void> {
if (!this.stopped) {
return Promise.resolve(void 0);
}
const start = this.callStack.length;
return this.getCallStackImpl(start, levels).then(callStack => {
if (start < this.callStack.length) {
// Set the stack frames for exact position we requested. To make sure no concurrent requests create duplicate stack frames #30660
this.callStack.splice(start, this.callStack.length - start);
}
this.callStack = this.callStack.concat(callStack || []);
});
}
private getCallStackImpl(startFrame: number, levels: number): Promise<IStackFrame[]> {
return this.session.stackTrace(this.threadId, startFrame, levels).then(response => {
if (!response || !response.body) {
return [];
}
if (this.stoppedDetails) {
this.stoppedDetails.totalFrames = response.body.totalFrames;
}
return response.body.stackFrames.map((rsf, index) => {
const source = this.session.getSource(rsf.source);
return new StackFrame(this, rsf.id, source, rsf.name, rsf.presentationHint, new Range(
rsf.line,
rsf.column,
rsf.endLine,
rsf.endColumn
), startFrame + index);
});
}, (err: Error) => {
if (this.stoppedDetails) {
this.stoppedDetails.framesErrorMessage = err.message;
}
return [];
});
}
/**
* Returns exception info promise if the exception was thrown, otherwise null
*/
get exceptionInfo(): Promise<IExceptionInfo | null> {
if (this.stoppedDetails && this.stoppedDetails.reason === 'exception') {
if (this.session.capabilities.supportsExceptionInfoRequest) {
return this.session.exceptionInfo(this.threadId);
}
return Promise.resolve({
description: this.stoppedDetails.text,
breakMode: null
});
}
return Promise.resolve(null);
}
next(): Promise<any> {
return this.session.next(this.threadId);
}
stepIn(): Promise<any> {
return this.session.stepIn(this.threadId);
}
stepOut(): Promise<any> {
return this.session.stepOut(this.threadId);
}
stepBack(): Promise<any> {
return this.session.stepBack(this.threadId);
}
continue(): Promise<any> {
return this.session.continue(this.threadId);
}
pause(): Promise<any> {
return this.session.pause(this.threadId);
}
terminate(): Promise<any> {
return this.session.terminateThreads([this.threadId]);
}
reverseContinue(): Promise<any> {
return this.session.reverseContinue(this.threadId);
}
}
export class Enablement implements IEnablement {
constructor(
public enabled: boolean,
private id: string
) { }
getId(): string {
return this.id;
}
}
export class BaseBreakpoint extends Enablement implements IBaseBreakpoint {
private sessionData = new Map<string, DebugProtocol.Breakpoint>();
private sessionId: string;
constructor(
enabled: boolean,
public hitCondition: string,
public condition: string,
public logMessage: string,
id: string
) {
super(enabled, id);
if (enabled === undefined) {
this.enabled = true;
}
}
protected getSessionData() {
return this.sessionData.get(this.sessionId);
}
setSessionData(sessionId: string, data: DebugProtocol.Breakpoint): void {
this.sessionData.set(sessionId, data);
}
setSessionId(sessionId: string): void {
this.sessionId = sessionId;
}
get verified(): boolean {
const data = this.getSessionData();
return data ? data.verified : true;
}
get idFromAdapter(): number {
const data = this.getSessionData();
return data ? data.id : undefined;
}
toJSON(): any {
const result = Object.create(null);
result.enabled = this.enabled;
result.condition = this.condition;
result.hitCondition = this.hitCondition;
result.logMessage = this.logMessage;
return result;
}
}
export class Breakpoint extends BaseBreakpoint implements IBreakpoint {
constructor(
public uri: uri,
private _lineNumber: number,
private _column: number,
enabled: boolean,
condition: string,
hitCondition: string,
logMessage: string,
private _adapterData: any,
private textFileService: ITextFileService,
id = generateUuid()
) {
super(enabled, hitCondition, condition, logMessage, id);
}
get lineNumber(): number {
const data = this.getSessionData();
return this.verified && data && typeof data.line === 'number' ? data.line : this._lineNumber;
}
get verified(): boolean {
const data = this.getSessionData();
if (data) {
return data.verified && !this.textFileService.isDirty(this.uri);
}
return true;
}
get column(): number {
const data = this.getSessionData();
// Only respect the column if the user explictly set the column to have an inline breakpoint
return data && typeof data.column === 'number' && typeof this._column === 'number' ? data.column : this._column;
}
get message(): string {
const data = this.getSessionData();
if (!data) {
return undefined;
}
if (this.textFileService.isDirty(this.uri)) {
return nls.localize('breakpointDirtydHover', "Unverified breakpoint. File is modified, please restart debug session.");
}
return data.message;
}
get adapterData(): any {
const data = this.getSessionData();
return data && data.source && data.source.adapterData ? data.source.adapterData : this._adapterData;
}
get endLineNumber(): number {
const data = this.getSessionData();
return data ? data.endLine : undefined;
}
get endColumn(): number {
const data = this.getSessionData();
return data ? data.endColumn : undefined;
}
toJSON(): any {
const result = super.toJSON();
result.uri = this.uri;
result.lineNumber = this._lineNumber;
result.column = this._column;
result.adapterData = this.adapterData;
return result;
}
toString(): string {
return resources.basenameOrAuthority(this.uri);
}
update(data: IBreakpointUpdateData): void {
if (!isUndefinedOrNull(data.lineNumber)) {
this._lineNumber = data.lineNumber;
}
if (!isUndefinedOrNull(data.column)) {
this._column = data.column;
}
if (!isUndefinedOrNull(data.condition)) {
this.condition = data.condition;
}
if (!isUndefinedOrNull(data.hitCondition)) {
this.hitCondition = data.hitCondition;
}
if (!isUndefinedOrNull(data.logMessage)) {
this.logMessage = data.logMessage;
}
}
}
export class FunctionBreakpoint extends BaseBreakpoint implements IFunctionBreakpoint {
constructor(
public name: string,
enabled: boolean,
hitCondition: string,
condition: string,
logMessage: string,
id = generateUuid()
) {
super(enabled, hitCondition, condition, logMessage, id);
}
toJSON(): any {
const result = super.toJSON();
result.name = this.name;
return result;
}
toString(): string {
return this.name;
}
}
export class ExceptionBreakpoint extends Enablement implements IExceptionBreakpoint {
constructor(public filter: string, public label: string, enabled: boolean) {
super(enabled, generateUuid());
}
toJSON(): any {
const result = Object.create(null);
result.filter = this.filter;
result.label = this.label;
result.enabled = this.enabled;
return result;
}
toString(): string {
return this.label;
}
}
export class ThreadAndSessionIds implements ITreeElement {
constructor(public sessionId: string, public threadId: number) { }
getId(): string {
return `${this.sessionId}:${this.threadId}`;
}
}
export class DebugModel implements IDebugModel {
private sessions: IDebugSession[];
private toDispose: lifecycle.IDisposable[];
private schedulers = new Map<string, RunOnceScheduler>();
private breakpointsSessionId: string;
private readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent>;
private readonly _onDidChangeCallStack: Emitter<void>;
private readonly _onDidChangeWatchExpressions: Emitter<IExpression>;
constructor(
private breakpoints: Breakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: FunctionBreakpoint[],
private exceptionBreakpoints: ExceptionBreakpoint[],
private watchExpressions: Expression[],
private textFileService: ITextFileService
) {
this.sessions = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<IBreakpointsChangeEvent>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<IExpression>();
}
getId(): string {
return 'root';
}
getSessions(includeInactive = false): IDebugSession[] {
// By default do not return inactive sesions.
// However we are still holding onto inactive sessions due to repl and debug service session revival (eh scenario)
return this.sessions.filter(s => includeInactive || s.state !== State.Inactive);
}
addSession(session: IDebugSession): void {
this.sessions = this.sessions.filter(s => {
if (s.getId() === session.getId()) {
// Make sure to de-dupe if a session is re-intialized. In case of EH debugging we are adding a session again after an attach.
return false;
}
if (s.state === State.Inactive && s.getLabel() === session.getLabel()) {
// Make sure to remove all inactive sessions that are using the same configuration as the new session
return false;
}
return true;
});
this.sessions.push(session);
this._onDidChangeCallStack.fire();
}
get onDidChangeBreakpoints(): Event<IBreakpointsChangeEvent> {
return this._onDidChangeBreakpoints.event;
}
get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
get onDidChangeWatchExpressions(): Event<IExpression> {
return this._onDidChangeWatchExpressions.event;
}
rawUpdate(data: IRawModelUpdate): void {
let session = this.sessions.filter(p => p.getId() === data.sessionId).pop();
if (session) {
session.rawUpdate(data);
this._onDidChangeCallStack.fire();
}
}
clearThreads(id: string, removeThreads: boolean, reference: number | undefined = undefined): void {
const session = this.sessions.filter(p => p.getId() === id).pop();
this.schedulers.forEach(scheduler => scheduler.dispose());
this.schedulers.clear();
if (session) {
session.clearThreads(removeThreads, reference);
this._onDidChangeCallStack.fire();
}
}
fetchCallStack(thread: Thread): Promise<void> {
if (thread.session.capabilities.supportsDelayedStackTraceLoading) {
// For improved performance load the first stack frame and then load the rest async.
return thread.fetchCallStack(1).then(() => {
if (!this.schedulers.has(thread.getId())) {
this.schedulers.set(thread.getId(), new RunOnceScheduler(() => {
thread.fetchCallStack(19).then(() => this._onDidChangeCallStack.fire());
}, 420));
}
this.schedulers.get(thread.getId()).schedule();
this._onDidChangeCallStack.fire();
});
}
return thread.fetchCallStack();
}
getBreakpoints(filter?: { uri?: uri, lineNumber?: number, column?: number, enabledOnly?: boolean }): IBreakpoint[] {
if (filter) {
const uriStr = filter.uri ? filter.uri.toString() : undefined;
return this.breakpoints.filter(bp => {
if (uriStr && bp.uri.toString() !== uriStr) {
return false;
}
if (filter.lineNumber && bp.lineNumber !== filter.lineNumber) {
return false;
}
if (filter.column && bp.column !== filter.column) {
return false;
}
if (filter.enabledOnly && (!this.breakpointsActivated || !bp.enabled)) {
return false;
}
return true;
});
}
return this.breakpoints;
}
getFunctionBreakpoints(): IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
getExceptionBreakpoints(): IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
if (this.exceptionBreakpoints.length === data.length && this.exceptionBreakpoints.every((exbp, i) => exbp.filter === data[i].filter && exbp.label === data[i].label)) {
// No change
return;
}
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
this._onDidChangeBreakpoints.fire();
}
}
areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
addBreakpoints(uri: uri, rawData: IBreakpointData[], fireEvent = true): IBreakpoint[] {
const newBreakpoints = rawData.map(rawBp => new Breakpoint(uri, rawBp.lineNumber, rawBp.column, rawBp.enabled, rawBp.condition, rawBp.hitCondition, rawBp.logMessage, undefined, this.textFileService, rawBp.id));
newBreakpoints.forEach(bp => bp.setSessionId(this.breakpointsSessionId));
this.breakpoints = this.breakpoints.concat(newBreakpoints);
this.breakpointsActivated = true;
this.sortAndDeDup();
if (fireEvent) {
this._onDidChangeBreakpoints.fire({ added: newBreakpoints });
}
return newBreakpoints;
}
removeBreakpoints(toRemove: IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire({ removed: toRemove });
}
updateBreakpoints(data: { [id: string]: IBreakpointUpdateData }): void {
const updated: IBreakpoint[] = [];
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.update(bpData);
updated.push(bp);
}
});
this.sortAndDeDup();
this._onDidChangeBreakpoints.fire({ changed: updated });
}
setBreakpointSessionData(sessionId: string, data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.setSessionData(sessionId, bpData);
}
});
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.setSessionData(sessionId, fbpData);
}
});
this._onDidChangeBreakpoints.fire({
sessionOnly: true
});
}
setBreakpointsSessionId(sessionId: string): void {
this.breakpointsSessionId = sessionId;
this.breakpoints.forEach(bp => bp.setSessionId(sessionId));
this.functionBreakpoints.forEach(fbp => fbp.setSessionId(sessionId));
this._onDidChangeBreakpoints.fire({
sessionOnly: true
});
}
private sortAndDeDup(): void {
this.breakpoints = this.breakpoints.sort((first, second) => {
if (first.uri.toString() !== second.uri.toString()) {
return resources.basenameOrAuthority(first.uri).localeCompare(resources.basenameOrAuthority(second.uri));
}
if (first.lineNumber === second.lineNumber) {
return first.column - second.column;
}
return first.lineNumber - second.lineNumber;
});
this.breakpoints = distinct(this.breakpoints, bp => `${bp.uri.toString()}:${bp.lineNumber}:${bp.column}`);
}
setEnablement(element: IEnablement, enable: boolean): void {
if (element instanceof Breakpoint || element instanceof FunctionBreakpoint || element instanceof ExceptionBreakpoint) {
const changed: Array<IBreakpoint | IFunctionBreakpoint> = [];
if (element.enabled !== enable && (element instanceof Breakpoint || element instanceof FunctionBreakpoint)) {
changed.push(element);
}
element.enabled = enable;
this._onDidChangeBreakpoints.fire({ changed: changed });
}
}
enableOrDisableAllBreakpoints(enable: boolean): void {
const changed: Array<IBreakpoint | IFunctionBreakpoint> = [];
this.breakpoints.forEach(bp => {
if (bp.enabled !== enable) {
changed.push(bp);
}
bp.enabled = enable;
});
this.functionBreakpoints.forEach(fbp => {
if (fbp.enabled !== enable) {
changed.push(fbp);
}
fbp.enabled = enable;
});
this._onDidChangeBreakpoints.fire({ changed: changed });
}
addFunctionBreakpoint(functionName: string, id: string): IFunctionBreakpoint {
const newFunctionBreakpoint = new FunctionBreakpoint(functionName, true, undefined, undefined, undefined, id);
this.functionBreakpoints.push(newFunctionBreakpoint);
this._onDidChangeBreakpoints.fire({ added: [newFunctionBreakpoint] });
return newFunctionBreakpoint;
}
renameFunctionBreakpoint(id: string, name: string): void {
const functionBreakpoint = this.functionBreakpoints.filter(fbp => fbp.getId() === id).pop();
if (functionBreakpoint) {
functionBreakpoint.name = name;
this._onDidChangeBreakpoints.fire({ changed: [functionBreakpoint] });
}
}
removeFunctionBreakpoints(id?: string): void {
let removed: IFunctionBreakpoint[];
if (id) {
removed = this.functionBreakpoints.filter(fbp => fbp.getId() === id);
this.functionBreakpoints = this.functionBreakpoints.filter(fbp => fbp.getId() !== id);
} else {
removed = this.functionBreakpoints;
this.functionBreakpoints = [];
}
this._onDidChangeBreakpoints.fire({ removed: removed });
}
getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
addWatchExpression(name: string): IExpression {
const we = new Expression(name);
this.watchExpressions.push(we);
this._onDidChangeWatchExpressions.fire(we);
return we;
}
renameWatchExpression(id: string, newName: string): void {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
this._onDidChangeWatchExpressions.fire(filtered[0]);
}
}
removeWatchExpressions(id: string | null = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
moveWatchExpression(id: string, position: number): void {
const we = this.watchExpressions.filter(we => we.getId() === id).pop();
this.watchExpressions = this.watchExpressions.filter(we => we.getId() !== id);
this.watchExpressions = this.watchExpressions.slice(0, position).concat(we, this.watchExpressions.slice(position));
this._onDidChangeWatchExpressions.fire();
}
sourceIsNotAvailable(uri: uri): void {
this.sessions.forEach(s => {
const source = s.getSourceForUri(uri);
if (source) {
source.available = false;
}
});
this._onDidChangeCallStack.fire();
}
dispose(): void {
// Make sure to shutdown each session, such that no debugged process is left laying around
this.sessions.forEach(s => s.shutdown());
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.9975997805595398,
0.15778541564941406,
0.00016269095067400485,
0.0001746857160469517,
0.3514178991317749
] |
{
"id": 0,
"code_window": [
"\tgetFunctionBreakpoints(): ReadonlyArray<IFunctionBreakpoint>;\n",
"\tgetExceptionBreakpoints(): ReadonlyArray<IExceptionBreakpoint>;\n",
"\tgetWatchExpressions(): ReadonlyArray<IExpression & IEvaluate>;\n",
"\n",
"\tonDidChangeBreakpoints: Event<IBreakpointsChangeEvent>;\n",
"\tonDidChangeCallStack: Event<void>;\n",
"\tonDidChangeWatchExpressions: Event<IExpression>;\n",
"}\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tonDidChangeCallStack: Event<IThread | undefined>;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debug.ts",
"type": "replace",
"edit_start_line_idx": 395
} | {
"editor": [
{
"name": "vs/platform",
"project": "vscode-editor"
},
{
"name": "vs/editor/contrib",
"project": "vscode-editor"
},
{
"name": "vs/editor",
"project": "vscode-editor"
},
{
"name": "vs/base",
"project": "vscode-editor"
}
],
"workbench": [
{
"name": "vs/code",
"project": "vscode-workbench"
},
{
"name": "vs/workbench",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/cli",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/codeEditor",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/comments",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/debug",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/emmet",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/execution",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/extensions",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/feedback",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/files",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/html",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/markers",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/localizations",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/logs",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/output",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/performance",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/preferences",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/quickopen",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/relauncher",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/scm",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/search",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/snippets",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/stats",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/surveys",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/tasks",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/terminal",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/themes",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/trust",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/update",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/url",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/watermark",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/webview",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/welcome",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/parts/outline",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/actions",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/bulkEdit",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/commands",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/configuration",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/configurationResolver",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/crashReporter",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/dialogs",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/editor",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/extensions",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/jsonschemas",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/files",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/keybinding",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/mode",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/progress",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/remote",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/textfile",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/themes",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/textMate",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/workspace",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/decorations",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/preferences",
"project": "vscode-preferences"
}
]
}
| build/lib/i18n.resources.json | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.0001761512248776853,
0.0001748252980178222,
0.0001740236912155524,
0.0001748014910845086,
4.849467245549022e-7
] |
{
"id": 0,
"code_window": [
"\tgetFunctionBreakpoints(): ReadonlyArray<IFunctionBreakpoint>;\n",
"\tgetExceptionBreakpoints(): ReadonlyArray<IExceptionBreakpoint>;\n",
"\tgetWatchExpressions(): ReadonlyArray<IExpression & IEvaluate>;\n",
"\n",
"\tonDidChangeBreakpoints: Event<IBreakpointsChangeEvent>;\n",
"\tonDidChangeCallStack: Event<void>;\n",
"\tonDidChangeWatchExpressions: Event<IExpression>;\n",
"}\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tonDidChangeCallStack: Event<IThread | undefined>;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debug.ts",
"type": "replace",
"edit_start_line_idx": 395
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as Objects from 'vs/base/common/objects';
import { IJSONSchema, IJSONSchemaMap } from 'vs/base/common/jsonSchema';
import commonSchema from './jsonSchemaCommon';
import { ProblemMatcherRegistry } from 'vs/workbench/parts/tasks/common/problemMatcher';
import { TaskDefinitionRegistry } from '../common/taskDefinitionRegistry';
import * as ConfigurationResolverUtils from 'vs/workbench/services/configurationResolver/common/configurationResolverUtils';
import { inputsSchema } from 'vs/workbench/services/configurationResolver/common/configurationResolverSchema';
function fixReferences(literal: any) {
if (Array.isArray(literal)) {
literal.forEach(fixReferences);
} else if (typeof literal === 'object') {
if (literal['$ref']) {
literal['$ref'] = literal['$ref'] + '2';
}
Object.getOwnPropertyNames(literal).forEach(property => {
let value = literal[property];
if (Array.isArray(value) || typeof value === 'object') {
fixReferences(value);
}
});
}
}
const shellCommand: IJSONSchema = {
anyOf: [
{
type: 'boolean',
default: true,
description: nls.localize('JsonSchema.shell', 'Specifies whether the command is a shell command or an external program. Defaults to false if omitted.')
},
{
$ref: '#definitions/shellConfiguration'
}
],
deprecationMessage: nls.localize('JsonSchema.tasks.isShellCommand.deprecated', 'The property isShellCommand is deprecated. Use the type property of the task and the shell property in the options instead. See also the 1.14 release notes.')
};
const taskIdentifier: IJSONSchema = {
type: 'object',
additionalProperties: true,
properties: {
type: {
type: 'string',
description: nls.localize('JsonSchema.tasks.dependsOn.identifier', 'The task indentifier.')
}
}
};
const dependsOn: IJSONSchema = {
anyOf: [
{
type: 'string',
description: nls.localize('JsonSchema.tasks.dependsOn.string', 'Another task this task depends on.')
},
taskIdentifier,
{
type: 'array',
description: nls.localize('JsonSchema.tasks.dependsOn.array', 'The other tasks this task depends on.'),
items: {
anyOf: [
{
type: 'string',
},
taskIdentifier
]
}
}
]
};
const presentation: IJSONSchema = {
type: 'object',
default: {
echo: true,
reveal: 'always',
focus: false,
panel: 'shared',
showReuseMessage: true,
clear: false,
},
description: nls.localize('JsonSchema.tasks.presentation', 'Configures the panel that is used to present the task\'s ouput and reads its input.'),
additionalProperties: false,
properties: {
echo: {
type: 'boolean',
default: true,
description: nls.localize('JsonSchema.tasks.presentation.echo', 'Controls whether the executed command is echoed to the panel. Default is true.')
},
focus: {
type: 'boolean',
default: false,
description: nls.localize('JsonSchema.tasks.presentation.focus', 'Controls whether the panel takes focus. Default is false. If set to true the panel is revealed as well.')
},
reveal: {
type: 'string',
enum: ['always', 'silent', 'never'],
enumDescriptions: [
nls.localize('JsonSchema.tasks.presentation.reveal.always', 'Always reveals the terminal when this task is executed.'),
nls.localize('JsonSchema.tasks.presentation.reveal.silent', 'Only reveals the terminal if no problem matcher is associated with the task and an errors occurs executing it.'),
nls.localize('JsonSchema.tasks.presentation.reveal.never', 'Never reveals the terminal when this task is executed.'),
],
default: 'always',
description: nls.localize('JsonSchema.tasks.presentation.reveals', 'Controls whether the panel running the task is revealed or not. Default is \"always\".')
},
panel: {
type: 'string',
enum: ['shared', 'dedicated', 'new'],
default: 'shared',
description: nls.localize('JsonSchema.tasks.presentation.instance', 'Controls if the panel is shared between tasks, dedicated to this task or a new one is created on every run.')
},
showReuseMessage: {
type: 'boolean',
default: true,
description: nls.localize('JsonSchema.tasks.presentation.showReuseMessage', 'Controls whether to show the `Terminal will be reused by tasks, press any key to close it` message.')
},
clear: {
type: 'boolean',
default: false,
description: nls.localize('JsonSchema.tasks.presentation.clear', 'Controls whether the terminal is cleared before executing the task.')
}
}
};
const terminal: IJSONSchema = Objects.deepClone(presentation);
terminal.deprecationMessage = nls.localize('JsonSchema.tasks.terminal', 'The terminal property is deprecated. Use presentation instead');
const group: IJSONSchema = {
oneOf: [
{
type: 'string',
},
{
type: 'object',
properties: {
kind: {
type: 'string',
default: 'none',
description: nls.localize('JsonSchema.tasks.group.kind', 'The task\'s execution group.')
},
isDefault: {
type: 'boolean',
default: false,
description: nls.localize('JsonSchema.tasks.group.isDefault', 'Defines if this task is the default task in the group.')
}
}
},
],
enum: [
{ kind: 'build', isDefault: true },
{ kind: 'test', isDefault: true },
'build',
'test',
'none'
],
enumDescriptions: [
nls.localize('JsonSchema.tasks.group.defaultBuild', 'Marks the task as the default build task.'),
nls.localize('JsonSchema.tasks.group.defaultTest', 'Marks the task as the default test task.'),
nls.localize('JsonSchema.tasks.group.build', 'Marks the task as a build task accesible through the \'Run Build Task\' command.'),
nls.localize('JsonSchema.tasks.group.test', 'Marks the task as a test task accesible through the \'Run Test Task\' command.'),
nls.localize('JsonSchema.tasks.group.none', 'Assigns the task to no group')
],
description: nls.localize('JsonSchema.tasks.group', 'Defines to which execution group this task belongs to. It supports "build" to add it to the build group and "test" to add it to the test group.')
};
const taskType: IJSONSchema = {
type: 'string',
enum: ['shell', 'process'],
default: 'shell',
description: nls.localize('JsonSchema.tasks.type', 'Defines whether the task is run as a process or as a command inside a shell.')
};
const command: IJSONSchema = {
oneOf: [
{
oneOf: [
{
type: 'string'
},
{
type: 'array',
items: {
type: 'string'
},
description: nls.localize('JsonSchema.commandArray', 'The shell command to be executed. Array items will be joined using a space character')
}
]
},
{
type: 'object',
required: ['value', 'quoting'],
properties: {
value: {
oneOf: [
{
type: 'string'
},
{
type: 'array',
items: {
type: 'string'
},
description: nls.localize('JsonSchema.commandArray', 'The shell command to be executed. Array items will be joined using a space character')
}
],
description: nls.localize('JsonSchema.command.quotedString.value', 'The actual command value')
},
quoting: {
type: 'string',
enum: ['escape', 'strong', 'weak'],
enumDescriptions: [
nls.localize('JsonSchema.tasks.quoting.escape', 'Escapes characters using the shell\'s escape character (e.g. ` under PowerShell and \\ under bash).'),
nls.localize('JsonSchema.tasks.quoting.strong', 'Quotes the argument using the shell\'s strong quote character (e.g. " under PowerShell and bash).'),
nls.localize('JsonSchema.tasks.quoting.weak', 'Quotes the argument using the shell\'s weak quote character (e.g. \' under PowerShell and bash).'),
],
default: 'strong',
description: nls.localize('JsonSchema.command.quotesString.quote', 'How the command value should be quoted.')
}
}
}
],
description: nls.localize('JsonSchema.command', 'The command to be executed. Can be an external program or a shell command.')
};
const args: IJSONSchema = {
type: 'array',
items: {
oneOf: [
{
type: 'string',
},
{
type: 'object',
required: ['value', 'quoting'],
properties: {
value: {
type: 'string',
description: nls.localize('JsonSchema.args.quotedString.value', 'The actual argument value')
},
quoting: {
type: 'string',
enum: ['escape', 'strong', 'weak'],
enumDescriptions: [
nls.localize('JsonSchema.tasks.quoting.escape', 'Escapes characters using the shell\'s escape character (e.g. ` under PowerShell and \\ under bash).'),
nls.localize('JsonSchema.tasks.quoting.strong', 'Quotes the argument using the shell\'s strong quote character (e.g. " under PowerShell and bash).'),
nls.localize('JsonSchema.tasks.quoting.weak', 'Quotes the argument using the shell\'s weak quote character (e.g. \' under PowerShell and bash).'),
],
default: 'strong',
description: nls.localize('JsonSchema.args.quotesString.quote', 'How the argument value should be quoted.')
}
}
}
]
},
description: nls.localize('JsonSchema.tasks.args', 'Arguments passed to the command when this task is invoked.')
};
const label: IJSONSchema = {
type: 'string',
description: nls.localize('JsonSchema.tasks.label', "The task's user interface label")
};
const version: IJSONSchema = {
type: 'string',
enum: ['2.0.0'],
description: nls.localize('JsonSchema.version', 'The config\'s version number.')
};
const identifier: IJSONSchema = {
type: 'string',
description: nls.localize('JsonSchema.tasks.identifier', 'A user defined identifier to reference the task in launch.json or a dependsOn clause.'),
deprecationMessage: nls.localize('JsonSchema.tasks.identifier.deprecated', 'User defined identifiers are deprecated. For custom task use the name as a reference and for tasks provided by extensions use their defined task identifier.')
};
const runOptions: IJSONSchema = {
type: 'object',
properties: {
reevaluateOnRerun: {
type: 'boolean',
description: nls.localize('JsonSchema.tasks.reevaluateOnRerun', 'Whether to reevaluate task variables on rerun.'),
default: true
},
runOn: {
type: 'string',
enum: ['default', 'folderOpen'],
description: nls.localize('JsonSchema.tasks.runOn', 'Configures when the task should be run. If set to folderOpen, then the task will be run automatically when the folder is opened.'),
default: 'default'
},
},
description: nls.localize('JsonSchema.tasks.runOptions', 'The task\'s run related options')
};
const commonSchemaDefinitions = commonSchema.definitions!;
const options: IJSONSchema = Objects.deepClone(commonSchemaDefinitions.options);
const optionsProperties = options.properties!;
optionsProperties.shell = Objects.deepClone(commonSchemaDefinitions.shellConfiguration);
let taskConfiguration: IJSONSchema = {
type: 'object',
additionalProperties: false,
properties: {
label: {
type: 'string',
description: nls.localize('JsonSchema.tasks.taskLabel', "The task's label")
},
taskName: {
type: 'string',
description: nls.localize('JsonSchema.tasks.taskName', 'The task\'s name'),
deprecationMessage: nls.localize('JsonSchema.tasks.taskName.deprecated', 'The task\'s name property is deprecated. Use the label property instead.')
},
identifier: Objects.deepClone(identifier),
group: Objects.deepClone(group),
isBackground: {
type: 'boolean',
description: nls.localize('JsonSchema.tasks.background', 'Whether the executed task is kept alive and is running in the background.'),
default: true
},
promptOnClose: {
type: 'boolean',
description: nls.localize('JsonSchema.tasks.promptOnClose', 'Whether the user is prompted when VS Code closes with a running task.'),
default: false
},
presentation: Objects.deepClone(presentation),
options: options,
problemMatcher: {
$ref: '#/definitions/problemMatcherType',
description: nls.localize('JsonSchema.tasks.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.')
},
runOptions: Objects.deepClone(runOptions),
}
};
let taskDefinitions: IJSONSchema[] = [];
TaskDefinitionRegistry.onReady().then(() => {
for (let taskType of TaskDefinitionRegistry.all()) {
let schema: IJSONSchema = Objects.deepClone(taskConfiguration);
const schemaProperties = schema.properties!;
// Since we do this after the schema is assigned we need to patch the refs.
schemaProperties.type = {
type: 'string',
description: nls.localize('JsonSchema.customizations.customizes.type', 'The task type to customize'),
enum: [taskType.taskType]
};
if (taskType.required) {
schema.required = taskType.required.slice();
}
if (taskType.properties) {
for (let key of Object.keys(taskType.properties)) {
let property = taskType.properties[key];
schemaProperties[key] = Objects.deepClone(property);
}
}
fixReferences(schema);
taskDefinitions.push(schema);
}
});
let customize = Objects.deepClone(taskConfiguration);
customize.properties!.customize = {
type: 'string',
deprecationMessage: nls.localize('JsonSchema.tasks.customize.deprecated', 'The customize property is deprecated. See the 1.14 release notes on how to migrate to the new task customization approach')
};
taskDefinitions.push(customize);
let definitions = Objects.deepClone(commonSchemaDefinitions);
let taskDescription: IJSONSchema = definitions.taskDescription;
taskDescription.required = ['label'];
const taskDescriptionProperties = taskDescription.properties!;
taskDescriptionProperties.label = Objects.deepClone(label);
taskDescriptionProperties.command = Objects.deepClone(command);
taskDescriptionProperties.args = Objects.deepClone(args);
taskDescriptionProperties.isShellCommand = Objects.deepClone(shellCommand);
taskDescriptionProperties.dependsOn = dependsOn;
taskDescriptionProperties.identifier = Objects.deepClone(identifier);
taskDescriptionProperties.type = Objects.deepClone(taskType);
taskDescriptionProperties.presentation = Objects.deepClone(presentation);
taskDescriptionProperties.terminal = terminal;
taskDescriptionProperties.group = Objects.deepClone(group);
taskDescriptionProperties.runOptions = Objects.deepClone(runOptions);
taskDescriptionProperties.taskName.deprecationMessage = nls.localize(
'JsonSchema.tasks.taskName.deprecated',
'The task\'s name property is deprecated. Use the label property instead.'
);
taskDescription.default = {
label: 'My Task',
type: 'shell',
command: 'echo Hello',
problemMatcher: []
};
definitions.showOutputType.deprecationMessage = nls.localize(
'JsonSchema.tasks.showOputput.deprecated',
'The property showOutput is deprecated. Use the reveal property inside the presentation property instead. See also the 1.14 release notes.'
);
taskDescriptionProperties.echoCommand.deprecationMessage = nls.localize(
'JsonSchema.tasks.echoCommand.deprecated',
'The property echoCommand is deprecated. Use the echo property inside the presentation property instead. See also the 1.14 release notes.'
);
taskDescriptionProperties.suppressTaskName.deprecationMessage = nls.localize(
'JsonSchema.tasks.suppressTaskName.deprecated',
'The property suppressTaskName is deprecated. Inline the command with its arguments into the task instead. See also the 1.14 release notes.'
);
taskDescriptionProperties.isBuildCommand.deprecationMessage = nls.localize(
'JsonSchema.tasks.isBuildCommand.deprecated',
'The property isBuildCommand is deprecated. Use the group property instead. See also the 1.14 release notes.'
);
taskDescriptionProperties.isTestCommand.deprecationMessage = nls.localize(
'JsonSchema.tasks.isTestCommand.deprecated',
'The property isTestCommand is deprecated. Use the group property instead. See also the 1.14 release notes.'
);
taskDefinitions.push({
$ref: '#/definitions/taskDescription'
} as IJSONSchema);
const definitionsTaskRunnerConfigurationProperties = definitions.taskRunnerConfiguration.properties!;
let tasks = definitionsTaskRunnerConfigurationProperties.tasks;
tasks.items = {
oneOf: taskDefinitions
};
definitionsTaskRunnerConfigurationProperties.inputs = inputsSchema.definitions!.inputs;
definitions.commandConfiguration.properties!.isShellCommand = Objects.deepClone(shellCommand);
definitions.options.properties!.shell = {
$ref: '#/definitions/shellConfiguration'
};
definitionsTaskRunnerConfigurationProperties.isShellCommand = Objects.deepClone(shellCommand);
definitionsTaskRunnerConfigurationProperties.type = Objects.deepClone(taskType);
definitionsTaskRunnerConfigurationProperties.group = Objects.deepClone(group);
definitionsTaskRunnerConfigurationProperties.presentation = Objects.deepClone(presentation);
definitionsTaskRunnerConfigurationProperties.suppressTaskName.deprecationMessage = nls.localize(
'JsonSchema.tasks.suppressTaskName.deprecated',
'The property suppressTaskName is deprecated. Inline the command with its arguments into the task instead. See also the 1.14 release notes.'
);
definitionsTaskRunnerConfigurationProperties.taskSelector.deprecationMessage = nls.localize(
'JsonSchema.tasks.taskSelector.deprecated',
'The property taskSelector is deprecated. Inline the command with its arguments into the task instead. See also the 1.14 release notes.'
);
let osSpecificTaskRunnerConfiguration = Objects.deepClone(definitions.taskRunnerConfiguration);
delete osSpecificTaskRunnerConfiguration.properties!.tasks;
osSpecificTaskRunnerConfiguration.additionalProperties = false;
definitions.osSpecificTaskRunnerConfiguration = osSpecificTaskRunnerConfiguration;
definitionsTaskRunnerConfigurationProperties.version = Objects.deepClone(version);
const schema: IJSONSchema = {
oneOf: [
{
'allOf': [
{
type: 'object',
required: ['version'],
properties: {
version: Objects.deepClone(version),
windows: {
'$ref': '#/definitions/osSpecificTaskRunnerConfiguration',
'description': nls.localize('JsonSchema.windows', 'Windows specific command configuration')
},
osx: {
'$ref': '#/definitions/osSpecificTaskRunnerConfiguration',
'description': nls.localize('JsonSchema.mac', 'Mac specific command configuration')
},
linux: {
'$ref': '#/definitions/osSpecificTaskRunnerConfiguration',
'description': nls.localize('JsonSchema.linux', 'Linux specific command configuration')
}
}
},
{
$ref: '#/definitions/taskRunnerConfiguration'
}
]
}
]
};
schema.definitions = definitions;
function deprecatedVariableMessage(schemaMap: IJSONSchemaMap, property: string) {
const mapAtProperty = schemaMap[property].properties!;
if (mapAtProperty) {
Object.keys(mapAtProperty).forEach(name => {
deprecatedVariableMessage(mapAtProperty, name);
});
} else {
ConfigurationResolverUtils.applyDeprecatedVariableMessage(schemaMap[property]);
}
}
Object.getOwnPropertyNames(definitions).forEach(key => {
let newKey = key + '2';
definitions[newKey] = definitions[key];
delete definitions[key];
deprecatedVariableMessage(definitions, newKey);
});
fixReferences(schema);
ProblemMatcherRegistry.onReady().then(() => {
try {
let matcherIds = ProblemMatcherRegistry.keys().map(key => '$' + key);
definitions.problemMatcherType2.oneOf![0].enum = matcherIds;
(definitions.problemMatcherType2.oneOf![2].items as IJSONSchema).anyOf![1].enum = matcherIds;
} catch (err) {
console.log('Installing problem matcher ids failed');
}
});
export default schema;
| src/vs/workbench/parts/tasks/electron-browser/jsonSchema_v2.ts | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.00017808255506679416,
0.00017421347729396075,
0.00016860870528034866,
0.0001744143955875188,
0.0000023087955014489125
] |
{
"id": 0,
"code_window": [
"\tgetFunctionBreakpoints(): ReadonlyArray<IFunctionBreakpoint>;\n",
"\tgetExceptionBreakpoints(): ReadonlyArray<IExceptionBreakpoint>;\n",
"\tgetWatchExpressions(): ReadonlyArray<IExpression & IEvaluate>;\n",
"\n",
"\tonDidChangeBreakpoints: Event<IBreakpointsChangeEvent>;\n",
"\tonDidChangeCallStack: Event<void>;\n",
"\tonDidChangeWatchExpressions: Event<IExpression>;\n",
"}\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tonDidChangeCallStack: Event<IThread | undefined>;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debug.ts",
"type": "replace",
"edit_start_line_idx": 395
} | /*---------------------------------------------------------------------------------------------
* 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 severity from 'vs/base/common/severity';
import { IAction, Action } from 'vs/base/common/actions';
import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import pkg from 'vs/platform/node/package';
import product from 'vs/platform/node/product';
import { URI } from 'vs/base/common/uri';
import { IActivityService, NumberBadge, IBadge, ProgressBadge } from 'vs/workbench/services/activity/common/activity';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IGlobalActivity } from 'vs/workbench/common/activity';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IUpdateService, State as UpdateState, StateType, IUpdate } from 'vs/platform/update/common/update';
import * as semver from 'semver';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { INotificationService, INotificationHandle, Severity } from 'vs/platform/notification/common/notification';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { ReleaseNotesManager } from './releaseNotesEditor';
import { isWindows } from 'vs/base/common/platform';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { HappyHolidaysAction } from 'vs/workbench/parts/holidays/electron-browser/holidays.contribution';
let releaseNotesManager: ReleaseNotesManager | undefined = undefined;
function showReleaseNotes(instantiationService: IInstantiationService, version: string) {
if (!releaseNotesManager) {
releaseNotesManager = instantiationService.createInstance(ReleaseNotesManager);
}
return instantiationService.invokeFunction(accessor => releaseNotesManager.show(accessor, version));
}
export class OpenLatestReleaseNotesInBrowserAction extends Action {
constructor(
@IOpenerService private openerService: IOpenerService
) {
super('update.openLatestReleaseNotes', nls.localize('releaseNotes', "Release Notes"), null, true);
}
run(): Promise<any> {
if (product.releaseNotesUrl) {
const uri = URI.parse(product.releaseNotesUrl);
return this.openerService.open(uri);
}
return Promise.resolve(false);
}
}
export abstract class AbstractShowReleaseNotesAction extends Action {
constructor(
id: string,
label: string,
private version: string,
@IInstantiationService private instantiationService: IInstantiationService
) {
super(id, label, null, true);
}
run(): Promise<boolean> {
if (!this.enabled) {
return Promise.resolve(false);
}
this.enabled = false;
return showReleaseNotes(this.instantiationService, this.version)
.then(void 0, () => {
const action = this.instantiationService.createInstance(OpenLatestReleaseNotesInBrowserAction);
return action.run().then(() => false);
});
}
}
export class ShowReleaseNotesAction extends AbstractShowReleaseNotesAction {
constructor(
version: string,
@IInstantiationService instantiationService: IInstantiationService
) {
super('update.showReleaseNotes', nls.localize('releaseNotes', "Release Notes"), version, instantiationService);
}
}
export class ShowCurrentReleaseNotesAction extends AbstractShowReleaseNotesAction {
static readonly ID = 'update.showCurrentReleaseNotes';
static LABEL = nls.localize('showReleaseNotes', "Show Release Notes");
constructor(
id = ShowCurrentReleaseNotesAction.ID,
label = ShowCurrentReleaseNotesAction.LABEL,
@IInstantiationService instantiationService: IInstantiationService
) {
super(id, label, pkg.version, instantiationService);
}
}
export class ProductContribution implements IWorkbenchContribution {
private static readonly KEY = 'releaseNotes/lastVersion';
constructor(
@IStorageService storageService: IStorageService,
@IInstantiationService instantiationService: IInstantiationService,
@INotificationService notificationService: INotificationService,
@IEnvironmentService environmentService: IEnvironmentService,
@IOpenerService openerService: IOpenerService,
@IConfigurationService configurationService: IConfigurationService
) {
const lastVersion = storageService.get(ProductContribution.KEY, StorageScope.GLOBAL, '');
const shouldShowReleaseNotes = configurationService.getValue<boolean>('update.showReleaseNotes');
// was there an update? if so, open release notes
if (shouldShowReleaseNotes && !environmentService.skipReleaseNotes && product.releaseNotesUrl && lastVersion && pkg.version !== lastVersion) {
showReleaseNotes(instantiationService, pkg.version)
.then(undefined, () => {
notificationService.prompt(
severity.Info,
nls.localize('read the release notes', "Welcome to {0} v{1}! Would you like to read the Release Notes?", product.nameLong, pkg.version),
[{
label: nls.localize('releaseNotes', "Release Notes"),
run: () => {
const uri = URI.parse(product.releaseNotesUrl);
openerService.open(uri);
}
}],
{ sticky: true }
);
});
}
// should we show the new license?
if (product.licenseUrl && lastVersion && semver.satisfies(lastVersion, '<1.0.0') && semver.satisfies(pkg.version, '>=1.0.0')) {
notificationService.info(nls.localize('licenseChanged', "Our license terms have changed, please click [here]({0}) to go through them.", product.licenseUrl));
}
storageService.store(ProductContribution.KEY, pkg.version, StorageScope.GLOBAL);
}
}
class NeverShowAgain {
private readonly key: string;
readonly action = new Action(`neverShowAgain:${this.key}`, nls.localize('neveragain', "Don't Show Again"), undefined, true, (notification: INotificationHandle) => {
// Hide notification
notification.close();
this.storageService.store(this.key, true, StorageScope.GLOBAL);
return Promise.resolve(true);
});
constructor(key: string, @IStorageService private storageService: IStorageService) {
this.key = `neverShowAgain:${key}`;
}
shouldShow(): boolean {
return !this.storageService.getBoolean(this.key, StorageScope.GLOBAL, false);
}
}
export class Win3264BitContribution implements IWorkbenchContribution {
private static readonly KEY = 'update/win32-64bits';
private static readonly URL = 'https://code.visualstudio.com/updates/v1_15#_windows-64-bit';
private static readonly INSIDER_URL = 'https://github.com/Microsoft/vscode-docs/blob/vnext/release-notes/v1_15.md#windows-64-bit';
constructor(
@IStorageService storageService: IStorageService,
@INotificationService notificationService: INotificationService,
@IEnvironmentService environmentService: IEnvironmentService
) {
if (environmentService.disableUpdates) {
return;
}
const neverShowAgain = new NeverShowAgain(Win3264BitContribution.KEY, storageService);
if (!neverShowAgain.shouldShow()) {
return;
}
const url = product.quality === 'insider'
? Win3264BitContribution.INSIDER_URL
: Win3264BitContribution.URL;
const handle = notificationService.prompt(
severity.Info,
nls.localize('64bitisavailable', "{0} for 64-bit Windows is now available! Click [here]({1}) to learn more.", product.nameShort, url),
[{
label: nls.localize('neveragain', "Don't Show Again"),
isSecondary: true,
run: () => {
neverShowAgain.action.run(handle);
neverShowAgain.action.dispose();
}
}],
{ sticky: true }
);
}
}
class CommandAction extends Action {
constructor(
commandId: string,
label: string,
@ICommandService commandService: ICommandService
) {
super(`command-action:${commandId}`, label, undefined, true, () => commandService.executeCommand(commandId));
}
}
export class UpdateContribution implements IGlobalActivity {
private static readonly showCommandsId = 'workbench.action.showCommands';
private static readonly openSettingsId = 'workbench.action.openSettings';
private static readonly openKeybindingsId = 'workbench.action.openGlobalKeybindings';
private static readonly openUserSnippets = 'workbench.action.openSnippets';
private static readonly selectColorThemeId = 'workbench.action.selectTheme';
private static readonly selectIconThemeId = 'workbench.action.selectIconTheme';
private static readonly showExtensionsId = 'workbench.view.extensions';
get id() { return 'vs.update'; }
get name() { return nls.localize('manage', "Manage"); }
get cssClass() { return 'update-activity'; }
private state: UpdateState;
private badgeDisposable: IDisposable = Disposable.None;
private disposables: IDisposable[] = [];
constructor(
@IStorageService private storageService: IStorageService,
@ICommandService private commandService: ICommandService,
@IInstantiationService private instantiationService: IInstantiationService,
@INotificationService private notificationService: INotificationService,
@IDialogService private dialogService: IDialogService,
@IUpdateService private updateService: IUpdateService,
@IActivityService private activityService: IActivityService,
@IWindowService private windowService: IWindowService
) {
this.state = updateService.state;
updateService.onStateChange(this.onUpdateStateChange, this, this.disposables);
this.onUpdateStateChange(this.updateService.state);
/*
The `update/lastKnownVersion` and `update/updateNotificationTime` storage keys are used in
combination to figure out when to show a message to the user that he should update.
This message should appear if the user has received an update notification but hasn't
updated since 5 days.
*/
const currentVersion = product.commit;
const lastKnownVersion = this.storageService.get('update/lastKnownVersion', StorageScope.GLOBAL);
// if current version != stored version, clear both fields
if (currentVersion !== lastKnownVersion) {
this.storageService.remove('update/lastKnownVersion', StorageScope.GLOBAL);
this.storageService.remove('update/updateNotificationTime', StorageScope.GLOBAL);
}
}
private onUpdateStateChange(state: UpdateState): void {
switch (state.type) {
case StateType.Idle:
if (state.error) {
this.onError(state.error);
} else if (this.state.type === StateType.CheckingForUpdates && this.state.context && this.state.context.windowId === this.windowService.getCurrentWindowId()) {
this.onUpdateNotAvailable();
}
break;
case StateType.AvailableForDownload:
this.onUpdateAvailable(state.update);
break;
case StateType.Downloaded:
this.onUpdateDownloaded(state.update);
break;
case StateType.Updating:
this.onUpdateUpdating(state.update);
break;
case StateType.Ready:
this.onUpdateReady(state.update);
break;
}
let badge: IBadge | undefined = undefined;
let clazz: string | undefined;
if (state.type === StateType.AvailableForDownload || state.type === StateType.Downloaded || state.type === StateType.Ready) {
badge = new NumberBadge(1, () => nls.localize('updateIsReady', "New {0} update available.", product.nameShort));
} else if (state.type === StateType.CheckingForUpdates || state.type === StateType.Downloading || state.type === StateType.Updating) {
badge = new ProgressBadge(() => nls.localize('updateIsReady', "New {0} update available.", product.nameShort));
clazz = 'progress-badge';
}
this.badgeDisposable.dispose();
if (badge) {
this.badgeDisposable = this.activityService.showActivity(this.id, badge, clazz);
}
this.state = state;
}
private onError(error: string): void {
error = error.replace(/See https:\/\/github\.com\/Squirrel\/Squirrel\.Mac\/issues\/182 for more information/, 'See [this link](https://github.com/Microsoft/vscode/issues/7426#issuecomment-425093469) for more information');
this.notificationService.notify({
severity: Severity.Error,
message: error,
source: nls.localize('update service', "Update Service"),
});
}
private onUpdateNotAvailable(): void {
this.dialogService.show(
severity.Info,
nls.localize('noUpdatesAvailable', "There are currently no updates available."),
[nls.localize('ok', "OK")]
);
}
// linux
private onUpdateAvailable(update: IUpdate): void {
if (!this.shouldShowNotification()) {
return;
}
this.notificationService.prompt(
severity.Info,
nls.localize('thereIsUpdateAvailable', "There is an available update."),
[{
label: nls.localize('download now', "Download Now"),
run: () => this.updateService.downloadUpdate()
}, {
label: nls.localize('later', "Later"),
run: () => { }
}, {
label: nls.localize('releaseNotes', "Release Notes"),
run: () => {
const action = this.instantiationService.createInstance(ShowReleaseNotesAction, update.productVersion);
action.run();
action.dispose();
}
}],
{ sticky: true }
);
}
// windows fast updates (target === system)
private onUpdateDownloaded(update: IUpdate): void {
if (!this.shouldShowNotification()) {
return;
}
this.notificationService.prompt(
severity.Info,
nls.localize('updateAvailable', "There's an update available: {0} {1}", product.nameLong, update.productVersion),
[{
label: nls.localize('installUpdate', "Install Update"),
run: () => this.updateService.applyUpdate()
}, {
label: nls.localize('later', "Later"),
run: () => { }
}, {
label: nls.localize('releaseNotes', "Release Notes"),
run: () => {
const action = this.instantiationService.createInstance(ShowReleaseNotesAction, update.productVersion);
action.run();
action.dispose();
}
}],
{ sticky: true }
);
}
// windows fast updates
private onUpdateUpdating(update: IUpdate): void {
if (isWindows && product.target === 'user') {
return;
}
// windows fast updates (target === system)
const neverShowAgain = new NeverShowAgain('update/win32-fast-updates', this.storageService);
if (!neverShowAgain.shouldShow()) {
return;
}
const handle = this.notificationService.prompt(
severity.Info,
nls.localize('updateInstalling', "{0} {1} is being installed in the background; we'll let you know when it's done.", product.nameLong, update.productVersion),
[{
label: nls.localize('neveragain', "Don't Show Again"),
isSecondary: true,
run: () => {
neverShowAgain.action.run(handle);
neverShowAgain.action.dispose();
}
}]
);
}
// windows and mac
private onUpdateReady(update: IUpdate): void {
if (!(isWindows && product.target !== 'user') && !this.shouldShowNotification()) {
return;
}
const actions = [{
label: nls.localize('updateNow', "Update Now"),
run: () => this.updateService.quitAndInstall()
}, {
label: nls.localize('later', "Later"),
run: () => { }
}];
// TODO@joao check why snap updates send `update` as falsy
if (update.productVersion) {
actions.push({
label: nls.localize('releaseNotes', "Release Notes"),
run: () => {
const action = this.instantiationService.createInstance(ShowReleaseNotesAction, update.productVersion);
action.run();
action.dispose();
}
});
}
// windows user fast updates and mac
this.notificationService.prompt(
severity.Info,
nls.localize('updateAvailableAfterRestart', "Restart {0} to apply the latest update.", product.nameLong),
actions,
{ sticky: true }
);
}
private shouldShowNotification(): boolean {
const currentVersion = product.commit;
const currentMillis = new Date().getTime();
const lastKnownVersion = this.storageService.get('update/lastKnownVersion', StorageScope.GLOBAL);
// if version != stored version, save version and date
if (currentVersion !== lastKnownVersion) {
this.storageService.store('update/lastKnownVersion', currentVersion, StorageScope.GLOBAL);
this.storageService.store('update/updateNotificationTime', currentMillis, StorageScope.GLOBAL);
}
const updateNotificationMillis = this.storageService.getInteger('update/updateNotificationTime', StorageScope.GLOBAL, currentMillis);
const diffDays = (currentMillis - updateNotificationMillis) / (1000 * 60 * 60 * 24);
return diffDays > 5;
}
getActions(): IAction[] {
const result: IAction[] = [
new CommandAction(UpdateContribution.showCommandsId, nls.localize('commandPalette', "Command Palette..."), this.commandService),
new Separator(),
new CommandAction(UpdateContribution.openSettingsId, nls.localize('settings', "Settings"), this.commandService),
new CommandAction(UpdateContribution.showExtensionsId, nls.localize('showExtensions', "Extensions"), this.commandService),
new CommandAction(UpdateContribution.openKeybindingsId, nls.localize('keyboardShortcuts', "Keyboard Shortcuts"), this.commandService),
new Separator(),
new CommandAction(UpdateContribution.openUserSnippets, nls.localize('userSnippets', "User Snippets"), this.commandService),
new Separator(),
new CommandAction(UpdateContribution.selectColorThemeId, nls.localize('selectTheme.label', "Color Theme"), this.commandService),
new CommandAction(UpdateContribution.selectIconThemeId, nls.localize('themes.selectIconTheme.label', "File Icon Theme"), this.commandService)
];
const updateAction = this.getUpdateAction();
if (updateAction) {
result.push(new Separator(), updateAction);
}
result.push(
new Separator(),
this.instantiationService.createInstance(HappyHolidaysAction, HappyHolidaysAction.ID, HappyHolidaysAction.LABEL)
);
return result;
}
private getUpdateAction(): IAction | null {
const state = this.updateService.state;
switch (state.type) {
case StateType.Uninitialized:
return null;
case StateType.Idle:
const windowId = this.windowService.getCurrentWindowId();
return new Action('update.check', nls.localize('checkForUpdates', "Check for Updates..."), undefined, true, () =>
this.updateService.checkForUpdates({ windowId }));
case StateType.CheckingForUpdates:
return new Action('update.checking', nls.localize('checkingForUpdates', "Checking For Updates..."), undefined, false);
case StateType.AvailableForDownload:
return new Action('update.downloadNow', nls.localize('download now', "Download Now"), null, true, () =>
this.updateService.downloadUpdate());
case StateType.Downloading:
return new Action('update.downloading', nls.localize('DownloadingUpdate', "Downloading Update..."), undefined, false);
case StateType.Downloaded:
return new Action('update.install', nls.localize('installUpdate...', "Install Update..."), undefined, true, () =>
this.updateService.applyUpdate());
case StateType.Updating:
return new Action('update.updating', nls.localize('installingUpdate', "Installing Update..."), undefined, false);
case StateType.Ready:
return new Action('update.restart', nls.localize('restartToUpdate', "Restart to Update..."), undefined, true, () =>
this.updateService.quitAndInstall());
}
}
dispose(): void {
this.disposables = dispose(this.disposables);
}
}
| src/vs/workbench/parts/update/electron-browser/update.ts | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.0002224808413302526,
0.0001740965381031856,
0.00016557271010242403,
0.00017440409283153713,
0.0000075292314249963965
] |
{
"id": 1,
"code_window": [
"\tprivate sessions: IDebugSession[];\n",
"\tprivate toDispose: lifecycle.IDisposable[];\n",
"\tprivate schedulers = new Map<string, RunOnceScheduler>();\n",
"\tprivate breakpointsSessionId: string;\n",
"\tprivate readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent>;\n",
"\tprivate readonly _onDidChangeCallStack: Emitter<void>;\n",
"\tprivate readonly _onDidChangeWatchExpressions: Emitter<IExpression>;\n",
"\n",
"\tconstructor(\n",
"\t\tprivate breakpoints: Breakpoint[],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate readonly _onDidChangeCallStack: Emitter<IThread | undefined>;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 739
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI as uri } from 'vs/base/common/uri';
import * as resources from 'vs/base/common/resources';
import * as lifecycle from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
import { generateUuid } from 'vs/base/common/uuid';
import { RunOnceScheduler } from 'vs/base/common/async';
import severity from 'vs/base/common/severity';
import { isObject, isString, isUndefinedOrNull } from 'vs/base/common/types';
import { distinct } from 'vs/base/common/arrays';
import { Range, IRange } from 'vs/editor/common/core/range';
import {
ITreeElement, IExpression, IExpressionContainer, IDebugSession, IStackFrame, IExceptionBreakpoint, IBreakpoint, IFunctionBreakpoint, IDebugModel, IReplElementSource,
IThread, IRawModelUpdate, IScope, IRawStoppedDetails, IEnablement, IBreakpointData, IExceptionInfo, IReplElement, IBreakpointsChangeEvent, IBreakpointUpdateData, IBaseBreakpoint, State
} from 'vs/workbench/parts/debug/common/debug';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { commonSuffixLength } from 'vs/base/common/strings';
import { sep } from 'vs/base/common/paths';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
export class SimpleReplElement implements IReplElement {
constructor(
private id: string,
public value: string,
public severity: severity,
public sourceData: IReplElementSource,
) { }
toString(): string {
return this.value;
}
getId(): string {
return this.id;
}
}
export class RawObjectReplElement implements IExpression {
private static readonly MAX_CHILDREN = 1000; // upper bound of children per value
constructor(private id: string, public name: string, public valueObj: any, public sourceData?: IReplElementSource, public annotation?: string) { }
getId(): string {
return this.id;
}
get value(): string {
if (this.valueObj === null) {
return 'null';
} else if (Array.isArray(this.valueObj)) {
return `Array[${this.valueObj.length}]`;
} else if (isObject(this.valueObj)) {
return 'Object';
} else if (isString(this.valueObj)) {
return `"${this.valueObj}"`;
}
return String(this.valueObj) || '';
}
get hasChildren(): boolean {
return (Array.isArray(this.valueObj) && this.valueObj.length > 0) || (isObject(this.valueObj) && Object.getOwnPropertyNames(this.valueObj).length > 0);
}
getChildren(): Promise<IExpression[]> {
let result: IExpression[] = [];
if (Array.isArray(this.valueObj)) {
result = (<any[]>this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN)
.map((v, index) => new RawObjectReplElement(`${this.id}:${index}`, String(index), v));
} else if (isObject(this.valueObj)) {
result = Object.getOwnPropertyNames(this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN)
.map((key, index) => new RawObjectReplElement(`${this.id}:${index}`, key, this.valueObj[key]));
}
return Promise.resolve(result);
}
toString(): string {
return `${this.name}\n${this.value}`;
}
}
export class ExpressionContainer implements IExpressionContainer {
public static allValues: Map<string, string> = new Map<string, string>();
// Use chunks to support variable paging #9537
private static readonly BASE_CHUNK_SIZE = 100;
public valueChanged: boolean;
private _value: string;
protected children: Promise<IExpression[]>;
constructor(
protected session: IDebugSession,
private _reference: number,
private id: string,
public namedVariables = 0,
public indexedVariables = 0,
private startOfVariables = 0
) { }
get reference(): number {
return this._reference;
}
set reference(value: number) {
this._reference = value;
this.children = undefined; // invalidate children cache
}
getChildren(): Promise<IExpression[]> {
if (!this.children) {
this.children = this.doGetChildren();
}
return this.children;
}
private doGetChildren(): Promise<IExpression[]> {
if (!this.hasChildren) {
return Promise.resolve([]);
}
if (!this.getChildrenInChunks) {
return this.fetchVariables(undefined, undefined, undefined);
}
// Check if object has named variables, fetch them independent from indexed variables #9670
const childrenThenable = !!this.namedVariables ? this.fetchVariables(undefined, undefined, 'named') : Promise.resolve([]);
return childrenThenable.then(childrenArray => {
// Use a dynamic chunk size based on the number of elements #9774
let chunkSize = ExpressionContainer.BASE_CHUNK_SIZE;
while (this.indexedVariables > chunkSize * ExpressionContainer.BASE_CHUNK_SIZE) {
chunkSize *= ExpressionContainer.BASE_CHUNK_SIZE;
}
if (this.indexedVariables > chunkSize) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const numberOfChunks = Math.ceil(this.indexedVariables / chunkSize);
for (let i = 0; i < numberOfChunks; i++) {
const start = this.startOfVariables + i * chunkSize;
const count = Math.min(chunkSize, this.indexedVariables - i * chunkSize);
childrenArray.push(new Variable(this.session, this, this.reference, `[${start}..${start + count - 1}]`, '', '', null, count, { kind: 'virtual' }, null, true, start));
}
return childrenArray;
}
return this.fetchVariables(this.startOfVariables, this.indexedVariables, 'indexed')
.then(variables => childrenArray.concat(variables));
});
}
getId(): string {
return this.id;
}
get value(): string {
return this._value;
}
get hasChildren(): boolean {
// only variables with reference > 0 have children.
return this.reference > 0;
}
private fetchVariables(start: number, count: number, filter: 'indexed' | 'named'): Promise<Variable[]> {
return this.session.variables(this.reference, filter, start, count).then(response => {
return response && response.body && response.body.variables
? distinct(response.body.variables.filter(v => !!v && isString(v.name)), v => v.name).map(
v => new Variable(this.session, this, v.variablesReference, v.name, v.evaluateName, v.value, v.namedVariables, v.indexedVariables, v.presentationHint, v.type))
: [];
}, (e: Error) => [new Variable(this.session, this, 0, e.message, e.message, '', 0, 0, { kind: 'virtual' }, null, false)]);
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.indexedVariables;
}
set value(value: string) {
this._value = value;
this.valueChanged = ExpressionContainer.allValues.get(this.getId()) &&
ExpressionContainer.allValues.get(this.getId()) !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues.get(this.getId()) !== value;
ExpressionContainer.allValues.set(this.getId(), value);
}
toString(): string {
return this.value;
}
}
export class Expression extends ExpressionContainer implements IExpression {
static DEFAULT_VALUE = nls.localize('notAvailable', "not available");
public available: boolean;
public type: string;
constructor(public name: string, id = generateUuid()) {
super(null, 0, id);
this.available = false;
// name is not set if the expression is just being added
// in that case do not set default value to prevent flashing #14499
if (name) {
this.value = Expression.DEFAULT_VALUE;
}
}
evaluate(session: IDebugSession, stackFrame: IStackFrame, context: string): Promise<void> {
if (!session || (!stackFrame && context !== 'repl')) {
this.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate expressions") : Expression.DEFAULT_VALUE;
this.available = false;
this.reference = 0;
return Promise.resolve(void 0);
}
this.session = session;
return session.evaluate(this.name, stackFrame ? stackFrame.frameId : undefined, context).then(response => {
this.available = !!(response && response.body);
if (response && response.body) {
this.value = response.body.result;
this.reference = response.body.variablesReference;
this.namedVariables = response.body.namedVariables;
this.indexedVariables = response.body.indexedVariables;
this.type = response.body.type;
}
}, err => {
this.value = err.message;
this.available = false;
this.reference = 0;
});
}
toString(): string {
return `${this.name}\n${this.value}`;
}
}
export class Variable extends ExpressionContainer implements IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
session: IDebugSession,
public parent: IExpressionContainer,
reference: number,
public name: string,
public evaluateName: string,
value: string,
namedVariables: number,
indexedVariables: number,
public presentationHint: DebugProtocol.VariablePresentationHint,
public type: string | null = null,
public available = true,
startOfVariables = 0
) {
super(session, reference, `variable:${parent.getId()}:${name}`, namedVariables, indexedVariables, startOfVariables);
this.value = value;
}
setVariable(value: string): Promise<any> {
return this.session.setVariable((<ExpressionContainer>this.parent).reference, this.name, value).then(response => {
if (response && response.body) {
this.value = response.body.value;
this.type = response.body.type || this.type;
this.reference = response.body.variablesReference;
this.namedVariables = response.body.namedVariables;
this.indexedVariables = response.body.indexedVariables;
}
}, err => {
this.errorMessage = err.message;
});
}
toString(): string {
return `${this.name}: ${this.value}`;
}
}
export class Scope extends ExpressionContainer implements IScope {
constructor(
stackFrame: IStackFrame,
index: number,
public name: string,
reference: number,
public expensive: boolean,
namedVariables: number,
indexedVariables: number,
public range?: IRange
) {
super(stackFrame.thread.session, reference, `scope:${stackFrame.getId()}:${name}:${index}`, namedVariables, indexedVariables);
}
toString(): string {
return this.name;
}
}
export class StackFrame implements IStackFrame {
private scopes: Promise<Scope[]>;
constructor(
public thread: IThread,
public frameId: number,
public source: Source,
public name: string,
public presentationHint: string,
public range: IRange,
private index: number
) {
this.scopes = null;
}
getId(): string {
return `stackframe:${this.thread.getId()}:${this.frameId}:${this.index}`;
}
getScopes(): Promise<IScope[]> {
if (!this.scopes) {
this.scopes = this.thread.session.scopes(this.frameId).then(response => {
return response && response.body && response.body.scopes ?
response.body.scopes.map((rs, index) => new Scope(this, index, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables,
rs.line && rs.column && rs.endLine && rs.endColumn ? new Range(rs.line, rs.column, rs.endLine, rs.endColumn) : null)) : [];
}, err => []);
}
return this.scopes;
}
getSpecificSourceName(): 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>this.thread).getStaleCallStack();
callStack = callStack.length > 0 ? callStack : this.thread.getCallStack();
const otherSources = callStack.map(sf => sf.source).filter(s => s !== this.source);
let suffixLength = 0;
otherSources.forEach(s => {
if (s.name === this.source.name) {
suffixLength = Math.max(suffixLength, commonSuffixLength(this.source.uri.path, s.uri.path));
}
});
if (suffixLength === 0) {
return this.source.name;
}
const from = Math.max(0, this.source.uri.path.lastIndexOf(sep, this.source.uri.path.length - suffixLength - 1));
return (from > 0 ? '...' : '') + this.source.uri.path.substr(from);
}
getMostSpecificScopes(range: IRange): Promise<IScope[]> {
return this.getScopes().then(scopes => {
scopes = scopes.filter(s => !s.expensive);
const haveRangeInfo = scopes.some(s => !!s.range);
if (!haveRangeInfo) {
return scopes;
}
const scopesContainingRange = scopes.filter(scope => scope.range && Range.containsRange(scope.range, range))
.sort((first, second) => (first.range.endLineNumber - first.range.startLineNumber) - (second.range.endLineNumber - second.range.startLineNumber));
return scopesContainingRange.length ? scopesContainingRange : scopes;
});
}
restart(): Promise<void> {
return this.thread.session.restartFrame(this.frameId, this.thread.threadId);
}
toString(): string {
return `${this.name} (${this.source.inMemory ? this.source.name : this.source.uri.fsPath}:${this.range.startLineNumber})`;
}
openInEditor(editorService: IEditorService, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): Promise<any> {
return !this.source.available ? Promise.resolve(null) :
this.source.openInEditor(editorService, this.range, preserveFocus, sideBySide, pinned);
}
}
export class Thread implements IThread {
private callStack: IStackFrame[];
private staleCallStack: IStackFrame[];
public stoppedDetails: IRawStoppedDetails;
public stopped: boolean;
constructor(public session: IDebugSession, public name: string, public threadId: number) {
this.stoppedDetails = null;
this.callStack = [];
this.staleCallStack = [];
this.stopped = false;
}
getId(): string {
return `thread:${this.session.getId()}:${this.threadId}`;
}
clearCallStack(): void {
if (this.callStack.length) {
this.staleCallStack = this.callStack;
}
this.callStack = [];
}
getCallStack(): IStackFrame[] {
return this.callStack;
}
getStaleCallStack(): ReadonlyArray<IStackFrame> {
return this.staleCallStack;
}
/**
* Queries the debug adapter for the callstack and returns a promise
* which completes once the call stack has been retrieved.
* If the thread is not stopped, it returns a promise to an empty array.
* Only fetches the first stack frame for performance reasons. Calling this method consecutive times
* gets the remainder of the call stack.
*/
fetchCallStack(levels = 20): Promise<void> {
if (!this.stopped) {
return Promise.resolve(void 0);
}
const start = this.callStack.length;
return this.getCallStackImpl(start, levels).then(callStack => {
if (start < this.callStack.length) {
// Set the stack frames for exact position we requested. To make sure no concurrent requests create duplicate stack frames #30660
this.callStack.splice(start, this.callStack.length - start);
}
this.callStack = this.callStack.concat(callStack || []);
});
}
private getCallStackImpl(startFrame: number, levels: number): Promise<IStackFrame[]> {
return this.session.stackTrace(this.threadId, startFrame, levels).then(response => {
if (!response || !response.body) {
return [];
}
if (this.stoppedDetails) {
this.stoppedDetails.totalFrames = response.body.totalFrames;
}
return response.body.stackFrames.map((rsf, index) => {
const source = this.session.getSource(rsf.source);
return new StackFrame(this, rsf.id, source, rsf.name, rsf.presentationHint, new Range(
rsf.line,
rsf.column,
rsf.endLine,
rsf.endColumn
), startFrame + index);
});
}, (err: Error) => {
if (this.stoppedDetails) {
this.stoppedDetails.framesErrorMessage = err.message;
}
return [];
});
}
/**
* Returns exception info promise if the exception was thrown, otherwise null
*/
get exceptionInfo(): Promise<IExceptionInfo | null> {
if (this.stoppedDetails && this.stoppedDetails.reason === 'exception') {
if (this.session.capabilities.supportsExceptionInfoRequest) {
return this.session.exceptionInfo(this.threadId);
}
return Promise.resolve({
description: this.stoppedDetails.text,
breakMode: null
});
}
return Promise.resolve(null);
}
next(): Promise<any> {
return this.session.next(this.threadId);
}
stepIn(): Promise<any> {
return this.session.stepIn(this.threadId);
}
stepOut(): Promise<any> {
return this.session.stepOut(this.threadId);
}
stepBack(): Promise<any> {
return this.session.stepBack(this.threadId);
}
continue(): Promise<any> {
return this.session.continue(this.threadId);
}
pause(): Promise<any> {
return this.session.pause(this.threadId);
}
terminate(): Promise<any> {
return this.session.terminateThreads([this.threadId]);
}
reverseContinue(): Promise<any> {
return this.session.reverseContinue(this.threadId);
}
}
export class Enablement implements IEnablement {
constructor(
public enabled: boolean,
private id: string
) { }
getId(): string {
return this.id;
}
}
export class BaseBreakpoint extends Enablement implements IBaseBreakpoint {
private sessionData = new Map<string, DebugProtocol.Breakpoint>();
private sessionId: string;
constructor(
enabled: boolean,
public hitCondition: string,
public condition: string,
public logMessage: string,
id: string
) {
super(enabled, id);
if (enabled === undefined) {
this.enabled = true;
}
}
protected getSessionData() {
return this.sessionData.get(this.sessionId);
}
setSessionData(sessionId: string, data: DebugProtocol.Breakpoint): void {
this.sessionData.set(sessionId, data);
}
setSessionId(sessionId: string): void {
this.sessionId = sessionId;
}
get verified(): boolean {
const data = this.getSessionData();
return data ? data.verified : true;
}
get idFromAdapter(): number {
const data = this.getSessionData();
return data ? data.id : undefined;
}
toJSON(): any {
const result = Object.create(null);
result.enabled = this.enabled;
result.condition = this.condition;
result.hitCondition = this.hitCondition;
result.logMessage = this.logMessage;
return result;
}
}
export class Breakpoint extends BaseBreakpoint implements IBreakpoint {
constructor(
public uri: uri,
private _lineNumber: number,
private _column: number,
enabled: boolean,
condition: string,
hitCondition: string,
logMessage: string,
private _adapterData: any,
private textFileService: ITextFileService,
id = generateUuid()
) {
super(enabled, hitCondition, condition, logMessage, id);
}
get lineNumber(): number {
const data = this.getSessionData();
return this.verified && data && typeof data.line === 'number' ? data.line : this._lineNumber;
}
get verified(): boolean {
const data = this.getSessionData();
if (data) {
return data.verified && !this.textFileService.isDirty(this.uri);
}
return true;
}
get column(): number {
const data = this.getSessionData();
// Only respect the column if the user explictly set the column to have an inline breakpoint
return data && typeof data.column === 'number' && typeof this._column === 'number' ? data.column : this._column;
}
get message(): string {
const data = this.getSessionData();
if (!data) {
return undefined;
}
if (this.textFileService.isDirty(this.uri)) {
return nls.localize('breakpointDirtydHover', "Unverified breakpoint. File is modified, please restart debug session.");
}
return data.message;
}
get adapterData(): any {
const data = this.getSessionData();
return data && data.source && data.source.adapterData ? data.source.adapterData : this._adapterData;
}
get endLineNumber(): number {
const data = this.getSessionData();
return data ? data.endLine : undefined;
}
get endColumn(): number {
const data = this.getSessionData();
return data ? data.endColumn : undefined;
}
toJSON(): any {
const result = super.toJSON();
result.uri = this.uri;
result.lineNumber = this._lineNumber;
result.column = this._column;
result.adapterData = this.adapterData;
return result;
}
toString(): string {
return resources.basenameOrAuthority(this.uri);
}
update(data: IBreakpointUpdateData): void {
if (!isUndefinedOrNull(data.lineNumber)) {
this._lineNumber = data.lineNumber;
}
if (!isUndefinedOrNull(data.column)) {
this._column = data.column;
}
if (!isUndefinedOrNull(data.condition)) {
this.condition = data.condition;
}
if (!isUndefinedOrNull(data.hitCondition)) {
this.hitCondition = data.hitCondition;
}
if (!isUndefinedOrNull(data.logMessage)) {
this.logMessage = data.logMessage;
}
}
}
export class FunctionBreakpoint extends BaseBreakpoint implements IFunctionBreakpoint {
constructor(
public name: string,
enabled: boolean,
hitCondition: string,
condition: string,
logMessage: string,
id = generateUuid()
) {
super(enabled, hitCondition, condition, logMessage, id);
}
toJSON(): any {
const result = super.toJSON();
result.name = this.name;
return result;
}
toString(): string {
return this.name;
}
}
export class ExceptionBreakpoint extends Enablement implements IExceptionBreakpoint {
constructor(public filter: string, public label: string, enabled: boolean) {
super(enabled, generateUuid());
}
toJSON(): any {
const result = Object.create(null);
result.filter = this.filter;
result.label = this.label;
result.enabled = this.enabled;
return result;
}
toString(): string {
return this.label;
}
}
export class ThreadAndSessionIds implements ITreeElement {
constructor(public sessionId: string, public threadId: number) { }
getId(): string {
return `${this.sessionId}:${this.threadId}`;
}
}
export class DebugModel implements IDebugModel {
private sessions: IDebugSession[];
private toDispose: lifecycle.IDisposable[];
private schedulers = new Map<string, RunOnceScheduler>();
private breakpointsSessionId: string;
private readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent>;
private readonly _onDidChangeCallStack: Emitter<void>;
private readonly _onDidChangeWatchExpressions: Emitter<IExpression>;
constructor(
private breakpoints: Breakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: FunctionBreakpoint[],
private exceptionBreakpoints: ExceptionBreakpoint[],
private watchExpressions: Expression[],
private textFileService: ITextFileService
) {
this.sessions = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<IBreakpointsChangeEvent>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<IExpression>();
}
getId(): string {
return 'root';
}
getSessions(includeInactive = false): IDebugSession[] {
// By default do not return inactive sesions.
// However we are still holding onto inactive sessions due to repl and debug service session revival (eh scenario)
return this.sessions.filter(s => includeInactive || s.state !== State.Inactive);
}
addSession(session: IDebugSession): void {
this.sessions = this.sessions.filter(s => {
if (s.getId() === session.getId()) {
// Make sure to de-dupe if a session is re-intialized. In case of EH debugging we are adding a session again after an attach.
return false;
}
if (s.state === State.Inactive && s.getLabel() === session.getLabel()) {
// Make sure to remove all inactive sessions that are using the same configuration as the new session
return false;
}
return true;
});
this.sessions.push(session);
this._onDidChangeCallStack.fire();
}
get onDidChangeBreakpoints(): Event<IBreakpointsChangeEvent> {
return this._onDidChangeBreakpoints.event;
}
get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
get onDidChangeWatchExpressions(): Event<IExpression> {
return this._onDidChangeWatchExpressions.event;
}
rawUpdate(data: IRawModelUpdate): void {
let session = this.sessions.filter(p => p.getId() === data.sessionId).pop();
if (session) {
session.rawUpdate(data);
this._onDidChangeCallStack.fire();
}
}
clearThreads(id: string, removeThreads: boolean, reference: number | undefined = undefined): void {
const session = this.sessions.filter(p => p.getId() === id).pop();
this.schedulers.forEach(scheduler => scheduler.dispose());
this.schedulers.clear();
if (session) {
session.clearThreads(removeThreads, reference);
this._onDidChangeCallStack.fire();
}
}
fetchCallStack(thread: Thread): Promise<void> {
if (thread.session.capabilities.supportsDelayedStackTraceLoading) {
// For improved performance load the first stack frame and then load the rest async.
return thread.fetchCallStack(1).then(() => {
if (!this.schedulers.has(thread.getId())) {
this.schedulers.set(thread.getId(), new RunOnceScheduler(() => {
thread.fetchCallStack(19).then(() => this._onDidChangeCallStack.fire());
}, 420));
}
this.schedulers.get(thread.getId()).schedule();
this._onDidChangeCallStack.fire();
});
}
return thread.fetchCallStack();
}
getBreakpoints(filter?: { uri?: uri, lineNumber?: number, column?: number, enabledOnly?: boolean }): IBreakpoint[] {
if (filter) {
const uriStr = filter.uri ? filter.uri.toString() : undefined;
return this.breakpoints.filter(bp => {
if (uriStr && bp.uri.toString() !== uriStr) {
return false;
}
if (filter.lineNumber && bp.lineNumber !== filter.lineNumber) {
return false;
}
if (filter.column && bp.column !== filter.column) {
return false;
}
if (filter.enabledOnly && (!this.breakpointsActivated || !bp.enabled)) {
return false;
}
return true;
});
}
return this.breakpoints;
}
getFunctionBreakpoints(): IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
getExceptionBreakpoints(): IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
if (this.exceptionBreakpoints.length === data.length && this.exceptionBreakpoints.every((exbp, i) => exbp.filter === data[i].filter && exbp.label === data[i].label)) {
// No change
return;
}
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
this._onDidChangeBreakpoints.fire();
}
}
areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
addBreakpoints(uri: uri, rawData: IBreakpointData[], fireEvent = true): IBreakpoint[] {
const newBreakpoints = rawData.map(rawBp => new Breakpoint(uri, rawBp.lineNumber, rawBp.column, rawBp.enabled, rawBp.condition, rawBp.hitCondition, rawBp.logMessage, undefined, this.textFileService, rawBp.id));
newBreakpoints.forEach(bp => bp.setSessionId(this.breakpointsSessionId));
this.breakpoints = this.breakpoints.concat(newBreakpoints);
this.breakpointsActivated = true;
this.sortAndDeDup();
if (fireEvent) {
this._onDidChangeBreakpoints.fire({ added: newBreakpoints });
}
return newBreakpoints;
}
removeBreakpoints(toRemove: IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire({ removed: toRemove });
}
updateBreakpoints(data: { [id: string]: IBreakpointUpdateData }): void {
const updated: IBreakpoint[] = [];
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.update(bpData);
updated.push(bp);
}
});
this.sortAndDeDup();
this._onDidChangeBreakpoints.fire({ changed: updated });
}
setBreakpointSessionData(sessionId: string, data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.setSessionData(sessionId, bpData);
}
});
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.setSessionData(sessionId, fbpData);
}
});
this._onDidChangeBreakpoints.fire({
sessionOnly: true
});
}
setBreakpointsSessionId(sessionId: string): void {
this.breakpointsSessionId = sessionId;
this.breakpoints.forEach(bp => bp.setSessionId(sessionId));
this.functionBreakpoints.forEach(fbp => fbp.setSessionId(sessionId));
this._onDidChangeBreakpoints.fire({
sessionOnly: true
});
}
private sortAndDeDup(): void {
this.breakpoints = this.breakpoints.sort((first, second) => {
if (first.uri.toString() !== second.uri.toString()) {
return resources.basenameOrAuthority(first.uri).localeCompare(resources.basenameOrAuthority(second.uri));
}
if (first.lineNumber === second.lineNumber) {
return first.column - second.column;
}
return first.lineNumber - second.lineNumber;
});
this.breakpoints = distinct(this.breakpoints, bp => `${bp.uri.toString()}:${bp.lineNumber}:${bp.column}`);
}
setEnablement(element: IEnablement, enable: boolean): void {
if (element instanceof Breakpoint || element instanceof FunctionBreakpoint || element instanceof ExceptionBreakpoint) {
const changed: Array<IBreakpoint | IFunctionBreakpoint> = [];
if (element.enabled !== enable && (element instanceof Breakpoint || element instanceof FunctionBreakpoint)) {
changed.push(element);
}
element.enabled = enable;
this._onDidChangeBreakpoints.fire({ changed: changed });
}
}
enableOrDisableAllBreakpoints(enable: boolean): void {
const changed: Array<IBreakpoint | IFunctionBreakpoint> = [];
this.breakpoints.forEach(bp => {
if (bp.enabled !== enable) {
changed.push(bp);
}
bp.enabled = enable;
});
this.functionBreakpoints.forEach(fbp => {
if (fbp.enabled !== enable) {
changed.push(fbp);
}
fbp.enabled = enable;
});
this._onDidChangeBreakpoints.fire({ changed: changed });
}
addFunctionBreakpoint(functionName: string, id: string): IFunctionBreakpoint {
const newFunctionBreakpoint = new FunctionBreakpoint(functionName, true, undefined, undefined, undefined, id);
this.functionBreakpoints.push(newFunctionBreakpoint);
this._onDidChangeBreakpoints.fire({ added: [newFunctionBreakpoint] });
return newFunctionBreakpoint;
}
renameFunctionBreakpoint(id: string, name: string): void {
const functionBreakpoint = this.functionBreakpoints.filter(fbp => fbp.getId() === id).pop();
if (functionBreakpoint) {
functionBreakpoint.name = name;
this._onDidChangeBreakpoints.fire({ changed: [functionBreakpoint] });
}
}
removeFunctionBreakpoints(id?: string): void {
let removed: IFunctionBreakpoint[];
if (id) {
removed = this.functionBreakpoints.filter(fbp => fbp.getId() === id);
this.functionBreakpoints = this.functionBreakpoints.filter(fbp => fbp.getId() !== id);
} else {
removed = this.functionBreakpoints;
this.functionBreakpoints = [];
}
this._onDidChangeBreakpoints.fire({ removed: removed });
}
getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
addWatchExpression(name: string): IExpression {
const we = new Expression(name);
this.watchExpressions.push(we);
this._onDidChangeWatchExpressions.fire(we);
return we;
}
renameWatchExpression(id: string, newName: string): void {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
this._onDidChangeWatchExpressions.fire(filtered[0]);
}
}
removeWatchExpressions(id: string | null = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
moveWatchExpression(id: string, position: number): void {
const we = this.watchExpressions.filter(we => we.getId() === id).pop();
this.watchExpressions = this.watchExpressions.filter(we => we.getId() !== id);
this.watchExpressions = this.watchExpressions.slice(0, position).concat(we, this.watchExpressions.slice(position));
this._onDidChangeWatchExpressions.fire();
}
sourceIsNotAvailable(uri: uri): void {
this.sessions.forEach(s => {
const source = s.getSourceForUri(uri);
if (source) {
source.available = false;
}
});
this._onDidChangeCallStack.fire();
}
dispose(): void {
// Make sure to shutdown each session, such that no debugged process is left laying around
this.sessions.forEach(s => s.shutdown());
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.9984022974967957,
0.22109903395175934,
0.00016017119924072176,
0.00019360420992597938,
0.4122641682624817
] |
{
"id": 1,
"code_window": [
"\tprivate sessions: IDebugSession[];\n",
"\tprivate toDispose: lifecycle.IDisposable[];\n",
"\tprivate schedulers = new Map<string, RunOnceScheduler>();\n",
"\tprivate breakpointsSessionId: string;\n",
"\tprivate readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent>;\n",
"\tprivate readonly _onDidChangeCallStack: Emitter<void>;\n",
"\tprivate readonly _onDidChangeWatchExpressions: Emitter<IExpression>;\n",
"\n",
"\tconstructor(\n",
"\t\tprivate breakpoints: Breakpoint[],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate readonly _onDidChangeCallStack: Emitter<IThread | undefined>;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 739
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as modes from 'vs/editor/common/modes';
import * as types from './extHostTypes';
import * as search from 'vs/workbench/parts/search/common/search';
import { ITextEditorOptions } from 'vs/platform/editor/common/editor';
import { EditorViewColumn } from 'vs/workbench/api/shared/editor';
import { IDecorationOptions, IThemeDecorationRenderOptions, IDecorationRenderOptions, IContentDecorationRenderOptions } from 'vs/editor/common/editorCommon';
import { EndOfLineSequence, TrackedRangeStickiness } from 'vs/editor/common/model';
import * as vscode from 'vscode';
import { URI, UriComponents } from 'vs/base/common/uri';
import { ProgressLocation as MainProgressLocation } from 'vs/platform/progress/common/progress';
import { SaveReason } from 'vs/workbench/services/textfile/common/textfiles';
import { IPosition } from 'vs/editor/common/core/position';
import { IRange } from 'vs/editor/common/core/range';
import { ISelection } from 'vs/editor/common/core/selection';
import * as htmlContent from 'vs/base/common/htmlContent';
import * as languageSelector from 'vs/editor/common/modes/languageSelector';
import { WorkspaceEditDto, ResourceTextEditDto, ResourceFileEditDto } from 'vs/workbench/api/node/extHost.protocol';
import { MarkerSeverity, IRelatedInformation, IMarkerData, MarkerTag } from 'vs/platform/markers/common/markers';
import { ACTIVE_GROUP, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/node/extHostDocumentsAndEditors';
import { isString, isNumber } from 'vs/base/common/types';
import * as marked from 'vs/base/common/marked/marked';
import { parse } from 'vs/base/common/marshalling';
import { cloneAndChange } from 'vs/base/common/objects';
import { LogLevel as _MainLogLevel } from 'vs/platform/log/common/log';
export interface PositionLike {
line: number;
character: number;
}
export interface RangeLike {
start: PositionLike;
end: PositionLike;
}
export interface SelectionLike extends RangeLike {
anchor: PositionLike;
active: PositionLike;
}
export namespace Selection {
export function to(selection: ISelection): types.Selection {
const { selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn } = selection;
const start = new types.Position(selectionStartLineNumber - 1, selectionStartColumn - 1);
const end = new types.Position(positionLineNumber - 1, positionColumn - 1);
return new types.Selection(start, end);
}
export function from(selection: SelectionLike): ISelection {
const { anchor, active } = selection;
return {
selectionStartLineNumber: anchor.line + 1,
selectionStartColumn: anchor.character + 1,
positionLineNumber: active.line + 1,
positionColumn: active.character + 1
};
}
}
export namespace Range {
export function from(range: RangeLike): IRange {
if (!range) {
return undefined;
}
const { start, end } = range;
return {
startLineNumber: start.line + 1,
startColumn: start.character + 1,
endLineNumber: end.line + 1,
endColumn: end.character + 1
};
}
export function to(range: IRange): types.Range {
if (!range) {
return undefined;
}
const { startLineNumber, startColumn, endLineNumber, endColumn } = range;
return new types.Range(startLineNumber - 1, startColumn - 1, endLineNumber - 1, endColumn - 1);
}
}
export namespace Position {
export function to(position: IPosition): types.Position {
return new types.Position(position.lineNumber - 1, position.column - 1);
}
export function from(position: types.Position): IPosition {
return { lineNumber: position.line + 1, column: position.character + 1 };
}
}
export namespace DiagnosticTag {
export function from(value: vscode.DiagnosticTag): MarkerTag {
switch (value) {
case types.DiagnosticTag.Unnecessary:
return MarkerTag.Unnecessary;
}
return undefined;
}
}
export namespace Diagnostic {
export function from(value: vscode.Diagnostic): IMarkerData {
return {
...Range.from(value.range),
message: value.message,
source: value.source,
code: isString(value.code) || isNumber(value.code) ? String(value.code) : void 0,
severity: DiagnosticSeverity.from(value.severity),
relatedInformation: value.relatedInformation && value.relatedInformation.map(DiagnosticRelatedInformation.from),
tags: Array.isArray(value.tags) ? value.tags.map(DiagnosticTag.from) : undefined,
};
}
}
export namespace DiagnosticRelatedInformation {
export function from(value: types.DiagnosticRelatedInformation): IRelatedInformation {
return {
...Range.from(value.location.range),
message: value.message,
resource: value.location.uri
};
}
export function to(value: IRelatedInformation): types.DiagnosticRelatedInformation {
return new types.DiagnosticRelatedInformation(new types.Location(value.resource, Range.to(value)), value.message);
}
}
export namespace DiagnosticSeverity {
export function from(value: number): MarkerSeverity {
switch (value) {
case types.DiagnosticSeverity.Error:
return MarkerSeverity.Error;
case types.DiagnosticSeverity.Warning:
return MarkerSeverity.Warning;
case types.DiagnosticSeverity.Information:
return MarkerSeverity.Info;
case types.DiagnosticSeverity.Hint:
return MarkerSeverity.Hint;
}
return MarkerSeverity.Error;
}
export function to(value: MarkerSeverity): types.DiagnosticSeverity {
switch (value) {
case MarkerSeverity.Info:
return types.DiagnosticSeverity.Information;
case MarkerSeverity.Warning:
return types.DiagnosticSeverity.Warning;
case MarkerSeverity.Error:
return types.DiagnosticSeverity.Error;
case MarkerSeverity.Hint:
return types.DiagnosticSeverity.Hint;
}
return types.DiagnosticSeverity.Error;
}
}
export namespace ViewColumn {
export function from(column?: vscode.ViewColumn): EditorViewColumn {
if (typeof column === 'number' && column >= types.ViewColumn.One) {
return column - 1; // adjust zero index (ViewColumn.ONE => 0)
}
if (column === types.ViewColumn.Beside) {
return SIDE_GROUP;
}
return ACTIVE_GROUP; // default is always the active group
}
export function to(position?: EditorViewColumn): vscode.ViewColumn {
if (typeof position === 'number' && position >= 0) {
return position + 1; // adjust to index (ViewColumn.ONE => 1)
}
return undefined;
}
}
function isDecorationOptions(something: any): something is vscode.DecorationOptions {
return (typeof something.range !== 'undefined');
}
export function isDecorationOptionsArr(something: vscode.Range[] | vscode.DecorationOptions[]): something is vscode.DecorationOptions[] {
if (something.length === 0) {
return true;
}
return isDecorationOptions(something[0]) ? true : false;
}
export namespace MarkdownString {
export function fromMany(markup: (vscode.MarkdownString | vscode.MarkedString)[]): htmlContent.IMarkdownString[] {
return markup.map(MarkdownString.from);
}
interface Codeblock {
language: string;
value: string;
}
function isCodeblock(thing: any): thing is Codeblock {
return thing && typeof thing === 'object'
&& typeof (<Codeblock>thing).language === 'string'
&& typeof (<Codeblock>thing).value === 'string';
}
export function from(markup: vscode.MarkdownString | vscode.MarkedString): htmlContent.IMarkdownString {
let res: htmlContent.IMarkdownString;
if (isCodeblock(markup)) {
const { language, value } = markup;
res = { value: '```' + language + '\n' + value + '\n```\n' };
} else if (htmlContent.isMarkdownString(markup)) {
res = markup;
} else if (typeof markup === 'string') {
res = { value: <string>markup };
} else {
res = { value: '' };
}
// extract uris into a separate object
res.uris = Object.create(null);
let renderer = new marked.Renderer();
renderer.image = renderer.link = (href: string): string => {
try {
let uri = URI.parse(href, true);
uri = uri.with({ query: _uriMassage(uri.query, res.uris) });
res.uris[href] = uri;
} catch (e) {
// ignore
}
return '';
};
marked(res.value, { renderer });
return res;
}
function _uriMassage(part: string, bucket: { [n: string]: UriComponents }): string {
if (!part) {
return part;
}
let data: any;
try {
data = parse(decodeURIComponent(part));
} catch (e) {
// ignore
}
if (!data) {
return part;
}
data = cloneAndChange(data, value => {
if (value instanceof URI) {
let key = `__uri_${Math.random().toString(16).slice(2, 8)}`;
bucket[key] = value;
return key;
} else {
return undefined;
}
});
return encodeURIComponent(JSON.stringify(data));
}
export function to(value: htmlContent.IMarkdownString): vscode.MarkdownString {
const ret = new htmlContent.MarkdownString(value.value);
ret.isTrusted = value.isTrusted;
return ret;
}
export function fromStrict(value: string | types.MarkdownString): undefined | string | htmlContent.IMarkdownString {
if (!value) {
return undefined;
}
return typeof value === 'string' ? value : MarkdownString.from(value);
}
}
export function fromRangeOrRangeWithMessage(ranges: vscode.Range[] | vscode.DecorationOptions[]): IDecorationOptions[] {
if (isDecorationOptionsArr(ranges)) {
return ranges.map(r => {
return {
range: Range.from(r.range),
hoverMessage: Array.isArray(r.hoverMessage) ? MarkdownString.fromMany(r.hoverMessage) : r.hoverMessage && MarkdownString.from(r.hoverMessage),
renderOptions: <any> /* URI vs Uri */r.renderOptions
};
});
} else {
return ranges.map((r): IDecorationOptions => {
return {
range: Range.from(r)
};
});
}
}
function pathOrURIToURI(value: string | URI): URI {
if (typeof value === 'undefined') {
return value;
}
if (typeof value === 'string') {
return URI.file(value);
} else {
return value;
}
}
export namespace ThemableDecorationAttachmentRenderOptions {
export function from(options: vscode.ThemableDecorationAttachmentRenderOptions): IContentDecorationRenderOptions {
if (typeof options === 'undefined') {
return options;
}
return {
contentText: options.contentText,
contentIconPath: pathOrURIToURI(options.contentIconPath),
border: options.border,
borderColor: <string | types.ThemeColor>options.borderColor,
fontStyle: options.fontStyle,
fontWeight: options.fontWeight,
textDecoration: options.textDecoration,
color: <string | types.ThemeColor>options.color,
backgroundColor: <string | types.ThemeColor>options.backgroundColor,
margin: options.margin,
width: options.width,
height: options.height,
};
}
}
export namespace ThemableDecorationRenderOptions {
export function from(options: vscode.ThemableDecorationRenderOptions): IThemeDecorationRenderOptions {
if (typeof options === 'undefined') {
return options;
}
return {
backgroundColor: <string | types.ThemeColor>options.backgroundColor,
outline: options.outline,
outlineColor: <string | types.ThemeColor>options.outlineColor,
outlineStyle: options.outlineStyle,
outlineWidth: options.outlineWidth,
border: options.border,
borderColor: <string | types.ThemeColor>options.borderColor,
borderRadius: options.borderRadius,
borderSpacing: options.borderSpacing,
borderStyle: options.borderStyle,
borderWidth: options.borderWidth,
fontStyle: options.fontStyle,
fontWeight: options.fontWeight,
textDecoration: options.textDecoration,
cursor: options.cursor,
color: <string | types.ThemeColor>options.color,
opacity: options.opacity,
letterSpacing: options.letterSpacing,
gutterIconPath: pathOrURIToURI(options.gutterIconPath),
gutterIconSize: options.gutterIconSize,
overviewRulerColor: <string | types.ThemeColor>options.overviewRulerColor,
before: ThemableDecorationAttachmentRenderOptions.from(options.before),
after: ThemableDecorationAttachmentRenderOptions.from(options.after),
};
}
}
export namespace DecorationRangeBehavior {
export function from(value: types.DecorationRangeBehavior): TrackedRangeStickiness {
if (typeof value === 'undefined') {
return value;
}
switch (value) {
case types.DecorationRangeBehavior.OpenOpen:
return TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges;
case types.DecorationRangeBehavior.ClosedClosed:
return TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges;
case types.DecorationRangeBehavior.OpenClosed:
return TrackedRangeStickiness.GrowsOnlyWhenTypingBefore;
case types.DecorationRangeBehavior.ClosedOpen:
return TrackedRangeStickiness.GrowsOnlyWhenTypingAfter;
}
}
}
export namespace DecorationRenderOptions {
export function from(options: vscode.DecorationRenderOptions): IDecorationRenderOptions {
return {
isWholeLine: options.isWholeLine,
rangeBehavior: DecorationRangeBehavior.from(options.rangeBehavior),
overviewRulerLane: options.overviewRulerLane,
light: ThemableDecorationRenderOptions.from(options.light),
dark: ThemableDecorationRenderOptions.from(options.dark),
backgroundColor: <string | types.ThemeColor>options.backgroundColor,
outline: options.outline,
outlineColor: <string | types.ThemeColor>options.outlineColor,
outlineStyle: options.outlineStyle,
outlineWidth: options.outlineWidth,
border: options.border,
borderColor: <string | types.ThemeColor>options.borderColor,
borderRadius: options.borderRadius,
borderSpacing: options.borderSpacing,
borderStyle: options.borderStyle,
borderWidth: options.borderWidth,
fontStyle: options.fontStyle,
fontWeight: options.fontWeight,
textDecoration: options.textDecoration,
cursor: options.cursor,
color: <string | types.ThemeColor>options.color,
opacity: options.opacity,
letterSpacing: options.letterSpacing,
gutterIconPath: pathOrURIToURI(options.gutterIconPath),
gutterIconSize: options.gutterIconSize,
overviewRulerColor: <string | types.ThemeColor>options.overviewRulerColor,
before: ThemableDecorationAttachmentRenderOptions.from(options.before),
after: ThemableDecorationAttachmentRenderOptions.from(options.after),
};
}
}
export namespace TextEdit {
export function from(edit: vscode.TextEdit): modes.TextEdit {
return <modes.TextEdit>{
text: edit.newText,
eol: EndOfLine.from(edit.newEol),
range: Range.from(edit.range)
};
}
export function to(edit: modes.TextEdit): types.TextEdit {
const result = new types.TextEdit(Range.to(edit.range), edit.text);
result.newEol = EndOfLine.to(edit.eol);
return result;
}
}
export namespace WorkspaceEdit {
export function from(value: vscode.WorkspaceEdit, documents?: ExtHostDocumentsAndEditors): WorkspaceEditDto {
const result: WorkspaceEditDto = {
edits: []
};
for (const entry of (value as types.WorkspaceEdit)._allEntries()) {
const [uri, uriOrEdits] = entry;
if (Array.isArray(uriOrEdits)) {
// text edits
const doc = documents ? documents.getDocument(uri.toString()) : undefined;
result.edits.push(<ResourceTextEditDto>{ resource: uri, modelVersionId: doc && doc.version, edits: uriOrEdits.map(TextEdit.from) });
} else {
// resource edits
result.edits.push(<ResourceFileEditDto>{ oldUri: uri, newUri: uriOrEdits, options: entry[2] });
}
}
return result;
}
export function to(value: WorkspaceEditDto) {
const result = new types.WorkspaceEdit();
for (const edit of value.edits) {
if (Array.isArray((<ResourceTextEditDto>edit).edits)) {
result.set(
URI.revive((<ResourceTextEditDto>edit).resource),
<types.TextEdit[]>(<ResourceTextEditDto>edit).edits.map(TextEdit.to)
);
} else {
result.renameFile(
URI.revive((<ResourceFileEditDto>edit).oldUri),
URI.revive((<ResourceFileEditDto>edit).newUri),
(<ResourceFileEditDto>edit).options
);
}
}
return result;
}
}
export namespace SymbolKind {
const _fromMapping: { [kind: number]: modes.SymbolKind } = Object.create(null);
_fromMapping[types.SymbolKind.File] = modes.SymbolKind.File;
_fromMapping[types.SymbolKind.Module] = modes.SymbolKind.Module;
_fromMapping[types.SymbolKind.Namespace] = modes.SymbolKind.Namespace;
_fromMapping[types.SymbolKind.Package] = modes.SymbolKind.Package;
_fromMapping[types.SymbolKind.Class] = modes.SymbolKind.Class;
_fromMapping[types.SymbolKind.Method] = modes.SymbolKind.Method;
_fromMapping[types.SymbolKind.Property] = modes.SymbolKind.Property;
_fromMapping[types.SymbolKind.Field] = modes.SymbolKind.Field;
_fromMapping[types.SymbolKind.Constructor] = modes.SymbolKind.Constructor;
_fromMapping[types.SymbolKind.Enum] = modes.SymbolKind.Enum;
_fromMapping[types.SymbolKind.Interface] = modes.SymbolKind.Interface;
_fromMapping[types.SymbolKind.Function] = modes.SymbolKind.Function;
_fromMapping[types.SymbolKind.Variable] = modes.SymbolKind.Variable;
_fromMapping[types.SymbolKind.Constant] = modes.SymbolKind.Constant;
_fromMapping[types.SymbolKind.String] = modes.SymbolKind.String;
_fromMapping[types.SymbolKind.Number] = modes.SymbolKind.Number;
_fromMapping[types.SymbolKind.Boolean] = modes.SymbolKind.Boolean;
_fromMapping[types.SymbolKind.Array] = modes.SymbolKind.Array;
_fromMapping[types.SymbolKind.Object] = modes.SymbolKind.Object;
_fromMapping[types.SymbolKind.Key] = modes.SymbolKind.Key;
_fromMapping[types.SymbolKind.Null] = modes.SymbolKind.Null;
_fromMapping[types.SymbolKind.EnumMember] = modes.SymbolKind.EnumMember;
_fromMapping[types.SymbolKind.Struct] = modes.SymbolKind.Struct;
_fromMapping[types.SymbolKind.Event] = modes.SymbolKind.Event;
_fromMapping[types.SymbolKind.Operator] = modes.SymbolKind.Operator;
_fromMapping[types.SymbolKind.TypeParameter] = modes.SymbolKind.TypeParameter;
export function from(kind: vscode.SymbolKind): modes.SymbolKind {
return typeof _fromMapping[kind] === 'number' ? _fromMapping[kind] : modes.SymbolKind.Property;
}
export function to(kind: modes.SymbolKind): vscode.SymbolKind {
for (const k in _fromMapping) {
if (_fromMapping[k] === kind) {
return Number(k);
}
}
return types.SymbolKind.Property;
}
}
export namespace WorkspaceSymbol {
export function from(info: vscode.SymbolInformation): search.IWorkspaceSymbol {
return <search.IWorkspaceSymbol>{
name: info.name,
kind: SymbolKind.from(info.kind),
containerName: info.containerName,
location: location.from(info.location)
};
}
export function to(info: search.IWorkspaceSymbol): types.SymbolInformation {
return new types.SymbolInformation(
info.name,
SymbolKind.to(info.kind),
info.containerName,
location.to(info.location)
);
}
}
export namespace DocumentSymbol {
export function from(info: vscode.DocumentSymbol): modes.DocumentSymbol {
const result: modes.DocumentSymbol = {
name: info.name,
detail: info.detail,
range: Range.from(info.range),
selectionRange: Range.from(info.selectionRange),
kind: SymbolKind.from(info.kind)
};
if (info.children) {
result.children = info.children.map(from);
}
return result;
}
export function to(info: modes.DocumentSymbol): vscode.DocumentSymbol {
const result = new types.DocumentSymbol(
info.name,
info.detail,
SymbolKind.to(info.kind),
Range.to(info.range),
Range.to(info.selectionRange),
);
if (info.children) {
result.children = info.children.map(to) as any;
}
return result;
}
}
export namespace location {
export function from(value: vscode.Location): modes.Location {
return {
range: value.range && Range.from(value.range),
uri: value.uri
};
}
export function to(value: modes.Location): types.Location {
return new types.Location(value.uri, Range.to(value.range));
}
}
export namespace DefinitionLink {
export function from(value: vscode.Location | vscode.DefinitionLink): modes.DefinitionLink {
const definitionLink = <vscode.DefinitionLink>value;
const location = <vscode.Location>value;
return {
origin: definitionLink.originSelectionRange
? Range.from(definitionLink.originSelectionRange)
: undefined,
uri: definitionLink.targetUri ? definitionLink.targetUri : location.uri,
range: Range.from(definitionLink.targetRange ? definitionLink.targetRange : location.range),
selectionRange: definitionLink.targetSelectionRange
? Range.from(definitionLink.targetSelectionRange)
: undefined,
};
}
}
export namespace Hover {
export function from(hover: vscode.Hover): modes.Hover {
return <modes.Hover>{
range: Range.from(hover.range),
contents: MarkdownString.fromMany(hover.contents)
};
}
export function to(info: modes.Hover): types.Hover {
return new types.Hover(info.contents.map(MarkdownString.to), Range.to(info.range));
}
}
export namespace DocumentHighlight {
export function from(documentHighlight: vscode.DocumentHighlight): modes.DocumentHighlight {
return {
range: Range.from(documentHighlight.range),
kind: documentHighlight.kind
};
}
export function to(occurrence: modes.DocumentHighlight): types.DocumentHighlight {
return new types.DocumentHighlight(Range.to(occurrence.range), occurrence.kind);
}
}
export namespace CompletionTriggerKind {
export function to(kind: modes.CompletionTriggerKind) {
switch (kind) {
case modes.CompletionTriggerKind.TriggerCharacter:
return types.CompletionTriggerKind.TriggerCharacter;
case modes.CompletionTriggerKind.TriggerForIncompleteCompletions:
return types.CompletionTriggerKind.TriggerForIncompleteCompletions;
case modes.CompletionTriggerKind.Invoke:
default:
return types.CompletionTriggerKind.Invoke;
}
}
}
export namespace CompletionContext {
export function to(context: modes.CompletionContext): types.CompletionContext {
return {
triggerKind: CompletionTriggerKind.to(context.triggerKind),
triggerCharacter: context.triggerCharacter
};
}
}
export namespace CompletionItemKind {
export function from(kind: types.CompletionItemKind): modes.CompletionItemKind {
switch (kind) {
case types.CompletionItemKind.Method: return modes.CompletionItemKind.Method;
case types.CompletionItemKind.Function: return modes.CompletionItemKind.Function;
case types.CompletionItemKind.Constructor: return modes.CompletionItemKind.Constructor;
case types.CompletionItemKind.Field: return modes.CompletionItemKind.Field;
case types.CompletionItemKind.Variable: return modes.CompletionItemKind.Variable;
case types.CompletionItemKind.Class: return modes.CompletionItemKind.Class;
case types.CompletionItemKind.Interface: return modes.CompletionItemKind.Interface;
case types.CompletionItemKind.Struct: return modes.CompletionItemKind.Struct;
case types.CompletionItemKind.Module: return modes.CompletionItemKind.Module;
case types.CompletionItemKind.Property: return modes.CompletionItemKind.Property;
case types.CompletionItemKind.Unit: return modes.CompletionItemKind.Unit;
case types.CompletionItemKind.Value: return modes.CompletionItemKind.Value;
case types.CompletionItemKind.Constant: return modes.CompletionItemKind.Constant;
case types.CompletionItemKind.Enum: return modes.CompletionItemKind.Enum;
case types.CompletionItemKind.EnumMember: return modes.CompletionItemKind.EnumMember;
case types.CompletionItemKind.Keyword: return modes.CompletionItemKind.Keyword;
case types.CompletionItemKind.Snippet: return modes.CompletionItemKind.Snippet;
case types.CompletionItemKind.Text: return modes.CompletionItemKind.Text;
case types.CompletionItemKind.Color: return modes.CompletionItemKind.Color;
case types.CompletionItemKind.File: return modes.CompletionItemKind.File;
case types.CompletionItemKind.Reference: return modes.CompletionItemKind.Reference;
case types.CompletionItemKind.Folder: return modes.CompletionItemKind.Folder;
case types.CompletionItemKind.Event: return modes.CompletionItemKind.Event;
case types.CompletionItemKind.Operator: return modes.CompletionItemKind.Operator;
case types.CompletionItemKind.TypeParameter: return modes.CompletionItemKind.TypeParameter;
}
return modes.CompletionItemKind.Property;
}
export function to(kind: modes.CompletionItemKind): types.CompletionItemKind {
switch (kind) {
case modes.CompletionItemKind.Method: return types.CompletionItemKind.Method;
case modes.CompletionItemKind.Function: return types.CompletionItemKind.Function;
case modes.CompletionItemKind.Constructor: return types.CompletionItemKind.Constructor;
case modes.CompletionItemKind.Field: return types.CompletionItemKind.Field;
case modes.CompletionItemKind.Variable: return types.CompletionItemKind.Variable;
case modes.CompletionItemKind.Class: return types.CompletionItemKind.Class;
case modes.CompletionItemKind.Interface: return types.CompletionItemKind.Interface;
case modes.CompletionItemKind.Struct: return types.CompletionItemKind.Struct;
case modes.CompletionItemKind.Module: return types.CompletionItemKind.Module;
case modes.CompletionItemKind.Property: return types.CompletionItemKind.Property;
case modes.CompletionItemKind.Unit: return types.CompletionItemKind.Unit;
case modes.CompletionItemKind.Value: return types.CompletionItemKind.Value;
case modes.CompletionItemKind.Constant: return types.CompletionItemKind.Constant;
case modes.CompletionItemKind.Enum: return types.CompletionItemKind.Enum;
case modes.CompletionItemKind.EnumMember: return types.CompletionItemKind.EnumMember;
case modes.CompletionItemKind.Keyword: return types.CompletionItemKind.Keyword;
case modes.CompletionItemKind.Snippet: return types.CompletionItemKind.Snippet;
case modes.CompletionItemKind.Text: return types.CompletionItemKind.Text;
case modes.CompletionItemKind.Color: return types.CompletionItemKind.Color;
case modes.CompletionItemKind.File: return types.CompletionItemKind.File;
case modes.CompletionItemKind.Reference: return types.CompletionItemKind.Reference;
case modes.CompletionItemKind.Folder: return types.CompletionItemKind.Folder;
case modes.CompletionItemKind.Event: return types.CompletionItemKind.Event;
case modes.CompletionItemKind.Operator: return types.CompletionItemKind.Operator;
case modes.CompletionItemKind.TypeParameter: return types.CompletionItemKind.TypeParameter;
}
return types.CompletionItemKind.Property;
}
}
export namespace CompletionItem {
export function to(suggestion: modes.CompletionItem): types.CompletionItem {
const result = new types.CompletionItem(suggestion.label);
result.insertText = suggestion.insertText;
result.kind = CompletionItemKind.to(suggestion.kind);
result.detail = suggestion.detail;
result.documentation = htmlContent.isMarkdownString(suggestion.documentation) ? MarkdownString.to(suggestion.documentation) : suggestion.documentation;
result.sortText = suggestion.sortText;
result.filterText = suggestion.filterText;
result.preselect = suggestion.preselect;
result.commitCharacters = suggestion.commitCharacters;
result.range = Range.to(suggestion.range);
result.keepWhitespace = Boolean(suggestion.insertTextRules & modes.CompletionItemInsertTextRule.KeepWhitespace);
// 'inserText'-logic
if (suggestion.insertTextRules & modes.CompletionItemInsertTextRule.InsertAsSnippet) {
result.insertText = new types.SnippetString(suggestion.insertText);
} else {
result.insertText = suggestion.insertText;
result.textEdit = new types.TextEdit(result.range, result.insertText);
}
// TODO additionalEdits, command
return result;
}
}
export namespace ParameterInformation {
export function from(info: types.ParameterInformation): modes.ParameterInformation {
return {
label: info.label,
documentation: MarkdownString.fromStrict(info.documentation)
};
}
export function to(info: modes.ParameterInformation): types.ParameterInformation {
return {
label: info.label,
documentation: htmlContent.isMarkdownString(info.documentation) ? MarkdownString.to(info.documentation) : info.documentation
};
}
}
export namespace SignatureInformation {
export function from(info: types.SignatureInformation): modes.SignatureInformation {
return {
label: info.label,
documentation: MarkdownString.fromStrict(info.documentation),
parameters: info.parameters && info.parameters.map(ParameterInformation.from)
};
}
export function to(info: modes.SignatureInformation): types.SignatureInformation {
return {
label: info.label,
documentation: htmlContent.isMarkdownString(info.documentation) ? MarkdownString.to(info.documentation) : info.documentation,
parameters: info.parameters && info.parameters.map(ParameterInformation.to)
};
}
}
export namespace SignatureHelp {
export function from(help: types.SignatureHelp): modes.SignatureHelp {
return {
activeSignature: help.activeSignature,
activeParameter: help.activeParameter,
signatures: help.signatures && help.signatures.map(SignatureInformation.from)
};
}
export function to(help: modes.SignatureHelp): types.SignatureHelp {
return {
activeSignature: help.activeSignature,
activeParameter: help.activeParameter,
signatures: help.signatures && help.signatures.map(SignatureInformation.to)
};
}
}
export namespace DocumentLink {
export function from(link: vscode.DocumentLink): modes.ILink {
return {
range: Range.from(link.range),
url: link.target && link.target.toString()
};
}
export function to(link: modes.ILink): vscode.DocumentLink {
return new types.DocumentLink(Range.to(link.range), link.url && URI.parse(link.url));
}
}
export namespace ColorPresentation {
export function to(colorPresentation: modes.IColorPresentation): types.ColorPresentation {
const cp = new types.ColorPresentation(colorPresentation.label);
if (colorPresentation.textEdit) {
cp.textEdit = TextEdit.to(colorPresentation.textEdit);
}
if (colorPresentation.additionalTextEdits) {
cp.additionalTextEdits = colorPresentation.additionalTextEdits.map(value => TextEdit.to(value));
}
return cp;
}
export function from(colorPresentation: vscode.ColorPresentation): modes.IColorPresentation {
return {
label: colorPresentation.label,
textEdit: colorPresentation.textEdit ? TextEdit.from(colorPresentation.textEdit) : undefined,
additionalTextEdits: colorPresentation.additionalTextEdits ? colorPresentation.additionalTextEdits.map(value => TextEdit.from(value)) : undefined
};
}
}
export namespace Color {
export function to(c: [number, number, number, number]): types.Color {
return new types.Color(c[0], c[1], c[2], c[3]);
}
export function from(color: types.Color): [number, number, number, number] {
return [color.red, color.green, color.blue, color.alpha];
}
}
export namespace SelectionRangeKind {
export function from(kind: vscode.SelectionRangeKind): string {
return kind.value;
}
export function to(value: string): vscode.SelectionRangeKind {
return new types.SelectionRangeKind(value);
}
}
export namespace SelectionRange {
export function from(obj: vscode.SelectionRange): modes.SelectionRange {
return {
kind: SelectionRangeKind.from(obj.kind),
range: Range.from(obj.range)
};
}
export function to(obj: modes.SelectionRange): vscode.SelectionRange {
return new types.SelectionRange(Range.to(obj.range), SelectionRangeKind.to(obj.kind));
}
}
export namespace TextDocumentSaveReason {
export function to(reason: SaveReason): vscode.TextDocumentSaveReason {
switch (reason) {
case SaveReason.AUTO:
return types.TextDocumentSaveReason.AfterDelay;
case SaveReason.EXPLICIT:
return types.TextDocumentSaveReason.Manual;
case SaveReason.FOCUS_CHANGE:
case SaveReason.WINDOW_CHANGE:
return types.TextDocumentSaveReason.FocusOut;
}
}
}
export namespace EndOfLine {
export function from(eol: vscode.EndOfLine): EndOfLineSequence {
if (eol === types.EndOfLine.CRLF) {
return EndOfLineSequence.CRLF;
} else if (eol === types.EndOfLine.LF) {
return EndOfLineSequence.LF;
}
return undefined;
}
export function to(eol: EndOfLineSequence): vscode.EndOfLine {
if (eol === EndOfLineSequence.CRLF) {
return types.EndOfLine.CRLF;
} else if (eol === EndOfLineSequence.LF) {
return types.EndOfLine.LF;
}
return undefined;
}
}
export namespace ProgressLocation {
export function from(loc: vscode.ProgressLocation): MainProgressLocation {
switch (loc) {
case types.ProgressLocation.SourceControl: return MainProgressLocation.Scm;
case types.ProgressLocation.Window: return MainProgressLocation.Window;
case types.ProgressLocation.Notification: return MainProgressLocation.Notification;
}
return undefined;
}
}
export namespace FoldingRange {
export function from(r: vscode.FoldingRange): modes.FoldingRange {
const range: modes.FoldingRange = { start: r.start + 1, end: r.end + 1 };
if (r.kind) {
range.kind = FoldingRangeKind.from(r.kind);
}
return range;
}
}
export namespace FoldingRangeKind {
export function from(kind: vscode.FoldingRangeKind | undefined): modes.FoldingRangeKind | undefined {
if (kind) {
switch (kind) {
case types.FoldingRangeKind.Comment:
return modes.FoldingRangeKind.Comment;
case types.FoldingRangeKind.Imports:
return modes.FoldingRangeKind.Imports;
case types.FoldingRangeKind.Region:
return modes.FoldingRangeKind.Region;
}
}
return void 0;
}
}
export namespace TextEditorOptions {
export function from(options?: vscode.TextDocumentShowOptions): ITextEditorOptions {
if (options) {
return {
pinned: typeof options.preview === 'boolean' ? !options.preview : undefined,
preserveFocus: options.preserveFocus,
selection: typeof options.selection === 'object' ? Range.from(options.selection) : undefined
} as ITextEditorOptions;
}
return undefined;
}
}
export namespace GlobPattern {
export function from(pattern: vscode.GlobPattern): string | types.RelativePattern {
if (pattern instanceof types.RelativePattern) {
return pattern;
}
if (typeof pattern === 'string') {
return pattern;
}
if (isRelativePattern(pattern)) {
return new types.RelativePattern(pattern.base, pattern.pattern);
}
return pattern; // preserve `undefined` and `null`
}
function isRelativePattern(obj: any): obj is vscode.RelativePattern {
const rp = obj as vscode.RelativePattern;
return rp && typeof rp.base === 'string' && typeof rp.pattern === 'string';
}
}
export namespace LanguageSelector {
export function from(selector: vscode.DocumentSelector): languageSelector.LanguageSelector {
if (!selector) {
return undefined;
} else if (Array.isArray(selector)) {
return <languageSelector.LanguageSelector>selector.map(from);
} else if (typeof selector === 'string') {
return selector;
} else {
return <languageSelector.LanguageFilter>{
language: selector.language,
scheme: selector.scheme,
pattern: GlobPattern.from(selector.pattern),
exclusive: selector.exclusive
};
}
}
}
export namespace LogLevel {
export function from(extLevel: types.LogLevel): _MainLogLevel {
switch (extLevel) {
case types.LogLevel.Trace:
return _MainLogLevel.Trace;
case types.LogLevel.Debug:
return _MainLogLevel.Debug;
case types.LogLevel.Info:
return _MainLogLevel.Info;
case types.LogLevel.Warning:
return _MainLogLevel.Warning;
case types.LogLevel.Error:
return _MainLogLevel.Error;
case types.LogLevel.Critical:
return _MainLogLevel.Critical;
case types.LogLevel.Critical:
return _MainLogLevel.Critical;
case types.LogLevel.Off:
return _MainLogLevel.Off;
}
return _MainLogLevel.Info;
}
export function to(mainLevel: _MainLogLevel): types.LogLevel {
switch (mainLevel) {
case _MainLogLevel.Trace:
return types.LogLevel.Trace;
case _MainLogLevel.Debug:
return types.LogLevel.Debug;
case _MainLogLevel.Info:
return types.LogLevel.Info;
case _MainLogLevel.Warning:
return types.LogLevel.Warning;
case _MainLogLevel.Error:
return types.LogLevel.Error;
case _MainLogLevel.Critical:
return types.LogLevel.Critical;
case _MainLogLevel.Critical:
return types.LogLevel.Critical;
case _MainLogLevel.Off:
return types.LogLevel.Off;
}
return types.LogLevel.Info;
}
}
| src/vs/workbench/api/node/extHostTypeConverters.ts | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.00017887524154502898,
0.00017409193969797343,
0.0001645256852498278,
0.0001743728353176266,
0.000002645009999469039
] |
{
"id": 1,
"code_window": [
"\tprivate sessions: IDebugSession[];\n",
"\tprivate toDispose: lifecycle.IDisposable[];\n",
"\tprivate schedulers = new Map<string, RunOnceScheduler>();\n",
"\tprivate breakpointsSessionId: string;\n",
"\tprivate readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent>;\n",
"\tprivate readonly _onDidChangeCallStack: Emitter<void>;\n",
"\tprivate readonly _onDidChangeWatchExpressions: Emitter<IExpression>;\n",
"\n",
"\tconstructor(\n",
"\t\tprivate breakpoints: Breakpoint[],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate readonly _onDidChangeCallStack: Emitter<IThread | undefined>;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 739
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><defs><style>.icon-canvas-transparent,.icon-vs-out{fill:#252526;}.icon-canvas-transparent{opacity:0;}.icon-vs-bg{fill:#c5c5c5;}</style></defs><title>breakpoints-activate</title><g id="canvas"><path class="icon-canvas-transparent" d="M16,0V16H0V0Z"/></g><g id="outline" style="display: none;"><path class="icon-vs-out" d="M16,5.5A5.536,5.536,0,0,1,11,11a5.536,5.536,0,0,1-5.5,5A5.549,5.549,0,0,1,0,10.5,5.465,5.465,0,0,1,5,5a5.512,5.512,0,0,1,11,.5Z"/></g><g id="iconBg"><path class="icon-vs-bg" d="M15,5.5A4.395,4.395,0,0,1,11,10a2.957,2.957,0,0,0-.2-1A3.565,3.565,0,0,0,14,5.5a3.507,3.507,0,0,0-7-.3A3.552,3.552,0,0,0,6,5a4.622,4.622,0,0,1,4.5-4A4.481,4.481,0,0,1,15,5.5ZM5.5,6A4.5,4.5,0,1,0,10,10.5,4.5,4.5,0,0,0,5.5,6Z"/></g></svg>
| src/vs/workbench/parts/debug/browser/media/breakpoints-activate-inverse.svg | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.00016699876869097352,
0.00016699876869097352,
0.00016699876869097352,
0.00016699876869097352,
0
] |
{
"id": 1,
"code_window": [
"\tprivate sessions: IDebugSession[];\n",
"\tprivate toDispose: lifecycle.IDisposable[];\n",
"\tprivate schedulers = new Map<string, RunOnceScheduler>();\n",
"\tprivate breakpointsSessionId: string;\n",
"\tprivate readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent>;\n",
"\tprivate readonly _onDidChangeCallStack: Emitter<void>;\n",
"\tprivate readonly _onDidChangeWatchExpressions: Emitter<IExpression>;\n",
"\n",
"\tconstructor(\n",
"\t\tprivate breakpoints: Breakpoint[],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate readonly _onDidChangeCallStack: Emitter<IThread | undefined>;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 739
} | /*---------------------------------------------------------------------------------------------
* 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/panelpart';
import * as nls from 'vs/nls';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
import { Action } from 'vs/base/common/actions';
import { Registry } from 'vs/platform/registry/common/platform';
import { SyncActionDescriptor, MenuId, MenuRegistry } from 'vs/platform/actions/common/actions';
import { IWorkbenchActionRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/actions';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IPartService, Parts, Position } from 'vs/workbench/services/part/common/partService';
import { ActivityAction } from 'vs/workbench/browser/parts/compositeBarActions';
import { IActivity } from 'vs/workbench/common/activity';
export class ClosePanelAction extends Action {
static readonly ID = 'workbench.action.closePanel';
static LABEL = nls.localize('closePanel', "Close Panel");
constructor(
id: string,
name: string,
@IPartService private partService: IPartService
) {
super(id, name, 'hide-panel-action');
}
run(): Promise<any> {
this.partService.setPanelHidden(true);
return Promise.resolve(null);
}
}
export class TogglePanelAction extends Action {
static readonly ID = 'workbench.action.togglePanel';
static LABEL = nls.localize('togglePanel', "Toggle Panel");
constructor(
id: string,
name: string,
@IPartService private partService: IPartService
) {
super(id, name, partService.isVisible(Parts.PANEL_PART) ? 'panel expanded' : 'panel');
}
run(): Promise<any> {
this.partService.setPanelHidden(this.partService.isVisible(Parts.PANEL_PART));
return Promise.resolve(null);
}
}
class FocusPanelAction extends Action {
static readonly ID = 'workbench.action.focusPanel';
static readonly LABEL = nls.localize('focusPanel', "Focus into Panel");
constructor(
id: string,
label: string,
@IPanelService private panelService: IPanelService,
@IPartService private partService: IPartService
) {
super(id, label);
}
run(): Promise<any> {
// Show panel
if (!this.partService.isVisible(Parts.PANEL_PART)) {
this.partService.setPanelHidden(false);
return Promise.resolve(null);
}
// Focus into active panel
let panel = this.panelService.getActivePanel();
if (panel) {
panel.focus();
}
return Promise.resolve(null);
}
}
export class TogglePanelPositionAction extends Action {
static readonly ID = 'workbench.action.togglePanelPosition';
static readonly LABEL = nls.localize('toggledPanelPosition', "Toggle Panel Position");
private static readonly MOVE_TO_RIGHT_LABEL = nls.localize('moveToRight', "Move Panel Right");
private static readonly MOVE_TO_BOTTOM_LABEL = nls.localize('moveToBottom', "Move Panel to Bottom");
private toDispose: IDisposable[];
constructor(
id: string,
label: string,
@IPartService private partService: IPartService,
) {
super(id, label, partService.getPanelPosition() === Position.RIGHT ? 'move-panel-to-bottom' : 'move-panel-to-right');
this.toDispose = [];
const setClassAndLabel = () => {
const positionRight = this.partService.getPanelPosition() === Position.RIGHT;
this.class = positionRight ? 'move-panel-to-bottom' : 'move-panel-to-right';
this.label = positionRight ? TogglePanelPositionAction.MOVE_TO_BOTTOM_LABEL : TogglePanelPositionAction.MOVE_TO_RIGHT_LABEL;
};
this.toDispose.push(partService.onEditorLayout(() => setClassAndLabel()));
setClassAndLabel();
}
run(): Promise<any> {
const position = this.partService.getPanelPosition();
this.partService.setPanelPosition(position === Position.BOTTOM ? Position.RIGHT : Position.BOTTOM);
return Promise.resolve(null);
}
dispose(): void {
super.dispose();
this.toDispose = dispose(this.toDispose);
}
}
export class ToggleMaximizedPanelAction extends Action {
static readonly ID = 'workbench.action.toggleMaximizedPanel';
static readonly LABEL = nls.localize('toggleMaximizedPanel', "Toggle Maximized Panel");
private static readonly MAXIMIZE_LABEL = nls.localize('maximizePanel', "Maximize Panel Size");
private static readonly RESTORE_LABEL = nls.localize('minimizePanel', "Restore Panel Size");
private toDispose: IDisposable[];
constructor(
id: string,
label: string,
@IPartService private partService: IPartService
) {
super(id, label, partService.isPanelMaximized() ? 'minimize-panel-action' : 'maximize-panel-action');
this.toDispose = [];
this.toDispose.push(partService.onEditorLayout(() => {
const maximized = this.partService.isPanelMaximized();
this.class = maximized ? 'minimize-panel-action' : 'maximize-panel-action';
this.label = maximized ? ToggleMaximizedPanelAction.RESTORE_LABEL : ToggleMaximizedPanelAction.MAXIMIZE_LABEL;
}));
}
run(): Promise<any> {
if (!this.partService.isVisible(Parts.PANEL_PART)) {
this.partService.setPanelHidden(false);
}
this.partService.toggleMaximizedPanel();
return Promise.resolve(null);
}
dispose(): void {
super.dispose();
this.toDispose = dispose(this.toDispose);
}
}
export class PanelActivityAction extends ActivityAction {
constructor(
activity: IActivity,
@IPanelService private panelService: IPanelService
) {
super(activity);
}
run(event: any): Promise<any> {
this.panelService.openPanel(this.activity.id, true);
this.activate();
return Promise.resolve(null);
}
}
export class SwitchPanelViewAction extends Action {
constructor(
id: string,
name: string,
@IPanelService private panelService: IPanelService
) {
super(id, name);
}
run(offset: number): Promise<any> {
const pinnedPanels = this.panelService.getPinnedPanels();
const activePanel = this.panelService.getActivePanel();
if (!activePanel) {
return Promise.resolve(null);
}
let targetPanelId: string;
for (let i = 0; i < pinnedPanels.length; i++) {
if (pinnedPanels[i].id === activePanel.getId()) {
targetPanelId = pinnedPanels[(i + pinnedPanels.length + offset) % pinnedPanels.length].id;
break;
}
}
this.panelService.openPanel(targetPanelId, true);
return Promise.resolve(null);
}
}
export class PreviousPanelViewAction extends SwitchPanelViewAction {
static readonly ID = 'workbench.action.previousPanelView';
static LABEL = nls.localize('previousPanelView', 'Previous Panel View');
constructor(
id: string,
name: string,
@IPanelService panelService: IPanelService
) {
super(id, name, panelService);
}
run(): Promise<any> {
return super.run(-1);
}
}
export class NextPanelViewAction extends SwitchPanelViewAction {
static readonly ID = 'workbench.action.nextPanelView';
static LABEL = nls.localize('nextPanelView', 'Next Panel View');
constructor(
id: string,
name: string,
@IPanelService panelService: IPanelService
) {
super(id, name, panelService);
}
public run(): Promise<any> {
return super.run(1);
}
}
const actionRegistry = Registry.as<IWorkbenchActionRegistry>(WorkbenchExtensions.WorkbenchActions);
actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(TogglePanelAction, TogglePanelAction.ID, TogglePanelAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.KEY_J }), 'View: Toggle Panel', nls.localize('view', "View"));
actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(FocusPanelAction, FocusPanelAction.ID, FocusPanelAction.LABEL), 'View: Focus into Panel', nls.localize('view', "View"));
actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(ToggleMaximizedPanelAction, ToggleMaximizedPanelAction.ID, ToggleMaximizedPanelAction.LABEL), 'View: Toggle Maximized Panel', nls.localize('view', "View"));
actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(ClosePanelAction, ClosePanelAction.ID, ClosePanelAction.LABEL), 'View: Close Panel', nls.localize('view', "View"));
actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(TogglePanelPositionAction, TogglePanelPositionAction.ID, TogglePanelPositionAction.LABEL), 'View: Toggle Panel Position', nls.localize('view', "View"));
actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(ToggleMaximizedPanelAction, ToggleMaximizedPanelAction.ID, undefined), 'View: Toggle Panel Position', nls.localize('view', "View"));
actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(PreviousPanelViewAction, PreviousPanelViewAction.ID, PreviousPanelViewAction.LABEL), 'View: Open Previous Panel View', nls.localize('view', "View"));
actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(NextPanelViewAction, NextPanelViewAction.ID, NextPanelViewAction.LABEL), 'View: Open Next Panel View', nls.localize('view', "View"));
MenuRegistry.appendMenuItem(MenuId.MenubarAppearanceMenu, {
group: '2_workbench_layout',
command: {
id: TogglePanelAction.ID,
title: nls.localize({ key: 'miTogglePanel', comment: ['&& denotes a mnemonic'] }, "Toggle &&Panel")
},
order: 5
});
MenuRegistry.appendMenuItem(MenuId.MenubarAppearanceMenu, {
group: '2_workbench_layout',
command: {
id: TogglePanelPositionAction.ID,
title: TogglePanelPositionAction.LABEL
},
order: 3
});
| src/vs/workbench/browser/parts/panel/panelActions.ts | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.0009407914476469159,
0.0002495433436706662,
0.0001627651072340086,
0.00017104181461036205,
0.00020400724315550178
] |
{
"id": 2,
"code_window": [
"\t\tprivate textFileService: ITextFileService\n",
"\t) {\n",
"\t\tthis.sessions = [];\n",
"\t\tthis.toDispose = [];\n",
"\t\tthis._onDidChangeBreakpoints = new Emitter<IBreakpointsChangeEvent>();\n",
"\t\tthis._onDidChangeCallStack = new Emitter<void>();\n",
"\t\tthis._onDidChangeWatchExpressions = new Emitter<IExpression>();\n",
"\t}\n",
"\n",
"\tgetId(): string {\n",
"\t\treturn 'root';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._onDidChangeCallStack = new Emitter<IThread | undefined>();\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 753
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI as uri } from 'vs/base/common/uri';
import severity from 'vs/base/common/severity';
import { Event } from 'vs/base/common/event';
import { IJSONSchemaSnippet } from 'vs/base/common/jsonSchema';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { ITextModel as EditorIModel } from 'vs/editor/common/model';
import { IEditor } from 'vs/workbench/common/editor';
import { Position } from 'vs/editor/common/core/position';
import { CompletionItem } from 'vs/editor/common/modes';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { Range, IRange } from 'vs/editor/common/core/range';
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IDisposable } from 'vs/base/common/lifecycle';
import { IViewContainersRegistry, ViewContainer, Extensions as ViewContainerExtensions } from 'vs/workbench/common/views';
import { Registry } from 'vs/platform/registry/common/platform';
import { TaskIdentifier } from 'vs/workbench/parts/tasks/common/tasks';
import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService';
import { IOutputService } from 'vs/workbench/parts/output/common/output';
export const VIEWLET_ID = 'workbench.view.debug';
export const VIEW_CONTAINER: ViewContainer = Registry.as<IViewContainersRegistry>(ViewContainerExtensions.ViewContainersRegistry).registerViewContainer(VIEWLET_ID);
export const VARIABLES_VIEW_ID = 'workbench.debug.variablesView';
export const WATCH_VIEW_ID = 'workbench.debug.watchExpressionsView';
export const CALLSTACK_VIEW_ID = 'workbench.debug.callStackView';
export const LOADED_SCRIPTS_VIEW_ID = 'workbench.debug.loadedScriptsView';
export const BREAKPOINTS_VIEW_ID = 'workbench.debug.breakPointsView';
export const REPL_ID = 'workbench.panel.repl';
export const DEBUG_SERVICE_ID = 'debugService';
export const CONTEXT_DEBUG_TYPE = new RawContextKey<string>('debugType', undefined);
export const CONTEXT_DEBUG_CONFIGURATION_TYPE = new RawContextKey<string>('debugConfigurationType', undefined);
export const CONTEXT_DEBUG_STATE = new RawContextKey<string>('debugState', 'inactive');
export const CONTEXT_IN_DEBUG_MODE = new RawContextKey<boolean>('inDebugMode', false);
export const CONTEXT_IN_DEBUG_REPL = new RawContextKey<boolean>('inDebugRepl', false);
export const CONTEXT_BREAKPOINT_WIDGET_VISIBLE = new RawContextKey<boolean>('breakpointWidgetVisible', false);
export const CONTEXT_IN_BREAKPOINT_WIDGET = new RawContextKey<boolean>('inBreakpointWidget', false);
export const CONTEXT_BREAKPOINTS_FOCUSED = new RawContextKey<boolean>('breakpointsFocused', true);
export const CONTEXT_WATCH_EXPRESSIONS_FOCUSED = new RawContextKey<boolean>('watchExpressionsFocused', true);
export const CONTEXT_VARIABLES_FOCUSED = new RawContextKey<boolean>('variablesFocused', true);
export const CONTEXT_EXPRESSION_SELECTED = new RawContextKey<boolean>('expressionSelected', false);
export const CONTEXT_BREAKPOINT_SELECTED = new RawContextKey<boolean>('breakpointSelected', false);
export const CONTEXT_CALLSTACK_ITEM_TYPE = new RawContextKey<string>('callStackItemType', undefined);
export const CONTEXT_LOADED_SCRIPTS_SUPPORTED = new RawContextKey<boolean>('loadedScriptsSupported', false);
export const CONTEXT_LOADED_SCRIPTS_ITEM_TYPE = new RawContextKey<string>('loadedScriptsItemType', undefined);
export const EDITOR_CONTRIBUTION_ID = 'editor.contrib.debug';
export const DEBUG_SCHEME = 'debug';
export const INTERNAL_CONSOLE_OPTIONS_SCHEMA = {
enum: ['neverOpen', 'openOnSessionStart', 'openOnFirstSessionStart'],
default: 'openOnFirstSessionStart',
description: nls.localize('internalConsoleOptions', "Controls when the internal debug console should open.")
};
// raw
export interface IRawModelUpdate {
threadId: number;
sessionId: string;
thread?: DebugProtocol.Thread;
callStack?: DebugProtocol.StackFrame[];
stoppedDetails?: IRawStoppedDetails;
}
export interface IRawStoppedDetails {
reason: string;
description?: string;
threadId?: number;
text?: string;
totalFrames?: number;
allThreadsStopped?: boolean;
framesErrorMessage?: string;
}
// model
export interface ITreeElement {
getId(): string;
}
export interface IReplElement extends ITreeElement {
toString(): string;
readonly sourceData?: IReplElementSource;
}
export interface IReplElementSource {
readonly source: Source;
readonly lineNumber: number;
readonly column: number;
}
export interface IExpressionContainer extends ITreeElement {
readonly hasChildren: boolean;
getChildren(): Promise<IExpression[]>;
}
export interface IExpression extends IReplElement, IExpressionContainer {
name: string;
readonly value: string;
readonly valueChanged?: boolean;
readonly type?: string;
}
export interface IDebugger {
createDebugAdapter(session: IDebugSession, outputService: IOutputService): Promise<IDebugAdapter>;
runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments): Promise<number | undefined>;
getCustomTelemetryService(): Promise<TelemetryService>;
}
export const enum State {
Inactive,
Initializing,
Stopped,
Running
}
export function getStateLabel(state: State): string {
switch (state) {
case State.Initializing: return 'initializing';
case State.Stopped: return 'stopped';
case State.Running: return 'running';
default: return 'inactive';
}
}
export class AdapterEndEvent {
error?: Error;
sessionLengthInSeconds: number;
emittedStopped: boolean;
}
export interface LoadedSourceEvent {
reason: 'new' | 'changed' | 'removed';
source: Source;
}
export interface IDebugSession extends ITreeElement {
readonly configuration: IConfig;
readonly unresolvedConfiguration: IConfig;
readonly state: State;
readonly root: IWorkspaceFolder;
getLabel(): string;
getSourceForUri(modelUri: uri): Source;
getSource(raw: DebugProtocol.Source): Source;
setConfiguration(configuration: { resolved: IConfig, unresolved: IConfig }): void;
rawUpdate(data: IRawModelUpdate): void;
getThread(threadId: number): IThread;
getAllThreads(): IThread[];
clearThreads(removeThreads: boolean, reference?: number): void;
getReplElements(): IReplElement[];
removeReplExpressions(): void;
addReplExpression(stackFrame: IStackFrame, name: string): Promise<void>;
appendToRepl(data: string | IExpression, severity: severity, source?: IReplElementSource): void;
logToRepl(sev: severity, args: any[], frame?: { uri: uri, line: number, column: number });
// session events
readonly onDidEndAdapter: Event<AdapterEndEvent>;
readonly onDidChangeState: Event<void>;
readonly onDidChangeReplElements: Event<void>;
// DA capabilities
readonly capabilities: DebugProtocol.Capabilities;
// DAP events
readonly onDidLoadedSource: Event<LoadedSourceEvent>;
readonly onDidCustomEvent: Event<DebugProtocol.Event>;
// Disconnects and clears state. Session can be initialized again for a new connection.
shutdown(): void;
// DAP request
initialize(dbgr: IDebugger): Promise<void>;
launchOrAttach(config: IConfig): Promise<void>;
restart(): Promise<void>;
terminate(restart?: boolean /* false */): Promise<void>;
disconnect(restart?: boolean /* false */): Promise<void>;
sendBreakpoints(modelUri: uri, bpts: IBreakpoint[], sourceModified: boolean): Promise<void>;
sendFunctionBreakpoints(fbps: IFunctionBreakpoint[]): Promise<void>;
sendExceptionBreakpoints(exbpts: IExceptionBreakpoint[]): Promise<void>;
stackTrace(threadId: number, startFrame: number, levels: number): Promise<DebugProtocol.StackTraceResponse>;
exceptionInfo(threadId: number): Promise<IExceptionInfo>;
scopes(frameId: number): Promise<DebugProtocol.ScopesResponse>;
variables(variablesReference: number, filter: 'indexed' | 'named', start: number, count: number): Promise<DebugProtocol.VariablesResponse>;
evaluate(expression: string, frameId?: number, context?: string): Promise<DebugProtocol.EvaluateResponse>;
customRequest(request: string, args: any): Promise<DebugProtocol.Response>;
restartFrame(frameId: number, threadId: number): Promise<void>;
next(threadId: number): Promise<void>;
stepIn(threadId: number): Promise<void>;
stepOut(threadId: number): Promise<void>;
stepBack(threadId: number): Promise<void>;
continue(threadId: number): Promise<void>;
reverseContinue(threadId: number): Promise<void>;
pause(threadId: number): Promise<void>;
terminateThreads(threadIds: number[]): Promise<void>;
completions(frameId: number, text: string, position: Position, overwriteBefore: number): Promise<CompletionItem[]>;
setVariable(variablesReference: number, name: string, value: string): Promise<DebugProtocol.SetVariableResponse>;
loadSource(resource: uri): Promise<DebugProtocol.SourceResponse>;
getLoadedSources(): Promise<Source[]>;
}
export interface IThread extends ITreeElement {
/**
* Process the thread belongs to
*/
readonly session: IDebugSession;
/**
* Id of the thread generated by the debug adapter backend.
*/
readonly threadId: number;
/**
* Name of the thread.
*/
readonly name: string;
/**
* Information about the current thread stop event. Null if thread is not stopped.
*/
readonly stoppedDetails: IRawStoppedDetails;
/**
* Information about the exception if an 'exception' stopped event raised and DA supports the 'exceptionInfo' request, otherwise null.
*/
readonly exceptionInfo: Promise<IExceptionInfo>;
/**
* Gets the callstack if it has already been received from the debug
* adapter, otherwise it returns null.
*/
getCallStack(): ReadonlyArray<IStackFrame>;
/**
* Invalidates the callstack cache
*/
clearCallStack(): void;
/**
* Indicates whether this thread is stopped. The callstack for stopped
* threads can be retrieved from the debug adapter.
*/
readonly stopped: boolean;
next(): Promise<any>;
stepIn(): Promise<any>;
stepOut(): Promise<any>;
stepBack(): Promise<any>;
continue(): Promise<any>;
pause(): Promise<any>;
terminate(): Promise<any>;
reverseContinue(): Promise<any>;
}
export interface IScope extends IExpressionContainer {
readonly name: string;
readonly expensive: boolean;
readonly range?: IRange;
}
export interface IStackFrame extends ITreeElement {
readonly thread: IThread;
readonly name: string;
readonly presentationHint: string;
readonly frameId: number;
readonly range: IRange;
readonly source: Source;
getScopes(): Promise<IScope[]>;
getMostSpecificScopes(range: IRange): Promise<ReadonlyArray<IScope>>;
getSpecificSourceName(): string;
restart(): Promise<any>;
toString(): string;
openInEditor(editorService: IEditorService, preserveFocus?: boolean, sideBySide?: boolean): Promise<any>;
}
export interface IEnablement extends ITreeElement {
readonly enabled: boolean;
}
export interface IBreakpointData {
readonly id?: string;
readonly lineNumber: number;
readonly column?: number;
readonly enabled?: boolean;
readonly condition?: string;
readonly logMessage?: string;
readonly hitCondition?: string;
}
export interface IBreakpointUpdateData {
readonly condition?: string;
readonly hitCondition?: string;
readonly logMessage?: string;
readonly lineNumber?: number;
readonly column?: number;
}
export interface IBaseBreakpoint extends IEnablement {
readonly condition: string;
readonly hitCondition: string;
readonly logMessage: string;
readonly verified: boolean;
readonly idFromAdapter: number;
}
export interface IBreakpoint extends IBaseBreakpoint {
readonly uri: uri;
readonly lineNumber: number;
readonly endLineNumber?: number;
readonly column: number;
readonly endColumn?: number;
readonly message: string;
readonly adapterData: any;
}
export interface IFunctionBreakpoint extends IBaseBreakpoint {
readonly name: string;
}
export interface IExceptionBreakpoint extends IEnablement {
readonly filter: string;
readonly label: string;
}
export interface IExceptionInfo {
readonly id?: string;
readonly description?: string;
readonly breakMode: string;
readonly details?: DebugProtocol.ExceptionDetails;
}
// model interfaces
export interface IViewModel extends ITreeElement {
/**
* Returns the focused debug session or null if no session is stopped.
*/
readonly focusedSession: IDebugSession;
/**
* Returns the focused thread or null if no thread is stopped.
*/
readonly focusedThread: IThread;
/**
* Returns the focused stack frame or null if there are no stack frames.
*/
readonly focusedStackFrame: IStackFrame;
getSelectedExpression(): IExpression;
getSelectedFunctionBreakpoint(): IFunctionBreakpoint;
setSelectedExpression(expression: IExpression): void;
setSelectedFunctionBreakpoint(functionBreakpoint: IFunctionBreakpoint): void;
isMultiSessionView(): boolean;
onDidFocusSession: Event<IDebugSession | undefined>;
onDidFocusStackFrame: Event<{ stackFrame: IStackFrame, explicit: boolean }>;
onDidSelectExpression: Event<IExpression>;
}
export interface IEvaluate {
evaluate(session: IDebugSession, stackFrame: IStackFrame, context: string): Promise<void>;
}
export interface IDebugModel extends ITreeElement {
getSessions(includeInactive?: boolean): IDebugSession[];
getBreakpoints(filter?: { uri?: uri, lineNumber?: number, column?: number, enabledOnly?: boolean }): ReadonlyArray<IBreakpoint>;
areBreakpointsActivated(): boolean;
getFunctionBreakpoints(): ReadonlyArray<IFunctionBreakpoint>;
getExceptionBreakpoints(): ReadonlyArray<IExceptionBreakpoint>;
getWatchExpressions(): ReadonlyArray<IExpression & IEvaluate>;
onDidChangeBreakpoints: Event<IBreakpointsChangeEvent>;
onDidChangeCallStack: Event<void>;
onDidChangeWatchExpressions: Event<IExpression>;
}
/**
* An event describing a change to the set of [breakpoints](#debug.Breakpoint).
*/
export interface IBreakpointsChangeEvent {
added?: Array<IBreakpoint | IFunctionBreakpoint>;
removed?: Array<IBreakpoint | IFunctionBreakpoint>;
changed?: Array<IBreakpoint | IFunctionBreakpoint>;
sessionOnly?: boolean;
}
// Debug configuration interfaces
export interface IDebugConfiguration {
allowBreakpointsEverywhere: boolean;
openDebug: 'neverOpen' | 'openOnSessionStart' | 'openOnFirstSessionStart' | 'openOnDebugBreak';
openExplorerOnEnd: boolean;
inlineValues: boolean;
toolBarLocation: 'floating' | 'docked' | 'hidden';
showInStatusBar: 'never' | 'always' | 'onFirstSessionStart';
internalConsoleOptions: 'neverOpen' | 'openOnSessionStart' | 'openOnFirstSessionStart';
extensionHostDebugAdapter: boolean;
enableAllHovers: boolean;
}
export interface IGlobalConfig {
version: string;
compounds: ICompound[];
configurations: IConfig[];
}
export interface IEnvConfig {
internalConsoleOptions?: 'neverOpen' | 'openOnSessionStart' | 'openOnFirstSessionStart';
preLaunchTask?: string | TaskIdentifier;
postDebugTask?: string | TaskIdentifier;
debugServer?: number;
noDebug?: boolean;
}
export interface IConfig extends IEnvConfig {
// fundamental attributes
type: string;
request: string;
name: string;
// platform specifics
windows?: IEnvConfig;
osx?: IEnvConfig;
linux?: IEnvConfig;
// internals
__sessionId?: string;
__restart?: any;
__autoAttach?: boolean;
port?: number; // TODO
}
export interface ICompound {
name: string;
configurations: (string | { name: string, folder: string })[];
}
export interface IDebugAdapter extends IDisposable {
readonly onError: Event<Error>;
readonly onExit: Event<number>;
onRequest(callback: (request: DebugProtocol.Request) => void);
onEvent(callback: (event: DebugProtocol.Event) => void);
startSession(): Promise<void>;
sendMessage(message: DebugProtocol.ProtocolMessage): void;
sendResponse(response: DebugProtocol.Response): void;
sendRequest(command: string, args: any, clb: (result: DebugProtocol.Response) => void, timemout?: number): void;
stopSession(): Promise<void>;
}
export interface IDebugAdapterFactory extends ITerminalLauncher {
createDebugAdapter(session: IDebugSession): IDebugAdapter;
substituteVariables(folder: IWorkspaceFolder, config: IConfig): Promise<IConfig>;
}
export interface IDebugAdapterExecutableOptions {
cwd?: string;
env?: { [key: string]: string };
}
export interface IDebugAdapterExecutable {
readonly type: 'executable';
readonly command: string;
readonly args: string[];
readonly options?: IDebugAdapterExecutableOptions;
}
export interface IDebugAdapterServer {
readonly type: 'server';
readonly port: number;
readonly host?: string;
}
export interface IDebugAdapterImplementation {
readonly type: 'implementation';
readonly implementation: any;
}
export type IAdapterDescriptor = IDebugAdapterExecutable | IDebugAdapterServer | IDebugAdapterImplementation;
export interface IPlatformSpecificAdapterContribution {
program?: string;
args?: string[];
runtime?: string;
runtimeArgs?: string[];
}
export interface IDebuggerContribution extends IPlatformSpecificAdapterContribution {
type?: string;
label?: string;
// debug adapter executable
adapterExecutableCommand?: string;
win?: IPlatformSpecificAdapterContribution;
winx86?: IPlatformSpecificAdapterContribution;
windows?: IPlatformSpecificAdapterContribution;
osx?: IPlatformSpecificAdapterContribution;
linux?: IPlatformSpecificAdapterContribution;
// internal
aiKey?: string;
// supported languages
languages?: string[];
enableBreakpointsFor?: { languageIds: string[] };
// debug configuration support
configurationAttributes?: any;
initialConfigurations?: any[];
configurationSnippets?: IJSONSchemaSnippet[];
variables?: { [key: string]: string };
}
export interface IDebugConfigurationProvider {
readonly type: string;
resolveDebugConfiguration?(folderUri: uri | undefined, debugConfiguration: IConfig): Promise<IConfig>;
provideDebugConfigurations?(folderUri: uri | undefined): Promise<IConfig[]>;
debugAdapterExecutable?(folderUri: uri | undefined): Promise<IAdapterDescriptor>; // TODO@AW legacy
hasTracker: boolean;
}
export interface IDebugAdapterDescriptorFactory {
readonly type: string;
createDebugAdapterDescriptor(session: IDebugSession): Promise<IAdapterDescriptor>;
}
export interface IDebugAdapterTrackerFactory {
readonly type: string;
}
export interface ITerminalLauncher {
runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments, config: ITerminalSettings): Promise<number | undefined>;
}
export interface ITerminalSettings {
external: {
windowsExec: string,
osxExec: string,
linuxExec: string
};
integrated: {
shell: {
osx: string,
windows: string,
linux: string
}
};
}
export interface IConfigurationManager {
/**
* Returns true if breakpoints can be set for a given editor model. Depends on mode.
*/
canSetBreakpointsIn(model: EditorIModel): boolean;
/**
* Returns an object containing the selected launch configuration and the selected configuration name. Both these fields can be null (no folder workspace).
*/
readonly selectedConfiguration: {
launch: ILaunch;
name: string;
};
selectConfiguration(launch: ILaunch, name?: string, debugStarted?: boolean): void;
getLaunches(): ReadonlyArray<ILaunch>;
getLaunch(workspaceUri: uri): ILaunch | undefined;
/**
* Allows to register on change of selected debug configuration.
*/
onDidSelectConfiguration: Event<void>;
activateDebuggers(activationEvent: string, debugType?: string): Promise<void>;
needsToRunInExtHost(debugType: string): boolean;
hasDebugConfigurationProvider(debugType: string): boolean;
registerDebugConfigurationProvider(debugConfigurationProvider: IDebugConfigurationProvider): IDisposable;
unregisterDebugConfigurationProvider(debugConfigurationProvider: IDebugConfigurationProvider): void;
registerDebugAdapterDescriptorFactory(debugAdapterDescriptorFactory: IDebugAdapterDescriptorFactory): IDisposable;
unregisterDebugAdapterDescriptorFactory(debugAdapterDescriptorFactory: IDebugAdapterDescriptorFactory): void;
registerDebugAdapterTrackerFactory(debugAdapterTrackerFactory: IDebugAdapterTrackerFactory): IDisposable;
unregisterDebugAdapterTrackerFactory(debugAdapterTrackerFactory: IDebugAdapterTrackerFactory): void;
resolveConfigurationByProviders(folderUri: uri | undefined, type: string | undefined, debugConfiguration: any): Promise<any>;
getDebugAdapterDescriptor(session: IDebugSession): Promise<IAdapterDescriptor | undefined>;
registerDebugAdapterFactory(debugTypes: string[], debugAdapterFactory: IDebugAdapterFactory): IDisposable;
createDebugAdapter(session: IDebugSession): IDebugAdapter;
substituteVariables(debugType: string, folder: IWorkspaceFolder, config: IConfig): Promise<IConfig>;
runInTerminal(debugType: string, args: DebugProtocol.RunInTerminalRequestArguments, config: ITerminalSettings): Promise<number | undefined>;
}
export interface ILaunch {
/**
* Resource pointing to the launch.json this object is wrapping.
*/
readonly uri: uri;
/**
* Name of the launch.
*/
readonly name: string;
/**
* Workspace of the launch. Can be null.
*/
readonly workspace: IWorkspaceFolder;
/**
* Should this launch be shown in the debug dropdown.
*/
readonly hidden: boolean;
/**
* Returns a configuration with the specified name.
* Returns null if there is no configuration with the specified name.
*/
getConfiguration(name: string): IConfig;
/**
* Returns a compound with the specified name.
* Returns null if there is no compound with the specified name.
*/
getCompound(name: string): ICompound;
/**
* Returns the names of all configurations and compounds.
* Ignores configurations which are invalid.
*/
getConfigurationNames(includeCompounds?: boolean): string[];
/**
* Opens the launch.json file. Creates if it does not exist.
*/
openConfigFile(sideBySide: boolean, preserveFocus: boolean, type?: string): Promise<{ editor: IEditor, created: boolean }>;
}
// Debug service interfaces
export const IDebugService = createDecorator<IDebugService>(DEBUG_SERVICE_ID);
export interface IDebugService {
_serviceBrand: any;
/**
* Gets the current debug state.
*/
readonly state: State;
/**
* Allows to register on debug state changes.
*/
onDidChangeState: Event<State>;
/**
* Allows to register on new session events.
*/
onDidNewSession: Event<IDebugSession>;
/**
* Allows to register on sessions about to be created (not yet fully initialised)
*/
onWillNewSession: Event<IDebugSession>;
/**
* Allows to register on end session events.
*/
onDidEndSession: Event<IDebugSession>;
/**
* Gets the current configuration manager.
*/
getConfigurationManager(): IConfigurationManager;
/**
* Sets the focused stack frame and evaluates all expressions against the newly focused stack frame,
*/
focusStackFrame(focusedStackFrame: IStackFrame, thread?: IThread, session?: IDebugSession, explicit?: boolean): void;
/**
* Adds new breakpoints to the model for the file specified with the uri. Notifies debug adapter of breakpoint changes.
*/
addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]>;
/**
* Updates the breakpoints.
*/
updateBreakpoints(uri: uri, data: { [id: string]: IBreakpointUpdateData }, sendOnResourceSaved: boolean): void;
/**
* Enables or disables all breakpoints. If breakpoint is passed only enables or disables the passed breakpoint.
* Notifies debug adapter of breakpoint changes.
*/
enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void>;
/**
* Sets the global activated property for all breakpoints.
* Notifies debug adapter of breakpoint changes.
*/
setBreakpointsActivated(activated: boolean): Promise<void>;
/**
* Removes all breakpoints. If id is passed only removes the breakpoint associated with that id.
* Notifies debug adapter of breakpoint changes.
*/
removeBreakpoints(id?: string): Promise<any>;
/**
* Adds a new function breakpoint for the given name.
*/
addFunctionBreakpoint(name?: string, id?: string): void;
/**
* Renames an already existing function breakpoint.
* Notifies debug adapter of breakpoint changes.
*/
renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void>;
/**
* Removes all function breakpoints. If id is passed only removes the function breakpoint with the passed id.
* Notifies debug adapter of breakpoint changes.
*/
removeFunctionBreakpoints(id?: string): Promise<void>;
/**
* Sends all breakpoints to the passed session.
* If session is not passed, sends all breakpoints to each session.
*/
sendAllBreakpoints(session?: IDebugSession): Promise<any>;
/**
* Adds a new watch expression and evaluates it against the debug adapter.
*/
addWatchExpression(name?: string): void;
/**
* Renames a watch expression and evaluates it against the debug adapter.
*/
renameWatchExpression(id: string, newName: string): void;
/**
* Moves a watch expression to a new possition. Used for reordering watch expressions.
*/
moveWatchExpression(id: string, position: number): void;
/**
* Removes all watch expressions. If id is passed only removes the watch expression with the passed id.
*/
removeWatchExpressions(id?: string): void;
/**
* Starts debugging. If the configOrName is not passed uses the selected configuration in the debug dropdown.
* Also saves all files, manages if compounds are present in the configuration
* and resolveds configurations via DebugConfigurationProviders.
*
* Returns true if the start debugging was successfull. For compound launches, all configurations have to start successfuly for it to return success.
* On errors the startDebugging will throw an error, however some error and cancelations are handled and in that case will simply return false.
*/
startDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug?: boolean): Promise<boolean>;
/**
* Restarts a session or creates a new one if there is no active session.
*/
restartSession(session: IDebugSession, restartData?: any): Promise<any>;
/**
* Stops the session. If the session does not exist then stops all sessions.
*/
stopSession(session: IDebugSession): Promise<any>;
/**
* Makes unavailable all sources with the passed uri. Source will appear as grayed out in callstack view.
*/
sourceIsNotAvailable(uri: uri): void;
/**
* Gets the current debug model.
*/
getModel(): IDebugModel;
/**
* Gets the current view model.
*/
getViewModel(): IViewModel;
}
// Editor interfaces
export const enum BreakpointWidgetContext {
CONDITION = 0,
HIT_COUNT = 1,
LOG_MESSAGE = 2
}
export interface IDebugEditorContribution extends IEditorContribution {
showHover(range: Range, focus: boolean): Promise<void>;
showBreakpointWidget(lineNumber: number, column: number, context?: BreakpointWidgetContext): void;
closeBreakpointWidget(): void;
addLaunchConfiguration(): Promise<any>;
}
| src/vs/workbench/parts/debug/common/debug.ts | 1 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.004760124254971743,
0.0004762904718518257,
0.00016357899585273117,
0.0001737096899887547,
0.0008795778849162161
] |
{
"id": 2,
"code_window": [
"\t\tprivate textFileService: ITextFileService\n",
"\t) {\n",
"\t\tthis.sessions = [];\n",
"\t\tthis.toDispose = [];\n",
"\t\tthis._onDidChangeBreakpoints = new Emitter<IBreakpointsChangeEvent>();\n",
"\t\tthis._onDidChangeCallStack = new Emitter<void>();\n",
"\t\tthis._onDidChangeWatchExpressions = new Emitter<IExpression>();\n",
"\t}\n",
"\n",
"\tgetId(): string {\n",
"\t\treturn 'root';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._onDidChangeCallStack = new Emitter<IThread | undefined>();\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 753
} | {
"$schema": "vscode://schemas/color-theme",
"name": "Dark Default Colors",
"colors": {
"editor.background": "#1E1E1E",
"editor.foreground": "#D4D4D4",
"editor.inactiveSelectionBackground": "#3A3D41",
"editorIndentGuide.background": "#404040",
"editorIndentGuide.activeBackground": "#707070",
"editor.selectionHighlightBackground": "#ADD6FF26",
"list.dropBackground": "#383B3D",
"activityBarBadge.background": "#007ACC",
"sideBarTitle.foreground": "#BBBBBB",
"input.placeholderForeground": "#A6A6A6",
"settings.textInputBackground": "#292929",
"settings.numberInputBackground": "#292929",
"menu.background": "#252526",
"menu.foreground": "#CCCCCC"
}
} | extensions/theme-defaults/themes/dark_defaults.json | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.00017405455582775176,
0.00017057130753528327,
0.00016554839385207742,
0.00017211092927027494,
0.0000036392816582520027
] |
{
"id": 2,
"code_window": [
"\t\tprivate textFileService: ITextFileService\n",
"\t) {\n",
"\t\tthis.sessions = [];\n",
"\t\tthis.toDispose = [];\n",
"\t\tthis._onDidChangeBreakpoints = new Emitter<IBreakpointsChangeEvent>();\n",
"\t\tthis._onDidChangeCallStack = new Emitter<void>();\n",
"\t\tthis._onDidChangeWatchExpressions = new Emitter<IExpression>();\n",
"\t}\n",
"\n",
"\tgetId(): string {\n",
"\t\treturn 'root';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._onDidChangeCallStack = new Emitter<IThread | undefined>();\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 753
} | <#
.
#> | extensions/powershell/test/colorize-fixtures/test-freeze-56476.ps1 | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.00017101735284086317,
0.00017101735284086317,
0.00017101735284086317,
0.00017101735284086317,
0
] |
{
"id": 2,
"code_window": [
"\t\tprivate textFileService: ITextFileService\n",
"\t) {\n",
"\t\tthis.sessions = [];\n",
"\t\tthis.toDispose = [];\n",
"\t\tthis._onDidChangeBreakpoints = new Emitter<IBreakpointsChangeEvent>();\n",
"\t\tthis._onDidChangeCallStack = new Emitter<void>();\n",
"\t\tthis._onDidChangeWatchExpressions = new Emitter<IExpression>();\n",
"\t}\n",
"\n",
"\tgetId(): string {\n",
"\t\treturn 'root';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._onDidChangeCallStack = new Emitter<IThread | undefined>();\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 753
} | /*---------------------------------------------------------------------------------------------
* 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 { Node, Stylesheet } from 'EmmetNode';
import { isValidLocationForEmmetAbbreviation } from './abbreviationActions';
import { getEmmetHelper, getMappingForIncludedLanguages, parsePartialStylesheet, getEmmetConfiguration, getEmmetMode, isStyleSheet, parseDocument, getEmbeddedCssNodeIfAny, isStyleAttribute, getNode } from './util';
export class DefaultCompletionItemProvider implements vscode.CompletionItemProvider {
private lastCompletionType: string | undefined;
public provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, _: vscode.CancellationToken, context: vscode.CompletionContext): Thenable<vscode.CompletionList | undefined> | undefined {
const completionResult = this.provideCompletionItemsInternal(document, position, context);
if (!completionResult) {
this.lastCompletionType = undefined;
return;
}
return completionResult.then(completionList => {
if (!completionList || !completionList.items.length) {
this.lastCompletionType = undefined;
return completionList;
}
const item = completionList.items[0];
const expandedText = item.documentation ? item.documentation.toString() : '';
if (expandedText.startsWith('<')) {
this.lastCompletionType = 'html';
} else if (expandedText.indexOf(':') > 0 && expandedText.endsWith(';')) {
this.lastCompletionType = 'css';
} else {
this.lastCompletionType = undefined;
}
return completionList;
});
}
private provideCompletionItemsInternal(document: vscode.TextDocument, position: vscode.Position, context: vscode.CompletionContext): Thenable<vscode.CompletionList | undefined> | undefined {
const emmetConfig = vscode.workspace.getConfiguration('emmet');
const excludedLanguages = emmetConfig['excludeLanguages'] ? emmetConfig['excludeLanguages'] : [];
if (excludedLanguages.indexOf(document.languageId) > -1) {
return;
}
const mappedLanguages = getMappingForIncludedLanguages();
const isSyntaxMapped = mappedLanguages[document.languageId] ? true : false;
let syntax = getEmmetMode((isSyntaxMapped ? mappedLanguages[document.languageId] : document.languageId), excludedLanguages);
if (!syntax
|| emmetConfig['showExpandedAbbreviation'] === 'never'
|| ((isSyntaxMapped || syntax === 'jsx') && emmetConfig['showExpandedAbbreviation'] !== 'always')) {
return;
}
const helper = getEmmetHelper();
let validateLocation = syntax === 'html' || syntax === 'jsx' || syntax === 'xml';
let rootNode: Node | undefined = undefined;
let currentNode: Node | null = null;
if (document.languageId === 'html') {
if (context.triggerKind === vscode.CompletionTriggerKind.TriggerForIncompleteCompletions) {
switch (this.lastCompletionType) {
case 'html':
validateLocation = false;
break;
case 'css':
validateLocation = false;
syntax = 'css';
break;
default:
break;
}
}
if (validateLocation) {
rootNode = parseDocument(document, false);
currentNode = getNode(rootNode, position, true);
if (isStyleAttribute(currentNode, position)) {
syntax = 'css';
validateLocation = false;
} else {
const embeddedCssNode = getEmbeddedCssNodeIfAny(document, currentNode, position);
if (embeddedCssNode) {
currentNode = getNode(embeddedCssNode, position, true);
syntax = 'css';
}
}
}
}
const extractAbbreviationResults = helper.extractAbbreviation(document, position, !isStyleSheet(syntax));
if (!extractAbbreviationResults || !helper.isAbbreviationValid(syntax, extractAbbreviationResults.abbreviation)) {
return;
}
if (isStyleSheet(document.languageId) && context.triggerKind !== vscode.CompletionTriggerKind.TriggerForIncompleteCompletions) {
validateLocation = true;
let usePartialParsing = vscode.workspace.getConfiguration('emmet')['optimizeStylesheetParsing'] === true;
rootNode = usePartialParsing && document.lineCount > 1000 ? parsePartialStylesheet(document, position) : <Stylesheet>parseDocument(document, false);
if (!rootNode) {
return;
}
currentNode = getNode(rootNode, position, true);
}
if (validateLocation && !isValidLocationForEmmetAbbreviation(document, rootNode, currentNode, syntax, position, extractAbbreviationResults.abbreviationRange)) {
return;
}
let noiseCheckPromise: Thenable<any> = Promise.resolve();
// Fix for https://github.com/Microsoft/vscode/issues/32647
// Check for document symbols in js/ts/jsx/tsx and avoid triggering emmet for abbreviations of the form symbolName.sometext
// Presence of > or * or + in the abbreviation denotes valid abbreviation that should trigger emmet
if (!isStyleSheet(syntax) && (document.languageId === 'javascript' || document.languageId === 'javascriptreact' || document.languageId === 'typescript' || document.languageId === 'typescriptreact')) {
let abbreviation: string = extractAbbreviationResults.abbreviation;
if (abbreviation.startsWith('this.')) {
noiseCheckPromise = Promise.resolve(true);
} else {
noiseCheckPromise = vscode.commands.executeCommand<vscode.SymbolInformation[]>('vscode.executeDocumentSymbolProvider', document.uri).then((symbols: vscode.SymbolInformation[] | undefined) => {
return symbols && symbols.find(x => abbreviation === x.name || (abbreviation.startsWith(x.name + '.') && !/>|\*|\+/.test(abbreviation)));
});
}
}
return noiseCheckPromise.then((noise): vscode.CompletionList | undefined => {
if (noise) {
return;
}
let result = helper.doComplete(document, position, syntax, getEmmetConfiguration(syntax!));
let newItems: vscode.CompletionItem[] = [];
if (result && result.items) {
result.items.forEach((item: any) => {
let newItem = new vscode.CompletionItem(item.label);
newItem.documentation = item.documentation;
newItem.detail = item.detail;
newItem.insertText = new vscode.SnippetString(item.textEdit.newText);
let oldrange = item.textEdit.range;
newItem.range = new vscode.Range(oldrange.start.line, oldrange.start.character, oldrange.end.line, oldrange.end.character);
newItem.filterText = item.filterText;
newItem.sortText = item.sortText;
if (emmetConfig['showSuggestionsAsSnippets'] === true) {
newItem.kind = vscode.CompletionItemKind.Snippet;
}
newItems.push(newItem);
});
}
return new vscode.CompletionList(newItems, true);
});
}
} | extensions/emmet/src/defaultCompletionProvider.ts | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.00017514951468911022,
0.00017216952983289957,
0.00016719043196644634,
0.00017259575542993844,
0.000002214423602708848
] |
{
"id": 3,
"code_window": [
"\n",
"\tget onDidChangeBreakpoints(): Event<IBreakpointsChangeEvent> {\n",
"\t\treturn this._onDidChangeBreakpoints.event;\n",
"\t}\n",
"\n",
"\tget onDidChangeCallStack(): Event<void> {\n",
"\t\treturn this._onDidChangeCallStack.event;\n",
"\t}\n",
"\n",
"\tget onDidChangeWatchExpressions(): Event<IExpression> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tget onDidChangeCallStack(): Event<IThread | undefined> {\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 788
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI as uri } from 'vs/base/common/uri';
import * as resources from 'vs/base/common/resources';
import * as lifecycle from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
import { generateUuid } from 'vs/base/common/uuid';
import { RunOnceScheduler } from 'vs/base/common/async';
import severity from 'vs/base/common/severity';
import { isObject, isString, isUndefinedOrNull } from 'vs/base/common/types';
import { distinct } from 'vs/base/common/arrays';
import { Range, IRange } from 'vs/editor/common/core/range';
import {
ITreeElement, IExpression, IExpressionContainer, IDebugSession, IStackFrame, IExceptionBreakpoint, IBreakpoint, IFunctionBreakpoint, IDebugModel, IReplElementSource,
IThread, IRawModelUpdate, IScope, IRawStoppedDetails, IEnablement, IBreakpointData, IExceptionInfo, IReplElement, IBreakpointsChangeEvent, IBreakpointUpdateData, IBaseBreakpoint, State
} from 'vs/workbench/parts/debug/common/debug';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { commonSuffixLength } from 'vs/base/common/strings';
import { sep } from 'vs/base/common/paths';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
export class SimpleReplElement implements IReplElement {
constructor(
private id: string,
public value: string,
public severity: severity,
public sourceData: IReplElementSource,
) { }
toString(): string {
return this.value;
}
getId(): string {
return this.id;
}
}
export class RawObjectReplElement implements IExpression {
private static readonly MAX_CHILDREN = 1000; // upper bound of children per value
constructor(private id: string, public name: string, public valueObj: any, public sourceData?: IReplElementSource, public annotation?: string) { }
getId(): string {
return this.id;
}
get value(): string {
if (this.valueObj === null) {
return 'null';
} else if (Array.isArray(this.valueObj)) {
return `Array[${this.valueObj.length}]`;
} else if (isObject(this.valueObj)) {
return 'Object';
} else if (isString(this.valueObj)) {
return `"${this.valueObj}"`;
}
return String(this.valueObj) || '';
}
get hasChildren(): boolean {
return (Array.isArray(this.valueObj) && this.valueObj.length > 0) || (isObject(this.valueObj) && Object.getOwnPropertyNames(this.valueObj).length > 0);
}
getChildren(): Promise<IExpression[]> {
let result: IExpression[] = [];
if (Array.isArray(this.valueObj)) {
result = (<any[]>this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN)
.map((v, index) => new RawObjectReplElement(`${this.id}:${index}`, String(index), v));
} else if (isObject(this.valueObj)) {
result = Object.getOwnPropertyNames(this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN)
.map((key, index) => new RawObjectReplElement(`${this.id}:${index}`, key, this.valueObj[key]));
}
return Promise.resolve(result);
}
toString(): string {
return `${this.name}\n${this.value}`;
}
}
export class ExpressionContainer implements IExpressionContainer {
public static allValues: Map<string, string> = new Map<string, string>();
// Use chunks to support variable paging #9537
private static readonly BASE_CHUNK_SIZE = 100;
public valueChanged: boolean;
private _value: string;
protected children: Promise<IExpression[]>;
constructor(
protected session: IDebugSession,
private _reference: number,
private id: string,
public namedVariables = 0,
public indexedVariables = 0,
private startOfVariables = 0
) { }
get reference(): number {
return this._reference;
}
set reference(value: number) {
this._reference = value;
this.children = undefined; // invalidate children cache
}
getChildren(): Promise<IExpression[]> {
if (!this.children) {
this.children = this.doGetChildren();
}
return this.children;
}
private doGetChildren(): Promise<IExpression[]> {
if (!this.hasChildren) {
return Promise.resolve([]);
}
if (!this.getChildrenInChunks) {
return this.fetchVariables(undefined, undefined, undefined);
}
// Check if object has named variables, fetch them independent from indexed variables #9670
const childrenThenable = !!this.namedVariables ? this.fetchVariables(undefined, undefined, 'named') : Promise.resolve([]);
return childrenThenable.then(childrenArray => {
// Use a dynamic chunk size based on the number of elements #9774
let chunkSize = ExpressionContainer.BASE_CHUNK_SIZE;
while (this.indexedVariables > chunkSize * ExpressionContainer.BASE_CHUNK_SIZE) {
chunkSize *= ExpressionContainer.BASE_CHUNK_SIZE;
}
if (this.indexedVariables > chunkSize) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const numberOfChunks = Math.ceil(this.indexedVariables / chunkSize);
for (let i = 0; i < numberOfChunks; i++) {
const start = this.startOfVariables + i * chunkSize;
const count = Math.min(chunkSize, this.indexedVariables - i * chunkSize);
childrenArray.push(new Variable(this.session, this, this.reference, `[${start}..${start + count - 1}]`, '', '', null, count, { kind: 'virtual' }, null, true, start));
}
return childrenArray;
}
return this.fetchVariables(this.startOfVariables, this.indexedVariables, 'indexed')
.then(variables => childrenArray.concat(variables));
});
}
getId(): string {
return this.id;
}
get value(): string {
return this._value;
}
get hasChildren(): boolean {
// only variables with reference > 0 have children.
return this.reference > 0;
}
private fetchVariables(start: number, count: number, filter: 'indexed' | 'named'): Promise<Variable[]> {
return this.session.variables(this.reference, filter, start, count).then(response => {
return response && response.body && response.body.variables
? distinct(response.body.variables.filter(v => !!v && isString(v.name)), v => v.name).map(
v => new Variable(this.session, this, v.variablesReference, v.name, v.evaluateName, v.value, v.namedVariables, v.indexedVariables, v.presentationHint, v.type))
: [];
}, (e: Error) => [new Variable(this.session, this, 0, e.message, e.message, '', 0, 0, { kind: 'virtual' }, null, false)]);
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.indexedVariables;
}
set value(value: string) {
this._value = value;
this.valueChanged = ExpressionContainer.allValues.get(this.getId()) &&
ExpressionContainer.allValues.get(this.getId()) !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues.get(this.getId()) !== value;
ExpressionContainer.allValues.set(this.getId(), value);
}
toString(): string {
return this.value;
}
}
export class Expression extends ExpressionContainer implements IExpression {
static DEFAULT_VALUE = nls.localize('notAvailable', "not available");
public available: boolean;
public type: string;
constructor(public name: string, id = generateUuid()) {
super(null, 0, id);
this.available = false;
// name is not set if the expression is just being added
// in that case do not set default value to prevent flashing #14499
if (name) {
this.value = Expression.DEFAULT_VALUE;
}
}
evaluate(session: IDebugSession, stackFrame: IStackFrame, context: string): Promise<void> {
if (!session || (!stackFrame && context !== 'repl')) {
this.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate expressions") : Expression.DEFAULT_VALUE;
this.available = false;
this.reference = 0;
return Promise.resolve(void 0);
}
this.session = session;
return session.evaluate(this.name, stackFrame ? stackFrame.frameId : undefined, context).then(response => {
this.available = !!(response && response.body);
if (response && response.body) {
this.value = response.body.result;
this.reference = response.body.variablesReference;
this.namedVariables = response.body.namedVariables;
this.indexedVariables = response.body.indexedVariables;
this.type = response.body.type;
}
}, err => {
this.value = err.message;
this.available = false;
this.reference = 0;
});
}
toString(): string {
return `${this.name}\n${this.value}`;
}
}
export class Variable extends ExpressionContainer implements IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
session: IDebugSession,
public parent: IExpressionContainer,
reference: number,
public name: string,
public evaluateName: string,
value: string,
namedVariables: number,
indexedVariables: number,
public presentationHint: DebugProtocol.VariablePresentationHint,
public type: string | null = null,
public available = true,
startOfVariables = 0
) {
super(session, reference, `variable:${parent.getId()}:${name}`, namedVariables, indexedVariables, startOfVariables);
this.value = value;
}
setVariable(value: string): Promise<any> {
return this.session.setVariable((<ExpressionContainer>this.parent).reference, this.name, value).then(response => {
if (response && response.body) {
this.value = response.body.value;
this.type = response.body.type || this.type;
this.reference = response.body.variablesReference;
this.namedVariables = response.body.namedVariables;
this.indexedVariables = response.body.indexedVariables;
}
}, err => {
this.errorMessage = err.message;
});
}
toString(): string {
return `${this.name}: ${this.value}`;
}
}
export class Scope extends ExpressionContainer implements IScope {
constructor(
stackFrame: IStackFrame,
index: number,
public name: string,
reference: number,
public expensive: boolean,
namedVariables: number,
indexedVariables: number,
public range?: IRange
) {
super(stackFrame.thread.session, reference, `scope:${stackFrame.getId()}:${name}:${index}`, namedVariables, indexedVariables);
}
toString(): string {
return this.name;
}
}
export class StackFrame implements IStackFrame {
private scopes: Promise<Scope[]>;
constructor(
public thread: IThread,
public frameId: number,
public source: Source,
public name: string,
public presentationHint: string,
public range: IRange,
private index: number
) {
this.scopes = null;
}
getId(): string {
return `stackframe:${this.thread.getId()}:${this.frameId}:${this.index}`;
}
getScopes(): Promise<IScope[]> {
if (!this.scopes) {
this.scopes = this.thread.session.scopes(this.frameId).then(response => {
return response && response.body && response.body.scopes ?
response.body.scopes.map((rs, index) => new Scope(this, index, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables,
rs.line && rs.column && rs.endLine && rs.endColumn ? new Range(rs.line, rs.column, rs.endLine, rs.endColumn) : null)) : [];
}, err => []);
}
return this.scopes;
}
getSpecificSourceName(): 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>this.thread).getStaleCallStack();
callStack = callStack.length > 0 ? callStack : this.thread.getCallStack();
const otherSources = callStack.map(sf => sf.source).filter(s => s !== this.source);
let suffixLength = 0;
otherSources.forEach(s => {
if (s.name === this.source.name) {
suffixLength = Math.max(suffixLength, commonSuffixLength(this.source.uri.path, s.uri.path));
}
});
if (suffixLength === 0) {
return this.source.name;
}
const from = Math.max(0, this.source.uri.path.lastIndexOf(sep, this.source.uri.path.length - suffixLength - 1));
return (from > 0 ? '...' : '') + this.source.uri.path.substr(from);
}
getMostSpecificScopes(range: IRange): Promise<IScope[]> {
return this.getScopes().then(scopes => {
scopes = scopes.filter(s => !s.expensive);
const haveRangeInfo = scopes.some(s => !!s.range);
if (!haveRangeInfo) {
return scopes;
}
const scopesContainingRange = scopes.filter(scope => scope.range && Range.containsRange(scope.range, range))
.sort((first, second) => (first.range.endLineNumber - first.range.startLineNumber) - (second.range.endLineNumber - second.range.startLineNumber));
return scopesContainingRange.length ? scopesContainingRange : scopes;
});
}
restart(): Promise<void> {
return this.thread.session.restartFrame(this.frameId, this.thread.threadId);
}
toString(): string {
return `${this.name} (${this.source.inMemory ? this.source.name : this.source.uri.fsPath}:${this.range.startLineNumber})`;
}
openInEditor(editorService: IEditorService, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): Promise<any> {
return !this.source.available ? Promise.resolve(null) :
this.source.openInEditor(editorService, this.range, preserveFocus, sideBySide, pinned);
}
}
export class Thread implements IThread {
private callStack: IStackFrame[];
private staleCallStack: IStackFrame[];
public stoppedDetails: IRawStoppedDetails;
public stopped: boolean;
constructor(public session: IDebugSession, public name: string, public threadId: number) {
this.stoppedDetails = null;
this.callStack = [];
this.staleCallStack = [];
this.stopped = false;
}
getId(): string {
return `thread:${this.session.getId()}:${this.threadId}`;
}
clearCallStack(): void {
if (this.callStack.length) {
this.staleCallStack = this.callStack;
}
this.callStack = [];
}
getCallStack(): IStackFrame[] {
return this.callStack;
}
getStaleCallStack(): ReadonlyArray<IStackFrame> {
return this.staleCallStack;
}
/**
* Queries the debug adapter for the callstack and returns a promise
* which completes once the call stack has been retrieved.
* If the thread is not stopped, it returns a promise to an empty array.
* Only fetches the first stack frame for performance reasons. Calling this method consecutive times
* gets the remainder of the call stack.
*/
fetchCallStack(levels = 20): Promise<void> {
if (!this.stopped) {
return Promise.resolve(void 0);
}
const start = this.callStack.length;
return this.getCallStackImpl(start, levels).then(callStack => {
if (start < this.callStack.length) {
// Set the stack frames for exact position we requested. To make sure no concurrent requests create duplicate stack frames #30660
this.callStack.splice(start, this.callStack.length - start);
}
this.callStack = this.callStack.concat(callStack || []);
});
}
private getCallStackImpl(startFrame: number, levels: number): Promise<IStackFrame[]> {
return this.session.stackTrace(this.threadId, startFrame, levels).then(response => {
if (!response || !response.body) {
return [];
}
if (this.stoppedDetails) {
this.stoppedDetails.totalFrames = response.body.totalFrames;
}
return response.body.stackFrames.map((rsf, index) => {
const source = this.session.getSource(rsf.source);
return new StackFrame(this, rsf.id, source, rsf.name, rsf.presentationHint, new Range(
rsf.line,
rsf.column,
rsf.endLine,
rsf.endColumn
), startFrame + index);
});
}, (err: Error) => {
if (this.stoppedDetails) {
this.stoppedDetails.framesErrorMessage = err.message;
}
return [];
});
}
/**
* Returns exception info promise if the exception was thrown, otherwise null
*/
get exceptionInfo(): Promise<IExceptionInfo | null> {
if (this.stoppedDetails && this.stoppedDetails.reason === 'exception') {
if (this.session.capabilities.supportsExceptionInfoRequest) {
return this.session.exceptionInfo(this.threadId);
}
return Promise.resolve({
description: this.stoppedDetails.text,
breakMode: null
});
}
return Promise.resolve(null);
}
next(): Promise<any> {
return this.session.next(this.threadId);
}
stepIn(): Promise<any> {
return this.session.stepIn(this.threadId);
}
stepOut(): Promise<any> {
return this.session.stepOut(this.threadId);
}
stepBack(): Promise<any> {
return this.session.stepBack(this.threadId);
}
continue(): Promise<any> {
return this.session.continue(this.threadId);
}
pause(): Promise<any> {
return this.session.pause(this.threadId);
}
terminate(): Promise<any> {
return this.session.terminateThreads([this.threadId]);
}
reverseContinue(): Promise<any> {
return this.session.reverseContinue(this.threadId);
}
}
export class Enablement implements IEnablement {
constructor(
public enabled: boolean,
private id: string
) { }
getId(): string {
return this.id;
}
}
export class BaseBreakpoint extends Enablement implements IBaseBreakpoint {
private sessionData = new Map<string, DebugProtocol.Breakpoint>();
private sessionId: string;
constructor(
enabled: boolean,
public hitCondition: string,
public condition: string,
public logMessage: string,
id: string
) {
super(enabled, id);
if (enabled === undefined) {
this.enabled = true;
}
}
protected getSessionData() {
return this.sessionData.get(this.sessionId);
}
setSessionData(sessionId: string, data: DebugProtocol.Breakpoint): void {
this.sessionData.set(sessionId, data);
}
setSessionId(sessionId: string): void {
this.sessionId = sessionId;
}
get verified(): boolean {
const data = this.getSessionData();
return data ? data.verified : true;
}
get idFromAdapter(): number {
const data = this.getSessionData();
return data ? data.id : undefined;
}
toJSON(): any {
const result = Object.create(null);
result.enabled = this.enabled;
result.condition = this.condition;
result.hitCondition = this.hitCondition;
result.logMessage = this.logMessage;
return result;
}
}
export class Breakpoint extends BaseBreakpoint implements IBreakpoint {
constructor(
public uri: uri,
private _lineNumber: number,
private _column: number,
enabled: boolean,
condition: string,
hitCondition: string,
logMessage: string,
private _adapterData: any,
private textFileService: ITextFileService,
id = generateUuid()
) {
super(enabled, hitCondition, condition, logMessage, id);
}
get lineNumber(): number {
const data = this.getSessionData();
return this.verified && data && typeof data.line === 'number' ? data.line : this._lineNumber;
}
get verified(): boolean {
const data = this.getSessionData();
if (data) {
return data.verified && !this.textFileService.isDirty(this.uri);
}
return true;
}
get column(): number {
const data = this.getSessionData();
// Only respect the column if the user explictly set the column to have an inline breakpoint
return data && typeof data.column === 'number' && typeof this._column === 'number' ? data.column : this._column;
}
get message(): string {
const data = this.getSessionData();
if (!data) {
return undefined;
}
if (this.textFileService.isDirty(this.uri)) {
return nls.localize('breakpointDirtydHover', "Unverified breakpoint. File is modified, please restart debug session.");
}
return data.message;
}
get adapterData(): any {
const data = this.getSessionData();
return data && data.source && data.source.adapterData ? data.source.adapterData : this._adapterData;
}
get endLineNumber(): number {
const data = this.getSessionData();
return data ? data.endLine : undefined;
}
get endColumn(): number {
const data = this.getSessionData();
return data ? data.endColumn : undefined;
}
toJSON(): any {
const result = super.toJSON();
result.uri = this.uri;
result.lineNumber = this._lineNumber;
result.column = this._column;
result.adapterData = this.adapterData;
return result;
}
toString(): string {
return resources.basenameOrAuthority(this.uri);
}
update(data: IBreakpointUpdateData): void {
if (!isUndefinedOrNull(data.lineNumber)) {
this._lineNumber = data.lineNumber;
}
if (!isUndefinedOrNull(data.column)) {
this._column = data.column;
}
if (!isUndefinedOrNull(data.condition)) {
this.condition = data.condition;
}
if (!isUndefinedOrNull(data.hitCondition)) {
this.hitCondition = data.hitCondition;
}
if (!isUndefinedOrNull(data.logMessage)) {
this.logMessage = data.logMessage;
}
}
}
export class FunctionBreakpoint extends BaseBreakpoint implements IFunctionBreakpoint {
constructor(
public name: string,
enabled: boolean,
hitCondition: string,
condition: string,
logMessage: string,
id = generateUuid()
) {
super(enabled, hitCondition, condition, logMessage, id);
}
toJSON(): any {
const result = super.toJSON();
result.name = this.name;
return result;
}
toString(): string {
return this.name;
}
}
export class ExceptionBreakpoint extends Enablement implements IExceptionBreakpoint {
constructor(public filter: string, public label: string, enabled: boolean) {
super(enabled, generateUuid());
}
toJSON(): any {
const result = Object.create(null);
result.filter = this.filter;
result.label = this.label;
result.enabled = this.enabled;
return result;
}
toString(): string {
return this.label;
}
}
export class ThreadAndSessionIds implements ITreeElement {
constructor(public sessionId: string, public threadId: number) { }
getId(): string {
return `${this.sessionId}:${this.threadId}`;
}
}
export class DebugModel implements IDebugModel {
private sessions: IDebugSession[];
private toDispose: lifecycle.IDisposable[];
private schedulers = new Map<string, RunOnceScheduler>();
private breakpointsSessionId: string;
private readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent>;
private readonly _onDidChangeCallStack: Emitter<void>;
private readonly _onDidChangeWatchExpressions: Emitter<IExpression>;
constructor(
private breakpoints: Breakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: FunctionBreakpoint[],
private exceptionBreakpoints: ExceptionBreakpoint[],
private watchExpressions: Expression[],
private textFileService: ITextFileService
) {
this.sessions = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<IBreakpointsChangeEvent>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<IExpression>();
}
getId(): string {
return 'root';
}
getSessions(includeInactive = false): IDebugSession[] {
// By default do not return inactive sesions.
// However we are still holding onto inactive sessions due to repl and debug service session revival (eh scenario)
return this.sessions.filter(s => includeInactive || s.state !== State.Inactive);
}
addSession(session: IDebugSession): void {
this.sessions = this.sessions.filter(s => {
if (s.getId() === session.getId()) {
// Make sure to de-dupe if a session is re-intialized. In case of EH debugging we are adding a session again after an attach.
return false;
}
if (s.state === State.Inactive && s.getLabel() === session.getLabel()) {
// Make sure to remove all inactive sessions that are using the same configuration as the new session
return false;
}
return true;
});
this.sessions.push(session);
this._onDidChangeCallStack.fire();
}
get onDidChangeBreakpoints(): Event<IBreakpointsChangeEvent> {
return this._onDidChangeBreakpoints.event;
}
get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
get onDidChangeWatchExpressions(): Event<IExpression> {
return this._onDidChangeWatchExpressions.event;
}
rawUpdate(data: IRawModelUpdate): void {
let session = this.sessions.filter(p => p.getId() === data.sessionId).pop();
if (session) {
session.rawUpdate(data);
this._onDidChangeCallStack.fire();
}
}
clearThreads(id: string, removeThreads: boolean, reference: number | undefined = undefined): void {
const session = this.sessions.filter(p => p.getId() === id).pop();
this.schedulers.forEach(scheduler => scheduler.dispose());
this.schedulers.clear();
if (session) {
session.clearThreads(removeThreads, reference);
this._onDidChangeCallStack.fire();
}
}
fetchCallStack(thread: Thread): Promise<void> {
if (thread.session.capabilities.supportsDelayedStackTraceLoading) {
// For improved performance load the first stack frame and then load the rest async.
return thread.fetchCallStack(1).then(() => {
if (!this.schedulers.has(thread.getId())) {
this.schedulers.set(thread.getId(), new RunOnceScheduler(() => {
thread.fetchCallStack(19).then(() => this._onDidChangeCallStack.fire());
}, 420));
}
this.schedulers.get(thread.getId()).schedule();
this._onDidChangeCallStack.fire();
});
}
return thread.fetchCallStack();
}
getBreakpoints(filter?: { uri?: uri, lineNumber?: number, column?: number, enabledOnly?: boolean }): IBreakpoint[] {
if (filter) {
const uriStr = filter.uri ? filter.uri.toString() : undefined;
return this.breakpoints.filter(bp => {
if (uriStr && bp.uri.toString() !== uriStr) {
return false;
}
if (filter.lineNumber && bp.lineNumber !== filter.lineNumber) {
return false;
}
if (filter.column && bp.column !== filter.column) {
return false;
}
if (filter.enabledOnly && (!this.breakpointsActivated || !bp.enabled)) {
return false;
}
return true;
});
}
return this.breakpoints;
}
getFunctionBreakpoints(): IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
getExceptionBreakpoints(): IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
if (this.exceptionBreakpoints.length === data.length && this.exceptionBreakpoints.every((exbp, i) => exbp.filter === data[i].filter && exbp.label === data[i].label)) {
// No change
return;
}
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
this._onDidChangeBreakpoints.fire();
}
}
areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
addBreakpoints(uri: uri, rawData: IBreakpointData[], fireEvent = true): IBreakpoint[] {
const newBreakpoints = rawData.map(rawBp => new Breakpoint(uri, rawBp.lineNumber, rawBp.column, rawBp.enabled, rawBp.condition, rawBp.hitCondition, rawBp.logMessage, undefined, this.textFileService, rawBp.id));
newBreakpoints.forEach(bp => bp.setSessionId(this.breakpointsSessionId));
this.breakpoints = this.breakpoints.concat(newBreakpoints);
this.breakpointsActivated = true;
this.sortAndDeDup();
if (fireEvent) {
this._onDidChangeBreakpoints.fire({ added: newBreakpoints });
}
return newBreakpoints;
}
removeBreakpoints(toRemove: IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire({ removed: toRemove });
}
updateBreakpoints(data: { [id: string]: IBreakpointUpdateData }): void {
const updated: IBreakpoint[] = [];
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.update(bpData);
updated.push(bp);
}
});
this.sortAndDeDup();
this._onDidChangeBreakpoints.fire({ changed: updated });
}
setBreakpointSessionData(sessionId: string, data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.setSessionData(sessionId, bpData);
}
});
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.setSessionData(sessionId, fbpData);
}
});
this._onDidChangeBreakpoints.fire({
sessionOnly: true
});
}
setBreakpointsSessionId(sessionId: string): void {
this.breakpointsSessionId = sessionId;
this.breakpoints.forEach(bp => bp.setSessionId(sessionId));
this.functionBreakpoints.forEach(fbp => fbp.setSessionId(sessionId));
this._onDidChangeBreakpoints.fire({
sessionOnly: true
});
}
private sortAndDeDup(): void {
this.breakpoints = this.breakpoints.sort((first, second) => {
if (first.uri.toString() !== second.uri.toString()) {
return resources.basenameOrAuthority(first.uri).localeCompare(resources.basenameOrAuthority(second.uri));
}
if (first.lineNumber === second.lineNumber) {
return first.column - second.column;
}
return first.lineNumber - second.lineNumber;
});
this.breakpoints = distinct(this.breakpoints, bp => `${bp.uri.toString()}:${bp.lineNumber}:${bp.column}`);
}
setEnablement(element: IEnablement, enable: boolean): void {
if (element instanceof Breakpoint || element instanceof FunctionBreakpoint || element instanceof ExceptionBreakpoint) {
const changed: Array<IBreakpoint | IFunctionBreakpoint> = [];
if (element.enabled !== enable && (element instanceof Breakpoint || element instanceof FunctionBreakpoint)) {
changed.push(element);
}
element.enabled = enable;
this._onDidChangeBreakpoints.fire({ changed: changed });
}
}
enableOrDisableAllBreakpoints(enable: boolean): void {
const changed: Array<IBreakpoint | IFunctionBreakpoint> = [];
this.breakpoints.forEach(bp => {
if (bp.enabled !== enable) {
changed.push(bp);
}
bp.enabled = enable;
});
this.functionBreakpoints.forEach(fbp => {
if (fbp.enabled !== enable) {
changed.push(fbp);
}
fbp.enabled = enable;
});
this._onDidChangeBreakpoints.fire({ changed: changed });
}
addFunctionBreakpoint(functionName: string, id: string): IFunctionBreakpoint {
const newFunctionBreakpoint = new FunctionBreakpoint(functionName, true, undefined, undefined, undefined, id);
this.functionBreakpoints.push(newFunctionBreakpoint);
this._onDidChangeBreakpoints.fire({ added: [newFunctionBreakpoint] });
return newFunctionBreakpoint;
}
renameFunctionBreakpoint(id: string, name: string): void {
const functionBreakpoint = this.functionBreakpoints.filter(fbp => fbp.getId() === id).pop();
if (functionBreakpoint) {
functionBreakpoint.name = name;
this._onDidChangeBreakpoints.fire({ changed: [functionBreakpoint] });
}
}
removeFunctionBreakpoints(id?: string): void {
let removed: IFunctionBreakpoint[];
if (id) {
removed = this.functionBreakpoints.filter(fbp => fbp.getId() === id);
this.functionBreakpoints = this.functionBreakpoints.filter(fbp => fbp.getId() !== id);
} else {
removed = this.functionBreakpoints;
this.functionBreakpoints = [];
}
this._onDidChangeBreakpoints.fire({ removed: removed });
}
getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
addWatchExpression(name: string): IExpression {
const we = new Expression(name);
this.watchExpressions.push(we);
this._onDidChangeWatchExpressions.fire(we);
return we;
}
renameWatchExpression(id: string, newName: string): void {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
this._onDidChangeWatchExpressions.fire(filtered[0]);
}
}
removeWatchExpressions(id: string | null = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
moveWatchExpression(id: string, position: number): void {
const we = this.watchExpressions.filter(we => we.getId() === id).pop();
this.watchExpressions = this.watchExpressions.filter(we => we.getId() !== id);
this.watchExpressions = this.watchExpressions.slice(0, position).concat(we, this.watchExpressions.slice(position));
this._onDidChangeWatchExpressions.fire();
}
sourceIsNotAvailable(uri: uri): void {
this.sessions.forEach(s => {
const source = s.getSourceForUri(uri);
if (source) {
source.available = false;
}
});
this._onDidChangeCallStack.fire();
}
dispose(): void {
// Make sure to shutdown each session, such that no debugged process is left laying around
this.sessions.forEach(s => s.shutdown());
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.9989891648292542,
0.19693711400032043,
0.00016367307398468256,
0.00017225058400072157,
0.388791024684906
] |
{
"id": 3,
"code_window": [
"\n",
"\tget onDidChangeBreakpoints(): Event<IBreakpointsChangeEvent> {\n",
"\t\treturn this._onDidChangeBreakpoints.event;\n",
"\t}\n",
"\n",
"\tget onDidChangeCallStack(): Event<void> {\n",
"\t\treturn this._onDidChangeCallStack.event;\n",
"\t}\n",
"\n",
"\tget onDidChangeWatchExpressions(): Event<IExpression> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tget onDidChangeCallStack(): Event<IThread | undefined> {\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 788
} | {
"injectionSelector": "L:comment.block.documentation",
"patterns": [
{
"include": "#example"
}
],
"repository": {
"example": {
"begin": "((@)example)\\s+(?=([^*]|[*](?!/))*$).*$",
"while": "(^|\\G)\\s(?!@)(?=([^*]|[*](?!/))*$)",
"beginCaptures": {
"1": {
"name": "storage.type.class.jsdoc"
},
"2": {
"name": "punctuation.definition.block.tag.jsdoc"
}
},
"contentName": "meta.embedded.block.example.source.ts",
"patterns": [
{
"include": "source.tsx"
}
]
}
},
"scopeName": "documentation.example.injection"
} | extensions/typescript-basics/syntaxes/ExampleJsDoc.injection.tmLanguage.json | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.00017164256132673472,
0.00017019215738400817,
0.00016918749315664172,
0.00016974641766864806,
0.000001050667378876824
] |
{
"id": 3,
"code_window": [
"\n",
"\tget onDidChangeBreakpoints(): Event<IBreakpointsChangeEvent> {\n",
"\t\treturn this._onDidChangeBreakpoints.event;\n",
"\t}\n",
"\n",
"\tget onDidChangeCallStack(): Event<void> {\n",
"\t\treturn this._onDidChangeCallStack.event;\n",
"\t}\n",
"\n",
"\tget onDidChangeWatchExpressions(): Event<IExpression> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tget onDidChangeCallStack(): Event<IThread | undefined> {\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 788
} | @octicons-font-path: ".";
@octicons-version: "396334ee3da78f4302d25c758ae3e3ce5dc3c97d";
@font-face {
font-family: 'octicons';
src: ~"url('@{octicons-font-path}/octicons.eot?#iefix&v=@{octicons-version}') format('embedded-opentype')",
~"url('@{octicons-font-path}/octicons.woff?v=@{octicons-version}') format('woff')",
~"url('@{octicons-font-path}/octicons.ttf?v=@{octicons-version}') format('truetype')",
~"url('@{octicons-font-path}/octicons.svg?v=@{octicons-version}#octicons') format('svg')";
font-weight: normal;
font-style: normal;
}
// .octicon is optimized for 16px.
// .mega-octicon is optimized for 32px but can be used larger.
.octicon, .mega-octicon {
font: normal normal normal 16px/1 octicons;
display: inline-block;
text-decoration: none;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.mega-octicon { font-size: 32px; }
.octicon-alert:before { content: '\f02d'} /* */
.octicon-arrow-down:before { content: '\f03f'} /* */
.octicon-arrow-left:before { content: '\f040'} /* */
.octicon-arrow-right:before { content: '\f03e'} /* */
.octicon-arrow-small-down:before { content: '\f0a0'} /* */
.octicon-arrow-small-left:before { content: '\f0a1'} /* */
.octicon-arrow-small-right:before { content: '\f071'} /* */
.octicon-arrow-small-up:before { content: '\f09f'} /* */
.octicon-arrow-up:before { content: '\f03d'} /* */
.octicon-microscope:before,
.octicon-beaker:before { content: '\f0dd'} /* */
.octicon-bell:before { content: '\f0de'} /* */
.octicon-book:before { content: '\f007'} /* */
.octicon-bookmark:before { content: '\f07b'} /* */
.octicon-briefcase:before { content: '\f0d3'} /* */
.octicon-broadcast:before { content: '\f048'} /* */
.octicon-browser:before { content: '\f0c5'} /* */
.octicon-bug:before { content: '\f091'} /* */
.octicon-calendar:before { content: '\f068'} /* */
.octicon-check:before { content: '\f03a'} /* */
.octicon-checklist:before { content: '\f076'} /* */
.octicon-chevron-down:before { content: '\f0a3'} /* */
.octicon-chevron-left:before { content: '\f0a4'} /* */
.octicon-chevron-right:before { content: '\f078'} /* */
.octicon-chevron-up:before { content: '\f0a2'} /* */
.octicon-circle-slash:before { content: '\f084'} /* */
.octicon-circuit-board:before { content: '\f0d6'} /* */
.octicon-clippy:before { content: '\f035'} /* */
.octicon-clock:before { content: '\f046'} /* */
.octicon-cloud-download:before { content: '\f00b'} /* */
.octicon-cloud-upload:before { content: '\f00c'} /* */
.octicon-code:before { content: '\f05f'} /* */
.octicon-color-mode:before { content: '\f065'} /* */
.octicon-comment-add:before,
.octicon-comment:before { content: '\f02b'} /* */
.octicon-comment-discussion:before { content: '\f04f'} /* */
.octicon-credit-card:before { content: '\f045'} /* */
.octicon-dash:before { content: '\f0ca'} /* */
.octicon-dashboard:before { content: '\f07d'} /* */
.octicon-database:before { content: '\f096'} /* */
.octicon-clone:before,
.octicon-desktop-download:before { content: '\f0dc'} /* */
.octicon-device-camera:before { content: '\f056'} /* */
.octicon-device-camera-video:before { content: '\f057'} /* */
.octicon-device-desktop:before { content: '\f27c'} /* */
.octicon-device-mobile:before { content: '\f038'} /* */
.octicon-diff:before { content: '\f04d'} /* */
.octicon-diff-added:before { content: '\f06b'} /* */
.octicon-diff-ignored:before { content: '\f099'} /* */
.octicon-diff-modified:before { content: '\f06d'} /* */
.octicon-diff-removed:before { content: '\f06c'} /* */
.octicon-diff-renamed:before { content: '\f06e'} /* */
.octicon-ellipsis:before { content: '\f09a'} /* */
.octicon-eye-unwatch:before,
.octicon-eye-watch:before,
.octicon-eye:before { content: '\f04e'} /* */
.octicon-file-binary:before { content: '\f094'} /* */
.octicon-file-code:before { content: '\f010'} /* */
.octicon-file-directory:before { content: '\f016'} /* */
.octicon-file-media:before { content: '\f012'} /* */
.octicon-file-pdf:before { content: '\f014'} /* */
.octicon-file-submodule:before { content: '\f017'} /* */
.octicon-file-symlink-directory:before { content: '\f0b1'} /* */
.octicon-file-symlink-file:before { content: '\f0b0'} /* */
.octicon-file-text:before { content: '\f011'} /* */
.octicon-file-zip:before { content: '\f013'} /* */
.octicon-flame:before { content: '\f0d2'} /* */
.octicon-fold:before { content: '\f0cc'} /* */
.octicon-gear:before { content: '\f02f'} /* */
.octicon-gift:before { content: '\f042'} /* */
.octicon-gist:before { content: '\f00e'} /* */
.octicon-gist-secret:before { content: '\f08c'} /* */
.octicon-git-branch-create:before,
.octicon-git-branch-delete:before,
.octicon-git-branch:before { content: '\f020'} /* */
.octicon-git-commit:before { content: '\f01f'} /* */
.octicon-git-compare:before { content: '\f0ac'} /* */
.octicon-git-merge:before { content: '\f023'} /* */
.octicon-git-pull-request-abandoned:before,
.octicon-git-pull-request:before { content: '\f009'} /* */
.octicon-globe:before { content: '\f0b6'} /* */
.octicon-graph:before { content: '\f043'} /* */
.octicon-heart:before { content: '\2665'} /* ♥ */
.octicon-history:before { content: '\f07e'} /* */
.octicon-home:before { content: '\f08d'} /* */
.octicon-horizontal-rule:before { content: '\f070'} /* */
.octicon-hubot:before { content: '\f09d'} /* */
.octicon-inbox:before { content: '\f0cf'} /* */
.octicon-info:before { content: '\f059'} /* */
.octicon-issue-closed:before { content: '\f028'} /* */
.octicon-issue-opened:before { content: '\f026'} /* */
.octicon-issue-reopened:before { content: '\f027'} /* */
.octicon-jersey:before { content: '\f019'} /* */
.octicon-key:before { content: '\f049'} /* */
.octicon-keyboard:before { content: '\f00d'} /* */
.octicon-law:before { content: '\f0d8'} /* */
.octicon-light-bulb:before { content: '\f000'} /* */
.octicon-link:before { content: '\f05c'} /* */
.octicon-link-external:before { content: '\f07f'} /* */
.octicon-list-ordered:before { content: '\f062'} /* */
.octicon-list-unordered:before { content: '\f061'} /* */
.octicon-location:before { content: '\f060'} /* */
.octicon-gist-private:before,
.octicon-mirror-private:before,
.octicon-git-fork-private:before,
.octicon-lock:before { content: '\f06a'} /* */
.octicon-logo-github:before { content: '\f092'} /* */
.octicon-mail:before { content: '\f03b'} /* */
.octicon-mail-read:before { content: '\f03c'} /* */
.octicon-mail-reply:before { content: '\f051'} /* */
.octicon-mark-github:before { content: '\f00a'} /* */
.octicon-markdown:before { content: '\f0c9'} /* */
.octicon-megaphone:before { content: '\f077'} /* */
.octicon-mention:before { content: '\f0be'} /* */
.octicon-milestone:before { content: '\f075'} /* */
.octicon-mirror-public:before,
.octicon-mirror:before { content: '\f024'} /* */
.octicon-mortar-board:before { content: '\f0d7'} /* */
.octicon-mute:before { content: '\f080'} /* */
.octicon-no-newline:before { content: '\f09c'} /* */
.octicon-octoface:before { content: '\f008'} /* */
.octicon-organization:before { content: '\f037'} /* */
.octicon-package:before { content: '\f0c4'} /* */
.octicon-paintcan:before { content: '\f0d1'} /* */
.octicon-pencil:before { content: '\f058'} /* */
.octicon-person-add:before,
.octicon-person-follow:before,
.octicon-person:before { content: '\f018'} /* */
.octicon-pin:before { content: '\f041'} /* */
.octicon-plug:before { content: '\f0d4'} /* */
.octicon-repo-create:before,
.octicon-gist-new:before,
.octicon-file-directory-create:before,
.octicon-file-add:before,
.octicon-plus:before { content: '\f05d'} /* */
.octicon-primitive-dot:before { content: '\f052'} /* */
.octicon-primitive-square:before { content: '\f053'} /* */
.octicon-pulse:before { content: '\f085'} /* */
.octicon-question:before { content: '\f02c'} /* */
.octicon-quote:before { content: '\f063'} /* */
.octicon-radio-tower:before { content: '\f030'} /* */
.octicon-repo-delete:before,
.octicon-repo:before { content: '\f001'} /* */
.octicon-repo-clone:before { content: '\f04c'} /* */
.octicon-repo-force-push:before { content: '\f04a'} /* */
.octicon-gist-fork:before,
.octicon-repo-forked:before { content: '\f002'} /* */
.octicon-repo-pull:before { content: '\f006'} /* */
.octicon-repo-push:before { content: '\f005'} /* */
.octicon-rocket:before { content: '\f033'} /* */
.octicon-rss:before { content: '\f034'} /* */
.octicon-ruby:before { content: '\f047'} /* */
.octicon-screen-full:before { content: '\f066'} /* */
.octicon-screen-normal:before { content: '\f067'} /* */
.octicon-search-save:before,
.octicon-search:before { content: '\f02e'} /* */
.octicon-server:before { content: '\f097'} /* */
.octicon-settings:before { content: '\f07c'} /* */
.octicon-shield:before { content: '\f0e1'} /* */
.octicon-log-in:before,
.octicon-sign-in:before { content: '\f036'} /* */
.octicon-log-out:before,
.octicon-sign-out:before { content: '\f032'} /* */
.octicon-squirrel:before { content: '\f0b2'} /* */
.octicon-star-add:before,
.octicon-star-delete:before,
.octicon-star:before { content: '\f02a'} /* */
.octicon-stop:before { content: '\f08f'} /* */
.octicon-repo-sync:before,
.octicon-sync:before { content: '\f087'} /* */
.octicon-tag-remove:before,
.octicon-tag-add:before,
.octicon-tag:before { content: '\f015'} /* */
.octicon-telescope:before { content: '\f088'} /* */
.octicon-terminal:before { content: '\f0c8'} /* */
.octicon-three-bars:before { content: '\f05e'} /* */
.octicon-thumbsdown:before { content: '\f0db'} /* */
.octicon-thumbsup:before { content: '\f0da'} /* */
.octicon-tools:before { content: '\f031'} /* */
.octicon-trashcan:before { content: '\f0d0'} /* */
.octicon-triangle-down:before { content: '\f05b'} /* */
.octicon-triangle-left:before { content: '\f044'} /* */
.octicon-triangle-right:before { content: '\f05a'} /* */
.octicon-triangle-up:before { content: '\f0aa'} /* */
.octicon-unfold:before { content: '\f039'} /* */
.octicon-unmute:before { content: '\f0ba'} /* */
.octicon-versions:before { content: '\f064'} /* */
.octicon-watch:before { content: '\f0e0'} /* */
.octicon-remove-close:before,
.octicon-x:before { content: '\f081'} /* */
.octicon-zap:before { content: '\26A1'} /* ⚡ */
| src/vs/base/browser/ui/octiconLabel/octicons/octicons.less | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.0001740112347761169,
0.00017045550339389592,
0.0001678046683082357,
0.0001700503344181925,
0.0000017036165900208289
] |
{
"id": 3,
"code_window": [
"\n",
"\tget onDidChangeBreakpoints(): Event<IBreakpointsChangeEvent> {\n",
"\t\treturn this._onDidChangeBreakpoints.event;\n",
"\t}\n",
"\n",
"\tget onDidChangeCallStack(): Event<void> {\n",
"\t\treturn this._onDidChangeCallStack.event;\n",
"\t}\n",
"\n",
"\tget onDidChangeWatchExpressions(): Event<IExpression> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tget onDidChangeCallStack(): Event<IThread | undefined> {\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 788
} | /*---------------------------------------------------------------------------------------------
* 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 PHPCompletionItemProvider from './features/completionItemProvider';
import PHPHoverProvider from './features/hoverProvider';
import PHPSignatureHelpProvider from './features/signatureHelpProvider';
import PHPValidationProvider from './features/validationProvider';
export function activate(context: vscode.ExtensionContext): any {
let validator = new PHPValidationProvider(context.workspaceState);
validator.activate(context.subscriptions);
// add providers
context.subscriptions.push(vscode.languages.registerCompletionItemProvider('php', new PHPCompletionItemProvider(), '>', '$'));
context.subscriptions.push(vscode.languages.registerHoverProvider('php', new PHPHoverProvider()));
context.subscriptions.push(vscode.languages.registerSignatureHelpProvider('php', new PHPSignatureHelpProvider(), '(', ','));
// need to set in the extension host as well as the completion provider uses it.
vscode.languages.setLanguageConfiguration('php', {
wordPattern: /(-?\d*\.\d\w*)|([^\-\`\~\!\@\#\%\^\&\*\(\)\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g,
onEnterRules: [
{
// e.g. /** | */
beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
afterText: /^\s*\*\/$/,
action: { indentAction: vscode.IndentAction.IndentOutdent, appendText: ' * ' }
},
{
// e.g. /** ...|
beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
action: { indentAction: vscode.IndentAction.None, appendText: ' * ' }
},
{
// e.g. * ...|
beforeText: /^(\t|(\ \ ))*\ \*(\ ([^\*]|\*(?!\/))*)?$/,
action: { indentAction: vscode.IndentAction.None, appendText: '* ' }
},
{
// e.g. */|
beforeText: /^(\t|(\ \ ))*\ \*\/\s*$/,
action: { indentAction: vscode.IndentAction.None, removeText: 1 }
},
{
// e.g. *-----*/|
beforeText: /^(\t|(\ \ ))*\ \*[^/]*\*\/\s*$/,
action: { indentAction: vscode.IndentAction.None, removeText: 1 }
}
]
});
} | extensions/php-language-features/src/phpMain.ts | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.0001778990845195949,
0.0001709975622361526,
0.00016789062647148967,
0.0001693477388471365,
0.0000034730526294879382
] |
{
"id": 4,
"code_window": [
"\t\t\treturn thread.fetchCallStack(1).then(() => {\n",
"\t\t\t\tif (!this.schedulers.has(thread.getId())) {\n",
"\t\t\t\t\tthis.schedulers.set(thread.getId(), new RunOnceScheduler(() => {\n",
"\t\t\t\t\t\tthread.fetchCallStack(19).then(() => this._onDidChangeCallStack.fire());\n",
"\t\t\t\t\t}, 420));\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\tthread.fetchCallStack(19).then(() => this._onDidChangeCallStack.fire(thread));\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 821
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI as uri } from 'vs/base/common/uri';
import severity from 'vs/base/common/severity';
import { Event } from 'vs/base/common/event';
import { IJSONSchemaSnippet } from 'vs/base/common/jsonSchema';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { ITextModel as EditorIModel } from 'vs/editor/common/model';
import { IEditor } from 'vs/workbench/common/editor';
import { Position } from 'vs/editor/common/core/position';
import { CompletionItem } from 'vs/editor/common/modes';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { Range, IRange } from 'vs/editor/common/core/range';
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IDisposable } from 'vs/base/common/lifecycle';
import { IViewContainersRegistry, ViewContainer, Extensions as ViewContainerExtensions } from 'vs/workbench/common/views';
import { Registry } from 'vs/platform/registry/common/platform';
import { TaskIdentifier } from 'vs/workbench/parts/tasks/common/tasks';
import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService';
import { IOutputService } from 'vs/workbench/parts/output/common/output';
export const VIEWLET_ID = 'workbench.view.debug';
export const VIEW_CONTAINER: ViewContainer = Registry.as<IViewContainersRegistry>(ViewContainerExtensions.ViewContainersRegistry).registerViewContainer(VIEWLET_ID);
export const VARIABLES_VIEW_ID = 'workbench.debug.variablesView';
export const WATCH_VIEW_ID = 'workbench.debug.watchExpressionsView';
export const CALLSTACK_VIEW_ID = 'workbench.debug.callStackView';
export const LOADED_SCRIPTS_VIEW_ID = 'workbench.debug.loadedScriptsView';
export const BREAKPOINTS_VIEW_ID = 'workbench.debug.breakPointsView';
export const REPL_ID = 'workbench.panel.repl';
export const DEBUG_SERVICE_ID = 'debugService';
export const CONTEXT_DEBUG_TYPE = new RawContextKey<string>('debugType', undefined);
export const CONTEXT_DEBUG_CONFIGURATION_TYPE = new RawContextKey<string>('debugConfigurationType', undefined);
export const CONTEXT_DEBUG_STATE = new RawContextKey<string>('debugState', 'inactive');
export const CONTEXT_IN_DEBUG_MODE = new RawContextKey<boolean>('inDebugMode', false);
export const CONTEXT_IN_DEBUG_REPL = new RawContextKey<boolean>('inDebugRepl', false);
export const CONTEXT_BREAKPOINT_WIDGET_VISIBLE = new RawContextKey<boolean>('breakpointWidgetVisible', false);
export const CONTEXT_IN_BREAKPOINT_WIDGET = new RawContextKey<boolean>('inBreakpointWidget', false);
export const CONTEXT_BREAKPOINTS_FOCUSED = new RawContextKey<boolean>('breakpointsFocused', true);
export const CONTEXT_WATCH_EXPRESSIONS_FOCUSED = new RawContextKey<boolean>('watchExpressionsFocused', true);
export const CONTEXT_VARIABLES_FOCUSED = new RawContextKey<boolean>('variablesFocused', true);
export const CONTEXT_EXPRESSION_SELECTED = new RawContextKey<boolean>('expressionSelected', false);
export const CONTEXT_BREAKPOINT_SELECTED = new RawContextKey<boolean>('breakpointSelected', false);
export const CONTEXT_CALLSTACK_ITEM_TYPE = new RawContextKey<string>('callStackItemType', undefined);
export const CONTEXT_LOADED_SCRIPTS_SUPPORTED = new RawContextKey<boolean>('loadedScriptsSupported', false);
export const CONTEXT_LOADED_SCRIPTS_ITEM_TYPE = new RawContextKey<string>('loadedScriptsItemType', undefined);
export const EDITOR_CONTRIBUTION_ID = 'editor.contrib.debug';
export const DEBUG_SCHEME = 'debug';
export const INTERNAL_CONSOLE_OPTIONS_SCHEMA = {
enum: ['neverOpen', 'openOnSessionStart', 'openOnFirstSessionStart'],
default: 'openOnFirstSessionStart',
description: nls.localize('internalConsoleOptions', "Controls when the internal debug console should open.")
};
// raw
export interface IRawModelUpdate {
threadId: number;
sessionId: string;
thread?: DebugProtocol.Thread;
callStack?: DebugProtocol.StackFrame[];
stoppedDetails?: IRawStoppedDetails;
}
export interface IRawStoppedDetails {
reason: string;
description?: string;
threadId?: number;
text?: string;
totalFrames?: number;
allThreadsStopped?: boolean;
framesErrorMessage?: string;
}
// model
export interface ITreeElement {
getId(): string;
}
export interface IReplElement extends ITreeElement {
toString(): string;
readonly sourceData?: IReplElementSource;
}
export interface IReplElementSource {
readonly source: Source;
readonly lineNumber: number;
readonly column: number;
}
export interface IExpressionContainer extends ITreeElement {
readonly hasChildren: boolean;
getChildren(): Promise<IExpression[]>;
}
export interface IExpression extends IReplElement, IExpressionContainer {
name: string;
readonly value: string;
readonly valueChanged?: boolean;
readonly type?: string;
}
export interface IDebugger {
createDebugAdapter(session: IDebugSession, outputService: IOutputService): Promise<IDebugAdapter>;
runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments): Promise<number | undefined>;
getCustomTelemetryService(): Promise<TelemetryService>;
}
export const enum State {
Inactive,
Initializing,
Stopped,
Running
}
export function getStateLabel(state: State): string {
switch (state) {
case State.Initializing: return 'initializing';
case State.Stopped: return 'stopped';
case State.Running: return 'running';
default: return 'inactive';
}
}
export class AdapterEndEvent {
error?: Error;
sessionLengthInSeconds: number;
emittedStopped: boolean;
}
export interface LoadedSourceEvent {
reason: 'new' | 'changed' | 'removed';
source: Source;
}
export interface IDebugSession extends ITreeElement {
readonly configuration: IConfig;
readonly unresolvedConfiguration: IConfig;
readonly state: State;
readonly root: IWorkspaceFolder;
getLabel(): string;
getSourceForUri(modelUri: uri): Source;
getSource(raw: DebugProtocol.Source): Source;
setConfiguration(configuration: { resolved: IConfig, unresolved: IConfig }): void;
rawUpdate(data: IRawModelUpdate): void;
getThread(threadId: number): IThread;
getAllThreads(): IThread[];
clearThreads(removeThreads: boolean, reference?: number): void;
getReplElements(): IReplElement[];
removeReplExpressions(): void;
addReplExpression(stackFrame: IStackFrame, name: string): Promise<void>;
appendToRepl(data: string | IExpression, severity: severity, source?: IReplElementSource): void;
logToRepl(sev: severity, args: any[], frame?: { uri: uri, line: number, column: number });
// session events
readonly onDidEndAdapter: Event<AdapterEndEvent>;
readonly onDidChangeState: Event<void>;
readonly onDidChangeReplElements: Event<void>;
// DA capabilities
readonly capabilities: DebugProtocol.Capabilities;
// DAP events
readonly onDidLoadedSource: Event<LoadedSourceEvent>;
readonly onDidCustomEvent: Event<DebugProtocol.Event>;
// Disconnects and clears state. Session can be initialized again for a new connection.
shutdown(): void;
// DAP request
initialize(dbgr: IDebugger): Promise<void>;
launchOrAttach(config: IConfig): Promise<void>;
restart(): Promise<void>;
terminate(restart?: boolean /* false */): Promise<void>;
disconnect(restart?: boolean /* false */): Promise<void>;
sendBreakpoints(modelUri: uri, bpts: IBreakpoint[], sourceModified: boolean): Promise<void>;
sendFunctionBreakpoints(fbps: IFunctionBreakpoint[]): Promise<void>;
sendExceptionBreakpoints(exbpts: IExceptionBreakpoint[]): Promise<void>;
stackTrace(threadId: number, startFrame: number, levels: number): Promise<DebugProtocol.StackTraceResponse>;
exceptionInfo(threadId: number): Promise<IExceptionInfo>;
scopes(frameId: number): Promise<DebugProtocol.ScopesResponse>;
variables(variablesReference: number, filter: 'indexed' | 'named', start: number, count: number): Promise<DebugProtocol.VariablesResponse>;
evaluate(expression: string, frameId?: number, context?: string): Promise<DebugProtocol.EvaluateResponse>;
customRequest(request: string, args: any): Promise<DebugProtocol.Response>;
restartFrame(frameId: number, threadId: number): Promise<void>;
next(threadId: number): Promise<void>;
stepIn(threadId: number): Promise<void>;
stepOut(threadId: number): Promise<void>;
stepBack(threadId: number): Promise<void>;
continue(threadId: number): Promise<void>;
reverseContinue(threadId: number): Promise<void>;
pause(threadId: number): Promise<void>;
terminateThreads(threadIds: number[]): Promise<void>;
completions(frameId: number, text: string, position: Position, overwriteBefore: number): Promise<CompletionItem[]>;
setVariable(variablesReference: number, name: string, value: string): Promise<DebugProtocol.SetVariableResponse>;
loadSource(resource: uri): Promise<DebugProtocol.SourceResponse>;
getLoadedSources(): Promise<Source[]>;
}
export interface IThread extends ITreeElement {
/**
* Process the thread belongs to
*/
readonly session: IDebugSession;
/**
* Id of the thread generated by the debug adapter backend.
*/
readonly threadId: number;
/**
* Name of the thread.
*/
readonly name: string;
/**
* Information about the current thread stop event. Null if thread is not stopped.
*/
readonly stoppedDetails: IRawStoppedDetails;
/**
* Information about the exception if an 'exception' stopped event raised and DA supports the 'exceptionInfo' request, otherwise null.
*/
readonly exceptionInfo: Promise<IExceptionInfo>;
/**
* Gets the callstack if it has already been received from the debug
* adapter, otherwise it returns null.
*/
getCallStack(): ReadonlyArray<IStackFrame>;
/**
* Invalidates the callstack cache
*/
clearCallStack(): void;
/**
* Indicates whether this thread is stopped. The callstack for stopped
* threads can be retrieved from the debug adapter.
*/
readonly stopped: boolean;
next(): Promise<any>;
stepIn(): Promise<any>;
stepOut(): Promise<any>;
stepBack(): Promise<any>;
continue(): Promise<any>;
pause(): Promise<any>;
terminate(): Promise<any>;
reverseContinue(): Promise<any>;
}
export interface IScope extends IExpressionContainer {
readonly name: string;
readonly expensive: boolean;
readonly range?: IRange;
}
export interface IStackFrame extends ITreeElement {
readonly thread: IThread;
readonly name: string;
readonly presentationHint: string;
readonly frameId: number;
readonly range: IRange;
readonly source: Source;
getScopes(): Promise<IScope[]>;
getMostSpecificScopes(range: IRange): Promise<ReadonlyArray<IScope>>;
getSpecificSourceName(): string;
restart(): Promise<any>;
toString(): string;
openInEditor(editorService: IEditorService, preserveFocus?: boolean, sideBySide?: boolean): Promise<any>;
}
export interface IEnablement extends ITreeElement {
readonly enabled: boolean;
}
export interface IBreakpointData {
readonly id?: string;
readonly lineNumber: number;
readonly column?: number;
readonly enabled?: boolean;
readonly condition?: string;
readonly logMessage?: string;
readonly hitCondition?: string;
}
export interface IBreakpointUpdateData {
readonly condition?: string;
readonly hitCondition?: string;
readonly logMessage?: string;
readonly lineNumber?: number;
readonly column?: number;
}
export interface IBaseBreakpoint extends IEnablement {
readonly condition: string;
readonly hitCondition: string;
readonly logMessage: string;
readonly verified: boolean;
readonly idFromAdapter: number;
}
export interface IBreakpoint extends IBaseBreakpoint {
readonly uri: uri;
readonly lineNumber: number;
readonly endLineNumber?: number;
readonly column: number;
readonly endColumn?: number;
readonly message: string;
readonly adapterData: any;
}
export interface IFunctionBreakpoint extends IBaseBreakpoint {
readonly name: string;
}
export interface IExceptionBreakpoint extends IEnablement {
readonly filter: string;
readonly label: string;
}
export interface IExceptionInfo {
readonly id?: string;
readonly description?: string;
readonly breakMode: string;
readonly details?: DebugProtocol.ExceptionDetails;
}
// model interfaces
export interface IViewModel extends ITreeElement {
/**
* Returns the focused debug session or null if no session is stopped.
*/
readonly focusedSession: IDebugSession;
/**
* Returns the focused thread or null if no thread is stopped.
*/
readonly focusedThread: IThread;
/**
* Returns the focused stack frame or null if there are no stack frames.
*/
readonly focusedStackFrame: IStackFrame;
getSelectedExpression(): IExpression;
getSelectedFunctionBreakpoint(): IFunctionBreakpoint;
setSelectedExpression(expression: IExpression): void;
setSelectedFunctionBreakpoint(functionBreakpoint: IFunctionBreakpoint): void;
isMultiSessionView(): boolean;
onDidFocusSession: Event<IDebugSession | undefined>;
onDidFocusStackFrame: Event<{ stackFrame: IStackFrame, explicit: boolean }>;
onDidSelectExpression: Event<IExpression>;
}
export interface IEvaluate {
evaluate(session: IDebugSession, stackFrame: IStackFrame, context: string): Promise<void>;
}
export interface IDebugModel extends ITreeElement {
getSessions(includeInactive?: boolean): IDebugSession[];
getBreakpoints(filter?: { uri?: uri, lineNumber?: number, column?: number, enabledOnly?: boolean }): ReadonlyArray<IBreakpoint>;
areBreakpointsActivated(): boolean;
getFunctionBreakpoints(): ReadonlyArray<IFunctionBreakpoint>;
getExceptionBreakpoints(): ReadonlyArray<IExceptionBreakpoint>;
getWatchExpressions(): ReadonlyArray<IExpression & IEvaluate>;
onDidChangeBreakpoints: Event<IBreakpointsChangeEvent>;
onDidChangeCallStack: Event<void>;
onDidChangeWatchExpressions: Event<IExpression>;
}
/**
* An event describing a change to the set of [breakpoints](#debug.Breakpoint).
*/
export interface IBreakpointsChangeEvent {
added?: Array<IBreakpoint | IFunctionBreakpoint>;
removed?: Array<IBreakpoint | IFunctionBreakpoint>;
changed?: Array<IBreakpoint | IFunctionBreakpoint>;
sessionOnly?: boolean;
}
// Debug configuration interfaces
export interface IDebugConfiguration {
allowBreakpointsEverywhere: boolean;
openDebug: 'neverOpen' | 'openOnSessionStart' | 'openOnFirstSessionStart' | 'openOnDebugBreak';
openExplorerOnEnd: boolean;
inlineValues: boolean;
toolBarLocation: 'floating' | 'docked' | 'hidden';
showInStatusBar: 'never' | 'always' | 'onFirstSessionStart';
internalConsoleOptions: 'neverOpen' | 'openOnSessionStart' | 'openOnFirstSessionStart';
extensionHostDebugAdapter: boolean;
enableAllHovers: boolean;
}
export interface IGlobalConfig {
version: string;
compounds: ICompound[];
configurations: IConfig[];
}
export interface IEnvConfig {
internalConsoleOptions?: 'neverOpen' | 'openOnSessionStart' | 'openOnFirstSessionStart';
preLaunchTask?: string | TaskIdentifier;
postDebugTask?: string | TaskIdentifier;
debugServer?: number;
noDebug?: boolean;
}
export interface IConfig extends IEnvConfig {
// fundamental attributes
type: string;
request: string;
name: string;
// platform specifics
windows?: IEnvConfig;
osx?: IEnvConfig;
linux?: IEnvConfig;
// internals
__sessionId?: string;
__restart?: any;
__autoAttach?: boolean;
port?: number; // TODO
}
export interface ICompound {
name: string;
configurations: (string | { name: string, folder: string })[];
}
export interface IDebugAdapter extends IDisposable {
readonly onError: Event<Error>;
readonly onExit: Event<number>;
onRequest(callback: (request: DebugProtocol.Request) => void);
onEvent(callback: (event: DebugProtocol.Event) => void);
startSession(): Promise<void>;
sendMessage(message: DebugProtocol.ProtocolMessage): void;
sendResponse(response: DebugProtocol.Response): void;
sendRequest(command: string, args: any, clb: (result: DebugProtocol.Response) => void, timemout?: number): void;
stopSession(): Promise<void>;
}
export interface IDebugAdapterFactory extends ITerminalLauncher {
createDebugAdapter(session: IDebugSession): IDebugAdapter;
substituteVariables(folder: IWorkspaceFolder, config: IConfig): Promise<IConfig>;
}
export interface IDebugAdapterExecutableOptions {
cwd?: string;
env?: { [key: string]: string };
}
export interface IDebugAdapterExecutable {
readonly type: 'executable';
readonly command: string;
readonly args: string[];
readonly options?: IDebugAdapterExecutableOptions;
}
export interface IDebugAdapterServer {
readonly type: 'server';
readonly port: number;
readonly host?: string;
}
export interface IDebugAdapterImplementation {
readonly type: 'implementation';
readonly implementation: any;
}
export type IAdapterDescriptor = IDebugAdapterExecutable | IDebugAdapterServer | IDebugAdapterImplementation;
export interface IPlatformSpecificAdapterContribution {
program?: string;
args?: string[];
runtime?: string;
runtimeArgs?: string[];
}
export interface IDebuggerContribution extends IPlatformSpecificAdapterContribution {
type?: string;
label?: string;
// debug adapter executable
adapterExecutableCommand?: string;
win?: IPlatformSpecificAdapterContribution;
winx86?: IPlatformSpecificAdapterContribution;
windows?: IPlatformSpecificAdapterContribution;
osx?: IPlatformSpecificAdapterContribution;
linux?: IPlatformSpecificAdapterContribution;
// internal
aiKey?: string;
// supported languages
languages?: string[];
enableBreakpointsFor?: { languageIds: string[] };
// debug configuration support
configurationAttributes?: any;
initialConfigurations?: any[];
configurationSnippets?: IJSONSchemaSnippet[];
variables?: { [key: string]: string };
}
export interface IDebugConfigurationProvider {
readonly type: string;
resolveDebugConfiguration?(folderUri: uri | undefined, debugConfiguration: IConfig): Promise<IConfig>;
provideDebugConfigurations?(folderUri: uri | undefined): Promise<IConfig[]>;
debugAdapterExecutable?(folderUri: uri | undefined): Promise<IAdapterDescriptor>; // TODO@AW legacy
hasTracker: boolean;
}
export interface IDebugAdapterDescriptorFactory {
readonly type: string;
createDebugAdapterDescriptor(session: IDebugSession): Promise<IAdapterDescriptor>;
}
export interface IDebugAdapterTrackerFactory {
readonly type: string;
}
export interface ITerminalLauncher {
runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments, config: ITerminalSettings): Promise<number | undefined>;
}
export interface ITerminalSettings {
external: {
windowsExec: string,
osxExec: string,
linuxExec: string
};
integrated: {
shell: {
osx: string,
windows: string,
linux: string
}
};
}
export interface IConfigurationManager {
/**
* Returns true if breakpoints can be set for a given editor model. Depends on mode.
*/
canSetBreakpointsIn(model: EditorIModel): boolean;
/**
* Returns an object containing the selected launch configuration and the selected configuration name. Both these fields can be null (no folder workspace).
*/
readonly selectedConfiguration: {
launch: ILaunch;
name: string;
};
selectConfiguration(launch: ILaunch, name?: string, debugStarted?: boolean): void;
getLaunches(): ReadonlyArray<ILaunch>;
getLaunch(workspaceUri: uri): ILaunch | undefined;
/**
* Allows to register on change of selected debug configuration.
*/
onDidSelectConfiguration: Event<void>;
activateDebuggers(activationEvent: string, debugType?: string): Promise<void>;
needsToRunInExtHost(debugType: string): boolean;
hasDebugConfigurationProvider(debugType: string): boolean;
registerDebugConfigurationProvider(debugConfigurationProvider: IDebugConfigurationProvider): IDisposable;
unregisterDebugConfigurationProvider(debugConfigurationProvider: IDebugConfigurationProvider): void;
registerDebugAdapterDescriptorFactory(debugAdapterDescriptorFactory: IDebugAdapterDescriptorFactory): IDisposable;
unregisterDebugAdapterDescriptorFactory(debugAdapterDescriptorFactory: IDebugAdapterDescriptorFactory): void;
registerDebugAdapterTrackerFactory(debugAdapterTrackerFactory: IDebugAdapterTrackerFactory): IDisposable;
unregisterDebugAdapterTrackerFactory(debugAdapterTrackerFactory: IDebugAdapterTrackerFactory): void;
resolveConfigurationByProviders(folderUri: uri | undefined, type: string | undefined, debugConfiguration: any): Promise<any>;
getDebugAdapterDescriptor(session: IDebugSession): Promise<IAdapterDescriptor | undefined>;
registerDebugAdapterFactory(debugTypes: string[], debugAdapterFactory: IDebugAdapterFactory): IDisposable;
createDebugAdapter(session: IDebugSession): IDebugAdapter;
substituteVariables(debugType: string, folder: IWorkspaceFolder, config: IConfig): Promise<IConfig>;
runInTerminal(debugType: string, args: DebugProtocol.RunInTerminalRequestArguments, config: ITerminalSettings): Promise<number | undefined>;
}
export interface ILaunch {
/**
* Resource pointing to the launch.json this object is wrapping.
*/
readonly uri: uri;
/**
* Name of the launch.
*/
readonly name: string;
/**
* Workspace of the launch. Can be null.
*/
readonly workspace: IWorkspaceFolder;
/**
* Should this launch be shown in the debug dropdown.
*/
readonly hidden: boolean;
/**
* Returns a configuration with the specified name.
* Returns null if there is no configuration with the specified name.
*/
getConfiguration(name: string): IConfig;
/**
* Returns a compound with the specified name.
* Returns null if there is no compound with the specified name.
*/
getCompound(name: string): ICompound;
/**
* Returns the names of all configurations and compounds.
* Ignores configurations which are invalid.
*/
getConfigurationNames(includeCompounds?: boolean): string[];
/**
* Opens the launch.json file. Creates if it does not exist.
*/
openConfigFile(sideBySide: boolean, preserveFocus: boolean, type?: string): Promise<{ editor: IEditor, created: boolean }>;
}
// Debug service interfaces
export const IDebugService = createDecorator<IDebugService>(DEBUG_SERVICE_ID);
export interface IDebugService {
_serviceBrand: any;
/**
* Gets the current debug state.
*/
readonly state: State;
/**
* Allows to register on debug state changes.
*/
onDidChangeState: Event<State>;
/**
* Allows to register on new session events.
*/
onDidNewSession: Event<IDebugSession>;
/**
* Allows to register on sessions about to be created (not yet fully initialised)
*/
onWillNewSession: Event<IDebugSession>;
/**
* Allows to register on end session events.
*/
onDidEndSession: Event<IDebugSession>;
/**
* Gets the current configuration manager.
*/
getConfigurationManager(): IConfigurationManager;
/**
* Sets the focused stack frame and evaluates all expressions against the newly focused stack frame,
*/
focusStackFrame(focusedStackFrame: IStackFrame, thread?: IThread, session?: IDebugSession, explicit?: boolean): void;
/**
* Adds new breakpoints to the model for the file specified with the uri. Notifies debug adapter of breakpoint changes.
*/
addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]>;
/**
* Updates the breakpoints.
*/
updateBreakpoints(uri: uri, data: { [id: string]: IBreakpointUpdateData }, sendOnResourceSaved: boolean): void;
/**
* Enables or disables all breakpoints. If breakpoint is passed only enables or disables the passed breakpoint.
* Notifies debug adapter of breakpoint changes.
*/
enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void>;
/**
* Sets the global activated property for all breakpoints.
* Notifies debug adapter of breakpoint changes.
*/
setBreakpointsActivated(activated: boolean): Promise<void>;
/**
* Removes all breakpoints. If id is passed only removes the breakpoint associated with that id.
* Notifies debug adapter of breakpoint changes.
*/
removeBreakpoints(id?: string): Promise<any>;
/**
* Adds a new function breakpoint for the given name.
*/
addFunctionBreakpoint(name?: string, id?: string): void;
/**
* Renames an already existing function breakpoint.
* Notifies debug adapter of breakpoint changes.
*/
renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void>;
/**
* Removes all function breakpoints. If id is passed only removes the function breakpoint with the passed id.
* Notifies debug adapter of breakpoint changes.
*/
removeFunctionBreakpoints(id?: string): Promise<void>;
/**
* Sends all breakpoints to the passed session.
* If session is not passed, sends all breakpoints to each session.
*/
sendAllBreakpoints(session?: IDebugSession): Promise<any>;
/**
* Adds a new watch expression and evaluates it against the debug adapter.
*/
addWatchExpression(name?: string): void;
/**
* Renames a watch expression and evaluates it against the debug adapter.
*/
renameWatchExpression(id: string, newName: string): void;
/**
* Moves a watch expression to a new possition. Used for reordering watch expressions.
*/
moveWatchExpression(id: string, position: number): void;
/**
* Removes all watch expressions. If id is passed only removes the watch expression with the passed id.
*/
removeWatchExpressions(id?: string): void;
/**
* Starts debugging. If the configOrName is not passed uses the selected configuration in the debug dropdown.
* Also saves all files, manages if compounds are present in the configuration
* and resolveds configurations via DebugConfigurationProviders.
*
* Returns true if the start debugging was successfull. For compound launches, all configurations have to start successfuly for it to return success.
* On errors the startDebugging will throw an error, however some error and cancelations are handled and in that case will simply return false.
*/
startDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug?: boolean): Promise<boolean>;
/**
* Restarts a session or creates a new one if there is no active session.
*/
restartSession(session: IDebugSession, restartData?: any): Promise<any>;
/**
* Stops the session. If the session does not exist then stops all sessions.
*/
stopSession(session: IDebugSession): Promise<any>;
/**
* Makes unavailable all sources with the passed uri. Source will appear as grayed out in callstack view.
*/
sourceIsNotAvailable(uri: uri): void;
/**
* Gets the current debug model.
*/
getModel(): IDebugModel;
/**
* Gets the current view model.
*/
getViewModel(): IViewModel;
}
// Editor interfaces
export const enum BreakpointWidgetContext {
CONDITION = 0,
HIT_COUNT = 1,
LOG_MESSAGE = 2
}
export interface IDebugEditorContribution extends IEditorContribution {
showHover(range: Range, focus: boolean): Promise<void>;
showBreakpointWidget(lineNumber: number, column: number, context?: BreakpointWidgetContext): void;
closeBreakpointWidget(): void;
addLaunchConfiguration(): Promise<any>;
}
| src/vs/workbench/parts/debug/common/debug.ts | 1 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.0035416046157479286,
0.0002549304626882076,
0.00016293265798594803,
0.00017197331180796027,
0.0004437021561898291
] |
{
"id": 4,
"code_window": [
"\t\t\treturn thread.fetchCallStack(1).then(() => {\n",
"\t\t\t\tif (!this.schedulers.has(thread.getId())) {\n",
"\t\t\t\t\tthis.schedulers.set(thread.getId(), new RunOnceScheduler(() => {\n",
"\t\t\t\t\t\tthread.fetchCallStack(19).then(() => this._onDidChangeCallStack.fire());\n",
"\t\t\t\t\t}, 420));\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\tthread.fetchCallStack(19).then(() => this._onDidChangeCallStack.fire(thread));\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 821
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI } from 'vs/base/common/uri';
import * as perf from 'vs/base/common/performance';
import { ThrottledDelayer, Delayer } from 'vs/base/common/async';
import * as paths from 'vs/base/common/paths';
import * as resources from 'vs/base/common/resources';
import * as glob from 'vs/base/common/glob';
import { Action, IAction } from 'vs/base/common/actions';
import { memoize } from 'vs/base/common/decorators';
import { IFilesConfiguration, ExplorerFolderContext, FilesExplorerFocusedContext, ExplorerFocusedContext, SortOrderConfiguration, SortOrder, IExplorerView, ExplorerRootContext, ExplorerResourceReadonlyContext } from 'vs/workbench/parts/files/common/files';
import { FileOperation, FileOperationEvent, IResolveFileOptions, FileChangeType, FileChangesEvent, IFileService, FILES_EXCLUDE_CONFIG, IFileStat } from 'vs/platform/files/common/files';
import { RefreshViewExplorerAction, NewFolderAction, NewFileAction } from 'vs/workbench/parts/files/electron-browser/fileActions';
import { FileDragAndDrop, FileFilter, FileSorter, FileController, FileRenderer, FileDataSource, FileViewletState, FileAccessibilityProvider } from 'vs/workbench/parts/files/electron-browser/views/explorerViewer';
import { toResource } from 'vs/workbench/common/editor';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import * as DOM from 'vs/base/browser/dom';
import { CollapseAction } from 'vs/workbench/browser/viewlet';
import { TreeViewsViewletPanel, FileIconThemableWorkbenchTree, IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet';
import { ExplorerItem, Model } from 'vs/workbench/parts/files/common/explorerModel';
import { IPartService } from 'vs/workbench/services/part/common/partService';
import { ExplorerDecorationsProvider } from 'vs/workbench/parts/files/electron-browser/views/explorerDecorationsProvider';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IProgressService } from 'vs/platform/progress/common/progress';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { ResourceContextKey } from 'vs/workbench/common/resources';
import { ResourceGlobMatcher } from 'vs/workbench/electron-browser/resources';
import { isLinux } from 'vs/base/common/platform';
import { IDecorationsService } from 'vs/workbench/services/decorations/browser/decorations';
import { WorkbenchTree } from 'vs/platform/list/browser/listService';
import { DelayedDragHandler } from 'vs/base/browser/dnd';
import { Schemas } from 'vs/base/common/network';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IViewletPanelOptions } from 'vs/workbench/browser/parts/views/panelViewlet';
import { ILabelService } from 'vs/platform/label/common/label';
import { ResourceLabels, IResourceLabelsContainer } from 'vs/workbench/browser/labels';
export interface IExplorerViewOptions extends IViewletViewOptions {
fileViewletState: FileViewletState;
}
export class ExplorerView extends TreeViewsViewletPanel implements IExplorerView {
public static readonly ID: string = 'workbench.explorer.fileView';
private static readonly EXPLORER_FILE_CHANGES_REACT_DELAY = 500; // delay in ms to react to file changes to give our internal events a chance to react first
private static readonly EXPLORER_FILE_CHANGES_REFRESH_DELAY = 100; // delay in ms to refresh the explorer from disk file changes
private static readonly MEMENTO_LAST_ACTIVE_FILE_RESOURCE = 'explorer.memento.lastActiveFileResource';
private static readonly MEMENTO_EXPANDED_FOLDER_RESOURCES = 'explorer.memento.expandedFolderResources';
public readonly id: string = ExplorerView.ID;
private explorerViewer: WorkbenchTree;
private explorerLabels: ResourceLabels;
private filter: FileFilter;
private fileViewletState: FileViewletState;
private explorerRefreshDelayer: ThrottledDelayer<void>;
private resourceContext: ResourceContextKey;
private folderContext: IContextKey<boolean>;
private readonlyContext: IContextKey<boolean>;
private rootContext: IContextKey<boolean>;
private fileEventsFilter: ResourceGlobMatcher;
private shouldRefresh: boolean;
private autoReveal: boolean;
private sortOrder: SortOrder;
private viewState: object;
private treeContainer: HTMLElement;
private dragHandler: DelayedDragHandler;
private decorationProvider: ExplorerDecorationsProvider;
private isDisposed: boolean;
constructor(
options: IExplorerViewOptions,
@INotificationService private notificationService: INotificationService,
@IContextMenuService contextMenuService: IContextMenuService,
@IInstantiationService private instantiationService: IInstantiationService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IProgressService private progressService: IProgressService,
@IEditorService private editorService: IEditorService,
@IFileService private fileService: IFileService,
@IPartService private partService: IPartService,
@IKeybindingService keybindingService: IKeybindingService,
@IContextKeyService contextKeyService: IContextKeyService,
@IConfigurationService configurationService: IConfigurationService,
@IDecorationsService decorationService: IDecorationsService,
@ILabelService private labelService: ILabelService
) {
super({ ...(options as IViewletPanelOptions), ariaHeaderLabel: nls.localize('explorerSection', "Files Explorer Section") }, keybindingService, contextMenuService, configurationService);
this.viewState = options.viewletState;
this.fileViewletState = options.fileViewletState;
this.autoReveal = true;
this.explorerRefreshDelayer = new ThrottledDelayer<void>(ExplorerView.EXPLORER_FILE_CHANGES_REFRESH_DELAY);
this.resourceContext = instantiationService.createInstance(ResourceContextKey);
this.disposables.push(this.resourceContext);
this.folderContext = ExplorerFolderContext.bindTo(contextKeyService);
this.readonlyContext = ExplorerResourceReadonlyContext.bindTo(contextKeyService);
this.rootContext = ExplorerRootContext.bindTo(contextKeyService);
this.fileEventsFilter = instantiationService.createInstance(
ResourceGlobMatcher,
(root: URI) => this.getFileEventsExcludes(root),
(event: IConfigurationChangeEvent) => event.affectsConfiguration(FILES_EXCLUDE_CONFIG)
);
this.decorationProvider = new ExplorerDecorationsProvider(this.model, contextService);
decorationService.registerDecorationsProvider(this.decorationProvider);
this.disposables.push(this.decorationProvider);
this.disposables.push(this.resourceContext);
}
private getFileEventsExcludes(root?: URI): glob.IExpression {
const scope = root ? { resource: root } : void 0;
const configuration = this.configurationService.getValue<IFilesConfiguration>(scope);
return (configuration && configuration.files && configuration.files.exclude) || Object.create(null);
}
protected renderHeader(container: HTMLElement): void {
super.renderHeader(container);
// Expand on drag over
this.dragHandler = new DelayedDragHandler(container, () => this.setExpanded(true));
const titleElement = container.querySelector('.title') as HTMLElement;
const setHeader = () => {
const workspace = this.contextService.getWorkspace();
const title = workspace.folders.map(folder => folder.name).join();
titleElement.textContent = this.name;
titleElement.title = title;
};
this.disposables.push(this.contextService.onDidChangeWorkspaceName(setHeader));
this.disposables.push(this.labelService.onDidRegisterFormatter(setHeader));
setHeader();
}
public get name(): string {
return this.labelService.getWorkspaceLabel(this.contextService.getWorkspace());
}
public get title(): string {
return this.name;
}
public set title(value: string) {
// noop
}
public set name(value) {
// noop
}
public render(): void {
super.render();
// Update configuration
const configuration = this.configurationService.getValue<IFilesConfiguration>();
this.onConfigurationUpdated(configuration);
// Load and Fill Viewer
let targetsToExpand: URI[] = [];
if (this.viewState[ExplorerView.MEMENTO_EXPANDED_FOLDER_RESOURCES]) {
targetsToExpand = this.viewState[ExplorerView.MEMENTO_EXPANDED_FOLDER_RESOURCES].map((e: string) => URI.parse(e));
}
this.doRefresh(targetsToExpand).then(() => {
// When the explorer viewer is loaded, listen to changes to the editor input
this.disposables.push(this.editorService.onDidActiveEditorChange(() => this.revealActiveFile()));
// Also handle configuration updates
this.disposables.push(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(this.configurationService.getValue<IFilesConfiguration>(), e)));
this.revealActiveFile();
});
}
public renderBody(container: HTMLElement): void {
this.treeContainer = DOM.append(container, DOM.$('.explorer-folders-view'));
this.tree = this.createViewer(this.treeContainer);
if (this.toolbar) {
this.toolbar.setActions(this.getActions(), this.getSecondaryActions())();
}
this.disposables.push(this.contextService.onDidChangeWorkspaceFolders(e => this.refreshFromEvent(e.added)));
this.disposables.push(this.contextService.onDidChangeWorkbenchState(e => this.refreshFromEvent()));
this.disposables.push(this.fileService.onDidChangeFileSystemProviderRegistrations(() => this.refreshFromEvent()));
this.disposables.push(this.labelService.onDidRegisterFormatter(() => {
this._onDidChangeTitleArea.fire();
this.refreshFromEvent();
}));
}
layoutBody(size: number): void {
if (this.treeContainer) {
this.treeContainer.style.height = size + 'px';
}
super.layoutBody(size);
}
public getActions(): IAction[] {
const actions: Action[] = [];
actions.push(this.instantiationService.createInstance(NewFileAction, this.getViewer(), null));
actions.push(this.instantiationService.createInstance(NewFolderAction, this.getViewer(), null));
actions.push(this.instantiationService.createInstance(RefreshViewExplorerAction, this, 'explorer-action refresh-explorer'));
actions.push(this.instantiationService.createInstance(CollapseAction, this.getViewer(), true, 'explorer-action collapse-explorer'));
return actions;
}
private revealActiveFile(): void {
if (!this.autoReveal) {
return; // do not touch selection or focus if autoReveal === false
}
let clearSelection = true;
let clearFocus = false;
// Handle files
const activeFile = this.getActiveFile();
if (activeFile) {
// Always remember last opened file
this.viewState[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE] = activeFile.toString();
// Select file if input is inside workspace
if (this.isBodyVisible() && !this.isDisposed && this.contextService.isInsideWorkspace(activeFile)) {
const selection = this.hasSingleSelection(activeFile);
if (!selection) {
this.select(activeFile);
}
clearSelection = false;
}
}
// Handle closed or untitled file (convince explorer to not reopen any file when getting visible)
const activeInput = this.editorService.activeEditor;
if (!activeInput || toResource(activeInput, { supportSideBySide: true, filter: Schemas.untitled })) {
this.viewState[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE] = void 0;
clearFocus = true;
}
// Otherwise clear
if (clearSelection) {
this.explorerViewer.clearSelection();
}
if (clearFocus) {
this.explorerViewer.clearFocus();
}
}
private onConfigurationUpdated(configuration: IFilesConfiguration, event?: IConfigurationChangeEvent): void {
if (this.isDisposed) {
return; // guard against possible race condition when config change causes recreate of views
}
this.autoReveal = configuration && configuration.explorer && configuration.explorer.autoReveal;
// Push down config updates to components of viewer
let needsRefresh = false;
if (this.filter) {
needsRefresh = this.filter.updateConfiguration();
}
const configSortOrder = configuration && configuration.explorer && configuration.explorer.sortOrder || 'default';
if (this.sortOrder !== configSortOrder) {
this.sortOrder = configSortOrder;
needsRefresh = true;
}
if (event && !needsRefresh) {
needsRefresh = event.affectsConfiguration('explorer.decorations.colors')
|| event.affectsConfiguration('explorer.decorations.badges');
}
// Refresh viewer as needed if this originates from a config event
if (event && needsRefresh) {
this.doRefresh();
}
}
public focus(): void {
super.focus();
let keepFocus = false;
// Make sure the current selected element is revealed
if (this.explorerViewer) {
if (this.autoReveal) {
const selection = this.explorerViewer.getSelection();
if (selection.length > 0) {
this.reveal(selection[0], 0.5);
}
}
// Pass Focus to Viewer
this.explorerViewer.domFocus();
keepFocus = true;
}
// Open the focused element in the editor if there is currently no file opened
const activeFile = this.getActiveFile();
if (!activeFile) {
this.openFocusedElement(keepFocus);
}
}
public setVisible(visible: boolean): void {
super.setVisible(visible);
// Show
if (visible) {
// If a refresh was requested and we are now visible, run it
let refreshPromise: Promise<void> = Promise.resolve(null);
if (this.shouldRefresh) {
refreshPromise = this.doRefresh();
this.shouldRefresh = false; // Reset flag
}
if (!this.autoReveal) {
return; // do not react to setVisible call if autoReveal === false
}
// Always select the current navigated file in explorer if input is file editor input
// unless autoReveal is set to false
const activeFile = this.getActiveFile();
if (activeFile) {
refreshPromise.then(() => {
this.select(activeFile);
});
return;
}
// Return now if the workbench has not yet been restored - in this case the workbench takes care of restoring last used editors
if (!this.partService.isRestored()) {
return;
}
// Otherwise restore last used file: By lastActiveFileResource
let lastActiveFileResource: URI;
if (this.viewState[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE]) {
lastActiveFileResource = URI.parse(this.viewState[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE]);
}
if (lastActiveFileResource && this.isCreated && this.model.findClosest(lastActiveFileResource)) {
this.editorService.openEditor({ resource: lastActiveFileResource, options: { revealIfVisible: true } });
return;
}
// Otherwise restore last used file: By Explorer selection
refreshPromise.then(() => {
this.openFocusedElement();
});
}
}
private openFocusedElement(preserveFocus?: boolean): void {
const stat: ExplorerItem = this.explorerViewer.getFocus();
if (stat && !stat.isDirectory) {
this.editorService.openEditor({ resource: stat.resource, options: { preserveFocus, revealIfVisible: true } });
}
}
private getActiveFile(): URI {
const input = this.editorService.activeEditor;
// ignore diff editor inputs (helps to get out of diffing when returning to explorer)
if (input instanceof DiffEditorInput) {
return null;
}
// check for files
return toResource(input, { supportSideBySide: true });
}
private get isCreated(): boolean {
return !!(this.explorerViewer && this.explorerViewer.getInput());
}
@memoize
private get model(): Model {
const model = this.instantiationService.createInstance(Model);
this.disposables.push(model);
return model;
}
private createViewer(container: HTMLElement): WorkbenchTree {
const dataSource = this.instantiationService.createInstance(FileDataSource);
this.explorerLabels = this.instantiationService.createInstance(ResourceLabels, { onDidChangeVisibility: this.onDidChangeBodyVisibility } as IResourceLabelsContainer);
this.disposables.push(this.explorerLabels);
const renderer = this.instantiationService.createInstance(FileRenderer, this.fileViewletState, this.explorerLabels);
const controller = this.instantiationService.createInstance(FileController);
this.disposables.push(controller);
const sorter = this.instantiationService.createInstance(FileSorter);
this.disposables.push(sorter);
this.filter = this.instantiationService.createInstance(FileFilter);
this.disposables.push(this.filter);
const dnd = this.instantiationService.createInstance(FileDragAndDrop);
const accessibilityProvider = this.instantiationService.createInstance(FileAccessibilityProvider);
this.explorerViewer = this.instantiationService.createInstance(FileIconThemableWorkbenchTree, container, {
dataSource,
renderer,
controller,
sorter,
filter: this.filter,
dnd,
accessibilityProvider
}, {
autoExpandSingleChildren: true,
ariaLabel: nls.localize('treeAriaLabel', "Files Explorer")
});
// Bind context keys
FilesExplorerFocusedContext.bindTo(this.explorerViewer.contextKeyService);
ExplorerFocusedContext.bindTo(this.explorerViewer.contextKeyService);
// Update Viewer based on File Change Events
this.disposables.push(this.fileService.onAfterOperation(e => this.onFileOperation(e)));
this.disposables.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));
// Update resource context based on focused element
this.disposables.push(this.explorerViewer.onDidChangeFocus((e: { focus: ExplorerItem }) => {
const isSingleFolder = this.contextService.getWorkbenchState() === WorkbenchState.FOLDER;
const resource = e.focus ? e.focus.resource : isSingleFolder ? this.contextService.getWorkspace().folders[0].uri : undefined;
this.resourceContext.set(resource);
this.folderContext.set((isSingleFolder && !e.focus) || e.focus && e.focus.isDirectory);
this.readonlyContext.set(e.focus && e.focus.isReadonly);
this.rootContext.set(!e.focus || (e.focus && e.focus.isRoot));
}));
// Open when selecting via keyboard
this.disposables.push(this.explorerViewer.onDidChangeSelection(event => {
if (event && event.payload && event.payload.origin === 'keyboard') {
const element = this.tree.getSelection();
if (Array.isArray(element) && element[0] instanceof ExplorerItem) {
if (element[0].isDirectory) {
this.explorerViewer.toggleExpansion(element[0]);
}
controller.openEditor(element[0], { pinned: false, sideBySide: false, preserveFocus: false });
}
}
}));
return this.explorerViewer;
}
getViewer(): WorkbenchTree {
return this.tree;
}
public getOptimalWidth(): number {
const parentNode = this.explorerViewer.getHTMLElement();
const childNodes = ([] as HTMLElement[]).slice.call(parentNode.querySelectorAll('.explorer-item .label-name')); // select all file labels
return DOM.getLargestChildWidth(parentNode, childNodes);
}
private onFileOperation(e: FileOperationEvent): void {
if (!this.isCreated) {
return; // ignore if not yet created
}
// Add
if (e.operation === FileOperation.CREATE || e.operation === FileOperation.COPY) {
const addedElement = e.target;
const parentResource = resources.dirname(addedElement.resource);
const parents = this.model.findAll(parentResource);
if (parents.length) {
// Add the new file to its parent (Model)
parents.forEach(p => {
// We have to check if the parent is resolved #29177
const thenable: Promise<IFileStat> = p.isDirectoryResolved ? Promise.resolve(null) : this.fileService.resolveFile(p.resource);
thenable.then(stat => {
if (stat) {
const modelStat = ExplorerItem.create(stat, p.root);
ExplorerItem.mergeLocalWithDisk(modelStat, p);
}
const childElement = ExplorerItem.create(addedElement, p.root);
p.removeChild(childElement); // make sure to remove any previous version of the file if any
p.addChild(childElement);
// Refresh the Parent (View)
this.explorerViewer.refresh(p).then(() => {
return this.reveal(childElement, 0.5).then(() => {
// Focus new element
this.explorerViewer.setFocus(childElement);
});
});
});
});
}
}
// Move (including Rename)
else if (e.operation === FileOperation.MOVE) {
const oldResource = e.resource;
const newElement = e.target;
const oldParentResource = resources.dirname(oldResource);
const newParentResource = resources.dirname(newElement.resource);
// Only update focus if renamed/moved element is selected
let restoreFocus = false;
const focus: ExplorerItem = this.explorerViewer.getFocus();
if (focus && focus.resource && focus.resource.toString() === oldResource.toString()) {
restoreFocus = true;
}
let isExpanded = false;
// Handle Rename
if (oldParentResource && newParentResource && oldParentResource.toString() === newParentResource.toString()) {
const modelElements = this.model.findAll(oldResource);
modelElements.forEach(modelElement => {
//Check if element is expanded
isExpanded = this.explorerViewer.isExpanded(modelElement);
// Rename File (Model)
modelElement.rename(newElement);
// Update Parent (View)
this.explorerViewer.refresh(modelElement.parent).then(() => {
// Select in Viewer if set
if (restoreFocus) {
this.explorerViewer.setFocus(modelElement);
}
//Expand the element again
if (isExpanded) {
this.explorerViewer.expand(modelElement);
}
});
});
}
// Handle Move
else if (oldParentResource && newParentResource) {
const newParents = this.model.findAll(newParentResource);
const modelElements = this.model.findAll(oldResource);
if (newParents.length && modelElements.length) {
// Move in Model
modelElements.forEach((modelElement, index) => {
const oldParent = modelElement.parent;
modelElement.move(newParents[index], (callback: () => void) => {
// Update old parent
this.explorerViewer.refresh(oldParent).then(callback);
}, () => {
// Update new parent
this.explorerViewer.refresh(newParents[index], true).then(() => this.explorerViewer.expand(newParents[index]));
});
});
}
}
}
// Delete
else if (e.operation === FileOperation.DELETE) {
const modelElements = this.model.findAll(e.resource);
modelElements.forEach(element => {
if (element.parent) {
const parent = element.parent;
// Remove Element from Parent (Model)
parent.removeChild(element);
// Refresh Parent (View)
const restoreFocus = this.explorerViewer.isDOMFocused();
this.explorerViewer.refresh(parent).then(() => {
// Ensure viewer has keyboard focus if event originates from viewer
if (restoreFocus) {
this.explorerViewer.domFocus();
}
});
}
});
}
}
private onFileChanges(e: FileChangesEvent): void {
// Ensure memento state does not capture a deleted file (we run this from a timeout because
// delete events can result in UI activity that will fill the memento again when multiple
// editors are closing)
setTimeout(() => {
const lastActiveResource: string = this.viewState[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE];
if (lastActiveResource && e.contains(URI.parse(lastActiveResource), FileChangeType.DELETED)) {
this.viewState[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE] = null;
}
});
// Check if an explorer refresh is necessary (delayed to give internal events a chance to react first)
// Note: there is no guarantee when the internal events are fired vs real ones. Code has to deal with the fact that one might
// be fired first over the other or not at all.
setTimeout(() => {
if (!this.shouldRefresh && this.shouldRefreshFromEvent(e)) {
this.refreshFromEvent();
}
}, ExplorerView.EXPLORER_FILE_CHANGES_REACT_DELAY);
}
private shouldRefreshFromEvent(e: FileChangesEvent): boolean {
if (!this.isCreated) {
return false;
}
// Filter to the ones we care
e = this.filterToViewRelevantEvents(e);
// Handle added files/folders
const added = e.getAdded();
if (added.length) {
// Check added: Refresh if added file/folder is not part of resolved root and parent is part of it
const ignoredPaths: { [resource: string]: boolean } = <{ [resource: string]: boolean }>{};
for (let i = 0; i < added.length; i++) {
const change = added[i];
// Find parent
const parent = resources.dirname(change.resource);
// Continue if parent was already determined as to be ignored
if (ignoredPaths[parent.toString()]) {
continue;
}
// Compute if parent is visible and added file not yet part of it
const parentStat = this.model.findClosest(parent);
if (parentStat && parentStat.isDirectoryResolved && !this.model.findClosest(change.resource)) {
return true;
}
// Keep track of path that can be ignored for faster lookup
if (!parentStat || !parentStat.isDirectoryResolved) {
ignoredPaths[parent.toString()] = true;
}
}
}
// Handle deleted files/folders
const deleted = e.getDeleted();
if (deleted.length) {
// Check deleted: Refresh if deleted file/folder part of resolved root
for (let j = 0; j < deleted.length; j++) {
const del = deleted[j];
if (this.model.findClosest(del.resource)) {
return true;
}
}
}
// Handle updated files/folders if we sort by modified
if (this.sortOrder === SortOrderConfiguration.MODIFIED) {
const updated = e.getUpdated();
// Check updated: Refresh if updated file/folder part of resolved root
for (let j = 0; j < updated.length; j++) {
const upd = updated[j];
if (this.model.findClosest(upd.resource)) {
return true;
}
}
}
return false;
}
private filterToViewRelevantEvents(e: FileChangesEvent): FileChangesEvent {
return new FileChangesEvent(e.changes.filter(change => {
if (change.type === FileChangeType.UPDATED && this.sortOrder !== SortOrderConfiguration.MODIFIED) {
return false; // we only are about updated if we sort by modified time
}
if (!this.contextService.isInsideWorkspace(change.resource)) {
return false; // exclude changes for resources outside of workspace
}
if (this.fileEventsFilter.matches(change.resource)) {
return false; // excluded via files.exclude setting
}
return true;
}));
}
private refreshFromEvent(newRoots: IWorkspaceFolder[] = []): void {
if (this.isBodyVisible() && !this.isDisposed) {
this.explorerRefreshDelayer.trigger(() => {
if (!this.explorerViewer.getHighlight()) {
return this.doRefresh(newRoots.map(r => r.uri)).then(() => {
if (newRoots.length === 1) {
return this.reveal(this.model.findClosest(newRoots[0].uri), 0.5);
}
return undefined;
});
}
return Promise.resolve(null);
});
} else {
this.shouldRefresh = true;
}
}
/**
* Refresh the contents of the explorer to get up to date data from the disk about the file structure.
*/
public refresh(): Promise<void> {
if (!this.explorerViewer || this.explorerViewer.getHighlight()) {
return Promise.resolve(void 0);
}
// Focus
this.explorerViewer.domFocus();
// Find resource to focus from active editor input if set
let resourceToFocus: URI;
if (this.autoReveal) {
resourceToFocus = this.getActiveFile();
if (!resourceToFocus) {
const selection = this.explorerViewer.getSelection();
if (selection && selection.length === 1) {
resourceToFocus = (<ExplorerItem>selection[0]).resource;
}
}
}
return this.doRefresh().then(() => {
if (resourceToFocus) {
return this.select(resourceToFocus, true);
}
return Promise.resolve(void 0);
});
}
private doRefresh(targetsToExpand: URI[] = []): Promise<any> {
const targetsToResolve = this.model.roots.map(root => ({ root, resource: root.resource, options: { resolveTo: [] } }));
// First time refresh: Receive target through active editor input or selection and also include settings from previous session
if (!this.isCreated) {
const activeFile = this.getActiveFile();
if (activeFile) {
const workspaceFolder = this.contextService.getWorkspaceFolder(activeFile);
if (workspaceFolder) {
const found = targetsToResolve.filter(t => t.root.resource.toString() === workspaceFolder.uri.toString()).pop();
found.options.resolveTo.push(activeFile);
}
}
targetsToExpand.forEach(toExpand => {
const workspaceFolder = this.contextService.getWorkspaceFolder(toExpand);
if (workspaceFolder) {
const found = targetsToResolve.filter(ttr => ttr.resource.toString() === workspaceFolder.uri.toString()).pop();
found.options.resolveTo.push(toExpand);
}
});
}
// Subsequent refresh: Receive targets through expanded folders in tree
else {
targetsToResolve.forEach(t => {
this.getResolvedDirectories(t.root, t.options.resolveTo);
});
}
const promise = this.resolveRoots(targetsToResolve, targetsToExpand).then(result => {
this.decorationProvider.changed(targetsToResolve.map(t => t.root.resource));
return result;
});
this.progressService.showWhile(promise, this.partService.isRestored() ? 800 : 1200 /* less ugly initial startup */);
return promise;
}
private resolveRoots(targetsToResolve: { root: ExplorerItem, resource: URI, options: { resolveTo: any[] } }[], targetsToExpand: URI[]): Promise<any> {
// Display roots only when multi folder workspace
let input = this.contextService.getWorkbenchState() === WorkbenchState.FOLDER ? this.model.roots[0] : this.model;
if (input !== this.explorerViewer.getInput()) {
perf.mark('willResolveExplorer');
}
const errorRoot = (resource: URI, root: ExplorerItem) => {
if (input === this.model.roots[0]) {
input = this.model;
}
return ExplorerItem.create({
resource: resource,
name: paths.basename(resource.fsPath),
mtime: 0,
etag: undefined,
isDirectory: true
}, root, undefined, true);
};
const setInputAndExpand = (input: ExplorerItem | Model, statsToExpand: ExplorerItem[]) => {
// Make sure to expand all folders that where expanded in the previous session
// Special case: we are switching to multi workspace view, thus expand all the roots (they might just be added)
if (input === this.model && statsToExpand.every(fs => fs && !fs.isRoot)) {
statsToExpand = this.model.roots.concat(statsToExpand);
}
return this.explorerViewer.setInput(input).then(() => this.explorerViewer.expandAll(statsToExpand))
.then(() => perf.mark('didResolveExplorer'));
};
if (targetsToResolve.every(t => t.root.resource.scheme === 'file')) {
// All the roots are local, resolve them in parallel
return this.fileService.resolveFiles(targetsToResolve).then(results => {
// Convert to model
const modelStats = results.map((result, index) => {
if (result.success && result.stat.isDirectory) {
return ExplorerItem.create(result.stat, targetsToResolve[index].root, targetsToResolve[index].options.resolveTo);
}
return errorRoot(targetsToResolve[index].resource, targetsToResolve[index].root);
});
// Subsequent refresh: Merge stat into our local model and refresh tree
modelStats.forEach((modelStat, index) => {
if (index < this.model.roots.length) {
ExplorerItem.mergeLocalWithDisk(modelStat, this.model.roots[index]);
}
});
const statsToExpand: ExplorerItem[] = this.explorerViewer.getExpandedElements().concat(targetsToExpand.map(expand => this.model.findClosest(expand)));
if (input === this.explorerViewer.getInput()) {
return this.explorerViewer.refresh().then(() => this.explorerViewer.expandAll(statsToExpand));
}
return setInputAndExpand(input, statsToExpand);
});
}
// There is a remote root, resolve the roots sequantally
let statsToExpand: ExplorerItem[] = [];
let delayer = new Delayer(100);
let delayerPromise: Promise<any>;
return Promise.all(targetsToResolve.map((target, index) => this.fileService.resolveFile(target.resource, target.options)
.then(result => result.isDirectory ? ExplorerItem.create(result, target.root, target.options.resolveTo) : errorRoot(target.resource, target.root), () => errorRoot(target.resource, target.root))
.then(modelStat => {
// Subsequent refresh: Merge stat into our local model and refresh tree
if (index < this.model.roots.length) {
ExplorerItem.mergeLocalWithDisk(modelStat, this.model.roots[index]);
}
let toExpand: ExplorerItem[] = this.explorerViewer.getExpandedElements().concat(targetsToExpand.map(target => this.model.findClosest(target)));
if (input === this.explorerViewer.getInput()) {
statsToExpand = statsToExpand.concat(toExpand);
if (!delayer.isTriggered()) {
delayerPromise = delayer.trigger(() => this.explorerViewer.refresh()
.then(() => this.explorerViewer.expandAll(statsToExpand))
.then(() => statsToExpand = [])
);
}
return delayerPromise;
}
return setInputAndExpand(input, statsToExpand);
})));
}
/**
* Given a stat, fills an array of path that make all folders below the stat that are resolved directories.
*/
private getResolvedDirectories(stat: ExplorerItem, resolvedDirectories: URI[]): void {
if (stat.isDirectoryResolved) {
if (!stat.isRoot) {
// Drop those path which are parents of the current one
for (let i = resolvedDirectories.length - 1; i >= 0; i--) {
const resource = resolvedDirectories[i];
if (resources.isEqualOrParent(stat.resource, resource, !isLinux /* ignorecase */)) {
resolvedDirectories.splice(i);
}
}
// Add to the list of path to resolve
resolvedDirectories.push(stat.resource);
}
// Recurse into children
stat.getChildrenArray().forEach(child => {
this.getResolvedDirectories(child, resolvedDirectories);
});
}
}
/**
* Selects and reveal the file element provided by the given resource if its found in the explorer. Will try to
* resolve the path from the disk in case the explorer is not yet expanded to the file yet.
*/
public select(resource: URI, reveal: boolean = this.autoReveal): Promise<void> {
// Require valid path
if (!resource) {
return Promise.resolve(void 0);
}
// If path already selected, just reveal and return
const selection = this.hasSingleSelection(resource);
if (selection) {
return reveal ? this.reveal(selection, 0.5) : Promise.resolve(void 0);
}
// First try to get the stat object from the input to avoid a roundtrip
if (!this.isCreated) {
return Promise.resolve(void 0);
}
const fileStat = this.model.findClosest(resource);
if (fileStat) {
return this.doSelect(fileStat, reveal);
}
// Stat needs to be resolved first and then revealed
const options: IResolveFileOptions = { resolveTo: [resource] };
const workspaceFolder = this.contextService.getWorkspaceFolder(resource);
const rootUri = workspaceFolder ? workspaceFolder.uri : this.model.roots[0].resource;
return this.fileService.resolveFile(rootUri, options).then(stat => {
// Convert to model
const root = this.model.roots.filter(r => r.resource.toString() === rootUri.toString()).pop();
const modelStat = ExplorerItem.create(stat, root, options.resolveTo);
// Update Input with disk Stat
ExplorerItem.mergeLocalWithDisk(modelStat, root);
// Select and Reveal
return this.explorerViewer.refresh(root).then(() => this.doSelect(root.find(resource), reveal));
}, e => { this.notificationService.error(e); });
}
private hasSingleSelection(resource: URI): ExplorerItem {
const currentSelection: ExplorerItem[] = this.explorerViewer.getSelection();
return currentSelection.length === 1 && currentSelection[0].resource.toString() === resource.toString()
? currentSelection[0]
: undefined;
}
private doSelect(fileStat: ExplorerItem, reveal: boolean): Promise<void> {
if (!fileStat) {
return Promise.resolve(void 0);
}
// Special case: we are asked to reveal and select an element that is not visible
// In this case we take the parent element so that we are at least close to it.
if (!this.filter.isVisible(this.tree, fileStat)) {
fileStat = fileStat.parent;
if (!fileStat) {
return Promise.resolve(void 0);
}
}
// Reveal depending on flag
let revealPromise: Promise<void>;
if (reveal) {
revealPromise = this.reveal(fileStat, 0.5);
} else {
revealPromise = Promise.resolve(void 0);
}
return revealPromise.then(() => {
if (!fileStat.isDirectory) {
this.explorerViewer.setSelection([fileStat]); // Since folders can not be opened, only select files
}
this.explorerViewer.setFocus(fileStat);
});
}
private reveal(element: any, relativeTop?: number): Promise<void> {
if (!this.tree) {
return Promise.resolve(void 0); // return early if viewlet has not yet been created
}
return this.tree.reveal(element, relativeTop);
}
saveState(): void {
// Keep list of expanded folders to restore on next load
if (this.isCreated) {
const expanded = this.explorerViewer.getExpandedElements()
.filter(e => e instanceof ExplorerItem)
.map((e: ExplorerItem) => e.resource.toString());
if (expanded.length) {
this.viewState[ExplorerView.MEMENTO_EXPANDED_FOLDER_RESOURCES] = expanded;
} else {
delete this.viewState[ExplorerView.MEMENTO_EXPANDED_FOLDER_RESOURCES];
}
}
// Clean up last focused if not set
if (!this.viewState[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE]) {
delete this.viewState[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE];
}
super.saveState();
}
dispose(): void {
this.isDisposed = true;
if (this.dragHandler) {
this.dragHandler.dispose();
}
super.dispose();
}
}
| src/vs/workbench/parts/files/electron-browser/views/explorerView.ts | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.00025514408480376005,
0.00017346661479678005,
0.00016220146790146828,
0.00017337444296572357,
0.000008627564966445789
] |
{
"id": 4,
"code_window": [
"\t\t\treturn thread.fetchCallStack(1).then(() => {\n",
"\t\t\t\tif (!this.schedulers.has(thread.getId())) {\n",
"\t\t\t\t\tthis.schedulers.set(thread.getId(), new RunOnceScheduler(() => {\n",
"\t\t\t\t\t\tthread.fetchCallStack(19).then(() => this._onDidChangeCallStack.fire());\n",
"\t\t\t\t\t}, 420));\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\tthread.fetchCallStack(19).then(() => this._onDidChangeCallStack.fire(thread));\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 821
} | /*---------------------------------------------------------------------------------------------
* 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!./linesDecorations';
import { DecorationToRender, DedupOverlay } from 'vs/editor/browser/viewParts/glyphMargin/glyphMargin';
import { RenderingContext } from 'vs/editor/common/view/renderingContext';
import { ViewContext } from 'vs/editor/common/view/viewContext';
import * as viewEvents from 'vs/editor/common/view/viewEvents';
export class LinesDecorationsOverlay extends DedupOverlay {
private _context: ViewContext;
private _decorationsLeft: number;
private _decorationsWidth: number;
private _renderResult: string[] | null;
constructor(context: ViewContext) {
super();
this._context = context;
this._decorationsLeft = this._context.configuration.editor.layoutInfo.decorationsLeft;
this._decorationsWidth = this._context.configuration.editor.layoutInfo.decorationsWidth;
this._renderResult = null;
this._context.addEventHandler(this);
}
public dispose(): void {
this._context.removeEventHandler(this);
this._renderResult = null;
super.dispose();
}
// --- begin event handlers
public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean {
if (e.layoutInfo) {
this._decorationsLeft = this._context.configuration.editor.layoutInfo.decorationsLeft;
this._decorationsWidth = this._context.configuration.editor.layoutInfo.decorationsWidth;
}
return true;
}
public onDecorationsChanged(e: viewEvents.ViewDecorationsChangedEvent): boolean {
return true;
}
public onFlushed(e: viewEvents.ViewFlushedEvent): boolean {
return true;
}
public onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean {
return true;
}
public onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): boolean {
return true;
}
public onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): boolean {
return true;
}
public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean {
return e.scrollTopChanged;
}
public onZonesChanged(e: viewEvents.ViewZonesChangedEvent): boolean {
return true;
}
// --- end event handlers
protected _getDecorations(ctx: RenderingContext): DecorationToRender[] {
let decorations = ctx.getDecorationsInViewport();
let r: DecorationToRender[] = [], rLen = 0;
for (let i = 0, len = decorations.length; i < len; i++) {
let d = decorations[i];
let linesDecorationsClassName = d.options.linesDecorationsClassName;
if (linesDecorationsClassName) {
r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, linesDecorationsClassName);
}
}
return r;
}
public prepareRender(ctx: RenderingContext): void {
let visibleStartLineNumber = ctx.visibleRange.startLineNumber;
let visibleEndLineNumber = ctx.visibleRange.endLineNumber;
let toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
let left = this._decorationsLeft.toString();
let width = this._decorationsWidth.toString();
let common = '" style="left:' + left + 'px;width:' + width + 'px;"></div>';
let output: string[] = [];
for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
let lineIndex = lineNumber - visibleStartLineNumber;
let classNames = toRender[lineIndex];
let lineOutput = '';
for (let i = 0, len = classNames.length; i < len; i++) {
lineOutput += '<div class="cldr ' + classNames[i] + common;
}
output[lineIndex] = lineOutput;
}
this._renderResult = output;
}
public render(startLineNumber: number, lineNumber: number): string {
if (!this._renderResult) {
return '';
}
return this._renderResult[lineNumber - startLineNumber];
}
} | src/vs/editor/browser/viewParts/linesDecorations/linesDecorations.ts | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.00017614031094126403,
0.00017191442020703107,
0.0001638593676034361,
0.00017310288967564702,
0.0000035396590192249278
] |
{
"id": 4,
"code_window": [
"\t\t\treturn thread.fetchCallStack(1).then(() => {\n",
"\t\t\t\tif (!this.schedulers.has(thread.getId())) {\n",
"\t\t\t\t\tthis.schedulers.set(thread.getId(), new RunOnceScheduler(() => {\n",
"\t\t\t\t\t\tthread.fetchCallStack(19).then(() => this._onDidChangeCallStack.fire());\n",
"\t\t\t\t\t}, 420));\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\tthread.fetchCallStack(19).then(() => this._onDidChangeCallStack.fire(thread));\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 821
} | [
{
"c": "function",
"t": "source.ts meta.function.ts storage.type.function.ts",
"r": {
"dark_plus": "storage.type: #569CD6",
"light_plus": "storage.type: #0000FF",
"dark_vs": "storage.type: #569CD6",
"light_vs": "storage.type: #0000FF",
"hc_black": "storage.type: #569CD6"
}
},
{
"c": "*",
"t": "source.ts meta.function.ts keyword.generator.asterisk.ts",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ",
"t": "source.ts meta.function.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "foo2",
"t": "source.ts meta.function.ts meta.definition.function.ts entity.name.function.ts",
"r": {
"dark_plus": "entity.name.function: #DCDCAA",
"light_plus": "entity.name.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.function: #DCDCAA"
}
},
{
"c": "(",
"t": "source.ts meta.function.ts meta.parameters.ts punctuation.definition.parameters.begin.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": ")",
"t": "source.ts meta.function.ts meta.parameters.ts punctuation.definition.parameters.end.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.ts meta.function.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "{",
"t": "source.ts meta.function.ts meta.block.ts punctuation.definition.block.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\t",
"t": "source.ts meta.function.ts meta.block.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "yield",
"t": "source.ts meta.function.ts meta.block.ts keyword.control.flow.ts",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": " ",
"t": "source.ts meta.function.ts meta.block.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "'",
"t": "source.ts meta.function.ts meta.block.ts string.quoted.single.ts punctuation.definition.string.begin.ts",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "bar",
"t": "source.ts meta.function.ts meta.block.ts string.quoted.single.ts",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "'",
"t": "source.ts meta.function.ts meta.block.ts string.quoted.single.ts punctuation.definition.string.end.ts",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": ";",
"t": "source.ts meta.function.ts meta.block.ts punctuation.terminator.statement.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\t",
"t": "source.ts meta.function.ts meta.block.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "yield",
"t": "source.ts meta.function.ts meta.block.ts keyword.control.flow.ts",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": "*",
"t": "source.ts meta.function.ts meta.block.ts keyword.generator.asterisk.ts",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ",
"t": "source.ts meta.function.ts meta.block.ts meta.array.literal.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "[",
"t": "source.ts meta.function.ts meta.block.ts meta.array.literal.ts meta.brace.square.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "'",
"t": "source.ts meta.function.ts meta.block.ts meta.array.literal.ts string.quoted.single.ts punctuation.definition.string.begin.ts",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "bar",
"t": "source.ts meta.function.ts meta.block.ts meta.array.literal.ts string.quoted.single.ts",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "'",
"t": "source.ts meta.function.ts meta.block.ts meta.array.literal.ts string.quoted.single.ts punctuation.definition.string.end.ts",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "]",
"t": "source.ts meta.function.ts meta.block.ts meta.array.literal.ts meta.brace.square.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": ";",
"t": "source.ts meta.function.ts meta.block.ts punctuation.terminator.statement.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "}",
"t": "source.ts meta.function.ts meta.block.ts punctuation.definition.block.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
}
] | extensions/typescript-basics/test/colorize-results/test-issue5465_ts.json | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.0001771875686245039,
0.00017527012096252292,
0.0001739755825838074,
0.0001751256495481357,
9.813488759391475e-7
] |
{
"id": 5,
"code_window": [
"\t\t\t\t}\n",
"\n",
"\t\t\t\tthis.schedulers.get(thread.getId()).schedule();\n",
"\t\t\t\tthis._onDidChangeCallStack.fire();\n",
"\t\t\t});\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tthis._onDidChangeCallStack.fire(thread);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 826
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI as uri } from 'vs/base/common/uri';
import * as resources from 'vs/base/common/resources';
import * as lifecycle from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
import { generateUuid } from 'vs/base/common/uuid';
import { RunOnceScheduler } from 'vs/base/common/async';
import severity from 'vs/base/common/severity';
import { isObject, isString, isUndefinedOrNull } from 'vs/base/common/types';
import { distinct } from 'vs/base/common/arrays';
import { Range, IRange } from 'vs/editor/common/core/range';
import {
ITreeElement, IExpression, IExpressionContainer, IDebugSession, IStackFrame, IExceptionBreakpoint, IBreakpoint, IFunctionBreakpoint, IDebugModel, IReplElementSource,
IThread, IRawModelUpdate, IScope, IRawStoppedDetails, IEnablement, IBreakpointData, IExceptionInfo, IReplElement, IBreakpointsChangeEvent, IBreakpointUpdateData, IBaseBreakpoint, State
} from 'vs/workbench/parts/debug/common/debug';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { commonSuffixLength } from 'vs/base/common/strings';
import { sep } from 'vs/base/common/paths';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
export class SimpleReplElement implements IReplElement {
constructor(
private id: string,
public value: string,
public severity: severity,
public sourceData: IReplElementSource,
) { }
toString(): string {
return this.value;
}
getId(): string {
return this.id;
}
}
export class RawObjectReplElement implements IExpression {
private static readonly MAX_CHILDREN = 1000; // upper bound of children per value
constructor(private id: string, public name: string, public valueObj: any, public sourceData?: IReplElementSource, public annotation?: string) { }
getId(): string {
return this.id;
}
get value(): string {
if (this.valueObj === null) {
return 'null';
} else if (Array.isArray(this.valueObj)) {
return `Array[${this.valueObj.length}]`;
} else if (isObject(this.valueObj)) {
return 'Object';
} else if (isString(this.valueObj)) {
return `"${this.valueObj}"`;
}
return String(this.valueObj) || '';
}
get hasChildren(): boolean {
return (Array.isArray(this.valueObj) && this.valueObj.length > 0) || (isObject(this.valueObj) && Object.getOwnPropertyNames(this.valueObj).length > 0);
}
getChildren(): Promise<IExpression[]> {
let result: IExpression[] = [];
if (Array.isArray(this.valueObj)) {
result = (<any[]>this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN)
.map((v, index) => new RawObjectReplElement(`${this.id}:${index}`, String(index), v));
} else if (isObject(this.valueObj)) {
result = Object.getOwnPropertyNames(this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN)
.map((key, index) => new RawObjectReplElement(`${this.id}:${index}`, key, this.valueObj[key]));
}
return Promise.resolve(result);
}
toString(): string {
return `${this.name}\n${this.value}`;
}
}
export class ExpressionContainer implements IExpressionContainer {
public static allValues: Map<string, string> = new Map<string, string>();
// Use chunks to support variable paging #9537
private static readonly BASE_CHUNK_SIZE = 100;
public valueChanged: boolean;
private _value: string;
protected children: Promise<IExpression[]>;
constructor(
protected session: IDebugSession,
private _reference: number,
private id: string,
public namedVariables = 0,
public indexedVariables = 0,
private startOfVariables = 0
) { }
get reference(): number {
return this._reference;
}
set reference(value: number) {
this._reference = value;
this.children = undefined; // invalidate children cache
}
getChildren(): Promise<IExpression[]> {
if (!this.children) {
this.children = this.doGetChildren();
}
return this.children;
}
private doGetChildren(): Promise<IExpression[]> {
if (!this.hasChildren) {
return Promise.resolve([]);
}
if (!this.getChildrenInChunks) {
return this.fetchVariables(undefined, undefined, undefined);
}
// Check if object has named variables, fetch them independent from indexed variables #9670
const childrenThenable = !!this.namedVariables ? this.fetchVariables(undefined, undefined, 'named') : Promise.resolve([]);
return childrenThenable.then(childrenArray => {
// Use a dynamic chunk size based on the number of elements #9774
let chunkSize = ExpressionContainer.BASE_CHUNK_SIZE;
while (this.indexedVariables > chunkSize * ExpressionContainer.BASE_CHUNK_SIZE) {
chunkSize *= ExpressionContainer.BASE_CHUNK_SIZE;
}
if (this.indexedVariables > chunkSize) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const numberOfChunks = Math.ceil(this.indexedVariables / chunkSize);
for (let i = 0; i < numberOfChunks; i++) {
const start = this.startOfVariables + i * chunkSize;
const count = Math.min(chunkSize, this.indexedVariables - i * chunkSize);
childrenArray.push(new Variable(this.session, this, this.reference, `[${start}..${start + count - 1}]`, '', '', null, count, { kind: 'virtual' }, null, true, start));
}
return childrenArray;
}
return this.fetchVariables(this.startOfVariables, this.indexedVariables, 'indexed')
.then(variables => childrenArray.concat(variables));
});
}
getId(): string {
return this.id;
}
get value(): string {
return this._value;
}
get hasChildren(): boolean {
// only variables with reference > 0 have children.
return this.reference > 0;
}
private fetchVariables(start: number, count: number, filter: 'indexed' | 'named'): Promise<Variable[]> {
return this.session.variables(this.reference, filter, start, count).then(response => {
return response && response.body && response.body.variables
? distinct(response.body.variables.filter(v => !!v && isString(v.name)), v => v.name).map(
v => new Variable(this.session, this, v.variablesReference, v.name, v.evaluateName, v.value, v.namedVariables, v.indexedVariables, v.presentationHint, v.type))
: [];
}, (e: Error) => [new Variable(this.session, this, 0, e.message, e.message, '', 0, 0, { kind: 'virtual' }, null, false)]);
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.indexedVariables;
}
set value(value: string) {
this._value = value;
this.valueChanged = ExpressionContainer.allValues.get(this.getId()) &&
ExpressionContainer.allValues.get(this.getId()) !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues.get(this.getId()) !== value;
ExpressionContainer.allValues.set(this.getId(), value);
}
toString(): string {
return this.value;
}
}
export class Expression extends ExpressionContainer implements IExpression {
static DEFAULT_VALUE = nls.localize('notAvailable', "not available");
public available: boolean;
public type: string;
constructor(public name: string, id = generateUuid()) {
super(null, 0, id);
this.available = false;
// name is not set if the expression is just being added
// in that case do not set default value to prevent flashing #14499
if (name) {
this.value = Expression.DEFAULT_VALUE;
}
}
evaluate(session: IDebugSession, stackFrame: IStackFrame, context: string): Promise<void> {
if (!session || (!stackFrame && context !== 'repl')) {
this.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate expressions") : Expression.DEFAULT_VALUE;
this.available = false;
this.reference = 0;
return Promise.resolve(void 0);
}
this.session = session;
return session.evaluate(this.name, stackFrame ? stackFrame.frameId : undefined, context).then(response => {
this.available = !!(response && response.body);
if (response && response.body) {
this.value = response.body.result;
this.reference = response.body.variablesReference;
this.namedVariables = response.body.namedVariables;
this.indexedVariables = response.body.indexedVariables;
this.type = response.body.type;
}
}, err => {
this.value = err.message;
this.available = false;
this.reference = 0;
});
}
toString(): string {
return `${this.name}\n${this.value}`;
}
}
export class Variable extends ExpressionContainer implements IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
session: IDebugSession,
public parent: IExpressionContainer,
reference: number,
public name: string,
public evaluateName: string,
value: string,
namedVariables: number,
indexedVariables: number,
public presentationHint: DebugProtocol.VariablePresentationHint,
public type: string | null = null,
public available = true,
startOfVariables = 0
) {
super(session, reference, `variable:${parent.getId()}:${name}`, namedVariables, indexedVariables, startOfVariables);
this.value = value;
}
setVariable(value: string): Promise<any> {
return this.session.setVariable((<ExpressionContainer>this.parent).reference, this.name, value).then(response => {
if (response && response.body) {
this.value = response.body.value;
this.type = response.body.type || this.type;
this.reference = response.body.variablesReference;
this.namedVariables = response.body.namedVariables;
this.indexedVariables = response.body.indexedVariables;
}
}, err => {
this.errorMessage = err.message;
});
}
toString(): string {
return `${this.name}: ${this.value}`;
}
}
export class Scope extends ExpressionContainer implements IScope {
constructor(
stackFrame: IStackFrame,
index: number,
public name: string,
reference: number,
public expensive: boolean,
namedVariables: number,
indexedVariables: number,
public range?: IRange
) {
super(stackFrame.thread.session, reference, `scope:${stackFrame.getId()}:${name}:${index}`, namedVariables, indexedVariables);
}
toString(): string {
return this.name;
}
}
export class StackFrame implements IStackFrame {
private scopes: Promise<Scope[]>;
constructor(
public thread: IThread,
public frameId: number,
public source: Source,
public name: string,
public presentationHint: string,
public range: IRange,
private index: number
) {
this.scopes = null;
}
getId(): string {
return `stackframe:${this.thread.getId()}:${this.frameId}:${this.index}`;
}
getScopes(): Promise<IScope[]> {
if (!this.scopes) {
this.scopes = this.thread.session.scopes(this.frameId).then(response => {
return response && response.body && response.body.scopes ?
response.body.scopes.map((rs, index) => new Scope(this, index, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables,
rs.line && rs.column && rs.endLine && rs.endColumn ? new Range(rs.line, rs.column, rs.endLine, rs.endColumn) : null)) : [];
}, err => []);
}
return this.scopes;
}
getSpecificSourceName(): 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>this.thread).getStaleCallStack();
callStack = callStack.length > 0 ? callStack : this.thread.getCallStack();
const otherSources = callStack.map(sf => sf.source).filter(s => s !== this.source);
let suffixLength = 0;
otherSources.forEach(s => {
if (s.name === this.source.name) {
suffixLength = Math.max(suffixLength, commonSuffixLength(this.source.uri.path, s.uri.path));
}
});
if (suffixLength === 0) {
return this.source.name;
}
const from = Math.max(0, this.source.uri.path.lastIndexOf(sep, this.source.uri.path.length - suffixLength - 1));
return (from > 0 ? '...' : '') + this.source.uri.path.substr(from);
}
getMostSpecificScopes(range: IRange): Promise<IScope[]> {
return this.getScopes().then(scopes => {
scopes = scopes.filter(s => !s.expensive);
const haveRangeInfo = scopes.some(s => !!s.range);
if (!haveRangeInfo) {
return scopes;
}
const scopesContainingRange = scopes.filter(scope => scope.range && Range.containsRange(scope.range, range))
.sort((first, second) => (first.range.endLineNumber - first.range.startLineNumber) - (second.range.endLineNumber - second.range.startLineNumber));
return scopesContainingRange.length ? scopesContainingRange : scopes;
});
}
restart(): Promise<void> {
return this.thread.session.restartFrame(this.frameId, this.thread.threadId);
}
toString(): string {
return `${this.name} (${this.source.inMemory ? this.source.name : this.source.uri.fsPath}:${this.range.startLineNumber})`;
}
openInEditor(editorService: IEditorService, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): Promise<any> {
return !this.source.available ? Promise.resolve(null) :
this.source.openInEditor(editorService, this.range, preserveFocus, sideBySide, pinned);
}
}
export class Thread implements IThread {
private callStack: IStackFrame[];
private staleCallStack: IStackFrame[];
public stoppedDetails: IRawStoppedDetails;
public stopped: boolean;
constructor(public session: IDebugSession, public name: string, public threadId: number) {
this.stoppedDetails = null;
this.callStack = [];
this.staleCallStack = [];
this.stopped = false;
}
getId(): string {
return `thread:${this.session.getId()}:${this.threadId}`;
}
clearCallStack(): void {
if (this.callStack.length) {
this.staleCallStack = this.callStack;
}
this.callStack = [];
}
getCallStack(): IStackFrame[] {
return this.callStack;
}
getStaleCallStack(): ReadonlyArray<IStackFrame> {
return this.staleCallStack;
}
/**
* Queries the debug adapter for the callstack and returns a promise
* which completes once the call stack has been retrieved.
* If the thread is not stopped, it returns a promise to an empty array.
* Only fetches the first stack frame for performance reasons. Calling this method consecutive times
* gets the remainder of the call stack.
*/
fetchCallStack(levels = 20): Promise<void> {
if (!this.stopped) {
return Promise.resolve(void 0);
}
const start = this.callStack.length;
return this.getCallStackImpl(start, levels).then(callStack => {
if (start < this.callStack.length) {
// Set the stack frames for exact position we requested. To make sure no concurrent requests create duplicate stack frames #30660
this.callStack.splice(start, this.callStack.length - start);
}
this.callStack = this.callStack.concat(callStack || []);
});
}
private getCallStackImpl(startFrame: number, levels: number): Promise<IStackFrame[]> {
return this.session.stackTrace(this.threadId, startFrame, levels).then(response => {
if (!response || !response.body) {
return [];
}
if (this.stoppedDetails) {
this.stoppedDetails.totalFrames = response.body.totalFrames;
}
return response.body.stackFrames.map((rsf, index) => {
const source = this.session.getSource(rsf.source);
return new StackFrame(this, rsf.id, source, rsf.name, rsf.presentationHint, new Range(
rsf.line,
rsf.column,
rsf.endLine,
rsf.endColumn
), startFrame + index);
});
}, (err: Error) => {
if (this.stoppedDetails) {
this.stoppedDetails.framesErrorMessage = err.message;
}
return [];
});
}
/**
* Returns exception info promise if the exception was thrown, otherwise null
*/
get exceptionInfo(): Promise<IExceptionInfo | null> {
if (this.stoppedDetails && this.stoppedDetails.reason === 'exception') {
if (this.session.capabilities.supportsExceptionInfoRequest) {
return this.session.exceptionInfo(this.threadId);
}
return Promise.resolve({
description: this.stoppedDetails.text,
breakMode: null
});
}
return Promise.resolve(null);
}
next(): Promise<any> {
return this.session.next(this.threadId);
}
stepIn(): Promise<any> {
return this.session.stepIn(this.threadId);
}
stepOut(): Promise<any> {
return this.session.stepOut(this.threadId);
}
stepBack(): Promise<any> {
return this.session.stepBack(this.threadId);
}
continue(): Promise<any> {
return this.session.continue(this.threadId);
}
pause(): Promise<any> {
return this.session.pause(this.threadId);
}
terminate(): Promise<any> {
return this.session.terminateThreads([this.threadId]);
}
reverseContinue(): Promise<any> {
return this.session.reverseContinue(this.threadId);
}
}
export class Enablement implements IEnablement {
constructor(
public enabled: boolean,
private id: string
) { }
getId(): string {
return this.id;
}
}
export class BaseBreakpoint extends Enablement implements IBaseBreakpoint {
private sessionData = new Map<string, DebugProtocol.Breakpoint>();
private sessionId: string;
constructor(
enabled: boolean,
public hitCondition: string,
public condition: string,
public logMessage: string,
id: string
) {
super(enabled, id);
if (enabled === undefined) {
this.enabled = true;
}
}
protected getSessionData() {
return this.sessionData.get(this.sessionId);
}
setSessionData(sessionId: string, data: DebugProtocol.Breakpoint): void {
this.sessionData.set(sessionId, data);
}
setSessionId(sessionId: string): void {
this.sessionId = sessionId;
}
get verified(): boolean {
const data = this.getSessionData();
return data ? data.verified : true;
}
get idFromAdapter(): number {
const data = this.getSessionData();
return data ? data.id : undefined;
}
toJSON(): any {
const result = Object.create(null);
result.enabled = this.enabled;
result.condition = this.condition;
result.hitCondition = this.hitCondition;
result.logMessage = this.logMessage;
return result;
}
}
export class Breakpoint extends BaseBreakpoint implements IBreakpoint {
constructor(
public uri: uri,
private _lineNumber: number,
private _column: number,
enabled: boolean,
condition: string,
hitCondition: string,
logMessage: string,
private _adapterData: any,
private textFileService: ITextFileService,
id = generateUuid()
) {
super(enabled, hitCondition, condition, logMessage, id);
}
get lineNumber(): number {
const data = this.getSessionData();
return this.verified && data && typeof data.line === 'number' ? data.line : this._lineNumber;
}
get verified(): boolean {
const data = this.getSessionData();
if (data) {
return data.verified && !this.textFileService.isDirty(this.uri);
}
return true;
}
get column(): number {
const data = this.getSessionData();
// Only respect the column if the user explictly set the column to have an inline breakpoint
return data && typeof data.column === 'number' && typeof this._column === 'number' ? data.column : this._column;
}
get message(): string {
const data = this.getSessionData();
if (!data) {
return undefined;
}
if (this.textFileService.isDirty(this.uri)) {
return nls.localize('breakpointDirtydHover', "Unverified breakpoint. File is modified, please restart debug session.");
}
return data.message;
}
get adapterData(): any {
const data = this.getSessionData();
return data && data.source && data.source.adapterData ? data.source.adapterData : this._adapterData;
}
get endLineNumber(): number {
const data = this.getSessionData();
return data ? data.endLine : undefined;
}
get endColumn(): number {
const data = this.getSessionData();
return data ? data.endColumn : undefined;
}
toJSON(): any {
const result = super.toJSON();
result.uri = this.uri;
result.lineNumber = this._lineNumber;
result.column = this._column;
result.adapterData = this.adapterData;
return result;
}
toString(): string {
return resources.basenameOrAuthority(this.uri);
}
update(data: IBreakpointUpdateData): void {
if (!isUndefinedOrNull(data.lineNumber)) {
this._lineNumber = data.lineNumber;
}
if (!isUndefinedOrNull(data.column)) {
this._column = data.column;
}
if (!isUndefinedOrNull(data.condition)) {
this.condition = data.condition;
}
if (!isUndefinedOrNull(data.hitCondition)) {
this.hitCondition = data.hitCondition;
}
if (!isUndefinedOrNull(data.logMessage)) {
this.logMessage = data.logMessage;
}
}
}
export class FunctionBreakpoint extends BaseBreakpoint implements IFunctionBreakpoint {
constructor(
public name: string,
enabled: boolean,
hitCondition: string,
condition: string,
logMessage: string,
id = generateUuid()
) {
super(enabled, hitCondition, condition, logMessage, id);
}
toJSON(): any {
const result = super.toJSON();
result.name = this.name;
return result;
}
toString(): string {
return this.name;
}
}
export class ExceptionBreakpoint extends Enablement implements IExceptionBreakpoint {
constructor(public filter: string, public label: string, enabled: boolean) {
super(enabled, generateUuid());
}
toJSON(): any {
const result = Object.create(null);
result.filter = this.filter;
result.label = this.label;
result.enabled = this.enabled;
return result;
}
toString(): string {
return this.label;
}
}
export class ThreadAndSessionIds implements ITreeElement {
constructor(public sessionId: string, public threadId: number) { }
getId(): string {
return `${this.sessionId}:${this.threadId}`;
}
}
export class DebugModel implements IDebugModel {
private sessions: IDebugSession[];
private toDispose: lifecycle.IDisposable[];
private schedulers = new Map<string, RunOnceScheduler>();
private breakpointsSessionId: string;
private readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent>;
private readonly _onDidChangeCallStack: Emitter<void>;
private readonly _onDidChangeWatchExpressions: Emitter<IExpression>;
constructor(
private breakpoints: Breakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: FunctionBreakpoint[],
private exceptionBreakpoints: ExceptionBreakpoint[],
private watchExpressions: Expression[],
private textFileService: ITextFileService
) {
this.sessions = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<IBreakpointsChangeEvent>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<IExpression>();
}
getId(): string {
return 'root';
}
getSessions(includeInactive = false): IDebugSession[] {
// By default do not return inactive sesions.
// However we are still holding onto inactive sessions due to repl and debug service session revival (eh scenario)
return this.sessions.filter(s => includeInactive || s.state !== State.Inactive);
}
addSession(session: IDebugSession): void {
this.sessions = this.sessions.filter(s => {
if (s.getId() === session.getId()) {
// Make sure to de-dupe if a session is re-intialized. In case of EH debugging we are adding a session again after an attach.
return false;
}
if (s.state === State.Inactive && s.getLabel() === session.getLabel()) {
// Make sure to remove all inactive sessions that are using the same configuration as the new session
return false;
}
return true;
});
this.sessions.push(session);
this._onDidChangeCallStack.fire();
}
get onDidChangeBreakpoints(): Event<IBreakpointsChangeEvent> {
return this._onDidChangeBreakpoints.event;
}
get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
get onDidChangeWatchExpressions(): Event<IExpression> {
return this._onDidChangeWatchExpressions.event;
}
rawUpdate(data: IRawModelUpdate): void {
let session = this.sessions.filter(p => p.getId() === data.sessionId).pop();
if (session) {
session.rawUpdate(data);
this._onDidChangeCallStack.fire();
}
}
clearThreads(id: string, removeThreads: boolean, reference: number | undefined = undefined): void {
const session = this.sessions.filter(p => p.getId() === id).pop();
this.schedulers.forEach(scheduler => scheduler.dispose());
this.schedulers.clear();
if (session) {
session.clearThreads(removeThreads, reference);
this._onDidChangeCallStack.fire();
}
}
fetchCallStack(thread: Thread): Promise<void> {
if (thread.session.capabilities.supportsDelayedStackTraceLoading) {
// For improved performance load the first stack frame and then load the rest async.
return thread.fetchCallStack(1).then(() => {
if (!this.schedulers.has(thread.getId())) {
this.schedulers.set(thread.getId(), new RunOnceScheduler(() => {
thread.fetchCallStack(19).then(() => this._onDidChangeCallStack.fire());
}, 420));
}
this.schedulers.get(thread.getId()).schedule();
this._onDidChangeCallStack.fire();
});
}
return thread.fetchCallStack();
}
getBreakpoints(filter?: { uri?: uri, lineNumber?: number, column?: number, enabledOnly?: boolean }): IBreakpoint[] {
if (filter) {
const uriStr = filter.uri ? filter.uri.toString() : undefined;
return this.breakpoints.filter(bp => {
if (uriStr && bp.uri.toString() !== uriStr) {
return false;
}
if (filter.lineNumber && bp.lineNumber !== filter.lineNumber) {
return false;
}
if (filter.column && bp.column !== filter.column) {
return false;
}
if (filter.enabledOnly && (!this.breakpointsActivated || !bp.enabled)) {
return false;
}
return true;
});
}
return this.breakpoints;
}
getFunctionBreakpoints(): IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
getExceptionBreakpoints(): IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
if (this.exceptionBreakpoints.length === data.length && this.exceptionBreakpoints.every((exbp, i) => exbp.filter === data[i].filter && exbp.label === data[i].label)) {
// No change
return;
}
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
this._onDidChangeBreakpoints.fire();
}
}
areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
addBreakpoints(uri: uri, rawData: IBreakpointData[], fireEvent = true): IBreakpoint[] {
const newBreakpoints = rawData.map(rawBp => new Breakpoint(uri, rawBp.lineNumber, rawBp.column, rawBp.enabled, rawBp.condition, rawBp.hitCondition, rawBp.logMessage, undefined, this.textFileService, rawBp.id));
newBreakpoints.forEach(bp => bp.setSessionId(this.breakpointsSessionId));
this.breakpoints = this.breakpoints.concat(newBreakpoints);
this.breakpointsActivated = true;
this.sortAndDeDup();
if (fireEvent) {
this._onDidChangeBreakpoints.fire({ added: newBreakpoints });
}
return newBreakpoints;
}
removeBreakpoints(toRemove: IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire({ removed: toRemove });
}
updateBreakpoints(data: { [id: string]: IBreakpointUpdateData }): void {
const updated: IBreakpoint[] = [];
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.update(bpData);
updated.push(bp);
}
});
this.sortAndDeDup();
this._onDidChangeBreakpoints.fire({ changed: updated });
}
setBreakpointSessionData(sessionId: string, data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.setSessionData(sessionId, bpData);
}
});
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.setSessionData(sessionId, fbpData);
}
});
this._onDidChangeBreakpoints.fire({
sessionOnly: true
});
}
setBreakpointsSessionId(sessionId: string): void {
this.breakpointsSessionId = sessionId;
this.breakpoints.forEach(bp => bp.setSessionId(sessionId));
this.functionBreakpoints.forEach(fbp => fbp.setSessionId(sessionId));
this._onDidChangeBreakpoints.fire({
sessionOnly: true
});
}
private sortAndDeDup(): void {
this.breakpoints = this.breakpoints.sort((first, second) => {
if (first.uri.toString() !== second.uri.toString()) {
return resources.basenameOrAuthority(first.uri).localeCompare(resources.basenameOrAuthority(second.uri));
}
if (first.lineNumber === second.lineNumber) {
return first.column - second.column;
}
return first.lineNumber - second.lineNumber;
});
this.breakpoints = distinct(this.breakpoints, bp => `${bp.uri.toString()}:${bp.lineNumber}:${bp.column}`);
}
setEnablement(element: IEnablement, enable: boolean): void {
if (element instanceof Breakpoint || element instanceof FunctionBreakpoint || element instanceof ExceptionBreakpoint) {
const changed: Array<IBreakpoint | IFunctionBreakpoint> = [];
if (element.enabled !== enable && (element instanceof Breakpoint || element instanceof FunctionBreakpoint)) {
changed.push(element);
}
element.enabled = enable;
this._onDidChangeBreakpoints.fire({ changed: changed });
}
}
enableOrDisableAllBreakpoints(enable: boolean): void {
const changed: Array<IBreakpoint | IFunctionBreakpoint> = [];
this.breakpoints.forEach(bp => {
if (bp.enabled !== enable) {
changed.push(bp);
}
bp.enabled = enable;
});
this.functionBreakpoints.forEach(fbp => {
if (fbp.enabled !== enable) {
changed.push(fbp);
}
fbp.enabled = enable;
});
this._onDidChangeBreakpoints.fire({ changed: changed });
}
addFunctionBreakpoint(functionName: string, id: string): IFunctionBreakpoint {
const newFunctionBreakpoint = new FunctionBreakpoint(functionName, true, undefined, undefined, undefined, id);
this.functionBreakpoints.push(newFunctionBreakpoint);
this._onDidChangeBreakpoints.fire({ added: [newFunctionBreakpoint] });
return newFunctionBreakpoint;
}
renameFunctionBreakpoint(id: string, name: string): void {
const functionBreakpoint = this.functionBreakpoints.filter(fbp => fbp.getId() === id).pop();
if (functionBreakpoint) {
functionBreakpoint.name = name;
this._onDidChangeBreakpoints.fire({ changed: [functionBreakpoint] });
}
}
removeFunctionBreakpoints(id?: string): void {
let removed: IFunctionBreakpoint[];
if (id) {
removed = this.functionBreakpoints.filter(fbp => fbp.getId() === id);
this.functionBreakpoints = this.functionBreakpoints.filter(fbp => fbp.getId() !== id);
} else {
removed = this.functionBreakpoints;
this.functionBreakpoints = [];
}
this._onDidChangeBreakpoints.fire({ removed: removed });
}
getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
addWatchExpression(name: string): IExpression {
const we = new Expression(name);
this.watchExpressions.push(we);
this._onDidChangeWatchExpressions.fire(we);
return we;
}
renameWatchExpression(id: string, newName: string): void {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
this._onDidChangeWatchExpressions.fire(filtered[0]);
}
}
removeWatchExpressions(id: string | null = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
moveWatchExpression(id: string, position: number): void {
const we = this.watchExpressions.filter(we => we.getId() === id).pop();
this.watchExpressions = this.watchExpressions.filter(we => we.getId() !== id);
this.watchExpressions = this.watchExpressions.slice(0, position).concat(we, this.watchExpressions.slice(position));
this._onDidChangeWatchExpressions.fire();
}
sourceIsNotAvailable(uri: uri): void {
this.sessions.forEach(s => {
const source = s.getSourceForUri(uri);
if (source) {
source.available = false;
}
});
this._onDidChangeCallStack.fire();
}
dispose(): void {
// Make sure to shutdown each session, such that no debugged process is left laying around
this.sessions.forEach(s => s.shutdown());
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.4180372357368469,
0.004968319088220596,
0.00016263355792034417,
0.00017252491670660675,
0.04010140895843506
] |
{
"id": 5,
"code_window": [
"\t\t\t\t}\n",
"\n",
"\t\t\t\tthis.schedulers.get(thread.getId()).schedule();\n",
"\t\t\t\tthis._onDidChangeCallStack.fire();\n",
"\t\t\t});\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tthis._onDidChangeCallStack.fire(thread);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 826
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { generateUuid } from 'vs/base/common/uuid';
import { join } from 'path';
import { tmpdir } from 'os';
import { mkdirp, del } from 'vs/base/node/pfs';
export interface ITestFileResult {
testFile: string;
cleanUp: () => Promise<void>;
}
export function testFile(folder: string, file: string): Promise<ITestFileResult> {
const id = generateUuid();
const parentDir = join(tmpdir(), 'vsctests', id);
const newDir = join(parentDir, 'config', id);
const testFile = join(newDir, 'config.json');
return mkdirp(newDir, 493).then(() => {
return {
testFile,
cleanUp: () => del(parentDir, tmpdir())
} as ITestFileResult;
});
}
| src/vs/base/test/node/utils.ts | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.00017485384887550026,
0.0001726648333715275,
0.00017136520182248205,
0.00017177549307234585,
0.000001556894062559877
] |
{
"id": 5,
"code_window": [
"\t\t\t\t}\n",
"\n",
"\t\t\t\tthis.schedulers.get(thread.getId()).schedule();\n",
"\t\t\t\tthis._onDidChangeCallStack.fire();\n",
"\t\t\t});\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tthis._onDidChangeCallStack.fire(thread);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 826
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { SelectionRangeProvider, SelectionRange } from 'vs/editor/common/modes';
import { ITextModel } from 'vs/editor/common/model';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { CharCode } from 'vs/base/common/charCode';
import { isUpperAsciiLetter, isLowerAsciiLetter } from 'vs/base/common/strings';
export class WordSelectionRangeProvider implements SelectionRangeProvider {
provideSelectionRanges(model: ITextModel, position: Position): SelectionRange[] {
let result: SelectionRange[] = [];
this._addInWordRanges(result, model, position);
this._addWordRanges(result, model, position);
this._addLineRanges(result, model, position);
result.push({ range: model.getFullModelRange(), kind: 'statement.all' });
return result;
}
private _addInWordRanges(bucket: SelectionRange[], model: ITextModel, pos: Position): void {
const obj = model.getWordAtPosition(pos);
if (!obj) {
return;
}
let { word, startColumn } = obj;
let offset = pos.column - startColumn;
let lastCh: number = 0;
for (; offset < word.length; offset++) {
let ch = word.charCodeAt(offset);
if (isUpperAsciiLetter(ch) && isLowerAsciiLetter(lastCh)) {
// fooBar
// ^^^
// ^^^^^^
bucket.push({ range: new Range(pos.lineNumber, startColumn, pos.lineNumber, startColumn + offset), kind: 'statement.word.part' });
} else if (ch === CharCode.Underline && lastCh !== CharCode.Underline) {
// foo_bar
// ^^^
// ^^^^^^^
bucket.push({ range: new Range(pos.lineNumber, startColumn, pos.lineNumber, startColumn + offset), kind: 'statement.word.part' });
offset += 1;
}
lastCh = ch;
}
}
private _addWordRanges(bucket: SelectionRange[], model: ITextModel, pos: Position): void {
const word = model.getWordAtPosition(pos);
if (word) {
bucket.push({ range: new Range(pos.lineNumber, word.startColumn, pos.lineNumber, word.endColumn), kind: 'statement.word' });
}
}
private _addLineRanges(bucket: SelectionRange[], model: ITextModel, pos: Position): void {
const nonWhitespaceColumn = model.getLineFirstNonWhitespaceColumn(pos.lineNumber);
if (nonWhitespaceColumn > 0) {
bucket.push({ range: new Range(pos.lineNumber, nonWhitespaceColumn, pos.lineNumber, model.getLineLastNonWhitespaceColumn(pos.lineNumber)), kind: 'statement.line' });
}
bucket.push({ range: new Range(pos.lineNumber, model.getLineMinColumn(pos.lineNumber), pos.lineNumber, model.getLineMaxColumn(pos.lineNumber)), kind: 'statement.line.full' });
}
}
| src/vs/editor/contrib/smartSelect/wordSelections.ts | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.00017578377446625382,
0.00017324231157545,
0.0001700128777883947,
0.00017345513333566487,
0.000001723588411550736
] |
{
"id": 5,
"code_window": [
"\t\t\t\t}\n",
"\n",
"\t\t\t\tthis.schedulers.get(thread.getId()).schedule();\n",
"\t\t\t\tthis._onDidChangeCallStack.fire();\n",
"\t\t\t});\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tthis._onDidChangeCallStack.fire(thread);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 826
} | {
// Each snippet is defined under a snippet name and has a scope, prefix, body and
// description. The scope defines in watch languages the snippet is applicable. The prefix is what is
// used to trigger the snippet and the body will be expanded and inserted.Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders.
// Placeholders with the same ids are connected.
// Example:
"MSFT Copyright Header": {
"scope": "javascript,typescript,css",
"prefix": [
"header",
"stub",
"copyright"
],
"body": [
"/*---------------------------------------------------------------------------------------------",
" * Copyright (c) Microsoft Corporation. All rights reserved.",
" * Licensed under the MIT License. See License.txt in the project root for license information.",
" *--------------------------------------------------------------------------------------------*/",
"",
"$0"
],
"description": "Insert Copyright Statement"
},
"TS -> Inject Service": {
"description": "Constructor Injection Pattern",
"prefix": "@inject",
"body": "@$1 private readonly _$2: ${1},$0"
},
"TS -> Event & Emitter": {
"prefix": "emitter",
"description": "Add emitter and event properties",
"body": [
"private readonly _onDid$1 = new Emitter<$2>();",
"readonly onDid$1: Event<$2> = this._onDid$1.event;"
],
}
}
| .vscode/shared.code-snippets | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.0001728290953906253,
0.0001704189635347575,
0.0001677803520578891,
0.00017053319606930017,
0.0000018054736301564844
] |
{
"id": 6,
"code_window": [
"\t\t\t\t\tthis.model.fetchCallStack(<Thread>thread).then(() => {\n",
"\t\t\t\t\t\tif (!event.body.preserveFocusHint && thread.getCallStack().length) {\n",
"\t\t\t\t\t\t\tthis.debugService.focusStackFrame(undefined, thread);\n",
"\t\t\t\t\t\t\tif (thread.stoppedDetails) {\n",
"\t\t\t\t\t\t\t\tif (this.configurationService.getValue<IDebugConfiguration>('debug').openDebug === 'openOnDebugBreak') {\n",
"\t\t\t\t\t\t\t\t\tthis.viewletService.openViewlet(VIEWLET_ID);\n",
"\t\t\t\t\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\tif (!this.debugService.getViewModel().focusedStackFrame) {\n",
"\t\t\t\t\t\t\t\t// There were no appropriate stack frames to focus.\n",
"\t\t\t\t\t\t\t\t// We need to listen on additional stack frame fetching and try to refocus #65012\n",
"\t\t\t\t\t\t\t\tconst listener = this.model.onDidChangeCallStack(t => {\n",
"\t\t\t\t\t\t\t\t\tif (t && t.getId() === thread.getId()) {\n",
"\t\t\t\t\t\t\t\t\t\tdispose(listener);\n",
"\t\t\t\t\t\t\t\t\t\tthis.debugService.focusStackFrame(undefined, thread);\n",
"\t\t\t\t\t\t\t\t\t}\n",
"\t\t\t\t\t\t\t\t});\n",
"\t\t\t\t\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugSession.ts",
"type": "add",
"edit_start_line_idx": 613
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI as uri } from 'vs/base/common/uri';
import severity from 'vs/base/common/severity';
import { Event } from 'vs/base/common/event';
import { IJSONSchemaSnippet } from 'vs/base/common/jsonSchema';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { ITextModel as EditorIModel } from 'vs/editor/common/model';
import { IEditor } from 'vs/workbench/common/editor';
import { Position } from 'vs/editor/common/core/position';
import { CompletionItem } from 'vs/editor/common/modes';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { Range, IRange } from 'vs/editor/common/core/range';
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IDisposable } from 'vs/base/common/lifecycle';
import { IViewContainersRegistry, ViewContainer, Extensions as ViewContainerExtensions } from 'vs/workbench/common/views';
import { Registry } from 'vs/platform/registry/common/platform';
import { TaskIdentifier } from 'vs/workbench/parts/tasks/common/tasks';
import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService';
import { IOutputService } from 'vs/workbench/parts/output/common/output';
export const VIEWLET_ID = 'workbench.view.debug';
export const VIEW_CONTAINER: ViewContainer = Registry.as<IViewContainersRegistry>(ViewContainerExtensions.ViewContainersRegistry).registerViewContainer(VIEWLET_ID);
export const VARIABLES_VIEW_ID = 'workbench.debug.variablesView';
export const WATCH_VIEW_ID = 'workbench.debug.watchExpressionsView';
export const CALLSTACK_VIEW_ID = 'workbench.debug.callStackView';
export const LOADED_SCRIPTS_VIEW_ID = 'workbench.debug.loadedScriptsView';
export const BREAKPOINTS_VIEW_ID = 'workbench.debug.breakPointsView';
export const REPL_ID = 'workbench.panel.repl';
export const DEBUG_SERVICE_ID = 'debugService';
export const CONTEXT_DEBUG_TYPE = new RawContextKey<string>('debugType', undefined);
export const CONTEXT_DEBUG_CONFIGURATION_TYPE = new RawContextKey<string>('debugConfigurationType', undefined);
export const CONTEXT_DEBUG_STATE = new RawContextKey<string>('debugState', 'inactive');
export const CONTEXT_IN_DEBUG_MODE = new RawContextKey<boolean>('inDebugMode', false);
export const CONTEXT_IN_DEBUG_REPL = new RawContextKey<boolean>('inDebugRepl', false);
export const CONTEXT_BREAKPOINT_WIDGET_VISIBLE = new RawContextKey<boolean>('breakpointWidgetVisible', false);
export const CONTEXT_IN_BREAKPOINT_WIDGET = new RawContextKey<boolean>('inBreakpointWidget', false);
export const CONTEXT_BREAKPOINTS_FOCUSED = new RawContextKey<boolean>('breakpointsFocused', true);
export const CONTEXT_WATCH_EXPRESSIONS_FOCUSED = new RawContextKey<boolean>('watchExpressionsFocused', true);
export const CONTEXT_VARIABLES_FOCUSED = new RawContextKey<boolean>('variablesFocused', true);
export const CONTEXT_EXPRESSION_SELECTED = new RawContextKey<boolean>('expressionSelected', false);
export const CONTEXT_BREAKPOINT_SELECTED = new RawContextKey<boolean>('breakpointSelected', false);
export const CONTEXT_CALLSTACK_ITEM_TYPE = new RawContextKey<string>('callStackItemType', undefined);
export const CONTEXT_LOADED_SCRIPTS_SUPPORTED = new RawContextKey<boolean>('loadedScriptsSupported', false);
export const CONTEXT_LOADED_SCRIPTS_ITEM_TYPE = new RawContextKey<string>('loadedScriptsItemType', undefined);
export const EDITOR_CONTRIBUTION_ID = 'editor.contrib.debug';
export const DEBUG_SCHEME = 'debug';
export const INTERNAL_CONSOLE_OPTIONS_SCHEMA = {
enum: ['neverOpen', 'openOnSessionStart', 'openOnFirstSessionStart'],
default: 'openOnFirstSessionStart',
description: nls.localize('internalConsoleOptions', "Controls when the internal debug console should open.")
};
// raw
export interface IRawModelUpdate {
threadId: number;
sessionId: string;
thread?: DebugProtocol.Thread;
callStack?: DebugProtocol.StackFrame[];
stoppedDetails?: IRawStoppedDetails;
}
export interface IRawStoppedDetails {
reason: string;
description?: string;
threadId?: number;
text?: string;
totalFrames?: number;
allThreadsStopped?: boolean;
framesErrorMessage?: string;
}
// model
export interface ITreeElement {
getId(): string;
}
export interface IReplElement extends ITreeElement {
toString(): string;
readonly sourceData?: IReplElementSource;
}
export interface IReplElementSource {
readonly source: Source;
readonly lineNumber: number;
readonly column: number;
}
export interface IExpressionContainer extends ITreeElement {
readonly hasChildren: boolean;
getChildren(): Promise<IExpression[]>;
}
export interface IExpression extends IReplElement, IExpressionContainer {
name: string;
readonly value: string;
readonly valueChanged?: boolean;
readonly type?: string;
}
export interface IDebugger {
createDebugAdapter(session: IDebugSession, outputService: IOutputService): Promise<IDebugAdapter>;
runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments): Promise<number | undefined>;
getCustomTelemetryService(): Promise<TelemetryService>;
}
export const enum State {
Inactive,
Initializing,
Stopped,
Running
}
export function getStateLabel(state: State): string {
switch (state) {
case State.Initializing: return 'initializing';
case State.Stopped: return 'stopped';
case State.Running: return 'running';
default: return 'inactive';
}
}
export class AdapterEndEvent {
error?: Error;
sessionLengthInSeconds: number;
emittedStopped: boolean;
}
export interface LoadedSourceEvent {
reason: 'new' | 'changed' | 'removed';
source: Source;
}
export interface IDebugSession extends ITreeElement {
readonly configuration: IConfig;
readonly unresolvedConfiguration: IConfig;
readonly state: State;
readonly root: IWorkspaceFolder;
getLabel(): string;
getSourceForUri(modelUri: uri): Source;
getSource(raw: DebugProtocol.Source): Source;
setConfiguration(configuration: { resolved: IConfig, unresolved: IConfig }): void;
rawUpdate(data: IRawModelUpdate): void;
getThread(threadId: number): IThread;
getAllThreads(): IThread[];
clearThreads(removeThreads: boolean, reference?: number): void;
getReplElements(): IReplElement[];
removeReplExpressions(): void;
addReplExpression(stackFrame: IStackFrame, name: string): Promise<void>;
appendToRepl(data: string | IExpression, severity: severity, source?: IReplElementSource): void;
logToRepl(sev: severity, args: any[], frame?: { uri: uri, line: number, column: number });
// session events
readonly onDidEndAdapter: Event<AdapterEndEvent>;
readonly onDidChangeState: Event<void>;
readonly onDidChangeReplElements: Event<void>;
// DA capabilities
readonly capabilities: DebugProtocol.Capabilities;
// DAP events
readonly onDidLoadedSource: Event<LoadedSourceEvent>;
readonly onDidCustomEvent: Event<DebugProtocol.Event>;
// Disconnects and clears state. Session can be initialized again for a new connection.
shutdown(): void;
// DAP request
initialize(dbgr: IDebugger): Promise<void>;
launchOrAttach(config: IConfig): Promise<void>;
restart(): Promise<void>;
terminate(restart?: boolean /* false */): Promise<void>;
disconnect(restart?: boolean /* false */): Promise<void>;
sendBreakpoints(modelUri: uri, bpts: IBreakpoint[], sourceModified: boolean): Promise<void>;
sendFunctionBreakpoints(fbps: IFunctionBreakpoint[]): Promise<void>;
sendExceptionBreakpoints(exbpts: IExceptionBreakpoint[]): Promise<void>;
stackTrace(threadId: number, startFrame: number, levels: number): Promise<DebugProtocol.StackTraceResponse>;
exceptionInfo(threadId: number): Promise<IExceptionInfo>;
scopes(frameId: number): Promise<DebugProtocol.ScopesResponse>;
variables(variablesReference: number, filter: 'indexed' | 'named', start: number, count: number): Promise<DebugProtocol.VariablesResponse>;
evaluate(expression: string, frameId?: number, context?: string): Promise<DebugProtocol.EvaluateResponse>;
customRequest(request: string, args: any): Promise<DebugProtocol.Response>;
restartFrame(frameId: number, threadId: number): Promise<void>;
next(threadId: number): Promise<void>;
stepIn(threadId: number): Promise<void>;
stepOut(threadId: number): Promise<void>;
stepBack(threadId: number): Promise<void>;
continue(threadId: number): Promise<void>;
reverseContinue(threadId: number): Promise<void>;
pause(threadId: number): Promise<void>;
terminateThreads(threadIds: number[]): Promise<void>;
completions(frameId: number, text: string, position: Position, overwriteBefore: number): Promise<CompletionItem[]>;
setVariable(variablesReference: number, name: string, value: string): Promise<DebugProtocol.SetVariableResponse>;
loadSource(resource: uri): Promise<DebugProtocol.SourceResponse>;
getLoadedSources(): Promise<Source[]>;
}
export interface IThread extends ITreeElement {
/**
* Process the thread belongs to
*/
readonly session: IDebugSession;
/**
* Id of the thread generated by the debug adapter backend.
*/
readonly threadId: number;
/**
* Name of the thread.
*/
readonly name: string;
/**
* Information about the current thread stop event. Null if thread is not stopped.
*/
readonly stoppedDetails: IRawStoppedDetails;
/**
* Information about the exception if an 'exception' stopped event raised and DA supports the 'exceptionInfo' request, otherwise null.
*/
readonly exceptionInfo: Promise<IExceptionInfo>;
/**
* Gets the callstack if it has already been received from the debug
* adapter, otherwise it returns null.
*/
getCallStack(): ReadonlyArray<IStackFrame>;
/**
* Invalidates the callstack cache
*/
clearCallStack(): void;
/**
* Indicates whether this thread is stopped. The callstack for stopped
* threads can be retrieved from the debug adapter.
*/
readonly stopped: boolean;
next(): Promise<any>;
stepIn(): Promise<any>;
stepOut(): Promise<any>;
stepBack(): Promise<any>;
continue(): Promise<any>;
pause(): Promise<any>;
terminate(): Promise<any>;
reverseContinue(): Promise<any>;
}
export interface IScope extends IExpressionContainer {
readonly name: string;
readonly expensive: boolean;
readonly range?: IRange;
}
export interface IStackFrame extends ITreeElement {
readonly thread: IThread;
readonly name: string;
readonly presentationHint: string;
readonly frameId: number;
readonly range: IRange;
readonly source: Source;
getScopes(): Promise<IScope[]>;
getMostSpecificScopes(range: IRange): Promise<ReadonlyArray<IScope>>;
getSpecificSourceName(): string;
restart(): Promise<any>;
toString(): string;
openInEditor(editorService: IEditorService, preserveFocus?: boolean, sideBySide?: boolean): Promise<any>;
}
export interface IEnablement extends ITreeElement {
readonly enabled: boolean;
}
export interface IBreakpointData {
readonly id?: string;
readonly lineNumber: number;
readonly column?: number;
readonly enabled?: boolean;
readonly condition?: string;
readonly logMessage?: string;
readonly hitCondition?: string;
}
export interface IBreakpointUpdateData {
readonly condition?: string;
readonly hitCondition?: string;
readonly logMessage?: string;
readonly lineNumber?: number;
readonly column?: number;
}
export interface IBaseBreakpoint extends IEnablement {
readonly condition: string;
readonly hitCondition: string;
readonly logMessage: string;
readonly verified: boolean;
readonly idFromAdapter: number;
}
export interface IBreakpoint extends IBaseBreakpoint {
readonly uri: uri;
readonly lineNumber: number;
readonly endLineNumber?: number;
readonly column: number;
readonly endColumn?: number;
readonly message: string;
readonly adapterData: any;
}
export interface IFunctionBreakpoint extends IBaseBreakpoint {
readonly name: string;
}
export interface IExceptionBreakpoint extends IEnablement {
readonly filter: string;
readonly label: string;
}
export interface IExceptionInfo {
readonly id?: string;
readonly description?: string;
readonly breakMode: string;
readonly details?: DebugProtocol.ExceptionDetails;
}
// model interfaces
export interface IViewModel extends ITreeElement {
/**
* Returns the focused debug session or null if no session is stopped.
*/
readonly focusedSession: IDebugSession;
/**
* Returns the focused thread or null if no thread is stopped.
*/
readonly focusedThread: IThread;
/**
* Returns the focused stack frame or null if there are no stack frames.
*/
readonly focusedStackFrame: IStackFrame;
getSelectedExpression(): IExpression;
getSelectedFunctionBreakpoint(): IFunctionBreakpoint;
setSelectedExpression(expression: IExpression): void;
setSelectedFunctionBreakpoint(functionBreakpoint: IFunctionBreakpoint): void;
isMultiSessionView(): boolean;
onDidFocusSession: Event<IDebugSession | undefined>;
onDidFocusStackFrame: Event<{ stackFrame: IStackFrame, explicit: boolean }>;
onDidSelectExpression: Event<IExpression>;
}
export interface IEvaluate {
evaluate(session: IDebugSession, stackFrame: IStackFrame, context: string): Promise<void>;
}
export interface IDebugModel extends ITreeElement {
getSessions(includeInactive?: boolean): IDebugSession[];
getBreakpoints(filter?: { uri?: uri, lineNumber?: number, column?: number, enabledOnly?: boolean }): ReadonlyArray<IBreakpoint>;
areBreakpointsActivated(): boolean;
getFunctionBreakpoints(): ReadonlyArray<IFunctionBreakpoint>;
getExceptionBreakpoints(): ReadonlyArray<IExceptionBreakpoint>;
getWatchExpressions(): ReadonlyArray<IExpression & IEvaluate>;
onDidChangeBreakpoints: Event<IBreakpointsChangeEvent>;
onDidChangeCallStack: Event<void>;
onDidChangeWatchExpressions: Event<IExpression>;
}
/**
* An event describing a change to the set of [breakpoints](#debug.Breakpoint).
*/
export interface IBreakpointsChangeEvent {
added?: Array<IBreakpoint | IFunctionBreakpoint>;
removed?: Array<IBreakpoint | IFunctionBreakpoint>;
changed?: Array<IBreakpoint | IFunctionBreakpoint>;
sessionOnly?: boolean;
}
// Debug configuration interfaces
export interface IDebugConfiguration {
allowBreakpointsEverywhere: boolean;
openDebug: 'neverOpen' | 'openOnSessionStart' | 'openOnFirstSessionStart' | 'openOnDebugBreak';
openExplorerOnEnd: boolean;
inlineValues: boolean;
toolBarLocation: 'floating' | 'docked' | 'hidden';
showInStatusBar: 'never' | 'always' | 'onFirstSessionStart';
internalConsoleOptions: 'neverOpen' | 'openOnSessionStart' | 'openOnFirstSessionStart';
extensionHostDebugAdapter: boolean;
enableAllHovers: boolean;
}
export interface IGlobalConfig {
version: string;
compounds: ICompound[];
configurations: IConfig[];
}
export interface IEnvConfig {
internalConsoleOptions?: 'neverOpen' | 'openOnSessionStart' | 'openOnFirstSessionStart';
preLaunchTask?: string | TaskIdentifier;
postDebugTask?: string | TaskIdentifier;
debugServer?: number;
noDebug?: boolean;
}
export interface IConfig extends IEnvConfig {
// fundamental attributes
type: string;
request: string;
name: string;
// platform specifics
windows?: IEnvConfig;
osx?: IEnvConfig;
linux?: IEnvConfig;
// internals
__sessionId?: string;
__restart?: any;
__autoAttach?: boolean;
port?: number; // TODO
}
export interface ICompound {
name: string;
configurations: (string | { name: string, folder: string })[];
}
export interface IDebugAdapter extends IDisposable {
readonly onError: Event<Error>;
readonly onExit: Event<number>;
onRequest(callback: (request: DebugProtocol.Request) => void);
onEvent(callback: (event: DebugProtocol.Event) => void);
startSession(): Promise<void>;
sendMessage(message: DebugProtocol.ProtocolMessage): void;
sendResponse(response: DebugProtocol.Response): void;
sendRequest(command: string, args: any, clb: (result: DebugProtocol.Response) => void, timemout?: number): void;
stopSession(): Promise<void>;
}
export interface IDebugAdapterFactory extends ITerminalLauncher {
createDebugAdapter(session: IDebugSession): IDebugAdapter;
substituteVariables(folder: IWorkspaceFolder, config: IConfig): Promise<IConfig>;
}
export interface IDebugAdapterExecutableOptions {
cwd?: string;
env?: { [key: string]: string };
}
export interface IDebugAdapterExecutable {
readonly type: 'executable';
readonly command: string;
readonly args: string[];
readonly options?: IDebugAdapterExecutableOptions;
}
export interface IDebugAdapterServer {
readonly type: 'server';
readonly port: number;
readonly host?: string;
}
export interface IDebugAdapterImplementation {
readonly type: 'implementation';
readonly implementation: any;
}
export type IAdapterDescriptor = IDebugAdapterExecutable | IDebugAdapterServer | IDebugAdapterImplementation;
export interface IPlatformSpecificAdapterContribution {
program?: string;
args?: string[];
runtime?: string;
runtimeArgs?: string[];
}
export interface IDebuggerContribution extends IPlatformSpecificAdapterContribution {
type?: string;
label?: string;
// debug adapter executable
adapterExecutableCommand?: string;
win?: IPlatformSpecificAdapterContribution;
winx86?: IPlatformSpecificAdapterContribution;
windows?: IPlatformSpecificAdapterContribution;
osx?: IPlatformSpecificAdapterContribution;
linux?: IPlatformSpecificAdapterContribution;
// internal
aiKey?: string;
// supported languages
languages?: string[];
enableBreakpointsFor?: { languageIds: string[] };
// debug configuration support
configurationAttributes?: any;
initialConfigurations?: any[];
configurationSnippets?: IJSONSchemaSnippet[];
variables?: { [key: string]: string };
}
export interface IDebugConfigurationProvider {
readonly type: string;
resolveDebugConfiguration?(folderUri: uri | undefined, debugConfiguration: IConfig): Promise<IConfig>;
provideDebugConfigurations?(folderUri: uri | undefined): Promise<IConfig[]>;
debugAdapterExecutable?(folderUri: uri | undefined): Promise<IAdapterDescriptor>; // TODO@AW legacy
hasTracker: boolean;
}
export interface IDebugAdapterDescriptorFactory {
readonly type: string;
createDebugAdapterDescriptor(session: IDebugSession): Promise<IAdapterDescriptor>;
}
export interface IDebugAdapterTrackerFactory {
readonly type: string;
}
export interface ITerminalLauncher {
runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments, config: ITerminalSettings): Promise<number | undefined>;
}
export interface ITerminalSettings {
external: {
windowsExec: string,
osxExec: string,
linuxExec: string
};
integrated: {
shell: {
osx: string,
windows: string,
linux: string
}
};
}
export interface IConfigurationManager {
/**
* Returns true if breakpoints can be set for a given editor model. Depends on mode.
*/
canSetBreakpointsIn(model: EditorIModel): boolean;
/**
* Returns an object containing the selected launch configuration and the selected configuration name. Both these fields can be null (no folder workspace).
*/
readonly selectedConfiguration: {
launch: ILaunch;
name: string;
};
selectConfiguration(launch: ILaunch, name?: string, debugStarted?: boolean): void;
getLaunches(): ReadonlyArray<ILaunch>;
getLaunch(workspaceUri: uri): ILaunch | undefined;
/**
* Allows to register on change of selected debug configuration.
*/
onDidSelectConfiguration: Event<void>;
activateDebuggers(activationEvent: string, debugType?: string): Promise<void>;
needsToRunInExtHost(debugType: string): boolean;
hasDebugConfigurationProvider(debugType: string): boolean;
registerDebugConfigurationProvider(debugConfigurationProvider: IDebugConfigurationProvider): IDisposable;
unregisterDebugConfigurationProvider(debugConfigurationProvider: IDebugConfigurationProvider): void;
registerDebugAdapterDescriptorFactory(debugAdapterDescriptorFactory: IDebugAdapterDescriptorFactory): IDisposable;
unregisterDebugAdapterDescriptorFactory(debugAdapterDescriptorFactory: IDebugAdapterDescriptorFactory): void;
registerDebugAdapterTrackerFactory(debugAdapterTrackerFactory: IDebugAdapterTrackerFactory): IDisposable;
unregisterDebugAdapterTrackerFactory(debugAdapterTrackerFactory: IDebugAdapterTrackerFactory): void;
resolveConfigurationByProviders(folderUri: uri | undefined, type: string | undefined, debugConfiguration: any): Promise<any>;
getDebugAdapterDescriptor(session: IDebugSession): Promise<IAdapterDescriptor | undefined>;
registerDebugAdapterFactory(debugTypes: string[], debugAdapterFactory: IDebugAdapterFactory): IDisposable;
createDebugAdapter(session: IDebugSession): IDebugAdapter;
substituteVariables(debugType: string, folder: IWorkspaceFolder, config: IConfig): Promise<IConfig>;
runInTerminal(debugType: string, args: DebugProtocol.RunInTerminalRequestArguments, config: ITerminalSettings): Promise<number | undefined>;
}
export interface ILaunch {
/**
* Resource pointing to the launch.json this object is wrapping.
*/
readonly uri: uri;
/**
* Name of the launch.
*/
readonly name: string;
/**
* Workspace of the launch. Can be null.
*/
readonly workspace: IWorkspaceFolder;
/**
* Should this launch be shown in the debug dropdown.
*/
readonly hidden: boolean;
/**
* Returns a configuration with the specified name.
* Returns null if there is no configuration with the specified name.
*/
getConfiguration(name: string): IConfig;
/**
* Returns a compound with the specified name.
* Returns null if there is no compound with the specified name.
*/
getCompound(name: string): ICompound;
/**
* Returns the names of all configurations and compounds.
* Ignores configurations which are invalid.
*/
getConfigurationNames(includeCompounds?: boolean): string[];
/**
* Opens the launch.json file. Creates if it does not exist.
*/
openConfigFile(sideBySide: boolean, preserveFocus: boolean, type?: string): Promise<{ editor: IEditor, created: boolean }>;
}
// Debug service interfaces
export const IDebugService = createDecorator<IDebugService>(DEBUG_SERVICE_ID);
export interface IDebugService {
_serviceBrand: any;
/**
* Gets the current debug state.
*/
readonly state: State;
/**
* Allows to register on debug state changes.
*/
onDidChangeState: Event<State>;
/**
* Allows to register on new session events.
*/
onDidNewSession: Event<IDebugSession>;
/**
* Allows to register on sessions about to be created (not yet fully initialised)
*/
onWillNewSession: Event<IDebugSession>;
/**
* Allows to register on end session events.
*/
onDidEndSession: Event<IDebugSession>;
/**
* Gets the current configuration manager.
*/
getConfigurationManager(): IConfigurationManager;
/**
* Sets the focused stack frame and evaluates all expressions against the newly focused stack frame,
*/
focusStackFrame(focusedStackFrame: IStackFrame, thread?: IThread, session?: IDebugSession, explicit?: boolean): void;
/**
* Adds new breakpoints to the model for the file specified with the uri. Notifies debug adapter of breakpoint changes.
*/
addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]>;
/**
* Updates the breakpoints.
*/
updateBreakpoints(uri: uri, data: { [id: string]: IBreakpointUpdateData }, sendOnResourceSaved: boolean): void;
/**
* Enables or disables all breakpoints. If breakpoint is passed only enables or disables the passed breakpoint.
* Notifies debug adapter of breakpoint changes.
*/
enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void>;
/**
* Sets the global activated property for all breakpoints.
* Notifies debug adapter of breakpoint changes.
*/
setBreakpointsActivated(activated: boolean): Promise<void>;
/**
* Removes all breakpoints. If id is passed only removes the breakpoint associated with that id.
* Notifies debug adapter of breakpoint changes.
*/
removeBreakpoints(id?: string): Promise<any>;
/**
* Adds a new function breakpoint for the given name.
*/
addFunctionBreakpoint(name?: string, id?: string): void;
/**
* Renames an already existing function breakpoint.
* Notifies debug adapter of breakpoint changes.
*/
renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void>;
/**
* Removes all function breakpoints. If id is passed only removes the function breakpoint with the passed id.
* Notifies debug adapter of breakpoint changes.
*/
removeFunctionBreakpoints(id?: string): Promise<void>;
/**
* Sends all breakpoints to the passed session.
* If session is not passed, sends all breakpoints to each session.
*/
sendAllBreakpoints(session?: IDebugSession): Promise<any>;
/**
* Adds a new watch expression and evaluates it against the debug adapter.
*/
addWatchExpression(name?: string): void;
/**
* Renames a watch expression and evaluates it against the debug adapter.
*/
renameWatchExpression(id: string, newName: string): void;
/**
* Moves a watch expression to a new possition. Used for reordering watch expressions.
*/
moveWatchExpression(id: string, position: number): void;
/**
* Removes all watch expressions. If id is passed only removes the watch expression with the passed id.
*/
removeWatchExpressions(id?: string): void;
/**
* Starts debugging. If the configOrName is not passed uses the selected configuration in the debug dropdown.
* Also saves all files, manages if compounds are present in the configuration
* and resolveds configurations via DebugConfigurationProviders.
*
* Returns true if the start debugging was successfull. For compound launches, all configurations have to start successfuly for it to return success.
* On errors the startDebugging will throw an error, however some error and cancelations are handled and in that case will simply return false.
*/
startDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug?: boolean): Promise<boolean>;
/**
* Restarts a session or creates a new one if there is no active session.
*/
restartSession(session: IDebugSession, restartData?: any): Promise<any>;
/**
* Stops the session. If the session does not exist then stops all sessions.
*/
stopSession(session: IDebugSession): Promise<any>;
/**
* Makes unavailable all sources with the passed uri. Source will appear as grayed out in callstack view.
*/
sourceIsNotAvailable(uri: uri): void;
/**
* Gets the current debug model.
*/
getModel(): IDebugModel;
/**
* Gets the current view model.
*/
getViewModel(): IViewModel;
}
// Editor interfaces
export const enum BreakpointWidgetContext {
CONDITION = 0,
HIT_COUNT = 1,
LOG_MESSAGE = 2
}
export interface IDebugEditorContribution extends IEditorContribution {
showHover(range: Range, focus: boolean): Promise<void>;
showBreakpointWidget(lineNumber: number, column: number, context?: BreakpointWidgetContext): void;
closeBreakpointWidget(): void;
addLaunchConfiguration(): Promise<any>;
}
| src/vs/workbench/parts/debug/common/debug.ts | 1 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.003486378351226449,
0.00046002017916180193,
0.00016202493861783296,
0.0001733769167913124,
0.0006525799981318414
] |
{
"id": 6,
"code_window": [
"\t\t\t\t\tthis.model.fetchCallStack(<Thread>thread).then(() => {\n",
"\t\t\t\t\t\tif (!event.body.preserveFocusHint && thread.getCallStack().length) {\n",
"\t\t\t\t\t\t\tthis.debugService.focusStackFrame(undefined, thread);\n",
"\t\t\t\t\t\t\tif (thread.stoppedDetails) {\n",
"\t\t\t\t\t\t\t\tif (this.configurationService.getValue<IDebugConfiguration>('debug').openDebug === 'openOnDebugBreak') {\n",
"\t\t\t\t\t\t\t\t\tthis.viewletService.openViewlet(VIEWLET_ID);\n",
"\t\t\t\t\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\tif (!this.debugService.getViewModel().focusedStackFrame) {\n",
"\t\t\t\t\t\t\t\t// There were no appropriate stack frames to focus.\n",
"\t\t\t\t\t\t\t\t// We need to listen on additional stack frame fetching and try to refocus #65012\n",
"\t\t\t\t\t\t\t\tconst listener = this.model.onDidChangeCallStack(t => {\n",
"\t\t\t\t\t\t\t\t\tif (t && t.getId() === thread.getId()) {\n",
"\t\t\t\t\t\t\t\t\t\tdispose(listener);\n",
"\t\t\t\t\t\t\t\t\t\tthis.debugService.focusStackFrame(undefined, thread);\n",
"\t\t\t\t\t\t\t\t\t}\n",
"\t\t\t\t\t\t\t\t});\n",
"\t\t\t\t\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugSession.ts",
"type": "add",
"edit_start_line_idx": 613
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" height="16" width="16"><path fill="#1E1E1E" d="M7.5 2L2 12l2 2h9l2-2L9.5 2z"/><path d="M9 3H8l-4.5 9 1 1h8l1-1L9 3zm0 9H8v-1h1v1zm0-2H8V6h1v4z" fill="#fc0"/><path d="M9 10H8V6h1v4zm0 1H8v1h1v-1z"/></svg> | src/vs/workbench/parts/markers/electron-browser/media/status-warning-inverse.svg | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.0001710157230263576,
0.0001710157230263576,
0.0001710157230263576,
0.0001710157230263576,
0
] |
{
"id": 6,
"code_window": [
"\t\t\t\t\tthis.model.fetchCallStack(<Thread>thread).then(() => {\n",
"\t\t\t\t\t\tif (!event.body.preserveFocusHint && thread.getCallStack().length) {\n",
"\t\t\t\t\t\t\tthis.debugService.focusStackFrame(undefined, thread);\n",
"\t\t\t\t\t\t\tif (thread.stoppedDetails) {\n",
"\t\t\t\t\t\t\t\tif (this.configurationService.getValue<IDebugConfiguration>('debug').openDebug === 'openOnDebugBreak') {\n",
"\t\t\t\t\t\t\t\t\tthis.viewletService.openViewlet(VIEWLET_ID);\n",
"\t\t\t\t\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\tif (!this.debugService.getViewModel().focusedStackFrame) {\n",
"\t\t\t\t\t\t\t\t// There were no appropriate stack frames to focus.\n",
"\t\t\t\t\t\t\t\t// We need to listen on additional stack frame fetching and try to refocus #65012\n",
"\t\t\t\t\t\t\t\tconst listener = this.model.onDidChangeCallStack(t => {\n",
"\t\t\t\t\t\t\t\t\tif (t && t.getId() === thread.getId()) {\n",
"\t\t\t\t\t\t\t\t\t\tdispose(listener);\n",
"\t\t\t\t\t\t\t\t\t\tthis.debugService.focusStackFrame(undefined, thread);\n",
"\t\t\t\t\t\t\t\t\t}\n",
"\t\t\t\t\t\t\t\t});\n",
"\t\t\t\t\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugSession.ts",
"type": "add",
"edit_start_line_idx": 613
} | {
"displayName": "Configuration Editing",
"description": "Provides capabilities (advanced IntelliSense, auto-fixing) in configuration files like settings, launch, and extension recommendation files."
} | extensions/configuration-editing/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.00016648060409352183,
0.00016648060409352183,
0.00016648060409352183,
0.00016648060409352183,
0
] |
{
"id": 6,
"code_window": [
"\t\t\t\t\tthis.model.fetchCallStack(<Thread>thread).then(() => {\n",
"\t\t\t\t\t\tif (!event.body.preserveFocusHint && thread.getCallStack().length) {\n",
"\t\t\t\t\t\t\tthis.debugService.focusStackFrame(undefined, thread);\n",
"\t\t\t\t\t\t\tif (thread.stoppedDetails) {\n",
"\t\t\t\t\t\t\t\tif (this.configurationService.getValue<IDebugConfiguration>('debug').openDebug === 'openOnDebugBreak') {\n",
"\t\t\t\t\t\t\t\t\tthis.viewletService.openViewlet(VIEWLET_ID);\n",
"\t\t\t\t\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\tif (!this.debugService.getViewModel().focusedStackFrame) {\n",
"\t\t\t\t\t\t\t\t// There were no appropriate stack frames to focus.\n",
"\t\t\t\t\t\t\t\t// We need to listen on additional stack frame fetching and try to refocus #65012\n",
"\t\t\t\t\t\t\t\tconst listener = this.model.onDidChangeCallStack(t => {\n",
"\t\t\t\t\t\t\t\t\tif (t && t.getId() === thread.getId()) {\n",
"\t\t\t\t\t\t\t\t\t\tdispose(listener);\n",
"\t\t\t\t\t\t\t\t\t\tthis.debugService.focusStackFrame(undefined, thread);\n",
"\t\t\t\t\t\t\t\t\t}\n",
"\t\t\t\t\t\t\t\t});\n",
"\t\t\t\t\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugSession.ts",
"type": "add",
"edit_start_line_idx": 613
} | /*---------------------------------------------------------------------------------------------
* 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!./goToDefinitionMouse';
import * as nls from 'vs/nls';
import { createCancelablePromise, CancelablePromise } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import { onUnexpectedError } from 'vs/base/common/errors';
import { MarkdownString } from 'vs/base/common/htmlContent';
import { IModeService } from 'vs/editor/common/services/modeService';
import { Range } from 'vs/editor/common/core/range';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { DefinitionProviderRegistry, DefinitionLink } from 'vs/editor/common/modes';
import { ICodeEditor, IMouseTarget, MouseTargetType } from 'vs/editor/browser/editorBrowser';
import { registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import { getDefinitionsAtPosition } from './goToDefinition';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { editorActiveLinkForeground } from 'vs/platform/theme/common/colorRegistry';
import { EditorState, CodeEditorStateFlag } from 'vs/editor/browser/core/editorState';
import { DefinitionAction, DefinitionActionConfig } from './goToDefinitionCommands';
import { ClickLinkGesture, ClickLinkMouseEvent, ClickLinkKeyboardEvent } from 'vs/editor/contrib/goToDefinition/clickLinkGesture';
import { IWordAtPosition, IModelDeltaDecoration, ITextModel, IFoundBracket } from 'vs/editor/common/model';
import { Position } from 'vs/editor/common/core/position';
class GotoDefinitionWithMouseEditorContribution implements editorCommon.IEditorContribution {
private static readonly ID = 'editor.contrib.gotodefinitionwithmouse';
static MAX_SOURCE_PREVIEW_LINES = 8;
private editor: ICodeEditor;
private toUnhook: IDisposable[];
private decorations: string[];
private currentWordUnderMouse: IWordAtPosition;
private previousPromise: CancelablePromise<DefinitionLink[]>;
constructor(
editor: ICodeEditor,
@ITextModelService private textModelResolverService: ITextModelService,
@IModeService private modeService: IModeService
) {
this.toUnhook = [];
this.decorations = [];
this.editor = editor;
this.previousPromise = null;
let linkGesture = new ClickLinkGesture(editor);
this.toUnhook.push(linkGesture);
this.toUnhook.push(linkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
this.startFindDefinition(mouseEvent, keyboardEvent);
}));
this.toUnhook.push(linkGesture.onExecute((mouseEvent: ClickLinkMouseEvent) => {
if (this.isEnabled(mouseEvent)) {
this.gotoDefinition(mouseEvent.target, mouseEvent.hasSideBySideModifier).then(() => {
this.removeDecorations();
}, (error: Error) => {
this.removeDecorations();
onUnexpectedError(error);
});
}
}));
this.toUnhook.push(linkGesture.onCancel(() => {
this.removeDecorations();
this.currentWordUnderMouse = null;
}));
}
private startFindDefinition(mouseEvent: ClickLinkMouseEvent, withKey?: ClickLinkKeyboardEvent): void {
// check if we are active and on a content widget
if (mouseEvent.target.type === MouseTargetType.CONTENT_WIDGET && this.decorations.length > 0) {
return;
}
if (!this.isEnabled(mouseEvent, withKey)) {
this.currentWordUnderMouse = null;
this.removeDecorations();
return;
}
// Find word at mouse position
let position = mouseEvent.target.position;
let word = position ? this.editor.getModel().getWordAtPosition(position) : null;
if (!word) {
this.currentWordUnderMouse = null;
this.removeDecorations();
return;
}
// Return early if word at position is still the same
if (this.currentWordUnderMouse && this.currentWordUnderMouse.startColumn === word.startColumn && this.currentWordUnderMouse.endColumn === word.endColumn && this.currentWordUnderMouse.word === word.word) {
return;
}
this.currentWordUnderMouse = word;
// Find definition and decorate word if found
let state = new EditorState(this.editor, CodeEditorStateFlag.Position | CodeEditorStateFlag.Value | CodeEditorStateFlag.Selection | CodeEditorStateFlag.Scroll);
if (this.previousPromise) {
this.previousPromise.cancel();
this.previousPromise = null;
}
this.previousPromise = createCancelablePromise(token => this.findDefinition(mouseEvent.target, token));
this.previousPromise.then(results => {
if (!results || !results.length || !state.validate(this.editor)) {
this.removeDecorations();
return;
}
// Multiple results
if (results.length > 1) {
this.addDecoration(
new Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn),
new MarkdownString().appendText(nls.localize('multipleResults', "Click to show {0} definitions.", results.length))
);
}
// Single result
else {
let result = results[0];
if (!result.uri) {
return;
}
this.textModelResolverService.createModelReference(result.uri).then(ref => {
if (!ref.object || !ref.object.textEditorModel) {
ref.dispose();
return;
}
const { object: { textEditorModel } } = ref;
const { startLineNumber } = result.range;
if (startLineNumber < 1 || startLineNumber > textEditorModel.getLineCount()) {
// invalid range
ref.dispose();
return;
}
const previewValue = this.getPreviewValue(textEditorModel, startLineNumber);
let wordRange: Range;
if (result.origin) {
wordRange = Range.lift(result.origin);
} else {
wordRange = new Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
}
this.addDecoration(
wordRange,
new MarkdownString().appendCodeblock(this.modeService.getModeIdByFilepathOrFirstLine(textEditorModel.uri.fsPath), previewValue)
);
ref.dispose();
});
}
}).then(undefined, onUnexpectedError);
}
private getPreviewValue(textEditorModel: ITextModel, startLineNumber: number) {
let rangeToUse = this.getPreviewRangeBasedOnBrackets(textEditorModel, startLineNumber);
const numberOfLinesInRange = rangeToUse.endLineNumber - rangeToUse.startLineNumber;
if (numberOfLinesInRange >= GotoDefinitionWithMouseEditorContribution.MAX_SOURCE_PREVIEW_LINES) {
rangeToUse = this.getPreviewRangeBasedOnIndentation(textEditorModel, startLineNumber);
}
const previewValue = this.stripIndentationFromPreviewRange(textEditorModel, startLineNumber, rangeToUse);
return previewValue;
}
private stripIndentationFromPreviewRange(textEditorModel: ITextModel, startLineNumber: number, previewRange: Range) {
const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
let minIndent = startIndent;
for (let endLineNumber = startLineNumber + 1; endLineNumber < previewRange.endLineNumber; endLineNumber++) {
const endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
minIndent = Math.min(minIndent, endIndent);
}
const previewValue = textEditorModel.getValueInRange(previewRange).replace(new RegExp(`^\\s{${minIndent - 1}}`, 'gm'), '').trim();
return previewValue;
}
private getPreviewRangeBasedOnIndentation(textEditorModel: ITextModel, startLineNumber: number) {
const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
const maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionWithMouseEditorContribution.MAX_SOURCE_PREVIEW_LINES);
let endLineNumber = startLineNumber + 1;
for (; endLineNumber < maxLineNumber; endLineNumber++) {
let endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
if (startIndent === endIndent) {
break;
}
}
return new Range(startLineNumber, 1, endLineNumber + 1, 1);
}
private getPreviewRangeBasedOnBrackets(textEditorModel: ITextModel, startLineNumber: number) {
const maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionWithMouseEditorContribution.MAX_SOURCE_PREVIEW_LINES);
const brackets: IFoundBracket[] = [];
let ignoreFirstEmpty = true;
let currentBracket = textEditorModel.findNextBracket(new Position(startLineNumber, 1));
while (currentBracket !== null) {
if (brackets.length === 0) {
brackets.push(currentBracket);
} else {
const lastBracket = brackets[brackets.length - 1];
if (lastBracket.open === currentBracket.open && lastBracket.isOpen && !currentBracket.isOpen) {
brackets.pop();
} else {
brackets.push(currentBracket);
}
if (brackets.length === 0) {
if (ignoreFirstEmpty) {
ignoreFirstEmpty = false;
} else {
return new Range(startLineNumber, 1, currentBracket.range.endLineNumber + 1, 1);
}
}
}
const maxColumn = textEditorModel.getLineMaxColumn(startLineNumber);
let nextLineNumber = currentBracket.range.endLineNumber;
let nextColumn = currentBracket.range.endColumn;
if (maxColumn === currentBracket.range.endColumn) {
nextLineNumber++;
nextColumn = 1;
}
if (nextLineNumber > maxLineNumber) {
return new Range(startLineNumber, 1, maxLineNumber + 1, 1);
}
currentBracket = textEditorModel.findNextBracket(new Position(nextLineNumber, nextColumn));
}
return new Range(startLineNumber, 1, maxLineNumber + 1, 1);
}
private addDecoration(range: Range, hoverMessage: MarkdownString): void {
const newDecorations: IModelDeltaDecoration = {
range: range,
options: {
inlineClassName: 'goto-definition-link',
hoverMessage
}
};
this.decorations = this.editor.deltaDecorations(this.decorations, [newDecorations]);
}
private removeDecorations(): void {
if (this.decorations.length > 0) {
this.decorations = this.editor.deltaDecorations(this.decorations, []);
}
}
private isEnabled(mouseEvent: ClickLinkMouseEvent, withKey?: ClickLinkKeyboardEvent): boolean {
return this.editor.getModel() &&
mouseEvent.isNoneOrSingleMouseDown &&
(mouseEvent.target.type === MouseTargetType.CONTENT_TEXT) &&
(mouseEvent.hasTriggerModifier || (withKey && withKey.keyCodeIsTriggerKey)) &&
DefinitionProviderRegistry.has(this.editor.getModel());
}
private findDefinition(target: IMouseTarget, token: CancellationToken): Promise<DefinitionLink[] | null> {
const model = this.editor.getModel();
if (!model) {
return Promise.resolve(null);
}
return getDefinitionsAtPosition(model, target.position, token);
}
private gotoDefinition(target: IMouseTarget, sideBySide: boolean): Promise<any> {
this.editor.setPosition(target.position);
const action = new DefinitionAction(new DefinitionActionConfig(sideBySide, false, true, false), { alias: undefined, label: undefined, id: undefined, precondition: undefined });
return this.editor.invokeWithinContext(accessor => action.run(accessor, this.editor));
}
public getId(): string {
return GotoDefinitionWithMouseEditorContribution.ID;
}
public dispose(): void {
this.toUnhook = dispose(this.toUnhook);
}
}
registerEditorContribution(GotoDefinitionWithMouseEditorContribution);
registerThemingParticipant((theme, collector) => {
const activeLinkForeground = theme.getColor(editorActiveLinkForeground);
if (activeLinkForeground) {
collector.addRule(`.monaco-editor .goto-definition-link { color: ${activeLinkForeground} !important; }`);
}
});
| src/vs/editor/contrib/goToDefinition/goToDefinitionMouse.ts | 0 | https://github.com/microsoft/vscode/commit/b995df24fa0cf4c3e99463296601e76ae2e3ba73 | [
0.00021689572895411402,
0.00017274839046876878,
0.00016033882275223732,
0.00017164272139780223,
0.000008432483809883706
] |
{
"id": 0,
"code_window": [
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details,\n",
" nature: infos.nature\n",
" }));\n",
"\n",
" // Template: drop the column.\n",
" // Simply make a `delete` template for this attribute wich drop the column\n",
" // with the `./builder/columns/dropColumn` template.\n",
" tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');\n",
" models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n",
" } else {\n",
" // Template: create a new column thanks to the attribute's relation.\n",
" // Simply make a `create` template for this attribute wich will be added\n",
" // to the table template-- either `./builder/tables/selectTable` or\n",
" // `./builder/tables/createTableIfNotExists`.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-generate-migrations/lib/builder/relations.js",
"type": "replace",
"edit_start_line_idx": 78
} | 'use strict';
/**
* Module dependencies
*/
// Node.js core.
const fs = require('fs');
const path = require('path');
// Public node modules.
const _ = require('lodash');
const pluralize = require('pluralize');
// Collections utils.
const utilsModels = require('strapi/lib/configuration/hooks/models/utils/');
const utilsBookShelf = require('strapi-bookshelf/lib/utils/');
/**
* Relationship templates
*/
module.exports = function (models, modelName, details, attribute, toDrop, onlyDrop) {
let tplRelationUp;
let tplRelationDown;
const infos = utilsModels.getNature(details, attribute, models);
_.set(models[modelName].attributes, attribute + '.create', {});
_.set(models[modelName].attributes, attribute + '.delete', {});
// If it's a "one-to-one" relationship.
if (infos.verbose === 'hasOne') {
// Force singular foreign key.
details.attribute = pluralize.singular(details.model);
// Define PK column.
details.column = utilsBookShelf.getPK(modelName, undefined, models);
// Template: create a new column thanks to the attribute's relation.
// Simply make a `create` template for this attribute wich will be added
// to the table template-- either `./builder/tables/selectTable` or
// `./builder/tables/createTableIfNotExists`.
tplRelationUp = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'relations', 'hasOne.template'), 'utf8');
models[modelName].attributes[attribute].create.others = _.unescape(_.template(tplRelationUp)({
tableName: modelName,
attribute: attribute,
details: details
}));
// Template: drop the column.
// Simply make a `delete` template for this attribute wich drop the column
// with the `./builder/columns/dropColumn` template.
tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');
models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({
tableName: modelName,
attribute: attribute,
details: details
}));
} else if (infos.verbose === 'belongsTo') {
// Force singular foreign key.
details.attribute = pluralize.singular(details.model);
// Define PK column.
details.column = utilsBookShelf.getPK(modelName, undefined, models);
if (infos.nature === 'oneToMany' || infos.nature === 'oneWay') {
// Template: create a new column thanks to the attribute's relation.
// Simply make a `create` template for this attribute wich will be added
// to the table template-- either `./builder/tables/selectTable` or
// `./builder/tables/createTableIfNotExists`.
tplRelationUp = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'relations', 'belongsTo.template'), 'utf8');
models[modelName].attributes[attribute].create.others = _.unescape(_.template(tplRelationUp)({
tableName: modelName,
attribute: attribute,
details: details,
nature: infos.nature
}));
// Template: drop the column.
// Simply make a `delete` template for this attribute wich drop the column
// with the `./builder/columns/dropColumn` template.
tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');
models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({
tableName: modelName,
attribute: attribute,
details: details
}));
} else {
// Template: create a new column thanks to the attribute's relation.
// Simply make a `create` template for this attribute wich will be added
// to the table template-- either `./builder/tables/selectTable` or
// `./builder/tables/createTableIfNotExists`.
tplRelationUp = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'relations', 'belongsTo-unique.template'), 'utf8');
models[modelName].attributes[attribute].create.others = _.unescape(_.template(tplRelationUp)({
tableName: modelName,
attribute: attribute,
details: details
}));
// Template: drop the column.
// Simply make a `delete` template for this attribute wich drop the column
// with the `./builder/columns/dropColumn` template.
tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');
models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({
tableName: modelName,
attribute: attribute,
details: details
}));
}
} else if (infos.verbose === 'belongsToMany') {
// Otherwise if it's a "many-to-many" relationship.
// Save the relationship.
const relationship = models[details.collection].attributes[details.via];
// Construct relation table name.
const relationTable = _.map(_.sortBy([relationship, details], 'collection'), function (table) {
return _.snakeCase(pluralize.plural(table.collection) + ' ' + pluralize.plural(table.via));
}).join('__');
// Force singular foreign key.
relationship.attribute = pluralize.singular(relationship.collection);
details.attribute = pluralize.singular(details.collection);
// Define PK column.
details.column = utilsBookShelf.getPK(modelName, undefined, models);
relationship.column = utilsBookShelf.getPK(details.collection, undefined, models);
// Avoid to create table both times.
if (!models.hasOwnProperty(relationTable)) {
// Save the relation table as a new model in the scope
// aiming to benefit of templates for the table such as
// `createTableIfNotExists` and `dropTable`.
models[relationTable] = {};
// Template: create the table for the `up` export if it doesn't exist.
// This adds a `up` logic for the relation table.
const tplTableUp = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'relations', 'belongsToMany.template'), 'utf8');
models[relationTable].up = _.unescape(_.template(tplTableUp)({
models: models,
tableName: relationTable,
details: details,
relationship: relationship
}));
// Template: drop the table for the `down` export.
// This adds a `down` logic for the relation table.
const tplTableDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'tables', 'dropTable.template'), 'utf8');
models[relationTable].down = _.unescape(_.template(tplTableDown)({
tableName: relationTable
}));
}
}
};
| packages/strapi-generate-migrations/lib/builder/relations.js | 1 | https://github.com/strapi/strapi/commit/7367e2ed61a55e811619da278271a30925bf6613 | [
0.9982428550720215,
0.25189247727394104,
0.00017252532416023314,
0.01150878518819809,
0.4067092537879944
] |
{
"id": 0,
"code_window": [
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details,\n",
" nature: infos.nature\n",
" }));\n",
"\n",
" // Template: drop the column.\n",
" // Simply make a `delete` template for this attribute wich drop the column\n",
" // with the `./builder/columns/dropColumn` template.\n",
" tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');\n",
" models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n",
" } else {\n",
" // Template: create a new column thanks to the attribute's relation.\n",
" // Simply make a `create` template for this attribute wich will be added\n",
" // to the table template-- either `./builder/tables/selectTable` or\n",
" // `./builder/tables/createTableIfNotExists`.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-generate-migrations/lib/builder/relations.js",
"type": "replace",
"edit_start_line_idx": 78
} | 'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
/**
* Lusca hook
*/
module.exports = function (strapi) {
const hook = {
/**
* Default options
*/
defaults: {
csrf: false,
csp: false,
p3p: false,
hsts: {
maxAge: 31536000,
includeSubDomains: true
},
xframe: 'SAMEORIGIN',
xssProtection: false
},
/**
* Initialize the hook
*/
initialize: function (cb) {
if (_.isPlainObject(strapi.config.csrf) && !_.isEmpty(strapi.config.csrf)) {
strapi.app.use(strapi.middlewares.lusca.csrf({
key: strapi.config.csrf.key,
secret: strapi.config.csrf.secret
}));
}
if (_.isPlainObject(strapi.config.csp) && !_.isEmpty(strapi.config.csp)) {
strapi.app.use(strapi.middlewares.lusca.csp(strapi.config.csp));
}
if (_.isString(strapi.config.xframe)) {
strapi.app.use(strapi.middlewares.lusca.xframe({
value: strapi.config.xframe
}));
}
if (_.isString(strapi.config.p3p)) {
strapi.app.use(strapi.middlewares.lusca.p3p({
value: strapi.config.p3p
}));
}
if (_.isPlainObject(strapi.config.hsts) && !_.isEmpty(strapi.config.hsts)) {
strapi.app.use(strapi.middlewares.lusca.hsts({
maxAge: strapi.config.hsts.maxAge,
includeSubDomains: strapi.config.hsts.includeSubDomains
}));
}
if (_.isPlainObject(strapi.config.xssProtection) && !_.isEmpty(strapi.config.xssProtection)) {
strapi.app.use(strapi.middlewares.lusca.xssProtection({
enabled: strapi.config.xssProtection.enabled,
mode: strapi.config.xssProtection.mode
}));
}
cb();
}
};
return hook;
};
| packages/strapi/lib/configuration/hooks/lusca/index.js | 0 | https://github.com/strapi/strapi/commit/7367e2ed61a55e811619da278271a30925bf6613 | [
0.0007299125427380204,
0.00026959285605698824,
0.00016448725364170969,
0.000168490078067407,
0.0001976957282749936
] |
{
"id": 0,
"code_window": [
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details,\n",
" nature: infos.nature\n",
" }));\n",
"\n",
" // Template: drop the column.\n",
" // Simply make a `delete` template for this attribute wich drop the column\n",
" // with the `./builder/columns/dropColumn` template.\n",
" tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');\n",
" models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n",
" } else {\n",
" // Template: create a new column thanks to the attribute's relation.\n",
" // Simply make a `create` template for this attribute wich will be added\n",
" // to the table template-- either `./builder/tables/selectTable` or\n",
" // `./builder/tables/createTableIfNotExists`.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-generate-migrations/lib/builder/relations.js",
"type": "replace",
"edit_start_line_idx": 78
} | 'use strict';
/**
* Default `forbidden` response.
*/
module.exports = function forbidden(data) {
// Set the status.
this.status = 403;
// Delete the `data` object if the app is used in production environment.
if (strapi.config.environment === 'production') {
data = '';
}
// Finally send the response.
this.body = data;
};
| packages/strapi/lib/configuration/hooks/responses/responses/forbidden.js | 0 | https://github.com/strapi/strapi/commit/7367e2ed61a55e811619da278271a30925bf6613 | [
0.00016522132500540465,
0.00016443869390059263,
0.0001636560627957806,
0.00016443869390059263,
7.82631104812026e-7
] |
{
"id": 0,
"code_window": [
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details,\n",
" nature: infos.nature\n",
" }));\n",
"\n",
" // Template: drop the column.\n",
" // Simply make a `delete` template for this attribute wich drop the column\n",
" // with the `./builder/columns/dropColumn` template.\n",
" tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');\n",
" models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n",
" } else {\n",
" // Template: create a new column thanks to the attribute's relation.\n",
" // Simply make a `create` template for this attribute wich will be added\n",
" // to the table template-- either `./builder/tables/selectTable` or\n",
" // `./builder/tables/createTableIfNotExists`.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-generate-migrations/lib/builder/relations.js",
"type": "replace",
"edit_start_line_idx": 78
} | 'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
/**
* Proxy hook
*/
module.exports = function (strapi) {
const hook = {
/**
* Default options
*/
defaults: {
proxy: false
},
/**
* Initialize the hook
*/
initialize: function (cb) {
if (_.isString(strapi.config.proxy)) {
strapi.app.use(strapi.middlewares.proxy({
host: strapi.config.proxy
}));
}
cb();
}
};
return hook;
};
| packages/strapi/lib/configuration/hooks/proxy/index.js | 0 | https://github.com/strapi/strapi/commit/7367e2ed61a55e811619da278271a30925bf6613 | [
0.000729910796508193,
0.00028340675635263324,
0.0001637078821659088,
0.00016600046365056187,
0.00022349742357619107
] |
{
"id": 1,
"code_window": [
" models[modelName].attributes[attribute].create.others = _.unescape(_.template(tplRelationUp)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n",
"\n",
" // Template: drop the column.\n",
" // Simply make a `delete` template for this attribute wich drop the column\n",
" // with the `./builder/columns/dropColumn` template.\n",
" tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');\n",
" models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-generate-migrations/lib/builder/relations.js",
"type": "replace",
"edit_start_line_idx": 99
} | 'use strict';
/**
* Module dependencies
*/
// Node.js core.
const fs = require('fs');
const path = require('path');
// Public node modules.
const _ = require('lodash');
const pluralize = require('pluralize');
// Collections utils.
const utilsModels = require('strapi/lib/configuration/hooks/models/utils/');
const utilsBookShelf = require('strapi-bookshelf/lib/utils/');
/**
* Relationship templates
*/
module.exports = function (models, modelName, details, attribute, toDrop, onlyDrop) {
let tplRelationUp;
let tplRelationDown;
const infos = utilsModels.getNature(details, attribute, models);
_.set(models[modelName].attributes, attribute + '.create', {});
_.set(models[modelName].attributes, attribute + '.delete', {});
// If it's a "one-to-one" relationship.
if (infos.verbose === 'hasOne') {
// Force singular foreign key.
details.attribute = pluralize.singular(details.model);
// Define PK column.
details.column = utilsBookShelf.getPK(modelName, undefined, models);
// Template: create a new column thanks to the attribute's relation.
// Simply make a `create` template for this attribute wich will be added
// to the table template-- either `./builder/tables/selectTable` or
// `./builder/tables/createTableIfNotExists`.
tplRelationUp = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'relations', 'hasOne.template'), 'utf8');
models[modelName].attributes[attribute].create.others = _.unescape(_.template(tplRelationUp)({
tableName: modelName,
attribute: attribute,
details: details
}));
// Template: drop the column.
// Simply make a `delete` template for this attribute wich drop the column
// with the `./builder/columns/dropColumn` template.
tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');
models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({
tableName: modelName,
attribute: attribute,
details: details
}));
} else if (infos.verbose === 'belongsTo') {
// Force singular foreign key.
details.attribute = pluralize.singular(details.model);
// Define PK column.
details.column = utilsBookShelf.getPK(modelName, undefined, models);
if (infos.nature === 'oneToMany' || infos.nature === 'oneWay') {
// Template: create a new column thanks to the attribute's relation.
// Simply make a `create` template for this attribute wich will be added
// to the table template-- either `./builder/tables/selectTable` or
// `./builder/tables/createTableIfNotExists`.
tplRelationUp = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'relations', 'belongsTo.template'), 'utf8');
models[modelName].attributes[attribute].create.others = _.unescape(_.template(tplRelationUp)({
tableName: modelName,
attribute: attribute,
details: details,
nature: infos.nature
}));
// Template: drop the column.
// Simply make a `delete` template for this attribute wich drop the column
// with the `./builder/columns/dropColumn` template.
tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');
models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({
tableName: modelName,
attribute: attribute,
details: details
}));
} else {
// Template: create a new column thanks to the attribute's relation.
// Simply make a `create` template for this attribute wich will be added
// to the table template-- either `./builder/tables/selectTable` or
// `./builder/tables/createTableIfNotExists`.
tplRelationUp = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'relations', 'belongsTo-unique.template'), 'utf8');
models[modelName].attributes[attribute].create.others = _.unescape(_.template(tplRelationUp)({
tableName: modelName,
attribute: attribute,
details: details
}));
// Template: drop the column.
// Simply make a `delete` template for this attribute wich drop the column
// with the `./builder/columns/dropColumn` template.
tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');
models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({
tableName: modelName,
attribute: attribute,
details: details
}));
}
} else if (infos.verbose === 'belongsToMany') {
// Otherwise if it's a "many-to-many" relationship.
// Save the relationship.
const relationship = models[details.collection].attributes[details.via];
// Construct relation table name.
const relationTable = _.map(_.sortBy([relationship, details], 'collection'), function (table) {
return _.snakeCase(pluralize.plural(table.collection) + ' ' + pluralize.plural(table.via));
}).join('__');
// Force singular foreign key.
relationship.attribute = pluralize.singular(relationship.collection);
details.attribute = pluralize.singular(details.collection);
// Define PK column.
details.column = utilsBookShelf.getPK(modelName, undefined, models);
relationship.column = utilsBookShelf.getPK(details.collection, undefined, models);
// Avoid to create table both times.
if (!models.hasOwnProperty(relationTable)) {
// Save the relation table as a new model in the scope
// aiming to benefit of templates for the table such as
// `createTableIfNotExists` and `dropTable`.
models[relationTable] = {};
// Template: create the table for the `up` export if it doesn't exist.
// This adds a `up` logic for the relation table.
const tplTableUp = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'relations', 'belongsToMany.template'), 'utf8');
models[relationTable].up = _.unescape(_.template(tplTableUp)({
models: models,
tableName: relationTable,
details: details,
relationship: relationship
}));
// Template: drop the table for the `down` export.
// This adds a `down` logic for the relation table.
const tplTableDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'tables', 'dropTable.template'), 'utf8');
models[relationTable].down = _.unescape(_.template(tplTableDown)({
tableName: relationTable
}));
}
}
};
| packages/strapi-generate-migrations/lib/builder/relations.js | 1 | https://github.com/strapi/strapi/commit/7367e2ed61a55e811619da278271a30925bf6613 | [
0.9980011582374573,
0.29429030418395996,
0.00016545607650186867,
0.004659492988139391,
0.43766549229621887
] |
{
"id": 1,
"code_window": [
" models[modelName].attributes[attribute].create.others = _.unescape(_.template(tplRelationUp)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n",
"\n",
" // Template: drop the column.\n",
" // Simply make a `delete` template for this attribute wich drop the column\n",
" // with the `./builder/columns/dropColumn` template.\n",
" tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');\n",
" models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-generate-migrations/lib/builder/relations.js",
"type": "replace",
"edit_start_line_idx": 99
} | #!/usr/bin/env node
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// Local Strapi dependencies.
const strapi = require('strapi/lib/server');
const packageJSON = require('../package.json');
// Logger.
const logger = require('strapi-utils').logger;
/**
* `$ strapi start`
*
* Expose method which starts the appropriate instance of Strapi
* (fire up the application in our working directory).
*/
module.exports = function () {
// Build initial scope.
const scope = {
rootPath: process.cwd(),
strapiPackageJSON: packageJSON
};
// Use the current directory as application path.
const appPath = process.cwd();
// Use the app's local `strapi` in `node_modules` if it's existant and valid.
const localStrapiPath = path.resolve(appPath, 'node_modules', 'strapi');
if (strapi.isLocalStrapiValid(localStrapiPath, appPath)) {
const localStrapi = require(localStrapiPath);
localStrapi.start(scope, afterwards);
return;
}
// Otherwise, if no workable local `strapi` module exists,
// run the application using the currently running version
// of `strapi`. This is probably always the global install.
const globalStrapi = strapi();
globalStrapi.start(scope, afterwards);
function afterwards(err, strapi) {
if (err) {
const message = err.stack ? err.stack : err;
logger.error(message);
strapi ? strapi.stop() : process.exit(1);
}
}
};
| packages/strapi-cli/bin/strapi-start.js | 0 | https://github.com/strapi/strapi/commit/7367e2ed61a55e811619da278271a30925bf6613 | [
0.0009463414316996932,
0.0002997477422468364,
0.00016605730343144387,
0.00017141300486400723,
0.00028917257441207767
] |
{
"id": 1,
"code_window": [
" models[modelName].attributes[attribute].create.others = _.unescape(_.template(tplRelationUp)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n",
"\n",
" // Template: drop the column.\n",
" // Simply make a `delete` template for this attribute wich drop the column\n",
" // with the `./builder/columns/dropColumn` template.\n",
" tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');\n",
" models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-generate-migrations/lib/builder/relations.js",
"type": "replace",
"edit_start_line_idx": 99
} | 'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// Public node modules.
const fs = require('fs-extra');
// Logger.
const logger = require('strapi-utils').logger;
/**
* Runs after this generator has finished
*
* @param {Object} scope
* @param {Function} cb
*/
module.exports = function afterGenerate(scope, cb) {
process.chdir(scope.rootPath);
// Copy the default files.
fs.copySync(path.resolve(__dirname, '..', 'files'), path.resolve(scope.rootPath));
// Log an info.
logger.warn('Installing dependencies... It might take a few seconds.');
// Create copies to all necessary node modules
// in the `node_modules` directory.
const srcDependencyPath = path.resolve(scope.strapiRoot, 'node_modules');
const destDependencyPath = path.resolve(scope.rootPath, 'node_modules');
fs.copy(srcDependencyPath, destDependencyPath, function (copyLinkErr) {
if (copyLinkErr) {
return cb(copyLinkErr);
}
logger.info('Your new application `' + scope.name + '` is ready at `' + scope.rootPath + '`.');
return cb();
});
};
| packages/strapi-generate-new/lib/after.js | 0 | https://github.com/strapi/strapi/commit/7367e2ed61a55e811619da278271a30925bf6613 | [
0.0008230072562582791,
0.0003763839486055076,
0.00016807769134175032,
0.00017313291027676314,
0.0002666109648998827
] |
{
"id": 1,
"code_window": [
" models[modelName].attributes[attribute].create.others = _.unescape(_.template(tplRelationUp)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n",
"\n",
" // Template: drop the column.\n",
" // Simply make a `delete` template for this attribute wich drop the column\n",
" // with the `./builder/columns/dropColumn` template.\n",
" tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');\n",
" models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-generate-migrations/lib/builder/relations.js",
"type": "replace",
"edit_start_line_idx": 99
} | <!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>Welcome to your Strapi application</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
* {
-webkit-box-sizing: border-box;
}
body, html {
margin: 0;
padding: 40px 0;
}
body {
font: 17px/1.5 "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, Verdana, sans-serif;
background: white;
margin: 0;
color: #33333d;
overflow-y: scroll;
overflow-x: hidden;
}
h1 {
font-size: 1.6em;
margin-top: 0;
}
h2 {
margin-top: 44px;
font-size: 1.3em;
}
h3 {
margin-top: 30px;
font-size: 1em;
}
section {
margin: 0 5.555555555555555%;
}
p {
font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, Verdana, sans-serif;
}
a {
color: #33a0c0;
}
code {
font-family: monospace;
font-size: 1.1em;
}
pre {
background: white;
border-top: 1px solid #eee;
border-bottom: 1px solid #eee;
padding: 25px;
font-family: monospace;
overflow-x: auto;
}
.wrapper {
padding: 0 .75em;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
@media screen and (min-width:40em) {
body {
font-size: 1.0625em;
}
}
@media screen and (min-width:45em) {
body {
font-size: 1em;
}
}
@media screen and (min-width:55.5em) {
body {
font-size: 1.0625em;
}
}
@media screen and (min-width:61.5em) {
body {
font-size: 1em;
}
section {
margin: 0 16.666666666666664%;
}
}
@media screen and (min-width:75em) {
body {
font-size: 1.0625em;
}
}
@media screen and (min-width:87em) {
body {
font-size: 1em;
}
section {
margin: 0 27.77777777777778%;
}
}
@media screen and (min-width:105em) {
body {
font-size: 1.0625em;
}
}
@media screen and (min-width:117em) {
section {
margin: 0 5.555555555555555%;
}
section .wrapper {
width: 37.5%;
margin-left: 25%;
}
}
@media screen and (min-width:130em) {
body {
font-size: 1.125em;
max-width: 160em;
}
}
</style>
</head>
<body lang="en">
<section>
<div class="wrapper">
<h1>Welcome.</h1>
<p>You successfully created your Strapi application.</p>
<p>You are looking at: <code>./public/index.html</code>.</p>
<p>Your built-in admin panel is available at <a href="http://localhost:1337/admin/" target="blank">http://localhost:1337/admin/</a>.
<h2>Create your first API</h2>
<p>The Strapi ecosystem offers you two possibilities to create a complete RESTful API.</p>
<h3>Via the CLI</h3>
<p>Easily generate a complete API with controllers, models and routes using:</p>
<pre><code class="lang-bash">$ strapi generate api <apiName></code></pre>
<p>For example, you can create a <code class="lang-bash">car</code> API with a name (<code class="lang-bash">name</code>), year (<code class="lang-bash">year</code>) and the license plate (<code class="lang-bash">license</code>) with:</p>
<pre><code class="lang-bash">$ strapi generate api car name:string year:integer license:string</code></pre>
<h3>Via the Strapi Studio</h3>
<p>The Strapi Studio allows you to easily build and manage your application environment thanks to a powerful User Interface.</p>
<p>Log into the Strapi Studio with your user account (<a href="http://studio.strapi.io/" target="blank">http://studio.strapi.io</a>) and follow the instructions to start the experience.</p>
<h2>Resources</h2>
<p>You'll probably also want to learn how to customize your application, set up security and configure your data sources.</p>
<p>For more help getting started, check out:
<ul>
<li><a href="http://strapi.io/documentation/introduction" target="blank">Strapi documentation</a></li>
<li><a href="https://github.com/wistityhq/strapi" target="blank">Strapi repository on GitHub</a></li>
<li><a href="https://twitter.com/strapijs" target="blank">Strapi news on Twitter</a></li>
</ul>
</p>
</div>
</section>
</body>
</html>
| packages/strapi-generate-new/files/public/index.html | 0 | https://github.com/strapi/strapi/commit/7367e2ed61a55e811619da278271a30925bf6613 | [
0.0001772029499989003,
0.00017343435320071876,
0.00016741504077799618,
0.00017490466416347772,
0.0000030477172003884334
] |
{
"id": 2,
"code_window": [
" }\n",
" } else if (infos.verbose === 'belongsToMany') {\n",
" // Otherwise if it's a \"many-to-many\" relationship.\n",
"\n",
" // Save the relationship.\n",
" const relationship = models[details.collection].attributes[details.via];\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" // Template: drop the column.\n",
" // Simply make a `delete` template for this attribute wich drop the column\n",
" // with the `./builder/columns/dropColumn` template.\n",
" tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');\n",
" models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n"
],
"file_path": "packages/strapi-generate-migrations/lib/builder/relations.js",
"type": "add",
"edit_start_line_idx": 110
} | 'use strict';
/**
* Module dependencies
*/
// Node.js core.
const fs = require('fs');
const path = require('path');
// Public node modules.
const _ = require('lodash');
const pluralize = require('pluralize');
// Collections utils.
const utilsModels = require('strapi/lib/configuration/hooks/models/utils/');
const utilsBookShelf = require('strapi-bookshelf/lib/utils/');
/**
* Relationship templates
*/
module.exports = function (models, modelName, details, attribute, toDrop, onlyDrop) {
let tplRelationUp;
let tplRelationDown;
const infos = utilsModels.getNature(details, attribute, models);
_.set(models[modelName].attributes, attribute + '.create', {});
_.set(models[modelName].attributes, attribute + '.delete', {});
// If it's a "one-to-one" relationship.
if (infos.verbose === 'hasOne') {
// Force singular foreign key.
details.attribute = pluralize.singular(details.model);
// Define PK column.
details.column = utilsBookShelf.getPK(modelName, undefined, models);
// Template: create a new column thanks to the attribute's relation.
// Simply make a `create` template for this attribute wich will be added
// to the table template-- either `./builder/tables/selectTable` or
// `./builder/tables/createTableIfNotExists`.
tplRelationUp = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'relations', 'hasOne.template'), 'utf8');
models[modelName].attributes[attribute].create.others = _.unescape(_.template(tplRelationUp)({
tableName: modelName,
attribute: attribute,
details: details
}));
// Template: drop the column.
// Simply make a `delete` template for this attribute wich drop the column
// with the `./builder/columns/dropColumn` template.
tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');
models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({
tableName: modelName,
attribute: attribute,
details: details
}));
} else if (infos.verbose === 'belongsTo') {
// Force singular foreign key.
details.attribute = pluralize.singular(details.model);
// Define PK column.
details.column = utilsBookShelf.getPK(modelName, undefined, models);
if (infos.nature === 'oneToMany' || infos.nature === 'oneWay') {
// Template: create a new column thanks to the attribute's relation.
// Simply make a `create` template for this attribute wich will be added
// to the table template-- either `./builder/tables/selectTable` or
// `./builder/tables/createTableIfNotExists`.
tplRelationUp = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'relations', 'belongsTo.template'), 'utf8');
models[modelName].attributes[attribute].create.others = _.unescape(_.template(tplRelationUp)({
tableName: modelName,
attribute: attribute,
details: details,
nature: infos.nature
}));
// Template: drop the column.
// Simply make a `delete` template for this attribute wich drop the column
// with the `./builder/columns/dropColumn` template.
tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');
models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({
tableName: modelName,
attribute: attribute,
details: details
}));
} else {
// Template: create a new column thanks to the attribute's relation.
// Simply make a `create` template for this attribute wich will be added
// to the table template-- either `./builder/tables/selectTable` or
// `./builder/tables/createTableIfNotExists`.
tplRelationUp = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'relations', 'belongsTo-unique.template'), 'utf8');
models[modelName].attributes[attribute].create.others = _.unescape(_.template(tplRelationUp)({
tableName: modelName,
attribute: attribute,
details: details
}));
// Template: drop the column.
// Simply make a `delete` template for this attribute wich drop the column
// with the `./builder/columns/dropColumn` template.
tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');
models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({
tableName: modelName,
attribute: attribute,
details: details
}));
}
} else if (infos.verbose === 'belongsToMany') {
// Otherwise if it's a "many-to-many" relationship.
// Save the relationship.
const relationship = models[details.collection].attributes[details.via];
// Construct relation table name.
const relationTable = _.map(_.sortBy([relationship, details], 'collection'), function (table) {
return _.snakeCase(pluralize.plural(table.collection) + ' ' + pluralize.plural(table.via));
}).join('__');
// Force singular foreign key.
relationship.attribute = pluralize.singular(relationship.collection);
details.attribute = pluralize.singular(details.collection);
// Define PK column.
details.column = utilsBookShelf.getPK(modelName, undefined, models);
relationship.column = utilsBookShelf.getPK(details.collection, undefined, models);
// Avoid to create table both times.
if (!models.hasOwnProperty(relationTable)) {
// Save the relation table as a new model in the scope
// aiming to benefit of templates for the table such as
// `createTableIfNotExists` and `dropTable`.
models[relationTable] = {};
// Template: create the table for the `up` export if it doesn't exist.
// This adds a `up` logic for the relation table.
const tplTableUp = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'relations', 'belongsToMany.template'), 'utf8');
models[relationTable].up = _.unescape(_.template(tplTableUp)({
models: models,
tableName: relationTable,
details: details,
relationship: relationship
}));
// Template: drop the table for the `down` export.
// This adds a `down` logic for the relation table.
const tplTableDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'tables', 'dropTable.template'), 'utf8');
models[relationTable].down = _.unescape(_.template(tplTableDown)({
tableName: relationTable
}));
}
}
};
| packages/strapi-generate-migrations/lib/builder/relations.js | 1 | https://github.com/strapi/strapi/commit/7367e2ed61a55e811619da278271a30925bf6613 | [
0.998725950717926,
0.18860593438148499,
0.00016879464965313673,
0.0013245339505374432,
0.3891032636165619
] |
{
"id": 2,
"code_window": [
" }\n",
" } else if (infos.verbose === 'belongsToMany') {\n",
" // Otherwise if it's a \"many-to-many\" relationship.\n",
"\n",
" // Save the relationship.\n",
" const relationship = models[details.collection].attributes[details.via];\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" // Template: drop the column.\n",
" // Simply make a `delete` template for this attribute wich drop the column\n",
" // with the `./builder/columns/dropColumn` template.\n",
" tplRelationDown = fs.readFileSync(path.resolve(__dirname, '..', '..', 'templates', 'builder', 'columns', 'dropColumn.template'), 'utf8');\n",
" models[modelName].attributes[attribute].delete.others = _.unescape(_.template(tplRelationDown)({\n",
" tableName: modelName,\n",
" attribute: attribute,\n",
" details: details\n",
" }));\n"
],
"file_path": "packages/strapi-generate-migrations/lib/builder/relations.js",
"type": "add",
"edit_start_line_idx": 110
} | 'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// Public node modules.
const _ = require('lodash');
const async = require('async');
// Strapi utilities.
const dictionary = require('strapi-utils').dictionary;
/**
* Async module loader to create a
* dictionary of the user APIs.
*/
module.exports = function (strapi) {
const hook = {
/**
* Initialize the hook
*/
initialize: function (cb) {
_.forEach(strapi.api, function (definition, api) {
async.auto({
// Expose the `name` of the API for the callback.
'name': function (cb) {
cb(null, api);
},
// Load API controllers from `./api/*/controllers/*.js`.
'controllers/*': function (cb) {
dictionary.optional({
dirname: path.resolve(strapi.config.appPath, strapi.config.paths.api, api, strapi.config.paths.controllers),
filter: /(.+)\.(js)$/,
depth: 1
}, cb);
},
// Load API models from `./api/*/models/*.js` and `./api/*/models/*.settings.json`.
'models/*': function (cb) {
async.parallel({
settings: function (cb) {
dictionary.optional({
dirname: path.resolve(strapi.config.appPath, strapi.config.paths.api, api, strapi.config.paths.models),
filter: /(.+)\.settings.json$/,
depth: 1
}, cb);
},
functions: function (cb) {
dictionary.optional({
dirname: path.resolve(strapi.config.appPath, strapi.config.paths.api, api, strapi.config.paths.models),
filter: /(.+)\.js$/,
depth: 1
}, cb);
}
}, function (err, models) {
if (err) {
return cb(err);
}
return cb(null, _.merge(models.settings, models.functions));
});
},
// Load API services from `./api/*/services/*.js`.
'services/*': function (cb) {
dictionary.optional({
dirname: path.resolve(strapi.config.appPath, strapi.config.paths.api, api, strapi.config.paths.services),
filter: /(.+)\.(js)$/,
depth: 1
}, cb);
},
// Load API policies from `./api/*/policies/*.js`.
'policies/*': function (cb) {
dictionary.aggregate({
dirname: path.resolve(strapi.config.appPath, strapi.config.paths.api, api, strapi.config.paths.policies),
filter: /(.+)\.(js)$/,
depth: 1
}, cb);
},
// Load API config from `./api/*/config/*.js|json` and `./api/*/config/environments/**/*.js|json`.
'config/**': function (cb) {
async.parallel({
common: function (cb) {
dictionary.aggregate({
dirname: path.resolve(strapi.config.appPath, strapi.config.paths.api, api, strapi.config.paths.config),
filter: /(.+)\.(js|json)$/,
depth: 2
}, cb);
},
specific: function (cb) {
dictionary.aggregate({
dirname: path.resolve(strapi.config.appPath, strapi.config.paths.api, api, strapi.config.paths.config, 'environments', strapi.config.environment),
filter: /(.+)\.(js|json)$/,
depth: 2
}, cb);
}
}, function (err, config) {
if (err) {
return cb(err);
}
return cb(null, _.merge(config.common, config.specific));
});
}
},
// Callback.
function (err, api) {
// Just in case there is an error.
if (err) {
return cb(err);
}
// Expose the API dictionary.
strapi.api[api.name] = {
controllers: api['controllers/*'],
models: api['models/*'],
services: api['services/*'],
policies: api['policies/*'],
config: api['config/**']
};
// Delete the definition if it's empty.
_.forEach(strapi.api[api.name], function (dictionary, entry) {
if (_.isEmpty(strapi.api[api.name][entry])) {
delete strapi.api[api.name][entry];
}
});
// If the module doesn't have a definition at all
// just remove it completely from the dictionary.
if (_.isEmpty(strapi.api[api.name])) {
delete strapi.api[api.name];
}
// Merge API controllers with the main ones.
strapi.controllers = _.merge({}, strapi.controllers, _.get(strapi.api, api.name + '.controllers'));
// Merge API services with the main ones.
strapi.services = _.merge({}, strapi.services, _.get(strapi.api, api.name + '.services'));
// Merge API models with the main ones.
strapi.models = _.merge({}, strapi.models, _.get(strapi.api, api.name + '.models'));
// Merge API policies with the main ones.
strapi.policies = _.merge({}, strapi.policies, _.get(strapi.api, api.name + '.policies'));
// Merge API routes with the main ones.
strapi.config.routes = _.merge({}, strapi.config.routes, _.get(strapi.api, api.name + '.config.routes'));
});
});
cb();
}
};
return hook;
};
| packages/strapi/lib/configuration/hooks/_api/index.js | 0 | https://github.com/strapi/strapi/commit/7367e2ed61a55e811619da278271a30925bf6613 | [
0.001379786292091012,
0.00024138404114637524,
0.0001617373782210052,
0.00017150120402220637,
0.00028463039780035615
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.