hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 1,
"code_window": [
"cf = cf.node(null, { type: 'BlankNode' });\n",
"cf = cf.node('example', { datatype: node.value });\n",
"cf = cf.node('example', { datatype: node });\n",
"\n",
"// .out\n",
"cf = cf.out(node);\n",
"cf = cf.out([node, node]);\n",
"cf = cf.out(cf.node([node, node]));\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"cf = cf.out();\n"
],
"file_path": "types/clownface/clownface-tests.ts",
"type": "add",
"edit_start_line_idx": 152
} | // Type definitions for clipboard.js 2.0
// Project: https://github.com/zenorocha/clipboard.js
// Definitions by: Andrei Kurosh <https://github.com/impworks>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare class ClipboardJS {
constructor(
selector: string | Element | NodeListOf<Element>,
options?: ClipboardJS.Options
);
/**
* Subscribes to events that indicate the result of a copy/cut operation.
* @param type Event type ('success' or 'error').
* @param handler Callback function.
*/
on(type: "success" | "error", handler: (e: ClipboardJS.Event) => void): this;
on(type: string, handler: (...args: any[]) => void): this;
/**
* Clears all event bindings.
*/
destroy(): void;
/**
* Checks if clipboard.js is supported
*/
static isSupported(): boolean;
}
declare namespace ClipboardJS {
interface Options {
/**
* Overwrites default command ('cut' or 'copy').
* @param elem Current element
*/
action?(elem: Element): "cut" | "copy";
/**
* Overwrites default target input element.
* @param elem Current element
* @returns <input> element to use.
*/
target?(elem: Element): Element;
/**
* Returns the explicit text to copy.
* @param elem Current element
* @returns Text to be copied.
*/
text?(elem: Element): string;
/**
* For use in Bootstrap Modals or with any
* other library that changes the focus
* you'll want to set the focused element
* as the container value.
*/
container?: Element;
}
interface Event {
action: string;
text: string;
trigger: Element;
clearSelection(): void;
}
}
export = ClipboardJS;
export as namespace ClipboardJS;
| types/clipboard/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.0001775019190972671,
0.00017359523917548358,
0.00016781908925622702,
0.0001743626780807972,
0.000002995155455209897
] |
{
"id": 1,
"code_window": [
"cf = cf.node(null, { type: 'BlankNode' });\n",
"cf = cf.node('example', { datatype: node.value });\n",
"cf = cf.node('example', { datatype: node });\n",
"\n",
"// .out\n",
"cf = cf.out(node);\n",
"cf = cf.out([node, node]);\n",
"cf = cf.out(cf.node([node, node]));\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"cf = cf.out();\n"
],
"file_path": "types/clownface/clownface-tests.ts",
"type": "add",
"edit_start_line_idx": 152
} | { "extends": "dtslint/dt.json" }
| types/react-scrollbar-size/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.00017143825243692845,
0.00017143825243692845,
0.00017143825243692845,
0.00017143825243692845,
0
] |
{
"id": 2,
"code_window": [
"\n",
" namedNode(value: SingleOrOneElementArray<string | NamedNode>): SingleContextClownface<D, NamedNode>;\n",
" namedNode(values: Array<string | NamedNode>): SafeClownface<D, NamedNode>;\n",
"\n",
" // tslint:disable:no-unnecessary-generics\n",
" in<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
"\n",
" has<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects?: SingleOrArrayOfTermsOrLiterals): SafeClownface<D, X>;\n",
"\n",
" addIn<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objectsOrCallback?: SingleOrArrayOfTermsOrLiterals | AddCallback<D, X>): SafeClownface<D, X>;\n",
" addIn<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects: SingleOrArrayOfTermsOrLiterals, callback: AddCallback<D, X>): SafeClownface<D, X>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" in<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n"
],
"file_path": "types/clownface/index.d.ts",
"type": "replace",
"edit_start_line_idx": 79
} | import { BlankNode, DatasetCore, Literal, NamedNode, Quad_Graph, Term, Variable, DefaultGraph } from 'rdf-js';
import {
Clownface as ClownfaceContract,
ClownfaceInit,
AddCallback,
NodeOptions,
SafeClownface,
SingleOrArray,
SingleOrArrayOfTerms,
SingleOrArrayOfTermsOrLiterals,
WithValues,
WithSingleValue,
WithTerms,
WithSingleTerm,
SingleContextClownface,
SingleOrOneElementArray
} from '..';
declare class Clownface<D extends DatasetCore = DatasetCore, T extends Term = Term> implements ClownfaceContract<D, T> {
constructor(options: ClownfaceInit & Partial<WithSingleTerm<T> | WithTerms<T>> & Partial<WithSingleValue | WithValues>);
readonly term: T | undefined;
readonly terms: T[];
readonly value: string | undefined;
readonly values: string[];
readonly dataset: D;
readonly datasets: D[];
readonly _context: any;
list(): Iterable<SingleContextClownface<D>>;
toArray(): Array<Clownface<D, T>>;
filter(cb: (quad: Clownface<D, T>) => boolean): Clownface<D, T>;
forEach(cb: (quad: Clownface<D, T>) => void): void;
map<X>(cb: (quad: Clownface<D, T>, index: number) => X): X[];
node(value: SingleOrOneElementArray<string | number | boolean>, options?: NodeOptions): SingleContextClownface<D, Literal>;
node(values: Array<string | number | boolean>, options?: NodeOptions): SafeClownface<D, Literal>;
node<X extends Term>(value: SingleOrOneElementArray<X>, options?: NodeOptions): SingleContextClownface<D, X>;
node<X extends Term>(values: X[], options?: NodeOptions): SafeClownface<D, X>;
node(value: null, options?: NodeOptions): SingleContextClownface<D, BlankNode>;
node(values: null[], options?: NodeOptions): SafeClownface<D, BlankNode>;
node(values: SingleOrArray<string | number | boolean | NamedNode | BlankNode | Literal | Variable | DefaultGraph | null>, options?: NodeOptions): SafeClownface<D>;
blankNode(value?: string | [string]): SingleContextClownface<D, BlankNode>;
blankNode(values: string[]): SafeClownface<D, BlankNode>;
literal(
value: SingleOrOneElementArray<string | number | boolean | NamedNode | BlankNode | Literal | Variable | DefaultGraph | null>,
languageOrDatatype?: string | NamedNode): SingleContextClownface<D, Literal>;
literal(values: Array<string | number | boolean | NamedNode | BlankNode | Literal | Variable | DefaultGraph | null>, languageOrDatatype?: string | NamedNode): SafeClownface<D, Literal>;
namedNode(value: SingleOrOneElementArray<string | NamedNode>): SingleContextClownface<D, NamedNode>;
namedNode(values: Array<string | NamedNode>): SafeClownface<D, NamedNode>;
// tslint:disable:no-unnecessary-generics
in<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;
out<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;
has<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects?: SingleOrArrayOfTermsOrLiterals): SafeClownface<D, X>;
addIn<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objectsOrCallback?: SingleOrArrayOfTermsOrLiterals | AddCallback<D, X>): SafeClownface<D, X>;
addIn<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects: SingleOrArrayOfTermsOrLiterals, callback: AddCallback<D, X>): SafeClownface<D, X>;
addOut<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objectsOrCallback?: SingleOrArrayOfTermsOrLiterals | AddCallback<D, X>): SafeClownface<D, X>;
addOut<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects: SingleOrArrayOfTermsOrLiterals, callback: AddCallback<D, X>): SafeClownface<D, X>;
addList<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects?: SingleOrArrayOfTerms, callback?: AddCallback<D, X>): SafeClownface<D, X>;
deleteIn<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;
deleteOut<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;
deleteList<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;
// tslint:enable:no-unnecessary-generics
}
export = Clownface;
| types/clownface/lib/Clownface.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.997605562210083,
0.24955779314041138,
0.00016465139924548566,
0.009649286977946758,
0.4199163019657135
] |
{
"id": 2,
"code_window": [
"\n",
" namedNode(value: SingleOrOneElementArray<string | NamedNode>): SingleContextClownface<D, NamedNode>;\n",
" namedNode(values: Array<string | NamedNode>): SafeClownface<D, NamedNode>;\n",
"\n",
" // tslint:disable:no-unnecessary-generics\n",
" in<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
"\n",
" has<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects?: SingleOrArrayOfTermsOrLiterals): SafeClownface<D, X>;\n",
"\n",
" addIn<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objectsOrCallback?: SingleOrArrayOfTermsOrLiterals | AddCallback<D, X>): SafeClownface<D, X>;\n",
" addIn<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects: SingleOrArrayOfTermsOrLiterals, callback: AddCallback<D, X>): SafeClownface<D, X>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" in<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n"
],
"file_path": "types/clownface/index.d.ts",
"type": "replace",
"edit_start_line_idx": 79
} | {
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"npm-naming": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
| types/nodemailer-smtp-transport/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.00018577883020043373,
0.00017249328084290028,
0.00016463898646179587,
0.00017134395602624863,
0.000005481379048433155
] |
{
"id": 2,
"code_window": [
"\n",
" namedNode(value: SingleOrOneElementArray<string | NamedNode>): SingleContextClownface<D, NamedNode>;\n",
" namedNode(values: Array<string | NamedNode>): SafeClownface<D, NamedNode>;\n",
"\n",
" // tslint:disable:no-unnecessary-generics\n",
" in<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
"\n",
" has<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects?: SingleOrArrayOfTermsOrLiterals): SafeClownface<D, X>;\n",
"\n",
" addIn<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objectsOrCallback?: SingleOrArrayOfTermsOrLiterals | AddCallback<D, X>): SafeClownface<D, X>;\n",
" addIn<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects: SingleOrArrayOfTermsOrLiterals, callback: AddCallback<D, X>): SafeClownface<D, X>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" in<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n"
],
"file_path": "types/clownface/index.d.ts",
"type": "replace",
"edit_start_line_idx": 79
} | import { Argv } from '.';
export = Yargs;
declare function Yargs(
processArgs?: ReadonlyArray<string>,
cwd?: string,
parentRequire?: NodeRequire,
): Argv;
| types/yargs/yargs.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.00017122604185715318,
0.00017122604185715318,
0.00017122604185715318,
0.00017122604185715318,
0
] |
{
"id": 2,
"code_window": [
"\n",
" namedNode(value: SingleOrOneElementArray<string | NamedNode>): SingleContextClownface<D, NamedNode>;\n",
" namedNode(values: Array<string | NamedNode>): SafeClownface<D, NamedNode>;\n",
"\n",
" // tslint:disable:no-unnecessary-generics\n",
" in<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
"\n",
" has<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects?: SingleOrArrayOfTermsOrLiterals): SafeClownface<D, X>;\n",
"\n",
" addIn<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objectsOrCallback?: SingleOrArrayOfTermsOrLiterals | AddCallback<D, X>): SafeClownface<D, X>;\n",
" addIn<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects: SingleOrArrayOfTermsOrLiterals, callback: AddCallback<D, X>): SafeClownface<D, X>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" in<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n"
],
"file_path": "types/clownface/index.d.ts",
"type": "replace",
"edit_start_line_idx": 79
} | import { forIn } from "lodash";
export default forIn;
| types/lodash-es/forIn.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.00016719028644729406,
0.00016719028644729406,
0.00016719028644729406,
0.00016719028644729406,
0
] |
{
"id": 3,
"code_window": [
" namedNode(value: SingleOrOneElementArray<string | NamedNode>): SingleContextClownface<D, NamedNode>;\n",
" namedNode(values: Array<string | NamedNode>): SafeClownface<D, NamedNode>;\n",
"\n",
" // tslint:disable:no-unnecessary-generics\n",
" in<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
"\n",
" has<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects?: SingleOrArrayOfTermsOrLiterals): SafeClownface<D, X>;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" in<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n"
],
"file_path": "types/clownface/lib/Clownface.d.ts",
"type": "replace",
"edit_start_line_idx": 53
} | import { Term, NamedNode, Dataset, Literal, DatasetCore, BlankNode } from 'rdf-js';
import Clownface = require('clownface/lib/Clownface');
import clownface = require('clownface');
const node: NamedNode = <any> {};
const blankNode: BlankNode = <any> {};
const predicate: NamedNode = <any> {};
const literal: Literal = <any> {};
let term: Term = <any> {};
// .ctor
const dataset: Dataset = <any> {};
const graph: NamedNode = <any> {};
let cf: Clownface<Dataset> = new Clownface({ dataset });
cf = new Clownface({ dataset, graph });
const typedByTerm: Clownface<DatasetCore, NamedNode> = new Clownface({ dataset, term: node });
const typedByTerms: Clownface<DatasetCore, NamedNode | BlankNode> = new Clownface({ dataset, term: [node, blankNode] });
cf = new Clownface({ dataset, value: 'foo' });
cf = new Clownface({ dataset, value: ['foo', 'bar'] });
cf = new Clownface({ dataset, term: [term, term], value: ['foo', 'bar'] });
// .addIn
cf = cf.addIn(node);
cf = cf.addIn(node, node);
cf = cf.addIn([ node, node ], node);
cf = cf.addIn(node, [ node, node ]);
cf = cf.addIn([ node, node ], [ node, node ], child => {
const values: string[] = child.values;
});
cf = cf.addIn(node, child => {
cf = child;
});
cf = cf.addIn(cf.node(node), cf.node(node));
// .addList
cf = cf.addList(predicate, [node, node]);
// .addOut
cf = cf.addOut(predicate, node);
cf = cf.addOut(predicate);
cf = cf.addOut(predicate, ['', 0]);
cf = cf.addOut([predicate, predicate], node);
cf = cf.addOut(predicate, [node, node]);
cf = cf.addOut([predicate, predicate], [node, node], child => {
const values: string[] = child.values;
});
cf = cf.addOut(predicate, child => {
const values: string[] = child.values;
});
cf = cf.addOut(cf.node(predicate), cf.node(node));
// .blankNode
let blankContext: Clownface;
blankContext = cf.blankNode();
blankContext = cf.blankNode('label');
blankContext = cf.blankNode([ 'b1', 'b2' ]);
// .deleteIn
cf = cf.deleteIn();
cf = cf.deleteIn(node);
cf = cf.deleteIn([node, node]);
// .deleteList
cf = cf.deleteList(predicate);
// .deleteOut
cf = cf.deleteOut();
cf = cf.deleteOut(node);
cf = cf.deleteOut([node, node]);
// factory
cf = clownface({ dataset });
const namedGraph: clownface.Clownface<Dataset, NamedNode> = clownface({ dataset, graph });
const singleFromValue: clownface.SingleContextClownface = clownface({ dataset, value: 'foo' });
const termContext: clownface.SingleContextClownface = clownface({
dataset,
term
});
const namedContext: clownface.SingleContextClownface<DatasetCore, NamedNode> = clownface({
dataset,
term: node,
});
const namedMutlipleTerms: clownface.SafeClownface<DatasetCore, NamedNode> = clownface({
dataset,
term: [node, node],
});
const mutlipleValues: clownface.SafeClownface = clownface({
dataset,
value: ['foo', 'bar'],
});
const maybeNamed: BlankNode | NamedNode = <any> {};
const altContext: clownface.SingleContextClownface<DatasetCore, BlankNode | NamedNode> = clownface({
dataset,
term: maybeNamed,
});
const literalContext: clownface.SingleContextClownface<Dataset, Literal> = <any> {};
const deriveContextFromOtherGraph: clownface.SingleContextClownface<Dataset, Literal> = clownface(literalContext);
// .filter
cf = cf.filter(() => true);
cf = cf.filter((thus: Clownface) => true);
// .forEach
cf.forEach(() => {});
cf.forEach((thus: Clownface) => {});
// .has
cf = cf.has(predicate, 'Stuart');
cf = cf.has([predicate, predicate], 'Stuart');
cf = cf.has(predicate, [literal, literal]);
// .in
cf = cf.in(node);
cf = cf.in([node, node]);
cf = cf.in(cf.node(node));
// .list
const listNodes: Iterable<clownface.SingleContextClownface<Dataset>> = cf.list();
// .literal
cf = cf.literal('foo');
cf = cf.literal(['foo', 'bar']);
cf = cf.literal('foo', node);
cf = cf.literal('foo', 'en');
// .map
const arr: Clownface[] = cf.map((item: Clownface) => item);
const nums: number[] = cf.map((item: Clownface, index: number) => index);
// .namedNode
cf = cf.namedNode(node);
cf = cf.namedNode('http://example.com/');
cf = cf.namedNode(['http://example.com/', 'http://example.org/']);
// .node
cf = cf.node(node);
cf = cf.node('foo');
cf = cf.node(123);
cf = cf.node(['foo', 'bar']);
cf = cf.node('http://example.org/', { type: 'NamedNode' });
cf = cf.node(null, { type: 'BlankNode' });
cf = cf.node('example', { datatype: node.value });
cf = cf.node('example', { datatype: node });
// .out
cf = cf.out(node);
cf = cf.out([node, node]);
cf = cf.out(cf.node([node, node]));
// .term
if (cf.term) {
term = cf.term;
}
// .terms
const terms: Term[] = cf.terms;
// .toArray
const toArray: Clownface[] = cf.toArray();
// .value
if (cf.value) {
const valueProp: string = cf.value;
}
// .values
const values: string[] = cf.values;
const safeCf: clownface.SafeClownface<Dataset> = <any> {};
let singleBlank: clownface.SingleContextClownface<Dataset, BlankNode> = safeCf.blankNode();
singleBlank = clownface({ dataset }).blankNode();
singleBlank = safeCf.blankNode('blank');
singleBlank = clownface({ dataset }).node(null);
let singleNamed: clownface.SingleContextClownface<Dataset, NamedNode> = clownface({ dataset }).namedNode('urn:foo:bar');
singleNamed = safeCf.namedNode('http://example.com/a');
singleNamed = clownface({ dataset }).node(node);
let singleLiteral: clownface.SingleContextClownface<Dataset, Literal> = clownface({ dataset }).literal('foo');
singleLiteral = safeCf.literal('a');
singleLiteral = clownface({ dataset }).node('b');
const fromSingleArrayBLank: clownface.SingleContextClownface<Dataset, BlankNode> = safeCf.blankNode([ 'b1' ]);
const fromSingleArrayNamed: clownface.SingleContextClownface<Dataset, NamedNode> = safeCf.namedNode([ 'http://example.com/a' ]);
const fromSingleArrayLiteral: clownface.SingleContextClownface<Dataset, Literal> = safeCf.literal([ 'a' ]);
let multipleBlanks: clownface.SafeClownface<Dataset, BlankNode> = safeCf.blankNode([ 'b1', 'b2' ]);
multipleBlanks = clownface({ dataset }).node([ null, null ]);
let multipleNamed: clownface.SafeClownface<Dataset, NamedNode> = safeCf.namedNode([ 'http://example.com/a', 'http://example.com/b' ]);
multipleNamed = clownface({ dataset }).node([ node, node ]);
let multipleLiterals: clownface.SafeClownface<Dataset, Literal> = safeCf.literal([ 'a', 'b' ]);
multipleLiterals = clownface({ dataset }).node([ 'a', 10, false ]);
const multipleMixedTerms: clownface.SafeClownface<Dataset> = clownface({ dataset }).node([ 'a', node, null ]);
| types/clownface/clownface-tests.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.998392641544342,
0.1262890100479126,
0.00016898482863325626,
0.00033787149004638195,
0.3087739646434784
] |
{
"id": 3,
"code_window": [
" namedNode(value: SingleOrOneElementArray<string | NamedNode>): SingleContextClownface<D, NamedNode>;\n",
" namedNode(values: Array<string | NamedNode>): SafeClownface<D, NamedNode>;\n",
"\n",
" // tslint:disable:no-unnecessary-generics\n",
" in<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
"\n",
" has<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects?: SingleOrArrayOfTermsOrLiterals): SafeClownface<D, X>;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" in<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n"
],
"file_path": "types/clownface/lib/Clownface.d.ts",
"type": "replace",
"edit_start_line_idx": 53
} | import * as fs from "fs-extra";
import * as Path from "path";
const len = 2;
const src = "";
const dest = "";
const file = "";
const dir = "";
const path = "";
const data = "";
const uid = 0;
const gid = 0;
const fd = 0;
const modeNum = 0;
const modeStr = "";
const object = {};
const errorCallback = (err: Error) => { };
const ensureNum = 0o700;
const ensureObj: fs.EnsureOptions = {
mode: 0o700
};
const readOptions: fs.ReadOptions = {
reviver: {}
};
const writeOptions: fs.WriteOptions = {
replacer: {}
};
fs.moveSync(src, dest, {});
fs.move(src, dest, {}).then(() => {
// stub
});
fs.move(src, dest).then(() => {
// stub
});
fs.move(src, dest, {}, () => {
// stub
});
fs.move(src, dest, () => {
// stub
});
fs.copy(src, dest).then(() => {
// stub
});
fs.copy(src, dest, { overwrite: true }).then(() => {
// stub
});
fs.copy(src, dest, errorCallback);
fs.copy(src, dest, { filter: (src: string, dest: string) => false }, errorCallback);
fs.copy(src, dest,
{
overwrite: true,
preserveTimestamps: true,
filter: (src: string, dest: string) => Promise.resolve(false)
},
errorCallback
);
fs.copySync(src, dest);
fs.copySync(src, dest, { filter: (src: string, dest: string) => false });
fs.copySync(src, dest,
{
overwrite: true,
preserveTimestamps: true,
filter: (src: string, dest: string) => false
}
);
fs.createFile(file).then(() => {
// stub
});
fs.createFile(file, errorCallback);
fs.createFileSync(file);
fs.mkdirs(dir).then(() => {
// stub
});
fs.mkdirp(dir).then(() => {
// stub
});
fs.mkdirs(dir, errorCallback);
fs.mkdirsSync(dir);
fs.mkdirp(dir, errorCallback);
fs.mkdirpSync(dir);
fs.outputFile(file, data).then(() => {
// stub
});
fs.outputFile(file, data, errorCallback);
fs.outputFileSync(file, data);
fs.outputJson(file, data, {
spaces: 2
}).then(() => {
// stub
});
fs.outputJson(file, data, {
spaces: 2
}, errorCallback);
fs.outputJSON(file, data, errorCallback);
fs.outputJSON(file, data).then(() => {
// stub
});
fs.outputJsonSync(file, data);
fs.outputJSONSync(file, data);
fs.readJson(file).then(() => {
// stub
});
fs.readJson(file, readOptions).then(() => {
// stub
});
fs.readJson(file, (error: Error, jsonObject: any) => { });
fs.readJson(file, readOptions, (error: Error, jsonObject: any) => { });
fs.readJSON(file, (error: Error, jsonObject: any) => { });
fs.readJSON(file, readOptions, (error: Error, jsonObject: any) => { });
fs.readJsonSync(file, readOptions);
fs.readJSONSync(file, readOptions);
fs.remove(dir, errorCallback);
fs.remove(dir).then(() => {
// stub
});
fs.removeSync(dir);
fs.writeJson(file, object).then(() => {
// stub
});
fs.writeJSON(file, object).then(() => {
// stub
});
fs.writeJson(file, object, errorCallback);
fs.writeJson(file, object, writeOptions, errorCallback);
fs.writeJSON(file, object, errorCallback);
fs.writeJSON(file, object, writeOptions, errorCallback);
fs.writeJson(file, object, writeOptions).then(() => {
// stub
});
fs.writeJSON(file, object, writeOptions).then(() => {
// stub
});
fs.writeJsonSync(file, object, writeOptions);
fs.writeJSONSync(file, object, writeOptions);
fs.ensureDir(path).then(() => {
// stub
});
fs.ensureDir(path, ensureObj).then(() => {
// stub
});
fs.ensureDir(path, ensureNum).then(() => {
// stub
});
fs.ensureDir(path, ensureObj, errorCallback);
fs.ensureDir(path, ensureNum, errorCallback);
fs.ensureDirSync(path);
fs.ensureDirSync(path, ensureObj);
fs.ensureDirSync(path, ensureNum);
fs.ensureFile(path).then(() => {
// stub
});
fs.ensureFile(path, errorCallback);
fs.ensureFileSync(path);
fs.ensureLink(path, path).then(() => {
// stub
});
fs.ensureLink(path, path, errorCallback);
fs.ensureLinkSync(path, path);
fs.ensureSymlink(path, path, "file").then(() => {
// stub
});
fs.ensureSymlink(path, path, errorCallback);
fs.ensureSymlinkSync(path, path);
fs.emptyDir(path).then(() => {
// stub
});
fs.emptyDir(path, errorCallback);
fs.emptyDirSync(path);
fs.pathExists(path).then((_exist: boolean) => {
// stub
});
fs.pathExists(path, (_err: Error, _exists: boolean) => { });
const x: boolean = fs.pathExistsSync(path);
fs.rename(src, dest, errorCallback);
fs.renameSync(src, dest);
fs.truncate(path, len, errorCallback);
fs.truncateSync(path, len);
fs.chown(path, uid, gid, errorCallback);
fs.chownSync(path, uid, gid);
fs.fchown(fd, uid, gid, errorCallback);
fs.fchownSync(fd, uid, gid);
fs.lchown(path, uid, gid, errorCallback);
fs.lchownSync(path, uid, gid);
fs.chmod(path, modeNum, errorCallback);
fs.chmod(path, modeStr, errorCallback);
fs.chmodSync(path, modeNum);
fs.chmodSync(path, modeStr);
fs.fchmod(fd, modeNum, errorCallback);
fs.fchmod(fd, modeStr, errorCallback);
fs.fchmodSync(fd, modeNum);
fs.fchmodSync(fd, modeStr);
fs.lchmod(path, modeStr, errorCallback);
fs.lchmod(path, modeNum, errorCallback);
fs.lchmodSync(path, modeNum);
fs.lchmodSync(path, modeStr);
fs.statSync(path);
fs.lstatSync(path);
fs.read(0, new Buffer(""), 0, 0, null).then(x => {
const a = x.buffer;
const b = x.bytesRead;
});
fs.write(0, new Buffer(""), 0, 0, null).then(x => {
const a = x.buffer;
const b = x.bytesWritten;
});
fs.write(0, new Buffer("")).then(x => {
const a = x.buffer;
const b = x.bytesWritten;
});
// $ExpectType Promise<void>
fs.writeFile("foo.txt", "i am foo", { encoding: "utf-8" });
// $ExpectType Promise<string>
fs.mkdtemp("foo");
fs.copyFile("src", "dest").then();
fs.copyFile("src", "dest", fs.constants.COPYFILE_EXCL).then();
fs.copyFile("src", "dest", errorCallback);
| types/fs-extra/fs-extra-tests.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.00017855742771644145,
0.00017637161363381892,
0.00017364360974170268,
0.00017659951117821038,
9.518918773210316e-7
] |
{
"id": 3,
"code_window": [
" namedNode(value: SingleOrOneElementArray<string | NamedNode>): SingleContextClownface<D, NamedNode>;\n",
" namedNode(values: Array<string | NamedNode>): SafeClownface<D, NamedNode>;\n",
"\n",
" // tslint:disable:no-unnecessary-generics\n",
" in<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
"\n",
" has<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects?: SingleOrArrayOfTermsOrLiterals): SafeClownface<D, X>;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" in<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n"
],
"file_path": "types/clownface/lib/Clownface.d.ts",
"type": "replace",
"edit_start_line_idx": 53
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"moment-duration-format-tests.ts",
"test/module-tests.ts"
]
} | types/moment-duration-format/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.0001771627285052091,
0.0001762744941515848,
0.00017571038915775716,
0.00017595030658412725,
6.356813173624687e-7
] |
{
"id": 3,
"code_window": [
" namedNode(value: SingleOrOneElementArray<string | NamedNode>): SingleContextClownface<D, NamedNode>;\n",
" namedNode(values: Array<string | NamedNode>): SafeClownface<D, NamedNode>;\n",
"\n",
" // tslint:disable:no-unnecessary-generics\n",
" in<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
"\n",
" has<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects?: SingleOrArrayOfTermsOrLiterals): SafeClownface<D, X>;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" in<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n",
" out<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;\n"
],
"file_path": "types/clownface/lib/Clownface.d.ts",
"type": "replace",
"edit_start_line_idx": 53
} | // Type definitions for ember-test-helpers 0.7
// Project: https://github.com/emberjs/ember-test-helpers#readme
// Definitions by: Derek Wickern <https://github.com/dwickern>
// Mike North <https://github.com/mike-north>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/// <reference types="jquery" />
declare module 'ember-test-helpers' {
import Ember from 'ember';
import { TemplateFactory } from 'htmlbars-inline-precompile';
import RSVP from "rsvp";
interface ModuleCallbacks {
integration?: boolean;
unit?: boolean;
needs?: string[];
beforeSetup?(assert?: any): void;
setup?(assert?: any): void;
teardown?(assert?: any): void;
afterTeardown?(assert?: any): void;
[key: string]: any;
}
interface TestContext {
get(key: string): any;
getProperties<K extends string>(...keys: K[]): Pick<any, K>;
set<V>(key: string, value: V): V;
setProperties<P extends { [key: string]: any }>(hash: P): P;
on(actionName: string, handler: (this: TestContext, ...args: any[]) => any): void;
send(actionName: string): void;
$: JQueryStatic;
subject(options?: {}): any;
render(template?: string | string[] | TemplateFactory): Promise<void>;
clearRender(): void;
registry: Ember.Registry;
container: Ember.Container;
dispatcher: Ember.EventDispatcher;
application: Ember.Application;
register(fullName: string, factory: any): void;
factory(fullName: string): any;
inject: {
controller(name: string, options?: { as: string }): any;
service(name: string, options?: { as: string }): any;
};
owner: Ember.ApplicationInstance & {
factoryFor(fullName: string, options?: {}): any;
};
pauseTest(): Promise<void>;
resumeTest(): void;
element: Element;
}
class TestModule {
constructor(name: string, callbacks?: ModuleCallbacks);
constructor(name: string, description?: string, callbacks?: ModuleCallbacks);
name: string;
subjectName: string;
description: string;
isIntegration: boolean;
callbacks: ModuleCallbacks;
context: TestContext;
resolver: Ember.Resolver;
setup(assert?: any): RSVP.Promise<void>;
teardown(assert?: any): RSVP.Promise<void>;
getContext(): TestContext;
setContext(context: TestContext): void;
}
class TestModuleForAcceptance extends TestModule {}
class TestModuleForIntegration extends TestModule {}
class TestModuleForComponent extends TestModule {}
class TestModuleForModel extends TestModule {}
function getContext(): TestContext | undefined;
function setContext(context: TestContext): void;
function unsetContext(): void;
function setResolver(resolver: Ember.Resolver): void;
}
declare module 'ember-test-helpers/wait' {
import RSVP from "rsvp";
interface WaitOptions {
waitForTimers?: boolean;
waitForAJAX?: boolean;
waitForWaiters?: boolean;
}
export default function wait(options?: WaitOptions): RSVP.Promise<void>;
}
declare module 'ember-test-helpers/has-ember-version' {
export default function hasEmberVersion(major: number, minor: number): boolean;
}
| types/ember-test-helpers/v0/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.0001769329683156684,
0.0001721177395666018,
0.00016524497186765075,
0.00017216494597960263,
0.0000034859438073908677
] |
{
"id": 0,
"code_window": [
"}\n",
"\n",
"export function getDocumentFormattingEdits(model: IReadOnlyModel, options: FormattingOptions): TPromise<ISingleEditOperation[]> {\n",
"\tconst [support] = DocumentFormattingEditProviderRegistry.ordered(model);\n",
"\tif (!support) {\n",
"\t\treturn getDocumentRangeFormattingEdits(model, model.getFullModelRange(), options);\n",
"\t}\n",
"\n",
"\treturn asWinJsPromise((token) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t// try range formatters when no document formatter is registered\n"
],
"file_path": "src/vs/editor/contrib/format/common/format.ts",
"type": "add",
"edit_start_line_idx": 32
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { illegalArgument } from 'vs/base/common/errors';
import URI from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { Range } from 'vs/editor/common/core/range';
import { IReadOnlyModel, ISingleEditOperation } from 'vs/editor/common/editorCommon';
import { CommonEditorRegistry } from 'vs/editor/common/editorCommonExtensions';
import { DocumentFormattingEditProviderRegistry, DocumentRangeFormattingEditProviderRegistry, OnTypeFormattingEditProviderRegistry, FormattingOptions } from 'vs/editor/common/modes';
import { IModelService } from 'vs/editor/common/services/modelService';
import { asWinJsPromise } from 'vs/base/common/async';
import { Position } from 'vs/editor/common/core/position';
export function getDocumentRangeFormattingEdits(model: IReadOnlyModel, range: Range, options: FormattingOptions): TPromise<ISingleEditOperation[]> {
const [support] = DocumentRangeFormattingEditProviderRegistry.ordered(model);
if (!support) {
return TPromise.as(undefined);
}
return asWinJsPromise((token) => {
return support.provideDocumentRangeFormattingEdits(model, range, options, token);
});
}
export function getDocumentFormattingEdits(model: IReadOnlyModel, options: FormattingOptions): TPromise<ISingleEditOperation[]> {
const [support] = DocumentFormattingEditProviderRegistry.ordered(model);
if (!support) {
return getDocumentRangeFormattingEdits(model, model.getFullModelRange(), options);
}
return asWinJsPromise((token) => {
return support.provideDocumentFormattingEdits(model, options, token);
});
}
export function getOnTypeFormattingEdits(model: IReadOnlyModel, position: Position, ch: string, options: FormattingOptions): TPromise<ISingleEditOperation[]> {
const [support] = OnTypeFormattingEditProviderRegistry.ordered(model);
if (!support) {
return TPromise.as(undefined);
}
if (support.autoFormatTriggerCharacters.indexOf(ch) < 0) {
return TPromise.as(undefined);
}
return asWinJsPromise((token) => {
return support.provideOnTypeFormattingEdits(model, position, ch, options, token);
});
}
CommonEditorRegistry.registerLanguageCommand('_executeFormatRangeProvider', function (accessor, args) {
const {resource, range, options} = args;
if (!(resource instanceof URI) || !Range.isIRange(range)) {
throw illegalArgument();
}
const model = accessor.get(IModelService).getModel(resource);
if (!model) {
throw illegalArgument('resource');
}
return getDocumentRangeFormattingEdits(model, Range.lift(range), options);
});
CommonEditorRegistry.registerLanguageCommand('_executeFormatDocumentProvider', function (accessor, args) {
const {resource, options} = args;
if (!(resource instanceof URI)) {
throw illegalArgument('resource');
}
const model = accessor.get(IModelService).getModel(resource);
if (!model) {
throw illegalArgument('resource');
}
return getDocumentFormattingEdits(model, options);
});
CommonEditorRegistry.registerDefaultLanguageCommand('_executeFormatOnTypeProvider', function (model, position, args) {
const {ch, options } = args;
if (typeof ch !== 'string') {
throw illegalArgument('ch');
}
return getOnTypeFormattingEdits(model, position, ch, options);
});
| src/vs/editor/contrib/format/common/format.ts | 1 | https://github.com/microsoft/vscode/commit/5c553b6ad4fe7d80269c9c8c6f286c4b04e9460c | [
0.9988788962364197,
0.6760945320129395,
0.0001756576239131391,
0.9846394062042236,
0.44825372099876404
] |
{
"id": 0,
"code_window": [
"}\n",
"\n",
"export function getDocumentFormattingEdits(model: IReadOnlyModel, options: FormattingOptions): TPromise<ISingleEditOperation[]> {\n",
"\tconst [support] = DocumentFormattingEditProviderRegistry.ordered(model);\n",
"\tif (!support) {\n",
"\t\treturn getDocumentRangeFormattingEdits(model, model.getFullModelRange(), options);\n",
"\t}\n",
"\n",
"\treturn asWinJsPromise((token) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t// try range formatters when no document formatter is registered\n"
],
"file_path": "src/vs/editor/contrib/format/common/format.ts",
"type": "add",
"edit_start_line_idx": 32
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"": "{0}: {1}",
"actionNotEnabled": "Команда {0} не разрешена в текущем контексте.",
"canNotRun": "Выполнить команду {0} отсюда невозможно.",
"commandLabel": "{0}: {1}",
"entryAriaLabel": "{0}, команды",
"entryAriaLabelWithKey": "{0}, {1}, команды",
"noCommandsMatching": "Нет соответствующих команд",
"showTriggerActions": "Показать все команды"
} | i18n/rus/src/vs/workbench/parts/quickopen/browser/commandsHandler.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5c553b6ad4fe7d80269c9c8c6f286c4b04e9460c | [
0.0001726112241158262,
0.00017134041991084814,
0.00017006963025778532,
0.00017134041991084814,
0.0000012707969290204346
] |
{
"id": 0,
"code_window": [
"}\n",
"\n",
"export function getDocumentFormattingEdits(model: IReadOnlyModel, options: FormattingOptions): TPromise<ISingleEditOperation[]> {\n",
"\tconst [support] = DocumentFormattingEditProviderRegistry.ordered(model);\n",
"\tif (!support) {\n",
"\t\treturn getDocumentRangeFormattingEdits(model, model.getFullModelRange(), options);\n",
"\t}\n",
"\n",
"\treturn asWinJsPromise((token) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t// try range formatters when no document formatter is registered\n"
],
"file_path": "src/vs/editor/contrib/format/common/format.ts",
"type": "add",
"edit_start_line_idx": 32
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"abbreviation": "縮寫",
"enterAbbreviation": "輸入縮寫",
"wrapWithAbbreviationAction": "Emmet: 以縮寫包裝"
} | i18n/cht/src/vs/workbench/parts/emmet/node/actions/wrapWithAbbreviation.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5c553b6ad4fe7d80269c9c8c6f286c4b04e9460c | [
0.00017571658827364445,
0.0001743649336276576,
0.00017301327898167074,
0.0001743649336276576,
0.000001351654645986855
] |
{
"id": 0,
"code_window": [
"}\n",
"\n",
"export function getDocumentFormattingEdits(model: IReadOnlyModel, options: FormattingOptions): TPromise<ISingleEditOperation[]> {\n",
"\tconst [support] = DocumentFormattingEditProviderRegistry.ordered(model);\n",
"\tif (!support) {\n",
"\t\treturn getDocumentRangeFormattingEdits(model, model.getFullModelRange(), options);\n",
"\t}\n",
"\n",
"\treturn asWinJsPromise((token) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t// try range formatters when no document formatter is registered\n"
],
"file_path": "src/vs/editor/contrib/format/common/format.ts",
"type": "add",
"edit_start_line_idx": 32
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"err.tooMuchData": "很抱歉,但 VS 代码的 JavaScript 源文件太多。请考虑使用 jsconfig.json 中的 exclude 属性。"
} | i18n/chs/src/vs/languages/typescript/common/typescriptMode.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5c553b6ad4fe7d80269c9c8c6f286c4b04e9460c | [
0.00017577507242094725,
0.00017577507242094725,
0.00017577507242094725,
0.00017577507242094725,
0
] |
{
"id": 1,
"code_window": [
"import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n",
"import { IPosition, IModel, ICommonCodeEditor, ISingleEditOperation, IIdentifiedSingleEditOperation } from 'vs/editor/common/editorCommon';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"import { Selection } from 'vs/editor/common/core/selection';\n",
"import { trimTrailingWhitespace } from 'vs/editor/common/commands/trimTrailingWhitespaceCommand';\n",
"import { getDocumentRangeFormattingEdits } from 'vs/editor/contrib/format/common/format';\n",
"import { EditOperationsCommand } from 'vs/editor/contrib/format/common/formatCommand';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';\n",
"import { ExtHostContext, ExtHostDocumentSaveParticipantShape } from './extHost.protocol';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { getDocumentFormattingEdits } from 'vs/editor/contrib/format/common/format';\n"
],
"file_path": "src/vs/workbench/api/node/mainThreadSaveParticipant.ts",
"type": "replace",
"edit_start_line_idx": 17
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { illegalArgument } from 'vs/base/common/errors';
import URI from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { Range } from 'vs/editor/common/core/range';
import { IReadOnlyModel, ISingleEditOperation } from 'vs/editor/common/editorCommon';
import { CommonEditorRegistry } from 'vs/editor/common/editorCommonExtensions';
import { DocumentFormattingEditProviderRegistry, DocumentRangeFormattingEditProviderRegistry, OnTypeFormattingEditProviderRegistry, FormattingOptions } from 'vs/editor/common/modes';
import { IModelService } from 'vs/editor/common/services/modelService';
import { asWinJsPromise } from 'vs/base/common/async';
import { Position } from 'vs/editor/common/core/position';
export function getDocumentRangeFormattingEdits(model: IReadOnlyModel, range: Range, options: FormattingOptions): TPromise<ISingleEditOperation[]> {
const [support] = DocumentRangeFormattingEditProviderRegistry.ordered(model);
if (!support) {
return TPromise.as(undefined);
}
return asWinJsPromise((token) => {
return support.provideDocumentRangeFormattingEdits(model, range, options, token);
});
}
export function getDocumentFormattingEdits(model: IReadOnlyModel, options: FormattingOptions): TPromise<ISingleEditOperation[]> {
const [support] = DocumentFormattingEditProviderRegistry.ordered(model);
if (!support) {
return getDocumentRangeFormattingEdits(model, model.getFullModelRange(), options);
}
return asWinJsPromise((token) => {
return support.provideDocumentFormattingEdits(model, options, token);
});
}
export function getOnTypeFormattingEdits(model: IReadOnlyModel, position: Position, ch: string, options: FormattingOptions): TPromise<ISingleEditOperation[]> {
const [support] = OnTypeFormattingEditProviderRegistry.ordered(model);
if (!support) {
return TPromise.as(undefined);
}
if (support.autoFormatTriggerCharacters.indexOf(ch) < 0) {
return TPromise.as(undefined);
}
return asWinJsPromise((token) => {
return support.provideOnTypeFormattingEdits(model, position, ch, options, token);
});
}
CommonEditorRegistry.registerLanguageCommand('_executeFormatRangeProvider', function (accessor, args) {
const {resource, range, options} = args;
if (!(resource instanceof URI) || !Range.isIRange(range)) {
throw illegalArgument();
}
const model = accessor.get(IModelService).getModel(resource);
if (!model) {
throw illegalArgument('resource');
}
return getDocumentRangeFormattingEdits(model, Range.lift(range), options);
});
CommonEditorRegistry.registerLanguageCommand('_executeFormatDocumentProvider', function (accessor, args) {
const {resource, options} = args;
if (!(resource instanceof URI)) {
throw illegalArgument('resource');
}
const model = accessor.get(IModelService).getModel(resource);
if (!model) {
throw illegalArgument('resource');
}
return getDocumentFormattingEdits(model, options);
});
CommonEditorRegistry.registerDefaultLanguageCommand('_executeFormatOnTypeProvider', function (model, position, args) {
const {ch, options } = args;
if (typeof ch !== 'string') {
throw illegalArgument('ch');
}
return getOnTypeFormattingEdits(model, position, ch, options);
});
| src/vs/editor/contrib/format/common/format.ts | 1 | https://github.com/microsoft/vscode/commit/5c553b6ad4fe7d80269c9c8c6f286c4b04e9460c | [
0.0031769778579473495,
0.0009263756219297647,
0.00016667279123794287,
0.0003361839917488396,
0.001039766357280314
] |
{
"id": 1,
"code_window": [
"import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n",
"import { IPosition, IModel, ICommonCodeEditor, ISingleEditOperation, IIdentifiedSingleEditOperation } from 'vs/editor/common/editorCommon';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"import { Selection } from 'vs/editor/common/core/selection';\n",
"import { trimTrailingWhitespace } from 'vs/editor/common/commands/trimTrailingWhitespaceCommand';\n",
"import { getDocumentRangeFormattingEdits } from 'vs/editor/contrib/format/common/format';\n",
"import { EditOperationsCommand } from 'vs/editor/contrib/format/common/formatCommand';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';\n",
"import { ExtHostContext, ExtHostDocumentSaveParticipantShape } from './extHost.protocol';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { getDocumentFormattingEdits } from 'vs/editor/contrib/format/common/format';\n"
],
"file_path": "src/vs/workbench/api/node/mainThreadSaveParticipant.ts",
"type": "replace",
"edit_start_line_idx": 17
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.git-viewlet > .disabled-view {
padding: 0 20px 0 20px;
}
| src/vs/workbench/parts/git/browser/views/disabled/disabledView.css | 0 | https://github.com/microsoft/vscode/commit/5c553b6ad4fe7d80269c9c8c6f286c4b04e9460c | [
0.00017465070413891226,
0.00017465070413891226,
0.00017465070413891226,
0.00017465070413891226,
0
] |
{
"id": 1,
"code_window": [
"import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n",
"import { IPosition, IModel, ICommonCodeEditor, ISingleEditOperation, IIdentifiedSingleEditOperation } from 'vs/editor/common/editorCommon';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"import { Selection } from 'vs/editor/common/core/selection';\n",
"import { trimTrailingWhitespace } from 'vs/editor/common/commands/trimTrailingWhitespaceCommand';\n",
"import { getDocumentRangeFormattingEdits } from 'vs/editor/contrib/format/common/format';\n",
"import { EditOperationsCommand } from 'vs/editor/contrib/format/common/formatCommand';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';\n",
"import { ExtHostContext, ExtHostDocumentSaveParticipantShape } from './extHost.protocol';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { getDocumentFormattingEdits } from 'vs/editor/contrib/format/common/format';\n"
],
"file_path": "src/vs/workbench/api/node/mainThreadSaveParticipant.ts",
"type": "replace",
"edit_start_line_idx": 17
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"filesCategory": "Fichiers"
} | i18n/fra/src/vs/workbench/parts/files/electron-browser/files.electron.contribution.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5c553b6ad4fe7d80269c9c8c6f286c4b04e9460c | [
0.00017625204054638743,
0.00017625204054638743,
0.00017625204054638743,
0.00017625204054638743,
0
] |
{
"id": 1,
"code_window": [
"import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n",
"import { IPosition, IModel, ICommonCodeEditor, ISingleEditOperation, IIdentifiedSingleEditOperation } from 'vs/editor/common/editorCommon';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"import { Selection } from 'vs/editor/common/core/selection';\n",
"import { trimTrailingWhitespace } from 'vs/editor/common/commands/trimTrailingWhitespaceCommand';\n",
"import { getDocumentRangeFormattingEdits } from 'vs/editor/contrib/format/common/format';\n",
"import { EditOperationsCommand } from 'vs/editor/contrib/format/common/formatCommand';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';\n",
"import { ExtHostContext, ExtHostDocumentSaveParticipantShape } from './extHost.protocol';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { getDocumentFormattingEdits } from 'vs/editor/contrib/format/common/format';\n"
],
"file_path": "src/vs/workbench/api/node/mainThreadSaveParticipant.ts",
"type": "replace",
"edit_start_line_idx": 17
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"extensions": "확장"
} | i18n/kor/src/vs/platform/extensionManagement/common/extensionManagement.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5c553b6ad4fe7d80269c9c8c6f286c4b04e9460c | [
0.00017596354882698506,
0.00017596354882698506,
0.00017596354882698506,
0.00017596354882698506,
0
] |
{
"id": 2,
"code_window": [
"\n",
"\t\treturn new TPromise<ISingleEditOperation[]>((resolve, reject) => {\n",
"\t\t\tsetTimeout(resolve, 750);\n",
"\t\t\tgetDocumentRangeFormattingEdits(model, model.getFullModelRange(), { tabSize, insertSpaces }).then(resolve, reject);\n",
"\n",
"\t\t}).then(edits => {\n",
"\t\t\tif (edits) {\n",
"\t\t\t\tconst editor = this._findEditor(model);\n",
"\t\t\t\tif (editor) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgetDocumentFormattingEdits(model, { tabSize, insertSpaces }).then(resolve, reject);\n"
],
"file_path": "src/vs/workbench/api/node/mainThreadSaveParticipant.ts",
"type": "replace",
"edit_start_line_idx": 99
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { TPromise } from 'vs/base/common/winjs.base';
import { sequence } from 'vs/base/common/async';
import { ICodeEditorService } from 'vs/editor/common/services/codeEditorService';
import { IThreadService } from 'vs/workbench/services/thread/common/threadService';
import { ISaveParticipant, ITextFileEditorModel, SaveReason } from 'vs/workbench/services/textfile/common/textfiles';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IPosition, IModel, ICommonCodeEditor, ISingleEditOperation, IIdentifiedSingleEditOperation } from 'vs/editor/common/editorCommon';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { trimTrailingWhitespace } from 'vs/editor/common/commands/trimTrailingWhitespaceCommand';
import { getDocumentRangeFormattingEdits } from 'vs/editor/contrib/format/common/format';
import { EditOperationsCommand } from 'vs/editor/contrib/format/common/formatCommand';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';
import { ExtHostContext, ExtHostDocumentSaveParticipantShape } from './extHost.protocol';
class TrimWhitespaceParticipant implements ISaveParticipant {
constructor(
@IConfigurationService private configurationService: IConfigurationService,
@ICodeEditorService private codeEditorService: ICodeEditorService
) {
// Nothing
}
public participate(model: ITextFileEditorModel, env: { reason: SaveReason }): any {
if (this.configurationService.lookup('files.trimTrailingWhitespace').value) {
this.doTrimTrailingWhitespace(model.textEditorModel, env.reason === SaveReason.AUTO);
}
}
private doTrimTrailingWhitespace(model: IModel, isAutoSaved: boolean): void {
let prevSelection: Selection[] = [new Selection(1, 1, 1, 1)];
const cursors: IPosition[] = [];
// Find `prevSelection` in any case do ensure a good undo stack when pushing the edit
// Collect active cursors in `cursors` only if `isAutoSaved` to avoid having the cursors jump
if (model.isAttachedToEditor()) {
const allEditors = this.codeEditorService.listCodeEditors();
for (let i = 0, len = allEditors.length; i < len; i++) {
const editor = allEditors[i];
const editorModel = editor.getModel();
if (!editorModel) {
continue; // empty editor
}
if (model === editorModel) {
prevSelection = editor.getSelections();
if (isAutoSaved) {
cursors.push(...prevSelection.map(s => {
return {
lineNumber: s.positionLineNumber,
column: s.positionColumn
};
}));
}
}
}
}
const ops = trimTrailingWhitespace(model, cursors);
if (!ops.length) {
return; // Nothing to do
}
model.pushEditOperations(prevSelection, ops, (edits) => prevSelection);
}
}
class FormatOnSaveParticipant implements ISaveParticipant {
constructor(
@ICodeEditorService private _editorService: ICodeEditorService,
@IConfigurationService private _configurationService: IConfigurationService
) {
// Nothing
}
participate(editorModel: ITextFileEditorModel, env: { reason: SaveReason }): TPromise<any> {
if (env.reason === SaveReason.AUTO
|| !this._configurationService.lookup('editor.formatOnSave').value) {
return;
}
const model: IModel = editorModel.textEditorModel;
const {tabSize, insertSpaces} = model.getOptions();
return new TPromise<ISingleEditOperation[]>((resolve, reject) => {
setTimeout(resolve, 750);
getDocumentRangeFormattingEdits(model, model.getFullModelRange(), { tabSize, insertSpaces }).then(resolve, reject);
}).then(edits => {
if (edits) {
const editor = this._findEditor(model);
if (editor) {
this._editsWithEditor(editor, edits);
} else {
this._editWithModel(model, edits);
}
}
});
}
private _editsWithEditor(editor: ICommonCodeEditor, edits: ISingleEditOperation[]): void {
editor.executeCommand('files.formatOnSave', new EditOperationsCommand(edits, editor.getSelection()));
}
private _editWithModel(model: IModel, edits: ISingleEditOperation[]): void {
const [{range}] = edits;
const initialSelection = new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
model.pushEditOperations([initialSelection], edits.map(FormatOnSaveParticipant._asIdentEdit), undoEdits => {
for (const {range} of undoEdits) {
if (Range.areIntersectingOrTouching(range, initialSelection)) {
return [new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn)];
}
}
});
}
private static _asIdentEdit({text, range}: ISingleEditOperation): IIdentifiedSingleEditOperation {
return {
text,
range: Range.lift(range),
identifier: undefined,
forceMoveMarkers: true
};
}
private _findEditor(model: IModel) {
if (!model.isAttachedToEditor()) {
return;
}
let candidate: ICommonCodeEditor;
for (const editor of this._editorService.listCodeEditors()) {
if (editor.getModel() === model) {
if (editor.isFocused()) {
return editor;
} else {
candidate = editor;
}
}
}
return candidate;
}
}
class ExtHostSaveParticipant implements ISaveParticipant {
private _proxy: ExtHostDocumentSaveParticipantShape;
constructor( @IThreadService threadService: IThreadService) {
this._proxy = threadService.get(ExtHostContext.ExtHostDocumentSaveParticipant);
}
participate(editorModel: ITextFileEditorModel, env: { reason: SaveReason }): TPromise<any> {
return this._proxy.$participateInSave(editorModel.getResource(), env.reason);
}
}
// The save participant can change a model before its saved to support various scenarios like trimming trailing whitespace
export class SaveParticipant implements ISaveParticipant {
private _saveParticipants: ISaveParticipant[];
constructor(
@IInstantiationService instantiationService: IInstantiationService,
@IThreadService threadService: IThreadService
) {
this._saveParticipants = [
instantiationService.createInstance(TrimWhitespaceParticipant),
instantiationService.createInstance(FormatOnSaveParticipant),
instantiationService.createInstance(ExtHostSaveParticipant)
];
// Hook into model
TextFileEditorModel.setSaveParticipant(this);
}
participate(model: ITextFileEditorModel, env: { reason: SaveReason }): TPromise<any> {
const promiseFactory = this._saveParticipants.map(p => () => {
return TPromise.as(p.participate(model, env)).then(undefined, err => {
// console.error(err);
});
});
return sequence(promiseFactory);
}
}
| src/vs/workbench/api/node/mainThreadSaveParticipant.ts | 1 | https://github.com/microsoft/vscode/commit/5c553b6ad4fe7d80269c9c8c6f286c4b04e9460c | [
0.9973254203796387,
0.17734666168689728,
0.0001657788670854643,
0.00017552652570884675,
0.3436184525489807
] |
{
"id": 2,
"code_window": [
"\n",
"\t\treturn new TPromise<ISingleEditOperation[]>((resolve, reject) => {\n",
"\t\t\tsetTimeout(resolve, 750);\n",
"\t\t\tgetDocumentRangeFormattingEdits(model, model.getFullModelRange(), { tabSize, insertSpaces }).then(resolve, reject);\n",
"\n",
"\t\t}).then(edits => {\n",
"\t\t\tif (edits) {\n",
"\t\t\t\tconst editor = this._findEditor(model);\n",
"\t\t\t\tif (editor) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgetDocumentFormattingEdits(model, { tabSize, insertSpaces }).then(resolve, reject);\n"
],
"file_path": "src/vs/workbench/api/node/mainThreadSaveParticipant.ts",
"type": "replace",
"edit_start_line_idx": 99
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"ConfigurationParser.globalMatcher": "警告: 全域比對器和工作不能混用。即將忽略全域比對器。",
"ConfigurationParser.invalidCWD": "警告: options.cwd 必須屬於字串類型。即將忽略值 {0}\n",
"ConfigurationParser.invalidVaraibleReference": "錯誤: problemMatcher 參考無效: {0}\n",
"ConfigurationParser.noCommand": "錯誤: 未提供有效的命令名稱。",
"ConfigurationParser.noName": "錯誤: 宣告範圍中的問題比對器必須有名稱:\n{0}\n",
"ConfigurationParser.noTaskName": "錯誤: 工作必須提供 taskName 屬性。即將忽略此工作。\n{0}\n",
"ConfigurationParser.noargs": "錯誤: 命令引數必須是字串陣列。提供的值為:\n{0}",
"ConfigurationParser.unknownMatcherKind": "警告: 定義的問題比對器未知。支援的類型為 string | ProblemMatcher | (string | ProblemMatcher)[]。\n{0}\n"
} | i18n/cht/src/vs/workbench/parts/tasks/node/processRunnerConfiguration.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5c553b6ad4fe7d80269c9c8c6f286c4b04e9460c | [
0.00017339526675641537,
0.0001724510220810771,
0.0001715067628538236,
0.0001724510220810771,
9.442519512958825e-7
] |
{
"id": 2,
"code_window": [
"\n",
"\t\treturn new TPromise<ISingleEditOperation[]>((resolve, reject) => {\n",
"\t\t\tsetTimeout(resolve, 750);\n",
"\t\t\tgetDocumentRangeFormattingEdits(model, model.getFullModelRange(), { tabSize, insertSpaces }).then(resolve, reject);\n",
"\n",
"\t\t}).then(edits => {\n",
"\t\t\tif (edits) {\n",
"\t\t\t\tconst editor = this._findEditor(model);\n",
"\t\t\t\tif (editor) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgetDocumentFormattingEdits(model, { tabSize, insertSpaces }).then(resolve, reject);\n"
],
"file_path": "src/vs/workbench/api/node/mainThreadSaveParticipant.ts",
"type": "replace",
"edit_start_line_idx": 99
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"cssserver.name": "CSS 語言伺服器"
} | i18n/cht/extensions/css/client/out/cssMain.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5c553b6ad4fe7d80269c9c8c6f286c4b04e9460c | [
0.0001753707620082423,
0.0001753707620082423,
0.0001753707620082423,
0.0001753707620082423,
0
] |
{
"id": 2,
"code_window": [
"\n",
"\t\treturn new TPromise<ISingleEditOperation[]>((resolve, reject) => {\n",
"\t\t\tsetTimeout(resolve, 750);\n",
"\t\t\tgetDocumentRangeFormattingEdits(model, model.getFullModelRange(), { tabSize, insertSpaces }).then(resolve, reject);\n",
"\n",
"\t\t}).then(edits => {\n",
"\t\t\tif (edits) {\n",
"\t\t\t\tconst editor = this._findEditor(model);\n",
"\t\t\t\tif (editor) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgetDocumentFormattingEdits(model, { tabSize, insertSpaces }).then(resolve, reject);\n"
],
"file_path": "src/vs/workbench/api/node/mainThreadSaveParticipant.ts",
"type": "replace",
"edit_start_line_idx": 99
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { Dimension, Builder, Box } from 'vs/base/browser/builder';
import { Part } from 'vs/workbench/browser/part';
import { QuickOpenController } from 'vs/workbench/browser/parts/quickopen/quickOpenController';
import { Sash, ISashEvent, IVerticalSashLayoutProvider, IHorizontalSashLayoutProvider, Orientation } from 'vs/base/browser/ui/sash/sash';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IPartService, Position } from 'vs/workbench/services/part/common/partService';
import { IViewletService } from 'vs/workbench/services/viewlet/common/viewletService';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IEventService } from 'vs/platform/event/common/event';
import { IThemeService } from 'vs/workbench/services/themes/common/themeService';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
const DEFAULT_MIN_PART_WIDTH = 170;
const DEFAULT_MIN_PANEL_PART_HEIGHT = 77;
const DEFAULT_MIN_EDITOR_PART_HEIGHT = 170;
const HIDE_SIDEBAR_WIDTH_THRESHOLD = 50;
const HIDE_PANEL_HEIGHT_THRESHOLD = 50;
export class LayoutOptions {
public margin: Box;
constructor() {
this.margin = new Box(0, 0, 0, 0);
}
public setMargin(margin: Box): LayoutOptions {
this.margin = margin;
return this;
}
}
interface ComputedStyles {
activitybar: { minWidth: number; };
sidebar: { minWidth: number; };
panel: { minHeight: number; };
editor: { minWidth: number; };
statusbar: { height: number; };
}
/**
* The workbench layout is responsible to lay out all parts that make the Workbench.
*/
export class WorkbenchLayout implements IVerticalSashLayoutProvider, IHorizontalSashLayoutProvider {
private static sashXWidthSettingsKey = 'workbench.sidebar.width';
private static sashYHeightSettingsKey = 'workbench.panel.height';
private parent: Builder;
private workbenchContainer: Builder;
private activitybar: Part;
private editor: Part;
private sidebar: Part;
private panel: Part;
private statusbar: Part;
private quickopen: QuickOpenController;
private options: LayoutOptions;
private toUnbind: IDisposable[];
private computedStyles: ComputedStyles;
private workbenchSize: Dimension;
private sashX: Sash;
private sashY: Sash;
private startSidebarWidth: number;
private sidebarWidth: number;
private sidebarHeight: number;
private startPanelHeight: number;
private panelHeight: number;
private panelWidth: number;
// Take parts as an object bag since instatation service does not have typings for constructors with 9+ arguments
constructor(
parent: Builder,
workbenchContainer: Builder,
parts: {
activitybar: Part,
editor: Part,
sidebar: Part,
panel: Part,
statusbar: Part
},
quickopen: QuickOpenController,
options: LayoutOptions,
@IStorageService private storageService: IStorageService,
@IEventService eventService: IEventService,
@IContextViewService private contextViewService: IContextViewService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@IEditorGroupService editorGroupService: IEditorGroupService,
@IPartService private partService: IPartService,
@IViewletService private viewletService: IViewletService,
@IThemeService themeService: IThemeService
) {
this.parent = parent;
this.workbenchContainer = workbenchContainer;
this.activitybar = parts.activitybar;
this.editor = parts.editor;
this.sidebar = parts.sidebar;
this.panel = parts.panel;
this.statusbar = parts.statusbar;
this.quickopen = quickopen;
this.options = options || new LayoutOptions();
this.toUnbind = [];
this.computedStyles = null;
this.sashX = new Sash(this.workbenchContainer.getHTMLElement(), this, {
baseSize: 5
});
this.sashY = new Sash(this.workbenchContainer.getHTMLElement(), this, {
baseSize: 4,
orientation: Orientation.HORIZONTAL
});
this.sidebarWidth = this.storageService.getInteger(WorkbenchLayout.sashXWidthSettingsKey, StorageScope.GLOBAL, -1);
this.panelHeight = this.storageService.getInteger(WorkbenchLayout.sashYHeightSettingsKey, StorageScope.GLOBAL, 0);
this.toUnbind.push(themeService.onDidColorThemeChange(_ => this.relayout()));
this.toUnbind.push(editorGroupService.onEditorsChanged(() => this.onEditorsChanged()));
this.registerSashListeners();
}
private registerSashListeners(): void {
let startX: number = 0;
let startY: number = 0;
this.sashX.addListener2('start', (e: ISashEvent) => {
this.startSidebarWidth = this.sidebarWidth;
startX = e.startX;
});
this.sashY.addListener2('start', (e: ISashEvent) => {
this.startPanelHeight = this.panelHeight;
startY = e.startY;
});
this.sashX.addListener2('change', (e: ISashEvent) => {
let doLayout = false;
let sidebarPosition = this.partService.getSideBarPosition();
let isSidebarHidden = this.partService.isSideBarHidden();
let newSashWidth = (sidebarPosition === Position.LEFT) ? this.startSidebarWidth + e.currentX - startX : this.startSidebarWidth - e.currentX + startX;
// Sidebar visible
if (!isSidebarHidden) {
// Automatically hide side bar when a certain threshold is met
if (newSashWidth + HIDE_SIDEBAR_WIDTH_THRESHOLD < this.computedStyles.sidebar.minWidth) {
let dragCompensation = DEFAULT_MIN_PART_WIDTH - HIDE_SIDEBAR_WIDTH_THRESHOLD;
this.partService.setSideBarHidden(true);
startX = (sidebarPosition === Position.LEFT) ? Math.max(this.computedStyles.activitybar.minWidth, e.currentX - dragCompensation) : Math.min(e.currentX + dragCompensation, this.workbenchSize.width - this.computedStyles.activitybar.minWidth);
this.sidebarWidth = this.startSidebarWidth; // when restoring sidebar, restore to the sidebar width we started from
}
// Otherwise size the sidebar accordingly
else {
this.sidebarWidth = Math.max(this.computedStyles.sidebar.minWidth, newSashWidth); // Sidebar can not become smaller than MIN_PART_WIDTH
doLayout = newSashWidth >= this.computedStyles.sidebar.minWidth;
}
}
// Sidebar hidden
else {
if ((sidebarPosition === Position.LEFT && e.currentX - startX >= this.computedStyles.sidebar.minWidth) ||
(sidebarPosition === Position.RIGHT && startX - e.currentX >= this.computedStyles.sidebar.minWidth)) {
this.startSidebarWidth = this.computedStyles.sidebar.minWidth - (sidebarPosition === Position.LEFT ? e.currentX - startX : startX - e.currentX);
this.sidebarWidth = this.computedStyles.sidebar.minWidth;
this.partService.setSideBarHidden(false);
}
}
if (doLayout) {
this.layout();
}
});
this.sashY.addListener2('change', (e: ISashEvent) => {
let doLayout = false;
let isPanelHidden = this.partService.isPanelHidden();
let isStatusbarHidden = this.partService.isStatusBarHidden();
let newSashHeight = this.startPanelHeight - (e.currentY - startY);
// Panel visible
if (!isPanelHidden) {
// Automatically hide panel when a certain threshold is met
if (newSashHeight + HIDE_PANEL_HEIGHT_THRESHOLD < this.computedStyles.panel.minHeight) {
let dragCompensation = DEFAULT_MIN_PANEL_PART_HEIGHT - HIDE_PANEL_HEIGHT_THRESHOLD;
this.partService.setPanelHidden(true);
let statusbarHeight = isStatusbarHidden ? 0 : this.computedStyles.statusbar.height;
startY = Math.min(this.sidebarHeight - statusbarHeight, e.currentY + dragCompensation);
this.panelHeight = this.startPanelHeight; // when restoring panel, restore to the panel height we started from
}
// Otherwise size the panel accordingly
else {
this.panelHeight = Math.max(this.computedStyles.panel.minHeight, newSashHeight); // Panel can not become smaller than MIN_PART_HEIGHT
doLayout = newSashHeight >= this.computedStyles.panel.minHeight;
}
}
// Panel hidden
else {
if (startY - e.currentY >= this.computedStyles.panel.minHeight) {
this.startPanelHeight = 0;
this.panelHeight = this.computedStyles.panel.minHeight;
this.partService.setPanelHidden(false);
}
}
if (doLayout) {
this.layout();
}
});
this.sashX.addListener2('end', () => {
this.storageService.store(WorkbenchLayout.sashXWidthSettingsKey, this.sidebarWidth, StorageScope.GLOBAL);
});
this.sashY.addListener2('end', () => {
this.storageService.store(WorkbenchLayout.sashYHeightSettingsKey, this.panelHeight, StorageScope.GLOBAL);
});
this.sashY.addListener2('reset', () => {
this.panelHeight = DEFAULT_MIN_PANEL_PART_HEIGHT;
this.storageService.store(WorkbenchLayout.sashYHeightSettingsKey, this.panelHeight, StorageScope.GLOBAL);
this.partService.setPanelHidden(false);
this.layout();
});
this.sashX.addListener2('reset', () => {
let activeViewlet = this.viewletService.getActiveViewlet();
let optimalWidth = activeViewlet && activeViewlet.getOptimalWidth();
this.sidebarWidth = Math.max(DEFAULT_MIN_PART_WIDTH, optimalWidth || 0);
this.storageService.store(WorkbenchLayout.sashXWidthSettingsKey, this.sidebarWidth, StorageScope.GLOBAL);
this.partService.setSideBarHidden(false);
this.layout();
});
}
private onEditorsChanged(): void {
// Make sure that we layout properly in case we detect that the sidebar is large enought to cause
// multiple opened editors to go below minimal size. The fix is to trigger a layout for any editor
// input change that falls into this category.
if (this.workbenchSize && this.sidebarWidth) {
let visibleEditors = this.editorService.getVisibleEditors().length;
if (visibleEditors > 1 && this.workbenchSize.width - this.sidebarWidth < visibleEditors * DEFAULT_MIN_PART_WIDTH) {
this.layout();
}
}
}
private relayout(): void {
// Recompute Styles
this.computeStyle();
this.editor.getLayout().computeStyle();
this.sidebar.getLayout().computeStyle();
this.panel.getLayout().computeStyle();
// Trigger Layout
this.layout();
}
private computeStyle(): void {
const sidebarStyle = this.sidebar.getContainer().getComputedStyle();
const panelStyle = this.panel.getContainer().getComputedStyle();
const editorStyle = this.editor.getContainer().getComputedStyle();
const activitybarStyle = this.activitybar.getContainer().getComputedStyle();
const statusbarStyle = this.statusbar.getContainer().getComputedStyle();
this.computedStyles = {
activitybar: {
minWidth: parseInt(activitybarStyle.getPropertyValue('min-width'), 10) || 0
},
sidebar: {
minWidth: parseInt(sidebarStyle.getPropertyValue('min-width'), 10) || DEFAULT_MIN_PART_WIDTH
},
panel: {
minHeight: parseInt(panelStyle.getPropertyValue('min-height'), 10) || DEFAULT_MIN_PANEL_PART_HEIGHT
},
editor: {
minWidth: parseInt(editorStyle.getPropertyValue('min-width'), 10) || DEFAULT_MIN_PART_WIDTH
},
statusbar: {
height: parseInt(statusbarStyle.getPropertyValue('height'), 10) || 18
}
};
}
public layout(forceStyleReCompute?: boolean, toggleMaximizedPanel?: boolean): void {
if (forceStyleReCompute) {
this.computeStyle();
this.editor.getLayout().computeStyle();
this.sidebar.getLayout().computeStyle();
this.panel.getLayout().computeStyle();
}
if (!this.computedStyles) {
this.computeStyle();
}
this.workbenchSize = this.getWorkbenchArea();
const isSidebarHidden = this.partService.isSideBarHidden();
const isPanelHidden = this.partService.isPanelHidden();
const sidebarPosition = this.partService.getSideBarPosition();
const isStatusbarHidden = this.partService.isStatusBarHidden();
// Sidebar
let sidebarWidth: number;
if (isSidebarHidden) {
sidebarWidth = 0;
} else if (this.sidebarWidth !== -1) {
sidebarWidth = Math.max(this.computedStyles.sidebar.minWidth, this.sidebarWidth);
} else {
sidebarWidth = this.workbenchSize.width / 5;
this.sidebarWidth = sidebarWidth;
}
let statusbarHeight = isStatusbarHidden ? 0 : this.computedStyles.statusbar.height;
this.sidebarHeight = this.workbenchSize.height - statusbarHeight;
let sidebarSize = new Dimension(sidebarWidth, this.sidebarHeight);
// Activity Bar
let activityBarMinWidth = this.computedStyles.activitybar.minWidth;
let activityBarSize = new Dimension(activityBarMinWidth, sidebarSize.height);
// Panel part
let panelHeight: number;
const maxPanelHeight = sidebarSize.height - DEFAULT_MIN_EDITOR_PART_HEIGHT;
if (isPanelHidden) {
panelHeight = 0;
} else if (this.panelHeight > 0) {
panelHeight = Math.min(maxPanelHeight, Math.max(this.computedStyles.panel.minHeight, this.panelHeight));
} else {
panelHeight = sidebarSize.height * 0.4;
}
if (toggleMaximizedPanel) {
panelHeight = panelHeight === maxPanelHeight ? sidebarSize.height * 0.4 : maxPanelHeight;
}
const panelDimension = new Dimension(this.workbenchSize.width - sidebarSize.width - activityBarSize.width, panelHeight);
this.panelWidth = panelDimension.width;
// Editor
let editorSize = {
width: 0,
height: 0,
remainderLeft: 0,
remainderRight: 0
};
let editorDimension = new Dimension(panelDimension.width, sidebarSize.height - panelDimension.height);
editorSize.width = editorDimension.width;
editorSize.height = editorDimension.height;
// Sidebar hidden
if (isSidebarHidden) {
editorSize.width = Math.min(this.workbenchSize.width - activityBarSize.width, this.workbenchSize.width - activityBarMinWidth);
if (sidebarPosition === Position.LEFT) {
editorSize.remainderLeft = Math.round((this.workbenchSize.width - editorSize.width + activityBarSize.width) / 2);
editorSize.remainderRight = this.workbenchSize.width - editorSize.width - editorSize.remainderLeft;
} else {
editorSize.remainderRight = Math.round((this.workbenchSize.width - editorSize.width + activityBarSize.width) / 2);
editorSize.remainderLeft = this.workbenchSize.width - editorSize.width - editorSize.remainderRight;
}
}
// Assert Sidebar and Editor Size to not overflow
let editorMinWidth = this.computedStyles.editor.minWidth;
let visibleEditorCount = this.editorService.getVisibleEditors().length;
if (visibleEditorCount > 1) {
editorMinWidth *= visibleEditorCount;
}
if (editorSize.width < editorMinWidth) {
let diff = editorMinWidth - editorSize.width;
editorSize.width = editorMinWidth;
panelDimension.width = editorMinWidth;
sidebarSize.width -= diff;
sidebarSize.width = Math.max(DEFAULT_MIN_PART_WIDTH, sidebarSize.width);
}
if (!isSidebarHidden) {
this.sidebarWidth = sidebarSize.width;
this.storageService.store(WorkbenchLayout.sashXWidthSettingsKey, this.sidebarWidth, StorageScope.GLOBAL);
}
if (!isPanelHidden) {
this.panelHeight = panelDimension.height;
this.storageService.store(WorkbenchLayout.sashYHeightSettingsKey, this.panelHeight, StorageScope.GLOBAL);
}
// Workbench
this.workbenchContainer
.position(this.options.margin.top, this.options.margin.right, this.options.margin.bottom, this.options.margin.left, 'relative')
.size(this.workbenchSize.width, this.workbenchSize.height);
// Bug on Chrome: Sometimes Chrome wants to scroll the workbench container on layout changes. The fix is to reset scrollTop in this case.
if (this.workbenchContainer.getHTMLElement().scrollTop > 0) {
this.workbenchContainer.getHTMLElement().scrollTop = 0;
}
// Editor Part and Panel part
this.editor.getContainer().size(editorSize.width, editorSize.height);
this.panel.getContainer().size(panelDimension.width, panelDimension.height);
const editorBottom = statusbarHeight + panelDimension.height;
if (isSidebarHidden) {
this.editor.getContainer().position(0, editorSize.remainderRight, editorBottom, editorSize.remainderLeft);
this.panel.getContainer().position(editorDimension.height, editorSize.remainderRight, statusbarHeight, editorSize.remainderLeft);
} else if (sidebarPosition === Position.LEFT) {
this.editor.getContainer().position(0, 0, editorBottom, sidebarSize.width + activityBarSize.width);
this.panel.getContainer().position(editorDimension.height, 0, statusbarHeight, sidebarSize.width + activityBarSize.width);
} else {
this.editor.getContainer().position(0, sidebarSize.width, editorBottom, 0);
this.panel.getContainer().position(editorDimension.height, sidebarSize.width, statusbarHeight, 0);
}
// Activity Bar Part
this.activitybar.getContainer().size(null, activityBarSize.height);
if (sidebarPosition === Position.LEFT) {
this.activitybar.getContainer().getHTMLElement().style.right = '';
this.activitybar.getContainer().position(0, null, 0, 0);
} else {
this.activitybar.getContainer().getHTMLElement().style.left = '';
this.activitybar.getContainer().position(0, 0, 0, null);
}
// Sidebar Part
this.sidebar.getContainer().size(sidebarSize.width, sidebarSize.height);
if (sidebarPosition === Position.LEFT) {
this.sidebar.getContainer().position(0, editorSize.width, 0, activityBarSize.width);
} else {
this.sidebar.getContainer().position(0, null, 0, editorSize.width);
}
// Statusbar Part
this.statusbar.getContainer().position(this.workbenchSize.height - statusbarHeight);
// Quick open
this.quickopen.layout(this.workbenchSize);
// Sashes
this.sashX.layout();
this.sashY.layout();
// Propagate to Part Layouts
this.editor.layout(new Dimension(editorSize.width, editorSize.height));
this.sidebar.layout(sidebarSize);
this.panel.layout(panelDimension);
// Propagate to Context View
this.contextViewService.layout();
}
private getWorkbenchArea(): Dimension {
// Client Area: Parent
let clientArea = this.parent.getClientArea();
// Workbench: Client Area - Margins
return clientArea.substract(this.options.margin);
}
public getVerticalSashTop(sash: Sash): number {
return 0;
}
public getVerticalSashLeft(sash: Sash): number {
let isSidebarHidden = this.partService.isSideBarHidden();
let sidebarPosition = this.partService.getSideBarPosition();
let activitybarWidth = this.computedStyles.activitybar.minWidth;
if (sidebarPosition === Position.LEFT) {
return !isSidebarHidden ? this.sidebarWidth + activitybarWidth : activitybarWidth;
}
return !isSidebarHidden ? this.workbenchSize.width - this.sidebarWidth - activitybarWidth : this.workbenchSize.width - activitybarWidth;
}
public getVerticalSashHeight(sash: Sash): number {
return this.sidebarHeight;
}
public getHorizontalSashTop(sash: Sash): number {
return 2 + (this.partService.isPanelHidden() ? this.sidebarHeight : this.sidebarHeight - this.panelHeight); // Horizontal sash should be a bit lower than the editor area, thus add 2px #5524
}
public getHorizontalSashLeft(sash: Sash): number {
return this.partService.getSideBarPosition() === Position.LEFT ? this.getVerticalSashLeft(sash) : 0;
}
public getHorizontalSashWidth(sash: Sash): number {
return this.panelWidth;
}
public dispose(): void {
if (this.toUnbind) {
dispose(this.toUnbind);
this.toUnbind = null;
}
}
} | src/vs/workbench/browser/layout.ts | 0 | https://github.com/microsoft/vscode/commit/5c553b6ad4fe7d80269c9c8c6f286c4b04e9460c | [
0.00017851963639259338,
0.00017264889902435243,
0.00016546696133445948,
0.00017270955140702426,
0.0000028740917059622006
] |
{
"id": 0,
"code_window": [
"load(\"@aio_npm//@bazel/jasmine:index.bzl\", \"jasmine_node_test\")\n",
"load(\"//tools:defaults.bzl\", \"nodejs_binary\")\n",
"load(\"@aio_npm//@angular/build-tooling/bazel/remote-execution:index.bzl\", \"ENABLE_NETWORK\")\n",
"\n",
"DEPLOY_TO_FIREBASE_SOURCES = glob(\n",
" [\"**/*.mjs\"],\n",
" [\"**/*.spec.mjs\"],\n",
")\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"load(\"//:yarn.bzl\", \"YARN_LABEL\")\n"
],
"file_path": "aio/scripts/deploy-to-firebase/BUILD.bazel",
"type": "add",
"edit_start_line_idx": 3
} | load("@aio_npm//@bazel/jasmine:index.bzl", "jasmine_node_test")
load("//tools:defaults.bzl", "nodejs_binary")
load("@aio_npm//@angular/build-tooling/bazel/remote-execution:index.bzl", "ENABLE_NETWORK")
DEPLOY_TO_FIREBASE_SOURCES = glob(
["**/*.mjs"],
["**/*.spec.mjs"],
)
DEPLOY_TO_FIREBASE_DEPS = [
"@aio_npm//shelljs",
"//aio:build",
"//:package.json",
]
nodejs_binary(
name = "deploy-to-firebase",
data = DEPLOY_TO_FIREBASE_SOURCES + DEPLOY_TO_FIREBASE_DEPS,
entry_point = "index.mjs",
)
jasmine_node_test(
name = "test",
srcs = glob(["**/*.spec.mjs"]),
data = DEPLOY_TO_FIREBASE_SOURCES,
# Tests make remote calls to git
exec_properties = ENABLE_NETWORK,
tags = ["requires-network"],
deps = DEPLOY_TO_FIREBASE_DEPS,
)
| aio/scripts/deploy-to-firebase/BUILD.bazel | 1 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.999492883682251,
0.7494150996208191,
0.00020609149942174554,
0.9989807605743408,
0.4325562119483948
] |
{
"id": 0,
"code_window": [
"load(\"@aio_npm//@bazel/jasmine:index.bzl\", \"jasmine_node_test\")\n",
"load(\"//tools:defaults.bzl\", \"nodejs_binary\")\n",
"load(\"@aio_npm//@angular/build-tooling/bazel/remote-execution:index.bzl\", \"ENABLE_NETWORK\")\n",
"\n",
"DEPLOY_TO_FIREBASE_SOURCES = glob(\n",
" [\"**/*.mjs\"],\n",
" [\"**/*.spec.mjs\"],\n",
")\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"load(\"//:yarn.bzl\", \"YARN_LABEL\")\n"
],
"file_path": "aio/scripts/deploy-to-firebase/BUILD.bazel",
"type": "add",
"edit_start_line_idx": 3
} | {
"en": [
"a",
"able",
"about",
"above",
"abst",
"accordance",
"according",
"accordingly",
"across",
"act",
"actually",
"added",
"adj",
"adopted",
"affected",
"affecting",
"affects",
"after",
"afterwards",
"again",
"against",
"ah",
"all",
"almost",
"alone",
"along",
"already",
"also",
"although",
"always",
"am",
"among",
"amongst",
"an",
"and",
"announce",
"another",
"any",
"anybody",
"anyhow",
"anymore",
"anyone",
"anything",
"anyway",
"anyways",
"anywhere",
"apparently",
"approximately",
"are",
"aren",
"arent",
"arise",
"around",
"as",
"aside",
"ask",
"asking",
"at",
"auth",
"available",
"away",
"awfully",
"b",
"back",
"be",
"became",
"because",
"become",
"becomes",
"becoming",
"been",
"before",
"beforehand",
"begin",
"beginning",
"beginnings",
"begins",
"behind",
"being",
"believe",
"below",
"beside",
"besides",
"between",
"beyond",
"biol",
"both",
"brief",
"briefly",
"but",
"by",
"c",
"ca",
"came",
"can",
"cannot",
"can't",
"cant",
"cause",
"causes",
"certain",
"certainly",
"co",
"com",
"come",
"comes",
"contain",
"containing",
"contains",
"could",
"couldnt",
"d",
"date",
"did",
"didn't",
"didnt",
"different",
"do",
"does",
"doesn't",
"doesnt",
"doing",
"done",
"don't",
"dont",
"down",
"downwards",
"due",
"during",
"e",
"each",
"ed",
"edu",
"effect",
"eg",
"eight",
"eighty",
"either",
"else",
"elsewhere",
"end",
"ending",
"enough",
"especially",
"et",
"et-al",
"etc",
"even",
"ever",
"every",
"everybody",
"everyone",
"everything",
"everywhere",
"ex",
"except",
"f",
"far",
"few",
"ff",
"fifth",
"first",
"five",
"fix",
"followed",
"following",
"follows",
"for",
"former",
"formerly",
"forth",
"found",
"four",
"from",
"further",
"furthermore",
"g",
"gave",
"get",
"gets",
"getting",
"give",
"given",
"gives",
"giving",
"go",
"goes",
"gone",
"got",
"gotten",
"h",
"had",
"happens",
"hardly",
"has",
"hasn't",
"hasnt",
"have",
"haven't",
"havent",
"having",
"he",
"hed",
"hence",
"her",
"here",
"hereafter",
"hereby",
"herein",
"heres",
"hereupon",
"hers",
"herself",
"hes",
"hi",
"hid",
"him",
"himself",
"his",
"hither",
"home",
"how",
"howbeit",
"however",
"hundred",
"i",
"id",
"ie",
"if",
"i'll",
"ill",
"im",
"immediate",
"immediately",
"importance",
"important",
"in",
"inc",
"indeed",
"index",
"information",
"instead",
"into",
"invention",
"inward",
"is",
"isn't",
"isnt",
"it",
"itd",
"it'll",
"itll",
"its",
"itself",
"i've",
"ive",
"j",
"just",
"k",
"keep",
"keeps",
"kept",
"keys",
"kg",
"km",
"know",
"known",
"knows",
"l",
"largely",
"last",
"lately",
"later",
"latter",
"latterly",
"least",
"less",
"lest",
"let",
"lets",
"like",
"liked",
"likely",
"line",
"little",
"'ll",
"'ll",
"look",
"looking",
"looks",
"ltd",
"m",
"made",
"mainly",
"make",
"makes",
"many",
"may",
"maybe",
"me",
"mean",
"means",
"meantime",
"meanwhile",
"merely",
"mg",
"might",
"million",
"miss",
"ml",
"more",
"moreover",
"most",
"mostly",
"mr",
"mrs",
"much",
"mug",
"must",
"my",
"myself",
"n",
"na",
"name",
"namely",
"nay",
"nd",
"near",
"nearly",
"necessarily",
"necessary",
"need",
"needs",
"neither",
"never",
"nevertheless",
"new",
"next",
"nine",
"ninety",
"no",
"nobody",
"non",
"none",
"nonetheless",
"noone",
"nor",
"normally",
"nos",
"not",
"noted",
"nothing",
"now",
"nowhere",
"o",
"obtain",
"obtained",
"obviously",
"of",
"off",
"often",
"oh",
"ok",
"okay",
"old",
"omitted",
"on",
"once",
"one",
"ones",
"only",
"onto",
"or",
"ord",
"other",
"others",
"otherwise",
"ought",
"our",
"ours",
"ourselves",
"out",
"outside",
"over",
"overall",
"owing",
"own",
"p",
"page",
"pages",
"part",
"particular",
"particularly",
"past",
"per",
"perhaps",
"placed",
"please",
"plus",
"poorly",
"possible",
"possibly",
"potentially",
"pp",
"predominantly",
"present",
"previously",
"primarily",
"probably",
"promptly",
"proud",
"provides",
"put",
"q",
"que",
"quickly",
"quite",
"qv",
"r",
"ran",
"rather",
"rd",
"re",
"readily",
"really",
"recent",
"recently",
"ref",
"refs",
"regarding",
"regardless",
"regards",
"related",
"relatively",
"research",
"respectively",
"resulted",
"resulting",
"results",
"right",
"run",
"s",
"said",
"same",
"saw",
"say",
"saying",
"says",
"sec",
"section",
"see",
"seeing",
"seem",
"seemed",
"seeming",
"seems",
"seen",
"self",
"selves",
"sent",
"seven",
"several",
"shall",
"she",
"shed",
"she'll",
"shell",
"shes",
"should",
"shouldn't",
"shouldnt",
"show",
"showed",
"shown",
"showns",
"shows",
"significant",
"significantly",
"similar",
"similarly",
"since",
"six",
"slightly",
"so",
"some",
"somebody",
"somehow",
"someone",
"somethan",
"something",
"sometime",
"sometimes",
"somewhat",
"somewhere",
"soon",
"sorry",
"specifically",
"specified",
"specify",
"specifying",
"state",
"states",
"still",
"stop",
"strongly",
"sub",
"substantially",
"successfully",
"such",
"sufficiently",
"suggest",
"sup",
"sure",
"t",
"take",
"taken",
"taking",
"tell",
"tends",
"th",
"than",
"thank",
"thanks",
"thanx",
"that",
"that'll",
"thatll",
"thats",
"that've",
"thatve",
"the",
"their",
"theirs",
"them",
"themselves",
"then",
"thence",
"there",
"thereafter",
"thereby",
"thered",
"therefore",
"therein",
"there'll",
"therell",
"thereof",
"therere",
"theres",
"thereto",
"thereupon",
"there've",
"thereve",
"these",
"they",
"theyd",
"they'll",
"theyll",
"theyre",
"they've",
"theyve",
"think",
"this",
"those",
"thou",
"though",
"thoughh",
"thousand",
"throug",
"through",
"throughout",
"thru",
"thus",
"til",
"tip",
"to",
"together",
"too",
"took",
"toward",
"towards",
"tried",
"tries",
"truly",
"try",
"trying",
"ts",
"twice",
"two",
"u",
"un",
"under",
"unfortunately",
"unless",
"unlike",
"unlikely",
"until",
"unto",
"up",
"upon",
"ups",
"us",
"use",
"used",
"useful",
"usefully",
"usefulness",
"uses",
"using",
"usually",
"v",
"value",
"various",
"'ve",
"'ve",
"very",
"via",
"viz",
"vol",
"vols",
"vs",
"w",
"want",
"wants",
"was",
"wasn't",
"wasnt",
"way",
"we",
"wed",
"welcome",
"we'll",
"well",
"went",
"were",
"weren't",
"werent",
"we've",
"weve",
"what",
"whatever",
"what'll",
"whatll",
"whats",
"when",
"whence",
"whenever",
"where",
"whereafter",
"whereas",
"whereby",
"wherein",
"wheres",
"whereupon",
"wherever",
"whether",
"which",
"while",
"whim",
"whither",
"who",
"whod",
"whoever",
"whole",
"who'll",
"wholl",
"whom",
"whomever",
"whos",
"whose",
"why",
"widely",
"will",
"willing",
"wish",
"with",
"within",
"without",
"won't",
"wont",
"words",
"would",
"wouldn't",
"wouldnt",
"www",
"x",
"y",
"yes",
"yet",
"you",
"youd",
"you'll",
"youll",
"your",
"youre",
"yours",
"yourself",
"yourselves",
"you've",
"youve",
"z",
"zero"
]
}
| aio/tools/transforms/angular-base-package/ignore-words.json | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.00017310849216300994,
0.00016998806677293032,
0.00016610592138022184,
0.00016997868078760803,
0.0000014188609611665015
] |
{
"id": 0,
"code_window": [
"load(\"@aio_npm//@bazel/jasmine:index.bzl\", \"jasmine_node_test\")\n",
"load(\"//tools:defaults.bzl\", \"nodejs_binary\")\n",
"load(\"@aio_npm//@angular/build-tooling/bazel/remote-execution:index.bzl\", \"ENABLE_NETWORK\")\n",
"\n",
"DEPLOY_TO_FIREBASE_SOURCES = glob(\n",
" [\"**/*.mjs\"],\n",
" [\"**/*.spec.mjs\"],\n",
")\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"load(\"//:yarn.bzl\", \"YARN_LABEL\")\n"
],
"file_path": "aio/scripts/deploy-to-firebase/BUILD.bazel",
"type": "add",
"edit_start_line_idx": 3
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, ComponentFactoryResolver, Injector, NgModule, TemplateRef, ViewChild, ViewContainerRef} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
describe('TemplateRef', () => {
describe('rootNodes', () => {
@Component({template: `<ng-template #templateRef></ng-template>`})
class App {
@ViewChild('templateRef', {static: true}) templateRef!: TemplateRef<any>;
minutes = 0;
}
function getRootNodes(template: string): any[] {
TestBed.configureTestingModule({
declarations: [App],
});
TestBed.overrideTemplate(App, template);
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const embeddedView = fixture.componentInstance.templateRef.createEmbeddedView({});
embeddedView.detectChanges();
return embeddedView.rootNodes;
}
it('should return root render nodes for an embedded view instance', () => {
const rootNodes =
getRootNodes(`<ng-template #templateRef><div></div>some text<span></span></ng-template>`);
expect(rootNodes.length).toBe(3);
});
it('should return an empty array for embedded view with no nodes', () => {
const rootNodes = getRootNodes('<ng-template #templateRef></ng-template>');
expect(rootNodes.length).toBe(0);
});
it('should include projected nodes and their children', () => {
@Component({
selector: 'menu-content',
template: `
<ng-template>
Header
<ng-content></ng-content>
</ng-template>
`,
exportAs: 'menuContent'
})
class MenuContent {
@ViewChild(TemplateRef, {static: true}) template!: TemplateRef<any>;
}
@Component({
template: `
<menu-content #menu="menuContent">
<button>Item one</button>
<button>Item two</button>
<ng-template [ngIf]="true"><button>Item three</button></ng-template>
</menu-content>
`
})
class App {
@ViewChild(MenuContent) content!: MenuContent;
constructor(public viewContainerRef: ViewContainerRef) {}
}
TestBed.configureTestingModule({declarations: [MenuContent, App]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const instance = fixture.componentInstance;
const viewRef = instance.viewContainerRef.createEmbeddedView(instance.content.template);
const rootNodeTextContent =
viewRef.rootNodes.map(node => node && node.textContent.trim())
.filter(text => text !== '' && text.indexOf('ng-reflect-ng-if') === -1);
expect(rootNodeTextContent).toEqual(['Header', 'Item one', 'Item two', 'Item three']);
});
it('should descend into view containers on ng-template', () => {
/**
* NOTE: In VE, if `SUFFIX` text node below is _not_ present, VE will add an
* additional `<!---->` comment, thus being slightly different than Ivy.
* (resulting in 1 root node in Ivy and 2 in VE).
*/
const rootNodes = getRootNodes(`
<ng-template #templateRef>
<ng-template [ngIf]="true">text|</ng-template>SUFFIX
</ng-template>`);
expect(rootNodes.length).toBe(3);
expect(rootNodes[0].nodeType).toBe(Node.COMMENT_NODE);
expect(rootNodes[1].nodeType).toBe(Node.TEXT_NODE);
expect(rootNodes[2].nodeType).toBe(Node.TEXT_NODE);
});
it('should descend into view containers on an element', () => {
/**
* NOTE: In VE, if `SUFFIX` text node below is _not_ present, VE will add an
* additional `<!---->` comment, thus being slightly different than Ivy.
* (resulting in 1 root node in Ivy and 2 in VE).
*/
const rootNodes = getRootNodes(`
<ng-template #dynamicTpl>text</ng-template>
<ng-template #templateRef>
<div [ngTemplateOutlet]="dynamicTpl"></div>SUFFIX
</ng-template>
`);
expect(rootNodes.length).toBe(3);
expect(rootNodes[0].nodeType).toBe(Node.ELEMENT_NODE);
expect(rootNodes[1].nodeType).toBe(Node.TEXT_NODE);
expect(rootNodes[2].nodeType).toBe(Node.TEXT_NODE);
});
it('should descend into view containers on ng-container', () => {
/**
* NOTE: In VE, if `SUFFIX` text node below is _not_ present, VE will add an
* additional `<!---->` comment, thus being slightly different than Ivy.
* (resulting in 1 root node in Ivy and 2 in VE).
*/
const rootNodes = getRootNodes(`
<ng-template #dynamicTpl>text</ng-template>
<ng-template #templateRef><ng-container [ngTemplateOutlet]="dynamicTpl"></ng-container>SUFFIX</ng-template>
`);
expect(rootNodes.length).toBe(3);
expect(rootNodes[0].nodeType).toBe(Node.COMMENT_NODE);
expect(rootNodes[1].nodeType).toBe(Node.TEXT_NODE);
expect(rootNodes[2].nodeType).toBe(Node.TEXT_NODE);
});
it('should descend into element containers', () => {
const rootNodes = getRootNodes(`
<ng-template #templateRef>
<ng-container>text</ng-container>
</ng-template>
`);
expect(rootNodes.length).toBe(2);
expect(rootNodes[0].nodeType).toBe(Node.COMMENT_NODE);
expect(rootNodes[1].nodeType).toBe(Node.TEXT_NODE);
});
it('should descend into ICU containers', () => {
const rootNodes = getRootNodes(`
<ng-template #templateRef>
<ng-container i18n>Updated {minutes, select, =0 {just now} other {some time ago}}</ng-container>
</ng-template>
`);
expect(rootNodes.length).toBe(4);
expect(rootNodes[0].nodeType).toBe(Node.COMMENT_NODE); // ng-container
expect(rootNodes[1].nodeType).toBe(Node.TEXT_NODE); // "Updated " text
expect(rootNodes[2].nodeType).toBe(Node.COMMENT_NODE); // ICU container
expect(rootNodes[3].nodeType).toBe(Node.TEXT_NODE); // "one minute ago" text
});
it('should return an empty array for an embedded view with projection and no projectable nodes',
() => {
const rootNodes =
getRootNodes(`<ng-template #templateRef><ng-content></ng-content></ng-template>`);
expect(rootNodes.length).toBe(0);
});
it('should return an empty array for an embedded view with multiple projections and no projectable nodes',
() => {
const rootNodes = getRootNodes(
`<ng-template #templateRef><ng-content></ng-content><ng-content select="foo"></ng-content></ng-template>`);
expect(rootNodes.length).toBe(0);
});
describe('projectable nodes provided to a dynamically created component', () => {
@Component({selector: 'dynamic', template: ''})
class DynamicCmp {
@ViewChild('templateRef', {static: true}) templateRef!: TemplateRef<any>;
}
@Component({selector: 'test', template: ''})
class TestCmp {
constructor(public cfr: ComponentFactoryResolver) {}
}
beforeEach(() => {
TestBed.configureTestingModule({declarations: [TestCmp, DynamicCmp]});
});
it('should return projectable nodes when provided', () => {
TestBed.overrideTemplate(
DynamicCmp, `<ng-template #templateRef><ng-content></ng-content></ng-template>`);
const fixture = TestBed.createComponent(TestCmp);
const dynamicCmptFactory =
fixture.componentInstance.cfr.resolveComponentFactory(DynamicCmp);
// Number of projectable nodes matches the number of slots - all nodes should be returned
const projectableNodes = [[document.createTextNode('textNode')]];
const cmptRef = dynamicCmptFactory.create(Injector.NULL, projectableNodes);
const viewRef = cmptRef.instance.templateRef.createEmbeddedView({});
expect(viewRef.rootNodes.length).toBe(1);
});
it('should return an empty collection when no projectable nodes were provided', () => {
TestBed.overrideTemplate(
DynamicCmp, `<ng-template #templateRef><ng-content></ng-content></ng-template>`);
const fixture = TestBed.createComponent(TestCmp);
const dynamicCmptFactory =
fixture.componentInstance.cfr.resolveComponentFactory(DynamicCmp);
// There are slots but projectable nodes were not provided - nothing should be returned
const cmptRef = dynamicCmptFactory.create(Injector.NULL, []);
const viewRef = cmptRef.instance.templateRef.createEmbeddedView({});
expect(viewRef.rootNodes.length).toBe(0);
});
it('should return an empty collection when projectable nodes were provided but there are no slots',
() => {
TestBed.overrideTemplate(DynamicCmp, `<ng-template #templateRef></ng-template>`);
const fixture = TestBed.createComponent(TestCmp);
const dynamicCmptFactory =
fixture.componentInstance.cfr.resolveComponentFactory(DynamicCmp);
// There are no slots but projectable were provided - nothing should be returned
const projectableNodes = [[document.createTextNode('textNode')]];
const cmptRef = dynamicCmptFactory.create(Injector.NULL, projectableNodes);
const viewRef = cmptRef.instance.templateRef.createEmbeddedView({});
expect(viewRef.rootNodes.length).toBe(0);
});
});
});
describe('context', () => {
@Component({
template: `
<ng-template #templateRef let-name="name">{{name}}</ng-template>
<ng-container #containerRef></ng-container>
`
})
class App {
@ViewChild('templateRef') templateRef!: TemplateRef<any>;
@ViewChild('containerRef', {read: ViewContainerRef}) containerRef!: ViewContainerRef;
}
it('should update if the context of a view ref is mutated', () => {
TestBed.configureTestingModule({declarations: [App]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const context = {name: 'Frodo'};
const viewRef = fixture.componentInstance.templateRef.createEmbeddedView(context);
fixture.componentInstance.containerRef.insert(viewRef);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('Frodo');
context.name = 'Bilbo';
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('Bilbo');
});
it('should update if the context of a view ref is replaced', () => {
TestBed.configureTestingModule({declarations: [App]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const viewRef = fixture.componentInstance.templateRef.createEmbeddedView({name: 'Frodo'});
fixture.componentInstance.containerRef.insert(viewRef);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('Frodo');
viewRef.context = {name: 'Bilbo'};
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('Bilbo');
});
it('should use the latest context information inside template listeners', () => {
const events: string[] = [];
@Component({
template: `
<ng-template #templateRef let-name="name">
<button (click)="log(name)"></button>
</ng-template>
<ng-container #containerRef></ng-container>
`
})
class ListenerTest {
@ViewChild('templateRef') templateRef!: TemplateRef<any>;
@ViewChild('containerRef', {read: ViewContainerRef}) containerRef!: ViewContainerRef;
log(name: string) {
events.push(name);
}
}
TestBed.configureTestingModule({declarations: [ListenerTest]});
const fixture = TestBed.createComponent(ListenerTest);
fixture.detectChanges();
const viewRef = fixture.componentInstance.templateRef.createEmbeddedView({name: 'Frodo'});
fixture.componentInstance.containerRef.insert(viewRef);
fixture.detectChanges();
const button = fixture.nativeElement.querySelector('button');
button.click();
expect(events).toEqual(['Frodo']);
viewRef.context = {name: 'Bilbo'};
fixture.detectChanges();
button.click();
expect(events).toEqual(['Frodo', 'Bilbo']);
});
});
});
| packages/core/test/acceptance/template_ref_spec.ts | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.0001768257061485201,
0.00017104377911891788,
0.00016520291683264077,
0.00017139838018920273,
0.000002948199380625738
] |
{
"id": 0,
"code_window": [
"load(\"@aio_npm//@bazel/jasmine:index.bzl\", \"jasmine_node_test\")\n",
"load(\"//tools:defaults.bzl\", \"nodejs_binary\")\n",
"load(\"@aio_npm//@angular/build-tooling/bazel/remote-execution:index.bzl\", \"ENABLE_NETWORK\")\n",
"\n",
"DEPLOY_TO_FIREBASE_SOURCES = glob(\n",
" [\"**/*.mjs\"],\n",
" [\"**/*.spec.mjs\"],\n",
")\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"load(\"//:yarn.bzl\", \"YARN_LABEL\")\n"
],
"file_path": "aio/scripts/deploy-to-firebase/BUILD.bazel",
"type": "add",
"edit_start_line_idx": 3
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {assertDefined} from '../../util/assert';
import {global} from '../../util/global';
import {setProfiler} from '../profiler';
import {applyChanges} from './change_detection_utils';
import {getComponent, getContext, getDirectiveMetadata, getDirectives, getHostElement, getInjector, getListeners, getOwningComponent, getRootComponents} from './discovery_utils';
/**
* This file introduces series of globally accessible debug tools
* to allow for the Angular debugging story to function.
*
* To see this in action run the following command:
*
* bazel run //packages/core/test/bundling/todo:devserver
*
* Then load `localhost:5432` and start using the console tools.
*/
/**
* This value reflects the property on the window where the dev
* tools are patched (window.ng).
* */
export const GLOBAL_PUBLISH_EXPANDO_KEY = 'ng';
let _published = false;
/**
* Publishes a collection of default debug tools onto`window.ng`.
*
* These functions are available globally when Angular is in development
* mode and are automatically stripped away from prod mode is on.
*/
export function publishDefaultGlobalUtils() {
if (!_published) {
_published = true;
/**
* Warning: this function is *INTERNAL* and should not be relied upon in application's code.
* The contract of the function might be changed in any release and/or the function can be
* removed completely.
*/
publishGlobalUtil('ɵsetProfiler', setProfiler);
publishGlobalUtil('getDirectiveMetadata', getDirectiveMetadata);
publishGlobalUtil('getComponent', getComponent);
publishGlobalUtil('getContext', getContext);
publishGlobalUtil('getListeners', getListeners);
publishGlobalUtil('getOwningComponent', getOwningComponent);
publishGlobalUtil('getHostElement', getHostElement);
publishGlobalUtil('getInjector', getInjector);
publishGlobalUtil('getRootComponents', getRootComponents);
publishGlobalUtil('getDirectives', getDirectives);
publishGlobalUtil('applyChanges', applyChanges);
}
}
export declare type GlobalDevModeContainer = {
[GLOBAL_PUBLISH_EXPANDO_KEY]: {[fnName: string]: Function};
};
/**
* Publishes the given function to `window.ng` so that it can be
* used from the browser console when an application is not in production.
*/
export function publishGlobalUtil(name: string, fn: Function): void {
if (typeof COMPILED === 'undefined' || !COMPILED) {
// Note: we can't export `ng` when using closure enhanced optimization as:
// - closure declares globals itself for minified names, which sometimes clobber our `ng` global
// - we can't declare a closure extern as the namespace `ng` is already used within Google
// for typings for AngularJS (via `goog.provide('ng....')`).
const w = global as any as GlobalDevModeContainer;
ngDevMode && assertDefined(fn, 'function not defined');
if (w) {
let container = w[GLOBAL_PUBLISH_EXPANDO_KEY];
if (!container) {
container = w[GLOBAL_PUBLISH_EXPANDO_KEY] = {};
}
container[name] = fn;
}
}
}
| packages/core/src/render3/util/global_utils.ts | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.0002826558775268495,
0.00019017762679141015,
0.0001619257964193821,
0.00016772164963185787,
0.00004284139140509069
] |
{
"id": 1,
"code_window": [
"\n",
"DEPLOY_TO_FIREBASE_DEPS = [\n",
" \"@aio_npm//shelljs\",\n",
" \"//aio:build\",\n",
" \"//:package.json\",\n",
"]\n",
"\n",
"nodejs_binary(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" YARN_LABEL,\n"
],
"file_path": "aio/scripts/deploy-to-firebase/BUILD.bazel",
"type": "add",
"edit_start_line_idx": 13
} | load("@aio_npm//@bazel/jasmine:index.bzl", "jasmine_node_test")
load("//tools:defaults.bzl", "nodejs_binary")
load("@aio_npm//@angular/build-tooling/bazel/remote-execution:index.bzl", "ENABLE_NETWORK")
DEPLOY_TO_FIREBASE_SOURCES = glob(
["**/*.mjs"],
["**/*.spec.mjs"],
)
DEPLOY_TO_FIREBASE_DEPS = [
"@aio_npm//shelljs",
"//aio:build",
"//:package.json",
]
nodejs_binary(
name = "deploy-to-firebase",
data = DEPLOY_TO_FIREBASE_SOURCES + DEPLOY_TO_FIREBASE_DEPS,
entry_point = "index.mjs",
)
jasmine_node_test(
name = "test",
srcs = glob(["**/*.spec.mjs"]),
data = DEPLOY_TO_FIREBASE_SOURCES,
# Tests make remote calls to git
exec_properties = ENABLE_NETWORK,
tags = ["requires-network"],
deps = DEPLOY_TO_FIREBASE_DEPS,
)
| aio/scripts/deploy-to-firebase/BUILD.bazel | 1 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.9994428753852844,
0.7493672966957092,
0.0006915569538250566,
0.9986673593521118,
0.432248592376709
] |
{
"id": 1,
"code_window": [
"\n",
"DEPLOY_TO_FIREBASE_DEPS = [\n",
" \"@aio_npm//shelljs\",\n",
" \"//aio:build\",\n",
" \"//:package.json\",\n",
"]\n",
"\n",
"nodejs_binary(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" YARN_LABEL,\n"
],
"file_path": "aio/scripts/deploy-to-firebase/BUILD.bazel",
"type": "add",
"edit_start_line_idx": 13
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Type} from '../interface/type';
import {resolveForwardRef} from './forward_ref';
import {InjectionToken} from './injection_token';
import {ClassProvider, ExistingProvider, FactoryProvider, Provider, TypeProvider, ValueProvider} from './interface/provider';
import {getReflect} from './jit/util';
import {Inject, Optional, Self, SkipSelf} from './metadata';
import {invalidProviderError, mixingMultiProvidersWithRegularProvidersError, noAnnotationError} from './reflective_errors';
import {ReflectiveKey} from './reflective_key';
interface NormalizedProvider extends TypeProvider, ValueProvider, ClassProvider, ExistingProvider,
FactoryProvider {}
/**
* `Dependency` is used by the framework to extend DI.
* This is internal to Angular and should not be used directly.
*/
export class ReflectiveDependency {
constructor(
public key: ReflectiveKey, public optional: boolean, public visibility: Self|SkipSelf|null) {}
static fromKey(key: ReflectiveKey): ReflectiveDependency {
return new ReflectiveDependency(key, false, null);
}
}
const _EMPTY_LIST: any[] = [];
/**
* An internal resolved representation of a `Provider` used by the `Injector`.
*
* @usageNotes
* This is usually created automatically by `Injector.resolveAndCreate`.
*
* It can be created manually, as follows:
*
* ### Example
*
* ```typescript
* var resolvedProviders = Injector.resolve([{ provide: 'message', useValue: 'Hello' }]);
* var injector = Injector.fromResolvedProviders(resolvedProviders);
*
* expect(injector.get('message')).toEqual('Hello');
* ```
*
* @publicApi
*/
export interface ResolvedReflectiveProvider {
/**
* A key, usually a `Type<any>`.
*/
key: ReflectiveKey;
/**
* Factory function which can return an instance of an object represented by a key.
*/
resolvedFactories: ResolvedReflectiveFactory[];
/**
* Indicates if the provider is a multi-provider or a regular provider.
*/
multiProvider: boolean;
}
export class ResolvedReflectiveProvider_ implements ResolvedReflectiveProvider {
readonly resolvedFactory: ResolvedReflectiveFactory;
constructor(
public key: ReflectiveKey, public resolvedFactories: ResolvedReflectiveFactory[],
public multiProvider: boolean) {
this.resolvedFactory = this.resolvedFactories[0];
}
}
/**
* An internal resolved representation of a factory function created by resolving `Provider`.
* @publicApi
*/
export class ResolvedReflectiveFactory {
constructor(
/**
* Factory function which can return an instance of an object represented by a key.
*/
public factory: Function,
/**
* Arguments (dependencies) to the `factory` function.
*/
public dependencies: ReflectiveDependency[]) {}
}
/**
* Resolve a single provider.
*/
function resolveReflectiveFactory(provider: NormalizedProvider): ResolvedReflectiveFactory {
let factoryFn: Function;
let resolvedDeps: ReflectiveDependency[];
if (provider.useClass) {
const useClass = resolveForwardRef(provider.useClass);
factoryFn = getReflect().factory(useClass);
resolvedDeps = _dependenciesFor(useClass);
} else if (provider.useExisting) {
factoryFn = (aliasInstance: any) => aliasInstance;
resolvedDeps = [ReflectiveDependency.fromKey(ReflectiveKey.get(provider.useExisting))];
} else if (provider.useFactory) {
factoryFn = provider.useFactory;
resolvedDeps = constructDependencies(provider.useFactory, provider.deps);
} else {
factoryFn = () => provider.useValue;
resolvedDeps = _EMPTY_LIST;
}
return new ResolvedReflectiveFactory(factoryFn, resolvedDeps);
}
/**
* Converts the `Provider` into `ResolvedProvider`.
*
* `Injector` internally only uses `ResolvedProvider`, `Provider` contains convenience provider
* syntax.
*/
function resolveReflectiveProvider(provider: NormalizedProvider): ResolvedReflectiveProvider {
return new ResolvedReflectiveProvider_(
ReflectiveKey.get(provider.provide), [resolveReflectiveFactory(provider)],
provider.multi || false);
}
/**
* Resolve a list of Providers.
*/
export function resolveReflectiveProviders(providers: Provider[]): ResolvedReflectiveProvider[] {
const normalized = _normalizeProviders(providers, []);
const resolved = normalized.map(resolveReflectiveProvider);
const resolvedProviderMap = mergeResolvedReflectiveProviders(resolved, new Map());
return Array.from(resolvedProviderMap.values());
}
/**
* Merges a list of ResolvedProviders into a list where each key is contained exactly once and
* multi providers have been merged.
*/
export function mergeResolvedReflectiveProviders(
providers: ResolvedReflectiveProvider[],
normalizedProvidersMap: Map<number, ResolvedReflectiveProvider>):
Map<number, ResolvedReflectiveProvider> {
for (let i = 0; i < providers.length; i++) {
const provider = providers[i];
const existing = normalizedProvidersMap.get(provider.key.id);
if (existing) {
if (provider.multiProvider !== existing.multiProvider) {
throw mixingMultiProvidersWithRegularProvidersError(existing, provider);
}
if (provider.multiProvider) {
for (let j = 0; j < provider.resolvedFactories.length; j++) {
existing.resolvedFactories.push(provider.resolvedFactories[j]);
}
} else {
normalizedProvidersMap.set(provider.key.id, provider);
}
} else {
let resolvedProvider: ResolvedReflectiveProvider;
if (provider.multiProvider) {
resolvedProvider = new ResolvedReflectiveProvider_(
provider.key, provider.resolvedFactories.slice(), provider.multiProvider);
} else {
resolvedProvider = provider;
}
normalizedProvidersMap.set(provider.key.id, resolvedProvider);
}
}
return normalizedProvidersMap;
}
function _normalizeProviders(
providers: Provider[], res: NormalizedProvider[]): NormalizedProvider[] {
providers.forEach(b => {
if (b instanceof Type) {
res.push({provide: b, useClass: b} as NormalizedProvider);
} else if (b && typeof b == 'object' && (b as any).provide !== undefined) {
res.push(b as NormalizedProvider);
} else if (Array.isArray(b)) {
_normalizeProviders(b, res);
} else {
throw invalidProviderError(b);
}
});
return res;
}
export function constructDependencies(
typeOrFunc: any, dependencies?: any[]): ReflectiveDependency[] {
if (!dependencies) {
return _dependenciesFor(typeOrFunc);
} else {
const params: any[][] = dependencies.map(t => [t]);
return dependencies.map(t => _extractToken(typeOrFunc, t, params));
}
}
function _dependenciesFor(typeOrFunc: any): ReflectiveDependency[] {
const params = getReflect().parameters(typeOrFunc);
if (!params) return [];
if (params.some(p => p == null)) {
throw noAnnotationError(typeOrFunc, params);
}
return params.map(p => _extractToken(typeOrFunc, p, params));
}
function _extractToken(
typeOrFunc: any, metadata: any[]|any, params: any[][]): ReflectiveDependency {
let token: any = null;
let optional = false;
if (!Array.isArray(metadata)) {
if (metadata instanceof Inject) {
return _createDependency(metadata.token, optional, null);
} else {
return _createDependency(metadata, optional, null);
}
}
let visibility: Self|SkipSelf|null = null;
for (let i = 0; i < metadata.length; ++i) {
const paramMetadata = metadata[i];
if (paramMetadata instanceof Type) {
token = paramMetadata;
} else if (paramMetadata instanceof Inject) {
token = paramMetadata.token;
} else if (paramMetadata instanceof Optional) {
optional = true;
} else if (paramMetadata instanceof Self || paramMetadata instanceof SkipSelf) {
visibility = paramMetadata;
} else if (paramMetadata instanceof InjectionToken) {
token = paramMetadata;
}
}
token = resolveForwardRef(token);
if (token != null) {
return _createDependency(token, optional, visibility);
} else {
throw noAnnotationError(typeOrFunc, params);
}
}
function _createDependency(
token: any, optional: boolean, visibility: Self|SkipSelf|null): ReflectiveDependency {
return new ReflectiveDependency(ReflectiveKey.get(token), optional, visibility);
}
| packages/core/src/di/reflective_provider.ts | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.0005580542492680252,
0.00022193659970071167,
0.00016976195911411196,
0.00019167002756148577,
0.00007973706669872627
] |
{
"id": 1,
"code_window": [
"\n",
"DEPLOY_TO_FIREBASE_DEPS = [\n",
" \"@aio_npm//shelljs\",\n",
" \"//aio:build\",\n",
" \"//:package.json\",\n",
"]\n",
"\n",
"nodejs_binary(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" YARN_LABEL,\n"
],
"file_path": "aio/scripts/deploy-to-firebase/BUILD.bazel",
"type": "add",
"edit_start_line_idx": 13
} | #
<!-- links -->
<!-- external links -->
<!-- end links -->
@reviewed 2022-08-22
| aio/content/guide/component/component-content-projection-multi-slot.md | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.00019055245502386242,
0.00019055245502386242,
0.00019055245502386242,
0.00019055245502386242,
0
] |
{
"id": 1,
"code_window": [
"\n",
"DEPLOY_TO_FIREBASE_DEPS = [\n",
" \"@aio_npm//shelljs\",\n",
" \"//aio:build\",\n",
" \"//:package.json\",\n",
"]\n",
"\n",
"nodejs_binary(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" YARN_LABEL,\n"
],
"file_path": "aio/scripts/deploy-to-firebase/BUILD.bazel",
"type": "add",
"edit_start_line_idx": 13
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AbsoluteSourceSpan, ParseLocation, ParseSourceFile, ParseSourceSpan} from '@angular/compiler';
import ts from 'typescript';
import {TemplateId, TemplateSourceMapping} from '../api';
import {getTemplateId} from '../diagnostics';
import {computeLineStartsMap, getLineAndCharacterFromPosition} from './line_mappings';
import {TemplateSourceResolver} from './tcb_util';
/**
* Represents the source of a template that was processed during type-checking. This information is
* used when translating parse offsets in diagnostics back to their original line/column location.
*/
export class TemplateSource {
private lineStarts: number[]|null = null;
constructor(readonly mapping: TemplateSourceMapping, private file: ParseSourceFile) {}
toParseSourceSpan(start: number, end: number): ParseSourceSpan {
const startLoc = this.toParseLocation(start);
const endLoc = this.toParseLocation(end);
return new ParseSourceSpan(startLoc, endLoc);
}
private toParseLocation(position: number) {
const lineStarts = this.acquireLineStarts();
const {line, character} = getLineAndCharacterFromPosition(lineStarts, position);
return new ParseLocation(this.file, position, line, character);
}
private acquireLineStarts(): number[] {
if (this.lineStarts === null) {
this.lineStarts = computeLineStartsMap(this.file.content);
}
return this.lineStarts;
}
}
/**
* Assigns IDs to templates and keeps track of their origins.
*
* Implements `TemplateSourceResolver` to resolve the source of a template based on these IDs.
*/
export class TemplateSourceManager implements TemplateSourceResolver {
/**
* This map keeps track of all template sources that have been type-checked by the id that is
* attached to a TCB's function declaration as leading trivia. This enables translation of
* diagnostics produced for TCB code to their source location in the template.
*/
private templateSources = new Map<TemplateId, TemplateSource>();
getTemplateId(node: ts.ClassDeclaration): TemplateId {
return getTemplateId(node);
}
captureSource(node: ts.ClassDeclaration, mapping: TemplateSourceMapping, file: ParseSourceFile):
TemplateId {
const id = getTemplateId(node);
this.templateSources.set(id, new TemplateSource(mapping, file));
return id;
}
getSourceMapping(id: TemplateId): TemplateSourceMapping {
if (!this.templateSources.has(id)) {
throw new Error(`Unexpected unknown template ID: ${id}`);
}
return this.templateSources.get(id)!.mapping;
}
toParseSourceSpan(id: TemplateId, span: AbsoluteSourceSpan): ParseSourceSpan|null {
if (!this.templateSources.has(id)) {
return null;
}
const templateSource = this.templateSources.get(id)!;
return templateSource.toParseSourceSpan(span.start, span.end);
}
}
| packages/compiler-cli/src/ngtsc/typecheck/src/source.ts | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.0003288731968495995,
0.00021951788221485913,
0.000171019317349419,
0.00018132869445253164,
0.000056649103498784825
] |
{
"id": 2,
"code_window": [
"nodejs_binary(\n",
" name = \"deploy-to-firebase\",\n",
" data = DEPLOY_TO_FIREBASE_SOURCES + DEPLOY_TO_FIREBASE_DEPS,\n",
" entry_point = \"index.mjs\",\n",
")\n",
"\n",
"jasmine_node_test(\n",
" name = \"test\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" env = {\n",
" \"YARN_BIN\": \"$(rootpath %s)\" % YARN_LABEL,\n",
" },\n"
],
"file_path": "aio/scripts/deploy-to-firebase/BUILD.bazel",
"type": "add",
"edit_start_line_idx": 19
} | import fs from 'fs';
import sh from 'shelljs';
import u from './utils.mjs';
describe('deploy-to-firebase/utils:', () => {
beforeEach(() => {
// Clear the `getRemoteRefs()` cache before each test to prevent previous executions from
// affecting subsequent tests.
u._GIT_REMOTE_REFS_CACHE.clear();
});
describe('computeMajorVersion()', () => {
it('should extract the major version from a branch name', () => {
expect(u.computeMajorVersion('1.2.3')).toBe(1);
expect(u.computeMajorVersion('4.5.6-rc.7')).toBe(4);
expect(u.computeMajorVersion('89.0')).toBe(89);
});
});
describe('getDirname()', () => {
it('should return the directory path given a file URL', () => {
expect(u.getDirname(import.meta.url)).toMatch(/aio[\\/]scripts[\\/]deploy-to-firebase$/);
expect(u.getDirname('file:///C:/foo/bar/baz.ext'))
.toBe((process.platform === 'win32') ? 'C:\\foo\\bar' : '/C:/foo/bar');
});
});
describe('getLatestCommit()', () => {
let getRemoteRefsSpy;
beforeEach(() => {
getRemoteRefsSpy = spyOn(u, 'getRemoteRefs').and.returnValue([
'1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40 refs/heads/3.0.x',
]);
});
it('should return the latest commit of a branch', () => {
expect(u.getLatestCommit('3.0.x')).toBe('1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40');
expect(getRemoteRefsSpy).toHaveBeenCalledWith('3.0.x', undefined);
});
it('should pass any options to `getRemoteRefs()`', () => {
const opts = {custom: true};
expect(u.getLatestCommit('3.0.x', opts)).toBe('1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40');
expect(getRemoteRefsSpy).toHaveBeenCalledWith('3.0.x', opts);
});
});
describe('getMostRecentMinorBranch()', () => {
let getRemoteRefsSpy;
beforeEach(() => {
const mockRefs3 = [
'1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40 refs/heads/3.1.x',
'1ccccccccccccccccccccccccccccccccccccc40 refs/heads/3.3.x',
'1bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb40 refs/heads/3.2.x',
];
const mockRefs4 = [
'1ddddddddddddddddddddddddddddddddddddd40 refs/heads/4.5.x',
'1eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee40 refs/heads/4.6.x',
];
const mockRefsAll = [
...mockRefs3,
...mockRefs4,
'1fffffffffffffffffffffffffffffffffffff40 refs/heads/5.0.x',
];
getRemoteRefsSpy = spyOn(u, 'getRemoteRefs')
.withArgs('refs/heads/3.*.x', undefined).and.returnValue(mockRefs3)
.withArgs('refs/heads/3.*.x', jasmine.anything()).and.returnValue(mockRefs3)
.withArgs('refs/heads/4.*.x', undefined).and.returnValue(mockRefs4)
.withArgs('refs/heads/4.*.x', jasmine.anything()).and.returnValue(mockRefs4)
.withArgs('refs/heads/*.*.x', undefined).and.returnValue(mockRefsAll)
.withArgs('refs/heads/*.*.x', jasmine.anything()).and.returnValue(mockRefsAll);
});
it('should get all minor branches for the specified major version', () => {
u.getMostRecentMinorBranch('3');
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/3.*.x', undefined);
u.getMostRecentMinorBranch('4');
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/4.*.x', undefined);
});
it('should get all minor branches when no major version is specified', () => {
u.getMostRecentMinorBranch();
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/*.*.x', undefined);
u.getMostRecentMinorBranch(undefined);
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/*.*.x', undefined);
});
it('should pass any options to `getRemoteRefs()`', () => {
u.getMostRecentMinorBranch();
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/*.*.x', undefined);
u.getMostRecentMinorBranch('3');
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/3.*.x', undefined);
u.getMostRecentMinorBranch(undefined, {custom: 1});
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/*.*.x', {custom: 1});
u.getMostRecentMinorBranch('4', {custom: 2});
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/4.*.x', {custom: 2});
});
it('should return the most recent branch', () => {
expect(u.getMostRecentMinorBranch('3')).toBe('3.3.x');
expect(u.getMostRecentMinorBranch('4')).toBe('4.6.x');
expect(u.getMostRecentMinorBranch()).toBe('5.0.x');
});
it('should ignore branches that do not match the expected pattern', () => {
getRemoteRefsSpy.withArgs('refs/heads/*.*.x', undefined).and.returnValue([
'1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40 refs/heads/6.0.x',
'1bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb40 refs/heads/6.1.x',
'1ccccccccccccccccccccccccccccccccccccc40 refs/heads/6.2.z',
'1ddddddddddddddddddddddddddddddddddddd40 refs/heads/7.3.x-rc.0',
]);
expect(u.getMostRecentMinorBranch()).toBe('6.1.x');
});
});
describe('getRemoteRefs()', () => {
let execSpy;
beforeEach(() => {
execSpy = spyOn(sh, 'exec').and.callFake(() => ([
' ',
'1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40 refs/heads/3.1.x',
'1ccccccccccccccccccccccccccccccccccccc40 refs/heads/3.3.x',
'1bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb40 refs/heads/3.2.x',
'1ddddddddddddddddddddddddddddddddddddd40 refs/heads/4.5.x',
'1eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee40 refs/heads/4.6.x',
'1fffffffffffffffffffffffffffffffffffff40 refs/heads/5.0.x',
' ',
].join('\n')));
});
it('should retrieve the remote refs based on the speficied pattern/remote', () => {
u.getRemoteRefs('some-pattern', {remote: 'https://example.com/repo.git'});
expect(execSpy).toHaveBeenCalledWith(
'git ls-remote https://example.com/repo.git some-pattern', jasmine.anything());
});
it('should use the `angular/angular` repo if not remote is specified', () => {
u.getRemoteRefs('some-pattern');
expect(execSpy).toHaveBeenCalledWith(
`git ls-remote ${u.NG_REMOTE_URL} some-pattern`, jasmine.anything());
u.getRemoteRefs('other-pattern', {other: 'option'});
expect(execSpy).toHaveBeenCalledWith(
`git ls-remote ${u.NG_REMOTE_URL} other-pattern`, jasmine.anything());
});
it('should run the git command in silent mode', () => {
u.getRemoteRefs('some-pattern');
expect(execSpy).toHaveBeenCalledWith(jasmine.any(String), {silent: true});
});
it('should return a list of refs', () => {
expect(u.getRemoteRefs('some-pattern')).toEqual([
'1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40 refs/heads/3.1.x',
'1ccccccccccccccccccccccccccccccccccccc40 refs/heads/3.3.x',
'1bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb40 refs/heads/3.2.x',
'1ddddddddddddddddddddddddddddddddddddd40 refs/heads/4.5.x',
'1eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee40 refs/heads/4.6.x',
'1fffffffffffffffffffffffffffffffffffff40 refs/heads/5.0.x',
]);
});
it('should retrieve results from the cache (if available)', () => {
// Initially, retrieve results by executing the command.
const results1 = u.getRemoteRefs('some-pattern');
expect(execSpy).toHaveBeenCalledTimes(1);
// On subsequent calls with the same command, retrieve results from the cache.
expect(u.getRemoteRefs('some-pattern')).toBe(results1);
expect(u.getRemoteRefs('some-pattern', {remote: u.NG_REMOTE_URL})).toBe(results1);
expect(execSpy).toHaveBeenCalledTimes(1);
// Retrieve results for different command (different remote) by executing the command.
const results2 = u.getRemoteRefs('some-pattern', {remote: 'other-remote'});
expect(results2).not.toBe(results1);
expect(execSpy).toHaveBeenCalledTimes(2);
// Retrieve results for different command (different pattern) by executing the command.
const results3 = u.getRemoteRefs('other-pattern');
expect(results3).not.toBe(results1);
expect(results3).not.toBe(results2);
expect(execSpy).toHaveBeenCalledTimes(3);
// Retrieve results from the cache once available.
expect(u.getRemoteRefs('other-pattern', {remote: u.NG_REMOTE_URL})).toBe(results3);
expect(execSpy).toHaveBeenCalledTimes(3);
});
it('should not retrieve results from the cache with `retrieveFromCache: false`', () => {
// Initial call to retrieve and cache the results.
const results1 = u.getRemoteRefs('some-pattern');
expect(execSpy).toHaveBeenCalledTimes(1);
// Do not use cached results with `retrieveFromCache: false`.
const results2 = u.getRemoteRefs('some-pattern', {retrieveFromCache: false});
expect(results2).not.toBe(results1);
expect(execSpy).toHaveBeenCalledTimes(2);
const results3 = u.getRemoteRefs(
'some-pattern', {remote: u.NG_REMOTE_URL, retrieveFromCache: false});
expect(results3).not.toBe(results1);
expect(results3).not.toBe(results2);
expect(execSpy).toHaveBeenCalledTimes(3);
});
it('should cache the results for future use even with `retrieveFromCache: false`', () => {
// Initial call with `retrieveFromCache: false` (should still cache the results).
const results = u.getRemoteRefs('some-pattern', {retrieveFromCache: false});
expect(execSpy).toHaveBeenCalledTimes(1);
// Subsequent call uses the cached results.
expect(u.getRemoteRefs('some-pattern')).toBe(results);
expect(u.getRemoteRefs('some-pattern', {other: 'option'})).toBe(results);
expect(u.getRemoteRefs('some-pattern', {retrieveFromCache: true})).toBe(results);
expect(execSpy).toHaveBeenCalledTimes(1);
});
});
describe('loadJson()', () => {
let readFileSyncSpy;
beforeEach(() => readFileSyncSpy = spyOn(fs, 'readFileSync'));
it('should load and parse a JSON file', () => {
readFileSyncSpy.withArgs('/foo/bar.json', 'utf8').and.returnValue('{"foo": "bar"}');
expect(u.loadJson('/foo/bar.json')).toEqual({foo: 'bar'});
});
});
describe('logSectionHeader()', () => {
let logSpy;
beforeEach(() => logSpy = spyOn(console, 'log'));
it('should log a section header', () => {
u.logSectionHeader('Foo header');
expect(logSpy).toHaveBeenCalledWith('\n\n\n==== Foo header ====\n');
});
});
describe('nameFunction()', () => {
it('should overwrite a function\'s name', () => {
function foo() {}
const bar = () => {};
const baz = ({baz() {}}).baz;
expect(foo.name).toBe('foo');
expect(bar.name).toBe('bar');
expect(baz.name).toBe('baz');
u.nameFunction('foo2', foo);
u.nameFunction('bar2', bar);
u.nameFunction('baz2', baz);
expect(foo.name).toBe('foo2');
expect(bar.name).toBe('bar2');
expect(baz.name).toBe('baz2');
});
it('should return the function', () => {
function foo() {}
const bar = () => {};
const baz = ({baz() {}}).baz;
expect(u.nameFunction('foo2', foo)).toBe(foo);
expect(u.nameFunction('bar2', bar)).toBe(bar);
expect(u.nameFunction('baz2', baz)).toBe(baz);
});
});
describe('yarn()', () => {
let execSpy;
beforeEach(() => execSpy = spyOn(sh, 'exec'));
it('should execute yarn in silent mode', () => {
u.yarn('foo --bar');
expect(execSpy).toHaveBeenCalledWith('yarn --silent foo --bar');
});
it('should return the output from the command\'s execution', () => {
execSpy.and.returnValue('command output\n');
expect(u.yarn('foo --bar')).toBe('command output\n');
});
});
});
| aio/scripts/deploy-to-firebase/utils.spec.mjs | 1 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.0002136288967449218,
0.00017729707178659737,
0.0001673264632700011,
0.00017675483832135797,
0.00000716912973075523
] |
{
"id": 2,
"code_window": [
"nodejs_binary(\n",
" name = \"deploy-to-firebase\",\n",
" data = DEPLOY_TO_FIREBASE_SOURCES + DEPLOY_TO_FIREBASE_DEPS,\n",
" entry_point = \"index.mjs\",\n",
")\n",
"\n",
"jasmine_node_test(\n",
" name = \"test\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" env = {\n",
" \"YARN_BIN\": \"$(rootpath %s)\" % YARN_LABEL,\n",
" },\n"
],
"file_path": "aio/scripts/deploy-to-firebase/BUILD.bazel",
"type": "add",
"edit_start_line_idx": 19
} | // #docregion
import { MissingTranslationStrategy } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
// ...
platformBrowserDynamic().bootstrapModule(AppModule, {
missingTranslation: MissingTranslationStrategy.Error,
providers: [
// ...
]
});
| aio/content/examples/i18n/doc-files/main.3.ts | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.00017726411169860512,
0.00017558931722305715,
0.0001739145372994244,
0.00017558931722305715,
0.0000016747871995903552
] |
{
"id": 2,
"code_window": [
"nodejs_binary(\n",
" name = \"deploy-to-firebase\",\n",
" data = DEPLOY_TO_FIREBASE_SOURCES + DEPLOY_TO_FIREBASE_DEPS,\n",
" entry_point = \"index.mjs\",\n",
")\n",
"\n",
"jasmine_node_test(\n",
" name = \"test\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" env = {\n",
" \"YARN_BIN\": \"$(rootpath %s)\" % YARN_LABEL,\n",
" },\n"
],
"file_path": "aio/scripts/deploy-to-firebase/BUILD.bazel",
"type": "add",
"edit_start_line_idx": 19
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system';
import {MockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import * as ts from 'typescript/lib/tsserverlibrary';
const NOOP_FILE_WATCHER: ts.FileWatcher = {
close() {}
};
export class MockServerHost implements ts.server.ServerHost {
constructor(private fs: MockFileSystem) {}
get newLine(): string {
return '\n';
}
get useCaseSensitiveFileNames(): boolean {
return this.fs.isCaseSensitive();
}
readFile(path: string, encoding?: string): string|undefined {
return this.fs.readFile(absoluteFrom(path));
}
resolvePath(path: string): string {
return this.fs.resolve(path);
}
fileExists(path: string): boolean {
const absPath = absoluteFrom(path);
return this.fs.exists(absPath) && this.fs.lstat(absPath).isFile();
}
directoryExists(path: string): boolean {
const absPath = absoluteFrom(path);
return this.fs.exists(absPath) && this.fs.lstat(absPath).isDirectory();
}
createDirectory(path: string): void {
this.fs.ensureDir(absoluteFrom(path));
}
getExecutingFilePath(): string {
// This is load-bearing, as TypeScript uses the result of this call to locate the directory in
// which it expects to find .d.ts files for the "standard libraries" - DOM, ES2015, etc.
return '/node_modules/typescript/lib/tsserver.js';
}
getCurrentDirectory(): string {
return '/';
}
createHash(data: string): string {
return ts.sys.createHash!(data);
}
get args(): string[] {
throw new Error('Property not implemented.');
}
watchFile(
path: string, callback: ts.FileWatcherCallback, pollingInterval?: number,
options?: ts.WatchOptions): ts.FileWatcher {
return NOOP_FILE_WATCHER;
}
watchDirectory(
path: string, callback: ts.DirectoryWatcherCallback, recursive?: boolean,
options?: ts.WatchOptions): ts.FileWatcher {
return NOOP_FILE_WATCHER;
}
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]) {
throw new Error('Method not implemented.');
}
clearTimeout(timeoutId: any): void {
throw new Error('Method not implemented.');
}
setImmediate(callback: (...args: any[]) => void, ...args: any[]) {
throw new Error('Method not implemented.');
}
clearImmediate(timeoutId: any): void {
throw new Error('Method not implemented.');
}
write(s: string): void {
throw new Error('Method not implemented.');
}
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void {
throw new Error('Method not implemented.');
}
getDirectories(path: string): string[] {
throw new Error('Method not implemented.');
}
readDirectory(
path: string, extensions?: readonly string[], exclude?: readonly string[],
include?: readonly string[], depth?: number): string[] {
throw new Error('Method not implemented.');
}
exit(exitCode?: number): void {
throw new Error('Method not implemented.');
}
}
| packages/language-service/testing/src/host.ts | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.97092604637146,
0.08134094625711441,
0.0001690513890935108,
0.00017485661373939365,
0.26822149753570557
] |
{
"id": 2,
"code_window": [
"nodejs_binary(\n",
" name = \"deploy-to-firebase\",\n",
" data = DEPLOY_TO_FIREBASE_SOURCES + DEPLOY_TO_FIREBASE_DEPS,\n",
" entry_point = \"index.mjs\",\n",
")\n",
"\n",
"jasmine_node_test(\n",
" name = \"test\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" env = {\n",
" \"YARN_BIN\": \"$(rootpath %s)\" % YARN_LABEL,\n",
" },\n"
],
"file_path": "aio/scripts/deploy-to-firebase/BUILD.bazel",
"type": "add",
"edit_start_line_idx": 19
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, EmbeddedViewRef, Input, TemplateRef, ViewContainerRef, ɵstringify as stringify} from '@angular/core';
/**
* A structural directive that conditionally includes a template based on the value of
* an expression coerced to Boolean.
* When the expression evaluates to true, Angular renders the template
* provided in a `then` clause, and when false or null,
* Angular renders the template provided in an optional `else` clause. The default
* template for the `else` clause is blank.
*
* A [shorthand form](guide/structural-directives#asterisk) of the directive,
* `*ngIf="condition"`, is generally used, provided
* as an attribute of the anchor element for the inserted template.
* Angular expands this into a more explicit version, in which the anchor element
* is contained in an `<ng-template>` element.
*
* Simple form with shorthand syntax:
*
* ```
* <div *ngIf="condition">Content to render when condition is true.</div>
* ```
*
* Simple form with expanded syntax:
*
* ```
* <ng-template [ngIf]="condition"><div>Content to render when condition is
* true.</div></ng-template>
* ```
*
* Form with an "else" block:
*
* ```
* <div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>
* <ng-template #elseBlock>Content to render when condition is false.</ng-template>
* ```
*
* Shorthand form with "then" and "else" blocks:
*
* ```
* <div *ngIf="condition; then thenBlock else elseBlock"></div>
* <ng-template #thenBlock>Content to render when condition is true.</ng-template>
* <ng-template #elseBlock>Content to render when condition is false.</ng-template>
* ```
*
* Form with storing the value locally:
*
* ```
* <div *ngIf="condition as value; else elseBlock">{{value}}</div>
* <ng-template #elseBlock>Content to render when value is null.</ng-template>
* ```
*
* @usageNotes
*
* The `*ngIf` directive is most commonly used to conditionally show an inline template,
* as seen in the following example.
* The default `else` template is blank.
*
* {@example common/ngIf/ts/module.ts region='NgIfSimple'}
*
* ### Showing an alternative template using `else`
*
* To display a template when `expression` evaluates to false, use an `else` template
* binding as shown in the following example.
* The `else` binding points to an `<ng-template>` element labeled `#elseBlock`.
* The template can be defined anywhere in the component view, but is typically placed right after
* `ngIf` for readability.
*
* {@example common/ngIf/ts/module.ts region='NgIfElse'}
*
* ### Using an external `then` template
*
* In the previous example, the then-clause template is specified inline, as the content of the
* tag that contains the `ngIf` directive. You can also specify a template that is defined
* externally, by referencing a labeled `<ng-template>` element. When you do this, you can
* change which template to use at runtime, as shown in the following example.
*
* {@example common/ngIf/ts/module.ts region='NgIfThenElse'}
*
* ### Storing a conditional result in a variable
*
* You might want to show a set of properties from the same object. If you are waiting
* for asynchronous data, the object can be undefined.
* In this case, you can use `ngIf` and store the result of the condition in a local
* variable as shown in the following example.
*
* {@example common/ngIf/ts/module.ts region='NgIfAs'}
*
* This code uses only one `AsyncPipe`, so only one subscription is created.
* The conditional statement stores the result of `userStream|async` in the local variable `user`.
* You can then bind the local `user` repeatedly.
*
* The conditional displays the data only if `userStream` returns a value,
* so you don't need to use the
* safe-navigation-operator (`?.`)
* to guard against null values when accessing properties.
* You can display an alternative template while waiting for the data.
*
* ### Shorthand syntax
*
* The shorthand syntax `*ngIf` expands into two separate template specifications
* for the "then" and "else" clauses. For example, consider the following shorthand statement,
* that is meant to show a loading page while waiting for data to be loaded.
*
* ```
* <div class="hero-list" *ngIf="heroes else loading">
* ...
* </div>
*
* <ng-template #loading>
* <div>Loading...</div>
* </ng-template>
* ```
*
* You can see that the "else" clause references the `<ng-template>`
* with the `#loading` label, and the template for the "then" clause
* is provided as the content of the anchor element.
*
* However, when Angular expands the shorthand syntax, it creates
* another `<ng-template>` tag, with `ngIf` and `ngIfElse` directives.
* The anchor element containing the template for the "then" clause becomes
* the content of this unlabeled `<ng-template>` tag.
*
* ```
* <ng-template [ngIf]="heroes" [ngIfElse]="loading">
* <div class="hero-list">
* ...
* </div>
* </ng-template>
*
* <ng-template #loading>
* <div>Loading...</div>
* </ng-template>
* ```
*
* The presence of the implicit template object has implications for the nesting of
* structural directives. For more on this subject, see
* [Structural Directives](guide/structural-directives#one-per-element).
*
* @ngModule CommonModule
* @publicApi
*/
@Directive({
selector: '[ngIf]',
standalone: true,
})
export class NgIf<T = unknown> {
private _context: NgIfContext<T> = new NgIfContext<T>();
private _thenTemplateRef: TemplateRef<NgIfContext<T>>|null = null;
private _elseTemplateRef: TemplateRef<NgIfContext<T>>|null = null;
private _thenViewRef: EmbeddedViewRef<NgIfContext<T>>|null = null;
private _elseViewRef: EmbeddedViewRef<NgIfContext<T>>|null = null;
constructor(private _viewContainer: ViewContainerRef, templateRef: TemplateRef<NgIfContext<T>>) {
this._thenTemplateRef = templateRef;
}
/**
* The Boolean expression to evaluate as the condition for showing a template.
*/
@Input()
set ngIf(condition: T) {
this._context.$implicit = this._context.ngIf = condition;
this._updateView();
}
/**
* A template to show if the condition expression evaluates to true.
*/
@Input()
set ngIfThen(templateRef: TemplateRef<NgIfContext<T>>|null) {
assertTemplate('ngIfThen', templateRef);
this._thenTemplateRef = templateRef;
this._thenViewRef = null; // clear previous view if any.
this._updateView();
}
/**
* A template to show if the condition expression evaluates to false.
*/
@Input()
set ngIfElse(templateRef: TemplateRef<NgIfContext<T>>|null) {
assertTemplate('ngIfElse', templateRef);
this._elseTemplateRef = templateRef;
this._elseViewRef = null; // clear previous view if any.
this._updateView();
}
private _updateView() {
if (this._context.$implicit) {
if (!this._thenViewRef) {
this._viewContainer.clear();
this._elseViewRef = null;
if (this._thenTemplateRef) {
this._thenViewRef =
this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
}
}
} else {
if (!this._elseViewRef) {
this._viewContainer.clear();
this._thenViewRef = null;
if (this._elseTemplateRef) {
this._elseViewRef =
this._viewContainer.createEmbeddedView(this._elseTemplateRef, this._context);
}
}
}
}
/** @internal */
public static ngIfUseIfTypeGuard: void;
/**
* Assert the correct type of the expression bound to the `ngIf` input within the template.
*
* The presence of this static field is a signal to the Ivy template type check compiler that
* when the `NgIf` structural directive renders its template, the type of the expression bound
* to `ngIf` should be narrowed in some way. For `NgIf`, the binding expression itself is used to
* narrow its type, which allows the strictNullChecks feature of TypeScript to work with `NgIf`.
*/
static ngTemplateGuard_ngIf: 'binding';
/**
* Asserts the correct type of the context for the template that `NgIf` will render.
*
* The presence of this method is a signal to the Ivy template type-check compiler that the
* `NgIf` structural directive renders its template with a specific context type.
*/
static ngTemplateContextGuard<T>(dir: NgIf<T>, ctx: any):
ctx is NgIfContext<Exclude<T, false|0|''|null|undefined>> {
return true;
}
}
/**
* @publicApi
*/
export class NgIfContext<T = unknown> {
public $implicit: T = null!;
public ngIf: T = null!;
}
function assertTemplate(property: string, templateRef: TemplateRef<any>|null): void {
const isTemplateRefOrNull = !!(!templateRef || templateRef.createEmbeddedView);
if (!isTemplateRefOrNull) {
throw new Error(`${property} must be a TemplateRef, but received '${stringify(templateRef)}'.`);
}
}
| packages/common/src/directives/ng_if.ts | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.00017637644486967474,
0.00017004134133458138,
0.0001626285957172513,
0.00017002364620566368,
0.000004618167167791398
] |
{
"id": 3,
"code_window": [
" // This is not strictly necessary, since CircleCI will mask secret environment variables in the\n",
" // output (see https://circleci.com/docs/2.0/env-vars/#secrets-masking), but is an extra\n",
" // precaution.\n",
" return sh.exec(`yarn --silent ${cmd}`);\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" return sh.exec(`${process.env.YARN_BIN} --silent ${cmd}`, {cwd: 'aio'});\n"
],
"file_path": "aio/scripts/deploy-to-firebase/utils.mjs",
"type": "replace",
"edit_start_line_idx": 107
} | load("@aio_npm//@bazel/jasmine:index.bzl", "jasmine_node_test")
load("//tools:defaults.bzl", "nodejs_binary")
load("@aio_npm//@angular/build-tooling/bazel/remote-execution:index.bzl", "ENABLE_NETWORK")
DEPLOY_TO_FIREBASE_SOURCES = glob(
["**/*.mjs"],
["**/*.spec.mjs"],
)
DEPLOY_TO_FIREBASE_DEPS = [
"@aio_npm//shelljs",
"//aio:build",
"//:package.json",
]
nodejs_binary(
name = "deploy-to-firebase",
data = DEPLOY_TO_FIREBASE_SOURCES + DEPLOY_TO_FIREBASE_DEPS,
entry_point = "index.mjs",
)
jasmine_node_test(
name = "test",
srcs = glob(["**/*.spec.mjs"]),
data = DEPLOY_TO_FIREBASE_SOURCES,
# Tests make remote calls to git
exec_properties = ENABLE_NETWORK,
tags = ["requires-network"],
deps = DEPLOY_TO_FIREBASE_DEPS,
)
| aio/scripts/deploy-to-firebase/BUILD.bazel | 1 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.0003709548036567867,
0.00022026966325938702,
0.00016722979489713907,
0.00017144702724181116,
0.00008702668128535151
] |
{
"id": 3,
"code_window": [
" // This is not strictly necessary, since CircleCI will mask secret environment variables in the\n",
" // output (see https://circleci.com/docs/2.0/env-vars/#secrets-masking), but is an extra\n",
" // precaution.\n",
" return sh.exec(`yarn --silent ${cmd}`);\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" return sh.exec(`${process.env.YARN_BIN} --silent ${cmd}`, {cwd: 'aio'});\n"
],
"file_path": "aio/scripts/deploy-to-firebase/utils.mjs",
"type": "replace",
"edit_start_line_idx": 107
} | @name Argument Not Literal
@category compiler
@shortDescription Decorator argument is not an object literal
@description
To make the metadata extraction in the Angular compiler faster, the decorators `@NgModule`, `@Pipe`, `@Component`, `@Directive`, and `@Injectable` accept only object literals as arguments.
This is an [intentional change in Ivy](https://github.com/angular/angular/issues/30840#issuecomment-498869540), which enforces stricter argument requirements for decorators than View Engine.
Ivy requires this approach because it compiles decorators by moving the expressions into other locations in the class output.
@debugging
Move all declarations:
<code-example format="typescript" language="typescript">
const moduleDefinition = {…}
@NgModule(moduleDefinition)
export class AppModule {
constructor() {}
}
</code-example>
into the decorator:
<code-example format="typescript" language="typescript">
@NgModule({…})
export class AppModule {
constructor() {}
}
</code-example>
<!-- links -->
<!-- external links -->
<!-- end links -->
@reviewed 2022-02-28
| aio/content/errors/NG1001.md | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.00017365736130159348,
0.00016821737517602742,
0.00016630369646009058,
0.0001668987824814394,
0.0000027770374799729325
] |
{
"id": 3,
"code_window": [
" // This is not strictly necessary, since CircleCI will mask secret environment variables in the\n",
" // output (see https://circleci.com/docs/2.0/env-vars/#secrets-masking), but is an extra\n",
" // precaution.\n",
" return sh.exec(`yarn --silent ${cmd}`);\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" return sh.exec(`${process.env.YARN_BIN} --silent ${cmd}`, {cwd: 'aio'});\n"
],
"file_path": "aio/scripts/deploy-to-firebase/utils.mjs",
"type": "replace",
"edit_start_line_idx": 107
} | import {Component, Directive, Input, NgModule} from '@angular/core';
@Directive({selector: 'div'})
export class DivDir {
@Input() event!: any;
}
@Component({template: '<div [event]="$event"></div>'})
class Comp {
$event = 1;
}
@NgModule({declarations: [Comp, DivDir]})
export class MyMod {
}
| packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_listener/event_in_property_binding.ts | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.00017275314894504845,
0.0001715521066216752,
0.00017035106429830194,
0.0001715521066216752,
0.0000012010423233732581
] |
{
"id": 3,
"code_window": [
" // This is not strictly necessary, since CircleCI will mask secret environment variables in the\n",
" // output (see https://circleci.com/docs/2.0/env-vars/#secrets-masking), but is an extra\n",
" // precaution.\n",
" return sh.exec(`yarn --silent ${cmd}`);\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" return sh.exec(`${process.env.YARN_BIN} --silent ${cmd}`, {cwd: 'aio'});\n"
],
"file_path": "aio/scripts/deploy-to-firebase/utils.mjs",
"type": "replace",
"edit_start_line_idx": 107
} | import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it("should have as title 'component-overview'", () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('component-overview');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('.content span')?.textContent).toContain('component-overview app is running!');
});
});
| aio/content/examples/component-overview/src/app/app.component.spec.ts | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.00017690969980321825,
0.0001749305665725842,
0.0001718723215162754,
0.00017547013703733683,
0.0000018648321429282078
] |
{
"id": 4,
"code_window": [
" let execSpy;\n",
"\n",
" beforeEach(() => execSpy = spyOn(sh, 'exec'));\n",
"\n",
" it('should execute yarn in silent mode', () => {\n",
" u.yarn('foo --bar');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" it('should execute the yarn binary in process.env.YARN_BIN', () => {\n",
" process.env.YARN_BIN = '/foo/yarn';\n",
" u.yarn('foo --bar');\n",
" const cmd = execSpy.calls.argsFor(0)[0];\n",
" expect(cmd.startsWith('/foo/yarn')).toEqual(true);\n",
" });\n",
"\n"
],
"file_path": "aio/scripts/deploy-to-firebase/utils.spec.mjs",
"type": "add",
"edit_start_line_idx": 286
} | import fs from 'fs';
import sh from 'shelljs';
import u from './utils.mjs';
describe('deploy-to-firebase/utils:', () => {
beforeEach(() => {
// Clear the `getRemoteRefs()` cache before each test to prevent previous executions from
// affecting subsequent tests.
u._GIT_REMOTE_REFS_CACHE.clear();
});
describe('computeMajorVersion()', () => {
it('should extract the major version from a branch name', () => {
expect(u.computeMajorVersion('1.2.3')).toBe(1);
expect(u.computeMajorVersion('4.5.6-rc.7')).toBe(4);
expect(u.computeMajorVersion('89.0')).toBe(89);
});
});
describe('getDirname()', () => {
it('should return the directory path given a file URL', () => {
expect(u.getDirname(import.meta.url)).toMatch(/aio[\\/]scripts[\\/]deploy-to-firebase$/);
expect(u.getDirname('file:///C:/foo/bar/baz.ext'))
.toBe((process.platform === 'win32') ? 'C:\\foo\\bar' : '/C:/foo/bar');
});
});
describe('getLatestCommit()', () => {
let getRemoteRefsSpy;
beforeEach(() => {
getRemoteRefsSpy = spyOn(u, 'getRemoteRefs').and.returnValue([
'1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40 refs/heads/3.0.x',
]);
});
it('should return the latest commit of a branch', () => {
expect(u.getLatestCommit('3.0.x')).toBe('1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40');
expect(getRemoteRefsSpy).toHaveBeenCalledWith('3.0.x', undefined);
});
it('should pass any options to `getRemoteRefs()`', () => {
const opts = {custom: true};
expect(u.getLatestCommit('3.0.x', opts)).toBe('1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40');
expect(getRemoteRefsSpy).toHaveBeenCalledWith('3.0.x', opts);
});
});
describe('getMostRecentMinorBranch()', () => {
let getRemoteRefsSpy;
beforeEach(() => {
const mockRefs3 = [
'1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40 refs/heads/3.1.x',
'1ccccccccccccccccccccccccccccccccccccc40 refs/heads/3.3.x',
'1bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb40 refs/heads/3.2.x',
];
const mockRefs4 = [
'1ddddddddddddddddddddddddddddddddddddd40 refs/heads/4.5.x',
'1eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee40 refs/heads/4.6.x',
];
const mockRefsAll = [
...mockRefs3,
...mockRefs4,
'1fffffffffffffffffffffffffffffffffffff40 refs/heads/5.0.x',
];
getRemoteRefsSpy = spyOn(u, 'getRemoteRefs')
.withArgs('refs/heads/3.*.x', undefined).and.returnValue(mockRefs3)
.withArgs('refs/heads/3.*.x', jasmine.anything()).and.returnValue(mockRefs3)
.withArgs('refs/heads/4.*.x', undefined).and.returnValue(mockRefs4)
.withArgs('refs/heads/4.*.x', jasmine.anything()).and.returnValue(mockRefs4)
.withArgs('refs/heads/*.*.x', undefined).and.returnValue(mockRefsAll)
.withArgs('refs/heads/*.*.x', jasmine.anything()).and.returnValue(mockRefsAll);
});
it('should get all minor branches for the specified major version', () => {
u.getMostRecentMinorBranch('3');
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/3.*.x', undefined);
u.getMostRecentMinorBranch('4');
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/4.*.x', undefined);
});
it('should get all minor branches when no major version is specified', () => {
u.getMostRecentMinorBranch();
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/*.*.x', undefined);
u.getMostRecentMinorBranch(undefined);
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/*.*.x', undefined);
});
it('should pass any options to `getRemoteRefs()`', () => {
u.getMostRecentMinorBranch();
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/*.*.x', undefined);
u.getMostRecentMinorBranch('3');
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/3.*.x', undefined);
u.getMostRecentMinorBranch(undefined, {custom: 1});
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/*.*.x', {custom: 1});
u.getMostRecentMinorBranch('4', {custom: 2});
expect(getRemoteRefsSpy).toHaveBeenCalledWith('refs/heads/4.*.x', {custom: 2});
});
it('should return the most recent branch', () => {
expect(u.getMostRecentMinorBranch('3')).toBe('3.3.x');
expect(u.getMostRecentMinorBranch('4')).toBe('4.6.x');
expect(u.getMostRecentMinorBranch()).toBe('5.0.x');
});
it('should ignore branches that do not match the expected pattern', () => {
getRemoteRefsSpy.withArgs('refs/heads/*.*.x', undefined).and.returnValue([
'1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40 refs/heads/6.0.x',
'1bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb40 refs/heads/6.1.x',
'1ccccccccccccccccccccccccccccccccccccc40 refs/heads/6.2.z',
'1ddddddddddddddddddddddddddddddddddddd40 refs/heads/7.3.x-rc.0',
]);
expect(u.getMostRecentMinorBranch()).toBe('6.1.x');
});
});
describe('getRemoteRefs()', () => {
let execSpy;
beforeEach(() => {
execSpy = spyOn(sh, 'exec').and.callFake(() => ([
' ',
'1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40 refs/heads/3.1.x',
'1ccccccccccccccccccccccccccccccccccccc40 refs/heads/3.3.x',
'1bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb40 refs/heads/3.2.x',
'1ddddddddddddddddddddddddddddddddddddd40 refs/heads/4.5.x',
'1eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee40 refs/heads/4.6.x',
'1fffffffffffffffffffffffffffffffffffff40 refs/heads/5.0.x',
' ',
].join('\n')));
});
it('should retrieve the remote refs based on the speficied pattern/remote', () => {
u.getRemoteRefs('some-pattern', {remote: 'https://example.com/repo.git'});
expect(execSpy).toHaveBeenCalledWith(
'git ls-remote https://example.com/repo.git some-pattern', jasmine.anything());
});
it('should use the `angular/angular` repo if not remote is specified', () => {
u.getRemoteRefs('some-pattern');
expect(execSpy).toHaveBeenCalledWith(
`git ls-remote ${u.NG_REMOTE_URL} some-pattern`, jasmine.anything());
u.getRemoteRefs('other-pattern', {other: 'option'});
expect(execSpy).toHaveBeenCalledWith(
`git ls-remote ${u.NG_REMOTE_URL} other-pattern`, jasmine.anything());
});
it('should run the git command in silent mode', () => {
u.getRemoteRefs('some-pattern');
expect(execSpy).toHaveBeenCalledWith(jasmine.any(String), {silent: true});
});
it('should return a list of refs', () => {
expect(u.getRemoteRefs('some-pattern')).toEqual([
'1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa40 refs/heads/3.1.x',
'1ccccccccccccccccccccccccccccccccccccc40 refs/heads/3.3.x',
'1bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb40 refs/heads/3.2.x',
'1ddddddddddddddddddddddddddddddddddddd40 refs/heads/4.5.x',
'1eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee40 refs/heads/4.6.x',
'1fffffffffffffffffffffffffffffffffffff40 refs/heads/5.0.x',
]);
});
it('should retrieve results from the cache (if available)', () => {
// Initially, retrieve results by executing the command.
const results1 = u.getRemoteRefs('some-pattern');
expect(execSpy).toHaveBeenCalledTimes(1);
// On subsequent calls with the same command, retrieve results from the cache.
expect(u.getRemoteRefs('some-pattern')).toBe(results1);
expect(u.getRemoteRefs('some-pattern', {remote: u.NG_REMOTE_URL})).toBe(results1);
expect(execSpy).toHaveBeenCalledTimes(1);
// Retrieve results for different command (different remote) by executing the command.
const results2 = u.getRemoteRefs('some-pattern', {remote: 'other-remote'});
expect(results2).not.toBe(results1);
expect(execSpy).toHaveBeenCalledTimes(2);
// Retrieve results for different command (different pattern) by executing the command.
const results3 = u.getRemoteRefs('other-pattern');
expect(results3).not.toBe(results1);
expect(results3).not.toBe(results2);
expect(execSpy).toHaveBeenCalledTimes(3);
// Retrieve results from the cache once available.
expect(u.getRemoteRefs('other-pattern', {remote: u.NG_REMOTE_URL})).toBe(results3);
expect(execSpy).toHaveBeenCalledTimes(3);
});
it('should not retrieve results from the cache with `retrieveFromCache: false`', () => {
// Initial call to retrieve and cache the results.
const results1 = u.getRemoteRefs('some-pattern');
expect(execSpy).toHaveBeenCalledTimes(1);
// Do not use cached results with `retrieveFromCache: false`.
const results2 = u.getRemoteRefs('some-pattern', {retrieveFromCache: false});
expect(results2).not.toBe(results1);
expect(execSpy).toHaveBeenCalledTimes(2);
const results3 = u.getRemoteRefs(
'some-pattern', {remote: u.NG_REMOTE_URL, retrieveFromCache: false});
expect(results3).not.toBe(results1);
expect(results3).not.toBe(results2);
expect(execSpy).toHaveBeenCalledTimes(3);
});
it('should cache the results for future use even with `retrieveFromCache: false`', () => {
// Initial call with `retrieveFromCache: false` (should still cache the results).
const results = u.getRemoteRefs('some-pattern', {retrieveFromCache: false});
expect(execSpy).toHaveBeenCalledTimes(1);
// Subsequent call uses the cached results.
expect(u.getRemoteRefs('some-pattern')).toBe(results);
expect(u.getRemoteRefs('some-pattern', {other: 'option'})).toBe(results);
expect(u.getRemoteRefs('some-pattern', {retrieveFromCache: true})).toBe(results);
expect(execSpy).toHaveBeenCalledTimes(1);
});
});
describe('loadJson()', () => {
let readFileSyncSpy;
beforeEach(() => readFileSyncSpy = spyOn(fs, 'readFileSync'));
it('should load and parse a JSON file', () => {
readFileSyncSpy.withArgs('/foo/bar.json', 'utf8').and.returnValue('{"foo": "bar"}');
expect(u.loadJson('/foo/bar.json')).toEqual({foo: 'bar'});
});
});
describe('logSectionHeader()', () => {
let logSpy;
beforeEach(() => logSpy = spyOn(console, 'log'));
it('should log a section header', () => {
u.logSectionHeader('Foo header');
expect(logSpy).toHaveBeenCalledWith('\n\n\n==== Foo header ====\n');
});
});
describe('nameFunction()', () => {
it('should overwrite a function\'s name', () => {
function foo() {}
const bar = () => {};
const baz = ({baz() {}}).baz;
expect(foo.name).toBe('foo');
expect(bar.name).toBe('bar');
expect(baz.name).toBe('baz');
u.nameFunction('foo2', foo);
u.nameFunction('bar2', bar);
u.nameFunction('baz2', baz);
expect(foo.name).toBe('foo2');
expect(bar.name).toBe('bar2');
expect(baz.name).toBe('baz2');
});
it('should return the function', () => {
function foo() {}
const bar = () => {};
const baz = ({baz() {}}).baz;
expect(u.nameFunction('foo2', foo)).toBe(foo);
expect(u.nameFunction('bar2', bar)).toBe(bar);
expect(u.nameFunction('baz2', baz)).toBe(baz);
});
});
describe('yarn()', () => {
let execSpy;
beforeEach(() => execSpy = spyOn(sh, 'exec'));
it('should execute yarn in silent mode', () => {
u.yarn('foo --bar');
expect(execSpy).toHaveBeenCalledWith('yarn --silent foo --bar');
});
it('should return the output from the command\'s execution', () => {
execSpy.and.returnValue('command output\n');
expect(u.yarn('foo --bar')).toBe('command output\n');
});
});
});
| aio/scripts/deploy-to-firebase/utils.spec.mjs | 1 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.9992038607597351,
0.3661106824874878,
0.00016704907466191798,
0.0006019399734213948,
0.4804479479789734
] |
{
"id": 4,
"code_window": [
" let execSpy;\n",
"\n",
" beforeEach(() => execSpy = spyOn(sh, 'exec'));\n",
"\n",
" it('should execute yarn in silent mode', () => {\n",
" u.yarn('foo --bar');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" it('should execute the yarn binary in process.env.YARN_BIN', () => {\n",
" process.env.YARN_BIN = '/foo/yarn';\n",
" u.yarn('foo --bar');\n",
" const cmd = execSpy.calls.argsFor(0)[0];\n",
" expect(cmd.startsWith('/foo/yarn')).toEqual(true);\n",
" });\n",
"\n"
],
"file_path": "aio/scripts/deploy-to-firebase/utils.spec.mjs",
"type": "add",
"edit_start_line_idx": 286
} | # Building dynamic forms
Many forms, such as questionnaires, can be very similar to one another in format and intent.
To make it faster and easier to generate different versions of such a form, you can create a *dynamic form template* based on metadata that describes the business object model.
Then, use the template to generate new forms automatically, according to changes in the data model.
The technique is particularly useful when you have a type of form whose content must change frequently to meet rapidly changing business and regulatory requirements.
A typical use-case is a questionnaire.
You might need to get input from users in different contexts.
The format and style of the forms a user sees should remain constant, while the actual questions you need to ask vary with the context.
In this tutorial you will build a dynamic form that presents a basic questionnaire.
You build an online application for heroes seeking employment.
The agency is constantly tinkering with the application process, but by using the dynamic form
you can create the new forms on the fly without changing the application code.
The tutorial walks you through the following steps.
1. Enable reactive forms for a project.
1. Establish a data model to represent form controls.
1. Populate the model with sample data.
1. Develop a component to create form controls dynamically.
The form you create uses input validation and styling to improve the user experience.
It has a Submit button that is only enabled when all user input is valid, and flags invalid input with color coding and error messages.
The basic version can evolve to support a richer variety of questions, more graceful rendering, and superior user experience.
<div class="alert is-helpful">
See the <live-example name="dynamic-form"></live-example>.
</div>
## Prerequisites
Before doing this tutorial, you should have a basic understanding to the following.
* [TypeScript](https://www.typescriptlang.org/ "The TypeScript language") and HTML5 programming
* Fundamental concepts of [Angular app design](guide/architecture "Introduction to Angular app-design concepts")
* Basic knowledge of [reactive forms](guide/reactive-forms "Reactive forms guide")
## Enable reactive forms for your project
Dynamic forms are based on reactive forms.
To give the application access reactive forms directives, the [root module](guide/bootstrapping "Learn about bootstrapping an app from the root module.") imports `ReactiveFormsModule` from the `@angular/forms` library.
The following code from the example shows the setup in the root module.
<code-tabs>
<code-pane header="app.module.ts" path="dynamic-form/src/app/app.module.ts"></code-pane>
<code-pane header="main.ts" path="dynamic-form/src/main.ts"></code-pane>
</code-tabs>
<a id="object-model"></a>
## Create a form object model
A dynamic form requires an object model that can describe all scenarios needed by the form functionality.
The example hero-application form is a set of questions —that is, each control in the form must ask a question and accept an answer.
The data model for this type of form must represent a question.
The example includes the `DynamicFormQuestionComponent`, which defines a question as the fundamental object in the model.
The following `QuestionBase` is a base class for a set of controls that can represent the question and its answer in the form.
<code-example header="src/app/question-base.ts" path="dynamic-form/src/app/question-base.ts"></code-example>
### Define control classes
From this base, the example derives two new classes, `TextboxQuestion` and `DropdownQuestion`, that represent different control types.
When you create the form template in the next step, you instantiate these specific question types in order to render the appropriate controls dynamically.
| Control type | Details |
|:--- |:--- |
| `TextboxQuestion` control type | Presents a question and lets users enter input. <code-example header="src/app/question-textbox.ts" path="dynamic-form/src/app/question-textbox.ts"></code-example> The `TextboxQuestion` control type is represented in a form template using an `<input>` element. The `type` attribute of the element is defined based on the `type` field specified in the `options` argument \(for example `text`, `email`, `url`\). |
| `DropdownQuestion` control type | Presents a list of choices in a select box. <code-example header="src/app/question-dropdown.ts" path="dynamic-form/src/app/question-dropdown.ts"></code-example> |
### Compose form groups
A dynamic form uses a service to create grouped sets of input controls, based on the form model.
The following `QuestionControlService` collects a set of `FormGroup` instances that consume the metadata from the question model.
You can specify default values and validation rules.
<code-example header="src/app/question-control.service.ts" path="dynamic-form/src/app/question-control.service.ts"></code-example>
<a id="form-component"></a>
## Compose dynamic form contents
The dynamic form itself is represented by a container component, which you add in a later step.
Each question is represented in the form component's template by an `<app-question>` tag, which matches an instance of `DynamicFormQuestionComponent`.
The `DynamicFormQuestionComponent` is responsible for rendering the details of an individual question based on values in the data-bound question object.
The form relies on a [`[formGroup]` directive](api/forms/FormGroupDirective "API reference") to connect the template HTML to the underlying control objects.
The `DynamicFormQuestionComponent` creates form groups and populates them with controls defined in the question model, specifying display and validation rules.
<code-tabs>
<code-pane header="dynamic-form-question.component.html" path="dynamic-form/src/app/dynamic-form-question.component.html"></code-pane>
<code-pane header="dynamic-form-question.component.ts" path="dynamic-form/src/app/dynamic-form-question.component.ts"></code-pane>
</code-tabs>
The goal of the `DynamicFormQuestionComponent` is to present question types defined in your model.
You only have two types of questions at this point but you can imagine many more.
The `ngSwitch` statement in the template determines which type of question to display.
The switch uses directives with the [`formControlName`](api/forms/FormControlName "FormControlName directive API reference") and [`formGroup`](api/forms/FormGroupDirective "FormGroupDirective API reference") selectors.
Both directives are defined in `ReactiveFormsModule`.
<a id="questionnaire-data"></a>
### Supply data
Another service is needed to supply a specific set of questions from which to build an individual form.
For this exercise you create the `QuestionService` to supply this array of questions from the hard-coded sample data.
In a real-world app, the service might fetch data from a backend system.
The key point, however, is that you control the hero job-application questions entirely through the objects returned from `QuestionService`.
To maintain the questionnaire as requirements change, you only need to add, update, and remove objects from the `questions` array.
The `QuestionService` supplies a set of questions in the form of an array bound to `@Input()` questions.
<code-example header="src/app/question.service.ts" path="dynamic-form/src/app/question.service.ts"></code-example>
<a id="dynamic-template"></a>
## Create a dynamic form template
The `DynamicFormComponent` component is the entry point and the main container for the form, which is represented using the `<app-dynamic-form>` in a template.
The `DynamicFormComponent` component presents a list of questions by binding each one to an `<app-question>` element that matches the `DynamicFormQuestionComponent`.
<code-tabs>
<code-pane header="dynamic-form.component.html" path="dynamic-form/src/app/dynamic-form.component.html"></code-pane>
<code-pane header="dynamic-form.component.ts" path="dynamic-form/src/app/dynamic-form.component.ts"></code-pane>
</code-tabs>
### Display the form
To display an instance of the dynamic form, the `AppComponent` shell template passes the `questions` array returned by the `QuestionService` to the form container component, `<app-dynamic-form>`.
<code-example header="app.component.ts" path="dynamic-form/src/app/app.component.ts"></code-example>
The example provides a model for a job application for heroes, but there are no references to any specific hero question other than the objects returned by `QuestionService`.
This separation of model and data lets you repurpose the components for any type of survey, as long as it's compatible with the *question* object model.
### Ensuring valid data
The form template uses dynamic data binding of metadata to render the form without making any hardcoded assumptions about specific questions.
It adds both control metadata and validation criteria dynamically.
To ensure valid input, the *Save* button is disabled until the form is in a valid state.
When the form is valid, click *Save* and the application renders the current form values as JSON.
The following figure shows the final form.
<div class="lightbox">
<img alt="Dynamic-Form" src="generated/images/guide/dynamic-form/dynamic-form.png">
</div>
## Next steps
| Steps | Details |
|:--- |:--- |
| Different types of forms and control collection | This tutorial shows how to build a questionnaire, which is just one kind of dynamic form. The example uses `FormGroup` to collect a set of controls. For an example of a different type of dynamic form, see the section [Creating dynamic forms](guide/reactive-forms#creating-dynamic-forms "Create dynamic forms with arrays") in the Reactive Forms guide. That example also shows how to use `FormArray` instead of `FormGroup` to collect a set of controls. |
| Validating user input | The section [Validating form input](guide/reactive-forms#validating-form-input "Basic input validation") introduces the basics of how input validation works in reactive forms. <br /> The [Form validation guide](guide/form-validation "Form validation guide") covers the topic in more depth. |
<!-- links -->
<!-- external links -->
<!-- end links -->
@reviewed 2022-02-28
| aio/content/guide/dynamic-form.md | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.00017553371435496956,
0.00017046084394678473,
0.00016470164700876921,
0.00017028895672410727,
0.0000030337330372276483
] |
{
"id": 4,
"code_window": [
" let execSpy;\n",
"\n",
" beforeEach(() => execSpy = spyOn(sh, 'exec'));\n",
"\n",
" it('should execute yarn in silent mode', () => {\n",
" u.yarn('foo --bar');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" it('should execute the yarn binary in process.env.YARN_BIN', () => {\n",
" process.env.YARN_BIN = '/foo/yarn';\n",
" u.yarn('foo --bar');\n",
" const cmd = execSpy.calls.argsFor(0)[0];\n",
" expect(cmd.startsWith('/foo/yarn')).toEqual(true);\n",
" });\n",
"\n"
],
"file_path": "aio/scripts/deploy-to-firebase/utils.spec.mjs",
"type": "add",
"edit_start_line_idx": 286
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// This file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| packages/compiler/testing/testing.ts | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.00017514450883027166,
0.00017424988618586212,
0.0001733552635414526,
0.00017424988618586212,
8.946226444095373e-7
] |
{
"id": 4,
"code_window": [
" let execSpy;\n",
"\n",
" beforeEach(() => execSpy = spyOn(sh, 'exec'));\n",
"\n",
" it('should execute yarn in silent mode', () => {\n",
" u.yarn('foo --bar');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" it('should execute the yarn binary in process.env.YARN_BIN', () => {\n",
" process.env.YARN_BIN = '/foo/yarn';\n",
" u.yarn('foo --bar');\n",
" const cmd = execSpy.calls.argsFor(0)[0];\n",
" expect(cmd.startsWith('/foo/yarn')).toEqual(true);\n",
" });\n",
"\n"
],
"file_path": "aio/scripts/deploy-to-firebase/utils.spec.mjs",
"type": "add",
"edit_start_line_idx": 286
} | import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'example';
}
| aio/content/examples/angular-compiler-options/src/app/app.component.ts | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.00017833181482274085,
0.00017601976287551224,
0.00017370771092828363,
0.00017601976287551224,
0.0000023120519472286105
] |
{
"id": 5,
"code_window": [
" it('should execute yarn in silent mode', () => {\n",
" u.yarn('foo --bar');\n",
" expect(execSpy).toHaveBeenCalledWith('yarn --silent foo --bar');\n",
" });\n",
"\n",
" it('should return the output from the command\\'s execution', () => {\n",
" execSpy.and.returnValue('command output\\n');\n",
" expect(u.yarn('foo --bar')).toBe('command output\\n');\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const cmd = execSpy.calls.argsFor(0)[0];\n",
" expect(cmd.endsWith('--silent foo --bar')).toEqual(true);\n",
" });\n",
"\n",
" it('should cd into aio', () => {\n",
" u.yarn('foo --bar');\n",
"\n",
" const options = execSpy.calls.argsFor(0)[1];\n",
" expect(options.cwd).toEqual('aio');\n"
],
"file_path": "aio/scripts/deploy-to-firebase/utils.spec.mjs",
"type": "replace",
"edit_start_line_idx": 288
} | load("@aio_npm//@bazel/jasmine:index.bzl", "jasmine_node_test")
load("//tools:defaults.bzl", "nodejs_binary")
load("@aio_npm//@angular/build-tooling/bazel/remote-execution:index.bzl", "ENABLE_NETWORK")
DEPLOY_TO_FIREBASE_SOURCES = glob(
["**/*.mjs"],
["**/*.spec.mjs"],
)
DEPLOY_TO_FIREBASE_DEPS = [
"@aio_npm//shelljs",
"//aio:build",
"//:package.json",
]
nodejs_binary(
name = "deploy-to-firebase",
data = DEPLOY_TO_FIREBASE_SOURCES + DEPLOY_TO_FIREBASE_DEPS,
entry_point = "index.mjs",
)
jasmine_node_test(
name = "test",
srcs = glob(["**/*.spec.mjs"]),
data = DEPLOY_TO_FIREBASE_SOURCES,
# Tests make remote calls to git
exec_properties = ENABLE_NETWORK,
tags = ["requires-network"],
deps = DEPLOY_TO_FIREBASE_DEPS,
)
| aio/scripts/deploy-to-firebase/BUILD.bazel | 1 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.00018117607396561652,
0.0001731213997118175,
0.00016854761634021997,
0.00017138096154667437,
0.000005000792498321971
] |
{
"id": 5,
"code_window": [
" it('should execute yarn in silent mode', () => {\n",
" u.yarn('foo --bar');\n",
" expect(execSpy).toHaveBeenCalledWith('yarn --silent foo --bar');\n",
" });\n",
"\n",
" it('should return the output from the command\\'s execution', () => {\n",
" execSpy.and.returnValue('command output\\n');\n",
" expect(u.yarn('foo --bar')).toBe('command output\\n');\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const cmd = execSpy.calls.argsFor(0)[0];\n",
" expect(cmd.endsWith('--silent foo --bar')).toEqual(true);\n",
" });\n",
"\n",
" it('should cd into aio', () => {\n",
" u.yarn('foo --bar');\n",
"\n",
" const options = execSpy.calls.argsFor(0)[1];\n",
" expect(options.cwd).toEqual('aio');\n"
],
"file_path": "aio/scripts/deploy-to-firebase/utils.spec.mjs",
"type": "replace",
"edit_start_line_idx": 288
} | /**
* Helper function to be invoked by a manually set-up, time-based trigger in order to update the
* data on Firebase.
*/
function updateEventsOnFirebase() {
const persister = new Persister();
persister.updateDb();
}
/**
* Helper class to encapsulate logic about persisting events changes in the spreadsheet to the
* database (currently Firebase Realtime Database).
*/
class Persister {
/**
* Update the database with the latest data from edited sheets.
*
* If no sheets have been edited, this is a no-op.
*/
updateDb() {
this._log('Updating database...');
// Get the data for each edited sheet.
const data = this._getDataForEditedSheets();
// If no sheets have been edited, there is nothing to do.
if (data.length === 0) {
this._log('No sheets edited. Exiting...');
return;
}
// Update the database.
const partialEvents = data.reduce((acc, dataForSheet) => {
acc[dataForSheet.year] = dataForSheet.events;
return acc;
}, {});
const res = UrlFetchApp.fetch(`${DB_BASE_URL}/events.json?print=silent`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${ScriptApp.getOAuthToken()}`,
'Content-type': 'application/json',
},
payload: JSON.stringify(partialEvents),
});
this._log(`Database updated: ${res.getResponseCode()} - ${res.getContentText()}`);
}
_getDataForEditedSheets() {
// Get edited sheets that need processing.
const editedSheets = Property.editedSheets.get() || [];
this._log(`Edited sheets (${editedSheets.length}): ${editedSheets.join(', ') || '-'}`);
// Delete the corresponding property, indicating that no processing is pending.
Property.editedSheets.delete();
// Get the events data for edited sheets.
const ss = SpreadsheetApp.getActiveSpreadsheet();
return editedSheets.map(name => this._getDataForSheet(ss.getSheetByName(name)));
}
_getDataForSheet(sheet) {
const year = TEAM_ALLOCATION_SHEET_NAME_RE.exec(sheet.getName())[1];
// Get event dates per cell index.
// Dates display value is expected to be in the format `M/D`. For example: `5/15`
const startDatesRange = sheet.getRange('1:1');
const startDates = startDatesRange.
getDisplayValues()[0].
map((x, i) => ({
index: i,
value: x,
})).
filter(x => x.value !== '').
map(x => ({
index: x.index,
date: `${year}-${x.value.split('/').map(p => p.padStart(2, '0')).join('-')}`,
}));
// Get other event info (name, url) per cell index and merge with dates.
const namesRange = sheet.getRange('2:2');
const events = namesRange.
getRichTextValues()[0].
map((x, i) => ({
index: i,
value: {
text: x.getText(),
url: x.getLinkUrl() || undefined,
},
})).
filter(x => !/^(?:total)?$/i.test(x.value.text)).
map(x => ({
name: x.value.text,
linkUrl: x.value.url,
date: {
start: (startDates.find(y => y.index === x.index) || {}).date,
},
}));
return {year, events};
}
_log(msg) {
Logger.log(`[Persister] ${msg}`);
}
}
| aio/scripts/generate-events/apps-script-extension/persister.js | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.00017650582594797015,
0.00017233494145330042,
0.00016652490012347698,
0.00017435320478398353,
0.000003573694584702025
] |
{
"id": 5,
"code_window": [
" it('should execute yarn in silent mode', () => {\n",
" u.yarn('foo --bar');\n",
" expect(execSpy).toHaveBeenCalledWith('yarn --silent foo --bar');\n",
" });\n",
"\n",
" it('should return the output from the command\\'s execution', () => {\n",
" execSpy.and.returnValue('command output\\n');\n",
" expect(u.yarn('foo --bar')).toBe('command output\\n');\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const cmd = execSpy.calls.argsFor(0)[0];\n",
" expect(cmd.endsWith('--silent foo --bar')).toEqual(true);\n",
" });\n",
"\n",
" it('should cd into aio', () => {\n",
" u.yarn('foo --bar');\n",
"\n",
" const options = execSpy.calls.argsFor(0)[1];\n",
" expect(options.cwd).toEqual('aio');\n"
],
"file_path": "aio/scripts/deploy-to-firebase/utils.spec.mjs",
"type": "replace",
"edit_start_line_idx": 288
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {NgLocalization} from '@angular/common';
import {Serializer} from '@angular/compiler/src/i18n';
import {MessageBundle} from '@angular/compiler/src/i18n/message_bundle';
import {HtmlParser} from '@angular/compiler/src/ml_parser/html_parser';
import {DEFAULT_INTERPOLATION_CONFIG} from '@angular/compiler/src/ml_parser/interpolation_config';
import {ResourceLoader} from '@angular/compiler/src/resource_loader';
import {Component, DebugElement, TRANSLATIONS, TRANSLATIONS_FORMAT} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {stringifyElement} from '@angular/platform-browser/testing/src/browser_util';
import {expect} from '@angular/platform-browser/testing/src/matchers';
@Component({
selector: 'i18n-cmp',
template: '',
})
export class I18nComponent {
count?: number;
sex?: string;
sexB?: string;
response: any = {getItemsList: (): any[] => []};
}
export class FrLocalization extends NgLocalization {
public static PROVIDE = {provide: NgLocalization, useClass: FrLocalization, deps: []};
getPluralCategory(value: number): string {
switch (value) {
case 0:
case 1:
return 'one';
default:
return 'other';
}
}
}
export function validateHtml(
tb: ComponentFixture<I18nComponent>, cmp: I18nComponent, el: DebugElement) {
expectHtml(el, 'h1').toBe('<h1>attributs i18n sur les balises</h1>');
expectHtml(el, '#i18n-1').toBe('<div id="i18n-1"><p>imbriqué</p></div>');
expectHtml(el, '#i18n-2').toBe('<div id="i18n-2"><p>imbriqué</p></div>');
expectHtml(el, '#i18n-3').toBe('<div id="i18n-3"><p><i>avec des espaces réservés</i></p></div>');
expectHtml(el, '#i18n-3b')
.toBe(
'<div id="i18n-3b"><p><i class="preserved-on-placeholders">avec des espaces réservés</i></p></div>');
expectHtml(el, '#i18n-4')
.toBe('<p data-html="<b>gras</b>" id="i18n-4" title="sur des balises non traductibles"></p>');
expectHtml(el, '#i18n-5').toBe('<p id="i18n-5" title="sur des balises traductibles"></p>');
expectHtml(el, '#i18n-6').toBe('<p id="i18n-6" title=""></p>');
cmp.count = 0;
tb.detectChanges();
expect(el.query(By.css('#i18n-7')).nativeElement).toHaveText('zero');
expect(el.query(By.css('#i18n-14')).nativeElement).toHaveText('zero');
cmp.count = 1;
tb.detectChanges();
expect(el.query(By.css('#i18n-7')).nativeElement).toHaveText('un');
expect(el.query(By.css('#i18n-14')).nativeElement).toHaveText('un');
expect(el.query(By.css('#i18n-17')).nativeElement).toHaveText('un');
cmp.count = 2;
tb.detectChanges();
expect(el.query(By.css('#i18n-7')).nativeElement).toHaveText('deux');
expect(el.query(By.css('#i18n-14')).nativeElement).toHaveText('deux');
expect(el.query(By.css('#i18n-17')).nativeElement).toHaveText('deux');
cmp.count = 3;
tb.detectChanges();
expect(el.query(By.css('#i18n-7')).nativeElement).toHaveText('beaucoup');
expect(el.query(By.css('#i18n-14')).nativeElement).toHaveText('beaucoup');
expect(el.query(By.css('#i18n-17')).nativeElement).toHaveText('beaucoup');
cmp.sex = 'male';
cmp.sexB = 'female';
tb.detectChanges();
expect(el.query(By.css('#i18n-8')).nativeElement).toHaveText('homme');
expect(el.query(By.css('#i18n-8b')).nativeElement).toHaveText('femme');
cmp.sex = 'female';
tb.detectChanges();
expect(el.query(By.css('#i18n-8')).nativeElement).toHaveText('femme');
cmp.sex = '0';
tb.detectChanges();
expect(el.query(By.css('#i18n-8')).nativeElement).toHaveText('autre');
cmp.count = 123;
tb.detectChanges();
expectHtml(el, '#i18n-9').toEqual('<div id="i18n-9">count = 123</div>');
cmp.sex = 'f';
tb.detectChanges();
expectHtml(el, '#i18n-10').toEqual('<div id="i18n-10">sexe = f</div>');
expectHtml(el, '#i18n-11').toEqual('<div id="i18n-11">custom name</div>');
expectHtml(el, '#i18n-12').toEqual('<h1 id="i18n-12">Balises dans les commentaires html</h1>');
expectHtml(el, '#i18n-13').toBe('<div id="i18n-13" title="dans une section traductible"></div>');
expectHtml(el, '#i18n-15').toMatch(/ca <b>devrait<\/b> marcher/);
expectHtml(el, '#i18n-16').toMatch(/avec un ID explicite/);
expectHtml(el, '#i18n-17-5').toContain('Pas de réponse');
cmp.response.getItemsList = () => ['a'];
tb.detectChanges();
expectHtml(el, '#i18n-17-5').toContain('Une réponse');
cmp.response.getItemsList = () => ['a', 'b'];
tb.detectChanges();
expectHtml(el, '#i18n-17-5').toContain('2 réponses');
expectHtml(el, '#i18n-18')
.toEqual('<div id="i18n-18">FOO<a title="dans une section traductible">BAR</a></div>');
}
function expectHtml(el: DebugElement, cssSelector: string): any {
return expect(stringifyElement(el.query(By.css(cssSelector)).nativeElement));
}
export const HTML = `
<div>
<h1 i18n>i18n attribute on tags</h1>
<div id="i18n-1"><p i18n>nested</p></div>
<div id="i18n-2"><p i18n="different meaning|">nested</p></div>
<div id="i18n-3"><p i18n><i>with placeholders</i></p></div>
<div id="i18n-3b"><p i18n><i class="preserved-on-placeholders">with placeholders</i></p></div>
<div id="i18n-3c"><div i18n><div>with <div>nested</div> placeholders</div></div></div>
<div>
<p id="i18n-4" i18n-title title="on not translatable node" i18n-data-html data-html="<b>bold</b>"></p>
<p id="i18n-5" i18n i18n-title title="on translatable node"></p>
<p id="i18n-6" i18n-title title></p>
</div>
<!-- no ph below because the ICU node is the only child of the div, i.e. no text nodes -->
<div i18n id="i18n-7">{count, plural, =0 {zero} =1 {one} =2 {two} other {<b>many</b>}}</div>
<div i18n id="i18n-8">
{sex, select, male {m} female {f} other {other}}
</div>
<div i18n id="i18n-8b">
{sexB, select, male {m} female {f}}
</div>
<div i18n id="i18n-9">{{ "count = " + count }}</div>
<div i18n id="i18n-10">sex = {{ sex }}</div>
<div i18n id="i18n-11">{{ "custom name" //i18n(ph="CUSTOM_NAME") }}</div>
</div>
<!-- i18n -->
<h1 id="i18n-12" >Markers in html comments</h1>
<div id="i18n-13" i18n-title title="in a translatable section"></div>
<div id="i18n-14">{count, plural, =0 {zero} =1 {one} =2 {two} other {<b>many</b>}}</div>
<!-- /i18n -->
<div id="i18n-15"><ng-container i18n>it <b>should</b> work</ng-container></div>
<div id="i18n-16" i18n="@@i18n16">with an explicit ID</div>
<div id="i18n-17" i18n="@@i18n17">{count, plural, =0 {zero} =1 {one} =2 {two} other {<b>many</b>}}</div>
<!-- make sure that ICU messages are not treated as text nodes -->
<div id="i18n-17-5" i18n="desc">{
response.getItemsList().length,
plural,
=0 {Found no results}
=1 {Found one result}
other {Found {{response.getItemsList().length}} results}
}</div>
<div i18n id="i18n-18">foo<a i18n-title title="in a translatable section">bar</a></div>
<div id="i18n-19" i18n>{{ 'test' //i18n(ph="map name") }}</div>
`;
export async function configureCompiler(translationsToMerge: string, format: string) {
TestBed.configureCompiler({
providers: [
{provide: ResourceLoader, useValue: jasmine.createSpyObj('ResourceLoader', ['get'])},
FrLocalization.PROVIDE,
{provide: TRANSLATIONS, useValue: translationsToMerge},
{provide: TRANSLATIONS_FORMAT, useValue: format},
]
});
TestBed.configureTestingModule({declarations: [I18nComponent]});
}
export function createComponent(html: string) {
const tb: ComponentFixture<I18nComponent> =
TestBed.overrideTemplate(I18nComponent, html).createComponent(I18nComponent);
return {tb, cmp: tb.componentInstance, el: tb.debugElement};
}
export function serializeTranslations(html: string, serializer: Serializer) {
const catalog = new MessageBundle(new HtmlParser, [], {});
catalog.updateFromTemplate(html, 'file.ts', DEFAULT_INTERPOLATION_CONFIG);
return catalog.write(serializer);
}
| packages/compiler/test/i18n/integration_common.ts | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.00018036115216091275,
0.00017553656653035432,
0.00016291727661155164,
0.00017603689047973603,
0.0000037685629195038928
] |
{
"id": 5,
"code_window": [
" it('should execute yarn in silent mode', () => {\n",
" u.yarn('foo --bar');\n",
" expect(execSpy).toHaveBeenCalledWith('yarn --silent foo --bar');\n",
" });\n",
"\n",
" it('should return the output from the command\\'s execution', () => {\n",
" execSpy.and.returnValue('command output\\n');\n",
" expect(u.yarn('foo --bar')).toBe('command output\\n');\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const cmd = execSpy.calls.argsFor(0)[0];\n",
" expect(cmd.endsWith('--silent foo --bar')).toEqual(true);\n",
" });\n",
"\n",
" it('should cd into aio', () => {\n",
" u.yarn('foo --bar');\n",
"\n",
" const options = execSpy.calls.argsFor(0)[1];\n",
" expect(options.cwd).toEqual('aio');\n"
],
"file_path": "aio/scripts/deploy-to-firebase/utils.spec.mjs",
"type": "replace",
"edit_start_line_idx": 288
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ParsedEvent, ParsedProperty, ParsedVariable} from '../expression_parser/ast';
import * as i18n from '../i18n/i18n_ast';
import * as html from '../ml_parser/ast';
import {replaceNgsp} from '../ml_parser/html_whitespaces';
import {isNgTemplate} from '../ml_parser/tags';
import {InterpolatedAttributeToken, InterpolatedTextToken} from '../ml_parser/tokens';
import {ParseError, ParseErrorLevel, ParseSourceSpan} from '../parse_util';
import {isStyleUrlResolvable} from '../style_url_resolver';
import {BindingParser} from '../template_parser/binding_parser';
import {PreparsedElementType, preparseElement} from '../template_parser/template_preparser';
import * as t from './r3_ast';
import {I18N_ICU_VAR_PREFIX, isI18nRootNode} from './view/i18n/util';
const BIND_NAME_REGEXP = /^(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.*)$/;
// Group 1 = "bind-"
const KW_BIND_IDX = 1;
// Group 2 = "let-"
const KW_LET_IDX = 2;
// Group 3 = "ref-/#"
const KW_REF_IDX = 3;
// Group 4 = "on-"
const KW_ON_IDX = 4;
// Group 5 = "bindon-"
const KW_BINDON_IDX = 5;
// Group 6 = "@"
const KW_AT_IDX = 6;
// Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
const IDENT_KW_IDX = 7;
const BINDING_DELIMS = {
BANANA_BOX: {start: '[(', end: ')]'},
PROPERTY: {start: '[', end: ']'},
EVENT: {start: '(', end: ')'},
};
const TEMPLATE_ATTR_PREFIX = '*';
// Result of the html AST to Ivy AST transformation
export interface Render3ParseResult {
nodes: t.Node[];
errors: ParseError[];
styles: string[];
styleUrls: string[];
ngContentSelectors: string[];
// Will be defined if `Render3ParseOptions['collectCommentNodes']` is true
commentNodes?: t.Comment[];
}
interface Render3ParseOptions {
collectCommentNodes: boolean;
}
export function htmlAstToRender3Ast(
htmlNodes: html.Node[], bindingParser: BindingParser,
options: Render3ParseOptions): Render3ParseResult {
const transformer = new HtmlAstToIvyAst(bindingParser, options);
const ivyNodes = html.visitAll(transformer, htmlNodes);
// Errors might originate in either the binding parser or the html to ivy transformer
const allErrors = bindingParser.errors.concat(transformer.errors);
const result: Render3ParseResult = {
nodes: ivyNodes,
errors: allErrors,
styleUrls: transformer.styleUrls,
styles: transformer.styles,
ngContentSelectors: transformer.ngContentSelectors
};
if (options.collectCommentNodes) {
result.commentNodes = transformer.commentNodes;
}
return result;
}
class HtmlAstToIvyAst implements html.Visitor {
errors: ParseError[] = [];
styles: string[] = [];
styleUrls: string[] = [];
ngContentSelectors: string[] = [];
// This array will be populated if `Render3ParseOptions['collectCommentNodes']` is true
commentNodes: t.Comment[] = [];
private inI18nBlock: boolean = false;
constructor(private bindingParser: BindingParser, private options: Render3ParseOptions) {}
// HTML visitor
visitElement(element: html.Element): t.Node|null {
const isI18nRootElement = isI18nRootNode(element.i18n);
if (isI18nRootElement) {
if (this.inI18nBlock) {
this.reportError(
'Cannot mark an element as translatable inside of a translatable section. Please remove the nested i18n marker.',
element.sourceSpan);
}
this.inI18nBlock = true;
}
const preparsedElement = preparseElement(element);
if (preparsedElement.type === PreparsedElementType.SCRIPT) {
return null;
} else if (preparsedElement.type === PreparsedElementType.STYLE) {
const contents = textContents(element);
if (contents !== null) {
this.styles.push(contents);
}
return null;
} else if (
preparsedElement.type === PreparsedElementType.STYLESHEET &&
isStyleUrlResolvable(preparsedElement.hrefAttr)) {
this.styleUrls.push(preparsedElement.hrefAttr);
return null;
}
// Whether the element is a `<ng-template>`
const isTemplateElement = isNgTemplate(element.name);
const parsedProperties: ParsedProperty[] = [];
const boundEvents: t.BoundEvent[] = [];
const variables: t.Variable[] = [];
const references: t.Reference[] = [];
const attributes: t.TextAttribute[] = [];
const i18nAttrsMeta: {[key: string]: i18n.I18nMeta} = {};
const templateParsedProperties: ParsedProperty[] = [];
const templateVariables: t.Variable[] = [];
// Whether the element has any *-attribute
let elementHasInlineTemplate = false;
for (const attribute of element.attrs) {
let hasBinding = false;
const normalizedName = normalizeAttributeName(attribute.name);
// `*attr` defines template bindings
let isTemplateBinding = false;
if (attribute.i18n) {
i18nAttrsMeta[attribute.name] = attribute.i18n;
}
if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX)) {
// *-attributes
if (elementHasInlineTemplate) {
this.reportError(
`Can't have multiple template bindings on one element. Use only one attribute prefixed with *`,
attribute.sourceSpan);
}
isTemplateBinding = true;
elementHasInlineTemplate = true;
const templateValue = attribute.value;
const templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX.length);
const parsedVariables: ParsedVariable[] = [];
const absoluteValueOffset = attribute.valueSpan ?
attribute.valueSpan.start.offset :
// If there is no value span the attribute does not have a value, like `attr` in
//`<div attr></div>`. In this case, point to one character beyond the last character of
// the attribute name.
attribute.sourceSpan.start.offset + attribute.name.length;
this.bindingParser.parseInlineTemplateBinding(
templateKey, templateValue, attribute.sourceSpan, absoluteValueOffset, [],
templateParsedProperties, parsedVariables, true /* isIvyAst */);
templateVariables.push(...parsedVariables.map(
v => new t.Variable(v.name, v.value, v.sourceSpan, v.keySpan, v.valueSpan)));
} else {
// Check for variables, events, property bindings, interpolation
hasBinding = this.parseAttribute(
isTemplateElement, attribute, [], parsedProperties, boundEvents, variables, references);
}
if (!hasBinding && !isTemplateBinding) {
// don't include the bindings as attributes as well in the AST
attributes.push(this.visitAttribute(attribute));
}
}
const children: t.Node[] =
html.visitAll(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children);
let parsedElement: t.Content|t.Template|t.Element|undefined;
if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
// `<ng-content>`
if (element.children &&
!element.children.every(
(node: html.Node) => isEmptyTextNode(node) || isCommentNode(node))) {
this.reportError(`<ng-content> element cannot have content.`, element.sourceSpan);
}
const selector = preparsedElement.selectAttr;
const attrs: t.TextAttribute[] = element.attrs.map(attr => this.visitAttribute(attr));
parsedElement = new t.Content(selector, attrs, element.sourceSpan, element.i18n);
this.ngContentSelectors.push(selector);
} else if (isTemplateElement) {
// `<ng-template>`
const attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
parsedElement = new t.Template(
element.name, attributes, attrs.bound, boundEvents, [/* no template attributes */],
children, references, variables, element.sourceSpan, element.startSourceSpan,
element.endSourceSpan, element.i18n);
} else {
const attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
parsedElement = new t.Element(
element.name, attributes, attrs.bound, boundEvents, children, references,
element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
}
if (elementHasInlineTemplate) {
// If this node is an inline-template (e.g. has *ngFor) then we need to create a template
// node that contains this node.
// Moreover, if the node is an element, then we need to hoist its attributes to the template
// node for matching against content projection selectors.
const attrs = this.extractAttributes('ng-template', templateParsedProperties, i18nAttrsMeta);
const templateAttrs: (t.TextAttribute|t.BoundAttribute)[] = [];
attrs.literal.forEach(attr => templateAttrs.push(attr));
attrs.bound.forEach(attr => templateAttrs.push(attr));
const hoistedAttrs = parsedElement instanceof t.Element ?
{
attributes: parsedElement.attributes,
inputs: parsedElement.inputs,
outputs: parsedElement.outputs,
} :
{attributes: [], inputs: [], outputs: []};
// For <ng-template>s with structural directives on them, avoid passing i18n information to
// the wrapping template to prevent unnecessary i18n instructions from being generated. The
// necessary i18n meta information will be extracted from child elements.
const i18n = isTemplateElement && isI18nRootElement ? undefined : element.i18n;
const name = parsedElement instanceof t.Template ? null : parsedElement.name;
parsedElement = new t.Template(
name, hoistedAttrs.attributes, hoistedAttrs.inputs, hoistedAttrs.outputs, templateAttrs,
[parsedElement], [/* no references */], templateVariables, element.sourceSpan,
element.startSourceSpan, element.endSourceSpan, i18n);
}
if (isI18nRootElement) {
this.inI18nBlock = false;
}
return parsedElement;
}
visitAttribute(attribute: html.Attribute): t.TextAttribute {
return new t.TextAttribute(
attribute.name, attribute.value, attribute.sourceSpan, attribute.keySpan,
attribute.valueSpan, attribute.i18n);
}
visitText(text: html.Text): t.Node {
return this._visitTextWithInterpolation(text.value, text.sourceSpan, text.tokens, text.i18n);
}
visitExpansion(expansion: html.Expansion): t.Icu|null {
if (!expansion.i18n) {
// do not generate Icu in case it was created
// outside of i18n block in a template
return null;
}
if (!isI18nRootNode(expansion.i18n)) {
throw new Error(`Invalid type "${expansion.i18n.constructor}" for "i18n" property of ${
expansion.sourceSpan.toString()}. Expected a "Message"`);
}
const message = expansion.i18n;
const vars: {[name: string]: t.BoundText} = {};
const placeholders: {[name: string]: t.Text|t.BoundText} = {};
// extract VARs from ICUs - we process them separately while
// assembling resulting message via goog.getMsg function, since
// we need to pass them to top-level goog.getMsg call
Object.keys(message.placeholders).forEach(key => {
const value = message.placeholders[key];
if (key.startsWith(I18N_ICU_VAR_PREFIX)) {
// Currently when the `plural` or `select` keywords in an ICU contain trailing spaces (e.g.
// `{count, select , ...}`), these spaces are also included into the key names in ICU vars
// (e.g. "VAR_SELECT "). These trailing spaces are not desirable, since they will later be
// converted into `_` symbols while normalizing placeholder names, which might lead to
// mismatches at runtime (i.e. placeholder will not be replaced with the correct value).
const formattedKey = key.trim();
const ast = this.bindingParser.parseInterpolationExpression(value.text, value.sourceSpan);
vars[formattedKey] = new t.BoundText(ast, value.sourceSpan);
} else {
placeholders[key] = this._visitTextWithInterpolation(value.text, value.sourceSpan, null);
}
});
return new t.Icu(vars, placeholders, expansion.sourceSpan, message);
}
visitExpansionCase(expansionCase: html.ExpansionCase): null {
return null;
}
visitComment(comment: html.Comment): null {
if (this.options.collectCommentNodes) {
this.commentNodes.push(new t.Comment(comment.value || '', comment.sourceSpan));
}
return null;
}
// convert view engine `ParsedProperty` to a format suitable for IVY
private extractAttributes(
elementName: string, properties: ParsedProperty[],
i18nPropsMeta: {[key: string]: i18n.I18nMeta}):
{bound: t.BoundAttribute[], literal: t.TextAttribute[]} {
const bound: t.BoundAttribute[] = [];
const literal: t.TextAttribute[] = [];
properties.forEach(prop => {
const i18n = i18nPropsMeta[prop.name];
if (prop.isLiteral) {
literal.push(new t.TextAttribute(
prop.name, prop.expression.source || '', prop.sourceSpan, prop.keySpan, prop.valueSpan,
i18n));
} else {
// Note that validation is skipped and property mapping is disabled
// due to the fact that we need to make sure a given prop is not an
// input of a directive and directive matching happens at runtime.
const bep = this.bindingParser.createBoundElementProperty(
elementName, prop, /* skipValidation */ true, /* mapPropertyName */ false);
bound.push(t.BoundAttribute.fromBoundElementProperty(bep, i18n));
}
});
return {bound, literal};
}
private parseAttribute(
isTemplateElement: boolean, attribute: html.Attribute, matchableAttributes: string[][],
parsedProperties: ParsedProperty[], boundEvents: t.BoundEvent[], variables: t.Variable[],
references: t.Reference[]) {
const name = normalizeAttributeName(attribute.name);
const value = attribute.value;
const srcSpan = attribute.sourceSpan;
const absoluteOffset =
attribute.valueSpan ? attribute.valueSpan.start.offset : srcSpan.start.offset;
function createKeySpan(srcSpan: ParseSourceSpan, prefix: string, identifier: string) {
// We need to adjust the start location for the keySpan to account for the removed 'data-'
// prefix from `normalizeAttributeName`.
const normalizationAdjustment = attribute.name.length - name.length;
const keySpanStart = srcSpan.start.moveBy(prefix.length + normalizationAdjustment);
const keySpanEnd = keySpanStart.moveBy(identifier.length);
return new ParseSourceSpan(keySpanStart, keySpanEnd, keySpanStart, identifier);
}
const bindParts = name.match(BIND_NAME_REGEXP);
if (bindParts) {
if (bindParts[KW_BIND_IDX] != null) {
const identifier = bindParts[IDENT_KW_IDX];
const keySpan = createKeySpan(srcSpan, bindParts[KW_BIND_IDX], identifier);
this.bindingParser.parsePropertyBinding(
identifier, value, false, srcSpan, absoluteOffset, attribute.valueSpan,
matchableAttributes, parsedProperties, keySpan);
} else if (bindParts[KW_LET_IDX]) {
if (isTemplateElement) {
const identifier = bindParts[IDENT_KW_IDX];
const keySpan = createKeySpan(srcSpan, bindParts[KW_LET_IDX], identifier);
this.parseVariable(identifier, value, srcSpan, keySpan, attribute.valueSpan, variables);
} else {
this.reportError(`"let-" is only supported on ng-template elements.`, srcSpan);
}
} else if (bindParts[KW_REF_IDX]) {
const identifier = bindParts[IDENT_KW_IDX];
const keySpan = createKeySpan(srcSpan, bindParts[KW_REF_IDX], identifier);
this.parseReference(identifier, value, srcSpan, keySpan, attribute.valueSpan, references);
} else if (bindParts[KW_ON_IDX]) {
const events: ParsedEvent[] = [];
const identifier = bindParts[IDENT_KW_IDX];
const keySpan = createKeySpan(srcSpan, bindParts[KW_ON_IDX], identifier);
this.bindingParser.parseEvent(
identifier, value, /* isAssignmentEvent */ false, srcSpan,
attribute.valueSpan || srcSpan, matchableAttributes, events, keySpan);
addEvents(events, boundEvents);
} else if (bindParts[KW_BINDON_IDX]) {
const identifier = bindParts[IDENT_KW_IDX];
const keySpan = createKeySpan(srcSpan, bindParts[KW_BINDON_IDX], identifier);
this.bindingParser.parsePropertyBinding(
identifier, value, false, srcSpan, absoluteOffset, attribute.valueSpan,
matchableAttributes, parsedProperties, keySpan);
this.parseAssignmentEvent(
identifier, value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents,
keySpan);
} else if (bindParts[KW_AT_IDX]) {
const keySpan = createKeySpan(srcSpan, '', name);
this.bindingParser.parseLiteralAttr(
name, value, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes,
parsedProperties, keySpan);
}
return true;
}
// We didn't see a kw-prefixed property binding, but we have not yet checked
// for the []/()/[()] syntax.
let delims: {start: string, end: string}|null = null;
if (name.startsWith(BINDING_DELIMS.BANANA_BOX.start)) {
delims = BINDING_DELIMS.BANANA_BOX;
} else if (name.startsWith(BINDING_DELIMS.PROPERTY.start)) {
delims = BINDING_DELIMS.PROPERTY;
} else if (name.startsWith(BINDING_DELIMS.EVENT.start)) {
delims = BINDING_DELIMS.EVENT;
}
if (delims !== null &&
// NOTE: older versions of the parser would match a start/end delimited
// binding iff the property name was terminated by the ending delimiter
// and the identifier in the binding was non-empty.
// TODO(ayazhafiz): update this to handle malformed bindings.
name.endsWith(delims.end) && name.length > delims.start.length + delims.end.length) {
const identifier = name.substring(delims.start.length, name.length - delims.end.length);
const keySpan = createKeySpan(srcSpan, delims.start, identifier);
if (delims.start === BINDING_DELIMS.BANANA_BOX.start) {
this.bindingParser.parsePropertyBinding(
identifier, value, false, srcSpan, absoluteOffset, attribute.valueSpan,
matchableAttributes, parsedProperties, keySpan);
this.parseAssignmentEvent(
identifier, value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents,
keySpan);
} else if (delims.start === BINDING_DELIMS.PROPERTY.start) {
this.bindingParser.parsePropertyBinding(
identifier, value, false, srcSpan, absoluteOffset, attribute.valueSpan,
matchableAttributes, parsedProperties, keySpan);
} else {
const events: ParsedEvent[] = [];
this.bindingParser.parseEvent(
identifier, value, /* isAssignmentEvent */ false, srcSpan,
attribute.valueSpan || srcSpan, matchableAttributes, events, keySpan);
addEvents(events, boundEvents);
}
return true;
}
// No explicit binding found.
const keySpan = createKeySpan(srcSpan, '' /* prefix */, name);
const hasBinding = this.bindingParser.parsePropertyInterpolation(
name, value, srcSpan, attribute.valueSpan, matchableAttributes, parsedProperties, keySpan,
attribute.valueTokens ?? null);
return hasBinding;
}
private _visitTextWithInterpolation(
value: string, sourceSpan: ParseSourceSpan,
interpolatedTokens: InterpolatedAttributeToken[]|InterpolatedTextToken[]|null,
i18n?: i18n.I18nMeta): t.Text|t.BoundText {
const valueNoNgsp = replaceNgsp(value);
const expr = this.bindingParser.parseInterpolation(valueNoNgsp, sourceSpan, interpolatedTokens);
return expr ? new t.BoundText(expr, sourceSpan, i18n) : new t.Text(valueNoNgsp, sourceSpan);
}
private parseVariable(
identifier: string, value: string, sourceSpan: ParseSourceSpan, keySpan: ParseSourceSpan,
valueSpan: ParseSourceSpan|undefined, variables: t.Variable[]) {
if (identifier.indexOf('-') > -1) {
this.reportError(`"-" is not allowed in variable names`, sourceSpan);
} else if (identifier.length === 0) {
this.reportError(`Variable does not have a name`, sourceSpan);
}
variables.push(new t.Variable(identifier, value, sourceSpan, keySpan, valueSpan));
}
private parseReference(
identifier: string, value: string, sourceSpan: ParseSourceSpan, keySpan: ParseSourceSpan,
valueSpan: ParseSourceSpan|undefined, references: t.Reference[]) {
if (identifier.indexOf('-') > -1) {
this.reportError(`"-" is not allowed in reference names`, sourceSpan);
} else if (identifier.length === 0) {
this.reportError(`Reference does not have a name`, sourceSpan);
} else if (references.some(reference => reference.name === identifier)) {
this.reportError(`Reference "#${identifier}" is defined more than once`, sourceSpan);
}
references.push(new t.Reference(identifier, value, sourceSpan, keySpan, valueSpan));
}
private parseAssignmentEvent(
name: string, expression: string, sourceSpan: ParseSourceSpan,
valueSpan: ParseSourceSpan|undefined, targetMatchableAttrs: string[][],
boundEvents: t.BoundEvent[], keySpan: ParseSourceSpan) {
const events: ParsedEvent[] = [];
this.bindingParser.parseEvent(
`${name}Change`, `${expression} =$event`, /* isAssignmentEvent */ true, sourceSpan,
valueSpan || sourceSpan, targetMatchableAttrs, events, keySpan);
addEvents(events, boundEvents);
}
private reportError(
message: string, sourceSpan: ParseSourceSpan,
level: ParseErrorLevel = ParseErrorLevel.ERROR) {
this.errors.push(new ParseError(sourceSpan, message, level));
}
}
class NonBindableVisitor implements html.Visitor {
visitElement(ast: html.Element): t.Element|null {
const preparsedElement = preparseElement(ast);
if (preparsedElement.type === PreparsedElementType.SCRIPT ||
preparsedElement.type === PreparsedElementType.STYLE ||
preparsedElement.type === PreparsedElementType.STYLESHEET) {
// Skipping <script> for security reasons
// Skipping <style> and stylesheets as we already processed them
// in the StyleCompiler
return null;
}
const children: t.Node[] = html.visitAll(this, ast.children, null);
return new t.Element(
ast.name, html.visitAll(this, ast.attrs) as t.TextAttribute[],
/* inputs */[], /* outputs */[], children, /* references */[], ast.sourceSpan,
ast.startSourceSpan, ast.endSourceSpan);
}
visitComment(comment: html.Comment): any {
return null;
}
visitAttribute(attribute: html.Attribute): t.TextAttribute {
return new t.TextAttribute(
attribute.name, attribute.value, attribute.sourceSpan, attribute.keySpan,
attribute.valueSpan, attribute.i18n);
}
visitText(text: html.Text): t.Text {
return new t.Text(text.value, text.sourceSpan);
}
visitExpansion(expansion: html.Expansion): any {
return null;
}
visitExpansionCase(expansionCase: html.ExpansionCase): any {
return null;
}
}
const NON_BINDABLE_VISITOR = new NonBindableVisitor();
function normalizeAttributeName(attrName: string): string {
return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
}
function addEvents(events: ParsedEvent[], boundEvents: t.BoundEvent[]) {
boundEvents.push(...events.map(e => t.BoundEvent.fromParsedEvent(e)));
}
function isEmptyTextNode(node: html.Node): boolean {
return node instanceof html.Text && node.value.trim().length == 0;
}
function isCommentNode(node: html.Node): boolean {
return node instanceof html.Comment;
}
function textContents(node: html.Element): string|null {
if (node.children.length !== 1 || !(node.children[0] instanceof html.Text)) {
return null;
} else {
return (node.children[0] as html.Text).value;
}
}
| packages/compiler/src/render3/r3_template_transform.ts | 0 | https://github.com/angular/angular/commit/28079b93649b5deed97ac04b3e70ec39a858b174 | [
0.0002476171648595482,
0.00017438885697629303,
0.00016537547344341874,
0.00017352569557260722,
0.000010092884622281417
] |
{
"id": 2,
"code_window": [
"\t\treadonly onDidReceiveMessage: Event<{ editor: NotebookEditor, message: any }>;\n",
"\t\tpostMessage(message: any, editor?: NotebookEditor): Thenable<boolean>;\n",
"\t\tasWebviewUri(localResource: Uri, editor: NotebookEditor): Uri;\n",
"\t}\n",
"\n",
"\texport interface NotebookControllerOptions {\n",
"\t\tid: string;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tasWebviewUri(localResource: Uri): Uri;\n"
],
"file_path": "src/vs/vscode.proposed.d.ts",
"type": "replace",
"edit_start_line_idx": 1027
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { ExtHostNotebookKernelsShape, IMainContext, INotebookKernelDto2, MainContext, MainThreadNotebookKernelsShape } from 'vs/workbench/api/common/extHost.protocol';
import * as vscode from 'vscode';
import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { URI, UriComponents } from 'vs/base/common/uri';
import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import * as extHostTypeConverters from 'vs/workbench/api/common/extHostTypeConverters';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { asWebviewUri } from 'vs/workbench/api/common/shared/webview';
type ExecuteHandler = (cells: vscode.NotebookCell[], controller: vscode.NotebookController) => void;
type InterruptHandler = (notebook: vscode.NotebookDocument) => void;
interface IKernelData {
controller: vscode.NotebookController;
onDidChangeSelection: Emitter<{ selected: boolean; notebook: vscode.NotebookDocument; }>;
onDidReceiveMessage: Emitter<{ editor: vscode.NotebookEditor, message: any }>;
}
export class ExtHostNotebookKernels implements ExtHostNotebookKernelsShape {
private readonly _proxy: MainThreadNotebookKernelsShape;
private readonly _kernelData = new Map<number, IKernelData>();
private _handlePool: number = 0;
constructor(
mainContext: IMainContext,
private readonly _initData: IExtHostInitDataService,
private readonly _extHostNotebook: ExtHostNotebookController
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadNotebookKernels);
}
createKernel(extension: IExtensionDescription, options: vscode.NotebookControllerOptions): vscode.NotebookController {
const handle = this._handlePool++;
const that = this;
let isDisposed = false;
const commandDisposables = new DisposableStore();
const onDidChangeSelection = new Emitter<{ selected: boolean, notebook: vscode.NotebookDocument }>();
const onDidReceiveMessage = new Emitter<{ editor: vscode.NotebookEditor, message: any }>();
const data: INotebookKernelDto2 = {
id: options.id,
selector: options.selector,
extensionId: extension.identifier,
extensionLocation: extension.extensionLocation,
label: options.label,
supportedLanguages: [],
};
//
let _executeHandler: ExecuteHandler = options.executeHandler;
let _interruptHandler: InterruptHandler | undefined = options.interruptHandler;
// todo@jrieken the selector needs to be massaged
this._proxy.$addKernel(handle, data);
// update: all setters write directly into the dto object
// and trigger an update. the actual update will only happen
// once per event loop execution
let tokenPool = 0;
const _update = () => {
if (isDisposed) {
return;
}
const myToken = ++tokenPool;
Promise.resolve().then(() => {
if (myToken === tokenPool) {
this._proxy.$updateKernel(handle, data);
}
});
};
const controller: vscode.NotebookController = {
get id() { return data.id; },
get selector() { return data.selector; },
onDidChangeNotebookAssociation: onDidChangeSelection.event,
get label() {
return data.label;
},
set label(value) {
data.label = value;
_update();
},
get description() {
return data.description ?? '';
},
set description(value) {
data.description = value;
_update();
},
get isPreferred() {
return data.isPreferred ?? false;
},
set isPreferred(value) {
data.isPreferred = value;
_update();
},
get supportedLanguages() {
return data.supportedLanguages;
},
set supportedLanguages(value) {
data.supportedLanguages = isNonEmptyArray(value) ? value : ['plaintext'];
_update();
},
get hasExecutionOrder() {
return data.hasExecutionOrder ?? false;
},
set hasExecutionOrder(value) {
data.hasExecutionOrder = value;
_update();
},
get preloads() {
return data.preloads && data.preloads.map(extHostTypeConverters.NotebookKernelPreload.to);
},
set preloads(value) {
data.preloads = value && value.map(extHostTypeConverters.NotebookKernelPreload.from);
_update();
},
get executeHandler() {
return _executeHandler;
},
get interruptHandler() {
return _interruptHandler;
},
set interruptHandler(value) {
_interruptHandler = value;
data.supportsInterrupt = Boolean(value);
_update();
},
createNotebookCellExecutionTask(cell) {
if (isDisposed) {
throw new Error('notebook controller is DISPOSED');
}
//todo@jrieken
return that._extHostNotebook.createNotebookCellExecution(cell.notebook.uri, cell.index, data.id)!;
},
dispose: () => {
if (!isDisposed) {
isDisposed = true;
this._kernelData.delete(handle);
commandDisposables.dispose();
onDidChangeSelection.dispose();
onDidReceiveMessage.dispose();
this._proxy.$removeKernel(handle);
}
},
// --- ipc
onDidReceiveMessage: onDidReceiveMessage.event,
postMessage(message, editor) {
return that._proxy.$postMessage(handle, editor && that._extHostNotebook.getIdByEditor(editor), message);
},
asWebviewUri(uri: URI, editor) {
return asWebviewUri(that._initData.environment, that._extHostNotebook.getIdByEditor(editor)!, uri);
}
};
this._kernelData.set(handle, { controller, onDidChangeSelection, onDidReceiveMessage });
controller.supportedLanguages = options.supportedLanguages ?? [];
controller.interruptHandler = options.interruptHandler;
controller.hasExecutionOrder = options.hasExecutionOrder ?? false;
return controller;
}
$acceptSelection(handle: number, uri: UriComponents, value: boolean): void {
const obj = this._kernelData.get(handle);
if (obj) {
obj.onDidChangeSelection.fire({
selected: value,
notebook: this._extHostNotebook.lookupNotebookDocument(URI.revive(uri))!.notebookDocument
});
}
}
$executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void {
const obj = this._kernelData.get(handle);
if (!obj) {
// extension can dispose kernels in the meantime
return;
}
const document = this._extHostNotebook.lookupNotebookDocument(URI.revive(uri));
if (!document) {
throw new Error('MISSING notebook');
}
const cells: vscode.NotebookCell[] = [];
for (let range of ranges) {
cells.push(...document.notebookDocument.getCells(extHostTypeConverters.NotebookRange.to(range)));
}
try {
obj.controller.executeHandler(cells, obj.controller);
} catch (err) {
//
console.error(err);
}
}
$cancelCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void {
const obj = this._kernelData.get(handle);
if (!obj) {
// extension can dispose kernels in the meantime
return;
}
const document = this._extHostNotebook.lookupNotebookDocument(URI.revive(uri));
if (!document) {
throw new Error('MISSING notebook');
}
if (obj.controller.interruptHandler) {
obj.controller.interruptHandler(document.notebookDocument);
}
// we do both? interrupt and cancellation or should we be selective?
for (const range of ranges) {
for (let i = range.start; i < range.end; i++) {
const cell = document.getCellFromIndex(i);
if (cell) {
this._extHostNotebook.cancelOneNotebookCellExecution(cell);
}
}
}
}
$acceptRendererMessage(handle: number, editorId: string, message: any): void {
const obj = this._kernelData.get(handle);
if (!obj) {
// extension can dispose kernels in the meantime
return;
}
const editor = this._extHostNotebook.getEditorById(editorId);
if (!editor) {
throw new Error(`send message for UNKNOWN editor: ${editorId}`);
}
obj.onDidReceiveMessage.fire(Object.freeze({ editor: editor.apiEditor, message }));
}
}
| src/vs/workbench/api/common/extHostNotebookKernels.ts | 1 | https://github.com/microsoft/vscode/commit/c074bf897c0c3cd6ba5705828402924a3cc2b4dc | [
0.9987331032752991,
0.11656203866004944,
0.00016463945212308317,
0.00017582657164894044,
0.3096008896827698
] |
{
"id": 2,
"code_window": [
"\t\treadonly onDidReceiveMessage: Event<{ editor: NotebookEditor, message: any }>;\n",
"\t\tpostMessage(message: any, editor?: NotebookEditor): Thenable<boolean>;\n",
"\t\tasWebviewUri(localResource: Uri, editor: NotebookEditor): Uri;\n",
"\t}\n",
"\n",
"\texport interface NotebookControllerOptions {\n",
"\t\tid: string;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tasWebviewUri(localResource: Uri): Uri;\n"
],
"file_path": "src/vs/vscode.proposed.d.ts",
"type": "replace",
"edit_start_line_idx": 1027
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { flatten } from 'vs/base/common/arrays';
import { Emitter, Event } from 'vs/base/common/event';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { Disposable, IDisposable, MutableDisposable } from 'vs/base/common/lifecycle';
import { isWeb } from 'vs/base/common/platform';
import { isFalsyOrWhitespace } from 'vs/base/common/strings';
import { isString } from 'vs/base/common/types';
import { AuthenticationProviderInformation, AuthenticationSession, AuthenticationSessionsChangeEvent } from 'vs/editor/common/modes';
import * as nls from 'vs/nls';
import { MenuId, MenuRegistry } from 'vs/platform/actions/common/actions';
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { Severity } from 'vs/platform/notification/common/notification';
import { IProductService } from 'vs/platform/product/common/productService';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { MainThreadAuthenticationProvider } from 'vs/workbench/api/browser/mainThreadAuthentication';
import { IActivityService, NumberBadge } from 'vs/workbench/services/activity/common/activity';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { ActivationKind, IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { ExtensionsRegistry } from 'vs/workbench/services/extensions/common/extensionsRegistry';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
export function getAuthenticationProviderActivationEvent(id: string): string { return `onAuthenticationRequest:${id}`; }
export interface IAccountUsage {
extensionId: string;
extensionName: string;
lastUsed: number;
}
const VSO_ALLOWED_EXTENSIONS = ['github.vscode-pull-request-github', 'github.vscode-pull-request-github-insiders', 'vscode.git', 'ms-vsonline.vsonline', 'vscode.github-browser', 'ms-vscode.github-browser', 'ms-vscode.remotehub', 'ms-vscode.remotehub-insiders', 'github.codespaces'];
export function readAccountUsages(storageService: IStorageService, providerId: string, accountName: string,): IAccountUsage[] {
const accountKey = `${providerId}-${accountName}-usages`;
const storedUsages = storageService.get(accountKey, StorageScope.GLOBAL);
let usages: IAccountUsage[] = [];
if (storedUsages) {
try {
usages = JSON.parse(storedUsages);
} catch (e) {
// ignore
}
}
return usages;
}
export function removeAccountUsage(storageService: IStorageService, providerId: string, accountName: string): void {
const accountKey = `${providerId}-${accountName}-usages`;
storageService.remove(accountKey, StorageScope.GLOBAL);
}
export function addAccountUsage(storageService: IStorageService, providerId: string, accountName: string, extensionId: string, extensionName: string) {
const accountKey = `${providerId}-${accountName}-usages`;
const usages = readAccountUsages(storageService, providerId, accountName);
const existingUsageIndex = usages.findIndex(usage => usage.extensionId === extensionId);
if (existingUsageIndex > -1) {
usages.splice(existingUsageIndex, 1, {
extensionId,
extensionName,
lastUsed: Date.now()
});
} else {
usages.push({
extensionId,
extensionName,
lastUsed: Date.now()
});
}
storageService.store(accountKey, JSON.stringify(usages), StorageScope.GLOBAL, StorageTarget.MACHINE);
}
export type AuthenticationSessionInfo = { readonly id: string, readonly accessToken: string, readonly providerId: string, readonly canSignOut?: boolean };
export async function getCurrentAuthenticationSessionInfo(environmentService: IWorkbenchEnvironmentService, productService: IProductService): Promise<AuthenticationSessionInfo | undefined> {
if (environmentService.options?.credentialsProvider) {
const authenticationSessionValue = await environmentService.options.credentialsProvider.getPassword(`${productService.urlProtocol}.login`, 'account');
if (authenticationSessionValue) {
const authenticationSessionInfo: AuthenticationSessionInfo = JSON.parse(authenticationSessionValue);
if (authenticationSessionInfo
&& isString(authenticationSessionInfo.id)
&& isString(authenticationSessionInfo.accessToken)
&& isString(authenticationSessionInfo.providerId)
) {
return authenticationSessionInfo;
}
}
}
return undefined;
}
export const IAuthenticationService = createDecorator<IAuthenticationService>('IAuthenticationService');
export interface IAuthenticationService {
readonly _serviceBrand: undefined;
isAuthenticationProviderRegistered(id: string): boolean;
getProviderIds(): string[];
registerAuthenticationProvider(id: string, provider: MainThreadAuthenticationProvider): void;
unregisterAuthenticationProvider(id: string): void;
isAccessAllowed(providerId: string, accountName: string, extensionId: string): boolean | undefined;
updatedAllowedExtension(providerId: string, accountName: string, extensionId: string, extensionName: string, isAllowed: boolean): Promise<void>;
showGetSessionPrompt(providerId: string, accountName: string, extensionId: string, extensionName: string): Promise<boolean>;
selectSession(providerId: string, extensionId: string, extensionName: string, scopes: string[], possibleSessions: readonly AuthenticationSession[]): Promise<AuthenticationSession>;
requestSessionAccess(providerId: string, extensionId: string, extensionName: string, scopes: string[], possibleSessions: readonly AuthenticationSession[]): void;
completeSessionAccessRequest(providerId: string, extensionId: string, extensionName: string, scopes: string[]): Promise<void>
requestNewSession(providerId: string, scopes: string[], extensionId: string, extensionName: string): Promise<void>;
sessionsUpdate(providerId: string, event: AuthenticationSessionsChangeEvent): void;
readonly onDidRegisterAuthenticationProvider: Event<AuthenticationProviderInformation>;
readonly onDidUnregisterAuthenticationProvider: Event<AuthenticationProviderInformation>;
readonly onDidChangeSessions: Event<{ providerId: string, label: string, event: AuthenticationSessionsChangeEvent }>;
// TODO @RMacfarlane completely remove this property
declaredProviders: AuthenticationProviderInformation[];
readonly onDidChangeDeclaredProviders: Event<AuthenticationProviderInformation[]>;
getSessions(id: string, scopes?: string[], activateImmediate?: boolean): Promise<ReadonlyArray<AuthenticationSession>>;
getLabel(providerId: string): string;
supportsMultipleAccounts(providerId: string): boolean;
createSession(providerId: string, scopes: string[], activateImmediate?: boolean): Promise<AuthenticationSession>;
removeSession(providerId: string, sessionId: string): Promise<void>;
manageTrustedExtensionsForAccount(providerId: string, accountName: string): Promise<void>;
removeAccountSessions(providerId: string, accountName: string, sessions: AuthenticationSession[]): Promise<void>;
}
export interface AllowedExtension {
id: string;
name: string;
allowed?: boolean;
}
export function readAllowedExtensions(storageService: IStorageService, providerId: string, accountName: string): AllowedExtension[] {
let trustedExtensions: AllowedExtension[] = [];
try {
const trustedExtensionSrc = storageService.get(`${providerId}-${accountName}`, StorageScope.GLOBAL);
if (trustedExtensionSrc) {
trustedExtensions = JSON.parse(trustedExtensionSrc);
}
} catch (err) { }
return trustedExtensions;
}
export interface SessionRequest {
disposables: IDisposable[];
requestingExtensionIds: string[];
}
export interface SessionRequestInfo {
[scopes: string]: SessionRequest;
}
CommandsRegistry.registerCommand('workbench.getCodeExchangeProxyEndpoints', function (accessor, _) {
const environmentService = accessor.get(IWorkbenchEnvironmentService);
return environmentService.options?.codeExchangeProxyEndpoints;
});
const authenticationDefinitionSchema: IJSONSchema = {
type: 'object',
additionalProperties: false,
properties: {
id: {
type: 'string',
description: nls.localize('authentication.id', 'The id of the authentication provider.')
},
label: {
type: 'string',
description: nls.localize('authentication.label', 'The human readable name of the authentication provider.'),
}
}
};
const authenticationExtPoint = ExtensionsRegistry.registerExtensionPoint<AuthenticationProviderInformation[]>({
extensionPoint: 'authentication',
jsonSchema: {
description: nls.localize({ key: 'authenticationExtensionPoint', comment: [`'Contributes' means adds here`] }, 'Contributes authentication'),
type: 'array',
items: authenticationDefinitionSchema
}
});
export class AuthenticationService extends Disposable implements IAuthenticationService {
declare readonly _serviceBrand: undefined;
private _placeholderMenuItem: IDisposable | undefined;
private _signInRequestItems = new Map<string, SessionRequestInfo>();
private _sessionAccessRequestItems = new Map<string, { [extensionId: string]: { disposables: IDisposable[], possibleSessions: AuthenticationSession[] } }>();
private _accountBadgeDisposable = this._register(new MutableDisposable());
private _authenticationProviders: Map<string, MainThreadAuthenticationProvider> = new Map<string, MainThreadAuthenticationProvider>();
/**
* All providers that have been statically declared by extensions. These may not be registered.
*/
declaredProviders: AuthenticationProviderInformation[] = [];
private _onDidRegisterAuthenticationProvider: Emitter<AuthenticationProviderInformation> = this._register(new Emitter<AuthenticationProviderInformation>());
readonly onDidRegisterAuthenticationProvider: Event<AuthenticationProviderInformation> = this._onDidRegisterAuthenticationProvider.event;
private _onDidUnregisterAuthenticationProvider: Emitter<AuthenticationProviderInformation> = this._register(new Emitter<AuthenticationProviderInformation>());
readonly onDidUnregisterAuthenticationProvider: Event<AuthenticationProviderInformation> = this._onDidUnregisterAuthenticationProvider.event;
private _onDidChangeSessions: Emitter<{ providerId: string, label: string, event: AuthenticationSessionsChangeEvent }> = this._register(new Emitter<{ providerId: string, label: string, event: AuthenticationSessionsChangeEvent }>());
readonly onDidChangeSessions: Event<{ providerId: string, label: string, event: AuthenticationSessionsChangeEvent }> = this._onDidChangeSessions.event;
private _onDidChangeDeclaredProviders: Emitter<AuthenticationProviderInformation[]> = this._register(new Emitter<AuthenticationProviderInformation[]>());
readonly onDidChangeDeclaredProviders: Event<AuthenticationProviderInformation[]> = this._onDidChangeDeclaredProviders.event;
constructor(
@IActivityService private readonly activityService: IActivityService,
@IExtensionService private readonly extensionService: IExtensionService,
@IStorageService private readonly storageService: IStorageService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService,
@IDialogService private readonly dialogService: IDialogService,
@IQuickInputService private readonly quickInputService: IQuickInputService
) {
super();
this._placeholderMenuItem = MenuRegistry.appendMenuItem(MenuId.AccountsContext, {
command: {
id: 'noAuthenticationProviders',
title: nls.localize('loading', "Loading..."),
precondition: ContextKeyExpr.false()
},
});
authenticationExtPoint.setHandler((extensions, { added, removed }) => {
added.forEach(point => {
for (const provider of point.value) {
if (isFalsyOrWhitespace(provider.id)) {
point.collector.error(nls.localize('authentication.missingId', 'An authentication contribution must specify an id.'));
continue;
}
if (isFalsyOrWhitespace(provider.label)) {
point.collector.error(nls.localize('authentication.missingLabel', 'An authentication contribution must specify a label.'));
continue;
}
if (!this.declaredProviders.some(p => p.id === provider.id)) {
this.declaredProviders.push(provider);
} else {
point.collector.error(nls.localize('authentication.idConflict', "This authentication id '{0}' has already been registered", provider.id));
}
}
});
const removedExtPoints = flatten(removed.map(r => r.value));
removedExtPoints.forEach(point => {
const index = this.declaredProviders.findIndex(provider => provider.id === point.id);
if (index > -1) {
this.declaredProviders.splice(index, 1);
}
});
this._onDidChangeDeclaredProviders.fire(this.declaredProviders);
});
}
getProviderIds(): string[] {
const providerIds: string[] = [];
this._authenticationProviders.forEach(provider => {
providerIds.push(provider.id);
});
return providerIds;
}
isAuthenticationProviderRegistered(id: string): boolean {
return this._authenticationProviders.has(id);
}
registerAuthenticationProvider(id: string, authenticationProvider: MainThreadAuthenticationProvider): void {
this._authenticationProviders.set(id, authenticationProvider);
this._onDidRegisterAuthenticationProvider.fire({ id, label: authenticationProvider.label });
if (this._placeholderMenuItem) {
this._placeholderMenuItem.dispose();
this._placeholderMenuItem = undefined;
}
}
unregisterAuthenticationProvider(id: string): void {
const provider = this._authenticationProviders.get(id);
if (provider) {
provider.dispose();
this._authenticationProviders.delete(id);
this._onDidUnregisterAuthenticationProvider.fire({ id, label: provider.label });
const accessRequests = this._sessionAccessRequestItems.get(id) || {};
Object.keys(accessRequests).forEach(extensionId => {
this.removeAccessRequest(id, extensionId);
});
}
if (!this._authenticationProviders.size) {
this._placeholderMenuItem = MenuRegistry.appendMenuItem(MenuId.AccountsContext, {
command: {
id: 'noAuthenticationProviders',
title: nls.localize('loading', "Loading..."),
precondition: ContextKeyExpr.false()
},
});
}
}
async sessionsUpdate(id: string, event: AuthenticationSessionsChangeEvent): Promise<void> {
const provider = this._authenticationProviders.get(id);
if (provider) {
this._onDidChangeSessions.fire({ providerId: id, label: provider.label, event: event });
if (event.added) {
await this.updateNewSessionRequests(provider, event.added);
}
if (event.removed) {
await this.updateAccessRequests(id, event.removed);
}
this.updateBadgeCount();
}
}
private async updateNewSessionRequests(provider: MainThreadAuthenticationProvider, addedSessions: readonly AuthenticationSession[]): Promise<void> {
const existingRequestsForProvider = this._signInRequestItems.get(provider.id);
if (!existingRequestsForProvider) {
return;
}
Object.keys(existingRequestsForProvider).forEach(requestedScopes => {
if (addedSessions.some(session => session.scopes.slice().sort().join('') === requestedScopes)) {
const sessionRequest = existingRequestsForProvider[requestedScopes];
sessionRequest?.disposables.forEach(item => item.dispose());
delete existingRequestsForProvider[requestedScopes];
if (Object.keys(existingRequestsForProvider).length === 0) {
this._signInRequestItems.delete(provider.id);
} else {
this._signInRequestItems.set(provider.id, existingRequestsForProvider);
}
}
});
}
private async updateAccessRequests(providerId: string, removedSessions: readonly AuthenticationSession[]) {
const providerRequests = this._sessionAccessRequestItems.get(providerId);
if (providerRequests) {
Object.keys(providerRequests).forEach(extensionId => {
removedSessions.forEach(removed => {
const indexOfSession = providerRequests[extensionId].possibleSessions.findIndex(session => session.id === removed.id);
if (indexOfSession) {
providerRequests[extensionId].possibleSessions.splice(indexOfSession, 1);
}
});
if (!providerRequests[extensionId].possibleSessions.length) {
this.removeAccessRequest(providerId, extensionId);
}
});
}
}
private updateBadgeCount(): void {
this._accountBadgeDisposable.clear();
let numberOfRequests = 0;
this._signInRequestItems.forEach(providerRequests => {
Object.keys(providerRequests).forEach(request => {
numberOfRequests += providerRequests[request].requestingExtensionIds.length;
});
});
this._sessionAccessRequestItems.forEach(accessRequest => {
numberOfRequests += Object.keys(accessRequest).length;
});
if (numberOfRequests > 0) {
const badge = new NumberBadge(numberOfRequests, () => nls.localize('sign in', "Sign in requested"));
this._accountBadgeDisposable.value = this.activityService.showAccountsActivity({ badge });
}
}
private removeAccessRequest(providerId: string, extensionId: string): void {
const providerRequests = this._sessionAccessRequestItems.get(providerId) || {};
if (providerRequests[extensionId]) {
providerRequests[extensionId].disposables.forEach(d => d.dispose());
delete providerRequests[extensionId];
this.updateBadgeCount();
}
}
/**
* Check extension access to an account
* @param providerId The id of the authentication provider
* @param accountName The account name that access is checked for
* @param extensionId The id of the extension requesting access
* @returns Returns true or false if the user has opted to permanently grant or disallow access, and undefined
* if they haven't made a choice yet
*/
isAccessAllowed(providerId: string, accountName: string, extensionId: string): boolean | undefined {
const allowList = readAllowedExtensions(this.storageService, providerId, accountName);
const extensionData = allowList.find(extension => extension.id === extensionId);
if (extensionData) {
// This property didn't exist on this data previously, inclusion in the list at all indicates allowance
return extensionData.allowed !== undefined
? extensionData.allowed
: true;
}
const remoteConnection = this.remoteAgentService.getConnection();
const isVSO = remoteConnection !== null
? remoteConnection.remoteAuthority.startsWith('vsonline') || remoteConnection.remoteAuthority.startsWith('codespaces')
: isWeb;
if (isVSO && VSO_ALLOWED_EXTENSIONS.includes(extensionId)) {
return true;
}
return undefined;
}
async updatedAllowedExtension(providerId: string, accountName: string, extensionId: string, extensionName: string, isAllowed: boolean): Promise<void> {
const allowList = readAllowedExtensions(this.storageService, providerId, accountName);
const index = allowList.findIndex(extension => extension.id === extensionId);
if (index === -1) {
allowList.push({ id: extensionId, name: extensionName, allowed: isAllowed });
} else {
allowList[index].allowed = isAllowed;
}
await this.storageService.store(`${providerId}-${accountName}`, JSON.stringify(allowList), StorageScope.GLOBAL, StorageTarget.USER);
}
async showGetSessionPrompt(providerId: string, accountName: string, extensionId: string, extensionName: string): Promise<boolean> {
const providerName = this.getLabel(providerId);
const { choice } = await this.dialogService.show(
Severity.Info,
nls.localize('confirmAuthenticationAccess', "The extension '{0}' wants to access the {1} account '{2}'.", extensionName, providerName, accountName),
[nls.localize('allow', "Allow"), nls.localize('deny', "Deny"), nls.localize('cancel', "Cancel")],
{
cancelId: 2
}
);
const cancelled = choice === 2;
const allowed = choice === 0;
if (!cancelled) {
this.updatedAllowedExtension(providerId, accountName, extensionId, extensionName, allowed);
this.removeAccessRequest(providerId, extensionId);
}
return allowed;
}
async selectSession(providerId: string, extensionId: string, extensionName: string, scopes: string[], availableSessions: AuthenticationSession[]): Promise<AuthenticationSession> {
return new Promise((resolve, reject) => {
// This function should be used only when there are sessions to disambiguate.
if (!availableSessions.length) {
reject('No available sessions');
}
const quickPick = this.quickInputService.createQuickPick<{ label: string, session?: AuthenticationSession }>();
quickPick.ignoreFocusOut = true;
const items: { label: string, session?: AuthenticationSession }[] = availableSessions.map(session => {
return {
label: session.account.label,
session: session
};
});
items.push({
label: nls.localize('useOtherAccount', "Sign in to another account")
});
const providerName = this.getLabel(providerId);
quickPick.items = items;
quickPick.title = nls.localize(
{
key: 'selectAccount',
comment: ['The placeholder {0} is the name of an extension. {1} is the name of the type of account, such as Microsoft or GitHub.']
},
"The extension '{0}' wants to access a {1} account",
extensionName,
providerName);
quickPick.placeholder = nls.localize('getSessionPlateholder', "Select an account for '{0}' to use or Esc to cancel", extensionName);
quickPick.onDidAccept(async _ => {
const session = quickPick.selectedItems[0].session ?? await this.createSession(providerId, scopes);
const accountName = session.account.label;
this.updatedAllowedExtension(providerId, accountName, extensionId, extensionName, true);
this.removeAccessRequest(providerId, extensionId);
this.storageService.store(`${extensionName}-${providerId}`, session.id, StorageScope.GLOBAL, StorageTarget.MACHINE);
quickPick.dispose();
resolve(session);
});
quickPick.onDidHide(_ => {
if (!quickPick.selectedItems[0]) {
reject('User did not consent to account access');
}
quickPick.dispose();
});
quickPick.show();
});
}
async completeSessionAccessRequest(providerId: string, extensionId: string, extensionName: string, scopes: string[]): Promise<void> {
const providerRequests = this._sessionAccessRequestItems.get(providerId) || {};
const existingRequest = providerRequests[extensionId];
if (!existingRequest) {
return;
}
const possibleSessions = existingRequest.possibleSessions;
const supportsMultipleAccounts = this.supportsMultipleAccounts(providerId);
let session: AuthenticationSession | undefined;
if (supportsMultipleAccounts) {
try {
session = await this.selectSession(providerId, extensionId, extensionName, scopes, possibleSessions);
} catch (_) {
// ignore cancel
}
} else {
const approved = await this.showGetSessionPrompt(providerId, possibleSessions[0].account.label, extensionId, extensionName);
if (approved) {
session = possibleSessions[0];
}
}
if (session) {
addAccountUsage(this.storageService, providerId, session.account.label, extensionId, extensionName);
const providerName = this.getLabel(providerId);
this._onDidChangeSessions.fire({ providerId, label: providerName, event: { added: [], removed: [], changed: [session] } });
}
}
requestSessionAccess(providerId: string, extensionId: string, extensionName: string, scopes: string[], possibleSessions: AuthenticationSession[]): void {
const providerRequests = this._sessionAccessRequestItems.get(providerId) || {};
const hasExistingRequest = providerRequests[extensionId];
if (hasExistingRequest) {
return;
}
const menuItem = MenuRegistry.appendMenuItem(MenuId.AccountsContext, {
group: '3_accessRequests',
command: {
id: `${providerId}${extensionId}Access`,
title: nls.localize({
key: 'accessRequest',
comment: ['The placeholder {0} will be replaced with an extension name. (1) is to indicate that this menu item contributes to a badge count']
},
"Grant access to {0}... (1)", extensionName)
}
});
const accessCommand = CommandsRegistry.registerCommand({
id: `${providerId}${extensionId}Access`,
handler: async (accessor) => {
const authenticationService = accessor.get(IAuthenticationService);
authenticationService.completeSessionAccessRequest(providerId, extensionId, extensionName, scopes);
}
});
providerRequests[extensionId] = { possibleSessions, disposables: [menuItem, accessCommand] };
this._sessionAccessRequestItems.set(providerId, providerRequests);
this.updateBadgeCount();
}
async requestNewSession(providerId: string, scopes: string[], extensionId: string, extensionName: string): Promise<void> {
let provider = this._authenticationProviders.get(providerId);
if (!provider) {
// Activate has already been called for the authentication provider, but it cannot block on registering itself
// since this is sync and returns a disposable. So, wait for registration event to fire that indicates the
// provider is now in the map.
await new Promise<void>((resolve, _) => {
this.onDidRegisterAuthenticationProvider(e => {
if (e.id === providerId) {
provider = this._authenticationProviders.get(providerId);
resolve();
}
});
});
}
if (provider) {
const providerRequests = this._signInRequestItems.get(providerId);
const scopesList = scopes.sort().join('');
const extensionHasExistingRequest = providerRequests
&& providerRequests[scopesList]
&& providerRequests[scopesList].requestingExtensionIds.includes(extensionId);
if (extensionHasExistingRequest) {
return;
}
const menuItem = MenuRegistry.appendMenuItem(MenuId.AccountsContext, {
group: '2_signInRequests',
command: {
id: `${extensionId}signIn`,
title: nls.localize(
{
key: 'signInRequest',
comment: ['The placeholder {0} will be replaced with an extension name. (1) is to indicate that this menu item contributes to a badge count.']
},
"Sign in to use {0} (1)",
extensionName)
}
});
const signInCommand = CommandsRegistry.registerCommand({
id: `${extensionId}signIn`,
handler: async (accessor) => {
const authenticationService = accessor.get(IAuthenticationService);
const storageService = accessor.get(IStorageService);
const session = await authenticationService.createSession(providerId, scopes);
// Add extension to allow list since user explicitly signed in on behalf of it
this.updatedAllowedExtension(providerId, session.account.label, extensionId, extensionName, true);
// And also set it as the preferred account for the extension
storageService.store(`${extensionName}-${providerId}`, session.id, StorageScope.GLOBAL, StorageTarget.MACHINE);
}
});
if (providerRequests) {
const existingRequest = providerRequests[scopesList] || { disposables: [], requestingExtensionIds: [] };
providerRequests[scopesList] = {
disposables: [...existingRequest.disposables, menuItem, signInCommand],
requestingExtensionIds: [...existingRequest.requestingExtensionIds, extensionId]
};
this._signInRequestItems.set(providerId, providerRequests);
} else {
this._signInRequestItems.set(providerId, {
[scopesList]: {
disposables: [menuItem, signInCommand],
requestingExtensionIds: [extensionId]
}
});
}
this.updateBadgeCount();
}
}
getLabel(id: string): string {
const authProvider = this._authenticationProviders.get(id);
if (authProvider) {
return authProvider.label;
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
supportsMultipleAccounts(id: string): boolean {
const authProvider = this._authenticationProviders.get(id);
if (authProvider) {
return authProvider.supportsMultipleAccounts;
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
private async tryActivateProvider(providerId: string, activateImmediate: boolean): Promise<MainThreadAuthenticationProvider> {
await this.extensionService.activateByEvent(getAuthenticationProviderActivationEvent(providerId), activateImmediate ? ActivationKind.Immediate : ActivationKind.Normal);
let provider = this._authenticationProviders.get(providerId);
if (provider) {
return provider;
}
// When activate has completed, the extension has made the call to `registerAuthenticationProvider`.
// However, activate cannot block on this, so the renderer may not have gotten the event yet.
const didRegister: Promise<MainThreadAuthenticationProvider> = new Promise((resolve, _) => {
this.onDidRegisterAuthenticationProvider(e => {
if (e.id === providerId) {
provider = this._authenticationProviders.get(providerId);
if (provider) {
resolve(provider);
} else {
throw new Error(`No authentication provider '${providerId}' is currently registered.`);
}
}
});
});
const didTimeout: Promise<MainThreadAuthenticationProvider> = new Promise((_, reject) => {
setTimeout(() => {
reject();
}, 5000);
});
return Promise.race([didRegister, didTimeout]);
}
async getSessions(id: string, scopes?: string[], activateImmediate: boolean = false): Promise<ReadonlyArray<AuthenticationSession>> {
try {
const authProvider = this._authenticationProviders.get(id) || await this.tryActivateProvider(id, activateImmediate);
return await authProvider.getSessions(scopes);
} catch (_) {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
async createSession(id: string, scopes: string[], activateImmediate: boolean = false): Promise<AuthenticationSession> {
try {
const authProvider = this._authenticationProviders.get(id) || await this.tryActivateProvider(id, activateImmediate);
return await authProvider.createSession(scopes);
} catch (_) {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
async removeSession(id: string, sessionId: string): Promise<void> {
const authProvider = this._authenticationProviders.get(id);
if (authProvider) {
return authProvider.removeSession(sessionId);
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
async manageTrustedExtensionsForAccount(id: string, accountName: string): Promise<void> {
const authProvider = this._authenticationProviders.get(id);
if (authProvider) {
return authProvider.manageTrustedExtensions(accountName);
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
async removeAccountSessions(id: string, accountName: string, sessions: AuthenticationSession[]): Promise<void> {
const authProvider = this._authenticationProviders.get(id);
if (authProvider) {
return authProvider.removeAccountSessions(accountName, sessions);
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
}
registerSingleton(IAuthenticationService, AuthenticationService);
| src/vs/workbench/services/authentication/browser/authenticationService.ts | 0 | https://github.com/microsoft/vscode/commit/c074bf897c0c3cd6ba5705828402924a3cc2b4dc | [
0.0007984901894815266,
0.00018863989680539817,
0.00016534063615836203,
0.0001734142133500427,
0.00008983727457234636
] |
{
"id": 2,
"code_window": [
"\t\treadonly onDidReceiveMessage: Event<{ editor: NotebookEditor, message: any }>;\n",
"\t\tpostMessage(message: any, editor?: NotebookEditor): Thenable<boolean>;\n",
"\t\tasWebviewUri(localResource: Uri, editor: NotebookEditor): Uri;\n",
"\t}\n",
"\n",
"\texport interface NotebookControllerOptions {\n",
"\t\tid: string;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tasWebviewUri(localResource: Uri): Uri;\n"
],
"file_path": "src/vs/vscode.proposed.d.ts",
"type": "replace",
"edit_start_line_idx": 1027
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { URI } from 'vs/base/common/uri';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { EditorPart } from 'vs/workbench/browser/parts/editor/editorPart';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { EditorService } from 'vs/workbench/services/editor/browser/editorService';
import { IUntitledTextResourceEditorInput } from 'vs/workbench/common/editor';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
import { toResource } from 'vs/base/test/common/utils';
import { IFilesConfigurationService } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService';
import { IWorkingCopyBackup, IWorkingCopyService } from 'vs/workbench/services/workingCopy/common/workingCopyService';
import { ILogService } from 'vs/platform/log/common/log';
import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { BackupTracker } from 'vs/workbench/services/backup/common/backupTracker';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { UntitledTextEditorInput } from 'vs/workbench/services/untitled/common/untitledTextEditorInput';
import { createEditorPart, InMemoryTestBackupFileService, registerTestResourceEditor, TestServiceAccessor, workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices';
import { TestWorkingCopy } from 'vs/workbench/test/common/workbenchTestServices';
import { CancellationToken } from 'vs/base/common/cancellation';
import { timeout } from 'vs/base/common/async';
import { BrowserBackupTracker } from 'vs/workbench/services/backup/browser/backupTracker';
import { DisposableStore } from 'vs/base/common/lifecycle';
suite('BackupTracker (browser)', function () {
let accessor: TestServiceAccessor;
class TestBackupTracker extends BrowserBackupTracker {
constructor(
@IBackupFileService backupFileService: IBackupFileService,
@IFilesConfigurationService filesConfigurationService: IFilesConfigurationService,
@IWorkingCopyService workingCopyService: IWorkingCopyService,
@ILifecycleService lifecycleService: ILifecycleService,
@ILogService logService: ILogService,
) {
super(backupFileService, filesConfigurationService, workingCopyService, lifecycleService, logService);
}
protected override getBackupScheduleDelay(): number {
return 10; // Reduce timeout for tests
}
}
async function createTracker(): Promise<{ accessor: TestServiceAccessor, part: EditorPart, tracker: BackupTracker, backupFileService: InMemoryTestBackupFileService, instantiationService: IInstantiationService, cleanup: () => void }> {
const disposables = new DisposableStore();
const backupFileService = new InMemoryTestBackupFileService();
const instantiationService = workbenchInstantiationService();
instantiationService.stub(IBackupFileService, backupFileService);
const part = await createEditorPart(instantiationService, disposables);
disposables.add(registerTestResourceEditor());
instantiationService.stub(IEditorGroupsService, part);
const editorService: EditorService = instantiationService.createInstance(EditorService);
instantiationService.stub(IEditorService, editorService);
accessor = instantiationService.createInstance(TestServiceAccessor);
const tracker = disposables.add(instantiationService.createInstance(TestBackupTracker));
return { accessor, part, tracker, backupFileService, instantiationService, cleanup: () => disposables.dispose() };
}
async function untitledBackupTest(untitled: IUntitledTextResourceEditorInput = {}): Promise<void> {
const { accessor, cleanup, backupFileService } = await createTracker();
const untitledEditor = (await accessor.editorService.openEditor(untitled))?.input as UntitledTextEditorInput;
const untitledModel = await untitledEditor.resolve();
if (!untitled?.contents) {
untitledModel.textEditorModel?.setValue('Super Good');
}
await backupFileService.joinBackupResource();
assert.strictEqual(backupFileService.hasBackupSync(untitledEditor.resource), true);
untitledModel.dispose();
await backupFileService.joinDiscardBackup();
assert.strictEqual(backupFileService.hasBackupSync(untitledEditor.resource), false);
cleanup();
}
test('Track backups (untitled)', function () {
return untitledBackupTest();
});
test('Track backups (untitled with initial contents)', function () {
return untitledBackupTest({ contents: 'Foo Bar' });
});
test('Track backups (custom)', async function () {
const { accessor, cleanup, backupFileService } = await createTracker();
class TestBackupWorkingCopy extends TestWorkingCopy {
backupDelay = 0;
constructor(resource: URI) {
super(resource);
accessor.workingCopyService.registerWorkingCopy(this);
}
async override backup(token: CancellationToken): Promise<IWorkingCopyBackup> {
await timeout(this.backupDelay);
return {};
}
}
const resource = toResource.call(this, '/path/custom.txt');
const customWorkingCopy = new TestBackupWorkingCopy(resource);
// Normal
customWorkingCopy.setDirty(true);
await backupFileService.joinBackupResource();
assert.strictEqual(backupFileService.hasBackupSync(resource), true);
customWorkingCopy.setDirty(false);
customWorkingCopy.setDirty(true);
await backupFileService.joinBackupResource();
assert.strictEqual(backupFileService.hasBackupSync(resource), true);
customWorkingCopy.setDirty(false);
await backupFileService.joinDiscardBackup();
assert.strictEqual(backupFileService.hasBackupSync(resource), false);
// Cancellation
customWorkingCopy.setDirty(true);
await timeout(0);
customWorkingCopy.setDirty(false);
await backupFileService.joinDiscardBackup();
assert.strictEqual(backupFileService.hasBackupSync(resource), false);
customWorkingCopy.dispose();
cleanup();
});
});
| src/vs/workbench/services/backup/test/browser/backupTracker.test.ts | 0 | https://github.com/microsoft/vscode/commit/c074bf897c0c3cd6ba5705828402924a3cc2b4dc | [
0.0001801119651645422,
0.00017508328892290592,
0.00017030509479809552,
0.000175026390934363,
0.000002476177769494825
] |
{
"id": 2,
"code_window": [
"\t\treadonly onDidReceiveMessage: Event<{ editor: NotebookEditor, message: any }>;\n",
"\t\tpostMessage(message: any, editor?: NotebookEditor): Thenable<boolean>;\n",
"\t\tasWebviewUri(localResource: Uri, editor: NotebookEditor): Uri;\n",
"\t}\n",
"\n",
"\texport interface NotebookControllerOptions {\n",
"\t\tid: string;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tasWebviewUri(localResource: Uri): Uri;\n"
],
"file_path": "src/vs/vscode.proposed.d.ts",
"type": "replace",
"edit_start_line_idx": 1027
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as browser from 'vs/base/browser/browser';
import { IframeUtils } from 'vs/base/browser/iframe';
import * as platform from 'vs/base/common/platform';
export interface IMouseEvent {
readonly browserEvent: MouseEvent;
readonly leftButton: boolean;
readonly middleButton: boolean;
readonly rightButton: boolean;
readonly buttons: number;
readonly target: HTMLElement;
readonly detail: number;
readonly posx: number;
readonly posy: number;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly timestamp: number;
preventDefault(): void;
stopPropagation(): void;
}
export class StandardMouseEvent implements IMouseEvent {
public readonly browserEvent: MouseEvent;
public readonly leftButton: boolean;
public readonly middleButton: boolean;
public readonly rightButton: boolean;
public readonly buttons: number;
public readonly target: HTMLElement;
public detail: number;
public readonly posx: number;
public readonly posy: number;
public readonly ctrlKey: boolean;
public readonly shiftKey: boolean;
public readonly altKey: boolean;
public readonly metaKey: boolean;
public readonly timestamp: number;
constructor(e: MouseEvent) {
this.timestamp = Date.now();
this.browserEvent = e;
this.leftButton = e.button === 0;
this.middleButton = e.button === 1;
this.rightButton = e.button === 2;
this.buttons = e.buttons;
this.target = <HTMLElement>e.target;
this.detail = e.detail || 1;
if (e.type === 'dblclick') {
this.detail = 2;
}
this.ctrlKey = e.ctrlKey;
this.shiftKey = e.shiftKey;
this.altKey = e.altKey;
this.metaKey = e.metaKey;
if (typeof e.pageX === 'number') {
this.posx = e.pageX;
this.posy = e.pageY;
} else {
// Probably hit by MSGestureEvent
this.posx = e.clientX + document.body.scrollLeft + document.documentElement!.scrollLeft;
this.posy = e.clientY + document.body.scrollTop + document.documentElement!.scrollTop;
}
// Find the position of the iframe this code is executing in relative to the iframe where the event was captured.
let iframeOffsets = IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(self, e.view);
this.posx -= iframeOffsets.left;
this.posy -= iframeOffsets.top;
}
public preventDefault(): void {
this.browserEvent.preventDefault();
}
public stopPropagation(): void {
this.browserEvent.stopPropagation();
}
}
export interface IDataTransfer {
dropEffect: string;
effectAllowed: string;
types: any[];
files: any[];
setData(type: string, data: string): void;
setDragImage(image: any, x: number, y: number): void;
getData(type: string): string;
clearData(types?: string[]): void;
}
export class DragMouseEvent extends StandardMouseEvent {
public readonly dataTransfer: IDataTransfer;
constructor(e: MouseEvent) {
super(e);
this.dataTransfer = (<any>e).dataTransfer;
}
}
export interface IMouseWheelEvent extends MouseEvent {
readonly wheelDelta: number;
readonly wheelDeltaX: number;
readonly wheelDeltaY: number;
readonly deltaX: number;
readonly deltaY: number;
readonly deltaZ: number;
readonly deltaMode: number;
}
interface IWebKitMouseWheelEvent {
wheelDeltaY: number;
wheelDeltaX: number;
}
interface IGeckoMouseWheelEvent {
HORIZONTAL_AXIS: number;
VERTICAL_AXIS: number;
axis: number;
detail: number;
}
export class StandardWheelEvent {
public readonly browserEvent: IMouseWheelEvent | null;
public readonly deltaY: number;
public readonly deltaX: number;
public readonly target: Node;
constructor(e: IMouseWheelEvent | null, deltaX: number = 0, deltaY: number = 0) {
this.browserEvent = e || null;
this.target = e ? (e.target || (<any>e).targetNode || e.srcElement) : null;
this.deltaY = deltaY;
this.deltaX = deltaX;
if (e) {
// Old (deprecated) wheel events
let e1 = <IWebKitMouseWheelEvent><any>e;
let e2 = <IGeckoMouseWheelEvent><any>e;
// vertical delta scroll
if (typeof e1.wheelDeltaY !== 'undefined') {
this.deltaY = e1.wheelDeltaY / 120;
} else if (typeof e2.VERTICAL_AXIS !== 'undefined' && e2.axis === e2.VERTICAL_AXIS) {
this.deltaY = -e2.detail / 3;
} else if (e.type === 'wheel') {
// Modern wheel event
// https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent
const ev = <WheelEvent><unknown>e;
if (ev.deltaMode === ev.DOM_DELTA_LINE) {
// the deltas are expressed in lines
if (browser.isFirefox && !platform.isMacintosh) {
this.deltaY = -e.deltaY / 3;
} else {
this.deltaY = -e.deltaY;
}
} else {
this.deltaY = -e.deltaY / 40;
}
}
// horizontal delta scroll
if (typeof e1.wheelDeltaX !== 'undefined') {
if (browser.isSafari && platform.isWindows) {
this.deltaX = - (e1.wheelDeltaX / 120);
} else {
this.deltaX = e1.wheelDeltaX / 120;
}
} else if (typeof e2.HORIZONTAL_AXIS !== 'undefined' && e2.axis === e2.HORIZONTAL_AXIS) {
this.deltaX = -e.detail / 3;
} else if (e.type === 'wheel') {
// Modern wheel event
// https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent
const ev = <WheelEvent><unknown>e;
if (ev.deltaMode === ev.DOM_DELTA_LINE) {
// the deltas are expressed in lines
if (browser.isFirefox && !platform.isMacintosh) {
this.deltaX = -e.deltaX / 3;
} else {
this.deltaX = -e.deltaX;
}
} else {
this.deltaX = -e.deltaX / 40;
}
}
// Assume a vertical scroll if nothing else worked
if (this.deltaY === 0 && this.deltaX === 0 && e.wheelDelta) {
this.deltaY = e.wheelDelta / 120;
}
}
}
public preventDefault(): void {
if (this.browserEvent) {
this.browserEvent.preventDefault();
}
}
public stopPropagation(): void {
if (this.browserEvent) {
this.browserEvent.stopPropagation();
}
}
}
| src/vs/base/browser/mouseEvent.ts | 0 | https://github.com/microsoft/vscode/commit/c074bf897c0c3cd6ba5705828402924a3cc2b4dc | [
0.0001779360609361902,
0.00017250094970222563,
0.00016330408107023686,
0.00017414237663615495,
0.000003842790192720713
] |
{
"id": 3,
"code_window": [
"\t\thasExecutionOrder?: boolean;\n",
"\t\texecuteHandler: (cells: NotebookCell[], controller: NotebookController) => void;\n",
"\t\tinterruptHandler?: (notebook: NotebookDocument) => void\n",
"\t}\n",
"\n",
"\texport namespace notebook {\n",
"\t\texport function createNotebookController(options: NotebookControllerOptions): NotebookController;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tpreloads?: NotebookKernelPreload[]\n"
],
"file_path": "src/vs/vscode.proposed.d.ts",
"type": "add",
"edit_start_line_idx": 1039
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { ExtHostNotebookKernelsShape, IMainContext, INotebookKernelDto2, MainContext, MainThreadNotebookKernelsShape } from 'vs/workbench/api/common/extHost.protocol';
import * as vscode from 'vscode';
import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { URI, UriComponents } from 'vs/base/common/uri';
import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import * as extHostTypeConverters from 'vs/workbench/api/common/extHostTypeConverters';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { asWebviewUri } from 'vs/workbench/api/common/shared/webview';
type ExecuteHandler = (cells: vscode.NotebookCell[], controller: vscode.NotebookController) => void;
type InterruptHandler = (notebook: vscode.NotebookDocument) => void;
interface IKernelData {
controller: vscode.NotebookController;
onDidChangeSelection: Emitter<{ selected: boolean; notebook: vscode.NotebookDocument; }>;
onDidReceiveMessage: Emitter<{ editor: vscode.NotebookEditor, message: any }>;
}
export class ExtHostNotebookKernels implements ExtHostNotebookKernelsShape {
private readonly _proxy: MainThreadNotebookKernelsShape;
private readonly _kernelData = new Map<number, IKernelData>();
private _handlePool: number = 0;
constructor(
mainContext: IMainContext,
private readonly _initData: IExtHostInitDataService,
private readonly _extHostNotebook: ExtHostNotebookController
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadNotebookKernels);
}
createKernel(extension: IExtensionDescription, options: vscode.NotebookControllerOptions): vscode.NotebookController {
const handle = this._handlePool++;
const that = this;
let isDisposed = false;
const commandDisposables = new DisposableStore();
const onDidChangeSelection = new Emitter<{ selected: boolean, notebook: vscode.NotebookDocument }>();
const onDidReceiveMessage = new Emitter<{ editor: vscode.NotebookEditor, message: any }>();
const data: INotebookKernelDto2 = {
id: options.id,
selector: options.selector,
extensionId: extension.identifier,
extensionLocation: extension.extensionLocation,
label: options.label,
supportedLanguages: [],
};
//
let _executeHandler: ExecuteHandler = options.executeHandler;
let _interruptHandler: InterruptHandler | undefined = options.interruptHandler;
// todo@jrieken the selector needs to be massaged
this._proxy.$addKernel(handle, data);
// update: all setters write directly into the dto object
// and trigger an update. the actual update will only happen
// once per event loop execution
let tokenPool = 0;
const _update = () => {
if (isDisposed) {
return;
}
const myToken = ++tokenPool;
Promise.resolve().then(() => {
if (myToken === tokenPool) {
this._proxy.$updateKernel(handle, data);
}
});
};
const controller: vscode.NotebookController = {
get id() { return data.id; },
get selector() { return data.selector; },
onDidChangeNotebookAssociation: onDidChangeSelection.event,
get label() {
return data.label;
},
set label(value) {
data.label = value;
_update();
},
get description() {
return data.description ?? '';
},
set description(value) {
data.description = value;
_update();
},
get isPreferred() {
return data.isPreferred ?? false;
},
set isPreferred(value) {
data.isPreferred = value;
_update();
},
get supportedLanguages() {
return data.supportedLanguages;
},
set supportedLanguages(value) {
data.supportedLanguages = isNonEmptyArray(value) ? value : ['plaintext'];
_update();
},
get hasExecutionOrder() {
return data.hasExecutionOrder ?? false;
},
set hasExecutionOrder(value) {
data.hasExecutionOrder = value;
_update();
},
get preloads() {
return data.preloads && data.preloads.map(extHostTypeConverters.NotebookKernelPreload.to);
},
set preloads(value) {
data.preloads = value && value.map(extHostTypeConverters.NotebookKernelPreload.from);
_update();
},
get executeHandler() {
return _executeHandler;
},
get interruptHandler() {
return _interruptHandler;
},
set interruptHandler(value) {
_interruptHandler = value;
data.supportsInterrupt = Boolean(value);
_update();
},
createNotebookCellExecutionTask(cell) {
if (isDisposed) {
throw new Error('notebook controller is DISPOSED');
}
//todo@jrieken
return that._extHostNotebook.createNotebookCellExecution(cell.notebook.uri, cell.index, data.id)!;
},
dispose: () => {
if (!isDisposed) {
isDisposed = true;
this._kernelData.delete(handle);
commandDisposables.dispose();
onDidChangeSelection.dispose();
onDidReceiveMessage.dispose();
this._proxy.$removeKernel(handle);
}
},
// --- ipc
onDidReceiveMessage: onDidReceiveMessage.event,
postMessage(message, editor) {
return that._proxy.$postMessage(handle, editor && that._extHostNotebook.getIdByEditor(editor), message);
},
asWebviewUri(uri: URI, editor) {
return asWebviewUri(that._initData.environment, that._extHostNotebook.getIdByEditor(editor)!, uri);
}
};
this._kernelData.set(handle, { controller, onDidChangeSelection, onDidReceiveMessage });
controller.supportedLanguages = options.supportedLanguages ?? [];
controller.interruptHandler = options.interruptHandler;
controller.hasExecutionOrder = options.hasExecutionOrder ?? false;
return controller;
}
$acceptSelection(handle: number, uri: UriComponents, value: boolean): void {
const obj = this._kernelData.get(handle);
if (obj) {
obj.onDidChangeSelection.fire({
selected: value,
notebook: this._extHostNotebook.lookupNotebookDocument(URI.revive(uri))!.notebookDocument
});
}
}
$executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void {
const obj = this._kernelData.get(handle);
if (!obj) {
// extension can dispose kernels in the meantime
return;
}
const document = this._extHostNotebook.lookupNotebookDocument(URI.revive(uri));
if (!document) {
throw new Error('MISSING notebook');
}
const cells: vscode.NotebookCell[] = [];
for (let range of ranges) {
cells.push(...document.notebookDocument.getCells(extHostTypeConverters.NotebookRange.to(range)));
}
try {
obj.controller.executeHandler(cells, obj.controller);
} catch (err) {
//
console.error(err);
}
}
$cancelCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void {
const obj = this._kernelData.get(handle);
if (!obj) {
// extension can dispose kernels in the meantime
return;
}
const document = this._extHostNotebook.lookupNotebookDocument(URI.revive(uri));
if (!document) {
throw new Error('MISSING notebook');
}
if (obj.controller.interruptHandler) {
obj.controller.interruptHandler(document.notebookDocument);
}
// we do both? interrupt and cancellation or should we be selective?
for (const range of ranges) {
for (let i = range.start; i < range.end; i++) {
const cell = document.getCellFromIndex(i);
if (cell) {
this._extHostNotebook.cancelOneNotebookCellExecution(cell);
}
}
}
}
$acceptRendererMessage(handle: number, editorId: string, message: any): void {
const obj = this._kernelData.get(handle);
if (!obj) {
// extension can dispose kernels in the meantime
return;
}
const editor = this._extHostNotebook.getEditorById(editorId);
if (!editor) {
throw new Error(`send message for UNKNOWN editor: ${editorId}`);
}
obj.onDidReceiveMessage.fire(Object.freeze({ editor: editor.apiEditor, message }));
}
}
| src/vs/workbench/api/common/extHostNotebookKernels.ts | 1 | https://github.com/microsoft/vscode/commit/c074bf897c0c3cd6ba5705828402924a3cc2b4dc | [
0.4377700686454773,
0.034352291375398636,
0.00016629212768748403,
0.0006695388583466411,
0.09665052592754364
] |
{
"id": 3,
"code_window": [
"\t\thasExecutionOrder?: boolean;\n",
"\t\texecuteHandler: (cells: NotebookCell[], controller: NotebookController) => void;\n",
"\t\tinterruptHandler?: (notebook: NotebookDocument) => void\n",
"\t}\n",
"\n",
"\texport namespace notebook {\n",
"\t\texport function createNotebookController(options: NotebookControllerOptions): NotebookController;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tpreloads?: NotebookKernelPreload[]\n"
],
"file_path": "src/vs/vscode.proposed.d.ts",
"type": "add",
"edit_start_line_idx": 1039
} | name: Locker
on:
schedule:
- cron: 20 23 * * * # 4:20pm Redmond
repository_dispatch:
types: [trigger-locker]
jobs:
main:
runs-on: ubuntu-latest
steps:
- name: Checkout Actions
uses: actions/checkout@v2
with:
repository: "microsoft/vscode-github-triage-actions"
path: ./actions
ref: stable
- name: Install Actions
run: npm install --production --prefix ./actions
- name: Run Locker
uses: ./actions/locker
with:
daysSinceClose: 45
appInsightsKey: ${{secrets.TRIAGE_ACTIONS_APP_INSIGHTS}}
daysSinceUpdate: 3
ignoredLabel: "*out-of-scope"
ignoreLabelUntil: "author-verification-requested"
labelUntil: "verified"
| .github/workflows/locker.yml | 0 | https://github.com/microsoft/vscode/commit/c074bf897c0c3cd6ba5705828402924a3cc2b4dc | [
0.00017711916007101536,
0.00017604981258045882,
0.00017483333067502826,
0.0001761969324434176,
9.3896687758388e-7
] |
{
"id": 3,
"code_window": [
"\t\thasExecutionOrder?: boolean;\n",
"\t\texecuteHandler: (cells: NotebookCell[], controller: NotebookController) => void;\n",
"\t\tinterruptHandler?: (notebook: NotebookDocument) => void\n",
"\t}\n",
"\n",
"\texport namespace notebook {\n",
"\t\texport function createNotebookController(options: NotebookControllerOptions): NotebookController;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tpreloads?: NotebookKernelPreload[]\n"
],
"file_path": "src/vs/vscode.proposed.d.ts",
"type": "add",
"edit_start_line_idx": 1039
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ | extensions/css-language-features/server/test/pathCompletionFixtures/scss/main.scss | 0 | https://github.com/microsoft/vscode/commit/c074bf897c0c3cd6ba5705828402924a3cc2b4dc | [
0.00017961701087187976,
0.00017961701087187976,
0.00017961701087187976,
0.00017961701087187976,
0
] |
{
"id": 3,
"code_window": [
"\t\thasExecutionOrder?: boolean;\n",
"\t\texecuteHandler: (cells: NotebookCell[], controller: NotebookController) => void;\n",
"\t\tinterruptHandler?: (notebook: NotebookDocument) => void\n",
"\t}\n",
"\n",
"\texport namespace notebook {\n",
"\t\texport function createNotebookController(options: NotebookControllerOptions): NotebookController;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tpreloads?: NotebookKernelPreload[]\n"
],
"file_path": "src/vs/vscode.proposed.d.ts",
"type": "add",
"edit_start_line_idx": 1039
} | /*---------------------------------------------------------------------------------------------
* 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 * as UUID from 'vs/base/common/uuid';
import * as editorCommon from 'vs/editor/common/editorCommon';
import * as nls from 'vs/nls';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { BOTTOM_CELL_TOOLBAR_GAP, BOTTOM_CELL_TOOLBAR_HEIGHT, CELL_MARGIN, CODE_CELL_LEFT_MARGIN, COLLAPSED_INDICATOR_HEIGHT, MARKDOWN_CELL_BOTTOM_MARGIN, MARKDOWN_CELL_TOP_MARGIN } from 'vs/workbench/contrib/notebook/browser/constants';
import { EditorFoldingStateDelegate } from 'vs/workbench/contrib/notebook/browser/contrib/fold/foldingModel';
import { CellEditState, CellFindMatch, ICellOutputViewModel, ICellViewModel, MarkdownCellLayoutChangeEvent, MarkdownCellLayoutInfo, NotebookLayoutInfo } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { MarkdownRenderer } from 'vs/editor/browser/core/markdownRenderer';
import { BaseCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/baseCellViewModel';
import { NotebookCellStateChangedEvent, NotebookEventDispatcher } from 'vs/workbench/contrib/notebook/browser/viewModel/eventDispatcher';
import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel';
import { CellKind, INotebookSearchOptions } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
export class MarkdownCellViewModel extends BaseCellViewModel implements ICellViewModel {
readonly cellKind = CellKind.Markdown;
private _html: HTMLElement | null = null;
private _layoutInfo: MarkdownCellLayoutInfo;
get layoutInfo() {
return this._layoutInfo;
}
set renderedMarkdownHeight(newHeight: number) {
if (this.editState === CellEditState.Preview) {
const newTotalHeight = newHeight + BOTTOM_CELL_TOOLBAR_GAP;
this.totalHeight = newTotalHeight;
}
}
private set totalHeight(newHeight: number) {
if (newHeight !== this.layoutInfo.totalHeight) {
this.layoutChange({ totalHeight: newHeight });
}
}
private get totalHeight() {
throw new Error('MarkdownCellViewModel.totalHeight is write only');
}
private _editorHeight = 0;
set editorHeight(newHeight: number) {
this._editorHeight = newHeight;
this.totalHeight = this._editorHeight + MARKDOWN_CELL_TOP_MARGIN + MARKDOWN_CELL_BOTTOM_MARGIN + BOTTOM_CELL_TOOLBAR_GAP + this.getEditorStatusbarHeight();
}
get editorHeight() {
throw new Error('MarkdownCellViewModel.editorHeight is write only');
}
protected readonly _onDidChangeLayout = new Emitter<MarkdownCellLayoutChangeEvent>();
readonly onDidChangeLayout = this._onDidChangeLayout.event;
get foldingState() {
return this.foldingDelegate.getFoldingState(this.foldingDelegate.getCellIndex(this));
}
private _hoveringOutput: boolean = false;
public get outputIsHovered(): boolean {
return this._hoveringOutput;
}
public set outputIsHovered(v: boolean) {
this._hoveringOutput = v;
}
private _focusOnOutput: boolean = false;
public get outputIsFocused(): boolean {
return this._focusOnOutput;
}
public set outputIsFocused(v: boolean) {
this._focusOnOutput = v;
}
private _hoveringCell = false;
public get cellIsHovered(): boolean {
return this._hoveringCell;
}
public set cellIsHovered(v: boolean) {
this._hoveringCell = v;
this._onDidChangeState.fire({ cellIsHoveredChanged: true });
}
public get contentHash(): number {
return this.model.getHashValue();
}
constructor(
viewType: string,
model: NotebookCellTextModel,
initialNotebookLayoutInfo: NotebookLayoutInfo | null,
readonly foldingDelegate: EditorFoldingStateDelegate,
readonly eventDispatcher: NotebookEventDispatcher,
private readonly _mdRenderer: MarkdownRenderer,
@IConfigurationService configurationService: IConfigurationService,
@ITextModelService textModelService: ITextModelService,
) {
super(viewType, model, UUID.generateUuid(), configurationService, textModelService);
this._layoutInfo = {
editorHeight: 0,
fontInfo: initialNotebookLayoutInfo?.fontInfo || null,
editorWidth: initialNotebookLayoutInfo?.width ? this.computeEditorWidth(initialNotebookLayoutInfo.width) : 0,
bottomToolbarOffset: BOTTOM_CELL_TOOLBAR_GAP,
totalHeight: 0
};
this._register(this.onDidChangeState(e => {
eventDispatcher.emit([new NotebookCellStateChangedEvent(e, this)]);
}));
}
/**
* we put outputs stuff here to make compiler happy
*/
outputsViewModels: ICellOutputViewModel[] = [];
getOutputOffset(index: number): number {
// throw new Error('Method not implemented.');
return -1;
}
updateOutputHeight(index: number, height: number): void {
// throw new Error('Method not implemented.');
}
triggerfoldingStateChange() {
this._onDidChangeState.fire({ foldingStateChanged: true });
}
private computeEditorWidth(outerWidth: number) {
return outerWidth - (CELL_MARGIN * 2) - CODE_CELL_LEFT_MARGIN;
}
layoutChange(state: MarkdownCellLayoutChangeEvent) {
// recompute
if (!this.metadata?.inputCollapsed) {
const editorWidth = state.outerWidth !== undefined ? this.computeEditorWidth(state.outerWidth) : this._layoutInfo.editorWidth;
const totalHeight = state.totalHeight === undefined ? this._layoutInfo.totalHeight : state.totalHeight;
this._layoutInfo = {
fontInfo: state.font || this._layoutInfo.fontInfo,
editorWidth,
editorHeight: this._editorHeight,
bottomToolbarOffset: totalHeight - BOTTOM_CELL_TOOLBAR_GAP - BOTTOM_CELL_TOOLBAR_HEIGHT / 2,
totalHeight
};
} else {
const editorWidth = state.outerWidth !== undefined ? this.computeEditorWidth(state.outerWidth) : this._layoutInfo.editorWidth;
const totalHeight = MARKDOWN_CELL_TOP_MARGIN + COLLAPSED_INDICATOR_HEIGHT + BOTTOM_CELL_TOOLBAR_GAP + MARKDOWN_CELL_BOTTOM_MARGIN;
state.totalHeight = totalHeight;
this._layoutInfo = {
fontInfo: state.font || this._layoutInfo.fontInfo,
editorWidth,
editorHeight: this._editorHeight,
bottomToolbarOffset: totalHeight - BOTTOM_CELL_TOOLBAR_GAP - BOTTOM_CELL_TOOLBAR_HEIGHT / 2,
totalHeight
};
}
this._onDidChangeLayout.fire(state);
}
override restoreEditorViewState(editorViewStates: editorCommon.ICodeEditorViewState | null, totalHeight?: number) {
super.restoreEditorViewState(editorViewStates);
// we might already warmup the viewport so the cell has a total height computed
if (totalHeight !== undefined && this._layoutInfo.totalHeight === 0) {
this._layoutInfo = {
fontInfo: this._layoutInfo.fontInfo,
editorWidth: this._layoutInfo.editorWidth,
bottomToolbarOffset: this._layoutInfo.bottomToolbarOffset,
totalHeight: totalHeight,
editorHeight: this._editorHeight
};
this.layoutChange({});
}
}
hasDynamicHeight() {
return false;
}
getHeight(lineHeight: number) {
if (this._layoutInfo.totalHeight === 0) {
return 100;
} else {
return this._layoutInfo.totalHeight;
}
}
clearHTML() {
this._html = null;
}
getHTML(): HTMLElement | null {
if (this.cellKind === CellKind.Markdown) {
if (this._html) {
return this._html;
}
const renderer = this.getMarkdownRenderer();
const text = this.getText();
if (text.length === 0) {
const el = document.createElement('p');
el.className = 'emptyMarkdownPlaceholder';
el.innerText = nls.localize('notebook.emptyMarkdownPlaceholder', "Empty markdown cell, double click or press enter to edit.");
this._html = el;
} else {
this._html = renderer.render({ value: this.getText(), isTrusted: true }, undefined, { gfm: true }).element;
}
return this._html;
}
return null;
}
protected onDidChangeTextModelContent(): void {
this._html = null;
this._onDidChangeState.fire({ contentChanged: true });
}
onDeselect() {
}
getMarkdownRenderer() {
return this._mdRenderer;
}
private readonly _hasFindResult = this._register(new Emitter<boolean>());
public readonly hasFindResult: Event<boolean> = this._hasFindResult.event;
startFind(value: string, options: INotebookSearchOptions): CellFindMatch | null {
const matches = super.cellStartFind(value, options);
if (matches === null) {
return null;
}
return {
cell: this,
matches
};
}
}
| src/vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel.ts | 0 | https://github.com/microsoft/vscode/commit/c074bf897c0c3cd6ba5705828402924a3cc2b4dc | [
0.00028247429872862995,
0.00017616411787457764,
0.0001656827807892114,
0.00017191775259561837,
0.000021649140762747265
] |
{
"id": 4,
"code_window": [
"\t\t\tselector: options.selector,\n",
"\t\t\textensionId: extension.identifier,\n",
"\t\t\textensionLocation: extension.extensionLocation,\n",
"\t\t\tlabel: options.label,\n",
"\t\t\tsupportedLanguages: [],\n",
"\t\t};\n",
"\n",
"\t\t//\n",
"\t\tlet _executeHandler: ExecuteHandler = options.executeHandler;\n",
"\t\tlet _interruptHandler: InterruptHandler | undefined = options.interruptHandler;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tpreloads: options.preloads ? options.preloads.map(extHostTypeConverters.NotebookKernelPreload.from) : []\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts",
"type": "add",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { ExtHostNotebookKernelsShape, IMainContext, INotebookKernelDto2, MainContext, MainThreadNotebookKernelsShape } from 'vs/workbench/api/common/extHost.protocol';
import * as vscode from 'vscode';
import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { URI, UriComponents } from 'vs/base/common/uri';
import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import * as extHostTypeConverters from 'vs/workbench/api/common/extHostTypeConverters';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { asWebviewUri } from 'vs/workbench/api/common/shared/webview';
type ExecuteHandler = (cells: vscode.NotebookCell[], controller: vscode.NotebookController) => void;
type InterruptHandler = (notebook: vscode.NotebookDocument) => void;
interface IKernelData {
controller: vscode.NotebookController;
onDidChangeSelection: Emitter<{ selected: boolean; notebook: vscode.NotebookDocument; }>;
onDidReceiveMessage: Emitter<{ editor: vscode.NotebookEditor, message: any }>;
}
export class ExtHostNotebookKernels implements ExtHostNotebookKernelsShape {
private readonly _proxy: MainThreadNotebookKernelsShape;
private readonly _kernelData = new Map<number, IKernelData>();
private _handlePool: number = 0;
constructor(
mainContext: IMainContext,
private readonly _initData: IExtHostInitDataService,
private readonly _extHostNotebook: ExtHostNotebookController
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadNotebookKernels);
}
createKernel(extension: IExtensionDescription, options: vscode.NotebookControllerOptions): vscode.NotebookController {
const handle = this._handlePool++;
const that = this;
let isDisposed = false;
const commandDisposables = new DisposableStore();
const onDidChangeSelection = new Emitter<{ selected: boolean, notebook: vscode.NotebookDocument }>();
const onDidReceiveMessage = new Emitter<{ editor: vscode.NotebookEditor, message: any }>();
const data: INotebookKernelDto2 = {
id: options.id,
selector: options.selector,
extensionId: extension.identifier,
extensionLocation: extension.extensionLocation,
label: options.label,
supportedLanguages: [],
};
//
let _executeHandler: ExecuteHandler = options.executeHandler;
let _interruptHandler: InterruptHandler | undefined = options.interruptHandler;
// todo@jrieken the selector needs to be massaged
this._proxy.$addKernel(handle, data);
// update: all setters write directly into the dto object
// and trigger an update. the actual update will only happen
// once per event loop execution
let tokenPool = 0;
const _update = () => {
if (isDisposed) {
return;
}
const myToken = ++tokenPool;
Promise.resolve().then(() => {
if (myToken === tokenPool) {
this._proxy.$updateKernel(handle, data);
}
});
};
const controller: vscode.NotebookController = {
get id() { return data.id; },
get selector() { return data.selector; },
onDidChangeNotebookAssociation: onDidChangeSelection.event,
get label() {
return data.label;
},
set label(value) {
data.label = value;
_update();
},
get description() {
return data.description ?? '';
},
set description(value) {
data.description = value;
_update();
},
get isPreferred() {
return data.isPreferred ?? false;
},
set isPreferred(value) {
data.isPreferred = value;
_update();
},
get supportedLanguages() {
return data.supportedLanguages;
},
set supportedLanguages(value) {
data.supportedLanguages = isNonEmptyArray(value) ? value : ['plaintext'];
_update();
},
get hasExecutionOrder() {
return data.hasExecutionOrder ?? false;
},
set hasExecutionOrder(value) {
data.hasExecutionOrder = value;
_update();
},
get preloads() {
return data.preloads && data.preloads.map(extHostTypeConverters.NotebookKernelPreload.to);
},
set preloads(value) {
data.preloads = value && value.map(extHostTypeConverters.NotebookKernelPreload.from);
_update();
},
get executeHandler() {
return _executeHandler;
},
get interruptHandler() {
return _interruptHandler;
},
set interruptHandler(value) {
_interruptHandler = value;
data.supportsInterrupt = Boolean(value);
_update();
},
createNotebookCellExecutionTask(cell) {
if (isDisposed) {
throw new Error('notebook controller is DISPOSED');
}
//todo@jrieken
return that._extHostNotebook.createNotebookCellExecution(cell.notebook.uri, cell.index, data.id)!;
},
dispose: () => {
if (!isDisposed) {
isDisposed = true;
this._kernelData.delete(handle);
commandDisposables.dispose();
onDidChangeSelection.dispose();
onDidReceiveMessage.dispose();
this._proxy.$removeKernel(handle);
}
},
// --- ipc
onDidReceiveMessage: onDidReceiveMessage.event,
postMessage(message, editor) {
return that._proxy.$postMessage(handle, editor && that._extHostNotebook.getIdByEditor(editor), message);
},
asWebviewUri(uri: URI, editor) {
return asWebviewUri(that._initData.environment, that._extHostNotebook.getIdByEditor(editor)!, uri);
}
};
this._kernelData.set(handle, { controller, onDidChangeSelection, onDidReceiveMessage });
controller.supportedLanguages = options.supportedLanguages ?? [];
controller.interruptHandler = options.interruptHandler;
controller.hasExecutionOrder = options.hasExecutionOrder ?? false;
return controller;
}
$acceptSelection(handle: number, uri: UriComponents, value: boolean): void {
const obj = this._kernelData.get(handle);
if (obj) {
obj.onDidChangeSelection.fire({
selected: value,
notebook: this._extHostNotebook.lookupNotebookDocument(URI.revive(uri))!.notebookDocument
});
}
}
$executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void {
const obj = this._kernelData.get(handle);
if (!obj) {
// extension can dispose kernels in the meantime
return;
}
const document = this._extHostNotebook.lookupNotebookDocument(URI.revive(uri));
if (!document) {
throw new Error('MISSING notebook');
}
const cells: vscode.NotebookCell[] = [];
for (let range of ranges) {
cells.push(...document.notebookDocument.getCells(extHostTypeConverters.NotebookRange.to(range)));
}
try {
obj.controller.executeHandler(cells, obj.controller);
} catch (err) {
//
console.error(err);
}
}
$cancelCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void {
const obj = this._kernelData.get(handle);
if (!obj) {
// extension can dispose kernels in the meantime
return;
}
const document = this._extHostNotebook.lookupNotebookDocument(URI.revive(uri));
if (!document) {
throw new Error('MISSING notebook');
}
if (obj.controller.interruptHandler) {
obj.controller.interruptHandler(document.notebookDocument);
}
// we do both? interrupt and cancellation or should we be selective?
for (const range of ranges) {
for (let i = range.start; i < range.end; i++) {
const cell = document.getCellFromIndex(i);
if (cell) {
this._extHostNotebook.cancelOneNotebookCellExecution(cell);
}
}
}
}
$acceptRendererMessage(handle: number, editorId: string, message: any): void {
const obj = this._kernelData.get(handle);
if (!obj) {
// extension can dispose kernels in the meantime
return;
}
const editor = this._extHostNotebook.getEditorById(editorId);
if (!editor) {
throw new Error(`send message for UNKNOWN editor: ${editorId}`);
}
obj.onDidReceiveMessage.fire(Object.freeze({ editor: editor.apiEditor, message }));
}
}
| src/vs/workbench/api/common/extHostNotebookKernels.ts | 1 | https://github.com/microsoft/vscode/commit/c074bf897c0c3cd6ba5705828402924a3cc2b4dc | [
0.9984910488128662,
0.11588137596845627,
0.00016481333295814693,
0.00017774468869902194,
0.31838613748550415
] |
{
"id": 4,
"code_window": [
"\t\t\tselector: options.selector,\n",
"\t\t\textensionId: extension.identifier,\n",
"\t\t\textensionLocation: extension.extensionLocation,\n",
"\t\t\tlabel: options.label,\n",
"\t\t\tsupportedLanguages: [],\n",
"\t\t};\n",
"\n",
"\t\t//\n",
"\t\tlet _executeHandler: ExecuteHandler = options.executeHandler;\n",
"\t\tlet _interruptHandler: InterruptHandler | undefined = options.interruptHandler;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tpreloads: options.preloads ? options.preloads.map(extHostTypeConverters.NotebookKernelPreload.from) : []\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts",
"type": "add",
"edit_start_line_idx": 60
} | [
{
"c": "rowData",
"t": "source.ts meta.function-call.ts variable.other.object.ts",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": ".",
"t": "source.ts meta.function-call.ts punctuation.accessor.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "push",
"t": "source.ts meta.function-call.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.brace.round.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "callback",
"t": "source.ts meta.function-call.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.brace.round.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "new",
"t": "source.ts new.expr.ts keyword.operator.new.ts",
"r": {
"dark_plus": "keyword.operator.new: #569CD6",
"light_plus": "keyword.operator.new: #0000FF",
"dark_vs": "keyword.operator.new: #569CD6",
"light_vs": "keyword.operator.new: #0000FF",
"hc_black": "keyword.operator.new: #569CD6"
}
},
{
"c": " ",
"t": "source.ts new.expr.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "Cell",
"t": "source.ts new.expr.ts meta.function-call.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 new.expr.ts meta.brace.round.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "row",
"t": "source.ts new.expr.ts variable.other.readwrite.ts",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": ",",
"t": "source.ts new.expr.ts punctuation.separator.comma.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 new.expr.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "col",
"t": "source.ts new.expr.ts variable.other.readwrite.ts",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": ",",
"t": "source.ts new.expr.ts punctuation.separator.comma.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 new.expr.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "false",
"t": "source.ts new.expr.ts constant.language.boolean.false.ts",
"r": {
"dark_plus": "constant.language: #569CD6",
"light_plus": "constant.language: #0000FF",
"dark_vs": "constant.language: #569CD6",
"light_vs": "constant.language: #0000FF",
"hc_black": "constant.language: #569CD6"
}
},
{
"c": ")",
"t": "source.ts new.expr.ts meta.brace.round.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.brace.round.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 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"
}
}
] | extensions/vscode-colorize-tests/test/colorize-results/test-function-inv_ts.json | 0 | https://github.com/microsoft/vscode/commit/c074bf897c0c3cd6ba5705828402924a3cc2b4dc | [
0.00017757168097887188,
0.00017547662719152868,
0.00017327758541796356,
0.00017539202235639095,
0.0000010002103181250277
] |
{
"id": 4,
"code_window": [
"\t\t\tselector: options.selector,\n",
"\t\t\textensionId: extension.identifier,\n",
"\t\t\textensionLocation: extension.extensionLocation,\n",
"\t\t\tlabel: options.label,\n",
"\t\t\tsupportedLanguages: [],\n",
"\t\t};\n",
"\n",
"\t\t//\n",
"\t\tlet _executeHandler: ExecuteHandler = options.executeHandler;\n",
"\t\tlet _interruptHandler: InterruptHandler | undefined = options.interruptHandler;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tpreloads: options.preloads ? options.preloads.map(extHostTypeConverters.NotebookKernelPreload.from) : []\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts",
"type": "add",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* 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 { createHash } from 'crypto';
import { join } from 'vs/base/common/path';
import { isLinux } from 'vs/base/common/platform';
import { writeFileSync, writeFile, readdir, exists, rimraf, RimRafMode } from 'vs/base/node/pfs';
import { IBackupMainService, IWorkspaceBackupInfo, isWorkspaceBackupInfo } from 'vs/platform/backup/electron-main/backup';
import { IBackupWorkspacesFormat, IEmptyWindowBackupInfo } from 'vs/platform/backup/node/backup';
import { IEnvironmentMainService } from 'vs/platform/environment/electron-main/environmentMainService';
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 } from 'vs/base/common/extpath';
import { Schemas } from 'vs/base/common/network';
import { extUriBiasedIgnorePathCase } from 'vs/base/common/resources';
export class BackupMainService implements IBackupMainService {
declare readonly _serviceBrand: undefined;
protected backupHome: string;
protected workspacesJsonPath: string;
private workspaces: IWorkspaceBackupInfo[] = [];
private folders: URI[] = [];
private emptyWindows: IEmptyWindowBackupInfo[] = [];
// Comparers for paths and resources that will
// - ignore path casing on Windows/macOS
// - respect path casing on Linux
private readonly backupUriComparer = extUriBiasedIgnorePathCase;
private readonly backupPathComparer = { isEqual: (pathA: string, pathB: string) => isEqual(pathA, pathB, !isLinux) };
constructor(
@IEnvironmentMainService environmentMainService: IEnvironmentMainService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ILogService private readonly logService: ILogService
) {
this.backupHome = environmentMainService.backupHome;
this.workspacesJsonPath = environmentMainService.backupWorkspacesPath;
}
async initialize(): Promise<void> {
let backups: IBackupWorkspacesFormat;
try {
backups = JSON.parse(await fs.promises.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.emptyWindows = await this.validateEmptyWorkspaces(backups.emptyWorkspaceInfos);
}
// read workspace backups
let rootWorkspaces: IWorkspaceBackupInfo[] = [];
try {
if (Array.isArray(backups.rootURIWorkspaces)) {
rootWorkspaces = backups.rootURIWorkspaces.map(workspace => ({ workspace: { id: workspace.id, configPath: URI.parse(workspace.configURIPath) }, remoteAuthority: workspace.remoteAuthority }));
}
} catch (e) {
// ignore URI parsing exceptions
}
this.workspaces = await this.validateWorkspaces(rootWorkspaces);
// read folder backups
let workspaceFolders: URI[] = [];
try {
if (Array.isArray(backups.folderURIWorkspaces)) {
workspaceFolders = backups.folderURIWorkspaces.map(folder => URI.parse(folder));
}
} catch (e) {
// ignore URI parsing exceptions
}
this.folders = 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.workspaces.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.folders.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.emptyWindows.slice(0); // return a copy
}
registerWorkspaceBackupSync(workspaceInfo: IWorkspaceBackupInfo, migrateFrom?: string): string {
if (!this.workspaces.some(workspace => workspaceInfo.workspace.id === workspace.workspace.id)) {
this.workspaces.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 (error) {
this.logService.error(`Backup: Could not move backup folder to new location: ${error.toString()}`);
}
}
}
unregisterWorkspaceBackupSync(workspace: IWorkspaceIdentifier): void {
const id = workspace.id;
const index = this.workspaces.findIndex(workspace => workspace.workspace.id === id);
if (index !== -1) {
this.workspaces.splice(index, 1);
this.saveSync();
}
}
registerFolderBackupSync(folderUri: URI): string {
if (!this.folders.some(folder => this.backupUriComparer.isEqual(folderUri, folder))) {
this.folders.push(folderUri);
this.saveSync();
}
return this.getBackupPath(this.getFolderHash(folderUri));
}
unregisterFolderBackupSync(folderUri: URI): void {
const index = this.folders.findIndex(folder => this.backupUriComparer.isEqual(folderUri, folder));
if (index !== -1) {
this.folders.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.emptyWindows.some(emptyWindow => !!emptyWindow.backupFolder && this.backupPathComparer.isEqual(emptyWindow.backupFolder, backupFolder))) {
this.emptyWindows.push({ backupFolder, remoteAuthority });
this.saveSync();
}
return this.getBackupPath(backupFolder);
}
unregisterEmptyWindowBackupSync(backupFolder: string): void {
const index = this.emptyWindows.findIndex(emptyWindow => !!emptyWindow.backupFolder && this.backupPathComparer.isEqual(emptyWindow.backupFolder, backupFolder));
if (index !== -1) {
this.emptyWindows.splice(index, 1);
this.saveSync();
}
}
private getBackupPath(oldFolderHash: string): string {
return 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.doHasBackups(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 = this.backupUriComparer.getComparisonKey(folderURI);
if (!seenIds.has(key)) {
seenIds.add(key);
const backupPath = this.getBackupPath(this.getFolderHash(folderURI));
const hasBackups = await this.doHasBackups(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.doHasBackups(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 (error) {
this.logService.error(`Backup: Could not delete stale backup: ${error.toString()}`);
}
}
private async convertToEmptyWindowBackup(backupPath: string): Promise<boolean> {
// New empty window backup
let newBackupFolder = this.getRandomEmptyWindowId();
while (this.emptyWindows.some(emptyWindow => !!emptyWindow.backupFolder && this.backupPathComparer.isEqual(emptyWindow.backupFolder, newBackupFolder))) {
newBackupFolder = this.getRandomEmptyWindowId();
}
// Rename backupPath to new empty window backup path
const newEmptyWindowBackupPath = this.getBackupPath(newBackupFolder);
try {
await fs.promises.rename(backupPath, newEmptyWindowBackupPath);
} catch (error) {
this.logService.error(`Backup: Could not rename backup folder: ${error.toString()}`);
return false;
}
this.emptyWindows.push({ backupFolder: newBackupFolder });
return true;
}
private convertToEmptyWindowBackupSync(backupPath: string): boolean {
// New empty window backup
let newBackupFolder = this.getRandomEmptyWindowId();
while (this.emptyWindows.some(emptyWindow => !!emptyWindow.backupFolder && this.backupPathComparer.isEqual(emptyWindow.backupFolder, newBackupFolder))) {
newBackupFolder = this.getRandomEmptyWindowId();
}
// Rename backupPath to new empty window backup path
const newEmptyWindowBackupPath = this.getBackupPath(newBackupFolder);
try {
fs.renameSync(backupPath, newEmptyWindowBackupPath);
} catch (error) {
this.logService.error(`Backup: Could not rename backup folder: ${error.toString()}`);
return false;
}
this.emptyWindows.push({ backupFolder: newBackupFolder });
return true;
}
async getDirtyWorkspaces(): Promise<Array<IWorkspaceIdentifier | URI>> {
const dirtyWorkspaces: Array<IWorkspaceIdentifier | URI> = [];
// Workspaces with backups
for (const workspace of this.workspaces) {
if ((await this.hasBackups(workspace))) {
dirtyWorkspaces.push(workspace.workspace);
}
}
// Folders with backups
for (const folder of this.folders) {
if ((await this.hasBackups(folder))) {
dirtyWorkspaces.push(folder);
}
}
return dirtyWorkspaces;
}
private hasBackups(backupLocation: IWorkspaceBackupInfo | IEmptyWindowBackupInfo | URI): Promise<boolean> {
let backupPath: string;
// Folder
if (URI.isUri(backupLocation)) {
backupPath = this.getBackupPath(this.getFolderHash(backupLocation));
}
// Workspace
else if (isWorkspaceBackupInfo(backupLocation)) {
backupPath = this.getBackupPath(backupLocation.workspace.id);
}
// Empty
else {
backupPath = backupLocation.backupFolder;
}
return this.doHasBackups(backupPath);
}
private async doHasBackups(backupPath: string): Promise<boolean> {
try {
const backupSchemas = await readdir(backupPath);
for (const backupSchema of backupSchemas) {
try {
const backupSchemaChildren = await readdir(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 (error) {
this.logService.error(`Backup: Could not save workspaces.json: ${error.toString()}`);
}
}
private async save(): Promise<void> {
try {
await writeFile(this.workspacesJsonPath, JSON.stringify(this.serializeBackups()));
} catch (error) {
this.logService.error(`Backup: Could not save workspaces.json: ${error.toString()}`);
}
}
private serializeBackups(): IBackupWorkspacesFormat {
return {
rootURIWorkspaces: this.workspaces.map(workspace => ({ id: workspace.workspace.id, configURIPath: workspace.workspace.configPath.toString(), remoteAuthority: workspace.remoteAuthority })),
folderURIWorkspaces: this.folders.map(folder => folder.toString()),
emptyWorkspaceInfos: this.emptyWindows
};
}
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 = isLinux ? folderUri.fsPath : folderUri.fsPath.toLowerCase();
} else {
key = folderUri.toString().toLowerCase();
}
return createHash('md5').update(key).digest('hex');
}
}
| src/vs/platform/backup/electron-main/backupMainService.ts | 0 | https://github.com/microsoft/vscode/commit/c074bf897c0c3cd6ba5705828402924a3cc2b4dc | [
0.00017754474538378417,
0.00017349445261061192,
0.00016807482461445034,
0.00017392018344253302,
0.0000024261144062620588
] |
{
"id": 4,
"code_window": [
"\t\t\tselector: options.selector,\n",
"\t\t\textensionId: extension.identifier,\n",
"\t\t\textensionLocation: extension.extensionLocation,\n",
"\t\t\tlabel: options.label,\n",
"\t\t\tsupportedLanguages: [],\n",
"\t\t};\n",
"\n",
"\t\t//\n",
"\t\tlet _executeHandler: ExecuteHandler = options.executeHandler;\n",
"\t\tlet _interruptHandler: InterruptHandler | undefined = options.interruptHandler;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tpreloads: options.preloads ? options.preloads.map(extHostTypeConverters.NotebookKernelPreload.from) : []\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts",
"type": "add",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-icon-label.file-icon.workspacetrusteditor-name-file-icon.ext-file-icon.tab-label::before {
font-family: 'codicon';
content: '\eb53';
}
.workspace-trust-editor {
max-width: 1000px;
padding-top: 11px;
padding-left: 15px;
padding-right: 15px;
margin: auto;
height: calc(100% - 11px);
}
.workspace-trust-editor:focus {
outline: none !important;
}
.workspace-trust-editor > .workspace-trust-header {
padding: 14px;
display: flex;
flex-direction: column;
align-items: center;
}
.workspace-trust-editor .workspace-trust-header .workspace-trust-title {
font-size: 24px;
font-weight: 600;
line-height: 32px;
padding: 10px 0px;
display: flex;
}
.workspace-trust-editor .workspace-trust-header .workspace-trust-title .workspace-trust-title-icon {
font-size: 32px;
margin-right: 8px;
}
.workspace-trust-editor .workspace-trust-header .workspace-trust-title .workspace-trust-title-icon.codicon-workspace-trusted-icon {
color: var(--workspace-trust-state-trusted-color) !important;
}
.workspace-trust-editor .workspace-trust-header .workspace-trust-title .workspace-trust-title-icon.codicon-workspace-untrusted-icon {
color: var(--workspace-trust-state-untrusted-color) !important;
}
.workspace-trust-editor .workspace-trust-header .workspace-trust-description {
cursor: default;
user-select: text;
max-width: 600px;
}
.workspace-trust-editor .workspace-trust-section-title {
font-weight: 600;
font-size: 18px;
padding-bottom: 5px;
}
.workspace-trust-editor .workspace-trust-subsection-title {
font-size: 16px;
font-weight: 600;
line-height: 32px;
}
.workspace-trust-editor .workspace-trust-editor-body {
height: 100%;
}
/** Features List */
.workspace-trust-editor .workspace-trust-features {
padding: 14px;
cursor: default;
user-select: text;
display: flex;
flex-direction: row;
justify-content: space-evenly;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations {
border: 2px solid rgba(0, 0, 0, 0);
margin: 0px 4px;
display: flex;
flex-direction: column;
padding: 0px 40px;
}
.workspace-trust-editor.trusted .workspace-trust-features .workspace-trust-limitations.trusted {
border-color: var(--workspace-trust-state-trusted-color) !important;
}
.workspace-trust-editor.untrusted .workspace-trust-features .workspace-trust-limitations.untrusted {
border-color: var(--workspace-trust-state-untrusted-color) !important;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations ul {
list-style: none;
padding-inline-start: 0px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations li {
display: flex;
padding-bottom: 10px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations .list-item-icon {
padding-right: 5px;
line-height: 24px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations.trusted .list-item-icon {
color: var(--workspace-trust-state-trusted-color) !important;
font-size: 18px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations.untrusted .list-item-icon {
color: var(--workspace-trust-state-untrusted-color) !important;
font-size: 20px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations .list-item-text {
font-size: 16px;
line-height: 24px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations-header {
display: flex;
flex-direction: column;
align-items: center;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations-header .workspace-trust-limitations-title {
font-size: 16px;
font-weight: 600;
line-height: 24px;
padding: 10px 0px;
display: flex;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations-header .workspace-trust-limitations-title .workspace-trust-title-icon {
font-size: 24px;
margin-right: 8px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations-header .workspace-trust-limitations-title .workspace-trust-title-icon.codicon-workspace-trusted-icon {
color: var(--workspace-trust-state-trusted-color) !important;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-limitations-header .workspace-trust-limitations-title .workspace-trust-title-icon.codicon-workspace-untrusted-icon {
color: var(--workspace-trust-state-untrusted-color) !important;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-untrusted-description {
font-style: italic;
}
/** Buttons Container */
.workspace-trust-editor .workspace-trust-features .workspace-trust-buttons-row {
display: flex;
align-items: center;
justify-content: center;
padding: 5px 0 10px 0;
overflow: hidden; /* buttons row should never overflow */
white-space: nowrap;
margin-top: auto;
}
/** Buttons */
.workspace-trust-editor .workspace-trust-features .workspace-trust-buttons-row .workspace-trust-buttons {
display: flex;
overflow: hidden;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-buttons-row .workspace-trust-buttons .monaco-button {
width: fit-content;
width: -moz-fit-content;
padding: 5px 10px;
overflow: hidden;
text-overflow: ellipsis;
margin: 4px 5px; /* allows button focus outline to be visible */
outline-offset: 2px !important;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-buttons-row .workspace-trust-buttons .monaco-button-dropdown {
padding: 0 2px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-buttons-row .workspace-trust-buttons .monaco-button-dropdown .monaco-button {
margin-left: 1px;
margin-right: 1px;
}
.workspace-trust-editor .workspace-trust-features .workspace-trust-buttons-row .workspace-trust-buttons .monaco-button-dropdown .monaco-dropdown-button {
padding: 5px 0px;
}
.workspace-trust-limitations {
width: 50%;
max-width: 350px;
}
/** Settings */
.workspace-trust-editor .workspace-trust-settings .workspace-trust-section-title {
padding: 14px;
}
.workspace-trust-editor .settings-editor .settings-body {
margin-top: 0;
}
.workspace-trust-editor .settings-editor .settings-body .settings-tree-container .shadow.top {
left: initial;
margin-left: initial;
max-width: initial;
}
.workspace-trust-editor .settings-editor .settings-body .settings-tree-container .monaco-list-rows {
background: unset;
}
.workspace-trust-editor .settings-editor .settings-body .settings-tree-container .monaco-list-row .monaco-tl-contents {
padding-left: 0;
padding-right: 0;
}
.workspace-trust-editor .settings-editor .settings-body .settings-tree-container .monaco-list-row .monaco-tl-contents .setting-list-edit-row > .setting-list-valueInput {
width: 100%;
max-width: 100%;
}
.workspace-trust-editor .settings-editor > .settings-body > .settings-tree-container .setting-item.setting-item-list .setting-list-object-widget .setting-list-object-key,
.workspace-trust-editor .settings-editor > .settings-body > .settings-tree-container .setting-item.setting-item-list .setting-list-object-widget .setting-list-object-input-key {
margin-left: 4px;
min-width: 20%;
}
.workspace-trust-intro-dialog {
min-width: min(50vw, 500px);
padding-right: 24px;
}
.workspace-trust-intro-dialog .workspace-trust-dialog-image-row p {
display: flex;
align-items: center;
}
.workspace-trust-intro-dialog .workspace-trust-dialog-image-row.badge-row img {
max-height: 40px;
padding-right: 10px;
}
.workspace-trust-intro-dialog .workspace-trust-dialog-image-row.status-bar img {
max-height: 32px;
padding-right: 10px;
}
| src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.css | 0 | https://github.com/microsoft/vscode/commit/c074bf897c0c3cd6ba5705828402924a3cc2b4dc | [
0.00017563953588251024,
0.00017134749214164913,
0.00016491315909661353,
0.0001718550338409841,
0.0000027748183129006065
] |
{
"id": 0,
"code_window": [
"\tcontent: \"\\ec12\";\n",
"}\n",
"\n",
"/*\n",
" * Clear animation styles when hovering.\n",
" */\n",
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Clear animation styles when hovering or when reduced motion is enabled.\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "replace",
"edit_start_line_idx": 14
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* Replace with "microphone" icon.
*/
.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before,
.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before {
content: "\ec12";
}
/*
* Clear animation styles when hovering.
*/
.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover,
.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover {
animation: none;
}
/*
* Replace with "stop" icon when hovering.
*/
.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before,
.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before {
content: "\ead7"; /* use `debug-stop` icon unicode for hovering over running voice recording */
}
| src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css | 1 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.9283975958824158,
0.3134259879589081,
0.0005323535879142582,
0.011348043568432331,
0.4348730444908142
] |
{
"id": 0,
"code_window": [
"\tcontent: \"\\ec12\";\n",
"}\n",
"\n",
"/*\n",
" * Clear animation styles when hovering.\n",
" */\n",
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Clear animation styles when hovering or when reduced motion is enabled.\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "replace",
"edit_start_line_idx": 14
} | <!-- Copyright (C) Microsoft Corporation. All rights reserved. -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Microsoft Account - Sign In</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="auth.css" />
</head>
<body>
<a class="branding" href="https://code.visualstudio.com/">
Visual Studio Code
</a>
<div class="message-container">
<div class="message">
You are signed in now and can close this page.
</div>
<div class="error-message">
An error occurred while signing in:
<div class="error-text"></div>
</div>
</div>
<script>
var search = window.location.search;
var error = (/[?&^]error=([^&]+)/.exec(search) || [])[1];
if (error) {
document.querySelector('.error-text')
.textContent = decodeURIComponent(error);
document.querySelector('body')
.classList.add('error');
}
</script>
</body>
</html>
| extensions/microsoft-authentication/media/index.html | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.000173401233041659,
0.00016956913168542087,
0.00016531746950931847,
0.000169778912095353,
0.0000028666834168689093
] |
{
"id": 0,
"code_window": [
"\tcontent: \"\\ec12\";\n",
"}\n",
"\n",
"/*\n",
" * Clear animation styles when hovering.\n",
" */\n",
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Clear animation styles when hovering or when reduced motion is enabled.\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "replace",
"edit_start_line_idx": 14
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IHistoryNavigationWidget } from 'vs/base/browser/history';
import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview';
import { FindInput, IFindInputOptions } from 'vs/base/browser/ui/findinput/findInput';
import { IReplaceInputOptions, ReplaceInput } from 'vs/base/browser/ui/findinput/replaceInput';
import { HistoryInputBox, IHistoryInputOptions } from 'vs/base/browser/ui/inputbox/inputBox';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { ContextKeyExpr, IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { localize } from 'vs/nls';
import { DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
export const historyNavigationVisible = new RawContextKey<boolean>('suggestWidgetVisible', false, localize('suggestWidgetVisible', "Whether suggestion are visible"));
const HistoryNavigationWidgetFocusContext = 'historyNavigationWidgetFocus';
const HistoryNavigationForwardsEnablementContext = 'historyNavigationForwardsEnabled';
const HistoryNavigationBackwardsEnablementContext = 'historyNavigationBackwardsEnabled';
export interface IHistoryNavigationContext extends IDisposable {
scopedContextKeyService: IContextKeyService;
historyNavigationForwardsEnablement: IContextKey<boolean>;
historyNavigationBackwardsEnablement: IContextKey<boolean>;
}
let lastFocusedWidget: IHistoryNavigationWidget | undefined = undefined;
const widgets: IHistoryNavigationWidget[] = [];
export function registerAndCreateHistoryNavigationContext(contextKeyService: IContextKeyService, widget: IHistoryNavigationWidget): IHistoryNavigationContext {
if (widgets.includes(widget)) {
throw new Error('Cannot register the same widget multiple times');
}
widgets.push(widget);
const disposableStore = new DisposableStore();
const scopedContextKeyService = disposableStore.add(contextKeyService.createScoped(widget.element));
const historyNavigationWidgetFocus = new RawContextKey<boolean>(HistoryNavigationWidgetFocusContext, false).bindTo(scopedContextKeyService);
const historyNavigationForwardsEnablement = new RawContextKey<boolean>(HistoryNavigationForwardsEnablementContext, true).bindTo(scopedContextKeyService);
const historyNavigationBackwardsEnablement = new RawContextKey<boolean>(HistoryNavigationBackwardsEnablementContext, true).bindTo(scopedContextKeyService);
const onDidFocus = () => {
historyNavigationWidgetFocus.set(true);
lastFocusedWidget = widget;
};
const onDidBlur = () => {
historyNavigationWidgetFocus.set(false);
if (lastFocusedWidget === widget) {
lastFocusedWidget = undefined;
}
};
// Check for currently being focused
if (widget.element === document.activeElement) {
onDidFocus();
}
disposableStore.add(widget.onDidFocus(() => onDidFocus()));
disposableStore.add(widget.onDidBlur(() => onDidBlur()));
disposableStore.add(toDisposable(() => {
widgets.splice(widgets.indexOf(widget), 1);
onDidBlur();
}));
return {
scopedContextKeyService,
historyNavigationForwardsEnablement,
historyNavigationBackwardsEnablement,
dispose() {
disposableStore.dispose();
}
};
}
export class ContextScopedHistoryInputBox extends HistoryInputBox {
constructor(container: HTMLElement, contextViewProvider: IContextViewProvider | undefined, options: IHistoryInputOptions,
@IContextKeyService contextKeyService: IContextKeyService
) {
super(container, contextViewProvider, options);
this._register(registerAndCreateHistoryNavigationContext(contextKeyService, this));
}
}
export class ContextScopedFindInput extends FindInput {
constructor(container: HTMLElement | null, contextViewProvider: IContextViewProvider, options: IFindInputOptions,
@IContextKeyService contextKeyService: IContextKeyService
) {
super(container, contextViewProvider, options);
this._register(registerAndCreateHistoryNavigationContext(contextKeyService, this.inputBox));
}
}
export class ContextScopedReplaceInput extends ReplaceInput {
constructor(container: HTMLElement | null, contextViewProvider: IContextViewProvider | undefined, options: IReplaceInputOptions,
@IContextKeyService contextKeyService: IContextKeyService, showReplaceOptions: boolean = false
) {
super(container, contextViewProvider, showReplaceOptions, options);
this._register(registerAndCreateHistoryNavigationContext(contextKeyService, this.inputBox));
}
}
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'history.showPrevious',
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(
ContextKeyExpr.has(HistoryNavigationWidgetFocusContext),
ContextKeyExpr.equals(HistoryNavigationBackwardsEnablementContext, true),
historyNavigationVisible.isEqualTo(false),
),
primary: KeyCode.UpArrow,
secondary: [KeyMod.Alt | KeyCode.UpArrow],
handler: (accessor) => {
lastFocusedWidget?.showPreviousValue();
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'history.showNext',
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(
ContextKeyExpr.has(HistoryNavigationWidgetFocusContext),
ContextKeyExpr.equals(HistoryNavigationForwardsEnablementContext, true),
historyNavigationVisible.isEqualTo(false),
),
primary: KeyCode.DownArrow,
secondary: [KeyMod.Alt | KeyCode.DownArrow],
handler: (accessor) => {
lastFocusedWidget?.showNextValue();
}
});
| src/vs/editor/test/node/diffing/fixtures/ts-fragmented-eager-diffing/1.tst | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.0001735699624987319,
0.0001683161681285128,
0.00016286152822431177,
0.00016759545542299747,
0.000003282571469753748
] |
{
"id": 0,
"code_window": [
"\tcontent: \"\\ec12\";\n",
"}\n",
"\n",
"/*\n",
" * Clear animation styles when hovering.\n",
" */\n",
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Clear animation styles when hovering or when reduced motion is enabled.\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "replace",
"edit_start_line_idx": 14
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IFileService } from 'vs/platform/files/common/files';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { ILabelService } from 'vs/platform/label/common/label';
import { ILogService } from 'vs/platform/log/common/log';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkingCopyHistoryModelOptions, WorkingCopyHistoryService } from 'vs/workbench/services/workingCopy/common/workingCopyHistoryService';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IWorkingCopyHistoryService } from 'vs/workbench/services/workingCopy/common/workingCopyHistory';
export class BrowserWorkingCopyHistoryService extends WorkingCopyHistoryService {
constructor(
@IFileService fileService: IFileService,
@IRemoteAgentService remoteAgentService: IRemoteAgentService,
@IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService,
@IUriIdentityService uriIdentityService: IUriIdentityService,
@ILabelService labelService: ILabelService,
@ILogService logService: ILogService,
@IConfigurationService configurationService: IConfigurationService
) {
super(fileService, remoteAgentService, environmentService, uriIdentityService, labelService, logService, configurationService);
}
protected getModelOptions(): IWorkingCopyHistoryModelOptions {
return { flushOnChange: true /* because browsers support no long running shutdown */ };
}
}
// Register Service
registerSingleton(IWorkingCopyHistoryService, BrowserWorkingCopyHistoryService, InstantiationType.Delayed);
| src/vs/workbench/services/workingCopy/browser/workingCopyHistoryService.ts | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.0001724587200442329,
0.00016912646242417395,
0.00016632875485811383,
0.00016885920194908977,
0.0000025109484340646304
] |
{
"id": 1,
"code_window": [
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover {\n",
"\tanimation: none;\n",
"}\n",
"\n",
"/*\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
".monaco-workbench.reduce-motion .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled),\n",
".monaco-workbench.reduce-motion .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled) {\n",
"\tanimation: none;\n",
"}\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "add",
"edit_start_line_idx": 20
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* Replace with "microphone" icon.
*/
.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before,
.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before {
content: "\ec12";
}
/*
* Clear animation styles when hovering.
*/
.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover,
.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover {
animation: none;
}
/*
* Replace with "stop" icon when hovering.
*/
.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before,
.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before {
content: "\ead7"; /* use `debug-stop` icon unicode for hovering over running voice recording */
}
| src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css | 1 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.9824105501174927,
0.3349992036819458,
0.009073389694094658,
0.013513644225895405,
0.4577925503253937
] |
{
"id": 1,
"code_window": [
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover {\n",
"\tanimation: none;\n",
"}\n",
"\n",
"/*\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
".monaco-workbench.reduce-motion .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled),\n",
".monaco-workbench.reduce-motion .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled) {\n",
"\tanimation: none;\n",
"}\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "add",
"edit_start_line_idx": 20
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ITreeNavigator } from 'vs/base/browser/ui/tree/tree';
import { Emitter } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { RenderableMatch } from 'vs/workbench/contrib/search/browser/searchModel';
const someEvent = new Emitter().event;
/**
* Add stub methods as needed
*/
export class MockObjectTree<T, TRef> implements IDisposable {
get onDidChangeFocus() { return someEvent; }
get onDidChangeSelection() { return someEvent; }
get onDidOpen() { return someEvent; }
get onMouseClick() { return someEvent; }
get onMouseDblClick() { return someEvent; }
get onContextMenu() { return someEvent; }
get onKeyDown() { return someEvent; }
get onKeyUp() { return someEvent; }
get onKeyPress() { return someEvent; }
get onDidFocus() { return someEvent; }
get onDidBlur() { return someEvent; }
get onDidChangeCollapseState() { return someEvent; }
get onDidChangeRenderNodeCount() { return someEvent; }
get onDidDispose() { return someEvent; }
get lastVisibleElement() { return this.elements[this.elements.length - 1]; }
constructor(private elements: any[]) { }
domFocus(): void { }
collapse(location: TRef, recursive: boolean = false): boolean {
return true;
}
expand(location: TRef, recursive: boolean = false): boolean {
return true;
}
navigate(start?: TRef): ITreeNavigator<T> {
const startIdx = start ? this.elements.indexOf(start) :
undefined;
return new ArrayNavigator(this.elements, startIdx);
}
getParentElement(elem: RenderableMatch) {
return elem.parent();
}
dispose(): void {
}
}
class ArrayNavigator<T> implements ITreeNavigator<T> {
constructor(private elements: T[], private index = 0) { }
current(): T | null {
return this.elements[this.index];
}
previous(): T | null {
return this.elements[--this.index];
}
first(): T | null {
this.index = 0;
return this.elements[this.index];
}
last(): T | null {
this.index = this.elements.length - 1;
return this.elements[this.index];
}
next(): T | null {
return this.elements[++this.index];
}
}
| src/vs/workbench/contrib/search/test/browser/mockSearchTree.ts | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.00017907661094795913,
0.00017429068975616246,
0.00016554318426642567,
0.00017488884623162448,
0.0000035274722449685214
] |
{
"id": 1,
"code_window": [
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover {\n",
"\tanimation: none;\n",
"}\n",
"\n",
"/*\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
".monaco-workbench.reduce-motion .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled),\n",
".monaco-workbench.reduce-motion .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled) {\n",
"\tanimation: none;\n",
"}\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "add",
"edit_start_line_idx": 20
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use crate::log;
#[cfg(not(windows))]
pub fn is_wsl_installed(_log: &log::Logger) -> bool {
false
}
#[cfg(windows)]
pub fn is_wsl_installed(log: &log::Logger) -> bool {
use std::path::PathBuf;
use crate::util::command::new_std_command;
let system32 = {
let sys_root = match std::env::var("SystemRoot") {
Ok(s) => s,
Err(_) => return false,
};
let is_32_on_64 = std::env::var("PROCESSOR_ARCHITEW6432").is_ok();
let mut system32 = PathBuf::from(sys_root);
system32.push(if is_32_on_64 { "Sysnative" } else { "System32" });
system32
};
// Windows builds < 22000
let mut maybe_lxss = system32.join("lxss");
maybe_lxss.push("LxssManager.dll");
if maybe_lxss.exists() {
trace!(log, "wsl availability detected via lxss");
return true;
}
// Windows builds >= 22000
let maybe_wsl = system32.join("wsl.exe");
if maybe_wsl.exists() {
if let Ok(s) = new_std_command(maybe_wsl).arg("--status").output() {
if s.status.success() {
trace!(log, "wsl availability detected via subprocess");
return true;
}
}
}
trace!(log, "wsl not detected");
false
}
| cli/src/tunnels/wsl_detect.rs | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.00017727106751408428,
0.0001729435898596421,
0.0001694936363492161,
0.00017248484073206782,
0.0000032117129649122944
] |
{
"id": 1,
"code_window": [
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover {\n",
"\tanimation: none;\n",
"}\n",
"\n",
"/*\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
".monaco-workbench.reduce-motion .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled),\n",
".monaco-workbench.reduce-motion .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled) {\n",
"\tanimation: none;\n",
"}\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "add",
"edit_start_line_idx": 20
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Code } from './code';
import { QuickAccess } from './quickaccess';
import { QuickInput } from './quickinput';
const activeRowSelector = `.notebook-editor .monaco-list-row.focused`;
export class Notebook {
constructor(
private readonly quickAccess: QuickAccess,
private readonly quickInput: QuickInput,
private readonly code: Code) {
}
async openNotebook() {
await this.quickAccess.openFileQuickAccessAndWait('notebook.ipynb', 1);
await this.quickInput.selectQuickInputElement(0);
await this.code.waitForElement(activeRowSelector);
await this.focusFirstCell();
await this.waitForActiveCellEditorContents('code()');
}
async focusNextCell() {
await this.code.dispatchKeybinding('down');
}
async focusFirstCell() {
await this.quickAccess.runCommand('notebook.focusTop');
}
async editCell() {
await this.code.dispatchKeybinding('enter');
}
async stopEditingCell() {
await this.quickAccess.runCommand('notebook.cell.quitEdit');
}
async waitForTypeInEditor(text: string): Promise<any> {
const editor = `${activeRowSelector} .monaco-editor`;
await this.code.waitForElement(editor);
const textarea = `${editor} textarea`;
await this.code.waitForActiveElement(textarea);
await this.code.waitForTypeInEditor(textarea, text);
await this._waitForActiveCellEditorContents(c => c.indexOf(text) > -1);
}
async waitForActiveCellEditorContents(contents: string): Promise<any> {
return this._waitForActiveCellEditorContents(str => str === contents);
}
private async _waitForActiveCellEditorContents(accept: (contents: string) => boolean): Promise<any> {
const selector = `${activeRowSelector} .monaco-editor .view-lines`;
return this.code.waitForTextContent(selector, undefined, c => accept(c.replace(/\u00a0/g, ' ')));
}
async waitForMarkdownContents(markdownSelector: string, text: string): Promise<void> {
const selector = `${activeRowSelector} .markdown ${markdownSelector}`;
await this.code.waitForTextContent(selector, text);
}
async insertNotebookCell(kind: 'markdown' | 'code'): Promise<void> {
if (kind === 'markdown') {
await this.quickAccess.runCommand('notebook.cell.insertMarkdownCellBelow');
} else {
await this.quickAccess.runCommand('notebook.cell.insertCodeCellBelow');
}
}
async deleteActiveCell(): Promise<void> {
await this.quickAccess.runCommand('notebook.cell.delete');
}
async focusInCellOutput(): Promise<void> {
await this.quickAccess.runCommand('notebook.cell.focusInOutput');
await this.code.waitForActiveElement('webview, .webview');
}
async focusOutCellOutput(): Promise<void> {
await this.quickAccess.runCommand('notebook.cell.focusOutOutput');
}
async executeActiveCell(): Promise<void> {
await this.quickAccess.runCommand('notebook.cell.execute');
}
async executeCellAction(selector: string): Promise<void> {
await this.code.waitAndClick(selector);
}
}
| test/automation/src/notebook.ts | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.00019756442634388804,
0.00017441908130422235,
0.0001675129315117374,
0.00017257336003240198,
0.000007774774530844297
] |
{
"id": 2,
"code_window": [
"\n",
"/*\n",
" * Replace with \"stop\" icon when hovering.\n",
" */\n",
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Replace with \"stop\" icon when hovering or when reduced motion is enabled.\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "replace",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* 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/voiceChatActions';
import { Event } from 'vs/base/common/event';
import { firstOrDefault } from 'vs/base/common/arrays';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { Codicon } from 'vs/base/common/codicons';
import { DisposableStore, toDisposable } from 'vs/base/common/lifecycle';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { localize } from 'vs/nls';
import { Action2, MenuId } from 'vs/platform/actions/common/actions';
import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { spinningLoading } from 'vs/platform/theme/common/iconRegistry';
import { CHAT_CATEGORY } from 'vs/workbench/contrib/chat/browser/actions/chatActions';
import { IChatWidget, IChatWidgetService, IQuickChatService } from 'vs/workbench/contrib/chat/browser/chat';
import { IChatService } from 'vs/workbench/contrib/chat/common/chatService';
import { MENU_INLINE_CHAT_WIDGET } from 'vs/workbench/contrib/inlineChat/common/inlineChat';
import { CONTEXT_PROVIDER_EXISTS } from 'vs/workbench/contrib/chat/common/chatContextKeys';
import { InlineChatController } from 'vs/workbench/contrib/inlineChat/browser/inlineChatController';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { getCodeEditor } from 'vs/editor/browser/editorBrowser';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { ActiveEditorContext } from 'vs/workbench/common/contextkeys';
import { IViewsService } from 'vs/workbench/common/views';
import { IChatContributionService } from 'vs/workbench/contrib/chat/common/chatContributionService';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { KeyCode } from 'vs/base/common/keyCodes';
import { isExecuteActionContext } from 'vs/workbench/contrib/chat/browser/actions/chatExecuteActions';
import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService';
import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService';
import { RunOnceScheduler } from 'vs/base/common/async';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { ACTIVITY_BAR_BADGE_BACKGROUND } from 'vs/workbench/common/theme';
import { ColorScheme } from 'vs/platform/theme/common/theme';
import { Color } from 'vs/base/common/color';
import { contrastBorder, focusBorder } from 'vs/platform/theme/common/colorRegistry';
const CONTEXT_VOICE_CHAT_GETTING_READY = new RawContextKey<boolean>('voiceChatGettingReady', false, { type: 'boolean', description: localize('voiceChatGettingReady', "True when getting ready for receiving voice input from the microphone for voice chat.") });
const CONTEXT_VOICE_CHAT_IN_PROGRESS = new RawContextKey<boolean>('voiceChatInProgress', false, { type: 'boolean', description: localize('voiceChatInProgress', "True when voice recording from microphone is in progress for voice chat.") });
const CONTEXT_QUICK_VOICE_CHAT_IN_PROGRESS = new RawContextKey<boolean>('quickVoiceChatInProgress', false, { type: 'boolean', description: localize('quickVoiceChatInProgress', "True when voice recording from microphone is in progress for quick chat.") });
const CONTEXT_INLINE_VOICE_CHAT_IN_PROGRESS = new RawContextKey<boolean>('inlineVoiceChatInProgress', false, { type: 'boolean', description: localize('inlineVoiceChatInProgress', "True when voice recording from microphone is in progress for inline chat.") });
const CONTEXT_VOICE_CHAT_IN_VIEW_IN_PROGRESS = new RawContextKey<boolean>('voiceChatInViewInProgress', false, { type: 'boolean', description: localize('voiceChatInViewInProgress', "True when voice recording from microphone is in progress in the chat view.") });
const CONTEXT_VOICE_CHAT_IN_EDITOR_IN_PROGRESS = new RawContextKey<boolean>('voiceChatInEditorInProgress', false, { type: 'boolean', description: localize('voiceChatInEditorInProgress', "True when voice recording from microphone is in progress in the chat editor.") });
type VoiceChatSessionContext = 'inline' | 'quick' | 'view' | 'editor';
interface IVoiceChatSessionController {
readonly onDidAcceptInput: Event<unknown>;
readonly onDidCancelInput: Event<unknown>;
readonly context: VoiceChatSessionContext;
focusInput(): void;
acceptInput(): void;
updateInput(text: string): void;
setInputPlaceholder(text: string): void;
clearInputPlaceholder(): void;
}
class VoiceChatSessionControllerFactory {
static create(accessor: ServicesAccessor, context: 'inline'): Promise<IVoiceChatSessionController | undefined>;
static create(accessor: ServicesAccessor, context: 'quick'): Promise<IVoiceChatSessionController | undefined>;
static create(accessor: ServicesAccessor, context: 'view'): Promise<IVoiceChatSessionController | undefined>;
static create(accessor: ServicesAccessor, context: 'focused'): Promise<IVoiceChatSessionController | undefined>;
static async create(accessor: ServicesAccessor, context: 'inline' | 'quick' | 'view' | 'focused'): Promise<IVoiceChatSessionController | undefined> {
const chatWidgetService = accessor.get(IChatWidgetService);
const chatService = accessor.get(IChatService);
const viewsService = accessor.get(IViewsService);
const chatContributionService = accessor.get(IChatContributionService);
const editorService = accessor.get(IEditorService);
const quickChatService = accessor.get(IQuickChatService);
const layoutService = accessor.get(IWorkbenchLayoutService);
// Currently Focused Context
if (context === 'focused') {
// Try with the chat widget service, which currently
// only supports the chat view and quick chat
// https://github.com/microsoft/vscode/issues/191191
const chatInput = chatWidgetService.lastFocusedWidget;
if (chatInput?.hasInputFocus()) {
// Unfortunately there does not seem to be a better way
// to figure out if the chat widget is in a part or picker
if (
layoutService.hasFocus(Parts.SIDEBAR_PART) ||
layoutService.hasFocus(Parts.PANEL_PART) ||
layoutService.hasFocus(Parts.AUXILIARYBAR_PART)
) {
return VoiceChatSessionControllerFactory.doCreateForChatView(chatInput, viewsService, chatContributionService);
}
if (layoutService.hasFocus(Parts.EDITOR_PART)) {
return VoiceChatSessionControllerFactory.doCreateForChatEditor(chatInput, viewsService, chatContributionService);
}
return VoiceChatSessionControllerFactory.doCreateForQuickChat(chatInput, quickChatService);
}
// Try with the inline chat
const activeCodeEditor = getCodeEditor(editorService.activeTextEditorControl);
if (activeCodeEditor) {
const inlineChat = InlineChatController.get(activeCodeEditor);
if (inlineChat?.hasFocus()) {
return VoiceChatSessionControllerFactory.doCreateForInlineChat(inlineChat);
}
}
}
// View Chat
if (context === 'view') {
const provider = firstOrDefault(chatService.getProviderInfos());
if (provider) {
const chatView = await chatWidgetService.revealViewForProvider(provider.id);
if (chatView) {
return VoiceChatSessionControllerFactory.doCreateForChatView(chatView, viewsService, chatContributionService);
}
}
}
// Inline Chat
if (context === 'inline') {
const activeCodeEditor = getCodeEditor(editorService.activeTextEditorControl);
if (activeCodeEditor) {
const inlineChat = InlineChatController.get(activeCodeEditor);
if (inlineChat) {
return VoiceChatSessionControllerFactory.doCreateForInlineChat(inlineChat);
}
}
}
// Quick Chat
if (context === 'quick') {
quickChatService.open();
const quickChat = chatWidgetService.lastFocusedWidget;
if (quickChat) {
return VoiceChatSessionControllerFactory.doCreateForQuickChat(quickChat, quickChatService);
}
}
return undefined;
}
private static doCreateForChatView(chatView: IChatWidget, viewsService: IViewsService, chatContributionService: IChatContributionService): IVoiceChatSessionController {
return VoiceChatSessionControllerFactory.doCreateForChatViewOrEditor('view', chatView, viewsService, chatContributionService);
}
private static doCreateForChatEditor(chatView: IChatWidget, viewsService: IViewsService, chatContributionService: IChatContributionService): IVoiceChatSessionController {
return VoiceChatSessionControllerFactory.doCreateForChatViewOrEditor('editor', chatView, viewsService, chatContributionService);
}
private static doCreateForChatViewOrEditor(context: 'view' | 'editor', chatView: IChatWidget, viewsService: IViewsService, chatContributionService: IChatContributionService): IVoiceChatSessionController {
return {
context,
onDidAcceptInput: chatView.onDidAcceptInput,
// TODO@bpasero cancellation needs to work better for chat editors that are not view bound
onDidCancelInput: Event.filter(viewsService.onDidChangeViewVisibility, e => e.id === chatContributionService.getViewIdForProvider(chatView.providerId)),
focusInput: () => chatView.focusInput(),
acceptInput: () => chatView.acceptInput(),
updateInput: text => chatView.updateInput(text),
setInputPlaceholder: text => chatView.setInputPlaceholder(text),
clearInputPlaceholder: () => chatView.resetInputPlaceholder()
};
}
private static doCreateForQuickChat(quickChat: IChatWidget, quickChatService: IQuickChatService): IVoiceChatSessionController {
return {
context: 'quick',
onDidAcceptInput: quickChat.onDidAcceptInput,
onDidCancelInput: quickChatService.onDidClose,
focusInput: () => quickChat.focusInput(),
acceptInput: () => quickChat.acceptInput(),
updateInput: text => quickChat.updateInput(text),
setInputPlaceholder: text => quickChat.setInputPlaceholder(text),
clearInputPlaceholder: () => quickChat.resetInputPlaceholder()
};
}
private static doCreateForInlineChat(inlineChat: InlineChatController,): IVoiceChatSessionController {
const inlineChatSession = inlineChat.run();
return {
context: 'inline',
onDidAcceptInput: inlineChat.onDidAcceptInput,
onDidCancelInput: Event.any(
inlineChat.onDidCancelInput,
Event.fromPromise(inlineChatSession)
),
focusInput: () => inlineChat.focus(),
acceptInput: () => inlineChat.acceptInput(),
updateInput: text => inlineChat.updateInput(text),
setInputPlaceholder: text => inlineChat.setPlaceholder(text),
clearInputPlaceholder: () => inlineChat.resetPlaceholder()
};
}
}
interface ActiveVoiceChatSession {
readonly id: number;
readonly controller: IVoiceChatSessionController;
readonly disposables: DisposableStore;
}
class VoiceChatSessions {
private static instance: VoiceChatSessions | undefined = undefined;
static getInstance(instantiationService: IInstantiationService): VoiceChatSessions {
if (!VoiceChatSessions.instance) {
VoiceChatSessions.instance = instantiationService.createInstance(VoiceChatSessions);
}
return VoiceChatSessions.instance;
}
private voiceChatInProgressKey = CONTEXT_VOICE_CHAT_IN_PROGRESS.bindTo(this.contextKeyService);
private voiceChatGettingReadyKey = CONTEXT_VOICE_CHAT_GETTING_READY.bindTo(this.contextKeyService);
private quickVoiceChatInProgressKey = CONTEXT_QUICK_VOICE_CHAT_IN_PROGRESS.bindTo(this.contextKeyService);
private inlineVoiceChatInProgressKey = CONTEXT_INLINE_VOICE_CHAT_IN_PROGRESS.bindTo(this.contextKeyService);
private voiceChatInViewInProgressKey = CONTEXT_VOICE_CHAT_IN_VIEW_IN_PROGRESS.bindTo(this.contextKeyService);
private voiceChatInEditorInProgressKey = CONTEXT_VOICE_CHAT_IN_EDITOR_IN_PROGRESS.bindTo(this.contextKeyService);
private currentVoiceChatSession: ActiveVoiceChatSession | undefined = undefined;
private voiceChatSessionIds = 0;
constructor(
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@ISpeechService private readonly speechService: ISpeechService
) { }
async start(controller: IVoiceChatSessionController): Promise<void> {
this.stop();
const sessionId = ++this.voiceChatSessionIds;
const session = this.currentVoiceChatSession = {
id: sessionId,
controller,
disposables: new DisposableStore()
};
const cts = new CancellationTokenSource();
session.disposables.add(toDisposable(() => cts.dispose(true)));
session.disposables.add(controller.onDidAcceptInput(() => this.stop(sessionId, controller.context)));
session.disposables.add(controller.onDidCancelInput(() => this.stop(sessionId, controller.context)));
controller.updateInput('');
controller.focusInput();
this.voiceChatGettingReadyKey.set(true);
const speechToTextSession = session.disposables.add(this.speechService.createSpeechToTextSession(cts.token));
let transcription: string = '';
const acceptTranscriptionScheduler = session.disposables.add(new RunOnceScheduler(() => session.controller.acceptInput(), 1200));
session.disposables.add(speechToTextSession.onDidChange(({ status, text }) => {
if (cts.token.isCancellationRequested) {
return;
}
switch (status) {
case SpeechToTextStatus.Started:
this.onDidSpeechToTextSessionStart(controller, session.disposables);
break;
case SpeechToTextStatus.Recognizing:
if (text) {
session.controller.updateInput([transcription, text].join(' '));
acceptTranscriptionScheduler.cancel();
}
break;
case SpeechToTextStatus.Recognized:
if (text) {
transcription = [transcription, text].join(' ');
session.controller.updateInput(transcription);
acceptTranscriptionScheduler.schedule();
}
break;
case SpeechToTextStatus.Stopped:
this.stop(session.id, controller.context);
break;
}
}));
}
private onDidSpeechToTextSessionStart(controller: IVoiceChatSessionController, disposables: DisposableStore): void {
this.voiceChatGettingReadyKey.set(false);
this.voiceChatInProgressKey.set(true);
switch (controller.context) {
case 'inline':
this.inlineVoiceChatInProgressKey.set(true);
break;
case 'quick':
this.quickVoiceChatInProgressKey.set(true);
break;
case 'view':
this.voiceChatInViewInProgressKey.set(true);
break;
case 'editor':
this.voiceChatInEditorInProgressKey.set(true);
break;
}
let dotCount = 0;
const updatePlaceholder = () => {
dotCount = (dotCount + 1) % 4;
controller.setInputPlaceholder(`${localize('listening', "I'm listening")}${'.'.repeat(dotCount)}`);
placeholderScheduler.schedule();
};
const placeholderScheduler = disposables.add(new RunOnceScheduler(updatePlaceholder, 500));
updatePlaceholder();
}
stop(voiceChatSessionId = this.voiceChatSessionIds, context?: VoiceChatSessionContext): void {
if (
!this.currentVoiceChatSession ||
this.voiceChatSessionIds !== voiceChatSessionId ||
(context && this.currentVoiceChatSession.controller.context !== context)
) {
return;
}
this.currentVoiceChatSession.controller.clearInputPlaceholder();
this.currentVoiceChatSession.disposables.dispose();
this.currentVoiceChatSession = undefined;
this.voiceChatGettingReadyKey.set(false);
this.voiceChatInProgressKey.set(false);
this.quickVoiceChatInProgressKey.set(false);
this.inlineVoiceChatInProgressKey.set(false);
this.voiceChatInViewInProgressKey.set(false);
this.voiceChatInEditorInProgressKey.set(false);
}
accept(voiceChatSessionId = this.voiceChatSessionIds): void {
if (
!this.currentVoiceChatSession ||
this.voiceChatSessionIds !== voiceChatSessionId
) {
return;
}
this.currentVoiceChatSession.controller.acceptInput();
}
}
export class VoiceChatInChatViewAction extends Action2 {
static readonly ID = 'workbench.action.chat.voiceChatInChatView';
constructor() {
super({
id: VoiceChatInChatViewAction.ID,
title: {
value: localize('workbench.action.chat.voiceChatInView.label', "Voice Chat in Chat View"),
original: 'Voice Chat in Chat View'
},
category: CHAT_CATEGORY,
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_PROVIDER_EXISTS),
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const instantiationService = accessor.get(IInstantiationService);
const controller = await VoiceChatSessionControllerFactory.create(accessor, 'view');
if (controller) {
VoiceChatSessions.getInstance(instantiationService).start(controller);
}
}
}
export class InlineVoiceChatAction extends Action2 {
static readonly ID = 'workbench.action.chat.inlineVoiceChat';
constructor() {
super({
id: InlineVoiceChatAction.ID,
title: {
value: localize('workbench.action.chat.inlineVoiceChat', "Inline Voice Chat"),
original: 'Inline Voice Chat'
},
category: CHAT_CATEGORY,
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_PROVIDER_EXISTS, ActiveEditorContext),
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const instantiationService = accessor.get(IInstantiationService);
const controller = await VoiceChatSessionControllerFactory.create(accessor, 'inline');
if (controller) {
VoiceChatSessions.getInstance(instantiationService).start(controller);
}
}
}
export class QuickVoiceChatAction extends Action2 {
static readonly ID = 'workbench.action.chat.quickVoiceChat';
constructor() {
super({
id: QuickVoiceChatAction.ID,
title: {
value: localize('workbench.action.chat.quickVoiceChat.label', "Quick Voice Chat"),
original: 'Quick Voice Chat'
},
category: CHAT_CATEGORY,
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_PROVIDER_EXISTS),
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const instantiationService = accessor.get(IInstantiationService);
const controller = await VoiceChatSessionControllerFactory.create(accessor, 'quick');
if (controller) {
VoiceChatSessions.getInstance(instantiationService).start(controller);
}
}
}
export class StartVoiceChatAction extends Action2 {
static readonly ID = 'workbench.action.chat.startVoiceChat';
constructor() {
super({
id: StartVoiceChatAction.ID,
title: {
value: localize('workbench.action.chat.startVoiceChat', "Start Voice Chat"),
original: 'Start Voice Chat'
},
icon: Codicon.mic,
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_GETTING_READY.negate()),
menu: [{
id: MenuId.ChatExecute,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_VIEW_IN_PROGRESS.negate(), CONTEXT_QUICK_VOICE_CHAT_IN_PROGRESS.negate(), CONTEXT_VOICE_CHAT_IN_EDITOR_IN_PROGRESS.negate()),
group: 'navigation',
order: -1
}, {
id: MENU_INLINE_CHAT_WIDGET,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_INLINE_VOICE_CHAT_IN_PROGRESS.negate()),
group: 'main',
order: -1
}]
});
}
async run(accessor: ServicesAccessor, context: unknown): Promise<void> {
const instantiationService = accessor.get(IInstantiationService);
const commandService = accessor.get(ICommandService);
if (isExecuteActionContext(context)) {
// if we already get a context when the action is executed
// from a toolbar within the chat widget, then make sure
// to move focus into the input field so that the controller
// is properly retrieved
// TODO@bpasero this will actually not work if the button
// is clicked from the inline editor while focus is in a
// chat input field in a view or picker
context.widget.focusInput();
}
const controller = await VoiceChatSessionControllerFactory.create(accessor, 'focused');
if (controller) {
VoiceChatSessions.getInstance(instantiationService).start(controller);
} else {
// fallback to Quick Voice Chat command
commandService.executeCommand(QuickVoiceChatAction.ID);
}
}
}
export class StopVoiceChatAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopVoiceChat';
constructor() {
super({
id: StopVoiceChatAction.ID,
title: {
value: localize('workbench.action.chat.stopVoiceChat.label', "Stop Voice Chat"),
original: 'Stop Voice Chat'
},
category: CHAT_CATEGORY,
f1: true,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib + 100,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_PROGRESS),
primary: KeyCode.Escape
},
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_PROGRESS)
});
}
run(accessor: ServicesAccessor): void {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).stop();
}
}
export class StopVoiceChatInChatViewAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopVoiceChatInChatView';
constructor() {
super({
id: StopVoiceChatInChatViewAction.ID,
title: {
value: localize('workbench.action.chat.stopVoiceChatInChatView.label', "Stop Voice Chat (Chat View)"),
original: 'Stop Voice Chat (Chat View)'
},
category: CHAT_CATEGORY,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib + 100,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_VIEW_IN_PROGRESS),
primary: KeyCode.Escape
},
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_VIEW_IN_PROGRESS),
icon: spinningLoading,
menu: [{
id: MenuId.ChatExecute,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_VIEW_IN_PROGRESS),
group: 'navigation',
order: -1
}]
});
}
run(accessor: ServicesAccessor): void {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).stop(undefined, 'view');
}
}
export class StopVoiceChatInChatEditorAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopVoiceChatInChatEditor';
constructor() {
super({
id: StopVoiceChatInChatEditorAction.ID,
title: {
value: localize('workbench.action.chat.stopVoiceChatInChatEditor.label', "Stop Voice Chat (Chat Editor)"),
original: 'Stop Voice Chat (Chat Editor)'
},
category: CHAT_CATEGORY,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib + 100,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_EDITOR_IN_PROGRESS),
primary: KeyCode.Escape
},
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_EDITOR_IN_PROGRESS),
icon: spinningLoading,
menu: [{
id: MenuId.ChatExecute,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_EDITOR_IN_PROGRESS),
group: 'navigation',
order: -1
}]
});
}
run(accessor: ServicesAccessor): void {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).stop(undefined, 'editor');
}
}
export class StopQuickVoiceChatAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopQuickVoiceChat';
constructor() {
super({
id: StopQuickVoiceChatAction.ID,
title: {
value: localize('workbench.action.chat.stopQuickVoiceChat.label', "Stop Voice Chat (Quick Chat)"),
original: 'Stop Voice Chat (Quick Chat)'
},
category: CHAT_CATEGORY,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib + 100,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_QUICK_VOICE_CHAT_IN_PROGRESS),
primary: KeyCode.Escape
},
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_QUICK_VOICE_CHAT_IN_PROGRESS),
icon: spinningLoading,
menu: [{
id: MenuId.ChatExecute,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_QUICK_VOICE_CHAT_IN_PROGRESS),
group: 'navigation',
order: -1
}]
});
}
run(accessor: ServicesAccessor): void {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).stop(undefined, 'quick');
}
}
export class StopInlineVoiceChatAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopInlineVoiceChat';
constructor() {
super({
id: StopInlineVoiceChatAction.ID,
title: {
value: localize('workbench.action.chat.stopInlineVoiceChat.label', "Stop Voice Chat (Inline Editor)"),
original: 'Stop Voice Chat (Inline Editor)'
},
category: CHAT_CATEGORY,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib + 100,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_INLINE_VOICE_CHAT_IN_PROGRESS),
primary: KeyCode.Escape
},
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_INLINE_VOICE_CHAT_IN_PROGRESS),
icon: spinningLoading,
menu: [{
id: MENU_INLINE_CHAT_WIDGET,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_INLINE_VOICE_CHAT_IN_PROGRESS),
group: 'main',
order: -1
}]
});
}
run(accessor: ServicesAccessor): void {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).stop(undefined, 'inline');
}
}
export class StopVoiceChatAndSubmitAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopVoiceChatAndSubmit';
constructor() {
super({
id: StopVoiceChatAndSubmitAction.ID,
title: {
value: localize('workbench.action.chat.stopAndAcceptVoiceChat.label', "Stop Voice Chat and Submit"),
original: 'Stop Voice Chat and Submit'
},
category: CHAT_CATEGORY,
f1: true,
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_PROGRESS)
});
}
run(accessor: ServicesAccessor): void {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).accept();
}
}
registerThemingParticipant((theme, collector) => {
let activeRecordingColor: Color | undefined;
let activeRecordingDimmedColor: Color | undefined;
if (theme.type === ColorScheme.LIGHT || theme.type === ColorScheme.DARK) {
activeRecordingColor = theme.getColor(ACTIVITY_BAR_BADGE_BACKGROUND) ?? theme.getColor(focusBorder);
activeRecordingDimmedColor = activeRecordingColor?.transparent(0.4);
} else {
activeRecordingColor = theme.getColor(contrastBorder);
activeRecordingDimmedColor = theme.getColor(contrastBorder);
}
// Show a "microphone" icon when recording is in progress that glows via outline.
collector.addRule(`
.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover),
.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover) {
color: ${activeRecordingColor};
outline: 1px solid ${activeRecordingColor};
outline-offset: -1px;
animation: pulseAnimation 1s infinite;
border-radius: 50%;
}
@keyframes pulseAnimation {
0% {
outline-width: 1px;
}
50% {
outline-width: 3px;
outline-color: ${activeRecordingDimmedColor};
}
100% {
outline-width: 1px;
}
}
`);
});
| src/vs/workbench/contrib/chat/electron-sandbox/actions/voiceChatActions.ts | 1 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.007277362979948521,
0.0006836522370576859,
0.00016137491911649704,
0.000174830318428576,
0.0014283196069300175
] |
{
"id": 2,
"code_window": [
"\n",
"/*\n",
" * Replace with \"stop\" icon when hovering.\n",
" */\n",
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Replace with \"stop\" icon when hovering or when reduced motion is enabled.\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "replace",
"edit_start_line_idx": 22
} | #!/usr/bin/env bash
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
if [[ "$OSTYPE" == "darwin"* ]]; then
realpath() { [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"; }
VSCODE_PATH=$(dirname $(dirname $(dirname $(dirname $(dirname $(realpath "$0"))))))
else
VSCODE_PATH=$(dirname $(dirname $(dirname $(dirname $(dirname $(readlink -f $0))))))
fi
PROD_NAME="Code Server - Dev"
VERSION=""
COMMIT=""
EXEC_NAME="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")"
CLI_SCRIPT="$VSCODE_PATH/out/server-cli.js"
node "$CLI_SCRIPT" "$PROD_NAME" "$VERSION" "$COMMIT" "$EXEC_NAME" "$@"
| resources/server/bin-dev/remote-cli/code.sh | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.00017008667055051774,
0.00016900201444514096,
0.00016791735833976418,
0.00016900201444514096,
0.00000108465610537678
] |
{
"id": 2,
"code_window": [
"\n",
"/*\n",
" * Replace with \"stop\" icon when hovering.\n",
" */\n",
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Replace with \"stop\" icon when hovering or when reduced motion is enabled.\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "replace",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item {
display: block;
position: relative;
}
.monaco-workbench .activitybar > .content .composite-bar > .monaco-action-bar .action-item::before,
.monaco-workbench .activitybar > .content .composite-bar > .monaco-action-bar .action-item::after {
position: absolute;
content: '';
width: 48px;
height: 2px;
display: none;
background-color: transparent;
transition-property: background-color;
transition-duration: 0ms;
transition-delay: 100ms;
}
.monaco-workbench .activitybar > .content.dragged-over .composite-bar > .monaco-action-bar .action-item::before,
.monaco-workbench .activitybar > .content.dragged-over .composite-bar > .monaco-action-bar .action-item::after {
display: block;
}
.monaco-workbench .activitybar > .content > .composite-bar > .monaco-action-bar .action-item::before {
top: 1px;
margin-top: -2px;
}
.monaco-workbench .activitybar > .content > .composite-bar > .monaco-action-bar .action-item::after {
bottom: 1px;
margin-bottom: -2px;
}
.monaco-workbench .activitybar > .content > .composite-bar > .monaco-action-bar .action-item:first-of-type::before {
top: 2px;
margin-top: -2px;
}
.monaco-workbench .activitybar > .content > .composite-bar > .monaco-action-bar .action-item:last-of-type::after {
bottom: 2px;
margin-bottom: -2px;
}
.monaco-workbench .activitybar > .content > .composite-bar > .monaco-action-bar .action-item.top::before,
.monaco-workbench .activitybar > .content > .composite-bar > .monaco-action-bar .action-item.top::after,
.monaco-workbench .activitybar > .content > .composite-bar > .monaco-action-bar .action-item.bottom::before,
.monaco-workbench .activitybar > .content > .composite-bar > .monaco-action-bar .action-item.bottom::after {
transition-delay: 0s;
}
.monaco-workbench .activitybar > .content > .composite-bar > .monaco-action-bar .action-item.bottom + .action-item::before,
.monaco-workbench .activitybar > .content > .composite-bar > .monaco-action-bar .action-item.top::before,
.monaco-workbench .activitybar > .content > .composite-bar > .monaco-action-bar .action-item:last-of-type.bottom::after,
.monaco-workbench .activitybar > .content.dragged-over-head > .composite-bar > .monaco-action-bar .action-item:first-of-type::before,
.monaco-workbench .activitybar > .content.dragged-over-tail > .composite-bar > .monaco-action-bar .action-item:last-of-type::after {
background-color: var(--insert-border-color);
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-label {
position: relative;
z-index: 1;
display: flex;
overflow: hidden;
width: 48px;
height: 48px;
margin-right: 0;
box-sizing: border-box;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-label:not(.codicon) {
font-size: 15px;
line-height: 40px;
padding: 0 0 0 48px;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-label.codicon {
font-size: 24px;
align-items: center;
justify-content: center;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.active .action-label.codicon,
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item:focus .action-label.codicon,
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item:hover .action-label.codicon {
color: var(--vscode-activityBar-foreground) !important;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.active .action-label.uri-icon,
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item:focus .action-label.uri-icon,
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item:hover .action-label.uri-icon {
background-color: var(--vscode-activityBar-foreground) !important;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.checked .active-item-indicator:before,
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item:focus .active-item-indicator:before {
content: "";
position: absolute;
z-index: 1;
top: 0;
height: 100%;
width: 0;
border-left: 2px solid;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.checked .active-item-indicator:before {
top: 0;
height: 100%;
}
/* Hides active elements in high contrast mode */
.monaco-workbench.hc-black .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator.action-item,
.monaco-workbench.hc-light .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator {
display: none;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.clicked:focus:before {
border-left: none !important; /* no focus feedback when using mouse */
}
.monaco-workbench .activitybar.left > .content :not(.monaco-menu) > .monaco-action-bar .action-item .active-item-indicator:before{
left: 0;
}
.monaco-workbench .activitybar.right > .content :not(.monaco-menu) > .monaco-action-bar .action-item .active-item-indicator:before {
right: 0;
}
/* Hides outline on HC as focus is handled by border */
.monaco-workbench.hc-black .activitybar.left > .content :not(.monaco-menu) > .monaco-action-bar .action-item:focus:before,
.monaco-workbench.hc-black .activitybar.right > .content :not(.monaco-menu) > .monaco-action-bar .action-item:focus:before,
.monaco-workbench.hc-light .activitybar.left > .content :not(.monaco-menu) > .monaco-action-bar .action-item:focus:before,
.monaco-workbench.hc-light .activitybar.right > .content :not(.monaco-menu) > .monaco-action-bar .action-item:focus:before {
outline: none;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .profile-badge,
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .active-item-indicator,
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .badge {
position: absolute;
top: 0;
bottom: 0;
margin: auto;
left: 0;
overflow: hidden;
width: 100%;
height: 100%;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .active-item-indicator,
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .badge {
z-index: 2;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .profile-badge {
z-index: 1;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .active-item-indicator {
pointer-events: none;
}
.monaco-workbench.border .activitybar.right > .content :not(.monaco-menu) > .monaco-action-bar .active-item-indicator {
left: -2px;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .badge .badge-content {
position: absolute;
top: 24px;
right: 8px;
font-size: 9px;
font-weight: 600;
min-width: 8px;
height: 16px;
line-height: 16px;
padding: 0 4px;
border-radius: 20px;
text-align: center;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .profile-badge .profile-icon-overlay {
position: absolute;
top: 27px;
right: 6px;
background-color: var(--vscode-activityBar-background);
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .profile-badge .profile-icon-overlay .codicon {
color: var(--vscode-activityBar-inactiveForeground);
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.active .profile-badge .profile-icon-overlay .codicon,
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item:focus .profile-badge .profile-icon-overlay .codicon,
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item:hover .profile-badge .profile-icon-overlay .codicon {
color: var(--vscode-activityBar-foreground) !important;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .profile-badge .profile-text-overlay {
position: absolute;
font-weight: 600;
font-size: 9px;
line-height: 10px;
top: 24px;
right: 6px;
padding: 2px 3px;
border-radius: 7px;
background-color: var(--vscode-profileBadge-background);
color: var(--vscode-profileBadge-foreground);
border: 2px solid var(--vscode-activityBar-background);
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item:active .profile-text-overlay,
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item:focus .profile-text-overlay,
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item:hover .profile-text-overlay {
color: var(--vscode-activityBar-foreground);
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .badge .codicon.badge-content {
font-size: 12px;
font-weight: unset;
padding: 0;
justify-content: center;
}
.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .badge .codicon.badge-content::before {
text-align: center;
vertical-align: baseline;
}
/* Right aligned */
.monaco-workbench .activitybar.right>.content :not(.monaco-menu)>.monaco-action-bar .profile-badge,
.monaco-workbench .activitybar.right > .content :not(.monaco-menu) > .monaco-action-bar .badge {
left: auto;
right: 0;
}
| src/vs/workbench/browser/parts/activitybar/media/activityaction.css | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.008553068153560162,
0.0021667114924639463,
0.00016954680904746056,
0.001512455870397389,
0.0022295061498880386
] |
{
"id": 2,
"code_window": [
"\n",
"/*\n",
" * Replace with \"stop\" icon when hovering.\n",
" */\n",
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Replace with \"stop\" icon when hovering or when reduced motion is enabled.\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "replace",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as array from './arrays';
export function equals(one: any, other: any): boolean {
if (one === other) {
return true;
}
if (one === null || one === undefined || other === null || other === undefined) {
return false;
}
if (typeof one !== typeof other) {
return false;
}
if (typeof one !== 'object') {
return false;
}
if (Array.isArray(one) !== Array.isArray(other)) {
return false;
}
if (Array.isArray(one)) {
return array.equals(one, other, equals);
} else {
const oneKeys: string[] = [];
for (const key in one) {
oneKeys.push(key);
}
oneKeys.sort();
const otherKeys: string[] = [];
for (const key in other) {
otherKeys.push(key);
}
otherKeys.sort();
if (!array.equals(oneKeys, otherKeys)) {
return false;
}
return oneKeys.every(key => equals(one[key], other[key]));
}
}
| extensions/typescript-language-features/src/utils/objects.ts | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.00017352710710838437,
0.0001698811975074932,
0.00016853217675816268,
0.00016860643518157303,
0.0000019298963707115036
] |
{
"id": 3,
"code_window": [
" */\n",
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before {\n",
"\tcontent: \"\\ead7\"; /* use `debug-stop` icon unicode for hovering over running voice recording */\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tcontent: \"\\ead7\";\n",
"}\n",
".monaco-workbench.reduce-motion .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before,\n",
".monaco-workbench.reduce-motion .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before {\n",
"\tcontent: \"\\ead7\";\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "replace",
"edit_start_line_idx": 26
} | /*---------------------------------------------------------------------------------------------
* 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/voiceChatActions';
import { Event } from 'vs/base/common/event';
import { firstOrDefault } from 'vs/base/common/arrays';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { Codicon } from 'vs/base/common/codicons';
import { DisposableStore, toDisposable } from 'vs/base/common/lifecycle';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { localize } from 'vs/nls';
import { Action2, MenuId } from 'vs/platform/actions/common/actions';
import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { spinningLoading } from 'vs/platform/theme/common/iconRegistry';
import { CHAT_CATEGORY } from 'vs/workbench/contrib/chat/browser/actions/chatActions';
import { IChatWidget, IChatWidgetService, IQuickChatService } from 'vs/workbench/contrib/chat/browser/chat';
import { IChatService } from 'vs/workbench/contrib/chat/common/chatService';
import { MENU_INLINE_CHAT_WIDGET } from 'vs/workbench/contrib/inlineChat/common/inlineChat';
import { CONTEXT_PROVIDER_EXISTS } from 'vs/workbench/contrib/chat/common/chatContextKeys';
import { InlineChatController } from 'vs/workbench/contrib/inlineChat/browser/inlineChatController';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { getCodeEditor } from 'vs/editor/browser/editorBrowser';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { ActiveEditorContext } from 'vs/workbench/common/contextkeys';
import { IViewsService } from 'vs/workbench/common/views';
import { IChatContributionService } from 'vs/workbench/contrib/chat/common/chatContributionService';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { KeyCode } from 'vs/base/common/keyCodes';
import { isExecuteActionContext } from 'vs/workbench/contrib/chat/browser/actions/chatExecuteActions';
import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService';
import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService';
import { RunOnceScheduler } from 'vs/base/common/async';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { ACTIVITY_BAR_BADGE_BACKGROUND } from 'vs/workbench/common/theme';
import { ColorScheme } from 'vs/platform/theme/common/theme';
import { Color } from 'vs/base/common/color';
import { contrastBorder, focusBorder } from 'vs/platform/theme/common/colorRegistry';
const CONTEXT_VOICE_CHAT_GETTING_READY = new RawContextKey<boolean>('voiceChatGettingReady', false, { type: 'boolean', description: localize('voiceChatGettingReady', "True when getting ready for receiving voice input from the microphone for voice chat.") });
const CONTEXT_VOICE_CHAT_IN_PROGRESS = new RawContextKey<boolean>('voiceChatInProgress', false, { type: 'boolean', description: localize('voiceChatInProgress', "True when voice recording from microphone is in progress for voice chat.") });
const CONTEXT_QUICK_VOICE_CHAT_IN_PROGRESS = new RawContextKey<boolean>('quickVoiceChatInProgress', false, { type: 'boolean', description: localize('quickVoiceChatInProgress', "True when voice recording from microphone is in progress for quick chat.") });
const CONTEXT_INLINE_VOICE_CHAT_IN_PROGRESS = new RawContextKey<boolean>('inlineVoiceChatInProgress', false, { type: 'boolean', description: localize('inlineVoiceChatInProgress', "True when voice recording from microphone is in progress for inline chat.") });
const CONTEXT_VOICE_CHAT_IN_VIEW_IN_PROGRESS = new RawContextKey<boolean>('voiceChatInViewInProgress', false, { type: 'boolean', description: localize('voiceChatInViewInProgress', "True when voice recording from microphone is in progress in the chat view.") });
const CONTEXT_VOICE_CHAT_IN_EDITOR_IN_PROGRESS = new RawContextKey<boolean>('voiceChatInEditorInProgress', false, { type: 'boolean', description: localize('voiceChatInEditorInProgress', "True when voice recording from microphone is in progress in the chat editor.") });
type VoiceChatSessionContext = 'inline' | 'quick' | 'view' | 'editor';
interface IVoiceChatSessionController {
readonly onDidAcceptInput: Event<unknown>;
readonly onDidCancelInput: Event<unknown>;
readonly context: VoiceChatSessionContext;
focusInput(): void;
acceptInput(): void;
updateInput(text: string): void;
setInputPlaceholder(text: string): void;
clearInputPlaceholder(): void;
}
class VoiceChatSessionControllerFactory {
static create(accessor: ServicesAccessor, context: 'inline'): Promise<IVoiceChatSessionController | undefined>;
static create(accessor: ServicesAccessor, context: 'quick'): Promise<IVoiceChatSessionController | undefined>;
static create(accessor: ServicesAccessor, context: 'view'): Promise<IVoiceChatSessionController | undefined>;
static create(accessor: ServicesAccessor, context: 'focused'): Promise<IVoiceChatSessionController | undefined>;
static async create(accessor: ServicesAccessor, context: 'inline' | 'quick' | 'view' | 'focused'): Promise<IVoiceChatSessionController | undefined> {
const chatWidgetService = accessor.get(IChatWidgetService);
const chatService = accessor.get(IChatService);
const viewsService = accessor.get(IViewsService);
const chatContributionService = accessor.get(IChatContributionService);
const editorService = accessor.get(IEditorService);
const quickChatService = accessor.get(IQuickChatService);
const layoutService = accessor.get(IWorkbenchLayoutService);
// Currently Focused Context
if (context === 'focused') {
// Try with the chat widget service, which currently
// only supports the chat view and quick chat
// https://github.com/microsoft/vscode/issues/191191
const chatInput = chatWidgetService.lastFocusedWidget;
if (chatInput?.hasInputFocus()) {
// Unfortunately there does not seem to be a better way
// to figure out if the chat widget is in a part or picker
if (
layoutService.hasFocus(Parts.SIDEBAR_PART) ||
layoutService.hasFocus(Parts.PANEL_PART) ||
layoutService.hasFocus(Parts.AUXILIARYBAR_PART)
) {
return VoiceChatSessionControllerFactory.doCreateForChatView(chatInput, viewsService, chatContributionService);
}
if (layoutService.hasFocus(Parts.EDITOR_PART)) {
return VoiceChatSessionControllerFactory.doCreateForChatEditor(chatInput, viewsService, chatContributionService);
}
return VoiceChatSessionControllerFactory.doCreateForQuickChat(chatInput, quickChatService);
}
// Try with the inline chat
const activeCodeEditor = getCodeEditor(editorService.activeTextEditorControl);
if (activeCodeEditor) {
const inlineChat = InlineChatController.get(activeCodeEditor);
if (inlineChat?.hasFocus()) {
return VoiceChatSessionControllerFactory.doCreateForInlineChat(inlineChat);
}
}
}
// View Chat
if (context === 'view') {
const provider = firstOrDefault(chatService.getProviderInfos());
if (provider) {
const chatView = await chatWidgetService.revealViewForProvider(provider.id);
if (chatView) {
return VoiceChatSessionControllerFactory.doCreateForChatView(chatView, viewsService, chatContributionService);
}
}
}
// Inline Chat
if (context === 'inline') {
const activeCodeEditor = getCodeEditor(editorService.activeTextEditorControl);
if (activeCodeEditor) {
const inlineChat = InlineChatController.get(activeCodeEditor);
if (inlineChat) {
return VoiceChatSessionControllerFactory.doCreateForInlineChat(inlineChat);
}
}
}
// Quick Chat
if (context === 'quick') {
quickChatService.open();
const quickChat = chatWidgetService.lastFocusedWidget;
if (quickChat) {
return VoiceChatSessionControllerFactory.doCreateForQuickChat(quickChat, quickChatService);
}
}
return undefined;
}
private static doCreateForChatView(chatView: IChatWidget, viewsService: IViewsService, chatContributionService: IChatContributionService): IVoiceChatSessionController {
return VoiceChatSessionControllerFactory.doCreateForChatViewOrEditor('view', chatView, viewsService, chatContributionService);
}
private static doCreateForChatEditor(chatView: IChatWidget, viewsService: IViewsService, chatContributionService: IChatContributionService): IVoiceChatSessionController {
return VoiceChatSessionControllerFactory.doCreateForChatViewOrEditor('editor', chatView, viewsService, chatContributionService);
}
private static doCreateForChatViewOrEditor(context: 'view' | 'editor', chatView: IChatWidget, viewsService: IViewsService, chatContributionService: IChatContributionService): IVoiceChatSessionController {
return {
context,
onDidAcceptInput: chatView.onDidAcceptInput,
// TODO@bpasero cancellation needs to work better for chat editors that are not view bound
onDidCancelInput: Event.filter(viewsService.onDidChangeViewVisibility, e => e.id === chatContributionService.getViewIdForProvider(chatView.providerId)),
focusInput: () => chatView.focusInput(),
acceptInput: () => chatView.acceptInput(),
updateInput: text => chatView.updateInput(text),
setInputPlaceholder: text => chatView.setInputPlaceholder(text),
clearInputPlaceholder: () => chatView.resetInputPlaceholder()
};
}
private static doCreateForQuickChat(quickChat: IChatWidget, quickChatService: IQuickChatService): IVoiceChatSessionController {
return {
context: 'quick',
onDidAcceptInput: quickChat.onDidAcceptInput,
onDidCancelInput: quickChatService.onDidClose,
focusInput: () => quickChat.focusInput(),
acceptInput: () => quickChat.acceptInput(),
updateInput: text => quickChat.updateInput(text),
setInputPlaceholder: text => quickChat.setInputPlaceholder(text),
clearInputPlaceholder: () => quickChat.resetInputPlaceholder()
};
}
private static doCreateForInlineChat(inlineChat: InlineChatController,): IVoiceChatSessionController {
const inlineChatSession = inlineChat.run();
return {
context: 'inline',
onDidAcceptInput: inlineChat.onDidAcceptInput,
onDidCancelInput: Event.any(
inlineChat.onDidCancelInput,
Event.fromPromise(inlineChatSession)
),
focusInput: () => inlineChat.focus(),
acceptInput: () => inlineChat.acceptInput(),
updateInput: text => inlineChat.updateInput(text),
setInputPlaceholder: text => inlineChat.setPlaceholder(text),
clearInputPlaceholder: () => inlineChat.resetPlaceholder()
};
}
}
interface ActiveVoiceChatSession {
readonly id: number;
readonly controller: IVoiceChatSessionController;
readonly disposables: DisposableStore;
}
class VoiceChatSessions {
private static instance: VoiceChatSessions | undefined = undefined;
static getInstance(instantiationService: IInstantiationService): VoiceChatSessions {
if (!VoiceChatSessions.instance) {
VoiceChatSessions.instance = instantiationService.createInstance(VoiceChatSessions);
}
return VoiceChatSessions.instance;
}
private voiceChatInProgressKey = CONTEXT_VOICE_CHAT_IN_PROGRESS.bindTo(this.contextKeyService);
private voiceChatGettingReadyKey = CONTEXT_VOICE_CHAT_GETTING_READY.bindTo(this.contextKeyService);
private quickVoiceChatInProgressKey = CONTEXT_QUICK_VOICE_CHAT_IN_PROGRESS.bindTo(this.contextKeyService);
private inlineVoiceChatInProgressKey = CONTEXT_INLINE_VOICE_CHAT_IN_PROGRESS.bindTo(this.contextKeyService);
private voiceChatInViewInProgressKey = CONTEXT_VOICE_CHAT_IN_VIEW_IN_PROGRESS.bindTo(this.contextKeyService);
private voiceChatInEditorInProgressKey = CONTEXT_VOICE_CHAT_IN_EDITOR_IN_PROGRESS.bindTo(this.contextKeyService);
private currentVoiceChatSession: ActiveVoiceChatSession | undefined = undefined;
private voiceChatSessionIds = 0;
constructor(
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@ISpeechService private readonly speechService: ISpeechService
) { }
async start(controller: IVoiceChatSessionController): Promise<void> {
this.stop();
const sessionId = ++this.voiceChatSessionIds;
const session = this.currentVoiceChatSession = {
id: sessionId,
controller,
disposables: new DisposableStore()
};
const cts = new CancellationTokenSource();
session.disposables.add(toDisposable(() => cts.dispose(true)));
session.disposables.add(controller.onDidAcceptInput(() => this.stop(sessionId, controller.context)));
session.disposables.add(controller.onDidCancelInput(() => this.stop(sessionId, controller.context)));
controller.updateInput('');
controller.focusInput();
this.voiceChatGettingReadyKey.set(true);
const speechToTextSession = session.disposables.add(this.speechService.createSpeechToTextSession(cts.token));
let transcription: string = '';
const acceptTranscriptionScheduler = session.disposables.add(new RunOnceScheduler(() => session.controller.acceptInput(), 1200));
session.disposables.add(speechToTextSession.onDidChange(({ status, text }) => {
if (cts.token.isCancellationRequested) {
return;
}
switch (status) {
case SpeechToTextStatus.Started:
this.onDidSpeechToTextSessionStart(controller, session.disposables);
break;
case SpeechToTextStatus.Recognizing:
if (text) {
session.controller.updateInput([transcription, text].join(' '));
acceptTranscriptionScheduler.cancel();
}
break;
case SpeechToTextStatus.Recognized:
if (text) {
transcription = [transcription, text].join(' ');
session.controller.updateInput(transcription);
acceptTranscriptionScheduler.schedule();
}
break;
case SpeechToTextStatus.Stopped:
this.stop(session.id, controller.context);
break;
}
}));
}
private onDidSpeechToTextSessionStart(controller: IVoiceChatSessionController, disposables: DisposableStore): void {
this.voiceChatGettingReadyKey.set(false);
this.voiceChatInProgressKey.set(true);
switch (controller.context) {
case 'inline':
this.inlineVoiceChatInProgressKey.set(true);
break;
case 'quick':
this.quickVoiceChatInProgressKey.set(true);
break;
case 'view':
this.voiceChatInViewInProgressKey.set(true);
break;
case 'editor':
this.voiceChatInEditorInProgressKey.set(true);
break;
}
let dotCount = 0;
const updatePlaceholder = () => {
dotCount = (dotCount + 1) % 4;
controller.setInputPlaceholder(`${localize('listening', "I'm listening")}${'.'.repeat(dotCount)}`);
placeholderScheduler.schedule();
};
const placeholderScheduler = disposables.add(new RunOnceScheduler(updatePlaceholder, 500));
updatePlaceholder();
}
stop(voiceChatSessionId = this.voiceChatSessionIds, context?: VoiceChatSessionContext): void {
if (
!this.currentVoiceChatSession ||
this.voiceChatSessionIds !== voiceChatSessionId ||
(context && this.currentVoiceChatSession.controller.context !== context)
) {
return;
}
this.currentVoiceChatSession.controller.clearInputPlaceholder();
this.currentVoiceChatSession.disposables.dispose();
this.currentVoiceChatSession = undefined;
this.voiceChatGettingReadyKey.set(false);
this.voiceChatInProgressKey.set(false);
this.quickVoiceChatInProgressKey.set(false);
this.inlineVoiceChatInProgressKey.set(false);
this.voiceChatInViewInProgressKey.set(false);
this.voiceChatInEditorInProgressKey.set(false);
}
accept(voiceChatSessionId = this.voiceChatSessionIds): void {
if (
!this.currentVoiceChatSession ||
this.voiceChatSessionIds !== voiceChatSessionId
) {
return;
}
this.currentVoiceChatSession.controller.acceptInput();
}
}
export class VoiceChatInChatViewAction extends Action2 {
static readonly ID = 'workbench.action.chat.voiceChatInChatView';
constructor() {
super({
id: VoiceChatInChatViewAction.ID,
title: {
value: localize('workbench.action.chat.voiceChatInView.label', "Voice Chat in Chat View"),
original: 'Voice Chat in Chat View'
},
category: CHAT_CATEGORY,
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_PROVIDER_EXISTS),
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const instantiationService = accessor.get(IInstantiationService);
const controller = await VoiceChatSessionControllerFactory.create(accessor, 'view');
if (controller) {
VoiceChatSessions.getInstance(instantiationService).start(controller);
}
}
}
export class InlineVoiceChatAction extends Action2 {
static readonly ID = 'workbench.action.chat.inlineVoiceChat';
constructor() {
super({
id: InlineVoiceChatAction.ID,
title: {
value: localize('workbench.action.chat.inlineVoiceChat', "Inline Voice Chat"),
original: 'Inline Voice Chat'
},
category: CHAT_CATEGORY,
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_PROVIDER_EXISTS, ActiveEditorContext),
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const instantiationService = accessor.get(IInstantiationService);
const controller = await VoiceChatSessionControllerFactory.create(accessor, 'inline');
if (controller) {
VoiceChatSessions.getInstance(instantiationService).start(controller);
}
}
}
export class QuickVoiceChatAction extends Action2 {
static readonly ID = 'workbench.action.chat.quickVoiceChat';
constructor() {
super({
id: QuickVoiceChatAction.ID,
title: {
value: localize('workbench.action.chat.quickVoiceChat.label', "Quick Voice Chat"),
original: 'Quick Voice Chat'
},
category: CHAT_CATEGORY,
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_PROVIDER_EXISTS),
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const instantiationService = accessor.get(IInstantiationService);
const controller = await VoiceChatSessionControllerFactory.create(accessor, 'quick');
if (controller) {
VoiceChatSessions.getInstance(instantiationService).start(controller);
}
}
}
export class StartVoiceChatAction extends Action2 {
static readonly ID = 'workbench.action.chat.startVoiceChat';
constructor() {
super({
id: StartVoiceChatAction.ID,
title: {
value: localize('workbench.action.chat.startVoiceChat', "Start Voice Chat"),
original: 'Start Voice Chat'
},
icon: Codicon.mic,
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_GETTING_READY.negate()),
menu: [{
id: MenuId.ChatExecute,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_VIEW_IN_PROGRESS.negate(), CONTEXT_QUICK_VOICE_CHAT_IN_PROGRESS.negate(), CONTEXT_VOICE_CHAT_IN_EDITOR_IN_PROGRESS.negate()),
group: 'navigation',
order: -1
}, {
id: MENU_INLINE_CHAT_WIDGET,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_INLINE_VOICE_CHAT_IN_PROGRESS.negate()),
group: 'main',
order: -1
}]
});
}
async run(accessor: ServicesAccessor, context: unknown): Promise<void> {
const instantiationService = accessor.get(IInstantiationService);
const commandService = accessor.get(ICommandService);
if (isExecuteActionContext(context)) {
// if we already get a context when the action is executed
// from a toolbar within the chat widget, then make sure
// to move focus into the input field so that the controller
// is properly retrieved
// TODO@bpasero this will actually not work if the button
// is clicked from the inline editor while focus is in a
// chat input field in a view or picker
context.widget.focusInput();
}
const controller = await VoiceChatSessionControllerFactory.create(accessor, 'focused');
if (controller) {
VoiceChatSessions.getInstance(instantiationService).start(controller);
} else {
// fallback to Quick Voice Chat command
commandService.executeCommand(QuickVoiceChatAction.ID);
}
}
}
export class StopVoiceChatAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopVoiceChat';
constructor() {
super({
id: StopVoiceChatAction.ID,
title: {
value: localize('workbench.action.chat.stopVoiceChat.label', "Stop Voice Chat"),
original: 'Stop Voice Chat'
},
category: CHAT_CATEGORY,
f1: true,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib + 100,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_PROGRESS),
primary: KeyCode.Escape
},
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_PROGRESS)
});
}
run(accessor: ServicesAccessor): void {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).stop();
}
}
export class StopVoiceChatInChatViewAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopVoiceChatInChatView';
constructor() {
super({
id: StopVoiceChatInChatViewAction.ID,
title: {
value: localize('workbench.action.chat.stopVoiceChatInChatView.label', "Stop Voice Chat (Chat View)"),
original: 'Stop Voice Chat (Chat View)'
},
category: CHAT_CATEGORY,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib + 100,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_VIEW_IN_PROGRESS),
primary: KeyCode.Escape
},
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_VIEW_IN_PROGRESS),
icon: spinningLoading,
menu: [{
id: MenuId.ChatExecute,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_VIEW_IN_PROGRESS),
group: 'navigation',
order: -1
}]
});
}
run(accessor: ServicesAccessor): void {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).stop(undefined, 'view');
}
}
export class StopVoiceChatInChatEditorAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopVoiceChatInChatEditor';
constructor() {
super({
id: StopVoiceChatInChatEditorAction.ID,
title: {
value: localize('workbench.action.chat.stopVoiceChatInChatEditor.label', "Stop Voice Chat (Chat Editor)"),
original: 'Stop Voice Chat (Chat Editor)'
},
category: CHAT_CATEGORY,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib + 100,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_EDITOR_IN_PROGRESS),
primary: KeyCode.Escape
},
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_EDITOR_IN_PROGRESS),
icon: spinningLoading,
menu: [{
id: MenuId.ChatExecute,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_EDITOR_IN_PROGRESS),
group: 'navigation',
order: -1
}]
});
}
run(accessor: ServicesAccessor): void {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).stop(undefined, 'editor');
}
}
export class StopQuickVoiceChatAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopQuickVoiceChat';
constructor() {
super({
id: StopQuickVoiceChatAction.ID,
title: {
value: localize('workbench.action.chat.stopQuickVoiceChat.label', "Stop Voice Chat (Quick Chat)"),
original: 'Stop Voice Chat (Quick Chat)'
},
category: CHAT_CATEGORY,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib + 100,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_QUICK_VOICE_CHAT_IN_PROGRESS),
primary: KeyCode.Escape
},
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_QUICK_VOICE_CHAT_IN_PROGRESS),
icon: spinningLoading,
menu: [{
id: MenuId.ChatExecute,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_QUICK_VOICE_CHAT_IN_PROGRESS),
group: 'navigation',
order: -1
}]
});
}
run(accessor: ServicesAccessor): void {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).stop(undefined, 'quick');
}
}
export class StopInlineVoiceChatAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopInlineVoiceChat';
constructor() {
super({
id: StopInlineVoiceChatAction.ID,
title: {
value: localize('workbench.action.chat.stopInlineVoiceChat.label', "Stop Voice Chat (Inline Editor)"),
original: 'Stop Voice Chat (Inline Editor)'
},
category: CHAT_CATEGORY,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib + 100,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_INLINE_VOICE_CHAT_IN_PROGRESS),
primary: KeyCode.Escape
},
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_INLINE_VOICE_CHAT_IN_PROGRESS),
icon: spinningLoading,
menu: [{
id: MENU_INLINE_CHAT_WIDGET,
when: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_INLINE_VOICE_CHAT_IN_PROGRESS),
group: 'main',
order: -1
}]
});
}
run(accessor: ServicesAccessor): void {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).stop(undefined, 'inline');
}
}
export class StopVoiceChatAndSubmitAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopVoiceChatAndSubmit';
constructor() {
super({
id: StopVoiceChatAndSubmitAction.ID,
title: {
value: localize('workbench.action.chat.stopAndAcceptVoiceChat.label', "Stop Voice Chat and Submit"),
original: 'Stop Voice Chat and Submit'
},
category: CHAT_CATEGORY,
f1: true,
precondition: ContextKeyExpr.and(HasSpeechProvider, CONTEXT_VOICE_CHAT_IN_PROGRESS)
});
}
run(accessor: ServicesAccessor): void {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).accept();
}
}
registerThemingParticipant((theme, collector) => {
let activeRecordingColor: Color | undefined;
let activeRecordingDimmedColor: Color | undefined;
if (theme.type === ColorScheme.LIGHT || theme.type === ColorScheme.DARK) {
activeRecordingColor = theme.getColor(ACTIVITY_BAR_BADGE_BACKGROUND) ?? theme.getColor(focusBorder);
activeRecordingDimmedColor = activeRecordingColor?.transparent(0.4);
} else {
activeRecordingColor = theme.getColor(contrastBorder);
activeRecordingDimmedColor = theme.getColor(contrastBorder);
}
// Show a "microphone" icon when recording is in progress that glows via outline.
collector.addRule(`
.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover),
.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover) {
color: ${activeRecordingColor};
outline: 1px solid ${activeRecordingColor};
outline-offset: -1px;
animation: pulseAnimation 1s infinite;
border-radius: 50%;
}
@keyframes pulseAnimation {
0% {
outline-width: 1px;
}
50% {
outline-width: 3px;
outline-color: ${activeRecordingDimmedColor};
}
100% {
outline-width: 1px;
}
}
`);
});
| src/vs/workbench/contrib/chat/electron-sandbox/actions/voiceChatActions.ts | 1 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.005456310696899891,
0.00040452604298479855,
0.00016029801918193698,
0.00017015432240441442,
0.0007422795169986784
] |
{
"id": 3,
"code_window": [
" */\n",
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before {\n",
"\tcontent: \"\\ead7\"; /* use `debug-stop` icon unicode for hovering over running voice recording */\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tcontent: \"\\ead7\";\n",
"}\n",
".monaco-workbench.reduce-motion .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before,\n",
".monaco-workbench.reduce-motion .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before {\n",
"\tcontent: \"\\ead7\";\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "replace",
"edit_start_line_idx": 26
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IExternalTerminalService } from 'vs/platform/externalTerminal/common/externalTerminal';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
export const IExternalTerminalMainService = createDecorator<IExternalTerminalMainService>('externalTerminal');
export interface IExternalTerminalMainService extends IExternalTerminalService {
readonly _serviceBrand: undefined;
}
| src/vs/platform/externalTerminal/electron-main/externalTerminal.ts | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.00017681594181340188,
0.00017099831893574446,
0.00016518069605808705,
0.00017099831893574446,
0.0000058176228776574135
] |
{
"id": 3,
"code_window": [
" */\n",
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before {\n",
"\tcontent: \"\\ead7\"; /* use `debug-stop` icon unicode for hovering over running voice recording */\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tcontent: \"\\ead7\";\n",
"}\n",
".monaco-workbench.reduce-motion .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before,\n",
".monaco-workbench.reduce-motion .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before {\n",
"\tcontent: \"\\ead7\";\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "replace",
"edit_start_line_idx": 26
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { IEditorOptions as ICodeEditorOptions } from 'vs/editor/common/config/editorOptions';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfiguration';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IEditorOpenContext } from 'vs/workbench/common/editor';
import { AbstractTextResourceEditor } from 'vs/workbench/browser/parts/editor/textResourceEditor';
import { OUTPUT_VIEW_ID, CONTEXT_IN_OUTPUT, IOutputChannel, CONTEXT_OUTPUT_SCROLL_LOCK } from 'vs/workbench/services/output/common/output';
import { IThemeService, registerThemingParticipant, IColorTheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { CancellationToken } from 'vs/base/common/cancellation';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { CursorChangeReason } from 'vs/editor/common/cursorEvents';
import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPane';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IViewDescriptorService } from 'vs/workbench/common/views';
import { TextResourceEditorInput } from 'vs/workbench/common/editor/textResourceEditorInput';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme';
import { editorBackground } from 'vs/platform/theme/common/colorRegistry';
import { Dimension } from 'vs/base/browser/dom';
import { ITextEditorOptions } from 'vs/platform/editor/common/editor';
import { CancelablePromise, createCancelablePromise } from 'vs/base/common/async';
import { IFileService } from 'vs/platform/files/common/files';
import { ResourceContextKey } from 'vs/workbench/common/contextkeys';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
export class OutputViewPane extends ViewPane {
private readonly editor: OutputEditor;
private channelId: string | undefined;
private editorPromise: CancelablePromise<OutputEditor> | null = null;
private readonly scrollLockContextKey: IContextKey<boolean>;
get scrollLock(): boolean { return !!this.scrollLockContextKey.get(); }
set scrollLock(scrollLock: boolean) { this.scrollLockContextKey.set(scrollLock); }
constructor(
options: IViewPaneOptions,
@IKeybindingService keybindingService: IKeybindingService,
@IContextMenuService contextMenuService: IContextMenuService,
@IConfigurationService configurationService: IConfigurationService,
@IContextKeyService contextKeyService: IContextKeyService,
@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
@IInstantiationService instantiationService: IInstantiationService,
@IOpenerService openerService: IOpenerService,
@IThemeService themeService: IThemeService,
@ITelemetryService telemetryService: ITelemetryService,
) {
super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService);
this.scrollLockContextKey = CONTEXT_OUTPUT_SCROLL_LOCK.bindTo(this.contextKeyService);
const editorInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.scopedContextKeyService]));
this.editor = editorInstantiationService.createInstance(OutputEditor);
this._register(this.editor.onTitleAreaUpdate(() => {
this.updateTitle(this.editor.getTitle());
this.updateActions();
}));
this._register(this.onDidChangeBodyVisibility(() => this.onDidChangeVisibility(this.isBodyVisible())));
}
showChannel(channel: IOutputChannel, preserveFocus: boolean): void {
if (this.channelId !== channel.id) {
this.setInput(channel);
}
if (!preserveFocus) {
this.focus();
}
}
override focus(): void {
super.focus();
this.editorPromise?.then(() => this.editor.focus());
}
protected override renderBody(container: HTMLElement): void {
super.renderBody(container);
this.editor.create(container);
container.classList.add('output-view');
const codeEditor = <ICodeEditor>this.editor.getControl();
codeEditor.setAriaOptions({ role: 'document', activeDescendant: undefined });
this._register(codeEditor.onDidChangeModelContent(() => {
if (!this.scrollLock) {
this.editor.revealLastLine();
}
}));
this._register(codeEditor.onDidChangeCursorPosition((e) => {
if (e.reason !== CursorChangeReason.Explicit) {
return;
}
if (!this.configurationService.getValue('output.smartScroll.enabled')) {
return;
}
const model = codeEditor.getModel();
if (model) {
const newPositionLine = e.position.lineNumber;
const lastLine = model.getLineCount();
this.scrollLock = lastLine !== newPositionLine;
}
}));
}
protected override layoutBody(height: number, width: number): void {
super.layoutBody(height, width);
this.editor.layout(new Dimension(width, height));
}
private onDidChangeVisibility(visible: boolean): void {
this.editor.setVisible(visible);
if (!visible) {
this.clearInput();
}
}
private setInput(channel: IOutputChannel): void {
this.channelId = channel.id;
const input = this.createInput(channel);
if (!this.editor.input || !input.matches(this.editor.input)) {
this.editorPromise?.cancel();
this.editorPromise = createCancelablePromise(token => this.editor.setInput(this.createInput(channel), { preserveFocus: true }, Object.create(null), token)
.then(() => this.editor));
}
}
private clearInput(): void {
this.channelId = undefined;
this.editor.clearInput();
this.editorPromise = null;
}
private createInput(channel: IOutputChannel): TextResourceEditorInput {
return this.instantiationService.createInstance(TextResourceEditorInput, channel.uri, nls.localize('output model title', "{0} - Output", channel.label), nls.localize('channel', "Output channel for '{0}'", channel.label), undefined, undefined);
}
}
class OutputEditor extends AbstractTextResourceEditor {
private readonly resourceContext: ResourceContextKey;
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IInstantiationService instantiationService: IInstantiationService,
@IStorageService storageService: IStorageService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ITextResourceConfigurationService textResourceConfigurationService: ITextResourceConfigurationService,
@IThemeService themeService: IThemeService,
@IEditorGroupsService editorGroupService: IEditorGroupsService,
@IEditorService editorService: IEditorService,
@IFileService fileService: IFileService,
@IContextKeyService contextKeyService: IContextKeyService,
) {
super(OUTPUT_VIEW_ID, telemetryService, instantiationService, storageService, textResourceConfigurationService, themeService, editorGroupService, editorService, fileService);
this.resourceContext = this._register(instantiationService.createInstance(ResourceContextKey));
}
override getId(): string {
return OUTPUT_VIEW_ID;
}
override getTitle(): string {
return nls.localize('output', "Output");
}
protected override getConfigurationOverrides(): ICodeEditorOptions {
const options = super.getConfigurationOverrides();
options.wordWrap = 'on'; // all output editors wrap
options.lineNumbers = 'off'; // all output editors hide line numbers
options.glyphMargin = false;
options.lineDecorationsWidth = 20;
options.rulers = [];
options.folding = false;
options.scrollBeyondLastLine = false;
options.renderLineHighlight = 'none';
options.minimap = { enabled: false };
options.renderValidationDecorations = 'editable';
options.padding = undefined;
options.readOnly = true;
options.domReadOnly = true;
options.unicodeHighlight = {
nonBasicASCII: false,
invisibleCharacters: false,
ambiguousCharacters: false,
};
const outputConfig = this.configurationService.getValue<any>('[Log]');
if (outputConfig) {
if (outputConfig['editor.minimap.enabled']) {
options.minimap = { enabled: true };
}
if ('editor.wordWrap' in outputConfig) {
options.wordWrap = outputConfig['editor.wordWrap'];
}
}
return options;
}
protected getAriaLabel(): string {
return this.input ? this.input.getAriaLabel() : nls.localize('outputViewAriaLabel', "Output panel");
}
override async setInput(input: TextResourceEditorInput, options: ITextEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> {
const focus = !(options && options.preserveFocus);
if (this.input && input.matches(this.input)) {
return;
}
if (this.input) {
// Dispose previous input (Output panel is not a workbench editor)
this.input.dispose();
}
await super.setInput(input, options, context, token);
this.resourceContext.set(input.resource);
if (focus) {
this.focus();
}
this.revealLastLine();
}
override clearInput(): void {
if (this.input) {
// Dispose current input (Output panel is not a workbench editor)
this.input.dispose();
}
super.clearInput();
this.resourceContext.reset();
}
protected override createEditor(parent: HTMLElement): void {
parent.setAttribute('role', 'document');
super.createEditor(parent);
const scopedContextKeyService = this.scopedContextKeyService;
if (scopedContextKeyService) {
CONTEXT_IN_OUTPUT.bindTo(scopedContextKeyService).set(true);
}
}
}
registerThemingParticipant((theme: IColorTheme, collector: ICssStyleCollector) => {
// Sidebar background for the output view
const sidebarBackground = theme.getColor(SIDE_BAR_BACKGROUND);
if (sidebarBackground && sidebarBackground !== theme.getColor(editorBackground)) {
collector.addRule(`
.monaco-workbench .part.sidebar .output-view .monaco-editor,
.monaco-workbench .part.sidebar .output-view .monaco-editor .margin,
.monaco-workbench .part.sidebar .output-view .monaco-editor .monaco-editor-background {
background-color: ${sidebarBackground};
}
`);
}
});
| src/vs/workbench/contrib/output/browser/outputView.ts | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.00047007171087898314,
0.00018061049922835082,
0.000162280528456904,
0.00017084606224671006,
0.000055802207498345524
] |
{
"id": 3,
"code_window": [
" */\n",
".monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before,\n",
".monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before {\n",
"\tcontent: \"\\ead7\"; /* use `debug-stop` icon unicode for hovering over running voice recording */\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tcontent: \"\\ead7\";\n",
"}\n",
".monaco-workbench.reduce-motion .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before,\n",
".monaco-workbench.reduce-motion .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before {\n",
"\tcontent: \"\\ead7\";\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css",
"type": "replace",
"edit_start_line_idx": 26
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ModifierKeyEmitter } from 'vs/base/browser/dom';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { RunOnceScheduler } from 'vs/base/common/async';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { onUnexpectedError } from 'vs/base/common/errors';
import { DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { LRUCache } from 'vs/base/common/map';
import { IRange } from 'vs/base/common/range';
import { assertType } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { IActiveCodeEditor, ICodeEditor, IEditorMouseEvent, MouseTargetType } from 'vs/editor/browser/editorBrowser';
import { ClassNameReference, CssProperties, DynamicCssRules } from 'vs/editor/browser/editorDom';
import { StableEditorScrollState } from 'vs/editor/browser/stableEditorScroll';
import { EditorOption, EDITOR_FONT_DEFAULTS } from 'vs/editor/common/config/editorOptions';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Range } from 'vs/editor/common/core/range';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import * as languages from 'vs/editor/common/languages';
import { IModelDeltaDecoration, InjectedTextCursorStops, InjectedTextOptions, ITextModel, TrackedRangeStickiness } from 'vs/editor/common/model';
import { ModelDecorationInjectedTextOptions } from 'vs/editor/common/model/textModel';
import { IFeatureDebounceInformation, ILanguageFeatureDebounceService } from 'vs/editor/common/services/languageFeatureDebounce';
import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { ClickLinkGesture, ClickLinkMouseEvent } from 'vs/editor/contrib/gotoSymbol/browser/link/clickLinkGesture';
import { InlayHintAnchor, InlayHintItem, InlayHintsFragments } from 'vs/editor/contrib/inlayHints/browser/inlayHints';
import { goToDefinitionWithLocation, showGoToContextMenu } from 'vs/editor/contrib/inlayHints/browser/inlayHintsLocations';
import { CommandsRegistry, ICommandService } from 'vs/platform/commands/common/commands';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import * as colors from 'vs/platform/theme/common/colorRegistry';
import { themeColorFromId } from 'vs/platform/theme/common/themeService';
// --- hint caching service (per session)
class InlayHintsCache {
declare readonly _serviceBrand: undefined;
private readonly _entries = new LRUCache<string, InlayHintItem[]>(50);
get(model: ITextModel): InlayHintItem[] | undefined {
const key = InlayHintsCache._key(model);
return this._entries.get(key);
}
set(model: ITextModel, value: InlayHintItem[]): void {
const key = InlayHintsCache._key(model);
this._entries.set(key, value);
}
private static _key(model: ITextModel): string {
return `${model.uri.toString()}/${model.getVersionId()}`;
}
}
interface IInlayHintsCache extends InlayHintsCache { }
const IInlayHintsCache = createDecorator<IInlayHintsCache>('IInlayHintsCache');
registerSingleton(IInlayHintsCache, InlayHintsCache, InstantiationType.Delayed);
// --- rendered label
export class RenderedInlayHintLabelPart {
constructor(readonly item: InlayHintItem, readonly index: number) { }
get part() {
const label = this.item.hint.label;
if (typeof label === 'string') {
return { label };
} else {
return label[this.index];
}
}
}
class ActiveInlayHintInfo {
constructor(readonly part: RenderedInlayHintLabelPart, readonly hasTriggerModifier: boolean) { }
}
type InlayHintDecorationRenderInfo = {
item: InlayHintItem;
decoration: IModelDeltaDecoration;
classNameRef: ClassNameReference;
};
const enum RenderMode {
Normal,
Invisible
}
// --- controller
export class InlayHintsController implements IEditorContribution {
static readonly ID: string = 'editor.contrib.InlayHints';
private static readonly _MAX_DECORATORS = 1500;
static get(editor: ICodeEditor): InlayHintsController | undefined {
return editor.getContribution<InlayHintsController>(InlayHintsController.ID) ?? undefined;
}
private readonly _disposables = new DisposableStore();
private readonly _sessionDisposables = new DisposableStore();
private readonly _debounceInfo: IFeatureDebounceInformation;
private readonly _decorationsMetadata = new Map<string, InlayHintDecorationRenderInfo>();
private readonly _ruleFactory = new DynamicCssRules(this._editor);
private _activeRenderMode = RenderMode.Normal;
private _activeInlayHintPart?: ActiveInlayHintInfo;
constructor(
private readonly _editor: ICodeEditor,
@ILanguageFeaturesService private readonly _languageFeaturesService: ILanguageFeaturesService,
@ILanguageFeatureDebounceService _featureDebounce: ILanguageFeatureDebounceService,
@IInlayHintsCache private readonly _inlayHintsCache: IInlayHintsCache,
@ICommandService private readonly _commandService: ICommandService,
@INotificationService private readonly _notificationService: INotificationService,
@IInstantiationService private readonly _instaService: IInstantiationService,
) {
this._debounceInfo = _featureDebounce.for(_languageFeaturesService.inlayHintsProvider, 'InlayHint', { min: 25 });
this._disposables.add(_languageFeaturesService.inlayHintsProvider.onDidChange(() => this._update()));
this._disposables.add(_editor.onDidChangeModel(() => this._update()));
this._disposables.add(_editor.onDidChangeModelLanguage(() => this._update()));
this._disposables.add(_editor.onDidChangeConfiguration(e => {
if (e.hasChanged(EditorOption.inlayHints)) {
this._update();
}
}));
this._update();
}
dispose(): void {
this._sessionDisposables.dispose();
this._removeAllDecorations();
this._disposables.dispose();
}
private _update(): void {
this._sessionDisposables.clear();
this._removeAllDecorations();
const options = this._editor.getOption(EditorOption.inlayHints);
if (options.enabled === 'off') {
return;
}
const model = this._editor.getModel();
if (!model || !this._languageFeaturesService.inlayHintsProvider.has(model)) {
return;
}
// iff possible, quickly update from cache
const cached = this._inlayHintsCache.get(model);
if (cached) {
this._updateHintsDecorators([model.getFullModelRange()], cached);
}
this._sessionDisposables.add(toDisposable(() => {
// cache items when switching files etc
if (!model.isDisposed()) {
this._cacheHintsForFastRestore(model);
}
}));
let cts: CancellationTokenSource | undefined;
const watchedProviders = new Set<languages.InlayHintsProvider>();
const scheduler = new RunOnceScheduler(async () => {
const t1 = Date.now();
cts?.dispose(true);
cts = new CancellationTokenSource();
const listener = model.onWillDispose(() => cts?.cancel());
try {
const myToken = cts.token;
const inlayHints = await InlayHintsFragments.create(this._languageFeaturesService.inlayHintsProvider, model, this._getHintsRanges(), myToken);
scheduler.delay = this._debounceInfo.update(model, Date.now() - t1);
if (myToken.isCancellationRequested) {
inlayHints.dispose();
return;
}
// listen to provider changes
for (const provider of inlayHints.provider) {
if (typeof provider.onDidChangeInlayHints === 'function' && !watchedProviders.has(provider)) {
watchedProviders.add(provider);
this._sessionDisposables.add(provider.onDidChangeInlayHints(() => {
if (!scheduler.isScheduled()) { // ignore event when request is already scheduled
scheduler.schedule();
}
}));
}
}
this._sessionDisposables.add(inlayHints);
this._updateHintsDecorators(inlayHints.ranges, inlayHints.items);
this._cacheHintsForFastRestore(model);
} catch (err) {
onUnexpectedError(err);
} finally {
cts.dispose();
listener.dispose();
}
}, this._debounceInfo.get(model));
this._sessionDisposables.add(scheduler);
this._sessionDisposables.add(toDisposable(() => cts?.dispose(true)));
scheduler.schedule(0);
this._sessionDisposables.add(this._editor.onDidScrollChange((e) => {
// update when scroll position changes
// uses scrollTopChanged has weak heuristic to differenatiate between scrolling due to
// typing or due to "actual" scrolling
if (e.scrollTopChanged || !scheduler.isScheduled()) {
scheduler.schedule();
}
}));
this._sessionDisposables.add(this._editor.onDidChangeModelContent((e) => {
// update less aggressive when typing
const delay = Math.max(scheduler.delay, 1250);
scheduler.schedule(delay);
}));
if (options.enabled === 'on') {
// different "on" modes: always
this._activeRenderMode = RenderMode.Normal;
} else {
// different "on" modes: offUnlessPressed, or onUnlessPressed
let defaultMode: RenderMode;
let altMode: RenderMode;
if (options.enabled === 'onUnlessPressed') {
defaultMode = RenderMode.Normal;
altMode = RenderMode.Invisible;
} else {
defaultMode = RenderMode.Invisible;
altMode = RenderMode.Normal;
}
this._activeRenderMode = defaultMode;
this._sessionDisposables.add(ModifierKeyEmitter.getInstance().event(e => {
if (!this._editor.hasModel()) {
return;
}
const newRenderMode = e.altKey && e.ctrlKey && !(e.shiftKey || e.metaKey) ? altMode : defaultMode;
if (newRenderMode !== this._activeRenderMode) {
this._activeRenderMode = newRenderMode;
const model = this._editor.getModel();
const copies = this._copyInlayHintsWithCurrentAnchor(model);
this._updateHintsDecorators([model.getFullModelRange()], copies);
scheduler.schedule(0);
}
}));
}
// mouse gestures
this._sessionDisposables.add(this._installDblClickGesture(() => scheduler.schedule(0)));
this._sessionDisposables.add(this._installLinkGesture());
this._sessionDisposables.add(this._installContextMenu());
}
private _installLinkGesture(): IDisposable {
const store = new DisposableStore();
const gesture = store.add(new ClickLinkGesture(this._editor));
// let removeHighlight = () => { };
const sessionStore = new DisposableStore();
store.add(sessionStore);
store.add(gesture.onMouseMoveOrRelevantKeyDown(e => {
const [mouseEvent] = e;
const labelPart = this._getInlayHintLabelPart(mouseEvent);
const model = this._editor.getModel();
if (!labelPart || !model) {
sessionStore.clear();
return;
}
// resolve the item
const cts = new CancellationTokenSource();
sessionStore.add(toDisposable(() => cts.dispose(true)));
labelPart.item.resolve(cts.token);
// render link => when the modifier is pressed and when there is a command or location
this._activeInlayHintPart = labelPart.part.command || labelPart.part.location
? new ActiveInlayHintInfo(labelPart, mouseEvent.hasTriggerModifier)
: undefined;
const lineNumber = model.validatePosition(labelPart.item.hint.position).lineNumber;
const range = new Range(lineNumber, 1, lineNumber, model.getLineMaxColumn(lineNumber));
const lineHints = this._getInlineHintsForRange(range);
this._updateHintsDecorators([range], lineHints);
sessionStore.add(toDisposable(() => {
this._activeInlayHintPart = undefined;
this._updateHintsDecorators([range], lineHints);
}));
}));
store.add(gesture.onCancel(() => sessionStore.clear()));
store.add(gesture.onExecute(async e => {
const label = this._getInlayHintLabelPart(e);
if (label) {
const part = label.part;
if (part.location) {
// location -> execute go to def
this._instaService.invokeFunction(goToDefinitionWithLocation, e, this._editor as IActiveCodeEditor, part.location);
} else if (languages.Command.is(part.command)) {
// command -> execute it
await this._invokeCommand(part.command, label.item);
}
}
}));
return store;
}
private _getInlineHintsForRange(range: Range) {
const lineHints = new Set<InlayHintItem>();
for (const data of this._decorationsMetadata.values()) {
if (range.containsRange(data.item.anchor.range)) {
lineHints.add(data.item);
}
}
return Array.from(lineHints);
}
private _installDblClickGesture(updateInlayHints: Function): IDisposable {
return this._editor.onMouseUp(async e => {
if (e.event.detail !== 2) {
return;
}
const part = this._getInlayHintLabelPart(e);
if (!part) {
return;
}
e.event.preventDefault();
await part.item.resolve(CancellationToken.None);
if (isNonEmptyArray(part.item.hint.textEdits)) {
const edits = part.item.hint.textEdits.map(edit => EditOperation.replace(Range.lift(edit.range), edit.text));
this._editor.executeEdits('inlayHint.default', edits);
updateInlayHints();
}
});
}
private _installContextMenu(): IDisposable {
return this._editor.onContextMenu(async e => {
if (!(e.event.target instanceof HTMLElement)) {
return;
}
const part = this._getInlayHintLabelPart(e);
if (part) {
await this._instaService.invokeFunction(showGoToContextMenu, this._editor, e.event.target, part);
}
});
}
private _getInlayHintLabelPart(e: IEditorMouseEvent | ClickLinkMouseEvent): RenderedInlayHintLabelPart | undefined {
if (e.target.type !== MouseTargetType.CONTENT_TEXT) {
return undefined;
}
const options = e.target.detail.injectedText?.options;
if (options instanceof ModelDecorationInjectedTextOptions && options?.attachedData instanceof RenderedInlayHintLabelPart) {
return options.attachedData;
}
return undefined;
}
private async _invokeCommand(command: languages.Command, item: InlayHintItem) {
try {
await this._commandService.executeCommand(command.id, ...(command.arguments ?? []));
} catch (err) {
this._notificationService.notify({
severity: Severity.Error,
source: item.provider.displayName,
message: err
});
}
}
private _cacheHintsForFastRestore(model: ITextModel): void {
const hints = this._copyInlayHintsWithCurrentAnchor(model);
this._inlayHintsCache.set(model, hints);
}
// return inlay hints but with an anchor that reflects "updates"
// that happened after receiving them, e.g adding new lines before a hint
private _copyInlayHintsWithCurrentAnchor(model: ITextModel): InlayHintItem[] {
const items = new Map<InlayHintItem, InlayHintItem>();
for (const [id, obj] of this._decorationsMetadata) {
if (items.has(obj.item)) {
// an inlay item can be rendered as multiple decorations
// but they will all uses the same range
continue;
}
const range = model.getDecorationRange(id);
if (range) {
// update range with whatever the editor has tweaked it to
const anchor = new InlayHintAnchor(range, obj.item.anchor.direction);
const copy = obj.item.with({ anchor });
items.set(obj.item, copy);
}
}
return Array.from(items.values());
}
private _getHintsRanges(): Range[] {
const extra = 30;
const model = this._editor.getModel()!;
const visibleRanges = this._editor.getVisibleRangesPlusViewportAboveBelow();
const result: Range[] = [];
for (const range of visibleRanges.sort(Range.compareRangesUsingStarts)) {
const extendedRange = model.validateRange(new Range(range.startLineNumber - extra, range.startColumn, range.endLineNumber + extra, range.endColumn));
if (result.length === 0 || !Range.areIntersectingOrTouching(result[result.length - 1], extendedRange)) {
result.push(extendedRange);
} else {
result[result.length - 1] = Range.plusRange(result[result.length - 1], extendedRange);
}
}
return result;
}
private _updateHintsDecorators(ranges: readonly Range[], items: readonly InlayHintItem[]): void {
// utils to collect/create injected text decorations
const newDecorationsData: InlayHintDecorationRenderInfo[] = [];
const addInjectedText = (item: InlayHintItem, ref: ClassNameReference, content: string, cursorStops: InjectedTextCursorStops, attachedData?: RenderedInlayHintLabelPart): void => {
const opts: InjectedTextOptions = {
content,
inlineClassNameAffectsLetterSpacing: true,
inlineClassName: ref.className,
cursorStops,
attachedData
};
newDecorationsData.push({
item,
classNameRef: ref,
decoration: {
range: item.anchor.range,
options: {
// className: "rangeHighlight", // DEBUG highlight to see to what range a hint is attached
description: 'InlayHint',
showIfCollapsed: item.anchor.range.isEmpty(), // "original" range is empty
collapseOnReplaceEdit: !item.anchor.range.isEmpty(),
stickiness: TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges,
[item.anchor.direction]: this._activeRenderMode === RenderMode.Normal ? opts : undefined
}
}
});
};
const addInjectedWhitespace = (item: InlayHintItem, isLast: boolean): void => {
const marginRule = this._ruleFactory.createClassNameRef({
width: `${(fontSize / 3) | 0}px`,
display: 'inline-block'
});
addInjectedText(item, marginRule, '\u200a', isLast ? InjectedTextCursorStops.Right : InjectedTextCursorStops.None);
};
//
const { fontSize, fontFamily, padding, isUniform } = this._getLayoutInfo();
const fontFamilyVar = '--code-editorInlayHintsFontFamily';
this._editor.getContainerDomNode().style.setProperty(fontFamilyVar, fontFamily);
for (const item of items) {
// whitespace leading the actual label
if (item.hint.paddingLeft) {
addInjectedWhitespace(item, false);
}
// the label with its parts
const parts: languages.InlayHintLabelPart[] = typeof item.hint.label === 'string'
? [{ label: item.hint.label }]
: item.hint.label;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
const isFirst = i === 0;
const isLast = i === parts.length - 1;
const cssProperties: CssProperties = {
fontSize: `${fontSize}px`,
fontFamily: `var(${fontFamilyVar}), ${EDITOR_FONT_DEFAULTS.fontFamily}`,
verticalAlign: isUniform ? 'baseline' : 'middle',
unicodeBidi: 'isolate'
};
if (isNonEmptyArray(item.hint.textEdits)) {
cssProperties.cursor = 'default';
}
this._fillInColors(cssProperties, item.hint);
if ((part.command || part.location) && this._activeInlayHintPart?.part.item === item && this._activeInlayHintPart.part.index === i) {
// active link!
cssProperties.textDecoration = 'underline';
if (this._activeInlayHintPart.hasTriggerModifier) {
cssProperties.color = themeColorFromId(colors.editorActiveLinkForeground);
cssProperties.cursor = 'pointer';
}
}
if (padding) {
if (isFirst && isLast) {
// only element
cssProperties.padding = `1px ${Math.max(1, fontSize / 4) | 0}px`;
cssProperties.borderRadius = `${(fontSize / 4) | 0}px`;
} else if (isFirst) {
// first element
cssProperties.padding = `1px 0 1px ${Math.max(1, fontSize / 4) | 0}px`;
cssProperties.borderRadius = `${(fontSize / 4) | 0}px 0 0 ${(fontSize / 4) | 0}px`;
} else if (isLast) {
// last element
cssProperties.padding = `1px ${Math.max(1, fontSize / 4) | 0}px 1px 0`;
cssProperties.borderRadius = `0 ${(fontSize / 4) | 0}px ${(fontSize / 4) | 0}px 0`;
} else {
cssProperties.padding = `1px 0 1px 0`;
}
}
addInjectedText(
item,
this._ruleFactory.createClassNameRef(cssProperties),
fixSpace(part.label),
isLast && !item.hint.paddingRight ? InjectedTextCursorStops.Right : InjectedTextCursorStops.None,
new RenderedInlayHintLabelPart(item, i)
);
}
// whitespace trailing the actual label
if (item.hint.paddingRight) {
addInjectedWhitespace(item, true);
}
if (newDecorationsData.length > InlayHintsController._MAX_DECORATORS) {
break;
}
}
// collect all decoration ids that are affected by the ranges
// and only update those decorations
const decorationIdsToReplace: string[] = [];
for (const range of ranges) {
for (const { id } of this._editor.getDecorationsInRange(range) ?? []) {
const metadata = this._decorationsMetadata.get(id);
if (metadata) {
decorationIdsToReplace.push(id);
metadata.classNameRef.dispose();
this._decorationsMetadata.delete(id);
}
}
}
const scrollState = StableEditorScrollState.capture(this._editor);
this._editor.changeDecorations(accessor => {
const newDecorationIds = accessor.deltaDecorations(decorationIdsToReplace, newDecorationsData.map(d => d.decoration));
for (let i = 0; i < newDecorationIds.length; i++) {
const data = newDecorationsData[i];
this._decorationsMetadata.set(newDecorationIds[i], data);
}
});
scrollState.restore(this._editor);
}
private _fillInColors(props: CssProperties, hint: languages.InlayHint): void {
if (hint.kind === languages.InlayHintKind.Parameter) {
props.backgroundColor = themeColorFromId(colors.editorInlayHintParameterBackground);
props.color = themeColorFromId(colors.editorInlayHintParameterForeground);
} else if (hint.kind === languages.InlayHintKind.Type) {
props.backgroundColor = themeColorFromId(colors.editorInlayHintTypeBackground);
props.color = themeColorFromId(colors.editorInlayHintTypeForeground);
} else {
props.backgroundColor = themeColorFromId(colors.editorInlayHintBackground);
props.color = themeColorFromId(colors.editorInlayHintForeground);
}
}
private _getLayoutInfo() {
const options = this._editor.getOption(EditorOption.inlayHints);
const padding = options.padding;
const editorFontSize = this._editor.getOption(EditorOption.fontSize);
const editorFontFamily = this._editor.getOption(EditorOption.fontFamily);
let fontSize = options.fontSize;
if (!fontSize || fontSize < 5 || fontSize > editorFontSize) {
fontSize = editorFontSize;
}
const fontFamily = options.fontFamily || editorFontFamily;
const isUniform = !padding
&& fontFamily === editorFontFamily
&& fontSize === editorFontSize;
return { fontSize, fontFamily, padding, isUniform };
}
private _removeAllDecorations(): void {
this._editor.removeDecorations(Array.from(this._decorationsMetadata.keys()));
for (const obj of this._decorationsMetadata.values()) {
obj.classNameRef.dispose();
}
this._decorationsMetadata.clear();
}
// --- accessibility
getInlayHintsForLine(line: number): InlayHintItem[] {
if (!this._editor.hasModel()) {
return [];
}
const set = new Set<languages.InlayHint>();
const result: InlayHintItem[] = [];
for (const deco of this._editor.getLineDecorations(line)) {
const data = this._decorationsMetadata.get(deco.id);
if (data && !set.has(data.item.hint)) {
set.add(data.item.hint);
result.push(data.item);
}
}
return result;
}
}
// Prevents the view from potentially visible whitespace
function fixSpace(str: string): string {
const noBreakWhitespace = '\xa0';
return str.replace(/[ \t]/g, noBreakWhitespace);
}
CommandsRegistry.registerCommand('_executeInlayHintProvider', async (accessor, ...args: [URI, IRange]): Promise<languages.InlayHint[]> => {
const [uri, range] = args;
assertType(URI.isUri(uri));
assertType(Range.isIRange(range));
const { inlayHintsProvider } = accessor.get(ILanguageFeaturesService);
const ref = await accessor.get(ITextModelService).createModelReference(uri);
try {
const model = await InlayHintsFragments.create(inlayHintsProvider, ref.object.textEditorModel, [Range.lift(range)], CancellationToken.None);
const result = model.items.map(i => i.hint);
setTimeout(() => model.dispose(), 0); // dispose after sending to ext host
return result;
} finally {
ref.dispose();
}
});
| src/vs/editor/contrib/inlayHints/browser/inlayHintsController.ts | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.0005351810832507908,
0.0001778227451723069,
0.00016555470938328654,
0.0001711852237349376,
0.000046352364734048024
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\t// Show a \"microphone\" icon when recording is in progress that glows via outline.\n",
"\tcollector.addRule(`\n",
"\t\t.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover),\n",
"\t\t.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover) {\n",
"\t\t\tcolor: ${activeRecordingColor};\n",
"\t\t\toutline: 1px solid ${activeRecordingColor};\n",
"\t\t\toutline-offset: -1px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t.monaco-workbench:not(.reduce-motion) .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover),\n",
"\t\t.monaco-workbench:not(.reduce-motion) .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover) {\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/voiceChatActions.ts",
"type": "replace",
"edit_start_line_idx": 685
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* Replace with "microphone" icon.
*/
.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before,
.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled)::before {
content: "\ec12";
}
/*
* Clear animation styles when hovering.
*/
.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover,
.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover {
animation: none;
}
/*
* Replace with "stop" icon when hovering.
*/
.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before,
.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):hover::before {
content: "\ead7"; /* use `debug-stop` icon unicode for hovering over running voice recording */
}
| src/vs/workbench/contrib/chat/electron-sandbox/actions/media/voiceChatActions.css | 1 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.007312328554689884,
0.004059542901813984,
0.00113338278606534,
0.0037329173646867275,
0.0025330951903015375
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\t// Show a \"microphone\" icon when recording is in progress that glows via outline.\n",
"\tcollector.addRule(`\n",
"\t\t.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover),\n",
"\t\t.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover) {\n",
"\t\t\tcolor: ${activeRecordingColor};\n",
"\t\t\toutline: 1px solid ${activeRecordingColor};\n",
"\t\t\toutline-offset: -1px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t.monaco-workbench:not(.reduce-motion) .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover),\n",
"\t\t.monaco-workbench:not(.reduce-motion) .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover) {\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/voiceChatActions.ts",
"type": "replace",
"edit_start_line_idx": 685
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { VSBuffer } from 'vs/base/common/buffer';
import { CancellationToken } from 'vs/base/common/cancellation';
import { IStringDictionary } from 'vs/base/common/collections';
import { Event } from 'vs/base/common/event';
import { deepClone } from 'vs/base/common/objects';
import { URI } from 'vs/base/common/uri';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { FileOperationError, FileOperationResult, IFileContent, IFileService, IFileStat } from 'vs/platform/files/common/files';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { IUserDataProfile, IUserDataProfilesService } from 'vs/platform/userDataProfile/common/userDataProfile';
import { AbstractInitializer, AbstractSynchroniser, IAcceptResult, IFileResourcePreview, IMergeResult } from 'vs/platform/userDataSync/common/abstractSynchronizer';
import { areSame, IMergeResult as ISnippetsMergeResult, merge } from 'vs/platform/userDataSync/common/snippetsMerge';
import { Change, IRemoteUserData, ISyncData, IUserDataSyncLocalStoreService, IUserDataSynchroniser, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncStoreService, SyncResource, USER_DATA_SYNC_SCHEME } from 'vs/platform/userDataSync/common/userDataSync';
interface ISnippetsResourcePreview extends IFileResourcePreview {
previewResult: IMergeResult;
}
interface ISnippetsAcceptedResourcePreview extends IFileResourcePreview {
acceptResult: IAcceptResult;
}
export function parseSnippets(syncData: ISyncData): IStringDictionary<string> {
return JSON.parse(syncData.content);
}
export class SnippetsSynchroniser extends AbstractSynchroniser implements IUserDataSynchroniser {
protected readonly version: number = 1;
private readonly snippetsFolder: URI;
constructor(
profile: IUserDataProfile,
collection: string | undefined,
@IEnvironmentService environmentService: IEnvironmentService,
@IFileService fileService: IFileService,
@IStorageService storageService: IStorageService,
@IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
@IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
@IUserDataSyncLogService logService: IUserDataSyncLogService,
@IConfigurationService configurationService: IConfigurationService,
@IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
@ITelemetryService telemetryService: ITelemetryService,
@IUriIdentityService uriIdentityService: IUriIdentityService,
) {
super({ syncResource: SyncResource.Snippets, profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
this.snippetsFolder = profile.snippetsHome;
this._register(this.fileService.watch(environmentService.userRoamingDataHome));
this._register(this.fileService.watch(this.snippetsFolder));
this._register(Event.filter(this.fileService.onDidFilesChange, e => e.affects(this.snippetsFolder))(() => this.triggerLocalChange()));
}
protected async generateSyncPreview(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, isRemoteDataFromCurrentMachine: boolean): Promise<ISnippetsResourcePreview[]> {
const local = await this.getSnippetsFileContents();
const localSnippets = this.toSnippetsContents(local);
const remoteSnippets: IStringDictionary<string> | null = remoteUserData.syncData ? this.parseSnippets(remoteUserData.syncData) : null;
// Use remote data as last sync data if last sync data does not exist and remote data is from same machine
lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData;
const lastSyncSnippets: IStringDictionary<string> | null = lastSyncUserData && lastSyncUserData.syncData ? this.parseSnippets(lastSyncUserData.syncData) : null;
if (remoteSnippets) {
this.logService.trace(`${this.syncResourceLogLabel}: Merging remote snippets with local snippets...`);
} else {
this.logService.trace(`${this.syncResourceLogLabel}: Remote snippets does not exist. Synchronizing snippets for the first time.`);
}
const mergeResult = merge(localSnippets, remoteSnippets, lastSyncSnippets);
return this.getResourcePreviews(mergeResult, local, remoteSnippets || {}, lastSyncSnippets || {});
}
protected async hasRemoteChanged(lastSyncUserData: IRemoteUserData): Promise<boolean> {
const lastSyncSnippets: IStringDictionary<string> | null = lastSyncUserData.syncData ? this.parseSnippets(lastSyncUserData.syncData) : null;
if (lastSyncSnippets === null) {
return true;
}
const local = await this.getSnippetsFileContents();
const localSnippets = this.toSnippetsContents(local);
const mergeResult = merge(localSnippets, lastSyncSnippets, lastSyncSnippets);
return Object.keys(mergeResult.remote.added).length > 0 || Object.keys(mergeResult.remote.updated).length > 0 || mergeResult.remote.removed.length > 0 || mergeResult.conflicts.length > 0;
}
protected async getMergeResult(resourcePreview: ISnippetsResourcePreview, token: CancellationToken): Promise<IMergeResult> {
return resourcePreview.previewResult;
}
protected async getAcceptResult(resourcePreview: ISnippetsResourcePreview, resource: URI, content: string | null | undefined, token: CancellationToken): Promise<IAcceptResult> {
/* Accept local resource */
if (this.extUri.isEqualOrParent(resource, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }))) {
return {
content: resourcePreview.fileContent ? resourcePreview.fileContent.value.toString() : null,
localChange: Change.None,
remoteChange: resourcePreview.fileContent
? resourcePreview.remoteContent !== null ? Change.Modified : Change.Added
: Change.Deleted
};
}
/* Accept remote resource */
if (this.extUri.isEqualOrParent(resource, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }))) {
return {
content: resourcePreview.remoteContent,
localChange: resourcePreview.remoteContent !== null
? resourcePreview.fileContent ? Change.Modified : Change.Added
: Change.Deleted,
remoteChange: Change.None,
};
}
/* Accept preview resource */
if (this.extUri.isEqualOrParent(resource, this.syncPreviewFolder)) {
if (content === undefined) {
return {
content: resourcePreview.previewResult.content,
localChange: resourcePreview.previewResult.localChange,
remoteChange: resourcePreview.previewResult.remoteChange,
};
} else {
return {
content,
localChange: content === null
? resourcePreview.fileContent !== null ? Change.Deleted : Change.None
: Change.Modified,
remoteChange: content === null
? resourcePreview.remoteContent !== null ? Change.Deleted : Change.None
: Change.Modified
};
}
}
throw new Error(`Invalid Resource: ${resource.toString()}`);
}
protected async applyResult(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, resourcePreviews: [ISnippetsResourcePreview, IAcceptResult][], force: boolean): Promise<void> {
const accptedResourcePreviews: ISnippetsAcceptedResourcePreview[] = resourcePreviews.map(([resourcePreview, acceptResult]) => ({ ...resourcePreview, acceptResult }));
if (accptedResourcePreviews.every(({ localChange, remoteChange }) => localChange === Change.None && remoteChange === Change.None)) {
this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing snippets.`);
}
if (accptedResourcePreviews.some(({ localChange }) => localChange !== Change.None)) {
// back up all snippets
await this.updateLocalBackup(accptedResourcePreviews);
await this.updateLocalSnippets(accptedResourcePreviews, force);
}
if (accptedResourcePreviews.some(({ remoteChange }) => remoteChange !== Change.None)) {
remoteUserData = await this.updateRemoteSnippets(accptedResourcePreviews, remoteUserData, force);
}
if (lastSyncUserData?.ref !== remoteUserData.ref) {
// update last sync
this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized snippets...`);
await this.updateLastSyncUserData(remoteUserData);
this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized snippets`);
}
for (const { previewResource } of accptedResourcePreviews) {
// Delete the preview
try {
await this.fileService.del(previewResource);
} catch (e) { /* ignore */ }
}
}
private getResourcePreviews(snippetsMergeResult: ISnippetsMergeResult, localFileContent: IStringDictionary<IFileContent>, remoteSnippets: IStringDictionary<string>, baseSnippets: IStringDictionary<string>): ISnippetsResourcePreview[] {
const resourcePreviews: Map<string, ISnippetsResourcePreview> = new Map<string, ISnippetsResourcePreview>();
/* Snippets added remotely -> add locally */
for (const key of Object.keys(snippetsMergeResult.local.added)) {
const previewResult: IMergeResult = {
content: snippetsMergeResult.local.added[key],
hasConflicts: false,
localChange: Change.Added,
remoteChange: Change.None,
};
resourcePreviews.set(key, {
baseResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' }),
baseContent: null,
fileContent: null,
localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }),
localContent: null,
remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }),
remoteContent: remoteSnippets[key],
previewResource: this.extUri.joinPath(this.syncPreviewFolder, key),
previewResult,
localChange: previewResult.localChange,
remoteChange: previewResult.remoteChange,
acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' })
});
}
/* Snippets updated remotely -> update locally */
for (const key of Object.keys(snippetsMergeResult.local.updated)) {
const previewResult: IMergeResult = {
content: snippetsMergeResult.local.updated[key],
hasConflicts: false,
localChange: Change.Modified,
remoteChange: Change.None,
};
const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
resourcePreviews.set(key, {
baseResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' }),
baseContent: baseSnippets[key] ?? null,
localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }),
fileContent: localFileContent[key],
localContent,
remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }),
remoteContent: remoteSnippets[key],
previewResource: this.extUri.joinPath(this.syncPreviewFolder, key),
previewResult,
localChange: previewResult.localChange,
remoteChange: previewResult.remoteChange,
acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' })
});
}
/* Snippets removed remotely -> remove locally */
for (const key of snippetsMergeResult.local.removed) {
const previewResult: IMergeResult = {
content: null,
hasConflicts: false,
localChange: Change.Deleted,
remoteChange: Change.None,
};
const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
resourcePreviews.set(key, {
baseResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' }),
baseContent: baseSnippets[key] ?? null,
localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }),
fileContent: localFileContent[key],
localContent,
remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }),
remoteContent: null,
previewResource: this.extUri.joinPath(this.syncPreviewFolder, key),
previewResult,
localChange: previewResult.localChange,
remoteChange: previewResult.remoteChange,
acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' })
});
}
/* Snippets added locally -> add remotely */
for (const key of Object.keys(snippetsMergeResult.remote.added)) {
const previewResult: IMergeResult = {
content: snippetsMergeResult.remote.added[key],
hasConflicts: false,
localChange: Change.None,
remoteChange: Change.Added,
};
const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
resourcePreviews.set(key, {
baseResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' }),
baseContent: baseSnippets[key] ?? null,
localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }),
fileContent: localFileContent[key],
localContent,
remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }),
remoteContent: null,
previewResource: this.extUri.joinPath(this.syncPreviewFolder, key),
previewResult,
localChange: previewResult.localChange,
remoteChange: previewResult.remoteChange,
acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' })
});
}
/* Snippets updated locally -> update remotely */
for (const key of Object.keys(snippetsMergeResult.remote.updated)) {
const previewResult: IMergeResult = {
content: snippetsMergeResult.remote.updated[key],
hasConflicts: false,
localChange: Change.None,
remoteChange: Change.Modified,
};
const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
resourcePreviews.set(key, {
baseResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' }),
baseContent: baseSnippets[key] ?? null,
localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }),
fileContent: localFileContent[key],
localContent,
remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }),
remoteContent: remoteSnippets[key],
previewResource: this.extUri.joinPath(this.syncPreviewFolder, key),
previewResult,
localChange: previewResult.localChange,
remoteChange: previewResult.remoteChange,
acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' })
});
}
/* Snippets removed locally -> remove remotely */
for (const key of snippetsMergeResult.remote.removed) {
const previewResult: IMergeResult = {
content: null,
hasConflicts: false,
localChange: Change.None,
remoteChange: Change.Deleted,
};
resourcePreviews.set(key, {
baseResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' }),
baseContent: baseSnippets[key] ?? null,
localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }),
fileContent: null,
localContent: null,
remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }),
remoteContent: remoteSnippets[key],
previewResource: this.extUri.joinPath(this.syncPreviewFolder, key),
previewResult,
localChange: previewResult.localChange,
remoteChange: previewResult.remoteChange,
acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' })
});
}
/* Snippets with conflicts */
for (const key of snippetsMergeResult.conflicts) {
const previewResult: IMergeResult = {
content: baseSnippets[key] ?? null,
hasConflicts: true,
localChange: localFileContent[key] ? Change.Modified : Change.Added,
remoteChange: remoteSnippets[key] ? Change.Modified : Change.Added
};
const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
resourcePreviews.set(key, {
baseResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' }),
baseContent: baseSnippets[key] ?? null,
localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }),
fileContent: localFileContent[key] || null,
localContent,
remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }),
remoteContent: remoteSnippets[key] || null,
previewResource: this.extUri.joinPath(this.syncPreviewFolder, key),
previewResult,
localChange: previewResult.localChange,
remoteChange: previewResult.remoteChange,
acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' })
});
}
/* Unmodified Snippets */
for (const key of Object.keys(localFileContent)) {
if (!resourcePreviews.has(key)) {
const previewResult: IMergeResult = {
content: localFileContent[key] ? localFileContent[key].value.toString() : null,
hasConflicts: false,
localChange: Change.None,
remoteChange: Change.None
};
const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
resourcePreviews.set(key, {
baseResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' }),
baseContent: baseSnippets[key] ?? null,
localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }),
fileContent: localFileContent[key] || null,
localContent,
remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }),
remoteContent: remoteSnippets[key] || null,
previewResource: this.extUri.joinPath(this.syncPreviewFolder, key),
previewResult,
localChange: previewResult.localChange,
remoteChange: previewResult.remoteChange,
acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' })
});
}
}
return [...resourcePreviews.values()];
}
override async resolveContent(uri: URI): Promise<string | null> {
if (this.extUri.isEqualOrParent(uri, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }))
|| this.extUri.isEqualOrParent(uri, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }))
|| this.extUri.isEqualOrParent(uri, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' }))
|| this.extUri.isEqualOrParent(uri, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' }))) {
return this.resolvePreviewContent(uri);
}
return null;
}
async hasLocalData(): Promise<boolean> {
try {
const localSnippets = await this.getSnippetsFileContents();
if (Object.keys(localSnippets).length) {
return true;
}
} catch (error) {
/* ignore error */
}
return false;
}
private async updateLocalBackup(resourcePreviews: IFileResourcePreview[]): Promise<void> {
const local: IStringDictionary<IFileContent> = {};
for (const resourcePreview of resourcePreviews) {
if (resourcePreview.fileContent) {
local[this.extUri.basename(resourcePreview.localResource!)] = resourcePreview.fileContent;
}
}
await this.backupLocal(JSON.stringify(this.toSnippetsContents(local)));
}
private async updateLocalSnippets(resourcePreviews: ISnippetsAcceptedResourcePreview[], force: boolean): Promise<void> {
for (const { fileContent, acceptResult, localResource, remoteResource, localChange } of resourcePreviews) {
if (localChange !== Change.None) {
const key = remoteResource ? this.extUri.basename(remoteResource) : this.extUri.basename(localResource!);
const resource = this.extUri.joinPath(this.snippetsFolder, key);
// Removed
if (localChange === Change.Deleted) {
this.logService.trace(`${this.syncResourceLogLabel}: Deleting snippet...`, this.extUri.basename(resource));
await this.fileService.del(resource);
this.logService.info(`${this.syncResourceLogLabel}: Deleted snippet`, this.extUri.basename(resource));
}
// Added
else if (localChange === Change.Added) {
this.logService.trace(`${this.syncResourceLogLabel}: Creating snippet...`, this.extUri.basename(resource));
await this.fileService.createFile(resource, VSBuffer.fromString(acceptResult.content!), { overwrite: force });
this.logService.info(`${this.syncResourceLogLabel}: Created snippet`, this.extUri.basename(resource));
}
// Updated
else {
this.logService.trace(`${this.syncResourceLogLabel}: Updating snippet...`, this.extUri.basename(resource));
await this.fileService.writeFile(resource, VSBuffer.fromString(acceptResult.content!), force ? undefined : fileContent!);
this.logService.info(`${this.syncResourceLogLabel}: Updated snippet`, this.extUri.basename(resource));
}
}
}
}
private async updateRemoteSnippets(resourcePreviews: ISnippetsAcceptedResourcePreview[], remoteUserData: IRemoteUserData, forcePush: boolean): Promise<IRemoteUserData> {
const currentSnippets: IStringDictionary<string> = remoteUserData.syncData ? this.parseSnippets(remoteUserData.syncData) : {};
const newSnippets: IStringDictionary<string> = deepClone(currentSnippets);
for (const { acceptResult, localResource, remoteResource, remoteChange } of resourcePreviews) {
if (remoteChange !== Change.None) {
const key = localResource ? this.extUri.basename(localResource) : this.extUri.basename(remoteResource!);
if (remoteChange === Change.Deleted) {
delete newSnippets[key];
} else {
newSnippets[key] = acceptResult.content!;
}
}
}
if (!areSame(currentSnippets, newSnippets)) {
// update remote
this.logService.trace(`${this.syncResourceLogLabel}: Updating remote snippets...`);
remoteUserData = await this.updateRemoteUserData(JSON.stringify(newSnippets), forcePush ? null : remoteUserData.ref);
this.logService.info(`${this.syncResourceLogLabel}: Updated remote snippets`);
}
return remoteUserData;
}
private parseSnippets(syncData: ISyncData): IStringDictionary<string> {
return parseSnippets(syncData);
}
private toSnippetsContents(snippetsFileContents: IStringDictionary<IFileContent>): IStringDictionary<string> {
const snippets: IStringDictionary<string> = {};
for (const key of Object.keys(snippetsFileContents)) {
snippets[key] = snippetsFileContents[key].value.toString();
}
return snippets;
}
private async getSnippetsFileContents(): Promise<IStringDictionary<IFileContent>> {
const snippets: IStringDictionary<IFileContent> = {};
let stat: IFileStat;
try {
stat = await this.fileService.resolve(this.snippetsFolder);
} catch (e) {
// No snippets
if (e instanceof FileOperationError && e.fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
return snippets;
} else {
throw e;
}
}
for (const entry of stat.children || []) {
const resource = entry.resource;
const extension = this.extUri.extname(resource);
if (extension === '.json' || extension === '.code-snippets') {
const key = this.extUri.relativePath(this.snippetsFolder, resource)!;
const content = await this.fileService.readFile(resource);
snippets[key] = content;
}
}
return snippets;
}
}
export class SnippetsInitializer extends AbstractInitializer {
constructor(
@IFileService fileService: IFileService,
@IUserDataProfilesService userDataProfilesService: IUserDataProfilesService,
@IEnvironmentService environmentService: IEnvironmentService,
@IUserDataSyncLogService logService: IUserDataSyncLogService,
@IStorageService storageService: IStorageService,
@IUriIdentityService uriIdentityService: IUriIdentityService,
) {
super(SyncResource.Snippets, userDataProfilesService, environmentService, logService, fileService, storageService, uriIdentityService);
}
protected async doInitialize(remoteUserData: IRemoteUserData): Promise<void> {
const remoteSnippets: IStringDictionary<string> | null = remoteUserData.syncData ? JSON.parse(remoteUserData.syncData.content) : null;
if (!remoteSnippets) {
this.logService.info('Skipping initializing snippets because remote snippets does not exist.');
return;
}
const isEmpty = await this.isEmpty();
if (!isEmpty) {
this.logService.info('Skipping initializing snippets because local snippets exist.');
return;
}
for (const key of Object.keys(remoteSnippets)) {
const content = remoteSnippets[key];
if (content) {
const resource = this.extUri.joinPath(this.userDataProfilesService.defaultProfile.snippetsHome, key);
await this.fileService.createFile(resource, VSBuffer.fromString(content));
this.logService.info('Created snippet', this.extUri.basename(resource));
}
}
await this.updateLastSyncUserData(remoteUserData);
}
private async isEmpty(): Promise<boolean> {
try {
const stat = await this.fileService.resolve(this.userDataProfilesService.defaultProfile.snippetsHome);
return !stat.children?.length;
} catch (error) {
return (<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND;
}
}
}
| src/vs/platform/userDataSync/common/snippetsSync.ts | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.0001765366323525086,
0.00017294837743975222,
0.00016888078243937343,
0.00017298036254942417,
0.000002021559794229688
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\t// Show a \"microphone\" icon when recording is in progress that glows via outline.\n",
"\tcollector.addRule(`\n",
"\t\t.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover),\n",
"\t\t.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover) {\n",
"\t\t\tcolor: ${activeRecordingColor};\n",
"\t\t\toutline: 1px solid ${activeRecordingColor};\n",
"\t\t\toutline-offset: -1px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t.monaco-workbench:not(.reduce-motion) .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover),\n",
"\t\t.monaco-workbench:not(.reduce-motion) .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover) {\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/voiceChatActions.ts",
"type": "replace",
"edit_start_line_idx": 685
} | parameters:
- name: VSCODE_RELEASE
type: boolean
steps:
- task: NodeTool@0
inputs:
versionSource: fromFile
versionFilePath: .nvmrc
nodejsMirror: https://github.com/joaomoreno/node-mirror/releases/download
- task: AzureCLI@2
displayName: Fetch secrets
inputs:
azureSubscription: "vscode-builds-subscription"
scriptType: pscore
scriptLocation: inlineScript
addSpnToEnvironment: true
inlineScript: |
Write-Host "##vso[task.setvariable variable=AZURE_TENANT_ID]$env:tenantId"
Write-Host "##vso[task.setvariable variable=AZURE_CLIENT_ID]$env:servicePrincipalId"
Write-Host "##vso[task.setvariable variable=AZURE_CLIENT_SECRET;issecret=true]$env:servicePrincipalKey"
- script: |
set -e
(cd build ; yarn)
AZURE_TENANT_ID="$(AZURE_TENANT_ID)" \
AZURE_CLIENT_ID="$(AZURE_CLIENT_ID)" \
AZURE_CLIENT_SECRET="$(AZURE_CLIENT_SECRET)" \
node build/azure-pipelines/common/releaseBuild.js ${{ parameters.VSCODE_RELEASE }}
displayName: Release build
| build/azure-pipelines/product-release.yml | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.00017387274419888854,
0.00017286108050029725,
0.00017208632198162377,
0.00017274264246225357,
7.491329938602576e-7
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\t// Show a \"microphone\" icon when recording is in progress that glows via outline.\n",
"\tcollector.addRule(`\n",
"\t\t.monaco-workbench .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover),\n",
"\t\t.monaco-workbench .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover) {\n",
"\t\t\tcolor: ${activeRecordingColor};\n",
"\t\t\toutline: 1px solid ${activeRecordingColor};\n",
"\t\t\toutline-offset: -1px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t.monaco-workbench:not(.reduce-motion) .interactive-input-part .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover),\n",
"\t\t.monaco-workbench:not(.reduce-motion) .inline-chat .monaco-action-bar .action-label.codicon-loading.codicon-modifier-spin:not(.disabled):not(:hover) {\n"
],
"file_path": "src/vs/workbench/contrib/chat/electron-sandbox/actions/voiceChatActions.ts",
"type": "replace",
"edit_start_line_idx": 685
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as path from 'vs/base/common/path';
import { Disposable } from 'vs/base/common/lifecycle';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
/**
* Shows a message when opening a large file which has been memory optimized (and features disabled).
*/
export class LargeFileOptimizationsWarner extends Disposable implements IEditorContribution {
public static readonly ID = 'editor.contrib.largeFileOptimizationsWarner';
constructor(
private readonly _editor: ICodeEditor,
@INotificationService private readonly _notificationService: INotificationService,
@IConfigurationService private readonly _configurationService: IConfigurationService,
) {
super();
this._register(this._editor.onDidChangeModel((e) => this._update()));
this._update();
}
private _update(): void {
const model = this._editor.getModel();
if (!model) {
return;
}
if (model.isTooLargeForTokenization()) {
const message = nls.localize(
{
key: 'largeFile',
comment: [
'Variable 0 will be a file name.'
]
},
"{0}: tokenization, wrapping, folding, codelens, word highlighting and sticky scroll have been turned off for this large file in order to reduce memory usage and avoid freezing or crashing.",
path.basename(model.uri.path)
);
this._notificationService.prompt(Severity.Info, message, [
{
label: nls.localize('removeOptimizations', "Forcefully Enable Features"),
run: () => {
this._configurationService.updateValue(`editor.largeFileOptimizations`, false).then(() => {
this._notificationService.info(nls.localize('reopenFilePrompt', "Please reopen file in order for this setting to take effect."));
}, (err) => {
this._notificationService.error(err);
});
}
}
], { neverShowAgain: { id: 'editor.contrib.largeFileOptimizationsWarner' } });
}
}
}
registerEditorContribution(LargeFileOptimizationsWarner.ID, LargeFileOptimizationsWarner, EditorContributionInstantiation.AfterFirstRender);
| src/vs/workbench/contrib/codeEditor/browser/largeFileOptimizations.ts | 0 | https://github.com/microsoft/vscode/commit/d31d5ca86a298eed6e18db6e77200accd9cb944d | [
0.0001745464833220467,
0.00017039715021383017,
0.00016561422671657056,
0.00016961181245278567,
0.0000028334152375464328
] |
{
"id": 0,
"code_window": [
"\n",
"\tprivate getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {\n",
"\t\tlet session = debugService.getActiveSession();\n",
"\t\treturn session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {\n",
"\t\t\tthis.stoppedDetails.totalFrames = response.body.totalFrames;\n",
"\t\t\treturn response.body.stackFrames.map((rsf, level) => {\n",
"\t\t\t\tif (!rsf) {\n",
"\t\t\t\t\treturn new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', \"Unknown stack location\"), undefined, undefined);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (!response || !response.body) {\n",
"\t\t\t\treturn [];\n",
"\t\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "add",
"edit_start_line_idx": 134
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import {guessMimeTypes} from 'vs/base/common/mime';
import Event, {Emitter} from 'vs/base/common/event';
import uri from 'vs/base/common/uri';
import {RunOnceScheduler} from 'vs/base/common/async';
import {Action} from 'vs/base/common/actions';
import arrays = require('vs/base/common/arrays');
import types = require('vs/base/common/types');
import errors = require('vs/base/common/errors');
import severity from 'vs/base/common/severity';
import {TPromise} from 'vs/base/common/winjs.base';
import aria = require('vs/base/browser/ui/aria/aria');
import editorbrowser = require('vs/editor/browser/editorBrowser');
import {ISuggestion} from 'vs/editor/common/modes';
import {Position} from 'vs/editor/common/core/position';
import {IContextKeyService, IContextKey} from 'vs/platform/contextkey/common/contextkey';
import {IMarkerService} from 'vs/platform/markers/common/markers';
import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle';
import {IExtensionService} from 'vs/platform/extensions/common/extensions';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IFileService, FileChangesEvent, FileChangeType, EventType} from 'vs/platform/files/common/files';
import {IEventService} from 'vs/platform/event/common/event';
import {IMessageService, CloseAction} from 'vs/platform/message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {TelemetryService} from 'vs/platform/telemetry/common/telemetryService';
import {TelemetryAppenderClient} from 'vs/platform/telemetry/common/telemetryIpc';
import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage';
import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService';
import {asFileEditorInput} from 'vs/workbench/common/editor';
import debug = require('vs/workbench/parts/debug/common/debug');
import {RawDebugSession} from 'vs/workbench/parts/debug/electron-browser/rawDebugSession';
import model = require('vs/workbench/parts/debug/common/debugModel');
import {DebugStringEditorInput, DebugErrorEditorInput} from 'vs/workbench/parts/debug/browser/debugEditorInputs';
import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel');
import debugactions = require('vs/workbench/parts/debug/browser/debugActions');
import {ConfigurationManager} from 'vs/workbench/parts/debug/node/debugConfigurationManager';
import {Source} from 'vs/workbench/parts/debug/common/debugSource';
import {ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary} from 'vs/workbench/parts/tasks/common/taskService';
import {TaskError, TaskErrors} from 'vs/workbench/parts/tasks/common/taskSystem';
import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService';
import {IPanelService} from 'vs/workbench/services/panel/common/panelService';
import {IPartService} from 'vs/workbench/services/part/common/partService';
import {ITextFileService} from 'vs/workbench/parts/files/common/files';
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {IWindowService, IBroadcast} from 'vs/workbench/services/window/electron-browser/windowService';
import {ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL} from 'vs/workbench/services/thread/electron-browser/threadService';
import {ipcRenderer as ipc} from 'electron';
import {Client} from 'vs/base/parts/ipc/node/ipc.cp';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname';
export class DebugService implements debug.IDebugService {
public _serviceBrand: any;
private _state: debug.State;
private _onDidChangeState: Emitter<debug.State>;
private session: RawDebugSession;
private model: model.Model;
private viewModel: viewmodel.ViewModel;
private configurationManager: ConfigurationManager;
private customTelemetryService: ITelemetryService;
private lastTaskEvent: TaskEvent;
private toDispose: lifecycle.IDisposable[];
private toDisposeOnSessionEnd: lifecycle.IDisposable[];
private inDebugMode: IContextKey<boolean>;
private breakpointsToSendOnResourceSaved: { [uri: string]: boolean };
constructor(
@IStorageService private storageService: IStorageService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@ITextFileService private textFileService: ITextFileService,
@IViewletService private viewletService: IViewletService,
@IPanelService private panelService: IPanelService,
@IFileService private fileService: IFileService,
@IMessageService private messageService: IMessageService,
@IPartService private partService: IPartService,
@IWindowService private windowService: IWindowService,
@ITelemetryService private telemetryService: ITelemetryService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@IEditorGroupService private editorGroupService: IEditorGroupService,
@IEventService eventService: IEventService,
@ILifecycleService private lifecycleService: ILifecycleService,
@IInstantiationService private instantiationService: IInstantiationService,
@IExtensionService private extensionService: IExtensionService,
@IMarkerService private markerService: IMarkerService,
@ITaskService private taskService: ITaskService,
@IConfigurationService private configurationService: IConfigurationService
) {
this.toDispose = [];
this.toDisposeOnSessionEnd = [];
this.session = null;
this.breakpointsToSendOnResourceSaved = {};
this._state = debug.State.Inactive;
this._onDidChangeState = new Emitter<debug.State>();
if (!this.contextService.getWorkspace()) {
this._state = debug.State.Disabled;
}
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, 'null'));
this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadWatchExpressions());
this.toDispose.push(this.model);
this.viewModel = new viewmodel.ViewModel();
this.registerListeners(eventService, lifecycleService);
}
private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void {
this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e)));
if (this.taskService) {
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => {
this.lastTaskEvent = e;
}));
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => {
if (e.type === TaskType.SingleRun) {
this.lastTaskEvent = null;
}
}));
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => {
this.lastTaskEvent = null;
}));
}
lifecycleService.onShutdown(this.store, this);
lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this));
}
private onBroadcast(broadcast: IBroadcast): void {
// attach: PH is ready to be attached to
if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) {
this.rawAttach(broadcast.payload.port);
return;
}
if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) {
this.onSessionEnd();
return;
}
// from this point on we require an active session
let session = this.getActiveSession();
if (!session || session.configuration.type !== 'extensionHost') {
return; // we are only intersted if we have an active debug session for extensionHost
}
// a plugin logged output, show it inside the REPL
if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) {
let extensionOutput: ILogEntry = broadcast.payload;
let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info;
let args: any[] = [];
try {
let parsed = JSON.parse(extensionOutput.arguments);
args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o]));
} catch (error) {
args.push(extensionOutput.arguments);
}
// add output for each argument logged
let simpleVals: any[] = [];
for (let i = 0; i < args.length; i++) {
let a = args[i];
// undefined gets printed as 'undefined'
if (typeof a === 'undefined') {
simpleVals.push('undefined');
}
// null gets printed as 'null'
else if (a === null) {
simpleVals.push('null');
}
// objects & arrays are special because we want to inspect them in the REPL
else if (types.isObject(a) || Array.isArray(a)) {
// flush any existing simple values logged
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev);
simpleVals = [];
}
// show object
this.logToRepl(a, sev);
}
// string: watch out for % replacement directive
// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
else if (typeof a === 'string') {
let buf = '';
for (let j = 0, len = a.length; j < len; j++) {
if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) {
i++; // read over substitution
buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace
j++; // read over directive
} else {
buf += a[j];
}
}
simpleVals.push(buf);
}
// number or boolean is joined together
else {
simpleVals.push(a);
}
}
// flush simple values
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev);
}
}
}
private registerSessionListeners(): void {
this.toDisposeOnSessionEnd.push(this.session);
this.toDisposeOnSessionEnd.push(this.session.onDidInitialize(event => {
aria.status(nls.localize('debuggingStarted', "Debugging started."));
this.sendAllBreakpoints().then(() => {
if (this.session.configuration.capabilities.supportsConfigurationDoneRequest) {
this.session.configurationDone().done(null, e => {
// Disconnect the debug session on configuration done error #10596
if (this.session) {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
this.messageService.show(severity.Error, e.message);
});
}
});
}));
this.toDisposeOnSessionEnd.push(this.session.onDidStop(event => {
this.setStateAndEmit(debug.State.Stopped);
const threadId = event.body.threadId;
this.getThreadData().done(() => {
this.model.rawUpdate({
threadId,
stoppedDetails: event.body,
allThreadsStopped: event.body.allThreadsStopped
});
const thread = this.model.getThreads()[threadId];
thread.getCallStack(this).then(callStack => {
if (callStack.length > 0) {
// focus first stack frame from top that has source location
const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]);
this.setFocusedStackFrameAndEvaluate(stackFrameToFocus, thread).done(null, errors.onUnexpectedError);
this.windowService.getWindow().focus();
aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber));
return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false);
} else {
this.setFocusedStackFrameAndEvaluate(null, thread).done(null, errors.onUnexpectedError);
}
});
}, errors.onUnexpectedError);
}));
this.toDisposeOnSessionEnd.push(this.session.onDidThread(event => {
if (event.body.reason === 'started') {
this.getThreadData().done(null, errors.onUnexpectedError);
} else if (event.body.reason === 'exited') {
this.model.clearThreads(true, event.body.threadId);
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidTerminateDebugee(event => {
aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
if (this.session && this.session.getId() === event.body.sessionId) {
if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) {
this.restartSession().done(null, err => this.messageService.show(severity.Error, err.message));
} else {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidContinued(event => {
this.lazyTransitionToRunningState(event.body.allThreadsContinued ? undefined : event.body.threadId);
}));
this.toDisposeOnSessionEnd.push(this.session.onDidOutput(event => {
if (event.body && event.body.category === 'telemetry') {
// only log telemetry events from debug adapter if the adapter provided the telemetry key
// and the user opted in telemetry
if (this.customTelemetryService && this.telemetryService.isOptedIn) {
this.customTelemetryService.publicLog(event.body.output, event.body.data);
}
} else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) {
this.onOutput(event);
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidBreakpoint(event => {
const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (breakpoint) {
this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint });
} else {
const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (functionBreakpoint) {
this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint });
}
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidExitAdapter(event => {
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (this.session.configuration.type === 'extensionHost' && this._state === debug.State.RunningNoDebug) {
ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath);
}
if (this.session && this.session.getId() === event.body.sessionId) {
this.onSessionEnd();
}
}));
}
private onOutput(event: DebugProtocol.OutputEvent): void {
const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info;
this.appendReplOutput(event.body.output, outputSeverity);
}
private getThreadData(): TPromise<void> {
return this.session.threads().then(response => {
response.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread }));
});
}
private loadBreakpoints(): debug.IBreakpoint[] {
let result: debug.IBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }),
breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition);
});
} catch (e) { }
return result || [];
}
private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
let result: debug.IFunctionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
return new model.FunctionBreakpoint(fb.name, fb.enabled);
});
} catch (e) { }
return result || [];
}
private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
let result: debug.IExceptionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled);
});
} catch (e) { }
return result || [];
}
private loadWatchExpressions(): model.Expression[] {
let result: model.Expression[];
try {
result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string } ) => {
return new model.Expression(watchStoredData.name, false, watchStoredData.id);
});
} catch (e) { }
return result || [];
}
public get state(): debug.State {
return this._state;
}
public get onDidChangeState(): Event<debug.State> {
return this._onDidChangeState.event;
}
private setStateAndEmit(newState: debug.State): void {
this._state = newState;
this._onDidChangeState.fire(newState);
}
public get enabled(): boolean {
return !!this.contextService.getWorkspace();
}
public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame, thread?: debug.IThread): TPromise<void> {
if (!thread && focusedStackFrame) {
thread = this.model.getThreads()[focusedStackFrame.threadId];
}
this.viewModel.setFocusedStackFrame(focusedStackFrame, thread);
if (focusedStackFrame) {
return this.model.evaluateWatchExpressions(this.session, focusedStackFrame);
} else {
this.model.clearWatchExpressionValues();
return TPromise.as(null);
}
}
public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof model.Breakpoint) {
return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri);
} else if (breakpoint instanceof model.FunctionBreakpoint) {
return this.sendFunctionBreakpoints();
}
return this.sendExceptionBreakpoints();
}
this.model.enableOrDisableAllBreakpoints(enable);
return this.sendAllBreakpoints();
}
public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void[]> {
this.model.addBreakpoints(rawBreakpoints);
const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri);
rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath)));
return TPromise.join(uris.map(uri => this.sendBreakpoints(uri)));
}
public removeBreakpoints(id?: string): TPromise<any> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.source.uri.fsPath)));
const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri);
this.model.removeBreakpoints(toRemove);
return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri)));
}
public setBreakpointsActivated(activated: boolean): TPromise<void> {
this.model.setBreakpointsActivated(activated);
return this.sendAllBreakpoints();
}
public addFunctionBreakpoint(): void {
this.model.addFunctionBreakpoint('');
}
public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> {
this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } });
return this.sendFunctionBreakpoints();
}
public removeFunctionBreakpoints(id?: string): TPromise<void> {
this.model.removeFunctionBreakpoints(id);
return this.sendFunctionBreakpoints();
}
public addReplExpression(name: string): TPromise<void> {
this.telemetryService.publicLog('debugService/addReplExpression');
const focussedStackFrame = this.viewModel.getFocusedStackFrame();
return this.model.addReplExpression(this.session, focussedStackFrame, name)
// Evaluate all watch expressions again since repl evaluation might have changed some.
.then(() => this.setFocusedStackFrameAndEvaluate(focussedStackFrame));
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
this.model.logToRepl(value, severity);
}
public appendReplOutput(value: string, severity?: severity): void {
this.model.appendReplOutput(value, severity);
}
public removeReplExpressions(): void {
this.model.removeReplExpressions();
}
public setVariable(variable: debug.IExpression, value: string): TPromise<any> {
if (!this.session || !(variable instanceof model.Variable)) {
return TPromise.as(null);
}
return this.session.setVariable({
name: variable.name,
value,
variablesReference: (<model.Variable>variable).parent.reference
}).then(response => {
variable.value = response.body.value;
// Evaluate all watch expressions again since changing variable value might have changed some #8118.
return this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame());
}, err => {
(<model.Variable>variable).errorMessage = err.message;
});
}
public addWatchExpression(name: string): TPromise<void> {
return this.model.addWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), name);
}
public renameWatchExpression(id: string, newName: string): TPromise<void> {
return this.model.renameWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), id, newName);
}
public removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
}
public createSession(noDebug: boolean, configuration?: debug.IConfig): TPromise<any> {
this.removeReplExpressions();
return this.textFileService.saveAll() // make sure all dirty files are saved
.then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date
.then(() => this.extensionService.onReady()
.then(() => this.configurationManager.setConfiguration(configuration || this.configurationManager.configurationName)
.then(() => this.configurationManager.resolveInteractiveVariables())
.then(resolvedConfiguration => {
configuration = resolvedConfiguration;
if (!configuration) {
return this.configurationManager.openConfigFile(false).then(openend => {
if (openend) {
this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application."));
}
});
}
if (configuration.silentlyAbort) {
return;
}
configuration.noDebug = noDebug;
if (!this.configurationManager.adapter) {
return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type)))
: TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."),
{ actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] }));
}
return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => {
const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return this.doCreateSession(configuration);
}
this.messageService.show(severity.Error, {
message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) :
errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) :
nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode),
actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => {
this.messageService.hideAll();
return this.doCreateSession(configuration);
}), CloseAction]
});
}, (err: TaskError) => {
if (err.code !== TaskErrors.NotConfigured) {
throw err;
}
this.messageService.show(err.severity, {
message: err.message,
actions: [this.taskService.configureAction(), CloseAction]
});
});
}))));
}
private doCreateSession(configuration: debug.IExtHostConfig): TPromise<any> {
this.setStateAndEmit(debug.State.Initializing);
return this.telemetryService.getTelemetryInfo().then(info => {
const telemetryInfo: { [key: string]: string } = Object.create(null);
telemetryInfo['common.vscodemachineid'] = info.machineId;
telemetryInfo['common.vscodesessionid'] = info.sessionId;
return telemetryInfo;
}).then(data => {
const { aiKey, type } = this.configurationManager.adapter;
const publisher = this.configurationManager.adapter.extensionDescription.publisher;
this.customTelemetryService = null;
if (aiKey) {
const client = new Client(
uri.parse(require.toUrl('bootstrap')).fsPath,
{
serverName: 'Debug Telemetry',
timeout: 1000 * 60 * 5,
args: [`${ publisher }.${ type }`, JSON.stringify(data), aiKey],
env: {
ELECTRON_RUN_AS_NODE: 1,
PIPE_LOGGING: 'true',
AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp'
}
}
);
const channel = client.getChannel('telemetryAppender');
const appender = new TelemetryAppenderClient(channel);
this.toDisposeOnSessionEnd.push(client);
this.customTelemetryService = new TelemetryService({ appender }, this.configurationService);
}
this.session = this.instantiationService.createInstance(RawDebugSession, configuration.debugServer, this.configurationManager.adapter, this.customTelemetryService);
this.registerSessionListeners();
return this.session.initialize({
adapterID: configuration.type,
pathFormat: 'path',
linesStartAt1: true,
columnsStartAt1: true,
supportsVariableType: true, // #8858
supportsVariablePaging: true, // #9537
supportsRunInTerminalRequest: true // #10574
}).then((result: DebugProtocol.InitializeResponse) => {
if (!this.session) {
return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly")));
}
this.model.setExceptionBreakpoints(this.session.configuration.capabilities.exceptionBreakpointFilters);
return configuration.request === 'attach' ? this.session.attach(configuration) : this.session.launch(configuration);
}).then((result: DebugProtocol.Response) => {
if (!this.session) {
return TPromise.as(null);
}
if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) {
// We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden
this.viewModel.changedWorkbenchViewState = true;
this.viewletService.openViewlet(debug.VIEWLET_ID);
}
// Do not change status bar to orange if we are just running without debug.
if (!configuration.noDebug) {
this.partService.addClass('debugging');
}
this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError);
this.inDebugMode.set(true);
this.lazyTransitionToRunningState();
this.telemetryService.publicLog('debugSessionStart', {
type: configuration.type,
breakpointCount: this.model.getBreakpoints().length,
exceptionBreakpoints: this.model.getExceptionBreakpoints(),
watchExpressionsCount: this.model.getWatchExpressions().length,
extensionName: `${ this.configurationManager.adapter.extensionDescription.publisher }.${ this.configurationManager.adapter.extensionDescription.name }`,
isBuiltin: this.configurationManager.adapter.extensionDescription.isBuiltin
});
}).then(undefined, (error: any) => {
if (error instanceof Error && error.message === 'Canceled') {
// Do not show 'canceled' error messages to the user #7906
return TPromise.as(null);
}
this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined });
this.setStateAndEmit(debug.State.Inactive);
if (this.session) {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
// Show the repl if some error got logged there #5870
if (this.model.getReplElements().length > 0) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction];
return TPromise.wrapError(errors.create(error.message, { actions }));
});
});
}
private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> {
if (!taskName) {
return TPromise.as(null);
}
// run a task before starting a debug session
return this.taskService.tasks().then(descriptions => {
const filteredTasks = descriptions.filter(task => task.name === taskName);
if (filteredTasks.length !== 1) {
return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), {
actions: [
this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL),
this.taskService.configureAction(),
CloseAction
]
}));
}
// task is already running - nothing to do.
if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) {
return TPromise.as(null);
}
if (this.lastTaskEvent) {
// there is a different task running currently.
return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName)));
}
// no task running, execute the preLaunchTask.
const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => {
this.lastTaskEvent = null;
return result;
}, err => {
this.lastTaskEvent = null;
});
if (filteredTasks[0].isWatching) {
return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null)));
}
return taskPromise;
});
}
private rawAttach(port: number): TPromise<any> {
if (this.session) {
return this.session.attach({ port });
}
this.setStateAndEmit(debug.State.Initializing);
const configuration = <debug.IExtHostConfig>this.configurationManager.configuration;
return this.doCreateSession({
type: configuration.type,
request: 'attach',
port,
sourceMaps: configuration.sourceMaps,
outDir: configuration.outDir,
debugServer: configuration.debugServer
});
}
public restartSession(): TPromise<any> {
return this.session ? this.session.disconnect(true).then(() =>
new TPromise<void>((c, e) => {
setTimeout(() => {
this.createSession(false, null).then(() => c(null), err => e(err));
}, 300);
})
) : this.createSession(false, null);
}
public getActiveSession(): debug.IRawDebugSession {
return this.session;
}
private onSessionEnd(): void {
if (this.session) {
const bpsExist = this.model.getBreakpoints().length > 0;
this.telemetryService.publicLog('debugSessionStop', {
type: this.session.configuration.type,
success: this.session.emittedStopped || !bpsExist,
sessionLengthInSeconds: this.session.getLengthInSeconds(),
breakpointCount: this.model.getBreakpoints().length,
watchExpressionsCount: this.model.getWatchExpressions().length
});
}
this.session = null;
try {
this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd);
} catch (e) {
// an internal module might be open so the dispose can throw -> ignore and continue with stop session.
}
this.partService.removeClass('debugging');
this.model.clearThreads(true);
this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError);
this.setStateAndEmit(debug.State.Inactive);
// set breakpoints back to unverified since the session ended.
// source reference changes across sessions, so we do not use it to persist the source.
const data: { [id: string]: { line: number, verified: boolean } } = {};
this.model.getBreakpoints().forEach(bp => {
delete bp.source.raw.sourceReference;
data[bp.getId()] = { line: bp.lineNumber, verified: false };
});
this.model.updateBreakpoints(data);
this.inDebugMode.reset();
}
public getModel(): debug.IModel {
return this.model;
}
public getViewModel(): debug.IViewModel {
return this.viewModel;
}
public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> {
const visibleEditors = this.editorService.getVisibleEditors();
for (let i = 0; i < visibleEditors.length; i++) {
const fileInput = asFileEditorInput(visibleEditors[i].input);
if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) ||
(visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) {
const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl();
if (control) {
control.revealLineInCenterIfOutsideViewport(lineNumber);
control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 });
this.editorGroupService.activateGroup(i);
if (!preserveFocus) {
this.editorGroupService.focusGroup(i);
}
}
return TPromise.as(null);
}
}
if (source.inMemory) {
// internal module
if (source.reference !== 0 && this.session && source.available) {
return this.session.source({ sourceReference: source.reference }).then(response => {
const mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0];
return this.getDebugStringEditorInput(source, response.body.content, mime);
}, (err: DebugProtocol.ErrorResponse) => {
// Display the error from debug adapter using a temporary editor #8836
return this.getDebugErrorEditorInput(source, err.message);
}).then(editorInput => {
return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide);
});
}
return this.sourceIsUnavailable(source, sideBySide);
}
return this.fileService.resolveFile(source.uri).then(() =>
this.editorService.openEditor({
resource: source.uri,
options: {
selection: {
startLineNumber: lineNumber,
startColumn: 1,
endLineNumber: lineNumber,
endColumn: 1
},
preserveFocus: preserveFocus
}
}, sideBySide), err => this.sourceIsUnavailable(source, sideBySide)
);
}
private sourceIsUnavailable(source: Source, sideBySide: boolean): TPromise<any> {
this.model.sourceIsUnavailable(source);
const editorInput = this.getDebugErrorEditorInput(source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name));
return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide);
}
public getConfigurationManager(): debug.IConfigurationManager {
return this.configurationManager;
}
public next(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.next({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepIn(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepIn({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepOut(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepOut({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepBack(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepBack({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public continue(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.continue({ threadId }).then(response => {
const allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true;
this.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId);
});
}
public pause(threadId: number): TPromise<any> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.pause({ threadId });
}
public restartFrame(frameId: number): TPromise<any> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.restartFrame({ frameId });
}
public completions(text: string, position: Position): TPromise<ISuggestion[]> {
if (!this.session || !this.session.configuration.capabilities.supportsCompletionsRequest) {
return TPromise.as([]);
}
const focussedStackFrame = this.viewModel.getFocusedStackFrame();
return this.session.completions({
frameId: focussedStackFrame ? focussedStackFrame.frameId : undefined,
text,
column: position.column,
line: position.lineNumber
}).then(response => {
return !response ? [] : response.body.targets.map(item => ({
label: item.label,
insertText: item.text || item.label,
type: item.type
}));
}, err => []);
}
private lazyTransitionToRunningState(threadId?: number): void {
let setNewFocusedStackFrameScheduler: RunOnceScheduler;
const toDispose = this.session.onDidStop(e => {
if (e.body.threadId === threadId || e.body.allThreadsStopped || !threadId) {
setNewFocusedStackFrameScheduler.cancel();
}
});
this.model.clearThreads(false, threadId);
// Get a top stack frame of a stopped thread if there is any.
const threads = this.model.getThreads();
const stoppedReference = Object.keys(threads).filter(ref => threads[ref].stopped).pop();
const stoppedThread = stoppedReference ? threads[parseInt(stoppedReference)] : null;
const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null;
const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null;
if (!stoppedThread) {
this.setStateAndEmit(this.configurationManager.configuration.noDebug ? debug.State.RunningNoDebug : debug.State.Running);
}
// Do not immediatly set a new focused stack frame since that might cause unnecessery flickering
// of the tree in the debug viewlet. Only set focused stack frame if no stopped event has arrived in 500ms.
setNewFocusedStackFrameScheduler = new RunOnceScheduler(() => {
toDispose.dispose();
aria.status(nls.localize('debuggingContinued', "Debugging continued."));
this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError);
}, 500);
setNewFocusedStackFrameScheduler.schedule();
}
private getDebugStringEditorInput(source: Source, value: string, mtype: string): DebugStringEditorInput {
const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0);
this.toDisposeOnSessionEnd.push(result);
return result;
}
private getDebugErrorEditorInput(source: Source, value: string): DebugErrorEditorInput {
const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value);
this.toDisposeOnSessionEnd.push(result);
return result;
}
private sendAllBreakpoints(): TPromise<any> {
return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri)))
.then(() => this.sendFunctionBreakpoints())
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints());
}
private sendBreakpoints(modelUri: uri, sourceModified = false): TPromise<void> {
if (!this.session || !this.session.readyForBreakpoints) {
return TPromise.as(null);
}
if (this.textFileService.isDirty(modelUri)) {
// Only send breakpoints for a file once it is not dirty #8077
this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true;
return TPromise.as(null);
}
const breakpointsToSend = arrays.distinct(
this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()),
bp => `${bp.desiredLineNumber}`
);
const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model);
return this.session.setBreakpoints({
source: rawSource,
lines: breakpointsToSend.map(bp => bp.desiredLineNumber),
breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })),
sourceModified
}).then(response => {
const data: { [id: string]: { line?: number, verified: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateBreakpoints(data);
});
}
private sendFunctionBreakpoints(): TPromise<void> {
if (!this.session || !this.session.readyForBreakpoints || !this.session.configuration.capabilities.supportsFunctionBreakpoints) {
return TPromise.as(null);
}
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {
const data: { [id: string]: { name?: string, verified?: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateFunctionBreakpoints(data);
});
}
private sendExceptionBreakpoints(): TPromise<any> {
if (!this.session || !this.session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) {
return TPromise.as(null);
}
const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
return this.session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) });
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED)));
fileChangesEvent.getUpdated().forEach(event => {
if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) {
this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false;
this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError);
}
});
}
private store(): void {
this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE);
this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.configurationManager.configurationName, StorageScope.WORKSPACE);
this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
}
public dispose(): void {
this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd);
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/electron-browser/debugService.ts | 1 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.010657749138772488,
0.0005395183688960969,
0.0001634615910006687,
0.00017415831098333,
0.0013289221096783876
] |
{
"id": 0,
"code_window": [
"\n",
"\tprivate getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {\n",
"\t\tlet session = debugService.getActiveSession();\n",
"\t\treturn session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {\n",
"\t\t\tthis.stoppedDetails.totalFrames = response.body.totalFrames;\n",
"\t\t\treturn response.body.stackFrames.map((rsf, level) => {\n",
"\t\t\t\tif (!rsf) {\n",
"\t\t\t\t\treturn new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', \"Unknown stack location\"), undefined, undefined);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (!response || !response.body) {\n",
"\t\t\t\treturn [];\n",
"\t\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "add",
"edit_start_line_idx": 134
} | CREATE VIEW METRIC_STATS (ID, MONTH, TEMP_C, RAIN_C) AS
SELECT ID,
MONTH,
(TEMP_F - 32) * 5 /9,
RAIN_I * 0.3937
FROM STATS; | extensions/sql/test/colorize-fixtures/test.sql | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00016066449461504817,
0.00016066449461504817,
0.00016066449461504817,
0.00016066449461504817,
0
] |
{
"id": 0,
"code_window": [
"\n",
"\tprivate getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {\n",
"\t\tlet session = debugService.getActiveSession();\n",
"\t\treturn session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {\n",
"\t\t\tthis.stoppedDetails.totalFrames = response.body.totalFrames;\n",
"\t\t\treturn response.body.stackFrames.map((rsf, level) => {\n",
"\t\t\t\tif (!rsf) {\n",
"\t\t\t\t\treturn new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', \"Unknown stack location\"), undefined, undefined);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (!response || !response.body) {\n",
"\t\t\t\treturn [];\n",
"\t\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "add",
"edit_start_line_idx": 134
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"close": "閉じる"
} | i18n/jpn/src/vs/workbench/api/node/extHostMessageService.i18n.json | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017685133207123727,
0.00017685133207123727,
0.00017685133207123727,
0.00017685133207123727,
0
] |
{
"id": 0,
"code_window": [
"\n",
"\tprivate getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {\n",
"\t\tlet session = debugService.getActiveSession();\n",
"\t\treturn session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {\n",
"\t\t\tthis.stoppedDetails.totalFrames = response.body.totalFrames;\n",
"\t\t\treturn response.body.stackFrames.map((rsf, level) => {\n",
"\t\t\t\tif (!rsf) {\n",
"\t\t\t\t\treturn new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', \"Unknown stack location\"), undefined, undefined);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (!response || !response.body) {\n",
"\t\t\t\treturn [];\n",
"\t\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "add",
"edit_start_line_idx": 134
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"err.tooMuchData": "抱歉,VS 程式碼有太多 JavaScript 來源檔案。請考慮在 jsconfig.json 中使用 exclude-property。"
} | i18n/cht/src/vs/languages/typescript/common/typescriptMode.i18n.json | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017541593115311116,
0.00017541593115311116,
0.00017541593115311116,
0.00017541593115311116,
0
] |
{
"id": 1,
"code_window": [
"\t\t\tcount,\n",
"\t\t\tfilter\n",
"\t\t}).then(response => {\n",
"\t\t\treturn arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n",
"\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\treturn response && response.body && response.body.variables ? arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 297
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import {guessMimeTypes} from 'vs/base/common/mime';
import Event, {Emitter} from 'vs/base/common/event';
import uri from 'vs/base/common/uri';
import {RunOnceScheduler} from 'vs/base/common/async';
import {Action} from 'vs/base/common/actions';
import arrays = require('vs/base/common/arrays');
import types = require('vs/base/common/types');
import errors = require('vs/base/common/errors');
import severity from 'vs/base/common/severity';
import {TPromise} from 'vs/base/common/winjs.base';
import aria = require('vs/base/browser/ui/aria/aria');
import editorbrowser = require('vs/editor/browser/editorBrowser');
import {ISuggestion} from 'vs/editor/common/modes';
import {Position} from 'vs/editor/common/core/position';
import {IContextKeyService, IContextKey} from 'vs/platform/contextkey/common/contextkey';
import {IMarkerService} from 'vs/platform/markers/common/markers';
import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle';
import {IExtensionService} from 'vs/platform/extensions/common/extensions';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IFileService, FileChangesEvent, FileChangeType, EventType} from 'vs/platform/files/common/files';
import {IEventService} from 'vs/platform/event/common/event';
import {IMessageService, CloseAction} from 'vs/platform/message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {TelemetryService} from 'vs/platform/telemetry/common/telemetryService';
import {TelemetryAppenderClient} from 'vs/platform/telemetry/common/telemetryIpc';
import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage';
import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService';
import {asFileEditorInput} from 'vs/workbench/common/editor';
import debug = require('vs/workbench/parts/debug/common/debug');
import {RawDebugSession} from 'vs/workbench/parts/debug/electron-browser/rawDebugSession';
import model = require('vs/workbench/parts/debug/common/debugModel');
import {DebugStringEditorInput, DebugErrorEditorInput} from 'vs/workbench/parts/debug/browser/debugEditorInputs';
import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel');
import debugactions = require('vs/workbench/parts/debug/browser/debugActions');
import {ConfigurationManager} from 'vs/workbench/parts/debug/node/debugConfigurationManager';
import {Source} from 'vs/workbench/parts/debug/common/debugSource';
import {ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary} from 'vs/workbench/parts/tasks/common/taskService';
import {TaskError, TaskErrors} from 'vs/workbench/parts/tasks/common/taskSystem';
import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService';
import {IPanelService} from 'vs/workbench/services/panel/common/panelService';
import {IPartService} from 'vs/workbench/services/part/common/partService';
import {ITextFileService} from 'vs/workbench/parts/files/common/files';
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {IWindowService, IBroadcast} from 'vs/workbench/services/window/electron-browser/windowService';
import {ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL} from 'vs/workbench/services/thread/electron-browser/threadService';
import {ipcRenderer as ipc} from 'electron';
import {Client} from 'vs/base/parts/ipc/node/ipc.cp';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname';
export class DebugService implements debug.IDebugService {
public _serviceBrand: any;
private _state: debug.State;
private _onDidChangeState: Emitter<debug.State>;
private session: RawDebugSession;
private model: model.Model;
private viewModel: viewmodel.ViewModel;
private configurationManager: ConfigurationManager;
private customTelemetryService: ITelemetryService;
private lastTaskEvent: TaskEvent;
private toDispose: lifecycle.IDisposable[];
private toDisposeOnSessionEnd: lifecycle.IDisposable[];
private inDebugMode: IContextKey<boolean>;
private breakpointsToSendOnResourceSaved: { [uri: string]: boolean };
constructor(
@IStorageService private storageService: IStorageService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@ITextFileService private textFileService: ITextFileService,
@IViewletService private viewletService: IViewletService,
@IPanelService private panelService: IPanelService,
@IFileService private fileService: IFileService,
@IMessageService private messageService: IMessageService,
@IPartService private partService: IPartService,
@IWindowService private windowService: IWindowService,
@ITelemetryService private telemetryService: ITelemetryService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@IEditorGroupService private editorGroupService: IEditorGroupService,
@IEventService eventService: IEventService,
@ILifecycleService private lifecycleService: ILifecycleService,
@IInstantiationService private instantiationService: IInstantiationService,
@IExtensionService private extensionService: IExtensionService,
@IMarkerService private markerService: IMarkerService,
@ITaskService private taskService: ITaskService,
@IConfigurationService private configurationService: IConfigurationService
) {
this.toDispose = [];
this.toDisposeOnSessionEnd = [];
this.session = null;
this.breakpointsToSendOnResourceSaved = {};
this._state = debug.State.Inactive;
this._onDidChangeState = new Emitter<debug.State>();
if (!this.contextService.getWorkspace()) {
this._state = debug.State.Disabled;
}
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, 'null'));
this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadWatchExpressions());
this.toDispose.push(this.model);
this.viewModel = new viewmodel.ViewModel();
this.registerListeners(eventService, lifecycleService);
}
private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void {
this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e)));
if (this.taskService) {
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => {
this.lastTaskEvent = e;
}));
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => {
if (e.type === TaskType.SingleRun) {
this.lastTaskEvent = null;
}
}));
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => {
this.lastTaskEvent = null;
}));
}
lifecycleService.onShutdown(this.store, this);
lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this));
}
private onBroadcast(broadcast: IBroadcast): void {
// attach: PH is ready to be attached to
if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) {
this.rawAttach(broadcast.payload.port);
return;
}
if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) {
this.onSessionEnd();
return;
}
// from this point on we require an active session
let session = this.getActiveSession();
if (!session || session.configuration.type !== 'extensionHost') {
return; // we are only intersted if we have an active debug session for extensionHost
}
// a plugin logged output, show it inside the REPL
if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) {
let extensionOutput: ILogEntry = broadcast.payload;
let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info;
let args: any[] = [];
try {
let parsed = JSON.parse(extensionOutput.arguments);
args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o]));
} catch (error) {
args.push(extensionOutput.arguments);
}
// add output for each argument logged
let simpleVals: any[] = [];
for (let i = 0; i < args.length; i++) {
let a = args[i];
// undefined gets printed as 'undefined'
if (typeof a === 'undefined') {
simpleVals.push('undefined');
}
// null gets printed as 'null'
else if (a === null) {
simpleVals.push('null');
}
// objects & arrays are special because we want to inspect them in the REPL
else if (types.isObject(a) || Array.isArray(a)) {
// flush any existing simple values logged
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev);
simpleVals = [];
}
// show object
this.logToRepl(a, sev);
}
// string: watch out for % replacement directive
// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
else if (typeof a === 'string') {
let buf = '';
for (let j = 0, len = a.length; j < len; j++) {
if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) {
i++; // read over substitution
buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace
j++; // read over directive
} else {
buf += a[j];
}
}
simpleVals.push(buf);
}
// number or boolean is joined together
else {
simpleVals.push(a);
}
}
// flush simple values
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev);
}
}
}
private registerSessionListeners(): void {
this.toDisposeOnSessionEnd.push(this.session);
this.toDisposeOnSessionEnd.push(this.session.onDidInitialize(event => {
aria.status(nls.localize('debuggingStarted', "Debugging started."));
this.sendAllBreakpoints().then(() => {
if (this.session.configuration.capabilities.supportsConfigurationDoneRequest) {
this.session.configurationDone().done(null, e => {
// Disconnect the debug session on configuration done error #10596
if (this.session) {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
this.messageService.show(severity.Error, e.message);
});
}
});
}));
this.toDisposeOnSessionEnd.push(this.session.onDidStop(event => {
this.setStateAndEmit(debug.State.Stopped);
const threadId = event.body.threadId;
this.getThreadData().done(() => {
this.model.rawUpdate({
threadId,
stoppedDetails: event.body,
allThreadsStopped: event.body.allThreadsStopped
});
const thread = this.model.getThreads()[threadId];
thread.getCallStack(this).then(callStack => {
if (callStack.length > 0) {
// focus first stack frame from top that has source location
const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]);
this.setFocusedStackFrameAndEvaluate(stackFrameToFocus, thread).done(null, errors.onUnexpectedError);
this.windowService.getWindow().focus();
aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber));
return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false);
} else {
this.setFocusedStackFrameAndEvaluate(null, thread).done(null, errors.onUnexpectedError);
}
});
}, errors.onUnexpectedError);
}));
this.toDisposeOnSessionEnd.push(this.session.onDidThread(event => {
if (event.body.reason === 'started') {
this.getThreadData().done(null, errors.onUnexpectedError);
} else if (event.body.reason === 'exited') {
this.model.clearThreads(true, event.body.threadId);
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidTerminateDebugee(event => {
aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
if (this.session && this.session.getId() === event.body.sessionId) {
if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) {
this.restartSession().done(null, err => this.messageService.show(severity.Error, err.message));
} else {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidContinued(event => {
this.lazyTransitionToRunningState(event.body.allThreadsContinued ? undefined : event.body.threadId);
}));
this.toDisposeOnSessionEnd.push(this.session.onDidOutput(event => {
if (event.body && event.body.category === 'telemetry') {
// only log telemetry events from debug adapter if the adapter provided the telemetry key
// and the user opted in telemetry
if (this.customTelemetryService && this.telemetryService.isOptedIn) {
this.customTelemetryService.publicLog(event.body.output, event.body.data);
}
} else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) {
this.onOutput(event);
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidBreakpoint(event => {
const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (breakpoint) {
this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint });
} else {
const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (functionBreakpoint) {
this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint });
}
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidExitAdapter(event => {
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (this.session.configuration.type === 'extensionHost' && this._state === debug.State.RunningNoDebug) {
ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath);
}
if (this.session && this.session.getId() === event.body.sessionId) {
this.onSessionEnd();
}
}));
}
private onOutput(event: DebugProtocol.OutputEvent): void {
const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info;
this.appendReplOutput(event.body.output, outputSeverity);
}
private getThreadData(): TPromise<void> {
return this.session.threads().then(response => {
response.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread }));
});
}
private loadBreakpoints(): debug.IBreakpoint[] {
let result: debug.IBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }),
breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition);
});
} catch (e) { }
return result || [];
}
private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
let result: debug.IFunctionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
return new model.FunctionBreakpoint(fb.name, fb.enabled);
});
} catch (e) { }
return result || [];
}
private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
let result: debug.IExceptionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled);
});
} catch (e) { }
return result || [];
}
private loadWatchExpressions(): model.Expression[] {
let result: model.Expression[];
try {
result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string } ) => {
return new model.Expression(watchStoredData.name, false, watchStoredData.id);
});
} catch (e) { }
return result || [];
}
public get state(): debug.State {
return this._state;
}
public get onDidChangeState(): Event<debug.State> {
return this._onDidChangeState.event;
}
private setStateAndEmit(newState: debug.State): void {
this._state = newState;
this._onDidChangeState.fire(newState);
}
public get enabled(): boolean {
return !!this.contextService.getWorkspace();
}
public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame, thread?: debug.IThread): TPromise<void> {
if (!thread && focusedStackFrame) {
thread = this.model.getThreads()[focusedStackFrame.threadId];
}
this.viewModel.setFocusedStackFrame(focusedStackFrame, thread);
if (focusedStackFrame) {
return this.model.evaluateWatchExpressions(this.session, focusedStackFrame);
} else {
this.model.clearWatchExpressionValues();
return TPromise.as(null);
}
}
public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof model.Breakpoint) {
return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri);
} else if (breakpoint instanceof model.FunctionBreakpoint) {
return this.sendFunctionBreakpoints();
}
return this.sendExceptionBreakpoints();
}
this.model.enableOrDisableAllBreakpoints(enable);
return this.sendAllBreakpoints();
}
public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void[]> {
this.model.addBreakpoints(rawBreakpoints);
const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri);
rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath)));
return TPromise.join(uris.map(uri => this.sendBreakpoints(uri)));
}
public removeBreakpoints(id?: string): TPromise<any> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.source.uri.fsPath)));
const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri);
this.model.removeBreakpoints(toRemove);
return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri)));
}
public setBreakpointsActivated(activated: boolean): TPromise<void> {
this.model.setBreakpointsActivated(activated);
return this.sendAllBreakpoints();
}
public addFunctionBreakpoint(): void {
this.model.addFunctionBreakpoint('');
}
public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> {
this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } });
return this.sendFunctionBreakpoints();
}
public removeFunctionBreakpoints(id?: string): TPromise<void> {
this.model.removeFunctionBreakpoints(id);
return this.sendFunctionBreakpoints();
}
public addReplExpression(name: string): TPromise<void> {
this.telemetryService.publicLog('debugService/addReplExpression');
const focussedStackFrame = this.viewModel.getFocusedStackFrame();
return this.model.addReplExpression(this.session, focussedStackFrame, name)
// Evaluate all watch expressions again since repl evaluation might have changed some.
.then(() => this.setFocusedStackFrameAndEvaluate(focussedStackFrame));
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
this.model.logToRepl(value, severity);
}
public appendReplOutput(value: string, severity?: severity): void {
this.model.appendReplOutput(value, severity);
}
public removeReplExpressions(): void {
this.model.removeReplExpressions();
}
public setVariable(variable: debug.IExpression, value: string): TPromise<any> {
if (!this.session || !(variable instanceof model.Variable)) {
return TPromise.as(null);
}
return this.session.setVariable({
name: variable.name,
value,
variablesReference: (<model.Variable>variable).parent.reference
}).then(response => {
variable.value = response.body.value;
// Evaluate all watch expressions again since changing variable value might have changed some #8118.
return this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame());
}, err => {
(<model.Variable>variable).errorMessage = err.message;
});
}
public addWatchExpression(name: string): TPromise<void> {
return this.model.addWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), name);
}
public renameWatchExpression(id: string, newName: string): TPromise<void> {
return this.model.renameWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), id, newName);
}
public removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
}
public createSession(noDebug: boolean, configuration?: debug.IConfig): TPromise<any> {
this.removeReplExpressions();
return this.textFileService.saveAll() // make sure all dirty files are saved
.then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date
.then(() => this.extensionService.onReady()
.then(() => this.configurationManager.setConfiguration(configuration || this.configurationManager.configurationName)
.then(() => this.configurationManager.resolveInteractiveVariables())
.then(resolvedConfiguration => {
configuration = resolvedConfiguration;
if (!configuration) {
return this.configurationManager.openConfigFile(false).then(openend => {
if (openend) {
this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application."));
}
});
}
if (configuration.silentlyAbort) {
return;
}
configuration.noDebug = noDebug;
if (!this.configurationManager.adapter) {
return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type)))
: TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."),
{ actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] }));
}
return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => {
const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return this.doCreateSession(configuration);
}
this.messageService.show(severity.Error, {
message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) :
errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) :
nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode),
actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => {
this.messageService.hideAll();
return this.doCreateSession(configuration);
}), CloseAction]
});
}, (err: TaskError) => {
if (err.code !== TaskErrors.NotConfigured) {
throw err;
}
this.messageService.show(err.severity, {
message: err.message,
actions: [this.taskService.configureAction(), CloseAction]
});
});
}))));
}
private doCreateSession(configuration: debug.IExtHostConfig): TPromise<any> {
this.setStateAndEmit(debug.State.Initializing);
return this.telemetryService.getTelemetryInfo().then(info => {
const telemetryInfo: { [key: string]: string } = Object.create(null);
telemetryInfo['common.vscodemachineid'] = info.machineId;
telemetryInfo['common.vscodesessionid'] = info.sessionId;
return telemetryInfo;
}).then(data => {
const { aiKey, type } = this.configurationManager.adapter;
const publisher = this.configurationManager.adapter.extensionDescription.publisher;
this.customTelemetryService = null;
if (aiKey) {
const client = new Client(
uri.parse(require.toUrl('bootstrap')).fsPath,
{
serverName: 'Debug Telemetry',
timeout: 1000 * 60 * 5,
args: [`${ publisher }.${ type }`, JSON.stringify(data), aiKey],
env: {
ELECTRON_RUN_AS_NODE: 1,
PIPE_LOGGING: 'true',
AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp'
}
}
);
const channel = client.getChannel('telemetryAppender');
const appender = new TelemetryAppenderClient(channel);
this.toDisposeOnSessionEnd.push(client);
this.customTelemetryService = new TelemetryService({ appender }, this.configurationService);
}
this.session = this.instantiationService.createInstance(RawDebugSession, configuration.debugServer, this.configurationManager.adapter, this.customTelemetryService);
this.registerSessionListeners();
return this.session.initialize({
adapterID: configuration.type,
pathFormat: 'path',
linesStartAt1: true,
columnsStartAt1: true,
supportsVariableType: true, // #8858
supportsVariablePaging: true, // #9537
supportsRunInTerminalRequest: true // #10574
}).then((result: DebugProtocol.InitializeResponse) => {
if (!this.session) {
return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly")));
}
this.model.setExceptionBreakpoints(this.session.configuration.capabilities.exceptionBreakpointFilters);
return configuration.request === 'attach' ? this.session.attach(configuration) : this.session.launch(configuration);
}).then((result: DebugProtocol.Response) => {
if (!this.session) {
return TPromise.as(null);
}
if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) {
// We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden
this.viewModel.changedWorkbenchViewState = true;
this.viewletService.openViewlet(debug.VIEWLET_ID);
}
// Do not change status bar to orange if we are just running without debug.
if (!configuration.noDebug) {
this.partService.addClass('debugging');
}
this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError);
this.inDebugMode.set(true);
this.lazyTransitionToRunningState();
this.telemetryService.publicLog('debugSessionStart', {
type: configuration.type,
breakpointCount: this.model.getBreakpoints().length,
exceptionBreakpoints: this.model.getExceptionBreakpoints(),
watchExpressionsCount: this.model.getWatchExpressions().length,
extensionName: `${ this.configurationManager.adapter.extensionDescription.publisher }.${ this.configurationManager.adapter.extensionDescription.name }`,
isBuiltin: this.configurationManager.adapter.extensionDescription.isBuiltin
});
}).then(undefined, (error: any) => {
if (error instanceof Error && error.message === 'Canceled') {
// Do not show 'canceled' error messages to the user #7906
return TPromise.as(null);
}
this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined });
this.setStateAndEmit(debug.State.Inactive);
if (this.session) {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
// Show the repl if some error got logged there #5870
if (this.model.getReplElements().length > 0) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction];
return TPromise.wrapError(errors.create(error.message, { actions }));
});
});
}
private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> {
if (!taskName) {
return TPromise.as(null);
}
// run a task before starting a debug session
return this.taskService.tasks().then(descriptions => {
const filteredTasks = descriptions.filter(task => task.name === taskName);
if (filteredTasks.length !== 1) {
return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), {
actions: [
this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL),
this.taskService.configureAction(),
CloseAction
]
}));
}
// task is already running - nothing to do.
if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) {
return TPromise.as(null);
}
if (this.lastTaskEvent) {
// there is a different task running currently.
return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName)));
}
// no task running, execute the preLaunchTask.
const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => {
this.lastTaskEvent = null;
return result;
}, err => {
this.lastTaskEvent = null;
});
if (filteredTasks[0].isWatching) {
return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null)));
}
return taskPromise;
});
}
private rawAttach(port: number): TPromise<any> {
if (this.session) {
return this.session.attach({ port });
}
this.setStateAndEmit(debug.State.Initializing);
const configuration = <debug.IExtHostConfig>this.configurationManager.configuration;
return this.doCreateSession({
type: configuration.type,
request: 'attach',
port,
sourceMaps: configuration.sourceMaps,
outDir: configuration.outDir,
debugServer: configuration.debugServer
});
}
public restartSession(): TPromise<any> {
return this.session ? this.session.disconnect(true).then(() =>
new TPromise<void>((c, e) => {
setTimeout(() => {
this.createSession(false, null).then(() => c(null), err => e(err));
}, 300);
})
) : this.createSession(false, null);
}
public getActiveSession(): debug.IRawDebugSession {
return this.session;
}
private onSessionEnd(): void {
if (this.session) {
const bpsExist = this.model.getBreakpoints().length > 0;
this.telemetryService.publicLog('debugSessionStop', {
type: this.session.configuration.type,
success: this.session.emittedStopped || !bpsExist,
sessionLengthInSeconds: this.session.getLengthInSeconds(),
breakpointCount: this.model.getBreakpoints().length,
watchExpressionsCount: this.model.getWatchExpressions().length
});
}
this.session = null;
try {
this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd);
} catch (e) {
// an internal module might be open so the dispose can throw -> ignore and continue with stop session.
}
this.partService.removeClass('debugging');
this.model.clearThreads(true);
this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError);
this.setStateAndEmit(debug.State.Inactive);
// set breakpoints back to unverified since the session ended.
// source reference changes across sessions, so we do not use it to persist the source.
const data: { [id: string]: { line: number, verified: boolean } } = {};
this.model.getBreakpoints().forEach(bp => {
delete bp.source.raw.sourceReference;
data[bp.getId()] = { line: bp.lineNumber, verified: false };
});
this.model.updateBreakpoints(data);
this.inDebugMode.reset();
}
public getModel(): debug.IModel {
return this.model;
}
public getViewModel(): debug.IViewModel {
return this.viewModel;
}
public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> {
const visibleEditors = this.editorService.getVisibleEditors();
for (let i = 0; i < visibleEditors.length; i++) {
const fileInput = asFileEditorInput(visibleEditors[i].input);
if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) ||
(visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) {
const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl();
if (control) {
control.revealLineInCenterIfOutsideViewport(lineNumber);
control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 });
this.editorGroupService.activateGroup(i);
if (!preserveFocus) {
this.editorGroupService.focusGroup(i);
}
}
return TPromise.as(null);
}
}
if (source.inMemory) {
// internal module
if (source.reference !== 0 && this.session && source.available) {
return this.session.source({ sourceReference: source.reference }).then(response => {
const mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0];
return this.getDebugStringEditorInput(source, response.body.content, mime);
}, (err: DebugProtocol.ErrorResponse) => {
// Display the error from debug adapter using a temporary editor #8836
return this.getDebugErrorEditorInput(source, err.message);
}).then(editorInput => {
return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide);
});
}
return this.sourceIsUnavailable(source, sideBySide);
}
return this.fileService.resolveFile(source.uri).then(() =>
this.editorService.openEditor({
resource: source.uri,
options: {
selection: {
startLineNumber: lineNumber,
startColumn: 1,
endLineNumber: lineNumber,
endColumn: 1
},
preserveFocus: preserveFocus
}
}, sideBySide), err => this.sourceIsUnavailable(source, sideBySide)
);
}
private sourceIsUnavailable(source: Source, sideBySide: boolean): TPromise<any> {
this.model.sourceIsUnavailable(source);
const editorInput = this.getDebugErrorEditorInput(source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name));
return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide);
}
public getConfigurationManager(): debug.IConfigurationManager {
return this.configurationManager;
}
public next(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.next({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepIn(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepIn({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepOut(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepOut({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepBack(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepBack({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public continue(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.continue({ threadId }).then(response => {
const allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true;
this.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId);
});
}
public pause(threadId: number): TPromise<any> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.pause({ threadId });
}
public restartFrame(frameId: number): TPromise<any> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.restartFrame({ frameId });
}
public completions(text: string, position: Position): TPromise<ISuggestion[]> {
if (!this.session || !this.session.configuration.capabilities.supportsCompletionsRequest) {
return TPromise.as([]);
}
const focussedStackFrame = this.viewModel.getFocusedStackFrame();
return this.session.completions({
frameId: focussedStackFrame ? focussedStackFrame.frameId : undefined,
text,
column: position.column,
line: position.lineNumber
}).then(response => {
return !response ? [] : response.body.targets.map(item => ({
label: item.label,
insertText: item.text || item.label,
type: item.type
}));
}, err => []);
}
private lazyTransitionToRunningState(threadId?: number): void {
let setNewFocusedStackFrameScheduler: RunOnceScheduler;
const toDispose = this.session.onDidStop(e => {
if (e.body.threadId === threadId || e.body.allThreadsStopped || !threadId) {
setNewFocusedStackFrameScheduler.cancel();
}
});
this.model.clearThreads(false, threadId);
// Get a top stack frame of a stopped thread if there is any.
const threads = this.model.getThreads();
const stoppedReference = Object.keys(threads).filter(ref => threads[ref].stopped).pop();
const stoppedThread = stoppedReference ? threads[parseInt(stoppedReference)] : null;
const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null;
const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null;
if (!stoppedThread) {
this.setStateAndEmit(this.configurationManager.configuration.noDebug ? debug.State.RunningNoDebug : debug.State.Running);
}
// Do not immediatly set a new focused stack frame since that might cause unnecessery flickering
// of the tree in the debug viewlet. Only set focused stack frame if no stopped event has arrived in 500ms.
setNewFocusedStackFrameScheduler = new RunOnceScheduler(() => {
toDispose.dispose();
aria.status(nls.localize('debuggingContinued', "Debugging continued."));
this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError);
}, 500);
setNewFocusedStackFrameScheduler.schedule();
}
private getDebugStringEditorInput(source: Source, value: string, mtype: string): DebugStringEditorInput {
const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0);
this.toDisposeOnSessionEnd.push(result);
return result;
}
private getDebugErrorEditorInput(source: Source, value: string): DebugErrorEditorInput {
const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value);
this.toDisposeOnSessionEnd.push(result);
return result;
}
private sendAllBreakpoints(): TPromise<any> {
return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri)))
.then(() => this.sendFunctionBreakpoints())
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints());
}
private sendBreakpoints(modelUri: uri, sourceModified = false): TPromise<void> {
if (!this.session || !this.session.readyForBreakpoints) {
return TPromise.as(null);
}
if (this.textFileService.isDirty(modelUri)) {
// Only send breakpoints for a file once it is not dirty #8077
this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true;
return TPromise.as(null);
}
const breakpointsToSend = arrays.distinct(
this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()),
bp => `${bp.desiredLineNumber}`
);
const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model);
return this.session.setBreakpoints({
source: rawSource,
lines: breakpointsToSend.map(bp => bp.desiredLineNumber),
breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })),
sourceModified
}).then(response => {
const data: { [id: string]: { line?: number, verified: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateBreakpoints(data);
});
}
private sendFunctionBreakpoints(): TPromise<void> {
if (!this.session || !this.session.readyForBreakpoints || !this.session.configuration.capabilities.supportsFunctionBreakpoints) {
return TPromise.as(null);
}
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {
const data: { [id: string]: { name?: string, verified?: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateFunctionBreakpoints(data);
});
}
private sendExceptionBreakpoints(): TPromise<any> {
if (!this.session || !this.session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) {
return TPromise.as(null);
}
const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
return this.session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) });
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED)));
fileChangesEvent.getUpdated().forEach(event => {
if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) {
this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false;
this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError);
}
});
}
private store(): void {
this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE);
this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.configurationManager.configurationName, StorageScope.WORKSPACE);
this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
}
public dispose(): void {
this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd);
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/electron-browser/debugService.ts | 1 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.034753717482089996,
0.0005295543232932687,
0.0001616595109226182,
0.00017337410827167332,
0.003267494263127446
] |
{
"id": 1,
"code_window": [
"\t\t\tcount,\n",
"\t\t\tfilter\n",
"\t\t}).then(response => {\n",
"\t\t\treturn arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n",
"\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\treturn response && response.body && response.body.variables ? arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 297
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"allFiles": "Tous les fichiers",
"cancel": "Annuler",
"dontSave": "&&Ne pas enregistrer",
"moreFile": "...1 fichier supplémentaire non affiché",
"moreFiles": "...{0} fichiers supplémentaires non affichés",
"save": "Enregi&&strer",
"saveAll": "&&Enregistrer tout",
"saveChangesDetail": "Vous perdrez vos modifications, si vous ne les enregistrez pas.",
"saveChangesMessage": "Voulez-vous enregistrer les modifications apportées à {0} ?",
"saveChangesMessages": "Voulez-vous enregistrer les modifications apportées aux {0} fichiers suivants ?"
} | i18n/fra/src/vs/workbench/parts/files/electron-browser/textFileServices.i18n.json | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017630767251830548,
0.0001747372152749449,
0.00017316675803158432,
0.0001747372152749449,
0.000001570457243360579
] |
{
"id": 1,
"code_window": [
"\t\t\tcount,\n",
"\t\t\tfilter\n",
"\t\t}).then(response => {\n",
"\t\t\treturn arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n",
"\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\treturn response && response.body && response.body.variables ? arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 297
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as dom from 'vs/base/browser/dom';
export abstract class FastDomNode {
private _domNode: HTMLElement;
private _maxWidth: number;
private _width: number;
private _height: number;
private _top: number;
private _left: number;
private _bottom: number;
private _right: number;
private _fontFamily: string;
private _fontWeight: string;
private _fontSize: number;
private _lineHeight: number;
private _className: string;
private _display: string;
private _position: string;
private _visibility: string;
private _transform: string;
private _lineNumber: string;
public get domNode(): HTMLElement {
return this._domNode;
}
constructor(domNode: HTMLElement) {
this._domNode = domNode;
this._maxWidth = -1;
this._width = -1;
this._height = -1;
this._top = -1;
this._left = -1;
this._bottom = -1;
this._right = -1;
this._fontFamily = '';
this._fontWeight = '';
this._fontSize = -1;
this._lineHeight = -1;
this._className = '';
this._display = '';
this._position = '';
this._visibility = '';
this._transform = '';
this._lineNumber = '';
}
public setMaxWidth(maxWidth: number): void {
if (this._maxWidth === maxWidth) {
return;
}
this._maxWidth = maxWidth;
this._domNode.style.maxWidth = this._maxWidth + 'px';
}
public setWidth(width: number): void {
if (this._width === width) {
return;
}
this._width = width;
this._domNode.style.width = this._width + 'px';
}
public setHeight(height: number): void {
if (this._height === height) {
return;
}
this._height = height;
this._domNode.style.height = this._height + 'px';
}
public setTop(top: number): void {
if (this._top === top) {
return;
}
this._top = top;
this._domNode.style.top = this._top + 'px';
}
public setLeft(left: number): void {
if (this._left === left) {
return;
}
this._left = left;
this._domNode.style.left = this._left + 'px';
}
public setBottom(bottom: number): void {
if (this._bottom === bottom) {
return;
}
this._bottom = bottom;
this._domNode.style.bottom = this._bottom + 'px';
}
public setRight(right: number): void {
if (this._right === right) {
return;
}
this._right = right;
this._domNode.style.right = this._right + 'px';
}
public setFontFamily(fontFamily: string): void {
if (this._fontFamily === fontFamily) {
return;
}
this._fontFamily = fontFamily;
this._domNode.style.fontFamily = this._fontFamily;
}
public setFontWeight(fontWeight: string): void {
if (this._fontWeight === fontWeight) {
return;
}
this._fontWeight = fontWeight;
this._domNode.style.fontWeight = this._fontWeight;
}
public setFontSize(fontSize: number): void {
if (this._fontSize === fontSize) {
return;
}
this._fontSize = fontSize;
this._domNode.style.fontSize = this._fontSize + 'px';
}
public setLineHeight(lineHeight: number): void {
if (this._lineHeight === lineHeight) {
return;
}
this._lineHeight = lineHeight;
this._domNode.style.lineHeight = this._lineHeight + 'px';
}
public setClassName(className: string): void {
if (this._className === className) {
return;
}
this._className = className;
this._domNode.className = this._className;
}
public toggleClassName(className: string, shouldHaveIt?: boolean): void {
dom.toggleClass(this._domNode, className, shouldHaveIt);
this._className = this._domNode.className;
}
public setDisplay(display: string): void {
if (this._display === display) {
return;
}
this._display = display;
this._domNode.style.display = this._display;
}
public setPosition(position: string): void {
if (this._position === position) {
return;
}
this._position = position;
this._domNode.style.position = this._position;
}
public setVisibility(visibility: string): void {
if (this._visibility === visibility) {
return;
}
this._visibility = visibility;
this._domNode.style.visibility = this._visibility;
}
public setTransform(transform:string): void {
if (this._transform === transform) {
return;
}
this._transform = transform;
this._setTransform(this._domNode, this._transform);
}
protected abstract _setTransform(domNode:HTMLElement, transform:string): void;
public setLineNumber(lineNumber:string): void {
if (this._lineNumber === lineNumber) {
return;
}
this._lineNumber = lineNumber;
this._domNode.setAttribute('lineNumber', this._lineNumber);
}
}
class WebKitFastDomNode extends FastDomNode {
protected _setTransform(domNode:HTMLElement, transform:string): void {
(<any>domNode.style).webkitTransform = transform;
}
}
class StandardFastDomNode extends FastDomNode {
protected _setTransform(domNode:HTMLElement, transform:string): void {
domNode.style.transform = transform;
}
}
let useWebKitFastDomNode = false;
(function() {
let testDomNode = document.createElement('div');
if (typeof (<any>testDomNode.style).webkitTransform !== 'undefined') {
useWebKitFastDomNode = true;
}
})();
export function createFastDomNode(domNode: HTMLElement): FastDomNode {
if (useWebKitFastDomNode) {
return new WebKitFastDomNode(domNode);
} else {
return new StandardFastDomNode(domNode);
}
}
export const StyleMutator = {
setMaxWidth: (domNode: HTMLElement, maxWidth: number) => {
let desiredValue = maxWidth + 'px';
if (domNode.style.maxWidth !== desiredValue) {
domNode.style.maxWidth = desiredValue;
}
},
setWidth: (domNode: HTMLElement, width: number) => {
let desiredValue = width + 'px';
if (domNode.style.width !== desiredValue) {
domNode.style.width = desiredValue;
}
},
setHeight: (domNode: HTMLElement, height: number) => {
let desiredValue = height + 'px';
if (domNode.style.height !== desiredValue) {
domNode.style.height = desiredValue;
}
},
setTop: (domNode: HTMLElement, top: number) => {
let desiredValue = top + 'px';
if (domNode.style.top !== desiredValue) {
domNode.style.top = desiredValue;
return true;
}
return false;
},
setLeft: (domNode: HTMLElement, left: number) => {
let desiredValue = left + 'px';
if (domNode.style.left !== desiredValue) {
domNode.style.left = desiredValue;
return true;
}
return false;
},
setBottom: (domNode: HTMLElement, bottom: number) => {
let desiredValue = bottom + 'px';
if (domNode.style.bottom !== desiredValue) {
domNode.style.bottom = desiredValue;
}
},
setRight: (domNode: HTMLElement, right: number) => {
let desiredValue = right + 'px';
if (domNode.style.right !== desiredValue) {
domNode.style.right = desiredValue;
}
},
setFontSize: (domNode: HTMLElement, fontSize: number) => {
let desiredValue = fontSize + 'px';
if (domNode.style.fontSize !== desiredValue) {
domNode.style.fontSize = desiredValue;
}
},
setLineHeight: (domNode: HTMLElement, lineHeight: number) => {
let desiredValue = lineHeight + 'px';
if (domNode.style.lineHeight !== desiredValue) {
domNode.style.lineHeight = desiredValue;
}
},
setTransform: null,
setDisplay: (domNode: HTMLElement, desiredValue: string) => {
if (domNode.style.display !== desiredValue) {
domNode.style.display = desiredValue;
}
},
setVisibility: (domNode: HTMLElement, desiredValue: string) => {
if (domNode.style.visibility !== desiredValue) {
domNode.style.visibility = desiredValue;
}
},
};
// Define setTransform
function setWebkitTransform(domNode: HTMLElement, desiredValue: string): boolean {
if (domNode.getAttribute('data-transform') !== desiredValue) {
domNode.setAttribute('data-transform', desiredValue);
(<any>domNode.style).webkitTransform = desiredValue;
return true;
}
return false;
}
function setTransform(domNode: HTMLElement, desiredValue: string): boolean {
if (domNode.getAttribute('data-transform') !== desiredValue) {
domNode.setAttribute('data-transform', desiredValue);
domNode.style.transform = desiredValue;
return true;
}
return false;
}
(function() {
let testDomNode = document.createElement('div');
if (typeof (<any>testDomNode.style).webkitTransform !== 'undefined') {
StyleMutator.setTransform = setWebkitTransform;
} else {
StyleMutator.setTransform = setTransform;
}
})(); | src/vs/base/browser/styleMutator.ts | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017631390073802322,
0.00017263204790651798,
0.00016392639372497797,
0.00017314069555141032,
0.000002980632189064636
] |
{
"id": 1,
"code_window": [
"\t\t\tcount,\n",
"\t\t\tfilter\n",
"\t\t}).then(response => {\n",
"\t\t\treturn arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n",
"\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\treturn response && response.body && response.body.variables ? arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 297
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"error.connection.unknown": "Error de conexión desconocido. Es posible que ya no esté conectado a Internet o que el servidor al que se había conectado esté sin conexión.",
"error.connection.unknown.verbose": "Error de conexión desconocido ({0})",
"error.defaultMessage": "Se ha producido un error desconocido. Consulte el registro para obtener más detalles.",
"error.http": "{0} (HTTP {1})",
"error.http.verbose": "{0} (HTTP {1}: {2})",
"error.moreErrors": "{0} ({1} errores en total)",
"error.permission": "Permiso denegado",
"error.permission.verbose": "Permiso denegado (HTTP {0})",
"illegalArgumentError": "Argumento no válido: {0}",
"illegalArgumentError2": "Argumento no válido",
"illegalStateError": "Estado no válido: {0}",
"illegalStateError2": "Estado no válido",
"loaderError": "No se pudo cargar un archivo necesario. O bien no está conectado a Internet o el servidor al que se había conectado está sin conexión. Actualice el explorador y vuelva a intentarlo.",
"loaderErrorNative": "No se pudo cargar un archivo requerido. Reinicie la aplicación para intentarlo de nuevo. Detalles: {0}",
"message": "{0}. Código de error: {1}",
"nodeExceptionMessage": "Se produjo un error del sistema ({0})",
"notImplementedError": "Sin implementar",
"stackTrace.format": "{0}:{1}"
} | i18n/esn/src/vs/base/common/errors.i18n.json | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017259344167541713,
0.00017156875401269644,
0.0001707887277007103,
0.000171324034454301,
7.568164619442541e-7
] |
{
"id": 2,
"code_window": [
"\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type)\n",
"\t\t\t);\n",
"\t\t}, (e: Error) => [new Variable(this, 0, null, e.message, 0, 0, null, false)]);\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t) : [];\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 299
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import {guessMimeTypes} from 'vs/base/common/mime';
import Event, {Emitter} from 'vs/base/common/event';
import uri from 'vs/base/common/uri';
import {RunOnceScheduler} from 'vs/base/common/async';
import {Action} from 'vs/base/common/actions';
import arrays = require('vs/base/common/arrays');
import types = require('vs/base/common/types');
import errors = require('vs/base/common/errors');
import severity from 'vs/base/common/severity';
import {TPromise} from 'vs/base/common/winjs.base';
import aria = require('vs/base/browser/ui/aria/aria');
import editorbrowser = require('vs/editor/browser/editorBrowser');
import {ISuggestion} from 'vs/editor/common/modes';
import {Position} from 'vs/editor/common/core/position';
import {IContextKeyService, IContextKey} from 'vs/platform/contextkey/common/contextkey';
import {IMarkerService} from 'vs/platform/markers/common/markers';
import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle';
import {IExtensionService} from 'vs/platform/extensions/common/extensions';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IFileService, FileChangesEvent, FileChangeType, EventType} from 'vs/platform/files/common/files';
import {IEventService} from 'vs/platform/event/common/event';
import {IMessageService, CloseAction} from 'vs/platform/message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {TelemetryService} from 'vs/platform/telemetry/common/telemetryService';
import {TelemetryAppenderClient} from 'vs/platform/telemetry/common/telemetryIpc';
import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage';
import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService';
import {asFileEditorInput} from 'vs/workbench/common/editor';
import debug = require('vs/workbench/parts/debug/common/debug');
import {RawDebugSession} from 'vs/workbench/parts/debug/electron-browser/rawDebugSession';
import model = require('vs/workbench/parts/debug/common/debugModel');
import {DebugStringEditorInput, DebugErrorEditorInput} from 'vs/workbench/parts/debug/browser/debugEditorInputs';
import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel');
import debugactions = require('vs/workbench/parts/debug/browser/debugActions');
import {ConfigurationManager} from 'vs/workbench/parts/debug/node/debugConfigurationManager';
import {Source} from 'vs/workbench/parts/debug/common/debugSource';
import {ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary} from 'vs/workbench/parts/tasks/common/taskService';
import {TaskError, TaskErrors} from 'vs/workbench/parts/tasks/common/taskSystem';
import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService';
import {IPanelService} from 'vs/workbench/services/panel/common/panelService';
import {IPartService} from 'vs/workbench/services/part/common/partService';
import {ITextFileService} from 'vs/workbench/parts/files/common/files';
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {IWindowService, IBroadcast} from 'vs/workbench/services/window/electron-browser/windowService';
import {ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL} from 'vs/workbench/services/thread/electron-browser/threadService';
import {ipcRenderer as ipc} from 'electron';
import {Client} from 'vs/base/parts/ipc/node/ipc.cp';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname';
export class DebugService implements debug.IDebugService {
public _serviceBrand: any;
private _state: debug.State;
private _onDidChangeState: Emitter<debug.State>;
private session: RawDebugSession;
private model: model.Model;
private viewModel: viewmodel.ViewModel;
private configurationManager: ConfigurationManager;
private customTelemetryService: ITelemetryService;
private lastTaskEvent: TaskEvent;
private toDispose: lifecycle.IDisposable[];
private toDisposeOnSessionEnd: lifecycle.IDisposable[];
private inDebugMode: IContextKey<boolean>;
private breakpointsToSendOnResourceSaved: { [uri: string]: boolean };
constructor(
@IStorageService private storageService: IStorageService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@ITextFileService private textFileService: ITextFileService,
@IViewletService private viewletService: IViewletService,
@IPanelService private panelService: IPanelService,
@IFileService private fileService: IFileService,
@IMessageService private messageService: IMessageService,
@IPartService private partService: IPartService,
@IWindowService private windowService: IWindowService,
@ITelemetryService private telemetryService: ITelemetryService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@IEditorGroupService private editorGroupService: IEditorGroupService,
@IEventService eventService: IEventService,
@ILifecycleService private lifecycleService: ILifecycleService,
@IInstantiationService private instantiationService: IInstantiationService,
@IExtensionService private extensionService: IExtensionService,
@IMarkerService private markerService: IMarkerService,
@ITaskService private taskService: ITaskService,
@IConfigurationService private configurationService: IConfigurationService
) {
this.toDispose = [];
this.toDisposeOnSessionEnd = [];
this.session = null;
this.breakpointsToSendOnResourceSaved = {};
this._state = debug.State.Inactive;
this._onDidChangeState = new Emitter<debug.State>();
if (!this.contextService.getWorkspace()) {
this._state = debug.State.Disabled;
}
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, 'null'));
this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadWatchExpressions());
this.toDispose.push(this.model);
this.viewModel = new viewmodel.ViewModel();
this.registerListeners(eventService, lifecycleService);
}
private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void {
this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e)));
if (this.taskService) {
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => {
this.lastTaskEvent = e;
}));
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => {
if (e.type === TaskType.SingleRun) {
this.lastTaskEvent = null;
}
}));
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => {
this.lastTaskEvent = null;
}));
}
lifecycleService.onShutdown(this.store, this);
lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this));
}
private onBroadcast(broadcast: IBroadcast): void {
// attach: PH is ready to be attached to
if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) {
this.rawAttach(broadcast.payload.port);
return;
}
if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) {
this.onSessionEnd();
return;
}
// from this point on we require an active session
let session = this.getActiveSession();
if (!session || session.configuration.type !== 'extensionHost') {
return; // we are only intersted if we have an active debug session for extensionHost
}
// a plugin logged output, show it inside the REPL
if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) {
let extensionOutput: ILogEntry = broadcast.payload;
let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info;
let args: any[] = [];
try {
let parsed = JSON.parse(extensionOutput.arguments);
args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o]));
} catch (error) {
args.push(extensionOutput.arguments);
}
// add output for each argument logged
let simpleVals: any[] = [];
for (let i = 0; i < args.length; i++) {
let a = args[i];
// undefined gets printed as 'undefined'
if (typeof a === 'undefined') {
simpleVals.push('undefined');
}
// null gets printed as 'null'
else if (a === null) {
simpleVals.push('null');
}
// objects & arrays are special because we want to inspect them in the REPL
else if (types.isObject(a) || Array.isArray(a)) {
// flush any existing simple values logged
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev);
simpleVals = [];
}
// show object
this.logToRepl(a, sev);
}
// string: watch out for % replacement directive
// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
else if (typeof a === 'string') {
let buf = '';
for (let j = 0, len = a.length; j < len; j++) {
if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) {
i++; // read over substitution
buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace
j++; // read over directive
} else {
buf += a[j];
}
}
simpleVals.push(buf);
}
// number or boolean is joined together
else {
simpleVals.push(a);
}
}
// flush simple values
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev);
}
}
}
private registerSessionListeners(): void {
this.toDisposeOnSessionEnd.push(this.session);
this.toDisposeOnSessionEnd.push(this.session.onDidInitialize(event => {
aria.status(nls.localize('debuggingStarted', "Debugging started."));
this.sendAllBreakpoints().then(() => {
if (this.session.configuration.capabilities.supportsConfigurationDoneRequest) {
this.session.configurationDone().done(null, e => {
// Disconnect the debug session on configuration done error #10596
if (this.session) {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
this.messageService.show(severity.Error, e.message);
});
}
});
}));
this.toDisposeOnSessionEnd.push(this.session.onDidStop(event => {
this.setStateAndEmit(debug.State.Stopped);
const threadId = event.body.threadId;
this.getThreadData().done(() => {
this.model.rawUpdate({
threadId,
stoppedDetails: event.body,
allThreadsStopped: event.body.allThreadsStopped
});
const thread = this.model.getThreads()[threadId];
thread.getCallStack(this).then(callStack => {
if (callStack.length > 0) {
// focus first stack frame from top that has source location
const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]);
this.setFocusedStackFrameAndEvaluate(stackFrameToFocus, thread).done(null, errors.onUnexpectedError);
this.windowService.getWindow().focus();
aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber));
return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false);
} else {
this.setFocusedStackFrameAndEvaluate(null, thread).done(null, errors.onUnexpectedError);
}
});
}, errors.onUnexpectedError);
}));
this.toDisposeOnSessionEnd.push(this.session.onDidThread(event => {
if (event.body.reason === 'started') {
this.getThreadData().done(null, errors.onUnexpectedError);
} else if (event.body.reason === 'exited') {
this.model.clearThreads(true, event.body.threadId);
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidTerminateDebugee(event => {
aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
if (this.session && this.session.getId() === event.body.sessionId) {
if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) {
this.restartSession().done(null, err => this.messageService.show(severity.Error, err.message));
} else {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidContinued(event => {
this.lazyTransitionToRunningState(event.body.allThreadsContinued ? undefined : event.body.threadId);
}));
this.toDisposeOnSessionEnd.push(this.session.onDidOutput(event => {
if (event.body && event.body.category === 'telemetry') {
// only log telemetry events from debug adapter if the adapter provided the telemetry key
// and the user opted in telemetry
if (this.customTelemetryService && this.telemetryService.isOptedIn) {
this.customTelemetryService.publicLog(event.body.output, event.body.data);
}
} else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) {
this.onOutput(event);
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidBreakpoint(event => {
const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (breakpoint) {
this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint });
} else {
const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (functionBreakpoint) {
this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint });
}
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidExitAdapter(event => {
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (this.session.configuration.type === 'extensionHost' && this._state === debug.State.RunningNoDebug) {
ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath);
}
if (this.session && this.session.getId() === event.body.sessionId) {
this.onSessionEnd();
}
}));
}
private onOutput(event: DebugProtocol.OutputEvent): void {
const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info;
this.appendReplOutput(event.body.output, outputSeverity);
}
private getThreadData(): TPromise<void> {
return this.session.threads().then(response => {
response.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread }));
});
}
private loadBreakpoints(): debug.IBreakpoint[] {
let result: debug.IBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }),
breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition);
});
} catch (e) { }
return result || [];
}
private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
let result: debug.IFunctionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
return new model.FunctionBreakpoint(fb.name, fb.enabled);
});
} catch (e) { }
return result || [];
}
private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
let result: debug.IExceptionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled);
});
} catch (e) { }
return result || [];
}
private loadWatchExpressions(): model.Expression[] {
let result: model.Expression[];
try {
result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string } ) => {
return new model.Expression(watchStoredData.name, false, watchStoredData.id);
});
} catch (e) { }
return result || [];
}
public get state(): debug.State {
return this._state;
}
public get onDidChangeState(): Event<debug.State> {
return this._onDidChangeState.event;
}
private setStateAndEmit(newState: debug.State): void {
this._state = newState;
this._onDidChangeState.fire(newState);
}
public get enabled(): boolean {
return !!this.contextService.getWorkspace();
}
public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame, thread?: debug.IThread): TPromise<void> {
if (!thread && focusedStackFrame) {
thread = this.model.getThreads()[focusedStackFrame.threadId];
}
this.viewModel.setFocusedStackFrame(focusedStackFrame, thread);
if (focusedStackFrame) {
return this.model.evaluateWatchExpressions(this.session, focusedStackFrame);
} else {
this.model.clearWatchExpressionValues();
return TPromise.as(null);
}
}
public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof model.Breakpoint) {
return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri);
} else if (breakpoint instanceof model.FunctionBreakpoint) {
return this.sendFunctionBreakpoints();
}
return this.sendExceptionBreakpoints();
}
this.model.enableOrDisableAllBreakpoints(enable);
return this.sendAllBreakpoints();
}
public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void[]> {
this.model.addBreakpoints(rawBreakpoints);
const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri);
rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath)));
return TPromise.join(uris.map(uri => this.sendBreakpoints(uri)));
}
public removeBreakpoints(id?: string): TPromise<any> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.source.uri.fsPath)));
const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri);
this.model.removeBreakpoints(toRemove);
return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri)));
}
public setBreakpointsActivated(activated: boolean): TPromise<void> {
this.model.setBreakpointsActivated(activated);
return this.sendAllBreakpoints();
}
public addFunctionBreakpoint(): void {
this.model.addFunctionBreakpoint('');
}
public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> {
this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } });
return this.sendFunctionBreakpoints();
}
public removeFunctionBreakpoints(id?: string): TPromise<void> {
this.model.removeFunctionBreakpoints(id);
return this.sendFunctionBreakpoints();
}
public addReplExpression(name: string): TPromise<void> {
this.telemetryService.publicLog('debugService/addReplExpression');
const focussedStackFrame = this.viewModel.getFocusedStackFrame();
return this.model.addReplExpression(this.session, focussedStackFrame, name)
// Evaluate all watch expressions again since repl evaluation might have changed some.
.then(() => this.setFocusedStackFrameAndEvaluate(focussedStackFrame));
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
this.model.logToRepl(value, severity);
}
public appendReplOutput(value: string, severity?: severity): void {
this.model.appendReplOutput(value, severity);
}
public removeReplExpressions(): void {
this.model.removeReplExpressions();
}
public setVariable(variable: debug.IExpression, value: string): TPromise<any> {
if (!this.session || !(variable instanceof model.Variable)) {
return TPromise.as(null);
}
return this.session.setVariable({
name: variable.name,
value,
variablesReference: (<model.Variable>variable).parent.reference
}).then(response => {
variable.value = response.body.value;
// Evaluate all watch expressions again since changing variable value might have changed some #8118.
return this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame());
}, err => {
(<model.Variable>variable).errorMessage = err.message;
});
}
public addWatchExpression(name: string): TPromise<void> {
return this.model.addWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), name);
}
public renameWatchExpression(id: string, newName: string): TPromise<void> {
return this.model.renameWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), id, newName);
}
public removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
}
public createSession(noDebug: boolean, configuration?: debug.IConfig): TPromise<any> {
this.removeReplExpressions();
return this.textFileService.saveAll() // make sure all dirty files are saved
.then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date
.then(() => this.extensionService.onReady()
.then(() => this.configurationManager.setConfiguration(configuration || this.configurationManager.configurationName)
.then(() => this.configurationManager.resolveInteractiveVariables())
.then(resolvedConfiguration => {
configuration = resolvedConfiguration;
if (!configuration) {
return this.configurationManager.openConfigFile(false).then(openend => {
if (openend) {
this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application."));
}
});
}
if (configuration.silentlyAbort) {
return;
}
configuration.noDebug = noDebug;
if (!this.configurationManager.adapter) {
return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type)))
: TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."),
{ actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] }));
}
return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => {
const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return this.doCreateSession(configuration);
}
this.messageService.show(severity.Error, {
message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) :
errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) :
nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode),
actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => {
this.messageService.hideAll();
return this.doCreateSession(configuration);
}), CloseAction]
});
}, (err: TaskError) => {
if (err.code !== TaskErrors.NotConfigured) {
throw err;
}
this.messageService.show(err.severity, {
message: err.message,
actions: [this.taskService.configureAction(), CloseAction]
});
});
}))));
}
private doCreateSession(configuration: debug.IExtHostConfig): TPromise<any> {
this.setStateAndEmit(debug.State.Initializing);
return this.telemetryService.getTelemetryInfo().then(info => {
const telemetryInfo: { [key: string]: string } = Object.create(null);
telemetryInfo['common.vscodemachineid'] = info.machineId;
telemetryInfo['common.vscodesessionid'] = info.sessionId;
return telemetryInfo;
}).then(data => {
const { aiKey, type } = this.configurationManager.adapter;
const publisher = this.configurationManager.adapter.extensionDescription.publisher;
this.customTelemetryService = null;
if (aiKey) {
const client = new Client(
uri.parse(require.toUrl('bootstrap')).fsPath,
{
serverName: 'Debug Telemetry',
timeout: 1000 * 60 * 5,
args: [`${ publisher }.${ type }`, JSON.stringify(data), aiKey],
env: {
ELECTRON_RUN_AS_NODE: 1,
PIPE_LOGGING: 'true',
AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp'
}
}
);
const channel = client.getChannel('telemetryAppender');
const appender = new TelemetryAppenderClient(channel);
this.toDisposeOnSessionEnd.push(client);
this.customTelemetryService = new TelemetryService({ appender }, this.configurationService);
}
this.session = this.instantiationService.createInstance(RawDebugSession, configuration.debugServer, this.configurationManager.adapter, this.customTelemetryService);
this.registerSessionListeners();
return this.session.initialize({
adapterID: configuration.type,
pathFormat: 'path',
linesStartAt1: true,
columnsStartAt1: true,
supportsVariableType: true, // #8858
supportsVariablePaging: true, // #9537
supportsRunInTerminalRequest: true // #10574
}).then((result: DebugProtocol.InitializeResponse) => {
if (!this.session) {
return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly")));
}
this.model.setExceptionBreakpoints(this.session.configuration.capabilities.exceptionBreakpointFilters);
return configuration.request === 'attach' ? this.session.attach(configuration) : this.session.launch(configuration);
}).then((result: DebugProtocol.Response) => {
if (!this.session) {
return TPromise.as(null);
}
if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) {
// We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden
this.viewModel.changedWorkbenchViewState = true;
this.viewletService.openViewlet(debug.VIEWLET_ID);
}
// Do not change status bar to orange if we are just running without debug.
if (!configuration.noDebug) {
this.partService.addClass('debugging');
}
this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError);
this.inDebugMode.set(true);
this.lazyTransitionToRunningState();
this.telemetryService.publicLog('debugSessionStart', {
type: configuration.type,
breakpointCount: this.model.getBreakpoints().length,
exceptionBreakpoints: this.model.getExceptionBreakpoints(),
watchExpressionsCount: this.model.getWatchExpressions().length,
extensionName: `${ this.configurationManager.adapter.extensionDescription.publisher }.${ this.configurationManager.adapter.extensionDescription.name }`,
isBuiltin: this.configurationManager.adapter.extensionDescription.isBuiltin
});
}).then(undefined, (error: any) => {
if (error instanceof Error && error.message === 'Canceled') {
// Do not show 'canceled' error messages to the user #7906
return TPromise.as(null);
}
this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined });
this.setStateAndEmit(debug.State.Inactive);
if (this.session) {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
// Show the repl if some error got logged there #5870
if (this.model.getReplElements().length > 0) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction];
return TPromise.wrapError(errors.create(error.message, { actions }));
});
});
}
private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> {
if (!taskName) {
return TPromise.as(null);
}
// run a task before starting a debug session
return this.taskService.tasks().then(descriptions => {
const filteredTasks = descriptions.filter(task => task.name === taskName);
if (filteredTasks.length !== 1) {
return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), {
actions: [
this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL),
this.taskService.configureAction(),
CloseAction
]
}));
}
// task is already running - nothing to do.
if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) {
return TPromise.as(null);
}
if (this.lastTaskEvent) {
// there is a different task running currently.
return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName)));
}
// no task running, execute the preLaunchTask.
const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => {
this.lastTaskEvent = null;
return result;
}, err => {
this.lastTaskEvent = null;
});
if (filteredTasks[0].isWatching) {
return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null)));
}
return taskPromise;
});
}
private rawAttach(port: number): TPromise<any> {
if (this.session) {
return this.session.attach({ port });
}
this.setStateAndEmit(debug.State.Initializing);
const configuration = <debug.IExtHostConfig>this.configurationManager.configuration;
return this.doCreateSession({
type: configuration.type,
request: 'attach',
port,
sourceMaps: configuration.sourceMaps,
outDir: configuration.outDir,
debugServer: configuration.debugServer
});
}
public restartSession(): TPromise<any> {
return this.session ? this.session.disconnect(true).then(() =>
new TPromise<void>((c, e) => {
setTimeout(() => {
this.createSession(false, null).then(() => c(null), err => e(err));
}, 300);
})
) : this.createSession(false, null);
}
public getActiveSession(): debug.IRawDebugSession {
return this.session;
}
private onSessionEnd(): void {
if (this.session) {
const bpsExist = this.model.getBreakpoints().length > 0;
this.telemetryService.publicLog('debugSessionStop', {
type: this.session.configuration.type,
success: this.session.emittedStopped || !bpsExist,
sessionLengthInSeconds: this.session.getLengthInSeconds(),
breakpointCount: this.model.getBreakpoints().length,
watchExpressionsCount: this.model.getWatchExpressions().length
});
}
this.session = null;
try {
this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd);
} catch (e) {
// an internal module might be open so the dispose can throw -> ignore and continue with stop session.
}
this.partService.removeClass('debugging');
this.model.clearThreads(true);
this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError);
this.setStateAndEmit(debug.State.Inactive);
// set breakpoints back to unverified since the session ended.
// source reference changes across sessions, so we do not use it to persist the source.
const data: { [id: string]: { line: number, verified: boolean } } = {};
this.model.getBreakpoints().forEach(bp => {
delete bp.source.raw.sourceReference;
data[bp.getId()] = { line: bp.lineNumber, verified: false };
});
this.model.updateBreakpoints(data);
this.inDebugMode.reset();
}
public getModel(): debug.IModel {
return this.model;
}
public getViewModel(): debug.IViewModel {
return this.viewModel;
}
public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> {
const visibleEditors = this.editorService.getVisibleEditors();
for (let i = 0; i < visibleEditors.length; i++) {
const fileInput = asFileEditorInput(visibleEditors[i].input);
if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) ||
(visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) {
const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl();
if (control) {
control.revealLineInCenterIfOutsideViewport(lineNumber);
control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 });
this.editorGroupService.activateGroup(i);
if (!preserveFocus) {
this.editorGroupService.focusGroup(i);
}
}
return TPromise.as(null);
}
}
if (source.inMemory) {
// internal module
if (source.reference !== 0 && this.session && source.available) {
return this.session.source({ sourceReference: source.reference }).then(response => {
const mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0];
return this.getDebugStringEditorInput(source, response.body.content, mime);
}, (err: DebugProtocol.ErrorResponse) => {
// Display the error from debug adapter using a temporary editor #8836
return this.getDebugErrorEditorInput(source, err.message);
}).then(editorInput => {
return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide);
});
}
return this.sourceIsUnavailable(source, sideBySide);
}
return this.fileService.resolveFile(source.uri).then(() =>
this.editorService.openEditor({
resource: source.uri,
options: {
selection: {
startLineNumber: lineNumber,
startColumn: 1,
endLineNumber: lineNumber,
endColumn: 1
},
preserveFocus: preserveFocus
}
}, sideBySide), err => this.sourceIsUnavailable(source, sideBySide)
);
}
private sourceIsUnavailable(source: Source, sideBySide: boolean): TPromise<any> {
this.model.sourceIsUnavailable(source);
const editorInput = this.getDebugErrorEditorInput(source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name));
return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide);
}
public getConfigurationManager(): debug.IConfigurationManager {
return this.configurationManager;
}
public next(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.next({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepIn(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepIn({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepOut(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepOut({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepBack(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepBack({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public continue(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.continue({ threadId }).then(response => {
const allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true;
this.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId);
});
}
public pause(threadId: number): TPromise<any> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.pause({ threadId });
}
public restartFrame(frameId: number): TPromise<any> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.restartFrame({ frameId });
}
public completions(text: string, position: Position): TPromise<ISuggestion[]> {
if (!this.session || !this.session.configuration.capabilities.supportsCompletionsRequest) {
return TPromise.as([]);
}
const focussedStackFrame = this.viewModel.getFocusedStackFrame();
return this.session.completions({
frameId: focussedStackFrame ? focussedStackFrame.frameId : undefined,
text,
column: position.column,
line: position.lineNumber
}).then(response => {
return !response ? [] : response.body.targets.map(item => ({
label: item.label,
insertText: item.text || item.label,
type: item.type
}));
}, err => []);
}
private lazyTransitionToRunningState(threadId?: number): void {
let setNewFocusedStackFrameScheduler: RunOnceScheduler;
const toDispose = this.session.onDidStop(e => {
if (e.body.threadId === threadId || e.body.allThreadsStopped || !threadId) {
setNewFocusedStackFrameScheduler.cancel();
}
});
this.model.clearThreads(false, threadId);
// Get a top stack frame of a stopped thread if there is any.
const threads = this.model.getThreads();
const stoppedReference = Object.keys(threads).filter(ref => threads[ref].stopped).pop();
const stoppedThread = stoppedReference ? threads[parseInt(stoppedReference)] : null;
const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null;
const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null;
if (!stoppedThread) {
this.setStateAndEmit(this.configurationManager.configuration.noDebug ? debug.State.RunningNoDebug : debug.State.Running);
}
// Do not immediatly set a new focused stack frame since that might cause unnecessery flickering
// of the tree in the debug viewlet. Only set focused stack frame if no stopped event has arrived in 500ms.
setNewFocusedStackFrameScheduler = new RunOnceScheduler(() => {
toDispose.dispose();
aria.status(nls.localize('debuggingContinued', "Debugging continued."));
this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError);
}, 500);
setNewFocusedStackFrameScheduler.schedule();
}
private getDebugStringEditorInput(source: Source, value: string, mtype: string): DebugStringEditorInput {
const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0);
this.toDisposeOnSessionEnd.push(result);
return result;
}
private getDebugErrorEditorInput(source: Source, value: string): DebugErrorEditorInput {
const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value);
this.toDisposeOnSessionEnd.push(result);
return result;
}
private sendAllBreakpoints(): TPromise<any> {
return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri)))
.then(() => this.sendFunctionBreakpoints())
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints());
}
private sendBreakpoints(modelUri: uri, sourceModified = false): TPromise<void> {
if (!this.session || !this.session.readyForBreakpoints) {
return TPromise.as(null);
}
if (this.textFileService.isDirty(modelUri)) {
// Only send breakpoints for a file once it is not dirty #8077
this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true;
return TPromise.as(null);
}
const breakpointsToSend = arrays.distinct(
this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()),
bp => `${bp.desiredLineNumber}`
);
const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model);
return this.session.setBreakpoints({
source: rawSource,
lines: breakpointsToSend.map(bp => bp.desiredLineNumber),
breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })),
sourceModified
}).then(response => {
const data: { [id: string]: { line?: number, verified: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateBreakpoints(data);
});
}
private sendFunctionBreakpoints(): TPromise<void> {
if (!this.session || !this.session.readyForBreakpoints || !this.session.configuration.capabilities.supportsFunctionBreakpoints) {
return TPromise.as(null);
}
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {
const data: { [id: string]: { name?: string, verified?: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateFunctionBreakpoints(data);
});
}
private sendExceptionBreakpoints(): TPromise<any> {
if (!this.session || !this.session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) {
return TPromise.as(null);
}
const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
return this.session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) });
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED)));
fileChangesEvent.getUpdated().forEach(event => {
if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) {
this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false;
this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError);
}
});
}
private store(): void {
this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE);
this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.configurationManager.configurationName, StorageScope.WORKSPACE);
this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
}
public dispose(): void {
this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd);
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/electron-browser/debugService.ts | 1 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.0005715870065614581,
0.0001846196682890877,
0.00016134460747707635,
0.00017248305084649473,
0.00006449104694183916
] |
{
"id": 2,
"code_window": [
"\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type)\n",
"\t\t\t);\n",
"\t\t}, (e: Error) => [new Variable(this, 0, null, e.message, 0, 0, null, false)]);\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t) : [];\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 299
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"navigateNext": "Далее",
"navigatePrevious": "Назад"
} | i18n/rus/src/vs/workbench/browser/actions/triggerNavigation.i18n.json | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017628968635108322,
0.00017628968635108322,
0.00017628968635108322,
0.00017628968635108322,
0
] |
{
"id": 2,
"code_window": [
"\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type)\n",
"\t\t\t);\n",
"\t\t}, (e: Error) => [new Variable(this, 0, null, e.message, 0, 0, null, false)]);\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t) : [];\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 299
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { CancellationToken, Uri } from 'vscode';
import * as Proto from './protocol';
export interface ITypescriptServiceClientHost {
syntaxDiagnosticsReceived(event: Proto.DiagnosticEvent): void;
semanticDiagnosticsReceived(event: Proto.DiagnosticEvent): void;
configFileDiagnosticsReceived(event: Proto.ConfigFileDiagnosticEvent): void;
populateService(): void;
}
export enum APIVersion {
v1_x = 1,
v2_0_0 = 2
};
export namespace APIVersion {
export function fromString(value: string): APIVersion {
if (!value) {
return APIVersion.v1_x;
}
const index = value.indexOf('.');
var major: number;
if (index > 0) {
major = parseInt(value.substr(0, index));
} else {
major = parseInt(value);
}
if (isNaN(major)) {
return APIVersion.v1_x;
}
if (major >= 2) {
return APIVersion.v2_0_0;
}
return APIVersion.v1_x;
}
}
export interface ITypescriptServiceClient {
asAbsolutePath(resource: Uri): string;
asUrl(filepath: string): Uri;
info(message: string, data?: any): void;
warn(message: string, data?: any): void;
error(message: string, data?: any): void;
logTelemetry(eventName: string, properties?: { [prop: string]: string });
experimentalAutoBuild: boolean;
apiVersion: APIVersion;
execute(command: 'configure', args: Proto.ConfigureRequestArguments, token?: CancellationToken):Promise<Proto.ConfigureResponse>;
execute(command: 'open', args: Proto.OpenRequestArgs, expectedResult:boolean, token?: CancellationToken):Promise<any>;
execute(command: 'close', args: Proto.FileRequestArgs, expectedResult:boolean, token?: CancellationToken):Promise<any>;
execute(command: 'change', args: Proto.ChangeRequestArgs, expectedResult:boolean, token?: CancellationToken):Promise<any>;
execute(command: 'geterr', args: Proto.GeterrRequestArgs, expectedResult:boolean, token?: CancellationToken):Promise<any>;
execute(command: 'quickinfo', args: Proto.FileLocationRequestArgs, token?: CancellationToken):Promise<Proto.QuickInfoResponse>;
execute(command: 'completions', args: Proto.CompletionsRequestArgs, token?: CancellationToken):Promise<Proto.CompletionsResponse>;
execute(commant: 'completionEntryDetails', args: Proto.CompletionDetailsRequestArgs, token?: CancellationToken):Promise<Proto.CompletionDetailsResponse>;
execute(commant: 'signatureHelp', args: Proto.SignatureHelpRequestArgs, token?: CancellationToken):Promise<Proto.SignatureHelpResponse>;
execute(command: 'definition', args: Proto.FileLocationRequestArgs, token?: CancellationToken):Promise<Proto.DefinitionResponse>;
execute(command: 'references', args: Proto.FileLocationRequestArgs, token?: CancellationToken):Promise<Proto.ReferencesResponse>;
execute(command: 'navto', args: Proto.NavtoRequestArgs, token?: CancellationToken):Promise<Proto.NavtoResponse>;
execute(command: 'navbar', args: Proto.FileRequestArgs, token?: CancellationToken):Promise<Proto.NavBarResponse>;
execute(command: 'format', args: Proto.FormatRequestArgs, token?: CancellationToken):Promise<Proto.FormatResponse>;
execute(command: 'formatonkey', args: Proto.FormatOnKeyRequestArgs, token?: CancellationToken):Promise<Proto.FormatResponse>;
execute(command: 'rename', args: Proto.RenameRequestArgs, token?: CancellationToken): Promise<Proto.RenameResponse>;
execute(command: 'occurrences', args: Proto.FileLocationRequestArgs, token?: CancellationToken): Promise<Proto.OccurrencesResponse>;
execute(command: 'projectInfo', args: Proto.ProjectInfoRequestArgs, token?: CancellationToken): Promise<Proto.ProjectInfoResponse>;
execute(command: 'reloadProjects', args: any, expectedResult:boolean, token?: CancellationToken): Promise<any>;
execute(command: 'reload', args: Proto.ReloadRequestArgs, expectedResult: boolean, token?: CancellationToken): Promise<any>;
execute(command: string, args: any, expectedResult: boolean | CancellationToken, token?: CancellationToken): Promise<any>;
} | extensions/typescript/src/typescriptService.ts | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00021533876133617014,
0.00017804637900553644,
0.00016531493747606874,
0.0001732119417283684,
0.000014538763025484513
] |
{
"id": 2,
"code_window": [
"\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type)\n",
"\t\t\t);\n",
"\t\t}, (e: Error) => [new Variable(this, 0, null, e.message, 0, 0, null, false)]);\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t) : [];\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 299
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"updateImageSize": "Emmet: Bildgröße aktualisieren"
} | i18n/deu/src/vs/workbench/parts/emmet/node/actions/updateImageSize.i18n.json | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017707458755467087,
0.00017707458755467087,
0.00017707458755467087,
0.00017707458755467087,
0
] |
{
"id": 3,
"code_window": [
"\n",
"\tpublic getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {\n",
"\t\tif (!this.scopes) {\n",
"\t\t\tthis.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {\n",
"\t\t\t\treturn response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables));\n",
"\t\t\t}, err => []);\n",
"\t\t}\n",
"\n",
"\t\treturn this.scopes;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\treturn response && response.body && response.body.scopes ?\n",
"\t\t\t\t\tresponse.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables)) : [];\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 386
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import {guessMimeTypes} from 'vs/base/common/mime';
import Event, {Emitter} from 'vs/base/common/event';
import uri from 'vs/base/common/uri';
import {RunOnceScheduler} from 'vs/base/common/async';
import {Action} from 'vs/base/common/actions';
import arrays = require('vs/base/common/arrays');
import types = require('vs/base/common/types');
import errors = require('vs/base/common/errors');
import severity from 'vs/base/common/severity';
import {TPromise} from 'vs/base/common/winjs.base';
import aria = require('vs/base/browser/ui/aria/aria');
import editorbrowser = require('vs/editor/browser/editorBrowser');
import {ISuggestion} from 'vs/editor/common/modes';
import {Position} from 'vs/editor/common/core/position';
import {IContextKeyService, IContextKey} from 'vs/platform/contextkey/common/contextkey';
import {IMarkerService} from 'vs/platform/markers/common/markers';
import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle';
import {IExtensionService} from 'vs/platform/extensions/common/extensions';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IFileService, FileChangesEvent, FileChangeType, EventType} from 'vs/platform/files/common/files';
import {IEventService} from 'vs/platform/event/common/event';
import {IMessageService, CloseAction} from 'vs/platform/message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {TelemetryService} from 'vs/platform/telemetry/common/telemetryService';
import {TelemetryAppenderClient} from 'vs/platform/telemetry/common/telemetryIpc';
import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage';
import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService';
import {asFileEditorInput} from 'vs/workbench/common/editor';
import debug = require('vs/workbench/parts/debug/common/debug');
import {RawDebugSession} from 'vs/workbench/parts/debug/electron-browser/rawDebugSession';
import model = require('vs/workbench/parts/debug/common/debugModel');
import {DebugStringEditorInput, DebugErrorEditorInput} from 'vs/workbench/parts/debug/browser/debugEditorInputs';
import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel');
import debugactions = require('vs/workbench/parts/debug/browser/debugActions');
import {ConfigurationManager} from 'vs/workbench/parts/debug/node/debugConfigurationManager';
import {Source} from 'vs/workbench/parts/debug/common/debugSource';
import {ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary} from 'vs/workbench/parts/tasks/common/taskService';
import {TaskError, TaskErrors} from 'vs/workbench/parts/tasks/common/taskSystem';
import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService';
import {IPanelService} from 'vs/workbench/services/panel/common/panelService';
import {IPartService} from 'vs/workbench/services/part/common/partService';
import {ITextFileService} from 'vs/workbench/parts/files/common/files';
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {IWindowService, IBroadcast} from 'vs/workbench/services/window/electron-browser/windowService';
import {ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL} from 'vs/workbench/services/thread/electron-browser/threadService';
import {ipcRenderer as ipc} from 'electron';
import {Client} from 'vs/base/parts/ipc/node/ipc.cp';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname';
export class DebugService implements debug.IDebugService {
public _serviceBrand: any;
private _state: debug.State;
private _onDidChangeState: Emitter<debug.State>;
private session: RawDebugSession;
private model: model.Model;
private viewModel: viewmodel.ViewModel;
private configurationManager: ConfigurationManager;
private customTelemetryService: ITelemetryService;
private lastTaskEvent: TaskEvent;
private toDispose: lifecycle.IDisposable[];
private toDisposeOnSessionEnd: lifecycle.IDisposable[];
private inDebugMode: IContextKey<boolean>;
private breakpointsToSendOnResourceSaved: { [uri: string]: boolean };
constructor(
@IStorageService private storageService: IStorageService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@ITextFileService private textFileService: ITextFileService,
@IViewletService private viewletService: IViewletService,
@IPanelService private panelService: IPanelService,
@IFileService private fileService: IFileService,
@IMessageService private messageService: IMessageService,
@IPartService private partService: IPartService,
@IWindowService private windowService: IWindowService,
@ITelemetryService private telemetryService: ITelemetryService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@IEditorGroupService private editorGroupService: IEditorGroupService,
@IEventService eventService: IEventService,
@ILifecycleService private lifecycleService: ILifecycleService,
@IInstantiationService private instantiationService: IInstantiationService,
@IExtensionService private extensionService: IExtensionService,
@IMarkerService private markerService: IMarkerService,
@ITaskService private taskService: ITaskService,
@IConfigurationService private configurationService: IConfigurationService
) {
this.toDispose = [];
this.toDisposeOnSessionEnd = [];
this.session = null;
this.breakpointsToSendOnResourceSaved = {};
this._state = debug.State.Inactive;
this._onDidChangeState = new Emitter<debug.State>();
if (!this.contextService.getWorkspace()) {
this._state = debug.State.Disabled;
}
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, 'null'));
this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadWatchExpressions());
this.toDispose.push(this.model);
this.viewModel = new viewmodel.ViewModel();
this.registerListeners(eventService, lifecycleService);
}
private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void {
this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e)));
if (this.taskService) {
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => {
this.lastTaskEvent = e;
}));
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => {
if (e.type === TaskType.SingleRun) {
this.lastTaskEvent = null;
}
}));
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => {
this.lastTaskEvent = null;
}));
}
lifecycleService.onShutdown(this.store, this);
lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this));
}
private onBroadcast(broadcast: IBroadcast): void {
// attach: PH is ready to be attached to
if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) {
this.rawAttach(broadcast.payload.port);
return;
}
if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) {
this.onSessionEnd();
return;
}
// from this point on we require an active session
let session = this.getActiveSession();
if (!session || session.configuration.type !== 'extensionHost') {
return; // we are only intersted if we have an active debug session for extensionHost
}
// a plugin logged output, show it inside the REPL
if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) {
let extensionOutput: ILogEntry = broadcast.payload;
let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info;
let args: any[] = [];
try {
let parsed = JSON.parse(extensionOutput.arguments);
args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o]));
} catch (error) {
args.push(extensionOutput.arguments);
}
// add output for each argument logged
let simpleVals: any[] = [];
for (let i = 0; i < args.length; i++) {
let a = args[i];
// undefined gets printed as 'undefined'
if (typeof a === 'undefined') {
simpleVals.push('undefined');
}
// null gets printed as 'null'
else if (a === null) {
simpleVals.push('null');
}
// objects & arrays are special because we want to inspect them in the REPL
else if (types.isObject(a) || Array.isArray(a)) {
// flush any existing simple values logged
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev);
simpleVals = [];
}
// show object
this.logToRepl(a, sev);
}
// string: watch out for % replacement directive
// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
else if (typeof a === 'string') {
let buf = '';
for (let j = 0, len = a.length; j < len; j++) {
if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) {
i++; // read over substitution
buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace
j++; // read over directive
} else {
buf += a[j];
}
}
simpleVals.push(buf);
}
// number or boolean is joined together
else {
simpleVals.push(a);
}
}
// flush simple values
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev);
}
}
}
private registerSessionListeners(): void {
this.toDisposeOnSessionEnd.push(this.session);
this.toDisposeOnSessionEnd.push(this.session.onDidInitialize(event => {
aria.status(nls.localize('debuggingStarted', "Debugging started."));
this.sendAllBreakpoints().then(() => {
if (this.session.configuration.capabilities.supportsConfigurationDoneRequest) {
this.session.configurationDone().done(null, e => {
// Disconnect the debug session on configuration done error #10596
if (this.session) {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
this.messageService.show(severity.Error, e.message);
});
}
});
}));
this.toDisposeOnSessionEnd.push(this.session.onDidStop(event => {
this.setStateAndEmit(debug.State.Stopped);
const threadId = event.body.threadId;
this.getThreadData().done(() => {
this.model.rawUpdate({
threadId,
stoppedDetails: event.body,
allThreadsStopped: event.body.allThreadsStopped
});
const thread = this.model.getThreads()[threadId];
thread.getCallStack(this).then(callStack => {
if (callStack.length > 0) {
// focus first stack frame from top that has source location
const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]);
this.setFocusedStackFrameAndEvaluate(stackFrameToFocus, thread).done(null, errors.onUnexpectedError);
this.windowService.getWindow().focus();
aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber));
return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false);
} else {
this.setFocusedStackFrameAndEvaluate(null, thread).done(null, errors.onUnexpectedError);
}
});
}, errors.onUnexpectedError);
}));
this.toDisposeOnSessionEnd.push(this.session.onDidThread(event => {
if (event.body.reason === 'started') {
this.getThreadData().done(null, errors.onUnexpectedError);
} else if (event.body.reason === 'exited') {
this.model.clearThreads(true, event.body.threadId);
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidTerminateDebugee(event => {
aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
if (this.session && this.session.getId() === event.body.sessionId) {
if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) {
this.restartSession().done(null, err => this.messageService.show(severity.Error, err.message));
} else {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidContinued(event => {
this.lazyTransitionToRunningState(event.body.allThreadsContinued ? undefined : event.body.threadId);
}));
this.toDisposeOnSessionEnd.push(this.session.onDidOutput(event => {
if (event.body && event.body.category === 'telemetry') {
// only log telemetry events from debug adapter if the adapter provided the telemetry key
// and the user opted in telemetry
if (this.customTelemetryService && this.telemetryService.isOptedIn) {
this.customTelemetryService.publicLog(event.body.output, event.body.data);
}
} else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) {
this.onOutput(event);
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidBreakpoint(event => {
const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (breakpoint) {
this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint });
} else {
const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (functionBreakpoint) {
this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint });
}
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidExitAdapter(event => {
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (this.session.configuration.type === 'extensionHost' && this._state === debug.State.RunningNoDebug) {
ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath);
}
if (this.session && this.session.getId() === event.body.sessionId) {
this.onSessionEnd();
}
}));
}
private onOutput(event: DebugProtocol.OutputEvent): void {
const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info;
this.appendReplOutput(event.body.output, outputSeverity);
}
private getThreadData(): TPromise<void> {
return this.session.threads().then(response => {
response.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread }));
});
}
private loadBreakpoints(): debug.IBreakpoint[] {
let result: debug.IBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }),
breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition);
});
} catch (e) { }
return result || [];
}
private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
let result: debug.IFunctionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
return new model.FunctionBreakpoint(fb.name, fb.enabled);
});
} catch (e) { }
return result || [];
}
private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
let result: debug.IExceptionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled);
});
} catch (e) { }
return result || [];
}
private loadWatchExpressions(): model.Expression[] {
let result: model.Expression[];
try {
result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string } ) => {
return new model.Expression(watchStoredData.name, false, watchStoredData.id);
});
} catch (e) { }
return result || [];
}
public get state(): debug.State {
return this._state;
}
public get onDidChangeState(): Event<debug.State> {
return this._onDidChangeState.event;
}
private setStateAndEmit(newState: debug.State): void {
this._state = newState;
this._onDidChangeState.fire(newState);
}
public get enabled(): boolean {
return !!this.contextService.getWorkspace();
}
public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame, thread?: debug.IThread): TPromise<void> {
if (!thread && focusedStackFrame) {
thread = this.model.getThreads()[focusedStackFrame.threadId];
}
this.viewModel.setFocusedStackFrame(focusedStackFrame, thread);
if (focusedStackFrame) {
return this.model.evaluateWatchExpressions(this.session, focusedStackFrame);
} else {
this.model.clearWatchExpressionValues();
return TPromise.as(null);
}
}
public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof model.Breakpoint) {
return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri);
} else if (breakpoint instanceof model.FunctionBreakpoint) {
return this.sendFunctionBreakpoints();
}
return this.sendExceptionBreakpoints();
}
this.model.enableOrDisableAllBreakpoints(enable);
return this.sendAllBreakpoints();
}
public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void[]> {
this.model.addBreakpoints(rawBreakpoints);
const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri);
rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath)));
return TPromise.join(uris.map(uri => this.sendBreakpoints(uri)));
}
public removeBreakpoints(id?: string): TPromise<any> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.source.uri.fsPath)));
const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri);
this.model.removeBreakpoints(toRemove);
return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri)));
}
public setBreakpointsActivated(activated: boolean): TPromise<void> {
this.model.setBreakpointsActivated(activated);
return this.sendAllBreakpoints();
}
public addFunctionBreakpoint(): void {
this.model.addFunctionBreakpoint('');
}
public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> {
this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } });
return this.sendFunctionBreakpoints();
}
public removeFunctionBreakpoints(id?: string): TPromise<void> {
this.model.removeFunctionBreakpoints(id);
return this.sendFunctionBreakpoints();
}
public addReplExpression(name: string): TPromise<void> {
this.telemetryService.publicLog('debugService/addReplExpression');
const focussedStackFrame = this.viewModel.getFocusedStackFrame();
return this.model.addReplExpression(this.session, focussedStackFrame, name)
// Evaluate all watch expressions again since repl evaluation might have changed some.
.then(() => this.setFocusedStackFrameAndEvaluate(focussedStackFrame));
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
this.model.logToRepl(value, severity);
}
public appendReplOutput(value: string, severity?: severity): void {
this.model.appendReplOutput(value, severity);
}
public removeReplExpressions(): void {
this.model.removeReplExpressions();
}
public setVariable(variable: debug.IExpression, value: string): TPromise<any> {
if (!this.session || !(variable instanceof model.Variable)) {
return TPromise.as(null);
}
return this.session.setVariable({
name: variable.name,
value,
variablesReference: (<model.Variable>variable).parent.reference
}).then(response => {
variable.value = response.body.value;
// Evaluate all watch expressions again since changing variable value might have changed some #8118.
return this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame());
}, err => {
(<model.Variable>variable).errorMessage = err.message;
});
}
public addWatchExpression(name: string): TPromise<void> {
return this.model.addWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), name);
}
public renameWatchExpression(id: string, newName: string): TPromise<void> {
return this.model.renameWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), id, newName);
}
public removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
}
public createSession(noDebug: boolean, configuration?: debug.IConfig): TPromise<any> {
this.removeReplExpressions();
return this.textFileService.saveAll() // make sure all dirty files are saved
.then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date
.then(() => this.extensionService.onReady()
.then(() => this.configurationManager.setConfiguration(configuration || this.configurationManager.configurationName)
.then(() => this.configurationManager.resolveInteractiveVariables())
.then(resolvedConfiguration => {
configuration = resolvedConfiguration;
if (!configuration) {
return this.configurationManager.openConfigFile(false).then(openend => {
if (openend) {
this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application."));
}
});
}
if (configuration.silentlyAbort) {
return;
}
configuration.noDebug = noDebug;
if (!this.configurationManager.adapter) {
return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type)))
: TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."),
{ actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] }));
}
return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => {
const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return this.doCreateSession(configuration);
}
this.messageService.show(severity.Error, {
message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) :
errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) :
nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode),
actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => {
this.messageService.hideAll();
return this.doCreateSession(configuration);
}), CloseAction]
});
}, (err: TaskError) => {
if (err.code !== TaskErrors.NotConfigured) {
throw err;
}
this.messageService.show(err.severity, {
message: err.message,
actions: [this.taskService.configureAction(), CloseAction]
});
});
}))));
}
private doCreateSession(configuration: debug.IExtHostConfig): TPromise<any> {
this.setStateAndEmit(debug.State.Initializing);
return this.telemetryService.getTelemetryInfo().then(info => {
const telemetryInfo: { [key: string]: string } = Object.create(null);
telemetryInfo['common.vscodemachineid'] = info.machineId;
telemetryInfo['common.vscodesessionid'] = info.sessionId;
return telemetryInfo;
}).then(data => {
const { aiKey, type } = this.configurationManager.adapter;
const publisher = this.configurationManager.adapter.extensionDescription.publisher;
this.customTelemetryService = null;
if (aiKey) {
const client = new Client(
uri.parse(require.toUrl('bootstrap')).fsPath,
{
serverName: 'Debug Telemetry',
timeout: 1000 * 60 * 5,
args: [`${ publisher }.${ type }`, JSON.stringify(data), aiKey],
env: {
ELECTRON_RUN_AS_NODE: 1,
PIPE_LOGGING: 'true',
AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp'
}
}
);
const channel = client.getChannel('telemetryAppender');
const appender = new TelemetryAppenderClient(channel);
this.toDisposeOnSessionEnd.push(client);
this.customTelemetryService = new TelemetryService({ appender }, this.configurationService);
}
this.session = this.instantiationService.createInstance(RawDebugSession, configuration.debugServer, this.configurationManager.adapter, this.customTelemetryService);
this.registerSessionListeners();
return this.session.initialize({
adapterID: configuration.type,
pathFormat: 'path',
linesStartAt1: true,
columnsStartAt1: true,
supportsVariableType: true, // #8858
supportsVariablePaging: true, // #9537
supportsRunInTerminalRequest: true // #10574
}).then((result: DebugProtocol.InitializeResponse) => {
if (!this.session) {
return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly")));
}
this.model.setExceptionBreakpoints(this.session.configuration.capabilities.exceptionBreakpointFilters);
return configuration.request === 'attach' ? this.session.attach(configuration) : this.session.launch(configuration);
}).then((result: DebugProtocol.Response) => {
if (!this.session) {
return TPromise.as(null);
}
if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) {
// We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden
this.viewModel.changedWorkbenchViewState = true;
this.viewletService.openViewlet(debug.VIEWLET_ID);
}
// Do not change status bar to orange if we are just running without debug.
if (!configuration.noDebug) {
this.partService.addClass('debugging');
}
this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError);
this.inDebugMode.set(true);
this.lazyTransitionToRunningState();
this.telemetryService.publicLog('debugSessionStart', {
type: configuration.type,
breakpointCount: this.model.getBreakpoints().length,
exceptionBreakpoints: this.model.getExceptionBreakpoints(),
watchExpressionsCount: this.model.getWatchExpressions().length,
extensionName: `${ this.configurationManager.adapter.extensionDescription.publisher }.${ this.configurationManager.adapter.extensionDescription.name }`,
isBuiltin: this.configurationManager.adapter.extensionDescription.isBuiltin
});
}).then(undefined, (error: any) => {
if (error instanceof Error && error.message === 'Canceled') {
// Do not show 'canceled' error messages to the user #7906
return TPromise.as(null);
}
this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined });
this.setStateAndEmit(debug.State.Inactive);
if (this.session) {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
// Show the repl if some error got logged there #5870
if (this.model.getReplElements().length > 0) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction];
return TPromise.wrapError(errors.create(error.message, { actions }));
});
});
}
private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> {
if (!taskName) {
return TPromise.as(null);
}
// run a task before starting a debug session
return this.taskService.tasks().then(descriptions => {
const filteredTasks = descriptions.filter(task => task.name === taskName);
if (filteredTasks.length !== 1) {
return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), {
actions: [
this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL),
this.taskService.configureAction(),
CloseAction
]
}));
}
// task is already running - nothing to do.
if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) {
return TPromise.as(null);
}
if (this.lastTaskEvent) {
// there is a different task running currently.
return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName)));
}
// no task running, execute the preLaunchTask.
const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => {
this.lastTaskEvent = null;
return result;
}, err => {
this.lastTaskEvent = null;
});
if (filteredTasks[0].isWatching) {
return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null)));
}
return taskPromise;
});
}
private rawAttach(port: number): TPromise<any> {
if (this.session) {
return this.session.attach({ port });
}
this.setStateAndEmit(debug.State.Initializing);
const configuration = <debug.IExtHostConfig>this.configurationManager.configuration;
return this.doCreateSession({
type: configuration.type,
request: 'attach',
port,
sourceMaps: configuration.sourceMaps,
outDir: configuration.outDir,
debugServer: configuration.debugServer
});
}
public restartSession(): TPromise<any> {
return this.session ? this.session.disconnect(true).then(() =>
new TPromise<void>((c, e) => {
setTimeout(() => {
this.createSession(false, null).then(() => c(null), err => e(err));
}, 300);
})
) : this.createSession(false, null);
}
public getActiveSession(): debug.IRawDebugSession {
return this.session;
}
private onSessionEnd(): void {
if (this.session) {
const bpsExist = this.model.getBreakpoints().length > 0;
this.telemetryService.publicLog('debugSessionStop', {
type: this.session.configuration.type,
success: this.session.emittedStopped || !bpsExist,
sessionLengthInSeconds: this.session.getLengthInSeconds(),
breakpointCount: this.model.getBreakpoints().length,
watchExpressionsCount: this.model.getWatchExpressions().length
});
}
this.session = null;
try {
this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd);
} catch (e) {
// an internal module might be open so the dispose can throw -> ignore and continue with stop session.
}
this.partService.removeClass('debugging');
this.model.clearThreads(true);
this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError);
this.setStateAndEmit(debug.State.Inactive);
// set breakpoints back to unverified since the session ended.
// source reference changes across sessions, so we do not use it to persist the source.
const data: { [id: string]: { line: number, verified: boolean } } = {};
this.model.getBreakpoints().forEach(bp => {
delete bp.source.raw.sourceReference;
data[bp.getId()] = { line: bp.lineNumber, verified: false };
});
this.model.updateBreakpoints(data);
this.inDebugMode.reset();
}
public getModel(): debug.IModel {
return this.model;
}
public getViewModel(): debug.IViewModel {
return this.viewModel;
}
public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> {
const visibleEditors = this.editorService.getVisibleEditors();
for (let i = 0; i < visibleEditors.length; i++) {
const fileInput = asFileEditorInput(visibleEditors[i].input);
if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) ||
(visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) {
const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl();
if (control) {
control.revealLineInCenterIfOutsideViewport(lineNumber);
control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 });
this.editorGroupService.activateGroup(i);
if (!preserveFocus) {
this.editorGroupService.focusGroup(i);
}
}
return TPromise.as(null);
}
}
if (source.inMemory) {
// internal module
if (source.reference !== 0 && this.session && source.available) {
return this.session.source({ sourceReference: source.reference }).then(response => {
const mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0];
return this.getDebugStringEditorInput(source, response.body.content, mime);
}, (err: DebugProtocol.ErrorResponse) => {
// Display the error from debug adapter using a temporary editor #8836
return this.getDebugErrorEditorInput(source, err.message);
}).then(editorInput => {
return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide);
});
}
return this.sourceIsUnavailable(source, sideBySide);
}
return this.fileService.resolveFile(source.uri).then(() =>
this.editorService.openEditor({
resource: source.uri,
options: {
selection: {
startLineNumber: lineNumber,
startColumn: 1,
endLineNumber: lineNumber,
endColumn: 1
},
preserveFocus: preserveFocus
}
}, sideBySide), err => this.sourceIsUnavailable(source, sideBySide)
);
}
private sourceIsUnavailable(source: Source, sideBySide: boolean): TPromise<any> {
this.model.sourceIsUnavailable(source);
const editorInput = this.getDebugErrorEditorInput(source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name));
return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide);
}
public getConfigurationManager(): debug.IConfigurationManager {
return this.configurationManager;
}
public next(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.next({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepIn(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepIn({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepOut(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepOut({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepBack(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepBack({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public continue(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.continue({ threadId }).then(response => {
const allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true;
this.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId);
});
}
public pause(threadId: number): TPromise<any> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.pause({ threadId });
}
public restartFrame(frameId: number): TPromise<any> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.restartFrame({ frameId });
}
public completions(text: string, position: Position): TPromise<ISuggestion[]> {
if (!this.session || !this.session.configuration.capabilities.supportsCompletionsRequest) {
return TPromise.as([]);
}
const focussedStackFrame = this.viewModel.getFocusedStackFrame();
return this.session.completions({
frameId: focussedStackFrame ? focussedStackFrame.frameId : undefined,
text,
column: position.column,
line: position.lineNumber
}).then(response => {
return !response ? [] : response.body.targets.map(item => ({
label: item.label,
insertText: item.text || item.label,
type: item.type
}));
}, err => []);
}
private lazyTransitionToRunningState(threadId?: number): void {
let setNewFocusedStackFrameScheduler: RunOnceScheduler;
const toDispose = this.session.onDidStop(e => {
if (e.body.threadId === threadId || e.body.allThreadsStopped || !threadId) {
setNewFocusedStackFrameScheduler.cancel();
}
});
this.model.clearThreads(false, threadId);
// Get a top stack frame of a stopped thread if there is any.
const threads = this.model.getThreads();
const stoppedReference = Object.keys(threads).filter(ref => threads[ref].stopped).pop();
const stoppedThread = stoppedReference ? threads[parseInt(stoppedReference)] : null;
const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null;
const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null;
if (!stoppedThread) {
this.setStateAndEmit(this.configurationManager.configuration.noDebug ? debug.State.RunningNoDebug : debug.State.Running);
}
// Do not immediatly set a new focused stack frame since that might cause unnecessery flickering
// of the tree in the debug viewlet. Only set focused stack frame if no stopped event has arrived in 500ms.
setNewFocusedStackFrameScheduler = new RunOnceScheduler(() => {
toDispose.dispose();
aria.status(nls.localize('debuggingContinued', "Debugging continued."));
this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError);
}, 500);
setNewFocusedStackFrameScheduler.schedule();
}
private getDebugStringEditorInput(source: Source, value: string, mtype: string): DebugStringEditorInput {
const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0);
this.toDisposeOnSessionEnd.push(result);
return result;
}
private getDebugErrorEditorInput(source: Source, value: string): DebugErrorEditorInput {
const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value);
this.toDisposeOnSessionEnd.push(result);
return result;
}
private sendAllBreakpoints(): TPromise<any> {
return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri)))
.then(() => this.sendFunctionBreakpoints())
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints());
}
private sendBreakpoints(modelUri: uri, sourceModified = false): TPromise<void> {
if (!this.session || !this.session.readyForBreakpoints) {
return TPromise.as(null);
}
if (this.textFileService.isDirty(modelUri)) {
// Only send breakpoints for a file once it is not dirty #8077
this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true;
return TPromise.as(null);
}
const breakpointsToSend = arrays.distinct(
this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()),
bp => `${bp.desiredLineNumber}`
);
const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model);
return this.session.setBreakpoints({
source: rawSource,
lines: breakpointsToSend.map(bp => bp.desiredLineNumber),
breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })),
sourceModified
}).then(response => {
const data: { [id: string]: { line?: number, verified: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateBreakpoints(data);
});
}
private sendFunctionBreakpoints(): TPromise<void> {
if (!this.session || !this.session.readyForBreakpoints || !this.session.configuration.capabilities.supportsFunctionBreakpoints) {
return TPromise.as(null);
}
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {
const data: { [id: string]: { name?: string, verified?: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateFunctionBreakpoints(data);
});
}
private sendExceptionBreakpoints(): TPromise<any> {
if (!this.session || !this.session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) {
return TPromise.as(null);
}
const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
return this.session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) });
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED)));
fileChangesEvent.getUpdated().forEach(event => {
if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) {
this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false;
this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError);
}
});
}
private store(): void {
this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE);
this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.configurationManager.configurationName, StorageScope.WORKSPACE);
this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
}
public dispose(): void {
this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd);
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/electron-browser/debugService.ts | 1 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.0019620023667812347,
0.00022359848662745208,
0.00015994563000276685,
0.0001715092221274972,
0.0002221900795120746
] |
{
"id": 3,
"code_window": [
"\n",
"\tpublic getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {\n",
"\t\tif (!this.scopes) {\n",
"\t\t\tthis.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {\n",
"\t\t\t\treturn response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables));\n",
"\t\t\t}, err => []);\n",
"\t\t}\n",
"\n",
"\t\treturn this.scopes;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\treturn response && response.body && response.body.scopes ?\n",
"\t\t\t\t\tresponse.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables)) : [];\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 386
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"searchExtensions": "Nach Extensions in Marketplace suchen"
} | i18n/deu/src/vs/workbench/parts/extensions/electron-browser/extensionsViewlet.i18n.json | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017580072744749486,
0.00017580072744749486,
0.00017580072744749486,
0.00017580072744749486,
0
] |
{
"id": 3,
"code_window": [
"\n",
"\tpublic getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {\n",
"\t\tif (!this.scopes) {\n",
"\t\t\tthis.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {\n",
"\t\t\t\treturn response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables));\n",
"\t\t\t}, err => []);\n",
"\t\t}\n",
"\n",
"\t\treturn this.scopes;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\treturn response && response.body && response.body.scopes ?\n",
"\t\t\t\t\tresponse.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables)) : [];\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 386
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"quickfix.trigger.label": "Correctif rapide"
} | i18n/fra/src/vs/editor/contrib/quickFix/browser/quickFix.i18n.json | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017650816880632192,
0.00017650816880632192,
0.00017650816880632192,
0.00017650816880632192,
0
] |
{
"id": 3,
"code_window": [
"\n",
"\tpublic getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {\n",
"\t\tif (!this.scopes) {\n",
"\t\t\tthis.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {\n",
"\t\t\t\treturn response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables));\n",
"\t\t\t}, err => []);\n",
"\t\t}\n",
"\n",
"\t\treturn this.scopes;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\treturn response && response.body && response.body.scopes ?\n",
"\t\t\t\t\tresponse.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables)) : [];\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 386
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"actions.goToDecl.label": "Atteindre la définition",
"actions.goToDeclToSide.label": "Ouvrir la définition sur le côté",
"actions.previewDecl.label": "Apercu de définition",
"meta.title": " – {0} définitions",
"multipleResults": "Cliquez pour afficher les {0} définitions trouvées."
} | i18n/fra/src/vs/editor/contrib/goToDeclaration/browser/goToDeclaration.i18n.json | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017600131104700267,
0.0001741325540933758,
0.00017226381169166416,
0.0001741325540933758,
0.000001868749677669257
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tprivate getThreadData(): TPromise<void> {\n",
"\t\treturn this.session.threads().then(response => {\n",
"\t\t\tresponse.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread }));\n",
"\t\t});\n",
"\t}\n",
"\n",
"\tprivate loadBreakpoints(): debug.IBreakpoint[] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (response && response.body && response.body.threads) {\n",
"\t\t\t\tresponse.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread }));\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.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 nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import {guessMimeTypes} from 'vs/base/common/mime';
import Event, {Emitter} from 'vs/base/common/event';
import uri from 'vs/base/common/uri';
import {RunOnceScheduler} from 'vs/base/common/async';
import {Action} from 'vs/base/common/actions';
import arrays = require('vs/base/common/arrays');
import types = require('vs/base/common/types');
import errors = require('vs/base/common/errors');
import severity from 'vs/base/common/severity';
import {TPromise} from 'vs/base/common/winjs.base';
import aria = require('vs/base/browser/ui/aria/aria');
import editorbrowser = require('vs/editor/browser/editorBrowser');
import {ISuggestion} from 'vs/editor/common/modes';
import {Position} from 'vs/editor/common/core/position';
import {IContextKeyService, IContextKey} from 'vs/platform/contextkey/common/contextkey';
import {IMarkerService} from 'vs/platform/markers/common/markers';
import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle';
import {IExtensionService} from 'vs/platform/extensions/common/extensions';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IFileService, FileChangesEvent, FileChangeType, EventType} from 'vs/platform/files/common/files';
import {IEventService} from 'vs/platform/event/common/event';
import {IMessageService, CloseAction} from 'vs/platform/message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {TelemetryService} from 'vs/platform/telemetry/common/telemetryService';
import {TelemetryAppenderClient} from 'vs/platform/telemetry/common/telemetryIpc';
import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage';
import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService';
import {asFileEditorInput} from 'vs/workbench/common/editor';
import debug = require('vs/workbench/parts/debug/common/debug');
import {RawDebugSession} from 'vs/workbench/parts/debug/electron-browser/rawDebugSession';
import model = require('vs/workbench/parts/debug/common/debugModel');
import {DebugStringEditorInput, DebugErrorEditorInput} from 'vs/workbench/parts/debug/browser/debugEditorInputs';
import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel');
import debugactions = require('vs/workbench/parts/debug/browser/debugActions');
import {ConfigurationManager} from 'vs/workbench/parts/debug/node/debugConfigurationManager';
import {Source} from 'vs/workbench/parts/debug/common/debugSource';
import {ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary} from 'vs/workbench/parts/tasks/common/taskService';
import {TaskError, TaskErrors} from 'vs/workbench/parts/tasks/common/taskSystem';
import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService';
import {IPanelService} from 'vs/workbench/services/panel/common/panelService';
import {IPartService} from 'vs/workbench/services/part/common/partService';
import {ITextFileService} from 'vs/workbench/parts/files/common/files';
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {IWindowService, IBroadcast} from 'vs/workbench/services/window/electron-browser/windowService';
import {ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL} from 'vs/workbench/services/thread/electron-browser/threadService';
import {ipcRenderer as ipc} from 'electron';
import {Client} from 'vs/base/parts/ipc/node/ipc.cp';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname';
export class DebugService implements debug.IDebugService {
public _serviceBrand: any;
private _state: debug.State;
private _onDidChangeState: Emitter<debug.State>;
private session: RawDebugSession;
private model: model.Model;
private viewModel: viewmodel.ViewModel;
private configurationManager: ConfigurationManager;
private customTelemetryService: ITelemetryService;
private lastTaskEvent: TaskEvent;
private toDispose: lifecycle.IDisposable[];
private toDisposeOnSessionEnd: lifecycle.IDisposable[];
private inDebugMode: IContextKey<boolean>;
private breakpointsToSendOnResourceSaved: { [uri: string]: boolean };
constructor(
@IStorageService private storageService: IStorageService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@ITextFileService private textFileService: ITextFileService,
@IViewletService private viewletService: IViewletService,
@IPanelService private panelService: IPanelService,
@IFileService private fileService: IFileService,
@IMessageService private messageService: IMessageService,
@IPartService private partService: IPartService,
@IWindowService private windowService: IWindowService,
@ITelemetryService private telemetryService: ITelemetryService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@IEditorGroupService private editorGroupService: IEditorGroupService,
@IEventService eventService: IEventService,
@ILifecycleService private lifecycleService: ILifecycleService,
@IInstantiationService private instantiationService: IInstantiationService,
@IExtensionService private extensionService: IExtensionService,
@IMarkerService private markerService: IMarkerService,
@ITaskService private taskService: ITaskService,
@IConfigurationService private configurationService: IConfigurationService
) {
this.toDispose = [];
this.toDisposeOnSessionEnd = [];
this.session = null;
this.breakpointsToSendOnResourceSaved = {};
this._state = debug.State.Inactive;
this._onDidChangeState = new Emitter<debug.State>();
if (!this.contextService.getWorkspace()) {
this._state = debug.State.Disabled;
}
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, 'null'));
this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadWatchExpressions());
this.toDispose.push(this.model);
this.viewModel = new viewmodel.ViewModel();
this.registerListeners(eventService, lifecycleService);
}
private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void {
this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e)));
if (this.taskService) {
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => {
this.lastTaskEvent = e;
}));
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => {
if (e.type === TaskType.SingleRun) {
this.lastTaskEvent = null;
}
}));
this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => {
this.lastTaskEvent = null;
}));
}
lifecycleService.onShutdown(this.store, this);
lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this));
}
private onBroadcast(broadcast: IBroadcast): void {
// attach: PH is ready to be attached to
if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) {
this.rawAttach(broadcast.payload.port);
return;
}
if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) {
this.onSessionEnd();
return;
}
// from this point on we require an active session
let session = this.getActiveSession();
if (!session || session.configuration.type !== 'extensionHost') {
return; // we are only intersted if we have an active debug session for extensionHost
}
// a plugin logged output, show it inside the REPL
if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) {
let extensionOutput: ILogEntry = broadcast.payload;
let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info;
let args: any[] = [];
try {
let parsed = JSON.parse(extensionOutput.arguments);
args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o]));
} catch (error) {
args.push(extensionOutput.arguments);
}
// add output for each argument logged
let simpleVals: any[] = [];
for (let i = 0; i < args.length; i++) {
let a = args[i];
// undefined gets printed as 'undefined'
if (typeof a === 'undefined') {
simpleVals.push('undefined');
}
// null gets printed as 'null'
else if (a === null) {
simpleVals.push('null');
}
// objects & arrays are special because we want to inspect them in the REPL
else if (types.isObject(a) || Array.isArray(a)) {
// flush any existing simple values logged
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev);
simpleVals = [];
}
// show object
this.logToRepl(a, sev);
}
// string: watch out for % replacement directive
// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
else if (typeof a === 'string') {
let buf = '';
for (let j = 0, len = a.length; j < len; j++) {
if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) {
i++; // read over substitution
buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace
j++; // read over directive
} else {
buf += a[j];
}
}
simpleVals.push(buf);
}
// number or boolean is joined together
else {
simpleVals.push(a);
}
}
// flush simple values
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev);
}
}
}
private registerSessionListeners(): void {
this.toDisposeOnSessionEnd.push(this.session);
this.toDisposeOnSessionEnd.push(this.session.onDidInitialize(event => {
aria.status(nls.localize('debuggingStarted', "Debugging started."));
this.sendAllBreakpoints().then(() => {
if (this.session.configuration.capabilities.supportsConfigurationDoneRequest) {
this.session.configurationDone().done(null, e => {
// Disconnect the debug session on configuration done error #10596
if (this.session) {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
this.messageService.show(severity.Error, e.message);
});
}
});
}));
this.toDisposeOnSessionEnd.push(this.session.onDidStop(event => {
this.setStateAndEmit(debug.State.Stopped);
const threadId = event.body.threadId;
this.getThreadData().done(() => {
this.model.rawUpdate({
threadId,
stoppedDetails: event.body,
allThreadsStopped: event.body.allThreadsStopped
});
const thread = this.model.getThreads()[threadId];
thread.getCallStack(this).then(callStack => {
if (callStack.length > 0) {
// focus first stack frame from top that has source location
const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]);
this.setFocusedStackFrameAndEvaluate(stackFrameToFocus, thread).done(null, errors.onUnexpectedError);
this.windowService.getWindow().focus();
aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber));
return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false);
} else {
this.setFocusedStackFrameAndEvaluate(null, thread).done(null, errors.onUnexpectedError);
}
});
}, errors.onUnexpectedError);
}));
this.toDisposeOnSessionEnd.push(this.session.onDidThread(event => {
if (event.body.reason === 'started') {
this.getThreadData().done(null, errors.onUnexpectedError);
} else if (event.body.reason === 'exited') {
this.model.clearThreads(true, event.body.threadId);
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidTerminateDebugee(event => {
aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
if (this.session && this.session.getId() === event.body.sessionId) {
if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) {
this.restartSession().done(null, err => this.messageService.show(severity.Error, err.message));
} else {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidContinued(event => {
this.lazyTransitionToRunningState(event.body.allThreadsContinued ? undefined : event.body.threadId);
}));
this.toDisposeOnSessionEnd.push(this.session.onDidOutput(event => {
if (event.body && event.body.category === 'telemetry') {
// only log telemetry events from debug adapter if the adapter provided the telemetry key
// and the user opted in telemetry
if (this.customTelemetryService && this.telemetryService.isOptedIn) {
this.customTelemetryService.publicLog(event.body.output, event.body.data);
}
} else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) {
this.onOutput(event);
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidBreakpoint(event => {
const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (breakpoint) {
this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint });
} else {
const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (functionBreakpoint) {
this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint });
}
}
}));
this.toDisposeOnSessionEnd.push(this.session.onDidExitAdapter(event => {
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (this.session.configuration.type === 'extensionHost' && this._state === debug.State.RunningNoDebug) {
ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath);
}
if (this.session && this.session.getId() === event.body.sessionId) {
this.onSessionEnd();
}
}));
}
private onOutput(event: DebugProtocol.OutputEvent): void {
const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info;
this.appendReplOutput(event.body.output, outputSeverity);
}
private getThreadData(): TPromise<void> {
return this.session.threads().then(response => {
response.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread }));
});
}
private loadBreakpoints(): debug.IBreakpoint[] {
let result: debug.IBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }),
breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition);
});
} catch (e) { }
return result || [];
}
private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
let result: debug.IFunctionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
return new model.FunctionBreakpoint(fb.name, fb.enabled);
});
} catch (e) { }
return result || [];
}
private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
let result: debug.IExceptionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled);
});
} catch (e) { }
return result || [];
}
private loadWatchExpressions(): model.Expression[] {
let result: model.Expression[];
try {
result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string } ) => {
return new model.Expression(watchStoredData.name, false, watchStoredData.id);
});
} catch (e) { }
return result || [];
}
public get state(): debug.State {
return this._state;
}
public get onDidChangeState(): Event<debug.State> {
return this._onDidChangeState.event;
}
private setStateAndEmit(newState: debug.State): void {
this._state = newState;
this._onDidChangeState.fire(newState);
}
public get enabled(): boolean {
return !!this.contextService.getWorkspace();
}
public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame, thread?: debug.IThread): TPromise<void> {
if (!thread && focusedStackFrame) {
thread = this.model.getThreads()[focusedStackFrame.threadId];
}
this.viewModel.setFocusedStackFrame(focusedStackFrame, thread);
if (focusedStackFrame) {
return this.model.evaluateWatchExpressions(this.session, focusedStackFrame);
} else {
this.model.clearWatchExpressionValues();
return TPromise.as(null);
}
}
public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof model.Breakpoint) {
return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri);
} else if (breakpoint instanceof model.FunctionBreakpoint) {
return this.sendFunctionBreakpoints();
}
return this.sendExceptionBreakpoints();
}
this.model.enableOrDisableAllBreakpoints(enable);
return this.sendAllBreakpoints();
}
public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void[]> {
this.model.addBreakpoints(rawBreakpoints);
const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri);
rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath)));
return TPromise.join(uris.map(uri => this.sendBreakpoints(uri)));
}
public removeBreakpoints(id?: string): TPromise<any> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.source.uri.fsPath)));
const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri);
this.model.removeBreakpoints(toRemove);
return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri)));
}
public setBreakpointsActivated(activated: boolean): TPromise<void> {
this.model.setBreakpointsActivated(activated);
return this.sendAllBreakpoints();
}
public addFunctionBreakpoint(): void {
this.model.addFunctionBreakpoint('');
}
public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> {
this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } });
return this.sendFunctionBreakpoints();
}
public removeFunctionBreakpoints(id?: string): TPromise<void> {
this.model.removeFunctionBreakpoints(id);
return this.sendFunctionBreakpoints();
}
public addReplExpression(name: string): TPromise<void> {
this.telemetryService.publicLog('debugService/addReplExpression');
const focussedStackFrame = this.viewModel.getFocusedStackFrame();
return this.model.addReplExpression(this.session, focussedStackFrame, name)
// Evaluate all watch expressions again since repl evaluation might have changed some.
.then(() => this.setFocusedStackFrameAndEvaluate(focussedStackFrame));
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
this.model.logToRepl(value, severity);
}
public appendReplOutput(value: string, severity?: severity): void {
this.model.appendReplOutput(value, severity);
}
public removeReplExpressions(): void {
this.model.removeReplExpressions();
}
public setVariable(variable: debug.IExpression, value: string): TPromise<any> {
if (!this.session || !(variable instanceof model.Variable)) {
return TPromise.as(null);
}
return this.session.setVariable({
name: variable.name,
value,
variablesReference: (<model.Variable>variable).parent.reference
}).then(response => {
variable.value = response.body.value;
// Evaluate all watch expressions again since changing variable value might have changed some #8118.
return this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame());
}, err => {
(<model.Variable>variable).errorMessage = err.message;
});
}
public addWatchExpression(name: string): TPromise<void> {
return this.model.addWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), name);
}
public renameWatchExpression(id: string, newName: string): TPromise<void> {
return this.model.renameWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), id, newName);
}
public removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
}
public createSession(noDebug: boolean, configuration?: debug.IConfig): TPromise<any> {
this.removeReplExpressions();
return this.textFileService.saveAll() // make sure all dirty files are saved
.then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date
.then(() => this.extensionService.onReady()
.then(() => this.configurationManager.setConfiguration(configuration || this.configurationManager.configurationName)
.then(() => this.configurationManager.resolveInteractiveVariables())
.then(resolvedConfiguration => {
configuration = resolvedConfiguration;
if (!configuration) {
return this.configurationManager.openConfigFile(false).then(openend => {
if (openend) {
this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application."));
}
});
}
if (configuration.silentlyAbort) {
return;
}
configuration.noDebug = noDebug;
if (!this.configurationManager.adapter) {
return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type)))
: TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."),
{ actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] }));
}
return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => {
const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return this.doCreateSession(configuration);
}
this.messageService.show(severity.Error, {
message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) :
errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) :
nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode),
actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => {
this.messageService.hideAll();
return this.doCreateSession(configuration);
}), CloseAction]
});
}, (err: TaskError) => {
if (err.code !== TaskErrors.NotConfigured) {
throw err;
}
this.messageService.show(err.severity, {
message: err.message,
actions: [this.taskService.configureAction(), CloseAction]
});
});
}))));
}
private doCreateSession(configuration: debug.IExtHostConfig): TPromise<any> {
this.setStateAndEmit(debug.State.Initializing);
return this.telemetryService.getTelemetryInfo().then(info => {
const telemetryInfo: { [key: string]: string } = Object.create(null);
telemetryInfo['common.vscodemachineid'] = info.machineId;
telemetryInfo['common.vscodesessionid'] = info.sessionId;
return telemetryInfo;
}).then(data => {
const { aiKey, type } = this.configurationManager.adapter;
const publisher = this.configurationManager.adapter.extensionDescription.publisher;
this.customTelemetryService = null;
if (aiKey) {
const client = new Client(
uri.parse(require.toUrl('bootstrap')).fsPath,
{
serverName: 'Debug Telemetry',
timeout: 1000 * 60 * 5,
args: [`${ publisher }.${ type }`, JSON.stringify(data), aiKey],
env: {
ELECTRON_RUN_AS_NODE: 1,
PIPE_LOGGING: 'true',
AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp'
}
}
);
const channel = client.getChannel('telemetryAppender');
const appender = new TelemetryAppenderClient(channel);
this.toDisposeOnSessionEnd.push(client);
this.customTelemetryService = new TelemetryService({ appender }, this.configurationService);
}
this.session = this.instantiationService.createInstance(RawDebugSession, configuration.debugServer, this.configurationManager.adapter, this.customTelemetryService);
this.registerSessionListeners();
return this.session.initialize({
adapterID: configuration.type,
pathFormat: 'path',
linesStartAt1: true,
columnsStartAt1: true,
supportsVariableType: true, // #8858
supportsVariablePaging: true, // #9537
supportsRunInTerminalRequest: true // #10574
}).then((result: DebugProtocol.InitializeResponse) => {
if (!this.session) {
return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly")));
}
this.model.setExceptionBreakpoints(this.session.configuration.capabilities.exceptionBreakpointFilters);
return configuration.request === 'attach' ? this.session.attach(configuration) : this.session.launch(configuration);
}).then((result: DebugProtocol.Response) => {
if (!this.session) {
return TPromise.as(null);
}
if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) {
// We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden
this.viewModel.changedWorkbenchViewState = true;
this.viewletService.openViewlet(debug.VIEWLET_ID);
}
// Do not change status bar to orange if we are just running without debug.
if (!configuration.noDebug) {
this.partService.addClass('debugging');
}
this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError);
this.inDebugMode.set(true);
this.lazyTransitionToRunningState();
this.telemetryService.publicLog('debugSessionStart', {
type: configuration.type,
breakpointCount: this.model.getBreakpoints().length,
exceptionBreakpoints: this.model.getExceptionBreakpoints(),
watchExpressionsCount: this.model.getWatchExpressions().length,
extensionName: `${ this.configurationManager.adapter.extensionDescription.publisher }.${ this.configurationManager.adapter.extensionDescription.name }`,
isBuiltin: this.configurationManager.adapter.extensionDescription.isBuiltin
});
}).then(undefined, (error: any) => {
if (error instanceof Error && error.message === 'Canceled') {
// Do not show 'canceled' error messages to the user #7906
return TPromise.as(null);
}
this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined });
this.setStateAndEmit(debug.State.Inactive);
if (this.session) {
this.session.disconnect().done(null, errors.onUnexpectedError);
}
// Show the repl if some error got logged there #5870
if (this.model.getReplElements().length > 0) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction];
return TPromise.wrapError(errors.create(error.message, { actions }));
});
});
}
private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> {
if (!taskName) {
return TPromise.as(null);
}
// run a task before starting a debug session
return this.taskService.tasks().then(descriptions => {
const filteredTasks = descriptions.filter(task => task.name === taskName);
if (filteredTasks.length !== 1) {
return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), {
actions: [
this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL),
this.taskService.configureAction(),
CloseAction
]
}));
}
// task is already running - nothing to do.
if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) {
return TPromise.as(null);
}
if (this.lastTaskEvent) {
// there is a different task running currently.
return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName)));
}
// no task running, execute the preLaunchTask.
const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => {
this.lastTaskEvent = null;
return result;
}, err => {
this.lastTaskEvent = null;
});
if (filteredTasks[0].isWatching) {
return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null)));
}
return taskPromise;
});
}
private rawAttach(port: number): TPromise<any> {
if (this.session) {
return this.session.attach({ port });
}
this.setStateAndEmit(debug.State.Initializing);
const configuration = <debug.IExtHostConfig>this.configurationManager.configuration;
return this.doCreateSession({
type: configuration.type,
request: 'attach',
port,
sourceMaps: configuration.sourceMaps,
outDir: configuration.outDir,
debugServer: configuration.debugServer
});
}
public restartSession(): TPromise<any> {
return this.session ? this.session.disconnect(true).then(() =>
new TPromise<void>((c, e) => {
setTimeout(() => {
this.createSession(false, null).then(() => c(null), err => e(err));
}, 300);
})
) : this.createSession(false, null);
}
public getActiveSession(): debug.IRawDebugSession {
return this.session;
}
private onSessionEnd(): void {
if (this.session) {
const bpsExist = this.model.getBreakpoints().length > 0;
this.telemetryService.publicLog('debugSessionStop', {
type: this.session.configuration.type,
success: this.session.emittedStopped || !bpsExist,
sessionLengthInSeconds: this.session.getLengthInSeconds(),
breakpointCount: this.model.getBreakpoints().length,
watchExpressionsCount: this.model.getWatchExpressions().length
});
}
this.session = null;
try {
this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd);
} catch (e) {
// an internal module might be open so the dispose can throw -> ignore and continue with stop session.
}
this.partService.removeClass('debugging');
this.model.clearThreads(true);
this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError);
this.setStateAndEmit(debug.State.Inactive);
// set breakpoints back to unverified since the session ended.
// source reference changes across sessions, so we do not use it to persist the source.
const data: { [id: string]: { line: number, verified: boolean } } = {};
this.model.getBreakpoints().forEach(bp => {
delete bp.source.raw.sourceReference;
data[bp.getId()] = { line: bp.lineNumber, verified: false };
});
this.model.updateBreakpoints(data);
this.inDebugMode.reset();
}
public getModel(): debug.IModel {
return this.model;
}
public getViewModel(): debug.IViewModel {
return this.viewModel;
}
public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> {
const visibleEditors = this.editorService.getVisibleEditors();
for (let i = 0; i < visibleEditors.length; i++) {
const fileInput = asFileEditorInput(visibleEditors[i].input);
if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) ||
(visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) {
const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl();
if (control) {
control.revealLineInCenterIfOutsideViewport(lineNumber);
control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 });
this.editorGroupService.activateGroup(i);
if (!preserveFocus) {
this.editorGroupService.focusGroup(i);
}
}
return TPromise.as(null);
}
}
if (source.inMemory) {
// internal module
if (source.reference !== 0 && this.session && source.available) {
return this.session.source({ sourceReference: source.reference }).then(response => {
const mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0];
return this.getDebugStringEditorInput(source, response.body.content, mime);
}, (err: DebugProtocol.ErrorResponse) => {
// Display the error from debug adapter using a temporary editor #8836
return this.getDebugErrorEditorInput(source, err.message);
}).then(editorInput => {
return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide);
});
}
return this.sourceIsUnavailable(source, sideBySide);
}
return this.fileService.resolveFile(source.uri).then(() =>
this.editorService.openEditor({
resource: source.uri,
options: {
selection: {
startLineNumber: lineNumber,
startColumn: 1,
endLineNumber: lineNumber,
endColumn: 1
},
preserveFocus: preserveFocus
}
}, sideBySide), err => this.sourceIsUnavailable(source, sideBySide)
);
}
private sourceIsUnavailable(source: Source, sideBySide: boolean): TPromise<any> {
this.model.sourceIsUnavailable(source);
const editorInput = this.getDebugErrorEditorInput(source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name));
return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide);
}
public getConfigurationManager(): debug.IConfigurationManager {
return this.configurationManager;
}
public next(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.next({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepIn(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepIn({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepOut(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepOut({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public stepBack(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.stepBack({ threadId }).then(() => {
this.lazyTransitionToRunningState(threadId);
});
}
public continue(threadId: number): TPromise<void> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.continue({ threadId }).then(response => {
const allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true;
this.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId);
});
}
public pause(threadId: number): TPromise<any> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.pause({ threadId });
}
public restartFrame(frameId: number): TPromise<any> {
if (!this.session) {
return TPromise.as(null);
}
return this.session.restartFrame({ frameId });
}
public completions(text: string, position: Position): TPromise<ISuggestion[]> {
if (!this.session || !this.session.configuration.capabilities.supportsCompletionsRequest) {
return TPromise.as([]);
}
const focussedStackFrame = this.viewModel.getFocusedStackFrame();
return this.session.completions({
frameId: focussedStackFrame ? focussedStackFrame.frameId : undefined,
text,
column: position.column,
line: position.lineNumber
}).then(response => {
return !response ? [] : response.body.targets.map(item => ({
label: item.label,
insertText: item.text || item.label,
type: item.type
}));
}, err => []);
}
private lazyTransitionToRunningState(threadId?: number): void {
let setNewFocusedStackFrameScheduler: RunOnceScheduler;
const toDispose = this.session.onDidStop(e => {
if (e.body.threadId === threadId || e.body.allThreadsStopped || !threadId) {
setNewFocusedStackFrameScheduler.cancel();
}
});
this.model.clearThreads(false, threadId);
// Get a top stack frame of a stopped thread if there is any.
const threads = this.model.getThreads();
const stoppedReference = Object.keys(threads).filter(ref => threads[ref].stopped).pop();
const stoppedThread = stoppedReference ? threads[parseInt(stoppedReference)] : null;
const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null;
const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null;
if (!stoppedThread) {
this.setStateAndEmit(this.configurationManager.configuration.noDebug ? debug.State.RunningNoDebug : debug.State.Running);
}
// Do not immediatly set a new focused stack frame since that might cause unnecessery flickering
// of the tree in the debug viewlet. Only set focused stack frame if no stopped event has arrived in 500ms.
setNewFocusedStackFrameScheduler = new RunOnceScheduler(() => {
toDispose.dispose();
aria.status(nls.localize('debuggingContinued', "Debugging continued."));
this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError);
}, 500);
setNewFocusedStackFrameScheduler.schedule();
}
private getDebugStringEditorInput(source: Source, value: string, mtype: string): DebugStringEditorInput {
const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0);
this.toDisposeOnSessionEnd.push(result);
return result;
}
private getDebugErrorEditorInput(source: Source, value: string): DebugErrorEditorInput {
const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value);
this.toDisposeOnSessionEnd.push(result);
return result;
}
private sendAllBreakpoints(): TPromise<any> {
return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri)))
.then(() => this.sendFunctionBreakpoints())
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints());
}
private sendBreakpoints(modelUri: uri, sourceModified = false): TPromise<void> {
if (!this.session || !this.session.readyForBreakpoints) {
return TPromise.as(null);
}
if (this.textFileService.isDirty(modelUri)) {
// Only send breakpoints for a file once it is not dirty #8077
this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true;
return TPromise.as(null);
}
const breakpointsToSend = arrays.distinct(
this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()),
bp => `${bp.desiredLineNumber}`
);
const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model);
return this.session.setBreakpoints({
source: rawSource,
lines: breakpointsToSend.map(bp => bp.desiredLineNumber),
breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })),
sourceModified
}).then(response => {
const data: { [id: string]: { line?: number, verified: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateBreakpoints(data);
});
}
private sendFunctionBreakpoints(): TPromise<void> {
if (!this.session || !this.session.readyForBreakpoints || !this.session.configuration.capabilities.supportsFunctionBreakpoints) {
return TPromise.as(null);
}
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {
const data: { [id: string]: { name?: string, verified?: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateFunctionBreakpoints(data);
});
}
private sendExceptionBreakpoints(): TPromise<any> {
if (!this.session || !this.session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) {
return TPromise.as(null);
}
const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
return this.session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) });
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED)));
fileChangesEvent.getUpdated().forEach(event => {
if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) {
this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false;
this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError);
}
});
}
private store(): void {
this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE);
this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE);
this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.configurationManager.configurationName, StorageScope.WORKSPACE);
this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
}
public dispose(): void {
this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd);
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/electron-browser/debugService.ts | 1 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.9991377592086792,
0.0549132339656353,
0.00016093773592729121,
0.0002693769056349993,
0.21853885054588318
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tprivate getThreadData(): TPromise<void> {\n",
"\t\treturn this.session.threads().then(response => {\n",
"\t\t\tresponse.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread }));\n",
"\t\t});\n",
"\t}\n",
"\n",
"\tprivate loadBreakpoints(): debug.IBreakpoint[] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (response && response.body && response.body.threads) {\n",
"\t\t\t\tresponse.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread }));\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.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.
*--------------------------------------------------------------------------------------------*/
.monaco-split-view {
position: relative;
}
.monaco-split-view > .split-view-view {
overflow: hidden;
}
.monaco-split-view.vertical > .split-view-view {
width: 100%;
}
.monaco-split-view.horizontal > .split-view-view {
height: 100%;
}
.monaco-split-view > .split-view-view > .header {
position: relative;
line-height: 22px;
font-size: 11px;
font-weight: bold;
text-transform: uppercase;
padding-left: 20px;
background: rgba(128, 128, 128, 0.2);
overflow: hidden;
display: flex;
}
/* Bold font style does not go well with CJK fonts */
.monaco-split-view:lang(zh-Hans) > .split-view-view > .header,
.monaco-split-view:lang(zh-Hant) > .split-view-view > .header,
.monaco-split-view:lang(ja) > .split-view-view > .header,
.monaco-split-view:lang(ko) > .split-view-view > .header { font-weight: normal; }
.monaco-split-view > .split-view-view > .header.collapsible {
cursor: pointer;
}
.monaco-split-view > .split-view-view > .header.collapsible {
background-image: url('arrow-collapse.svg');
background-position: 2px center;
background-repeat: no-repeat;
}
.monaco-split-view > .split-view-view > .header.collapsible:not(.collapsed) {
background-image: url('arrow-expand.svg');
background-position: 2px center;
background-repeat: no-repeat;
}
.vs-dark .monaco-split-view > .split-view-view > .header.collapsible {
background-image: url('arrow-collapse-dark.svg');
}
.vs-dark .monaco-split-view > .split-view-view > .header.collapsible:not(.collapsed) {
background-image: url('arrow-expand-dark.svg');
background-position: 2px center;
background-repeat: no-repeat;
}
/* Animation */
.monaco-split-view.animated > .split-view-view {
transition-duration: 0.15s;
-webkit-transition-duration: 0.15s;
-moz-transition-duration: 0.15s;
transition-timing-function: ease-out;
-webkit-transition-timing-function: ease-out;
-moz-transition-timing-function: ease-out;
}
.monaco-split-view.vertical.animated > .split-view-view {
transition-property: height;
-webkit-transition-property: height;
-moz-transition-property: height;
}
.monaco-split-view.horizontal.animated > .split-view-view {
transition-property: width;
-webkit-transition-property: width;
-moz-transition-property: width;
}
/* High Contrast Theming */
.hc-black .monaco-split-view > .split-view-view:not(:first-child) > .header {
border-top: 1px solid #6FC3DF;
}
.hc-black .split-view-view .action-label {
background: none;
}
.hc-black .split-view-view > .header .action-label:before {
top: 4px !important;
} | src/vs/base/browser/ui/splitview/splitview.css | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017719466995913535,
0.00017355772433802485,
0.00017102062702178955,
0.00017354413284920156,
0.0000014127488157100743
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tprivate getThreadData(): TPromise<void> {\n",
"\t\treturn this.session.threads().then(response => {\n",
"\t\t\tresponse.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread }));\n",
"\t\t});\n",
"\t}\n",
"\n",
"\tprivate loadBreakpoints(): debug.IBreakpoint[] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (response && response.body && response.body.threads) {\n",
"\t\t\t\tresponse.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread }));\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.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.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"extensions": "Extensiones"
} | i18n/esn/src/vs/platform/extensionManagement/common/extensionManagement.i18n.json | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017735964502207935,
0.00017735964502207935,
0.00017735964502207935,
0.00017735964502207935,
0
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tprivate getThreadData(): TPromise<void> {\n",
"\t\treturn this.session.threads().then(response => {\n",
"\t\t\tresponse.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread }));\n",
"\t\t});\n",
"\t}\n",
"\n",
"\tprivate loadBreakpoints(): debug.IBreakpoint[] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (response && response.body && response.body.threads) {\n",
"\t\t\t\tresponse.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread }));\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.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.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"git": "Git"
} | i18n/fra/src/vs/workbench/parts/git/electron-main/askpassService.i18n.json | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017837536870501935,
0.00017837536870501935,
0.00017837536870501935,
0.00017837536870501935,
0
] |
{
"id": 5,
"code_window": [
"\t\treturn this.session.setVariable({\n",
"\t\t\tname: variable.name,\n",
"\t\t\tvalue,\n",
"\t\t\tvariablesReference: (<model.Variable>variable).parent.reference\n",
"\t\t}).then(response => {\n",
"\t\t\tvariable.value = response.body.value;\n",
"\t\t\t// Evaluate all watch expressions again since changing variable value might have changed some #8118.\n",
"\t\t\treturn this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame());\n",
"\t\t}, err => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (response && response.body) {\n",
"\t\t\t\tvariable.value = response.body.value;\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 510
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import nls = require('vs/nls');
import cp = require('child_process');
import fs = require('fs');
import net = require('net');
import Event, {Emitter} from 'vs/base/common/event';
import platform = require('vs/base/common/platform');
import objects = require('vs/base/common/objects');
import {Action} from 'vs/base/common/actions';
import errors = require('vs/base/common/errors');
import {TPromise} from 'vs/base/common/winjs.base';
import severity from 'vs/base/common/severity';
import stdfork = require('vs/base/node/stdFork');
import {IMessageService, CloseAction} from 'vs/platform/message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {ITerminalService} from 'vs/workbench/parts/terminal/electron-browser/terminal';
import {ITerminalService as IExternalTerminalService} from 'vs/workbench/parts/execution/common/execution';
import debug = require('vs/workbench/parts/debug/common/debug');
import {Adapter} from 'vs/workbench/parts/debug/node/debugAdapter';
import v8 = require('vs/workbench/parts/debug/node/v8Protocol');
import {IOutputService} from 'vs/workbench/parts/output/common/output';
import {ExtensionsChannelId} from 'vs/platform/extensionManagement/common/extensionManagement';
import {TerminalSupport} from 'vs/workbench/parts/debug/electron-browser/terminalSupport';
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
import {shell} from 'electron';
export interface SessionExitedEvent extends DebugProtocol.ExitedEvent {
body: {
exitCode: number,
sessionId: string
};
}
export interface SessionTerminatedEvent extends DebugProtocol.TerminatedEvent {
body: {
restart?: boolean,
sessionId: string
};
}
export class RawDebugSession extends v8.V8Protocol implements debug.IRawDebugSession {
public restarted: boolean;
public emittedStopped: boolean;
public readyForBreakpoints: boolean;
private serverProcess: cp.ChildProcess;
private socket: net.Socket = null;
private cachedInitServer: TPromise<void>;
private startTime: number;
private stopServerPending: boolean;
private sentPromises: TPromise<DebugProtocol.Response>[];
private capabilities: DebugProtocol.Capabilities;
private _onDidInitialize: Emitter<DebugProtocol.InitializedEvent>;
private _onDidStop: Emitter<DebugProtocol.StoppedEvent>;
private _onDidContinued: Emitter<DebugProtocol.ContinuedEvent>;
private _onDidTerminateDebugee: Emitter<SessionTerminatedEvent>;
private _onDidExitAdapter: Emitter<SessionExitedEvent>;
private _onDidThread: Emitter<DebugProtocol.ThreadEvent>;
private _onDidOutput: Emitter<DebugProtocol.OutputEvent>;
private _onDidBreakpoint: Emitter<DebugProtocol.BreakpointEvent>;
private _onDidEvent: Emitter<DebugProtocol.Event>;
constructor(
private debugServerPort: number,
private adapter: Adapter,
private customTelemetryService: ITelemetryService,
@IMessageService private messageService: IMessageService,
@ITelemetryService private telemetryService: ITelemetryService,
@IOutputService private outputService: IOutputService,
@ITerminalService private terminalService: ITerminalService,
@IExternalTerminalService private nativeTerminalService: IExternalTerminalService,
@IConfigurationService private configurationService: IConfigurationService
) {
super();
this.emittedStopped = false;
this.readyForBreakpoints = false;
this.sentPromises = [];
this._onDidInitialize = new Emitter<DebugProtocol.InitializedEvent>();
this._onDidStop = new Emitter<DebugProtocol.StoppedEvent>();
this._onDidContinued = new Emitter<DebugProtocol.ContinuedEvent>();
this._onDidTerminateDebugee = new Emitter<SessionTerminatedEvent>();
this._onDidExitAdapter = new Emitter<SessionExitedEvent>();
this._onDidThread = new Emitter<DebugProtocol.ThreadEvent>();
this._onDidOutput = new Emitter<DebugProtocol.OutputEvent>();
this._onDidBreakpoint = new Emitter<DebugProtocol.BreakpointEvent>();
this._onDidEvent = new Emitter<DebugProtocol.Event>();
}
public get onDidInitialize(): Event<DebugProtocol.InitializedEvent> {
return this._onDidInitialize.event;
}
public get onDidStop(): Event<DebugProtocol.StoppedEvent> {
return this._onDidStop.event;
}
public get onDidContinued(): Event<DebugProtocol.ContinuedEvent> {
return this._onDidContinued.event;
}
public get onDidTerminateDebugee(): Event<SessionTerminatedEvent> {
return this._onDidTerminateDebugee.event;
}
public get onDidExitAdapter(): Event<SessionExitedEvent> {
return this._onDidExitAdapter.event;
}
public get onDidThread(): Event<DebugProtocol.ThreadEvent> {
return this._onDidThread.event;
}
public get onDidOutput(): Event<DebugProtocol.OutputEvent> {
return this._onDidOutput.event;
}
public get onDidBreakpoint(): Event<DebugProtocol.BreakpointEvent> {
return this._onDidBreakpoint.event;
}
public get onDidEvent(): Event<DebugProtocol.Event> {
return this._onDidEvent.event;
}
private initServer(): TPromise<void> {
if (this.cachedInitServer) {
return this.cachedInitServer;
}
const serverPromise = this.debugServerPort ? this.connectServer(this.debugServerPort) : this.startServer();
this.cachedInitServer = serverPromise.then(() => {
this.startTime = new Date().getTime();
}, err => {
this.cachedInitServer = null;
return TPromise.wrapError(err);
}
);
return this.cachedInitServer;
}
public custom(request: string, args: any): TPromise<DebugProtocol.Response> {
return this.send(request, args);
}
protected send(command: string, args: any, cancelOnDisconnect = true): TPromise<DebugProtocol.Response> {
return this.initServer().then(() => {
const promise = super.send(command, args).then(response => response, (errorResponse: DebugProtocol.ErrorResponse) => {
const error = errorResponse.body ? errorResponse.body.error : null;
const telemetryMessage = error ? debug.formatPII(error.format, true, error.variables) : errorResponse.message;
if (error && error.sendTelemetry) {
this.telemetryService.publicLog('debugProtocolErrorResponse', { error: telemetryMessage });
if (this.customTelemetryService) {
this.customTelemetryService.publicLog('debugProtocolErrorResponse', { error: telemetryMessage });
}
}
if (errors.isPromiseCanceledError(errorResponse) || (error && error.showUser === false)) {
// Do not show error message to user if showUser === false or 'canceled' error message #7906
return TPromise.as(null);
}
const userMessage = error ? debug.formatPII(error.format, false, error.variables) : errorResponse.message;
if (error && error.url) {
const label = error.urlLabel ? error.urlLabel : nls.localize('moreInfo', "More Info");
return TPromise.wrapError(errors.create(userMessage, { actions: [CloseAction, new Action('debug.moreInfo', label, null, true, () => {
shell.openExternal(error.url);
return TPromise.as(null);
})]}));
}
return TPromise.wrapError(new Error(userMessage));
});
if (cancelOnDisconnect) {
this.sentPromises.push(promise);
}
return promise;
});
}
protected onEvent(event: DebugProtocol.Event): void {
if (event.body) {
event.body.sessionId = this.getId();
} else {
event.body = { sessionId: this.getId() };
}
if (event.event === 'initialized') {
this.readyForBreakpoints = true;
this._onDidInitialize.fire(event);
} else if (event.event === 'stopped') {
this.emittedStopped = true;
this._onDidStop.fire(<DebugProtocol.StoppedEvent>event);
} else if (event.event === 'continued') {
this._onDidContinued.fire(<DebugProtocol.ContinuedEvent>event);
} else if (event.event === 'thread') {
this._onDidThread.fire(<DebugProtocol.ThreadEvent>event);
} else if (event.event === 'output') {
this._onDidOutput.fire(<DebugProtocol.OutputEvent>event);
} else if (event.event === 'breakpoint') {
this._onDidBreakpoint.fire(<DebugProtocol.BreakpointEvent>event);
} else if (event.event === 'terminated') {
this._onDidTerminateDebugee.fire(<SessionTerminatedEvent>event);
} else if (event.event === 'exit') {
this._onDidExitAdapter.fire(<SessionExitedEvent>event);
}
this._onDidEvent.fire(event);
}
public get configuration(): { type: string, capabilities: DebugProtocol.Capabilities } {
return {
type: this.adapter.type,
capabilities: this.capabilities || {}
};
}
public initialize(args: DebugProtocol.InitializeRequestArguments): TPromise<DebugProtocol.InitializeResponse> {
return this.send('initialize', args).then(response => this.readCapabilities(response));
}
private readCapabilities(response: DebugProtocol.Response): DebugProtocol.Response {
if (response) {
this.capabilities = objects.mixin(this.capabilities, response.body);
}
return response;
}
public launch(args: DebugProtocol.LaunchRequestArguments): TPromise<DebugProtocol.LaunchResponse> {
return this.send('launch', args).then(response => this.readCapabilities(response));
}
public attach(args: DebugProtocol.AttachRequestArguments): TPromise<DebugProtocol.AttachResponse> {
return this.send('attach', args).then(response => this.readCapabilities(response));
}
public next(args: DebugProtocol.NextArguments): TPromise<DebugProtocol.NextResponse> {
return this.send('next', args);
}
public stepIn(args: DebugProtocol.StepInArguments): TPromise<DebugProtocol.StepInResponse> {
return this.send('stepIn', args);
}
public stepOut(args: DebugProtocol.StepOutArguments): TPromise<DebugProtocol.StepOutResponse> {
return this.send('stepOut', args);
}
public stepBack(args: DebugProtocol.StepBackArguments): TPromise<DebugProtocol.StepBackResponse> {
return this.send('stepBack', args);
}
public continue(args: DebugProtocol.ContinueArguments): TPromise<DebugProtocol.ContinueResponse> {
return this.send('continue', args);
}
public pause(args: DebugProtocol.PauseArguments): TPromise<DebugProtocol.PauseResponse> {
return this.send('pause', args);
}
public setVariable(args: DebugProtocol.SetVariableArguments): TPromise<DebugProtocol.SetVariableResponse> {
return this.send('setVariable', args);
}
public restartFrame(args: DebugProtocol.RestartFrameArguments): TPromise<DebugProtocol.RestartFrameResponse> {
return this.send('restartFrame', args);
}
public completions(args: DebugProtocol.CompletionsArguments): TPromise<DebugProtocol.CompletionsResponse> {
return this.send('completions', args);
}
public disconnect(restart = false, force = false): TPromise<DebugProtocol.DisconnectResponse> {
if (this.stopServerPending && force) {
return this.stopServer();
}
// Cancel all sent promises on disconnect so debug trees are not left in a broken state #3666.
// Give a 1s timeout to give a chance for some promises to complete.
setTimeout(() => {
this.sentPromises.forEach(p => p.cancel());
this.sentPromises = [];
}, 1000);
if ((this.serverProcess || this.socket) && !this.stopServerPending) {
// point of no return: from now on don't report any errors
this.stopServerPending = true;
this.restarted = restart;
return this.send('disconnect', { restart: restart }, false).then(() => this.stopServer(), () => this.stopServer());
}
return TPromise.as(null);
}
public setBreakpoints(args: DebugProtocol.SetBreakpointsArguments): TPromise<DebugProtocol.SetBreakpointsResponse> {
return this.send('setBreakpoints', args);
}
public setFunctionBreakpoints(args: DebugProtocol.SetFunctionBreakpointsArguments): TPromise<DebugProtocol.SetFunctionBreakpointsResponse> {
return this.send('setFunctionBreakpoints', args);
}
public setExceptionBreakpoints(args: DebugProtocol.SetExceptionBreakpointsArguments): TPromise<DebugProtocol.SetExceptionBreakpointsResponse> {
return this.send('setExceptionBreakpoints', args);
}
public configurationDone(): TPromise<DebugProtocol.ConfigurationDoneResponse> {
return this.send('configurationDone', null);
}
public stackTrace(args: DebugProtocol.StackTraceArguments): TPromise<DebugProtocol.StackTraceResponse> {
return this.send('stackTrace', args);
}
public scopes(args: DebugProtocol.ScopesArguments): TPromise<DebugProtocol.ScopesResponse> {
return this.send('scopes', args);
}
public variables(args: DebugProtocol.VariablesArguments): TPromise<DebugProtocol.VariablesResponse> {
return this.send('variables', args);
}
public source(args: DebugProtocol.SourceArguments): TPromise<DebugProtocol.SourceResponse> {
return this.send('source', args);
}
public threads(): TPromise<DebugProtocol.ThreadsResponse> {
return this.send('threads', null);
}
public evaluate(args: DebugProtocol.EvaluateArguments): TPromise<DebugProtocol.EvaluateResponse> {
return this.send('evaluate', args);
}
public getLengthInSeconds(): number {
return (new Date().getTime() - this.startTime) / 1000;
}
protected dispatchRequest(request: DebugProtocol.Request, response: DebugProtocol.Response): void {
if (request.command === 'runInTerminal') {
TerminalSupport.runInTerminal(this.terminalService, this.nativeTerminalService, this.configurationService, <DebugProtocol.RunInTerminalRequestArguments>request.arguments, <DebugProtocol.RunInTerminalResponse>response).then(() => {
this.sendResponse(response);
}, e => {
response.success = false;
response.message = e.message;
this.sendResponse(response);
});
} else {
response.success = false;
response.message = `unknown request '${request.command}'`;
this.sendResponse(response);
}
}
private connectServer(port: number): TPromise<void> {
return new TPromise<void>((c, e) => {
this.socket = net.createConnection(port, '127.0.0.1', () => {
this.connect(this.socket, <any>this.socket);
c(null);
});
this.socket.on('error', (err: any) => {
e(err);
});
this.socket.on('close', () => this.onServerExit());
});
}
private startServer(): TPromise<any> {
if (!this.adapter.program) {
return TPromise.wrapError(new Error(nls.localize('noDebugAdapterExtensionInstalled', "No extension installed for '{0}' debugging.", this.adapter.type)));
}
return this.getLaunchDetails().then(d => this.launchServer(d).then(() => {
this.serverProcess.on('error', (err: Error) => this.onServerError(err));
this.serverProcess.on('exit', (code: number, signal: string) => this.onServerExit());
const sanitize = (s: string) => s.toString().replace(/\r?\n$/mg, '');
// this.serverProcess.stdout.on('data', (data: string) => {
// console.log('%c' + sanitize(data), 'background: #ddd; font-style: italic;');
// });
this.serverProcess.stderr.on('data', (data: string) => {
this.outputService.getChannel(ExtensionsChannelId).append(sanitize(data));
});
this.connect(this.serverProcess.stdout, this.serverProcess.stdin);
}));
}
private launchServer(launch: { command: string, argv: string[] }): TPromise<void> {
return new TPromise<void>((c, e) => {
if (launch.command === 'node') {
stdfork.fork(launch.argv[0], launch.argv.slice(1), {}, (err, child) => {
if (err) {
e(new Error(nls.localize('unableToLaunchDebugAdapter', "Unable to launch debug adapter from '{0}'.", launch.argv[0])));
}
this.serverProcess = child;
c(null);
});
} else {
this.serverProcess = cp.spawn(launch.command, launch.argv, {
stdio: [
'pipe', // stdin
'pipe', // stdout
'pipe' // stderr
],
});
c(null);
}
});
}
private stopServer(): TPromise<any> {
if (this.socket !== null) {
this.socket.end();
this.cachedInitServer = null;
this.onEvent({ event: 'exit', type: 'event', seq: 0 });
}
if (!this.serverProcess) {
return TPromise.as(null);
}
this.stopServerPending = true;
let ret: TPromise<void>;
// when killing a process in windows its child
// processes are *not* killed but become root
// processes. Therefore we use TASKKILL.EXE
if (platform.isWindows) {
ret = new TPromise<void>((c, e) => {
const killer = cp.exec(`taskkill /F /T /PID ${this.serverProcess.pid}`, function (err, stdout, stderr) {
if (err) {
return e(err);
}
});
killer.on('exit', c);
killer.on('error', e);
});
} else {
this.serverProcess.kill('SIGTERM');
ret = TPromise.as(null);
}
return ret;
}
private getLaunchDetails(): TPromise<{ command: string; argv: string[]; }> {
return new TPromise((c, e) => {
fs.exists(this.adapter.program, exists => {
if (exists) {
c(null);
} else {
e(new Error(nls.localize('debugAdapterBinNotFound', "Debug adapter executable '{0}' not found.", this.adapter.program)));
}
});
}).then(() => {
if (this.adapter.runtime) {
return {
command: this.adapter.runtime,
argv: (this.adapter.runtimeArgs || []).concat([this.adapter.program]).concat(this.adapter.args || [])
};
}
return {
command: this.adapter.program,
argv: this.adapter.args || []
};
});
}
protected onServerError(err: Error): void {
this.messageService.show(severity.Error, nls.localize('stoppingDebugAdapter', "{0}. Stopping the debug adapter.", err.message));
this.stopServer().done(null, errors.onUnexpectedError);
}
private onServerExit(): void {
this.serverProcess = null;
this.cachedInitServer = null;
if (!this.stopServerPending) {
this.messageService.show(severity.Error, nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly"));
}
this.onEvent({ event: 'exit', type: 'event', seq: 0 });
}
public dispose(): void {
this.disconnect().done(null, errors.onUnexpectedError);
}
}
| src/vs/workbench/parts/debug/electron-browser/rawDebugSession.ts | 1 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00108088250271976,
0.00019635511853266507,
0.00016367650823667645,
0.0001708833733573556,
0.00013660162221640348
] |
{
"id": 5,
"code_window": [
"\t\treturn this.session.setVariable({\n",
"\t\t\tname: variable.name,\n",
"\t\t\tvalue,\n",
"\t\t\tvariablesReference: (<model.Variable>variable).parent.reference\n",
"\t\t}).then(response => {\n",
"\t\t\tvariable.value = response.body.value;\n",
"\t\t\t// Evaluate all watch expressions again since changing variable value might have changed some #8118.\n",
"\t\t\treturn this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame());\n",
"\t\t}, err => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (response && response.body) {\n",
"\t\t\t\tvariable.value = response.body.value;\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 510
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"titleKeybinding": "{0} ({1})"
} | i18n/esn/src/vs/workbench/browser/parts/activitybar/activityAction.i18n.json | 0 | https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97 | [
0.00017598184058442712,
0.00017598184058442712,
0.00017598184058442712,
0.00017598184058442712,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.