diff --git a/build/lib/i18n.resources.json b/build/lib/i18n.resources.json index 87da5e9bb0d..81fda4c4e9e 100644 --- a/build/lib/i18n.resources.json +++ b/build/lib/i18n.resources.json @@ -78,6 +78,10 @@ "name": "vs/workbench/parts/logs", "project": "vscode-workbench" }, + { + "name": "vs/workbench/parts/navigation", + "project": "vscode-workbench" + }, { "name": "vs/workbench/parts/output", "project": "vscode-workbench" diff --git a/src/vs/base/browser/builder.ts b/src/vs/base/browser/builder.ts index b47acecc5ae..74b574df9a0 100644 --- a/src/vs/base/browser/builder.ts +++ b/src/vs/base/browser/builder.ts @@ -70,8 +70,8 @@ export class Builder implements IDisposable { private offdom: boolean; private container: HTMLElement; private createdElements: HTMLElement[]; - private toUnbind: { [type: string]: IDisposable[]; }; - private captureToUnbind: { [type: string]: IDisposable[]; }; + private toDispose: { [type: string]: IDisposable[]; }; + private captureToDispose: { [type: string]: IDisposable[]; }; constructor(element?: HTMLElement, offdom?: boolean) { this.offdom = offdom; @@ -81,27 +81,27 @@ export class Builder implements IDisposable { this.currentElement = element; this.createdElements = []; - this.toUnbind = {}; - this.captureToUnbind = {}; + this.toDispose = {}; + this.captureToDispose = {}; } /** * Returns a new builder that lets the current HTML Element of this builder be the container * for future additions on the builder. */ - public asContainer(): Builder { + asContainer(): Builder { return withBuilder(this, this.offdom); } /** * Clones the builder providing the same properties as this one. */ - public clone(): Builder { + clone(): Builder { let builder = new Builder(this.container, this.offdom); builder.currentElement = this.currentElement; builder.createdElements = this.createdElements; - builder.captureToUnbind = this.captureToUnbind; - builder.toUnbind = this.toUnbind; + builder.captureToDispose = this.captureToDispose; + builder.toDispose = this.toDispose; return builder; } @@ -113,9 +113,9 @@ export class Builder implements IDisposable { * at the end. * This method is a no-op unless the builder was created with the offdom option to be true. */ - public build(container?: Builder, index?: number): Builder; - public build(container?: HTMLElement, index?: number): Builder; - public build(container?: any, index?: number): Builder { + build(container?: Builder, index?: number): Builder; + build(container?: HTMLElement, index?: number): Builder; + build(container?: any, index?: number): Builder { assert.ok(this.offdom, 'This builder was not created off-dom, so build() can not be called.'); // Use builders own container if present @@ -154,9 +154,9 @@ export class Builder implements IDisposable { * attached the current element. If the current element has a parent, it will be * detached from that parent. */ - public appendTo(container?: Builder, index?: number): Builder; - public appendTo(container?: HTMLElement, index?: number): Builder; - public appendTo(container?: any, index?: number): Builder { + appendTo(container?: Builder, index?: number): Builder; + appendTo(container?: HTMLElement, index?: number): Builder; + appendTo(container?: any, index?: number): Builder { // Use builders own container if present if (!container) { @@ -194,9 +194,9 @@ export class Builder implements IDisposable { * of the return value being the builder which called the operation (`a` in the * first case; `b` in the second case). */ - public append(child: HTMLElement, index?: number): Builder; - public append(child: Builder, index?: number): Builder; - public append(child: any, index?: number): Builder { + append(child: HTMLElement, index?: number): Builder; + append(child: Builder, index?: number): Builder; + append(child: any, index?: number): Builder { assert.ok(child, 'Need a child to append'); if (DOM.isHTMLElement(child)) { @@ -213,7 +213,7 @@ export class Builder implements IDisposable { /** * Removes the current element of this builder from its parent node. */ - public offDOM(): Builder { + offDOM(): Builder { if (this.currentElement.parentNode) { this.currentElement.parentNode.removeChild(this.currentElement); } @@ -224,14 +224,14 @@ export class Builder implements IDisposable { /** * Returns the HTML Element the builder is currently active on. */ - public getHTMLElement(): HTMLElement { + getHTMLElement(): HTMLElement { return this.currentElement; } /** * Returns the HTML Element the builder is building in. */ - public getContainer(): HTMLElement { + getContainer(): HTMLElement { return this.container; } @@ -245,7 +245,7 @@ export class Builder implements IDisposable { * of the element. The function will be called with a new builder created with the * provided element. */ - public div(attributes?: any, fn?: (builder: Builder) => void): Builder { + div(attributes?: any, fn?: (builder: Builder) => void): Builder { return this.doElement('div', attributes, fn); } @@ -257,7 +257,7 @@ export class Builder implements IDisposable { * of the element. The function will be called with a new builder created with the * provided element. */ - public p(attributes?: any, fn?: (builder: Builder) => void): Builder { + p(attributes?: any, fn?: (builder: Builder) => void): Builder { return this.doElement('p', attributes, fn); } @@ -269,7 +269,7 @@ export class Builder implements IDisposable { * of the element. The function will be called with a new builder created with the * provided element. */ - public ul(attributes?: any, fn?: (builder: Builder) => void): Builder { + ul(attributes?: any, fn?: (builder: Builder) => void): Builder { return this.doElement('ul', attributes, fn); } @@ -281,7 +281,7 @@ export class Builder implements IDisposable { * of the element. The function will be called with a new builder created with the * provided element. */ - public li(attributes?: any, fn?: (builder: Builder) => void): Builder { + li(attributes?: any, fn?: (builder: Builder) => void): Builder { return this.doElement('li', attributes, fn); } @@ -293,7 +293,7 @@ export class Builder implements IDisposable { * of the element. The function will be called with a new builder created with the * provided element. */ - public span(attributes?: any, fn?: (builder: Builder) => void): Builder { + span(attributes?: any, fn?: (builder: Builder) => void): Builder { return this.doElement('span', attributes, fn); } @@ -305,7 +305,7 @@ export class Builder implements IDisposable { * of the element. The function will be called with a new builder created with the * provided element. */ - public img(attributes?: any, fn?: (builder: Builder) => void): Builder { + img(attributes?: any, fn?: (builder: Builder) => void): Builder { return this.doElement('img', attributes, fn); } @@ -317,7 +317,7 @@ export class Builder implements IDisposable { * of the element. The function will be called with a new builder created with the * provided element. */ - public a(attributes?: any, fn?: (builder: Builder) => void): Builder { + a(attributes?: any, fn?: (builder: Builder) => void): Builder { return this.doElement('a', attributes, fn); } @@ -329,7 +329,7 @@ export class Builder implements IDisposable { * of the element. The function will be called with a new builder created with the * provided element. */ - public element(name: string, attributes?: any, fn?: (builder: Builder) => void): Builder { + element(name: string, attributes?: any, fn?: (builder: Builder) => void): Builder { return this.doElement(name, attributes, fn); } @@ -371,7 +371,7 @@ export class Builder implements IDisposable { /** * Calls focus() on the current HTML element; */ - public domFocus(): Builder { + domFocus(): Builder { this.currentElement.focus(); return this; @@ -380,7 +380,7 @@ export class Builder implements IDisposable { /** * Calls blur() on the current HTML element; */ - public domBlur(): Builder { + domBlur(): Builder { this.currentElement.blur(); return this; @@ -389,14 +389,14 @@ export class Builder implements IDisposable { /** * Registers listener on event types on the current element. */ - public on(type: string, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder; - public on(typeArray: string[], fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder; - public on(arg1: any, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder { + on(type: string, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToDisposeContainer?: IDisposable[], useCapture?: boolean): Builder; + on(typeArray: string[], fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToDisposeContainer?: IDisposable[], useCapture?: boolean): Builder; + on(arg1: any, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToDisposeContainer?: IDisposable[], useCapture?: boolean): Builder { // Event Type Array if (types.isArray(arg1)) { arg1.forEach((type: string) => { - this.on(type, fn, listenerToUnbindContainer, useCapture); + this.on(type, fn, listenerToDisposeContainer, useCapture); }); } @@ -411,15 +411,15 @@ export class Builder implements IDisposable { // Remember for off() use if (useCapture) { - if (!this.captureToUnbind[type]) { - this.captureToUnbind[type] = []; + if (!this.captureToDispose[type]) { + this.captureToDispose[type] = []; } - this.captureToUnbind[type].push(unbind); + this.captureToDispose[type].push(unbind); } else { - if (!this.toUnbind[type]) { - this.toUnbind[type] = []; + if (!this.toDispose[type]) { + this.toDispose[type] = []; } - this.toUnbind[type].push(unbind); + this.toDispose[type].push(unbind); } // Bind to Element @@ -428,8 +428,8 @@ export class Builder implements IDisposable { this.setProperty(LISTENER_BINDING_ID, listenerBinding); // Add to Array if passed in - if (listenerToUnbindContainer && types.isArray(listenerToUnbindContainer)) { - listenerToUnbindContainer.push(unbind); + if (listenerToDisposeContainer && types.isArray(listenerToDisposeContainer)) { + listenerToDisposeContainer.push(unbind); } } @@ -439,9 +439,9 @@ export class Builder implements IDisposable { /** * Removes all listeners from all elements created by the builder for the given event type. */ - public off(type: string, useCapture?: boolean): Builder; - public off(typeArray: string[], useCapture?: boolean): Builder; - public off(arg1: any, useCapture?: boolean): Builder { + off(type: string, useCapture?: boolean): Builder; + off(typeArray: string[], useCapture?: boolean): Builder; + off(arg1: any, useCapture?: boolean): Builder { // Event Type Array if (types.isArray(arg1)) { @@ -454,12 +454,12 @@ export class Builder implements IDisposable { else { let type = arg1; if (useCapture) { - if (this.captureToUnbind[type]) { - this.captureToUnbind[type] = dispose(this.captureToUnbind[type]); + if (this.captureToDispose[type]) { + this.captureToDispose[type] = dispose(this.captureToDispose[type]); } } else { - if (this.toUnbind[type]) { - this.toUnbind[type] = dispose(this.toUnbind[type]); + if (this.toDispose[type]) { + this.toDispose[type] = dispose(this.toDispose[type]); } } } @@ -471,9 +471,9 @@ export class Builder implements IDisposable { * Registers listener on event types on the current element and removes * them after first invocation. */ - public once(type: string, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder; - public once(typesArray: string[], fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder; - public once(arg1: any, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder { + once(type: string, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToDisposeContainer?: IDisposable[], useCapture?: boolean): Builder; + once(typesArray: string[], fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToDisposeContainer?: IDisposable[], useCapture?: boolean): Builder; + once(arg1: any, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToDisposeContainer?: IDisposable[], useCapture?: boolean): Builder { // Event Type Array if (types.isArray(arg1)) { @@ -493,8 +493,8 @@ export class Builder implements IDisposable { }, useCapture || false); // Add to Array if passed in - if (listenerToUnbindContainer && types.isArray(listenerToUnbindContainer)) { - listenerToUnbindContainer.push(unbind); + if (listenerToDisposeContainer && types.isArray(listenerToDisposeContainer)) { + listenerToDisposeContainer.push(unbind); } } @@ -510,12 +510,12 @@ export class Builder implements IDisposable { * c) an object literal passed in will apply the properties of the literal as attributes * to the current element of the builder. */ - public attr(name: string): string; - public attr(name: string, value: string): Builder; - public attr(name: string, value: boolean): Builder; - public attr(name: string, value: number): Builder; - public attr(attributes: any): Builder; - public attr(firstP: any, secondP?: any): any { + attr(name: string): string; + attr(name: string, value: string): Builder; + attr(name: string, value: boolean): Builder; + attr(name: string, value: number): Builder; + attr(attributes: any): Builder; + attr(firstP: any, secondP?: any): any { // Apply Object Literal to Attributes of Element if (types.isObject(firstP)) { @@ -564,14 +564,14 @@ export class Builder implements IDisposable { /** * Removes an attribute by the given name. */ - public removeAttribute(prop: string): void { + removeAttribute(prop: string): void { this.currentElement.removeAttribute(prop); } /** * Sets the id attribute to the value provided for the current HTML element of the builder. */ - public id(id: string): Builder { + id(id: string): Builder { this.currentElement.setAttribute('id', id); return this; @@ -580,7 +580,7 @@ export class Builder implements IDisposable { /** * Sets the title attribute to the value provided for the current HTML element of the builder. */ - public title(title: string): Builder { + title(title: string): Builder { this.currentElement.setAttribute('title', title); return this; @@ -589,7 +589,7 @@ export class Builder implements IDisposable { /** * Sets the type attribute to the value provided for the current HTML element of the builder. */ - public type(type: string): Builder { + type(type: string): Builder { this.currentElement.setAttribute('type', type); return this; @@ -598,7 +598,7 @@ export class Builder implements IDisposable { /** * Sets the value attribute to the value provided for the current HTML element of the builder. */ - public value(value: string): Builder { + value(value: string): Builder { this.currentElement.setAttribute('value', value); return this; @@ -607,7 +607,7 @@ export class Builder implements IDisposable { /** * Sets the tabindex attribute to the value provided for the current HTML element of the builder. */ - public tabindex(index: number): Builder { + tabindex(index: number): Builder { this.currentElement.setAttribute('tabindex', index.toString()); return this; @@ -623,10 +623,10 @@ export class Builder implements IDisposable { * c) an object literal passed in will apply the properties of the literal as styles * to the current element of the builder. */ - public style(name: string): string; - public style(name: string, value: string): Builder; - public style(attributes: any): Builder; - public style(firstP: any, secondP?: any): any { + style(name: string): string; + style(name: string, value: string): Builder; + style(attributes: any): Builder; + style(firstP: any, secondP?: any): any { // Apply Object Literal to Styles of Element if (types.isObject(firstP)) { @@ -692,14 +692,14 @@ export class Builder implements IDisposable { /** * Returns the computed CSS style for the current HTML element of the builder. */ - public getComputedStyle(): CSSStyleDeclaration { + getComputedStyle(): CSSStyleDeclaration { return DOM.getComputedStyle(this.currentElement); } /** * Adds the variable list of arguments as class names to the current HTML element of the builder. */ - public addClass(...classes: string[]): Builder { + addClass(...classes: string[]): Builder { classes.forEach((nameValue: string) => { let names = nameValue.split(' '); names.forEach((name: string) => { @@ -714,7 +714,7 @@ export class Builder implements IDisposable { * Sets the class name of the current HTML element of the builder to the provided className. * If shouldAddClass is provided - for true class is added, for false class is removed. */ - public setClass(className: string, shouldAddClass: boolean = null): Builder { + setClass(className: string, shouldAddClass: boolean = null): Builder { if (shouldAddClass === null) { this.currentElement.className = className; } else if (shouldAddClass) { @@ -729,14 +729,14 @@ export class Builder implements IDisposable { /** * Returns whether the current HTML element of the builder has the provided class assigned. */ - public hasClass(className: string): boolean { + hasClass(className: string): boolean { return DOM.hasClass(this.currentElement, className); } /** * Removes the variable list of arguments as class names from the current HTML element of the builder. */ - public removeClass(...classes: string[]): Builder { + removeClass(...classes: string[]): Builder { classes.forEach((nameValue: string) => { let names = nameValue.split(' '); names.forEach((name: string) => { @@ -750,7 +750,7 @@ export class Builder implements IDisposable { /** * Adds or removes the provided className for the current HTML element of the builder. */ - public toggleClass(className: string): Builder { + toggleClass(className: string): Builder { if (this.hasClass(className)) { this.removeClass(className); } else { @@ -763,7 +763,7 @@ export class Builder implements IDisposable { /** * Sets the CSS property color. */ - public color(color: string): Builder { + color(color: string): Builder { this.currentElement.style.color = color; return this; @@ -772,10 +772,10 @@ export class Builder implements IDisposable { /** * Sets the CSS property padding. */ - public padding(padding: string): Builder; - public padding(top: number, right?: number, bottom?: number, left?: number): Builder; - public padding(top: string, right?: string, bottom?: string, left?: string): Builder; - public padding(top: any, right?: any, bottom?: any, left?: any): Builder { + padding(padding: string): Builder; + padding(top: number, right?: number, bottom?: number, left?: number): Builder; + padding(top: string, right?: string, bottom?: string, left?: string): Builder; + padding(top: any, right?: any, bottom?: any, left?: any): Builder { if (types.isString(top) && top.indexOf(' ') >= 0) { return this.padding.apply(this, top.split(' ')); } @@ -802,10 +802,10 @@ export class Builder implements IDisposable { /** * Sets the CSS property margin. */ - public margin(margin: string): Builder; - public margin(top: number, right?: number, bottom?: number, left?: number): Builder; - public margin(top: string, right?: string, bottom?: string, left?: string): Builder; - public margin(top: any, right?: any, bottom?: any, left?: any): Builder { + margin(margin: string): Builder; + margin(top: number, right?: number, bottom?: number, left?: number): Builder; + margin(top: string, right?: string, bottom?: string, left?: string): Builder; + margin(top: any, right?: any, bottom?: any, left?: any): Builder { if (types.isString(top) && top.indexOf(' ') >= 0) { return this.margin.apply(this, top.split(' ')); } @@ -832,10 +832,10 @@ export class Builder implements IDisposable { /** * Sets the CSS property position. */ - public position(position: string): Builder; - public position(top: number, right?: number, bottom?: number, left?: number, position?: string): Builder; - public position(top: string, right?: string, bottom?: string, left?: string, position?: string): Builder; - public position(top: any, right?: any, bottom?: any, left?: any, position?: string): Builder { + position(position: string): Builder; + position(top: number, right?: number, bottom?: number, left?: number, position?: string): Builder; + position(top: string, right?: string, bottom?: string, left?: string, position?: string): Builder; + position(top: any, right?: any, bottom?: any, left?: any, position?: string): Builder { if (types.isString(top) && top.indexOf(' ') >= 0) { return this.position.apply(this, top.split(' ')); } @@ -868,10 +868,10 @@ export class Builder implements IDisposable { /** * Sets the CSS property size. */ - public size(size: string): Builder; - public size(width: number, height?: number): Builder; - public size(width: string, height?: string): Builder; - public size(width: any, height?: any): Builder { + size(size: string): Builder; + size(width: number, height?: number): Builder; + size(width: string, height?: string): Builder; + size(width: any, height?: any): Builder { if (types.isString(width) && width.indexOf(' ') >= 0) { return this.size.apply(this, width.split(' ')); } @@ -890,7 +890,7 @@ export class Builder implements IDisposable { /** * Sets the CSS property display. */ - public display(display: string): Builder { + display(display: string): Builder { this.currentElement.style.display = display; return this; @@ -899,7 +899,7 @@ export class Builder implements IDisposable { /** * Shows the current element of the builder. */ - public show(): Builder { + show(): Builder { if (this.hasClass('monaco-builder-hidden')) { this.removeClass('monaco-builder-hidden'); } @@ -919,7 +919,7 @@ export class Builder implements IDisposable { * only show the element when a specific delay is reached (e.g. for a long running * operation. */ - public showDelayed(delay: number): Builder { + showDelayed(delay: number): Builder { // Cancel any pending showDelayed() invocation this.cancelVisibilityPromise(); @@ -938,7 +938,7 @@ export class Builder implements IDisposable { /** * Hides the current element of the builder. */ - public hide(): Builder { + hide(): Builder { if (!this.hasClass('monaco-builder-hidden')) { this.addClass('monaco-builder-hidden'); } @@ -953,7 +953,7 @@ export class Builder implements IDisposable { /** * Returns true if the current element of the builder is hidden. */ - public isHidden(): boolean { + isHidden(): boolean { return this.hasClass('monaco-builder-hidden') || this.currentElement.style.display === 'none'; } @@ -976,7 +976,7 @@ export class Builder implements IDisposable { /** * Sets the innerHTML attribute. */ - public innerHtml(html: string, append?: boolean): Builder { + innerHtml(html: string, append?: boolean): Builder { if (append) { this.currentElement.innerHTML += html; } else { @@ -990,7 +990,7 @@ export class Builder implements IDisposable { * Sets the textContent property of the element. * All HTML special characters will be escaped. */ - public text(text: string, append?: boolean): Builder { + text(text: string, append?: boolean): Builder { if (append) { // children is child Elements versus childNodes includes textNodes if (this.currentElement.children.length === 0) { @@ -1011,14 +1011,14 @@ export class Builder implements IDisposable { /** * Sets the innerHTML attribute in escaped form. */ - public safeInnerHtml(html: string, append?: boolean): Builder { + safeInnerHtml(html: string, append?: boolean): Builder { return this.innerHtml(strings.escape(html), append); } /** * Allows to store arbritary data into the current element. */ - public setProperty(key: string, value: any): Builder { + setProperty(key: string, value: any): Builder { setPropertyOnElement(this.currentElement, key, value); return this; @@ -1027,14 +1027,14 @@ export class Builder implements IDisposable { /** * Allows to get arbritary data from the current element. */ - public getProperty(key: string, fallback?: any): any { + getProperty(key: string, fallback?: any): any { return getPropertyFromElement(this.currentElement, key, fallback); } /** * Removes a property from the current element that is stored under the given key. */ - public removeProperty(key: string): Builder { + removeProperty(key: string): Builder { if (hasData(this.currentElement)) { delete data(this.currentElement)[key]; } @@ -1045,7 +1045,7 @@ export class Builder implements IDisposable { /** * Returns a new builder with the child at the given index. */ - public child(index = 0): Builder { + child(index = 0): Builder { let children = this.currentElement.children; return withElement(children.item(index)); @@ -1085,7 +1085,7 @@ export class Builder implements IDisposable { * event listners registered and also clear any data binding and properties stored * to any child element. */ - public empty(): Builder { + empty(): Builder { this.unbindDescendants(this.currentElement); this.clearChildren(); @@ -1100,7 +1100,7 @@ export class Builder implements IDisposable { /** * Removes all HTML elements from the current element of the builder. */ - public clearChildren(): Builder { + clearChildren(): Builder { // Remove Elements if (this.currentElement) { @@ -1114,7 +1114,7 @@ export class Builder implements IDisposable { * Removes the current HTML element and all its children from its parent and unbinds * all listeners and properties set to the data slots. */ - public destroy(): void { + destroy(): void { if (this.currentElement) { @@ -1144,15 +1144,15 @@ export class Builder implements IDisposable { let type: string; - for (type in this.toUnbind) { - if (this.toUnbind.hasOwnProperty(type) && types.isArray(this.toUnbind[type])) { - this.toUnbind[type] = dispose(this.toUnbind[type]); + for (type in this.toDispose) { + if (this.toDispose.hasOwnProperty(type) && types.isArray(this.toDispose[type])) { + this.toDispose[type] = dispose(this.toDispose[type]); } } - for (type in this.captureToUnbind) { - if (this.captureToUnbind.hasOwnProperty(type) && types.isArray(this.captureToUnbind[type])) { - this.captureToUnbind[type] = dispose(this.captureToUnbind[type]); + for (type in this.captureToDispose) { + if (this.captureToDispose.hasOwnProperty(type) && types.isArray(this.captureToDispose[type])) { + this.captureToDispose[type] = dispose(this.captureToDispose[type]); } } @@ -1161,22 +1161,22 @@ export class Builder implements IDisposable { this.container = null; this.offdom = null; this.createdElements = null; - this.captureToUnbind = null; - this.toUnbind = null; + this.captureToDispose = null; + this.toDispose = null; } /** * Removes the current HTML element and all its children from its parent and unbinds * all listeners and properties set to the data slots. */ - public dispose(): void { + dispose(): void { this.destroy(); } /** * Gets the size (in pixels) of an element, including the margin. */ - public getTotalSize(): DOM.Dimension { + getTotalSize(): DOM.Dimension { let totalWidth = DOM.getTotalWidth(this.currentElement); let totalHeight = DOM.getTotalHeight(this.currentElement); @@ -1186,7 +1186,7 @@ export class Builder implements IDisposable { /** * Another variant of getting the inner dimensions of an element. */ - public getClientArea(): DOM.Dimension { + getClientArea(): DOM.Dimension { return DOM.getClientArea(this.currentElement); } } @@ -1197,7 +1197,7 @@ export class Builder implements IDisposable { */ export class MultiBuilder extends Builder { - public length: number; + length: number; private builders: Builder[]; @@ -1278,11 +1278,11 @@ export class MultiBuilder extends Builder { } } - public item(i: number): Builder { + item(i: number): Builder { return this.builders[i]; } - public push(...items: Builder[]): void { + push(...items: Builder[]): void { for (let i = 0; i < items.length; i++) { this.builders.push(items[i]); } @@ -1290,7 +1290,7 @@ export class MultiBuilder extends Builder { this.length = this.builders.length; } - public clone(): MultiBuilder { + clone(): MultiBuilder { return new MultiBuilder(this); } } diff --git a/src/vs/base/browser/dnd.ts b/src/vs/base/browser/dnd.ts index a4bc02edd33..cc5e1202acd 100644 --- a/src/vs/base/browser/dnd.ts +++ b/src/vs/base/browser/dnd.ts @@ -5,19 +5,20 @@ 'use strict'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; import { addDisposableListener } from 'vs/base/browser/dom'; /** * A helper that will execute a provided function when the provided HTMLElement receives * dragover event for 800ms. If the drag is aborted before, the callback will not be triggered. */ -export class DelayedDragHandler { - private toDispose: IDisposable[] = []; +export class DelayedDragHandler extends Disposable { private timeout: number; constructor(container: HTMLElement, callback: () => void) { - this.toDispose.push(addDisposableListener(container, 'dragover', () => { + super(); + + this._register(addDisposableListener(container, 'dragover', () => { if (!this.timeout) { this.timeout = setTimeout(() => { callback(); @@ -28,7 +29,7 @@ export class DelayedDragHandler { })); ['dragleave', 'drop', 'dragend'].forEach(type => { - this.toDispose.push(addDisposableListener(container, type, () => { + this._register(addDisposableListener(container, type, () => { this.clearDragTimeout(); })); }); @@ -41,8 +42,9 @@ export class DelayedDragHandler { } } - public dispose(): void { - this.toDispose = dispose(this.toDispose); + dispose(): void { + super.dispose(); + this.clearDragTimeout(); } } diff --git a/src/vs/base/browser/ui/button/button.ts b/src/vs/base/browser/ui/button/button.ts index 129009f5088..dec147c543d 100644 --- a/src/vs/base/browser/ui/button/button.ts +++ b/src/vs/base/browser/ui/button/button.ts @@ -13,7 +13,7 @@ import { KeyCode } from 'vs/base/common/keyCodes'; import { Color } from 'vs/base/common/color'; import { mixin } from 'vs/base/common/objects'; import { Event as BaseEvent, Emitter } from 'vs/base/common/event'; -import { dispose, IDisposable } from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; import { Gesture, EventType } from 'vs/base/browser/touch'; export interface IButtonOptions extends IButtonStyles { @@ -33,7 +33,7 @@ const defaultOptions: IButtonStyles = { buttonForeground: Color.white }; -export class Button { +export class Button extends Disposable { private $el: Builder; private options: IButtonOptions; @@ -43,12 +43,14 @@ export class Button { private buttonForeground: Color; private buttonBorder: Color; - private _onDidClick = new Emitter(); - readonly onDidClick: BaseEvent = this._onDidClick.event; + private _onDidClick = this._register(new Emitter()); + get onDidClick(): BaseEvent { return this._onDidClick.event; } private focusTracker: DOM.IFocusTracker; constructor(container: HTMLElement, options?: IButtonOptions) { + super(); + this.options = options || Object.create(null); mixin(this.options, defaultOptions, false); @@ -57,10 +59,10 @@ export class Button { this.buttonForeground = this.options.buttonForeground; this.buttonBorder = this.options.buttonBorder; - this.$el = $('a.monaco-button').attr({ + this.$el = this._register($('a.monaco-button').attr({ 'tabIndex': '0', 'role': 'button' - }).appendTo(container); + }).appendTo(container)); Gesture.addTarget(this.$el.getHTMLElement()); @@ -74,7 +76,7 @@ export class Button { }); this.$el.on(DOM.EventType.KEY_DOWN, e => { - let event = new StandardKeyboardEvent(e as KeyboardEvent); + const event = new StandardKeyboardEvent(e as KeyboardEvent); let eventHandled = false; if (this.enabled && event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) { this._onDidClick.fire(e); @@ -100,9 +102,9 @@ export class Button { }); // Also set hover background when button is focused for feedback - this.focusTracker = DOM.trackFocus(this.$el.getHTMLElement()); - this.focusTracker.onDidFocus(() => this.setHoverBackground()); - this.focusTracker.onDidBlur(() => this.applyStyles()); // restore standard styles + this.focusTracker = this._register(DOM.trackFocus(this.$el.getHTMLElement())); + this._register(this.focusTracker.onDidFocus(() => this.setHoverBackground())); + this._register(this.focusTracker.onDidBlur(() => this.applyStyles())); // restore standard styles this.applyStyles(); } @@ -177,27 +179,13 @@ export class Button { focus(): void { this.$el.domFocus(); } - - dispose(): void { - if (this.$el) { - this.$el.dispose(); - this.$el = null; - - this.focusTracker.dispose(); - this.focusTracker = null; - } - - this._onDidClick.dispose(); - } } -export class ButtonGroup { - private _buttons: Button[]; - private toDispose: IDisposable[]; +export class ButtonGroup extends Disposable { + private _buttons: Button[] = []; constructor(container: HTMLElement, count: number, options?: IButtonOptions) { - this._buttons = []; - this.toDispose = []; + super(); this.create(container, count, options); } @@ -208,9 +196,8 @@ export class ButtonGroup { private create(container: HTMLElement, count: number, options?: IButtonOptions): void { for (let index = 0; index < count; index++) { - const button = new Button(container, options); + const button = this._register(new Button(container, options)); this._buttons.push(button); - this.toDispose.push(button); // Implement keyboard access in buttons if there are multiple if (count > 1) { @@ -236,8 +223,4 @@ export class ButtonGroup { } } } - - dispose(): void { - this.toDispose = dispose(this.toDispose); - } } \ No newline at end of file diff --git a/src/vs/base/browser/ui/checkbox/checkbox.ts b/src/vs/base/browser/ui/checkbox/checkbox.ts index c1486f8f32b..1b1c5df8521 100644 --- a/src/vs/base/browser/ui/checkbox/checkbox.ts +++ b/src/vs/base/browser/ui/checkbox/checkbox.ts @@ -5,6 +5,7 @@ 'use strict'; +import 'vs/css!./checkbox'; import * as DOM from 'vs/base/browser/dom'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Widget } from 'vs/base/browser/ui/widget'; @@ -12,7 +13,6 @@ import { Color } from 'vs/base/common/color'; import { Emitter, Event } from 'vs/base/common/event'; import { KeyCode } from 'vs/base/common/keyCodes'; import * as objects from 'vs/base/common/objects'; -import 'vs/css!./checkbox'; export interface ICheckboxOpts extends ICheckboxStyles { readonly actionClassName: string; @@ -31,18 +31,19 @@ const defaultOpts = { export class Checkbox extends Widget { private readonly _onChange = this._register(new Emitter()); - public readonly onChange: Event = this._onChange.event; + get onChange(): Event { return this._onChange.event; } private readonly _onKeyDown = this._register(new Emitter()); - public readonly onKeyDown: Event = this._onKeyDown.event; + get onKeyDown(): Event { return this._onKeyDown.event; } private readonly _opts: ICheckboxOpts; - public readonly domNode: HTMLElement; + readonly domNode: HTMLElement; private _checked: boolean; constructor(opts: ICheckboxOpts) { super(); + this._opts = objects.deepClone(opts); objects.mixin(this._opts, defaultOpts, false); this._checked = this._opts.isChecked; @@ -75,19 +76,19 @@ export class Checkbox extends Widget { }); } - public get enabled(): boolean { + get enabled(): boolean { return this.domNode.getAttribute('aria-disabled') !== 'true'; } - public focus(): void { + focus(): void { this.domNode.focus(); } - public get checked(): boolean { + get checked(): boolean { return this._checked; } - public set checked(newIsChecked: boolean) { + set checked(newIsChecked: boolean) { this._checked = newIsChecked; this.domNode.setAttribute('aria-checked', String(this._checked)); if (this._checked) { @@ -99,11 +100,11 @@ export class Checkbox extends Widget { this.applyStyles(); } - public width(): number { + width(): number { return 2 /*marginleft*/ + 2 /*border*/ + 2 /*padding*/ + 16 /* icon width */; } - public style(styles: ICheckboxStyles): void { + style(styles: ICheckboxStyles): void { if (styles.inputActiveOptionBorder) { this._opts.inputActiveOptionBorder = styles.inputActiveOptionBorder; } @@ -116,12 +117,12 @@ export class Checkbox extends Widget { } } - public enable(): void { + enable(): void { this.domNode.tabIndex = 0; this.domNode.setAttribute('aria-disabled', String(false)); } - public disable(): void { + disable(): void { DOM.removeTabIndexAndUpdateFocus(this.domNode); this.domNode.setAttribute('aria-disabled', String(true)); } diff --git a/src/vs/base/browser/ui/dropdown/dropdown.ts b/src/vs/base/browser/ui/dropdown/dropdown.ts index 969453f6942..f2b9a1f842e 100644 --- a/src/vs/base/browser/ui/dropdown/dropdown.ts +++ b/src/vs/base/browser/ui/dropdown/dropdown.ts @@ -28,7 +28,8 @@ export interface IBaseDropdownOptions { } export class BaseDropdown extends ActionRunner { - private _toDispose: IDisposable[]; + private _toDispose: IDisposable[] = []; + private $el: Builder; private $boxContainer: Builder; private $label: Builder; @@ -38,8 +39,6 @@ export class BaseDropdown extends ActionRunner { constructor(container: HTMLElement, options: IBaseDropdownOptions) { super(); - this._toDispose = []; - this.$el = $('.monaco-dropdown').appendTo(container); this.$label = $('.dropdown-label'); @@ -66,8 +65,7 @@ export class BaseDropdown extends ActionRunner { } }).appendTo(this.$el); - let cleanupFn = labelRenderer(this.$label.getHTMLElement()); - + const cleanupFn = labelRenderer(this.$label.getHTMLElement()); if (cleanupFn) { this._toDispose.push(cleanupFn); } @@ -75,27 +73,27 @@ export class BaseDropdown extends ActionRunner { Gesture.addTarget(this.$label.getHTMLElement()); } - public get toDispose(): IDisposable[] { + get toDispose(): IDisposable[] { return this._toDispose; } - public get element(): HTMLElement { + get element(): HTMLElement { return this.$el.getHTMLElement(); } - public get label(): HTMLElement { + get label(): HTMLElement { return this.$label.getHTMLElement(); } - public set tooltip(tooltip: string) { + set tooltip(tooltip: string) { this.$label.title(tooltip); } - public show(): void { + show(): void { this.visible = true; } - public hide(): void { + hide(): void { this.visible = false; } @@ -103,7 +101,7 @@ export class BaseDropdown extends ActionRunner { this.hide(); } - public dispose(): void { + dispose(): void { super.dispose(); this.hide(); @@ -139,7 +137,7 @@ export class Dropdown extends BaseDropdown { this.contextViewProvider = options.contextViewProvider; } - public show(): void { + show(): void { super.show(); addClass(this.element, 'active'); @@ -167,7 +165,7 @@ export class Dropdown extends BaseDropdown { removeClass(this.element, 'active'); } - public hide(): void { + hide(): void { super.hide(); if (this.contextViewProvider) { @@ -211,11 +209,11 @@ export class DropdownMenu extends BaseDropdown { this.menuClassName = options.menuClassName || ''; } - public set menuOptions(options: IMenuOptions) { + set menuOptions(options: IMenuOptions) { this._menuOptions = options; } - public get menuOptions(): IMenuOptions { + get menuOptions(): IMenuOptions { return this._menuOptions; } @@ -231,7 +229,7 @@ export class DropdownMenu extends BaseDropdown { this._actions = actions; } - public show(): void { + show(): void { super.show(); addClass(this.element, 'active'); @@ -248,7 +246,7 @@ export class DropdownMenu extends BaseDropdown { }); } - public hide(): void { + hide(): void { super.hide(); } @@ -279,8 +277,8 @@ export class DropdownMenuActionItem extends BaseActionItem { this.clazz = clazz; } - public render(container: HTMLElement): void { - let labelRenderer: ILabelRenderer = (el: HTMLElement): IDisposable => { + render(container: HTMLElement): void { + const labelRenderer: ILabelRenderer = (el: HTMLElement): IDisposable => { this.builder = $('a.action-label').attr({ tabIndex: '0', role: 'button', @@ -294,7 +292,7 @@ export class DropdownMenuActionItem extends BaseActionItem { return null; }; - let options: IDropdownMenuOptions = { + const options: IDropdownMenuOptions = { contextMenuProvider: this.contextMenuProvider, labelRenderer: labelRenderer }; @@ -316,7 +314,7 @@ export class DropdownMenuActionItem extends BaseActionItem { }; } - public setActionContext(newContext: any): void { + setActionContext(newContext: any): void { super.setActionContext(newContext); if (this.dropdownMenu) { @@ -324,13 +322,13 @@ export class DropdownMenuActionItem extends BaseActionItem { } } - public show(): void { + show(): void { if (this.dropdownMenu) { this.dropdownMenu.show(); } } - public dispose(): void { + dispose(): void { this.dropdownMenu.dispose(); super.dispose(); diff --git a/src/vs/base/browser/ui/iconLabel/iconLabel.ts b/src/vs/base/browser/ui/iconLabel/iconLabel.ts index f2f641431bb..8d62877e57d 100644 --- a/src/vs/base/browser/ui/iconLabel/iconLabel.ts +++ b/src/vs/base/browser/ui/iconLabel/iconLabel.ts @@ -12,7 +12,7 @@ import { IMatch } from 'vs/base/common/filters'; import uri from 'vs/base/common/uri'; import * as paths from 'vs/base/common/paths'; import { IWorkspaceFolderProvider, getPathLabel, IUserHomeProvider, getBaseLabel } from 'vs/base/common/labels'; -import { IDisposable, combinedDisposable } from 'vs/base/common/lifecycle'; +import { IDisposable, combinedDisposable, Disposable } from 'vs/base/common/lifecycle'; export interface IIconLabelCreationOptions { supportHighlights?: boolean; @@ -38,11 +38,11 @@ class FastLabelNode { constructor(private _element: HTMLElement) { } - public get element(): HTMLElement { + get element(): HTMLElement { return this._element; } - public set textContent(content: string) { + set textContent(content: string) { if (this.disposed || content === this._textContent) { return; } @@ -51,7 +51,7 @@ class FastLabelNode { this._element.textContent = content; } - public set className(className: string) { + set className(className: string) { if (this.disposed || className === this._className) { return; } @@ -60,7 +60,7 @@ class FastLabelNode { this._element.className = className; } - public set title(title: string) { + set title(title: string) { if (this.disposed || title === this._title) { return; } @@ -73,7 +73,7 @@ class FastLabelNode { } } - public set empty(empty: boolean) { + set empty(empty: boolean) { if (this.disposed || empty === this._empty) { return; } @@ -82,12 +82,12 @@ class FastLabelNode { this._element.style.marginLeft = empty ? '0' : null; } - public dispose(): void { + dispose(): void { this.disposed = true; } } -export class IconLabel { +export class IconLabel extends Disposable { private domNode: FastLabelNode; private labelDescriptionContainer: FastLabelNode; private labelNode: FastLabelNode | HighlightedLabel; @@ -95,34 +95,36 @@ export class IconLabel { private descriptionNodeFactory: () => FastLabelNode | HighlightedLabel; constructor(container: HTMLElement, options?: IIconLabelCreationOptions) { - this.domNode = new FastLabelNode(dom.append(container, dom.$('.monaco-icon-label'))); + super(); - this.labelDescriptionContainer = new FastLabelNode(dom.append(this.domNode.element, dom.$('.monaco-icon-label-description-container'))); + this.domNode = this._register(new FastLabelNode(dom.append(container, dom.$('.monaco-icon-label')))); + + this.labelDescriptionContainer = this._register(new FastLabelNode(dom.append(this.domNode.element, dom.$('.monaco-icon-label-description-container')))); if (options && options.supportHighlights) { - this.labelNode = new HighlightedLabel(dom.append(this.labelDescriptionContainer.element, dom.$('a.label-name'))); + this.labelNode = this._register(new HighlightedLabel(dom.append(this.labelDescriptionContainer.element, dom.$('a.label-name')))); } else { - this.labelNode = new FastLabelNode(dom.append(this.labelDescriptionContainer.element, dom.$('a.label-name'))); + this.labelNode = this._register(new FastLabelNode(dom.append(this.labelDescriptionContainer.element, dom.$('a.label-name')))); } if (options && options.supportDescriptionHighlights) { - this.descriptionNodeFactory = () => new HighlightedLabel(dom.append(this.labelDescriptionContainer.element, dom.$('span.label-description'))); + this.descriptionNodeFactory = () => this._register(new HighlightedLabel(dom.append(this.labelDescriptionContainer.element, dom.$('span.label-description')))); } else { - this.descriptionNodeFactory = () => new FastLabelNode(dom.append(this.labelDescriptionContainer.element, dom.$('span.label-description'))); + this.descriptionNodeFactory = () => this._register(new FastLabelNode(dom.append(this.labelDescriptionContainer.element, dom.$('span.label-description')))); } } - public get element(): HTMLElement { + get element(): HTMLElement { return this.domNode.element; } - public onClick(callback: (event: MouseEvent) => void): IDisposable { + onClick(callback: (event: MouseEvent) => void): IDisposable { return combinedDisposable([ dom.addDisposableListener(this.labelDescriptionContainer.element, dom.EventType.CLICK, (e: MouseEvent) => callback(e)), ]); } - public setValue(label?: string, description?: string, options?: IIconLabelValueOptions): void { + setValue(label?: string, description?: string, options?: IIconLabelValueOptions): void { const classes = ['monaco-icon-label']; if (options) { if (options.extraClasses) { @@ -162,15 +164,6 @@ export class IconLabel { } } } - - public dispose(): void { - this.domNode.dispose(); - this.labelNode.dispose(); - - if (this.descriptionNode) { - this.descriptionNode.dispose(); - } - } } export class FileLabel extends IconLabel { @@ -181,7 +174,7 @@ export class FileLabel extends IconLabel { this.setFile(file, provider, userHome); } - public setFile(file: uri, provider: IWorkspaceFolderProvider, userHome: IUserHomeProvider): void { + setFile(file: uri, provider: IWorkspaceFolderProvider, userHome: IUserHomeProvider): void { const parent = paths.dirname(file.fsPath); this.setValue(getBaseLabel(file), parent && parent !== '.' ? getPathLabel(parent, userHome, provider) : '', { title: file.fsPath }); diff --git a/src/vs/base/browser/ui/progressbar/progressbar.ts b/src/vs/base/browser/ui/progressbar/progressbar.ts index f1969feebac..7d294d601f5 100644 --- a/src/vs/base/browser/ui/progressbar/progressbar.ts +++ b/src/vs/base/browser/ui/progressbar/progressbar.ts @@ -10,7 +10,7 @@ import { TPromise, ValueCallback } from 'vs/base/common/winjs.base'; import * as assert from 'vs/base/common/assert'; import { Builder, $ } from 'vs/base/browser/builder'; import * as DOM from 'vs/base/browser/dom'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; import { Color } from 'vs/base/common/color'; import { mixin } from 'vs/base/common/objects'; @@ -35,9 +35,8 @@ const defaultOpts = { /** * A progress bar with support for infinite or discrete progress. */ -export class ProgressBar { +export class ProgressBar extends Disposable { private options: IProgressBarOptions; - private toUnbind: IDisposable[]; private workedVal: number; private element: Builder; private bit: HTMLElement; @@ -46,10 +45,11 @@ export class ProgressBar { private progressBarBackground: Color; constructor(container: HTMLElement, options?: IProgressBarOptions) { + super(); + this.options = options || Object.create(null); mixin(this.options, defaultOpts, false); - this.toUnbind = []; this.workedVal = 0; this.progressBarBackground = this.options.progressBarBackground; @@ -70,7 +70,7 @@ export class ProgressBar { break; } - }, this.toUnbind); + }, this.toDispose); this.bit = builder.getHTMLElement(); }); @@ -92,14 +92,14 @@ export class ProgressBar { /** * Indicates to the progress bar that all work is done. */ - public done(): ProgressBar { + done(): ProgressBar { return this.doDone(true); } /** * Stops the progressbar from showing any progress instantly without fading out. */ - public stop(): ProgressBar { + stop(): ProgressBar { return this.doDone(false); } @@ -133,7 +133,7 @@ export class ProgressBar { /** * Use this mode to indicate progress that has no total number of work units. */ - public infinite(): ProgressBar { + infinite(): ProgressBar { this.bit.style.width = '2%'; this.bit.style.opacity = '1'; @@ -149,7 +149,7 @@ export class ProgressBar { * Tells the progress bar the total number of work. Use in combination with workedVal() to let * the progress bar show the actual progress based on the work that is done. */ - public total(value: number): ProgressBar { + total(value: number): ProgressBar { this.workedVal = 0; this.totalWork = value; @@ -159,14 +159,14 @@ export class ProgressBar { /** * Finds out if this progress bar is configured with total work */ - public hasTotal(): boolean { + hasTotal(): boolean { return !isNaN(this.totalWork); } /** * Tells the progress bar that an increment of work has been completed. */ - public worked(value: number): ProgressBar { + worked(value: number): ProgressBar { value = Number(value); assert.ok(!isNaN(value), 'Value is not a number'); value = Math.max(1, value); @@ -177,7 +177,7 @@ export class ProgressBar { /** * Tells the progress bar the total amount of work that has been completed. */ - public setWorked(value: number): ProgressBar { + setWorked(value: number): ProgressBar { value = Number(value); assert.ok(!isNaN(value), 'Value is not a number'); value = Math.max(1, value); @@ -212,11 +212,11 @@ export class ProgressBar { return this; } - public getContainer(): HTMLElement { + getContainer(): HTMLElement { return this.element.getHTMLElement(); } - public show(delay?: number): void { + show(delay?: number): void { if (typeof delay === 'number') { this.element.showDelayed(delay); } else { @@ -224,11 +224,11 @@ export class ProgressBar { } } - public hide(): void { + hide(): void { this.element.hide(); } - public style(styles: IProgressBarStyles): void { + style(styles: IProgressBarStyles): void { this.progressBarBackground = styles.progressBarBackground; this.applyStyles(); @@ -241,8 +241,4 @@ export class ProgressBar { this.bit.style.backgroundColor = background; } } - - public dispose(): void { - this.toUnbind = dispose(this.toUnbind); - } } \ No newline at end of file diff --git a/src/vs/base/browser/ui/selectBox/selectBox.ts b/src/vs/base/browser/ui/selectBox/selectBox.ts index 28828be39de..af1752d992e 100644 --- a/src/vs/base/browser/ui/selectBox/selectBox.ts +++ b/src/vs/base/browser/ui/selectBox/selectBox.ts @@ -5,7 +5,6 @@ import 'vs/css!./selectBox'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { Event } from 'vs/base/common/event'; import { Widget } from 'vs/base/browser/ui/widget'; import { Color } from 'vs/base/common/color'; @@ -58,15 +57,12 @@ export interface ISelectData { } export class SelectBox extends Widget implements ISelectBoxDelegate { - private toDispose: IDisposable[]; private styles: ISelectBoxStyles; private selectBoxDelegate: ISelectBoxDelegate; constructor(options: string[], selected: number, contextViewProvider: IContextViewProvider, styles: ISelectBoxStyles = deepClone(defaultStyles), selectBoxOptions?: ISelectBoxOptions) { super(); - this.toDispose = []; - mixin(this.styles, defaultStyles, false); // Instantiate select implementation based on platform @@ -76,7 +72,7 @@ export class SelectBox extends Widget implements ISelectBoxDelegate { this.selectBoxDelegate = new SelectBoxList(options, selected, contextViewProvider, styles, selectBoxOptions); } - this.toDispose.push(this.selectBoxDelegate); + this._register(this.selectBoxDelegate); } // Public SelectBox Methods - routed through delegate interface @@ -114,9 +110,4 @@ export class SelectBox extends Widget implements ISelectBoxDelegate { public applyStyles(): void { this.selectBoxDelegate.applyStyles(); } - - public dispose(): void { - this.toDispose = dispose(this.toDispose); - super.dispose(); - } } \ No newline at end of file diff --git a/src/vs/base/browser/ui/toolbar/toolbar.ts b/src/vs/base/browser/ui/toolbar/toolbar.ts index cecc9f9831e..50e06012bba 100644 --- a/src/vs/base/browser/ui/toolbar/toolbar.ts +++ b/src/vs/base/browser/ui/toolbar/toolbar.ts @@ -12,6 +12,7 @@ import { Action, IActionRunner, IAction } from 'vs/base/common/actions'; import { ActionBar, ActionsOrientation, IActionItemProvider } from 'vs/base/browser/ui/actionbar/actionbar'; import { IContextMenuProvider, DropdownMenuActionItem } from 'vs/base/browser/ui/dropdown/dropdown'; import { ResolvedKeybinding } from 'vs/base/common/keyCodes'; +import { Disposable } from 'vs/base/common/lifecycle'; export const CONTEXT = 'context.toolbar'; @@ -26,7 +27,7 @@ export interface IToolBarOptions { /** * A widget that combines an action bar for primary actions and a dropdown for secondary actions. */ -export class ToolBar { +export class ToolBar extends Disposable { private options: IToolBarOptions; private actionBar: ActionBar; private toggleMenuAction: ToggleMenuAction; @@ -35,16 +36,18 @@ export class ToolBar { private lookupKeybindings: boolean; constructor(container: HTMLElement, contextMenuProvider: IContextMenuProvider, options: IToolBarOptions = { orientation: ActionsOrientation.HORIZONTAL }) { + super(); + this.options = options; this.lookupKeybindings = typeof this.options.getKeyBinding === 'function'; - this.toggleMenuAction = new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show()); + this.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show())); let element = document.createElement('div'); element.className = 'monaco-toolbar'; container.appendChild(element); - this.actionBar = new ActionBar(element, { + this.actionBar = this._register(new ActionBar(element, { orientation: options.orientation, ariaLabel: options.ariaLabel, actionRunner: options.actionRunner, @@ -75,29 +78,29 @@ export class ToolBar { return options.actionItemProvider ? options.actionItemProvider(action) : null; } - }); + })); } - public set actionRunner(actionRunner: IActionRunner) { + set actionRunner(actionRunner: IActionRunner) { this.actionBar.actionRunner = actionRunner; } - public get actionRunner(): IActionRunner { + get actionRunner(): IActionRunner { return this.actionBar.actionRunner; } - public set context(context: any) { + set context(context: any) { this.actionBar.context = context; if (this.toggleMenuActionItem) { this.toggleMenuActionItem.setActionContext(context); } } - public getContainer(): HTMLElement { + getContainer(): HTMLElement { return this.actionBar.getContainer(); } - public getItemsWidth(): number { + getItemsWidth(): number { let itemsWidth = 0; for (let i = 0; i < this.actionBar.length(); i++) { itemsWidth += this.actionBar.getWidth(i); @@ -105,11 +108,11 @@ export class ToolBar { return itemsWidth; } - public setAriaLabel(label: string): void { + setAriaLabel(label: string): void { this.actionBar.setAriaLabel(label); } - public setActions(primaryActions: IAction[], secondaryActions?: IAction[]): () => void { + setActions(primaryActions: IAction[], secondaryActions?: IAction[]): () => void { return () => { let primaryActionsToSet = primaryActions ? primaryActions.slice(0) : []; @@ -134,7 +137,7 @@ export class ToolBar { return key ? key.getLabel() : void 0; } - public addPrimaryAction(primaryAction: IAction): () => void { + addPrimaryAction(primaryAction: IAction): () => void { return () => { // Add after the "..." action if we have secondary actions @@ -150,19 +153,19 @@ export class ToolBar { }; } - public dispose(): void { - this.actionBar.dispose(); - this.toggleMenuAction.dispose(); - + dispose(): void { if (this.toggleMenuActionItem) { this.toggleMenuActionItem.dispose(); + this.toggleMenuActionItem = void 0; } + + super.dispose(); } } class ToggleMenuAction extends Action { - public static readonly ID = 'toolbar.toggle.more'; + static readonly ID = 'toolbar.toggle.more'; private _menuActions: IAction[]; private toggleDropdownMenu: () => void; @@ -173,17 +176,17 @@ class ToggleMenuAction extends Action { this.toggleDropdownMenu = toggleDropdownMenu; } - public run(): TPromise { + run(): TPromise { this.toggleDropdownMenu(); return TPromise.as(true); } - public get menuActions() { + get menuActions() { return this._menuActions; } - public set menuActions(actions: IAction[]) { + set menuActions(actions: IAction[]) { this._menuActions = actions; } } \ No newline at end of file diff --git a/src/vs/base/common/lifecycle.ts b/src/vs/base/common/lifecycle.ts index f16ede05fb0..befc15c2676 100644 --- a/src/vs/base/common/lifecycle.ts +++ b/src/vs/base/common/lifecycle.ts @@ -57,11 +57,8 @@ export function toDisposable(...fns: (() => void)[]): IDisposable { export abstract class Disposable implements IDisposable { - protected _toDispose: IDisposable[]; - - constructor() { - this._toDispose = []; - } + protected _toDispose: IDisposable[] = []; + protected get toDispose(): IDisposable[] { return this._toDispose; } public dispose(): void { this._toDispose = dispose(this._toDispose); @@ -69,6 +66,7 @@ export abstract class Disposable implements IDisposable { protected _register(t: T): T { this._toDispose.push(t); + return t; } } diff --git a/src/vs/base/parts/quickopen/browser/quickOpenModel.ts b/src/vs/base/parts/quickopen/browser/quickOpenModel.ts index db04c0b00dd..74828296605 100644 --- a/src/vs/base/parts/quickopen/browser/quickOpenModel.ts +++ b/src/vs/base/parts/quickopen/browser/quickOpenModel.ts @@ -37,15 +37,15 @@ let IDS = 0; export class QuickOpenItemAccessorClass implements IItemAccessor { - public getItemLabel(entry: QuickOpenEntry): string { + getItemLabel(entry: QuickOpenEntry): string { return entry.getLabel(); } - public getItemDescription(entry: QuickOpenEntry): string { + getItemDescription(entry: QuickOpenEntry): string { return entry.getDescription(); } - public getItemPath(entry: QuickOpenEntry): string { + getItemPath(entry: QuickOpenEntry): string { const resource = entry.getResource(); return resource ? resource.fsPath : void 0; @@ -70,70 +70,70 @@ export class QuickOpenEntry { /** * A unique identifier for the entry */ - public getId(): string { + getId(): string { return this.id; } /** * The label of the entry to identify it from others in the list */ - public getLabel(): string { + getLabel(): string { return null; } /** * The options for the label to use for this entry */ - public getLabelOptions(): IIconLabelValueOptions { + getLabelOptions(): IIconLabelValueOptions { return null; } /** * The label of the entry to use when a screen reader wants to read about the entry */ - public getAriaLabel(): string { + getAriaLabel(): string { return this.getLabel(); } /** * Detail information about the entry that is optional and can be shown below the label */ - public getDetail(): string { + getDetail(): string { return null; } /** * The icon of the entry to identify it from others in the list */ - public getIcon(): string { + getIcon(): string { return null; } /** * A secondary description that is optional and can be shown right to the label */ - public getDescription(): string { + getDescription(): string { return null; } /** * A tooltip to show when hovering over the entry. */ - public getTooltip(): string { + getTooltip(): string { return null; } /** * A tooltip to show when hovering over the description portion of the entry. */ - public getDescriptionTooltip(): string { + getDescriptionTooltip(): string { return null; } /** * An optional keybinding to show for an entry. */ - public getKeybinding(): ResolvedKeybinding { + getKeybinding(): ResolvedKeybinding { return null; } @@ -141,28 +141,28 @@ export class QuickOpenEntry { * A resource for this entry. Resource URIs can be used to compare different kinds of entries and group * them together. */ - public getResource(): URI { + getResource(): URI { return null; } /** * Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer. */ - public isHidden(): boolean { + isHidden(): boolean { return this.hidden; } /** * Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer. */ - public setHidden(hidden: boolean): void { + setHidden(hidden: boolean): void { this.hidden = hidden; } /** * Allows to set highlight ranges that should show up for the entry label and optionally description if set. */ - public setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[], detailHighlights?: IHighlight[]): void { + setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[], detailHighlights?: IHighlight[]): void { this.labelHighlights = labelHighlights; this.descriptionHighlights = descriptionHighlights; this.detailHighlights = detailHighlights; @@ -171,7 +171,7 @@ export class QuickOpenEntry { /** * Allows to return highlight ranges that should show up for the entry label and description. */ - public getHighlights(): [IHighlight[] /* Label */, IHighlight[] /* Description */, IHighlight[] /* Detail */] { + getHighlights(): [IHighlight[] /* Label */, IHighlight[] /* Description */, IHighlight[] /* Detail */] { return [this.labelHighlights, this.descriptionHighlights, this.detailHighlights]; } @@ -181,7 +181,7 @@ export class QuickOpenEntry { * * The context parameter provides additional context information how the run was triggered. */ - public run(mode: Mode, context: IContext): boolean { + run(mode: Mode, context: IContext): boolean { return false; } @@ -190,7 +190,7 @@ export class QuickOpenEntry { * and the resource of this entry is the same as the resource for an editor history, it will not show up * because it is considered to be a duplicate of an editor history. */ - public mergeWithEditorHistory(): boolean { + mergeWithEditorHistory(): boolean { return false; } } @@ -211,97 +211,97 @@ export class QuickOpenEntryGroup extends QuickOpenEntry { /** * The label of the group or null if none. */ - public getGroupLabel(): string { + getGroupLabel(): string { return this.groupLabel; } - public setGroupLabel(groupLabel: string): void { + setGroupLabel(groupLabel: string): void { this.groupLabel = groupLabel; } /** * Whether to show a border on top of the group entry or not. */ - public showBorder(): boolean { + showBorder(): boolean { return this.withBorder; } - public setShowBorder(showBorder: boolean): void { + setShowBorder(showBorder: boolean): void { this.withBorder = showBorder; } - public getLabel(): string { + getLabel(): string { return this.entry ? this.entry.getLabel() : super.getLabel(); } - public getLabelOptions(): IIconLabelValueOptions { + getLabelOptions(): IIconLabelValueOptions { return this.entry ? this.entry.getLabelOptions() : super.getLabelOptions(); } - public getAriaLabel(): string { + getAriaLabel(): string { return this.entry ? this.entry.getAriaLabel() : super.getAriaLabel(); } - public getDetail(): string { + getDetail(): string { return this.entry ? this.entry.getDetail() : super.getDetail(); } - public getResource(): URI { + getResource(): URI { return this.entry ? this.entry.getResource() : super.getResource(); } - public getIcon(): string { + getIcon(): string { return this.entry ? this.entry.getIcon() : super.getIcon(); } - public getDescription(): string { + getDescription(): string { return this.entry ? this.entry.getDescription() : super.getDescription(); } - public getEntry(): QuickOpenEntry { + getEntry(): QuickOpenEntry { return this.entry; } - public getHighlights(): [IHighlight[], IHighlight[], IHighlight[]] { + getHighlights(): [IHighlight[], IHighlight[], IHighlight[]] { return this.entry ? this.entry.getHighlights() : super.getHighlights(); } - public isHidden(): boolean { + isHidden(): boolean { return this.entry ? this.entry.isHidden() : super.isHidden(); } - public setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[], detailHighlights?: IHighlight[]): void { + setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[], detailHighlights?: IHighlight[]): void { this.entry ? this.entry.setHighlights(labelHighlights, descriptionHighlights, detailHighlights) : super.setHighlights(labelHighlights, descriptionHighlights, detailHighlights); } - public setHidden(hidden: boolean): void { + setHidden(hidden: boolean): void { this.entry ? this.entry.setHidden(hidden) : super.setHidden(hidden); } - public run(mode: Mode, context: IContext): boolean { + run(mode: Mode, context: IContext): boolean { return this.entry ? this.entry.run(mode, context) : super.run(mode, context); } } class NoActionProvider implements IActionProvider { - public hasActions(tree: ITree, element: any): boolean { + hasActions(tree: ITree, element: any): boolean { return false; } - public getActions(tree: ITree, element: any): TPromise { + getActions(tree: ITree, element: any): TPromise { return TPromise.as(null); } - public hasSecondaryActions(tree: ITree, element: any): boolean { + hasSecondaryActions(tree: ITree, element: any): boolean { return false; } - public getSecondaryActions(tree: ITree, element: any): TPromise { + getSecondaryActions(tree: ITree, element: any): TPromise { return TPromise.as(null); } - public getActionItem(tree: ITree, element: any, action: Action): IActionItem { + getActionItem(tree: ITree, element: any, action: Action): IActionItem { return null; } } @@ -333,7 +333,7 @@ class Renderer implements IRenderer { this.actionRunner = actionRunner; } - public getHeight(entry: QuickOpenEntry): number { + getHeight(entry: QuickOpenEntry): number { if (entry.getDetail()) { return 44; } @@ -341,7 +341,7 @@ class Renderer implements IRenderer { return 22; } - public getTemplateId(entry: QuickOpenEntry): string { + getTemplateId(entry: QuickOpenEntry): string { if (entry instanceof QuickOpenEntryGroup) { return templateEntryGroup; } @@ -349,7 +349,7 @@ class Renderer implements IRenderer { return templateEntry; } - public renderTemplate(templateId: string, container: HTMLElement, styles: IQuickOpenStyles): IQuickOpenEntryGroupTemplateData { + renderTemplate(templateId: string, container: HTMLElement, styles: IQuickOpenStyles): IQuickOpenEntryGroupTemplateData { const entryContainer = document.createElement('div'); DOM.addClass(entryContainer, 'sub-content'); container.appendChild(entryContainer); @@ -410,7 +410,7 @@ class Renderer implements IRenderer { }; } - public renderElement(entry: QuickOpenEntry, templateId: string, data: IQuickOpenEntryGroupTemplateData, styles: IQuickOpenStyles): void { + renderElement(entry: QuickOpenEntry, templateId: string, data: IQuickOpenEntryGroupTemplateData, styles: IQuickOpenStyles): void { // Action Bar if (this.actionProvider.hasActions(null, entry)) { @@ -480,7 +480,7 @@ class Renderer implements IRenderer { } } - public disposeTemplate(templateId: string, templateData: IQuickOpenEntryGroupTemplateData): void { + disposeTemplate(templateId: string, templateData: IQuickOpenEntryGroupTemplateData): void { const data = templateData as IQuickOpenEntryGroupTemplateData; data.actionBar.dispose(); data.actionBar = null; @@ -519,21 +519,21 @@ export class QuickOpenModel implements this._accessibilityProvider = this; } - public get entries() { return this._entries; } - public get dataSource() { return this._dataSource; } - public get renderer() { return this._renderer; } - public get filter() { return this._filter; } - public get runner() { return this._runner; } - public get accessibilityProvider() { return this._accessibilityProvider; } + get entries() { return this._entries; } + get dataSource() { return this._dataSource; } + get renderer() { return this._renderer; } + get filter() { return this._filter; } + get runner() { return this._runner; } + get accessibilityProvider() { return this._accessibilityProvider; } - public set entries(entries: QuickOpenEntry[]) { + set entries(entries: QuickOpenEntry[]) { this._entries = entries; } /** * Adds entries that should show up in the quick open viewer. */ - public addEntries(entries: QuickOpenEntry[]): void { + addEntries(entries: QuickOpenEntry[]): void { if (types.isArray(entries)) { this._entries = this._entries.concat(entries); } @@ -542,7 +542,7 @@ export class QuickOpenModel implements /** * Set the entries that should show up in the quick open viewer. */ - public setEntries(entries: QuickOpenEntry[]): void { + setEntries(entries: QuickOpenEntry[]): void { if (types.isArray(entries)) { this._entries = entries; } @@ -553,7 +553,7 @@ export class QuickOpenModel implements * * @visibleOnly optional parameter to only return visible entries */ - public getEntries(visibleOnly?: boolean): QuickOpenEntry[] { + getEntries(visibleOnly?: boolean): QuickOpenEntry[] { if (visibleOnly) { return this._entries.filter((e) => !e.isHidden()); } @@ -561,15 +561,15 @@ export class QuickOpenModel implements return this._entries; } - public getId(entry: QuickOpenEntry): string { + getId(entry: QuickOpenEntry): string { return entry.getId(); } - public getLabel(entry: QuickOpenEntry): string { + getLabel(entry: QuickOpenEntry): string { return entry.getLabel(); } - public getAriaLabel(entry: QuickOpenEntry): string { + getAriaLabel(entry: QuickOpenEntry): string { const ariaLabel = entry.getAriaLabel(); if (ariaLabel) { return nls.localize('quickOpenAriaLabelEntry', "{0}, picker", entry.getAriaLabel()); @@ -578,11 +578,11 @@ export class QuickOpenModel implements return nls.localize('quickOpenAriaLabel', "picker"); } - public isVisible(entry: QuickOpenEntry): boolean { + isVisible(entry: QuickOpenEntry): boolean { return !entry.isHidden(); } - public run(entry: QuickOpenEntry, mode: Mode, context: IContext): boolean { + run(entry: QuickOpenEntry, mode: Mode, context: IContext): boolean { return entry.run(mode, context); } } diff --git a/src/vs/base/parts/quickopen/browser/quickOpenViewer.ts b/src/vs/base/parts/quickopen/browser/quickOpenViewer.ts index 07817947cbb..084c12b65df 100644 --- a/src/vs/base/parts/quickopen/browser/quickOpenViewer.ts +++ b/src/vs/base/parts/quickopen/browser/quickOpenViewer.ts @@ -23,7 +23,7 @@ export class DataSource implements IDataSource { this.modelProvider = isFunction(arg.getModel) ? arg : { getModel: () => arg }; } - public getId(tree: ITree, element: any): string { + getId(tree: ITree, element: any): string { if (!element) { return null; } @@ -32,17 +32,17 @@ export class DataSource implements IDataSource { return model === element ? '__root__' : model.dataSource.getId(element); } - public hasChildren(tree: ITree, element: any): boolean { + hasChildren(tree: ITree, element: any): boolean { const model = this.modelProvider.getModel(); return model && model === element && model.entries.length > 0; } - public getChildren(tree: ITree, element: any): TPromise { + getChildren(tree: ITree, element: any): TPromise { const model = this.modelProvider.getModel(); return TPromise.as(model === element ? model.entries : []); } - public getParent(tree: ITree, element: any): TPromise { + getParent(tree: ITree, element: any): TPromise { return TPromise.as(null); } } @@ -50,18 +50,18 @@ export class DataSource implements IDataSource { export class AccessibilityProvider implements IAccessibilityProvider { constructor(private modelProvider: IModelProvider) { } - public getAriaLabel(tree: ITree, element: any): string { + getAriaLabel(tree: ITree, element: any): string { const model = this.modelProvider.getModel(); return model.accessibilityProvider && model.accessibilityProvider.getAriaLabel(element); } - public getPosInSet(tree: ITree, element: any): string { + getPosInSet(tree: ITree, element: any): string { const model = this.modelProvider.getModel(); return String(model.entries.indexOf(element) + 1); } - public getSetSize(): string { + getSetSize(): string { const model = this.modelProvider.getModel(); return String(model.entries.length); } @@ -71,7 +71,7 @@ export class Filter implements IFilter { constructor(private modelProvider: IModelProvider) { } - public isVisible(tree: ITree, element: any): boolean { + isVisible(tree: ITree, element: any): boolean { const model = this.modelProvider.getModel(); if (!model.filter) { @@ -89,31 +89,31 @@ export class Renderer implements IRenderer { this.styles = styles; } - public updateStyles(styles: IQuickOpenStyles): void { + updateStyles(styles: IQuickOpenStyles): void { this.styles = styles; } - public getHeight(tree: ITree, element: any): number { + getHeight(tree: ITree, element: any): number { const model = this.modelProvider.getModel(); return model.renderer.getHeight(element); } - public getTemplateId(tree: ITree, element: any): string { + getTemplateId(tree: ITree, element: any): string { const model = this.modelProvider.getModel(); return model.renderer.getTemplateId(element); } - public renderTemplate(tree: ITree, templateId: string, container: HTMLElement): any { + renderTemplate(tree: ITree, templateId: string, container: HTMLElement): any { const model = this.modelProvider.getModel(); return model.renderer.renderTemplate(templateId, container, this.styles); } - public renderElement(tree: ITree, element: any, templateId: string, templateData: any): void { + renderElement(tree: ITree, element: any, templateId: string, templateData: any): void { const model = this.modelProvider.getModel(); model.renderer.renderElement(element, templateId, templateData, this.styles); } - public disposeTemplate(tree: ITree, templateId: string, templateData: any): void { + disposeTemplate(tree: ITree, templateId: string, templateData: any): void { const model = this.modelProvider.getModel(); model.renderer.disposeTemplate(templateId, templateData); } diff --git a/src/vs/base/parts/quickopen/browser/quickOpenWidget.ts b/src/vs/base/parts/quickopen/browser/quickOpenWidget.ts index 53a84d50876..2a3a7f0d15a 100644 --- a/src/vs/base/parts/quickopen/browser/quickOpenWidget.ts +++ b/src/vs/base/parts/quickopen/browser/quickOpenWidget.ts @@ -22,7 +22,7 @@ import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { DefaultController, ClickBehavior } from 'vs/base/parts/tree/browser/treeDefaults'; import * as DOM from 'vs/base/browser/dom'; import { KeyCode } from 'vs/base/common/keyCodes'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import { Color } from 'vs/base/common/color'; import { mixin } from 'vs/base/common/objects'; @@ -65,7 +65,7 @@ export interface IShowOptions { export class QuickOpenController extends DefaultController { - public onContextMenu(tree: ITree, element: any, event: ContextMenuEvent): boolean { + onContextMenu(tree: ITree, element: any, event: ContextMenuEvent): boolean { if (platform.isMacintosh) { return this.onLeftClick(tree, element, event); // https://github.com/Microsoft/vscode/issues/1011 } @@ -91,7 +91,7 @@ const defaultStyles = { const DEFAULT_INPUT_ARIA_LABEL = nls.localize('quickOpenAriaLabel', "Quick picker. Type to narrow down results."); -export class QuickOpenWidget implements IModelProvider { +export class QuickOpenWidget extends Disposable implements IModelProvider { private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private static readonly MAX_ITEMS_HEIGHT = 20 * 22; // Max height of item list below input field @@ -108,7 +108,6 @@ export class QuickOpenWidget implements IModelProvider { private visible: boolean; private isLoosingFocus: boolean; private callbacks: IQuickOpenCallbacks; - private toUnbind: IDisposable[]; private quickNavigateConfiguration: IQuickNavigateConfiguration; private container: HTMLElement; private treeElement: HTMLElement; @@ -120,8 +119,9 @@ export class QuickOpenWidget implements IModelProvider { private renderer: Renderer; constructor(container: HTMLElement, callbacks: IQuickOpenCallbacks, options: IQuickOpenOptions) { + super(); + this.isDisposed = false; - this.toUnbind = []; this.container = container; this.callbacks = callbacks; this.options = options; @@ -130,19 +130,19 @@ export class QuickOpenWidget implements IModelProvider { this.model = null; } - public getElement(): HTMLElement { + getElement(): HTMLElement { return $(this.builder).getHTMLElement(); } - public getModel(): IModel { + getModel(): IModel { return this.model; } - public setCallbacks(callbacks: IQuickOpenCallbacks): void { + setCallbacks(callbacks: IQuickOpenCallbacks): void { this.callbacks = callbacks; } - public create(): HTMLElement { + create(): HTMLElement { this.builder = $().div(div => { // Eventing @@ -159,13 +159,13 @@ export class QuickOpenWidget implements IModelProvider { .on(DOM.EventType.BLUR, (e: FocusEvent) => this.loosingFocus(e), null, true); // Progress Bar - this.progressBar = new ProgressBar(div.clone(), { progressBarBackground: this.styles.progressBarBackground }); + this.progressBar = this._register(new ProgressBar(div.clone(), { progressBarBackground: this.styles.progressBarBackground })); this.progressBar.hide(); // Input Field div.div({ 'class': 'quick-open-input' }, inputContainer => { this.inputContainer = inputContainer; - this.inputBox = new InputBox(inputContainer.getHTMLElement(), null, { + this.inputBox = this._register(new InputBox(inputContainer.getHTMLElement(), null, { placeholder: this.options.inputPlaceHolder || '', ariaLabel: DEFAULT_INPUT_ARIA_LABEL, inputBackground: this.styles.inputBackground, @@ -177,7 +177,7 @@ export class QuickOpenWidget implements IModelProvider { inputValidationWarningBorder: this.styles.inputValidationWarningBorder, inputValidationErrorBackground: this.styles.inputValidationErrorBackground, inputValidationErrorBorder: this.styles.inputValidationErrorBorder - }); + })); // ARIA this.inputElement = this.inputBox.inputElement; @@ -229,7 +229,7 @@ export class QuickOpenWidget implements IModelProvider { }, div => { const createTree = this.options.treeCreator || ((container, config, opts) => new Tree(container, config, opts)); - this.tree = createTree(div.getHTMLElement(), { + this.tree = this._register(createTree(div.getHTMLElement(), { dataSource: new DataSource(this), controller: new QuickOpenController({ clickBehavior: ClickBehavior.ON_MOUSE_UP, keyboardSupport: this.options.keyboardSupport }), renderer: (this.renderer = new Renderer(this, this.styles)), @@ -244,16 +244,16 @@ export class QuickOpenWidget implements IModelProvider { ariaLabel: nls.localize('treeAriaLabel', "Quick Picker"), keyboardSupport: this.options.keyboardSupport, preventRootFocus: true - }); + })); this.treeElement = this.tree.getHTMLElement(); // Handle Focus and Selection event - this.toUnbind.push(this.tree.onDidChangeFocus(event => { + this._register(this.tree.onDidChangeFocus(event => { this.elementFocused(event.focus, event); })); - this.toUnbind.push(this.tree.onDidChangeSelection(event => { + this._register(this.tree.onDidChangeSelection(event => { if (event.selection && event.selection.length > 0) { const mouseEvent: StandardMouseEvent = event.payload && event.payload.originalEvent instanceof StandardMouseEvent ? event.payload.originalEvent : void 0; const shouldOpenInBackground = mouseEvent ? this.shouldOpenInBackground(mouseEvent) : false; @@ -354,7 +354,7 @@ export class QuickOpenWidget implements IModelProvider { return this.builder.getHTMLElement(); } - public style(styles: IQuickOpenStyles): void { + style(styles: IQuickOpenStyles): void { this.styles = styles; this.applyStyles(); @@ -442,7 +442,7 @@ export class QuickOpenWidget implements IModelProvider { this.callbacks.onType(value); } - public navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration): void { + navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration): void { if (this.isVisible()) { // Transition into quick navigate mode if not yet done @@ -548,9 +548,9 @@ export class QuickOpenWidget implements IModelProvider { }; } - public show(prefix: string, options?: IShowOptions): void; - public show(input: IModel, options?: IShowOptions): void; - public show(param: any, options?: IShowOptions): void { + show(prefix: string, options?: IShowOptions): void; + show(input: IModel, options?: IShowOptions): void; + show(param: any, options?: IShowOptions): void { this.visible = true; this.isLoosingFocus = false; this.quickNavigateConfiguration = options ? options.quickNavigateConfiguration : void 0; @@ -696,7 +696,7 @@ export class QuickOpenWidget implements IModelProvider { } } - public refresh(input?: IModel, autoFocus?: IAutoFocus): void { + refresh(input?: IModel, autoFocus?: IAutoFocus): void { if (!this.isVisible()) { return; } @@ -760,7 +760,7 @@ export class QuickOpenWidget implements IModelProvider { return height; } - public hide(reason?: HideReason): void { + hide(reason?: HideReason): void { if (!this.isVisible()) { return; } @@ -801,17 +801,17 @@ export class QuickOpenWidget implements IModelProvider { } } - public getQuickNavigateConfiguration(): IQuickNavigateConfiguration { + getQuickNavigateConfiguration(): IQuickNavigateConfiguration { return this.quickNavigateConfiguration; } - public setPlaceHolder(placeHolder: string): void { + setPlaceHolder(placeHolder: string): void { if (this.inputBox) { this.inputBox.setPlaceHolder(placeHolder); } } - public setValue(value: string, selectionOrStableHint?: [number, number] | null): void { + setValue(value: string, selectionOrStableHint?: [number, number] | null): void { if (this.inputBox) { this.inputBox.value = value; if (selectionOrStableHint === null) { @@ -825,13 +825,13 @@ export class QuickOpenWidget implements IModelProvider { } } - public setPassword(isPassword: boolean): void { + setPassword(isPassword: boolean): void { if (this.inputBox) { this.inputBox.inputElement.type = isPassword ? 'password' : 'text'; } } - public setInput(input: IModel, autoFocus: IAutoFocus, ariaLabel?: string): void { + setInput(input: IModel, autoFocus: IAutoFocus, ariaLabel?: string): void { if (!this.isVisible()) { return; } @@ -864,29 +864,29 @@ export class QuickOpenWidget implements IModelProvider { }, 500); } - public getInput(): IModel { + getInput(): IModel { return this.tree.getInput(); } - public showInputDecoration(decoration: Severity): void { + showInputDecoration(decoration: Severity): void { if (this.inputBox) { this.inputBox.showMessage({ type: decoration === Severity.Info ? MessageType.INFO : decoration === Severity.Warning ? MessageType.WARNING : MessageType.ERROR, content: '' }); } } - public clearInputDecoration(): void { + clearInputDecoration(): void { if (this.inputBox) { this.inputBox.hideMessage(); } } - public focus(): void { + focus(): void { if (this.isVisible() && this.inputBox) { this.inputBox.focus(); } } - public accept(): void { + accept(): void { if (this.isVisible()) { const focus = this.tree.getFocus(); if (focus) { @@ -895,15 +895,15 @@ export class QuickOpenWidget implements IModelProvider { } } - public getProgressBar(): ProgressBar { + getProgressBar(): ProgressBar { return this.progressBar; } - public getInputBox(): InputBox { + getInputBox(): InputBox { return this.inputBox; } - public setExtraClass(clazz: string): void { + setExtraClass(clazz: string): void { const previousClass = this.builder.getProperty('extra-class'); if (previousClass) { this.builder.removeClass(previousClass); @@ -917,11 +917,11 @@ export class QuickOpenWidget implements IModelProvider { } } - public isVisible(): boolean { + isVisible(): boolean { return this.visible; } - public layout(dimension: DOM.Dimension): void { + layout(dimension: DOM.Dimension): void { this.layoutDimensions = dimension; // Apply to quick open width (height is dynamic by number of items to show) @@ -971,12 +971,9 @@ export class QuickOpenWidget implements IModelProvider { }); } - public dispose(): void { - this.isDisposed = true; - this.toUnbind = dispose(this.toUnbind); + dispose(): void { + super.dispose(); - this.progressBar.dispose(); - this.inputBox.dispose(); - this.tree.dispose(); + this.isDisposed = true; } } diff --git a/src/vs/code/electron-main/app.ts b/src/vs/code/electron-main/app.ts index a262d3fb3a6..edd6a1a8f68 100644 --- a/src/vs/code/electron-main/app.ts +++ b/src/vs/code/electron-main/app.ts @@ -261,7 +261,7 @@ export class CodeApplication { } } - public startup(): TPromise { + startup(): TPromise { this.logService.debug('Starting VS Code'); this.logService.debug(`from: ${this.environmentService.appRoot}`); this.logService.debug('args:', this.environmentService.args); diff --git a/src/vs/code/electron-main/launch.ts b/src/vs/code/electron-main/launch.ts index c0e2ce460e0..7da8d2edbd2 100644 --- a/src/vs/code/electron-main/launch.ts +++ b/src/vs/code/electron-main/launch.ts @@ -79,7 +79,7 @@ export class LaunchChannel implements ILaunchChannel { constructor(private service: ILaunchService) { } - public call(command: string, arg: any): TPromise { + call(command: string, arg: any): TPromise { switch (command) { case 'start': const { args, userEnv } = arg as IStartArguments; @@ -105,19 +105,19 @@ export class LaunchChannelClient implements ILaunchService { constructor(private channel: ILaunchChannel) { } - public start(args: ParsedArgs, userEnv: IProcessEnvironment): TPromise { + start(args: ParsedArgs, userEnv: IProcessEnvironment): TPromise { return this.channel.call('start', { args, userEnv }); } - public getMainProcessId(): TPromise { + getMainProcessId(): TPromise { return this.channel.call('get-main-process-id', null); } - public getMainProcessInfo(): TPromise { + getMainProcessInfo(): TPromise { return this.channel.call('get-main-process-info', null); } - public getLogsPath(): TPromise { + getLogsPath(): TPromise { return this.channel.call('get-logs-path', null); } } @@ -135,7 +135,7 @@ export class LaunchService implements ILaunchService { @IConfigurationService private readonly configurationService: IConfigurationService ) { } - public start(args: ParsedArgs, userEnv: IProcessEnvironment): TPromise { + start(args: ParsedArgs, userEnv: IProcessEnvironment): TPromise { this.logService.trace('Received data from other instance: ', args, userEnv); const urlsToOpen = parseOpenUrl(args); @@ -237,13 +237,13 @@ export class LaunchService implements ILaunchService { return TPromise.as(null); } - public getMainProcessId(): TPromise { + getMainProcessId(): TPromise { this.logService.trace('Received request for process ID from other instance.'); return TPromise.as(process.pid); } - public getMainProcessInfo(): TPromise { + getMainProcessInfo(): TPromise { this.logService.trace('Received request for main process info from other instance.'); const windows: IWindowInfo[] = []; @@ -263,7 +263,7 @@ export class LaunchService implements ILaunchService { } as IMainProcessInfo); } - public getLogsPath(): TPromise { + getLogsPath(): TPromise { this.logService.trace('Received request for logs path from other instance.'); return TPromise.as(this.environmentService.logsPath); diff --git a/src/vs/code/electron-main/window.ts b/src/vs/code/electron-main/window.ts index 5dba67940e6..5c70b90de69 100644 --- a/src/vs/code/electron-main/window.ts +++ b/src/vs/code/electron-main/window.ts @@ -55,8 +55,8 @@ interface ITouchBarSegment extends Electron.SegmentedControlSegment { export class CodeWindow implements ICodeWindow { - public static readonly themeStorageKey = 'theme'; - public static readonly themeBackgroundStorageKey = 'themeBackground'; + static readonly themeStorageKey = 'theme'; + static readonly themeBackgroundStorageKey = 'themeBackground'; private static readonly DEFAULT_BG_LIGHT = '#FFFFFF'; private static readonly DEFAULT_BG_DARK = '#1E1E1E'; @@ -229,35 +229,35 @@ export class CodeWindow implements ICodeWindow { this._lastFocusTime = Date.now(); // since we show directly, we need to set the last focus time too } - public hasHiddenTitleBarStyle(): boolean { + hasHiddenTitleBarStyle(): boolean { return this.hiddenTitleBarStyle; } - public get isExtensionDevelopmentHost(): boolean { + get isExtensionDevelopmentHost(): boolean { return !!this.config.extensionDevelopmentPath; } - public get isExtensionTestHost(): boolean { + get isExtensionTestHost(): boolean { return !!this.config.extensionTestsPath; } - public get extensionDevelopmentPath(): string { + get extensionDevelopmentPath(): string { return this.config.extensionDevelopmentPath; } - public get config(): IWindowConfiguration { + get config(): IWindowConfiguration { return this.currentConfig; } - public get id(): number { + get id(): number { return this._id; } - public get win(): Electron.BrowserWindow { + get win(): Electron.BrowserWindow { return this._win; } - public setRepresentedFilename(filename: string): void { + setRepresentedFilename(filename: string): void { if (isMacintosh) { this.win.setRepresentedFilename(filename); } else { @@ -265,7 +265,7 @@ export class CodeWindow implements ICodeWindow { } } - public getRepresentedFilename(): string { + getRepresentedFilename(): string { if (isMacintosh) { return this.win.getRepresentedFilename(); } @@ -273,7 +273,7 @@ export class CodeWindow implements ICodeWindow { return this.representedFilename; } - public focus(): void { + focus(): void { if (!this._win) { return; } @@ -285,23 +285,23 @@ export class CodeWindow implements ICodeWindow { this._win.focus(); } - public get lastFocusTime(): number { + get lastFocusTime(): number { return this._lastFocusTime; } - public get backupPath(): string { + get backupPath(): string { return this.currentConfig ? this.currentConfig.backupPath : void 0; } - public get openedWorkspace(): IWorkspaceIdentifier { + get openedWorkspace(): IWorkspaceIdentifier { return this.currentConfig ? this.currentConfig.workspace : void 0; } - public get openedFolderPath(): string { + get openedFolderPath(): string { return this.currentConfig ? this.currentConfig.folderPath : void 0; } - public setReady(): void { + setReady(): void { this._readyState = ReadyState.READY; // inform all waiting promises that we are ready now @@ -310,7 +310,7 @@ export class CodeWindow implements ICodeWindow { } } - public ready(): TPromise { + ready(): TPromise { return new TPromise((c) => { if (this._readyState === ReadyState.READY) { return c(this); @@ -321,7 +321,7 @@ export class CodeWindow implements ICodeWindow { }); } - public get readyState(): ReadyState { + get readyState(): ReadyState { return this._readyState; } @@ -517,7 +517,7 @@ export class CodeWindow implements ICodeWindow { }); } - public load(config: IWindowConfiguration, isReload?: boolean, disableExtensions?: boolean): void { + load(config: IWindowConfiguration, isReload?: boolean, disableExtensions?: boolean): void { // If this is the first time the window is loaded, we associate the paths // directly with the window because we assume the loading will just work @@ -574,7 +574,7 @@ export class CodeWindow implements ICodeWindow { } } - public reload(configuration?: IWindowConfiguration, cli?: ParsedArgs): void { + reload(configuration?: IWindowConfiguration, cli?: ParsedArgs): void { // If config is not provided, copy our current one if (!configuration) { @@ -678,7 +678,7 @@ export class CodeWindow implements ICodeWindow { return background; } - public serializeWindowState(): IWindowState { + serializeWindowState(): IWindowState { if (!this._win) { return defaultWindowState(); } @@ -834,14 +834,14 @@ export class CodeWindow implements ICodeWindow { return null; } - public getBounds(): Electron.Rectangle { + getBounds(): Electron.Rectangle { const pos = this._win.getPosition(); const dimension = this._win.getSize(); return { x: pos[0], y: pos[1], width: dimension[0], height: dimension[1] }; } - public toggleFullScreen(): void { + toggleFullScreen(): void { const willBeFullScreen = !this._win.isFullScreen(); // set fullscreen flag on window @@ -916,7 +916,7 @@ export class CodeWindow implements ICodeWindow { } } - public onWindowTitleDoubleClick(): void { + onWindowTitleDoubleClick(): void { // Respect system settings on mac with regards to title click on windows title if (isMacintosh) { @@ -943,25 +943,25 @@ export class CodeWindow implements ICodeWindow { } } - public close(): void { + close(): void { if (this._win) { this._win.close(); } } - public sendWhenReady(channel: string, ...args: any[]): void { + sendWhenReady(channel: string, ...args: any[]): void { this.ready().then(() => { this.send(channel, ...args); }); } - public send(channel: string, ...args: any[]): void { + send(channel: string, ...args: any[]): void { if (this._win) { this._win.webContents.send(channel, ...args); } } - public updateTouchBar(groups: ISerializableCommandAction[][]): void { + updateTouchBar(groups: ISerializableCommandAction[][]): void { if (!isMacintosh) { return; // only supported on macOS } @@ -1033,7 +1033,7 @@ export class CodeWindow implements ICodeWindow { return segments; } - public dispose(): void { + dispose(): void { if (this.showTimeoutHandle) { clearTimeout(this.showTimeoutHandle); } diff --git a/src/vs/code/electron-main/windows.ts b/src/vs/code/electron-main/windows.ts index bc331038334..04d9d28c4ee 100644 --- a/src/vs/code/electron-main/windows.ts +++ b/src/vs/code/electron-main/windows.ts @@ -153,7 +153,7 @@ export class WindowsManager implements IWindowsMainService { this.workspacesManager = new WorkspacesManager(workspacesMainService, backupMainService, environmentService, this); } - public ready(initialUserEnv: IProcessEnvironment): void { + ready(initialUserEnv: IProcessEnvironment): void { this.initialUserEnv = initialUserEnv; this.registerListeners(); @@ -323,7 +323,7 @@ export class WindowsManager implements IWindowsMainService { }; } - public open(openConfig: IOpenConfiguration): ICodeWindow[] { + open(openConfig: IOpenConfiguration): ICodeWindow[] { openConfig = this.validateOpenConfig(openConfig); let pathsToOpen = this.getPathsToOpen(openConfig); @@ -1010,7 +1010,7 @@ export class WindowsManager implements IWindowsMainService { return { openFolderInNewWindow, openFilesInNewWindow }; } - public openExtensionDevelopmentHostWindow(openConfig: IOpenConfiguration): void { + openExtensionDevelopmentHostWindow(openConfig: IOpenConfiguration): void { // Reload an existing extension development host window on the same path // We currently do not allow more than one extension development window @@ -1286,7 +1286,7 @@ export class WindowsManager implements IWindowsMainService { return state; } - public reload(win: ICodeWindow, cli?: ParsedArgs): void { + reload(win: ICodeWindow, cli?: ParsedArgs): void { // Only reload when the window has not vetoed this this.lifecycleService.unload(win, UnloadReason.RELOAD).done(veto => { @@ -1299,18 +1299,18 @@ export class WindowsManager implements IWindowsMainService { }); } - public closeWorkspace(win: ICodeWindow): void { + closeWorkspace(win: ICodeWindow): void { this.openInBrowserWindow({ cli: this.environmentService.args, windowToUse: win }); } - public saveAndEnterWorkspace(win: ICodeWindow, path: string): TPromise { + saveAndEnterWorkspace(win: ICodeWindow, path: string): TPromise { return this.workspacesManager.saveAndEnterWorkspace(win, path).then(result => this.doEnterWorkspace(win, result)); } - public createAndEnterWorkspace(win: ICodeWindow, folders?: IWorkspaceFolderCreationData[], path?: string): TPromise { + createAndEnterWorkspace(win: ICodeWindow, folders?: IWorkspaceFolderCreationData[], path?: string): TPromise { return this.workspacesManager.createAndEnterWorkspace(win, folders, path).then(result => this.doEnterWorkspace(win, result)); } @@ -1325,7 +1325,7 @@ export class WindowsManager implements IWindowsMainService { return result; } - public pickWorkspaceAndOpen(options: INativeOpenDialogOptions): void { + pickWorkspaceAndOpen(options: INativeOpenDialogOptions): void { this.workspacesManager.pickWorkspaceAndOpen(options); } @@ -1366,7 +1366,7 @@ export class WindowsManager implements IWindowsMainService { })); } - public focusLastActive(cli: ParsedArgs, context: OpenContext): ICodeWindow { + focusLastActive(cli: ParsedArgs, context: OpenContext): ICodeWindow { const lastActive = this.getLastActiveWindow(); if (lastActive) { lastActive.focus(); @@ -1378,15 +1378,15 @@ export class WindowsManager implements IWindowsMainService { return this.open({ context, cli, forceEmpty: true })[0]; } - public getLastActiveWindow(): ICodeWindow { + getLastActiveWindow(): ICodeWindow { return getLastActiveWindow(WindowsManager.WINDOWS); } - public openNewWindow(context: OpenContext): ICodeWindow[] { + openNewWindow(context: OpenContext): ICodeWindow[] { return this.open({ context, cli: this.environmentService.args, forceNewWindow: true, forceEmpty: true }); } - public waitForWindowCloseOrLoad(windowId: number): TPromise { + waitForWindowCloseOrLoad(windowId: number): TPromise { return new TPromise(c => { function handler(id: number) { if (id === windowId) { @@ -1402,7 +1402,7 @@ export class WindowsManager implements IWindowsMainService { }); } - public sendToFocused(channel: string, ...args: any[]): void { + sendToFocused(channel: string, ...args: any[]): void { const focusedWindow = this.getFocusedWindow() || this.getLastActiveWindow(); if (focusedWindow) { @@ -1410,7 +1410,7 @@ export class WindowsManager implements IWindowsMainService { } } - public sendToAll(channel: string, payload?: any, windowIdsToIgnore?: number[]): void { + sendToAll(channel: string, payload?: any, windowIdsToIgnore?: number[]): void { WindowsManager.WINDOWS.forEach(w => { if (windowIdsToIgnore && windowIdsToIgnore.indexOf(w.id) >= 0) { return; // do not send if we are instructed to ignore it @@ -1420,7 +1420,7 @@ export class WindowsManager implements IWindowsMainService { }); } - public getFocusedWindow(): ICodeWindow { + getFocusedWindow(): ICodeWindow { const win = BrowserWindow.getFocusedWindow(); if (win) { return this.getWindowById(win.id); @@ -1429,7 +1429,7 @@ export class WindowsManager implements IWindowsMainService { return null; } - public getWindowById(windowId: number): ICodeWindow { + getWindowById(windowId: number): ICodeWindow { const res = WindowsManager.WINDOWS.filter(w => w.id === windowId); if (res && res.length === 1) { return res[0]; @@ -1438,11 +1438,11 @@ export class WindowsManager implements IWindowsMainService { return null; } - public getWindows(): ICodeWindow[] { + getWindows(): ICodeWindow[] { return WindowsManager.WINDOWS; } - public getWindowCount(): number { + getWindowCount(): number { return WindowsManager.WINDOWS.length; } @@ -1510,15 +1510,15 @@ export class WindowsManager implements IWindowsMainService { this._onWindowClose.fire(win.id); } - public pickFileFolderAndOpen(options: INativeOpenDialogOptions): void { + pickFileFolderAndOpen(options: INativeOpenDialogOptions): void { this.doPickAndOpen(options, true /* pick folders */, true /* pick files */); } - public pickFolderAndOpen(options: INativeOpenDialogOptions): void { + pickFolderAndOpen(options: INativeOpenDialogOptions): void { this.doPickAndOpen(options, true /* pick folders */, false /* pick files */); } - public pickFileAndOpen(options: INativeOpenDialogOptions): void { + pickFileAndOpen(options: INativeOpenDialogOptions): void { this.doPickAndOpen(options, false /* pick folders */, true /* pick files */); } @@ -1556,19 +1556,19 @@ export class WindowsManager implements IWindowsMainService { this.dialogs.pickAndOpen(internalOptions); } - public showMessageBox(options: Electron.MessageBoxOptions, win?: ICodeWindow): TPromise { + showMessageBox(options: Electron.MessageBoxOptions, win?: ICodeWindow): TPromise { return this.dialogs.showMessageBox(options, win); } - public showSaveDialog(options: Electron.SaveDialogOptions, win?: ICodeWindow): TPromise { + showSaveDialog(options: Electron.SaveDialogOptions, win?: ICodeWindow): TPromise { return this.dialogs.showSaveDialog(options, win); } - public showOpenDialog(options: Electron.OpenDialogOptions, win?: ICodeWindow): TPromise { + showOpenDialog(options: Electron.OpenDialogOptions, win?: ICodeWindow): TPromise { return this.dialogs.showOpenDialog(options, win); } - public quit(): void { + quit(): void { // If the user selected to exit from an extension development host window, do not quit, but just // close the window unless this is the last window that is opened. @@ -1608,7 +1608,7 @@ class Dialogs { this.noWindowDialogQueue = new Queue(); } - public pickAndOpen(options: INativeOpenDialogOptions): void { + pickAndOpen(options: INativeOpenDialogOptions): void { this.getFileOrFolderPaths(options).then(paths => { const numberOfPaths = paths ? paths.length : 0; @@ -1694,7 +1694,7 @@ class Dialogs { return windowDialogQueue; } - public showMessageBox(options: Electron.MessageBoxOptions, window?: ICodeWindow): TPromise { + showMessageBox(options: Electron.MessageBoxOptions, window?: ICodeWindow): TPromise { return this.getDialogQueue(window).queue(() => { return new TPromise((c, e) => { dialog.showMessageBox(window ? window.win : void 0, options, (response: number, checkboxChecked: boolean) => { @@ -1704,7 +1704,7 @@ class Dialogs { }); } - public showSaveDialog(options: Electron.SaveDialogOptions, window?: ICodeWindow): TPromise { + showSaveDialog(options: Electron.SaveDialogOptions, window?: ICodeWindow): TPromise { function normalizePath(path: string): string { if (path && isMacintosh) { @@ -1723,7 +1723,7 @@ class Dialogs { }); } - public showOpenDialog(options: Electron.OpenDialogOptions, window?: ICodeWindow): TPromise { + showOpenDialog(options: Electron.OpenDialogOptions, window?: ICodeWindow): TPromise { function normalizePaths(paths: string[]): string[] { if (paths && paths.length > 0 && isMacintosh) { @@ -1767,7 +1767,7 @@ class WorkspacesManager { ) { } - public saveAndEnterWorkspace(window: ICodeWindow, path: string): TPromise { + saveAndEnterWorkspace(window: ICodeWindow, path: string): TPromise { if (!window || !window.win || window.readyState !== ReadyState.READY || !window.openedWorkspace || !path || !this.isValidTargetWorkspacePath(window, path)) { return TPromise.as(null); // return early if the window is not ready or disposed or does not have a workspace } @@ -1775,7 +1775,7 @@ class WorkspacesManager { return this.doSaveAndOpenWorkspace(window, window.openedWorkspace, path); } - public createAndEnterWorkspace(window: ICodeWindow, folders?: IWorkspaceFolderCreationData[], path?: string): TPromise { + createAndEnterWorkspace(window: ICodeWindow, folders?: IWorkspaceFolderCreationData[], path?: string): TPromise { if (!window || !window.win || window.readyState !== ReadyState.READY) { return TPromise.as(null); // return early if the window is not ready or disposed } @@ -1844,7 +1844,7 @@ class WorkspacesManager { }); } - public pickWorkspaceAndOpen(options: INativeOpenDialogOptions): void { + pickWorkspaceAndOpen(options: INativeOpenDialogOptions): void { const window = this.windowsMainService.getWindowById(options.windowId) || this.windowsMainService.getFocusedWindow() || this.windowsMainService.getLastActiveWindow(); this.windowsMainService.pickFileAndOpen({ @@ -1862,7 +1862,7 @@ class WorkspacesManager { }); } - public promptToSaveUntitledWorkspace(window: ICodeWindow, workspace: IWorkspaceIdentifier): TPromise { + promptToSaveUntitledWorkspace(window: ICodeWindow, workspace: IWorkspaceIdentifier): TPromise { enum ConfirmResult { SAVE, DONT_SAVE, diff --git a/src/vs/editor/contrib/hover/modesContentHover.ts b/src/vs/editor/contrib/hover/modesContentHover.ts index af946d803c9..9a3665d60d8 100644 --- a/src/vs/editor/contrib/hover/modesContentHover.ts +++ b/src/vs/editor/contrib/hover/modesContentHover.ts @@ -21,7 +21,7 @@ import { ColorPickerModel } from 'vs/editor/contrib/colorPicker/colorPickerModel import { ColorPickerWidget } from 'vs/editor/contrib/colorPicker/colorPickerWidget'; import { ColorDetector } from 'vs/editor/contrib/colorPicker/colorDetector'; import { Color, RGBA } from 'vs/base/common/color'; -import { IDisposable, empty as EmptyDisposable, dispose, combinedDisposable } from 'vs/base/common/lifecycle'; +import { IDisposable, empty as EmptyDisposable, combinedDisposable } from 'vs/base/common/lifecycle'; import { getColorPresentations } from 'vs/editor/contrib/colorPicker/color'; import { IThemeService } from 'vs/platform/theme/common/themeService'; const $ = dom.$; @@ -168,7 +168,6 @@ export class ModesContentHoverWidget extends ContentHoverWidget { private _colorPicker: ColorPickerWidget; private renderDisposable: IDisposable = EmptyDisposable; - private toDispose: IDisposable[] = []; constructor( editor: ICodeEditor, @@ -182,7 +181,7 @@ export class ModesContentHoverWidget extends ContentHoverWidget { this._isChangingDecorations = false; this._markdownRenderer = markdownRenderer; - markdownRenderer.onDidRenderCodeBlock(this.onContentsChange, this, this.toDispose); + this._register(markdownRenderer.onDidRenderCodeBlock(this.onContentsChange, this)); this._hoverOperation = new HoverOperation( this._computer, @@ -191,15 +190,15 @@ export class ModesContentHoverWidget extends ContentHoverWidget { result => this._withResult(result, false) ); - this.toDispose.push(dom.addStandardDisposableListener(this.getDomNode(), dom.EventType.FOCUS, () => { + this._register(dom.addStandardDisposableListener(this.getDomNode(), dom.EventType.FOCUS, () => { if (this._colorPicker) { dom.addClass(this.getDomNode(), 'colorpicker-hover'); } })); - this.toDispose.push(dom.addStandardDisposableListener(this.getDomNode(), dom.EventType.BLUR, () => { + this._register(dom.addStandardDisposableListener(this.getDomNode(), dom.EventType.BLUR, () => { dom.removeClass(this.getDomNode(), 'colorpicker-hover'); })); - this.toDispose.push(editor.onDidChangeConfiguration((e) => { + this._register(editor.onDidChangeConfiguration((e) => { this._hoverOperation.setHoverTime(this._editor.getConfiguration().contribInfo.hover.delay); })); } @@ -208,7 +207,6 @@ export class ModesContentHoverWidget extends ContentHoverWidget { this.renderDisposable.dispose(); this.renderDisposable = EmptyDisposable; this._hoverOperation.cancel(); - this.toDispose = dispose(this.toDispose); super.dispose(); } diff --git a/src/vs/platform/files/common/files.ts b/src/vs/platform/files/common/files.ts index c62cf489c50..72b73ed86d2 100644 --- a/src/vs/platform/files/common/files.ts +++ b/src/vs/platform/files/common/files.ts @@ -233,15 +233,15 @@ export class FileOperationEvent { constructor(private _resource: URI, private _operation: FileOperation, private _target?: IFileStat) { } - public get resource(): URI { + get resource(): URI { return this._resource; } - public get target(): IFileStat { + get target(): IFileStat { return this._target; } - public get operation(): FileOperation { + get operation(): FileOperation { return this._operation; } } @@ -279,7 +279,7 @@ export class FileChangesEvent { this._changes = changes; } - public get changes() { + get changes() { return this._changes; } @@ -288,7 +288,7 @@ export class FileChangesEvent { * type DELETED, this method will also return true if a folder got deleted that is the parent of the * provided file path. */ - public contains(resource: URI, type: FileChangeType): boolean { + contains(resource: URI, type: FileChangeType): boolean { if (!resource) { return false; } @@ -310,42 +310,42 @@ export class FileChangesEvent { /** * Returns the changes that describe added files. */ - public getAdded(): IFileChange[] { + getAdded(): IFileChange[] { return this.getOfType(FileChangeType.ADDED); } /** * Returns if this event contains added files. */ - public gotAdded(): boolean { + gotAdded(): boolean { return this.hasType(FileChangeType.ADDED); } /** * Returns the changes that describe deleted files. */ - public getDeleted(): IFileChange[] { + getDeleted(): IFileChange[] { return this.getOfType(FileChangeType.DELETED); } /** * Returns if this event contains deleted files. */ - public gotDeleted(): boolean { + gotDeleted(): boolean { return this.hasType(FileChangeType.DELETED); } /** * Returns the changes that describe updated files. */ - public getUpdated(): IFileChange[] { + getUpdated(): IFileChange[] { return this.getOfType(FileChangeType.UPDATED); } /** * Returns if this event contains updated files. */ - public gotUpdated(): boolean { + gotUpdated(): boolean { return this.hasType(FileChangeType.UPDATED); } diff --git a/src/vs/platform/history/electron-main/historyMainService.ts b/src/vs/platform/history/electron-main/historyMainService.ts index 556cae0126b..8b8dbc2fe10 100644 --- a/src/vs/platform/history/electron-main/historyMainService.ts +++ b/src/vs/platform/history/electron-main/historyMainService.ts @@ -57,7 +57,7 @@ export class HistoryMainService implements IHistoryMainService { this.addRecentlyOpened([e.workspace], []); } - public addRecentlyOpened(workspaces: (IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier)[], files: string[]): void { + addRecentlyOpened(workspaces: (IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier)[], files: string[]): void { if ((workspaces && workspaces.length > 0) || (files && files.length > 0)) { const mru = this.getRecentlyOpened(); @@ -100,7 +100,7 @@ export class HistoryMainService implements IHistoryMainService { } } - public removeFromRecentlyOpened(pathsToRemove: string[]): void { + removeFromRecentlyOpened(pathsToRemove: string[]): void { const mru = this.getRecentlyOpened(); let update = false; @@ -162,7 +162,7 @@ export class HistoryMainService implements IHistoryMainService { } } - public clearRecentlyOpened(): void { + clearRecentlyOpened(): void { this.saveRecentlyOpened({ workspaces: [], files: [] }); app.clearRecentDocuments(); @@ -170,7 +170,7 @@ export class HistoryMainService implements IHistoryMainService { this._onRecentlyOpenedChange.fire(); } - public getRecentlyOpened(currentWorkspace?: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier, currentFiles?: IPath[]): IRecentlyOpened { + getRecentlyOpened(currentWorkspace?: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier, currentFiles?: IPath[]): IRecentlyOpened { let workspaces: (IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier)[]; let files: string[]; @@ -216,7 +216,7 @@ export class HistoryMainService implements IHistoryMainService { this.stateService.setItem(HistoryMainService.recentlyOpenedStorageKey, recent); } - public updateWindowsJumpList(): void { + updateWindowsJumpList(): void { if (!isWindows) { return; // only on windows } diff --git a/src/vs/platform/lifecycle/electron-browser/lifecycleService.ts b/src/vs/platform/lifecycle/electron-browser/lifecycleService.ts index 4b6efd06abb..34c1b8e99a9 100644 --- a/src/vs/platform/lifecycle/electron-browser/lifecycleService.ts +++ b/src/vs/platform/lifecycle/electron-browser/lifecycleService.ts @@ -20,7 +20,7 @@ export class LifecycleService implements ILifecycleService { private static readonly _lastShutdownReasonKey = 'lifecyle.lastShutdownReason'; - public _serviceBrand: any; + _serviceBrand: any; private readonly _onWillShutdown = new Emitter(); private readonly _onShutdown = new Emitter(); @@ -95,11 +95,11 @@ export class LifecycleService implements ILifecycleService { return handleVetos(vetos, err => this._notificationService.error(toErrorMessage(err))); } - public get phase(): LifecyclePhase { + get phase(): LifecyclePhase { return this._phase; } - public set phase(value: LifecyclePhase) { + set phase(value: LifecyclePhase) { if (value < this.phase) { throw new Error('Lifecycle cannot go backwards'); } @@ -119,7 +119,7 @@ export class LifecycleService implements ILifecycleService { } } - public when(phase: LifecyclePhase): Thenable { + when(phase: LifecyclePhase): Thenable { if (phase <= this._phase) { return Promise.resolve(); } @@ -133,15 +133,15 @@ export class LifecycleService implements ILifecycleService { return barrier.wait(); } - public get startupKind(): StartupKind { + get startupKind(): StartupKind { return this._startupKind; } - public get onWillShutdown(): Event { + get onWillShutdown(): Event { return this._onWillShutdown.event; } - public get onShutdown(): Event { + get onShutdown(): Event { return this._onShutdown.event; } } diff --git a/src/vs/platform/lifecycle/electron-main/lifecycleMain.ts b/src/vs/platform/lifecycle/electron-main/lifecycleMain.ts index a2388d8fa49..118edffa98f 100644 --- a/src/vs/platform/lifecycle/electron-main/lifecycleMain.ts +++ b/src/vs/platform/lifecycle/electron-main/lifecycleMain.ts @@ -129,15 +129,15 @@ export class LifecycleService implements ILifecycleService { } } - public get wasRestarted(): boolean { + get wasRestarted(): boolean { return this._wasRestarted; } - public get isQuitRequested(): boolean { + get isQuitRequested(): boolean { return !!this.quitRequested; } - public ready(): void { + ready(): void { this.registerListeners(); } @@ -178,7 +178,7 @@ export class LifecycleService implements ILifecycleService { }); } - public registerWindow(window: ICodeWindow): void { + registerWindow(window: ICodeWindow): void { // track window count this.windowCounter++; @@ -232,7 +232,7 @@ export class LifecycleService implements ILifecycleService { }); } - public unload(window: ICodeWindow, reason: UnloadReason): TPromise { + unload(window: ICodeWindow, reason: UnloadReason): TPromise { // Always allow to unload a window that is not yet ready if (window.readyState !== ReadyState.READY) { @@ -326,7 +326,7 @@ export class LifecycleService implements ILifecycleService { * A promise that completes to indicate if the quit request has been veto'd * by the user or not. */ - public quit(fromUpdate?: boolean): TPromise { + quit(fromUpdate?: boolean): TPromise { this.logService.trace('Lifecycle#quit()'); if (!this.pendingQuitPromise) { @@ -362,13 +362,13 @@ export class LifecycleService implements ILifecycleService { return this.pendingQuitPromise; } - public kill(code?: number): void { + kill(code?: number): void { this.logService.trace('Lifecycle#kill()'); app.exit(code); } - public relaunch(options?: { addArgs?: string[], removeArgs?: string[] }): void { + relaunch(options?: { addArgs?: string[], removeArgs?: string[] }): void { this.logService.trace('Lifecycle#relaunch()'); const args = process.argv.slice(1); diff --git a/src/vs/platform/notification/common/notification.ts b/src/vs/platform/notification/common/notification.ts index 4b1315c077f..525d8f18a25 100644 --- a/src/vs/platform/notification/common/notification.ts +++ b/src/vs/platform/notification/common/notification.ts @@ -205,7 +205,7 @@ export class NoOpNotification implements INotificationHandle { private readonly _onDidClose: Emitter = new Emitter(); - public get onDidClose(): Event { + get onDidClose(): Event { return this._onDidClose.event; } diff --git a/src/vs/platform/state/node/stateService.ts b/src/vs/platform/state/node/stateService.ts index 12e1682db58..77d9c406d30 100644 --- a/src/vs/platform/state/node/stateService.ts +++ b/src/vs/platform/state/node/stateService.ts @@ -25,7 +25,7 @@ export class FileStorage { } } - public getItem(key: string, defaultValue?: T): T { + getItem(key: string, defaultValue?: T): T { this.ensureLoaded(); const res = this.database[key]; @@ -36,7 +36,7 @@ export class FileStorage { return res; } - public setItem(key: string, data: any): void { + setItem(key: string, data: any): void { this.ensureLoaded(); // Remove an item when it is undefined or null @@ -55,7 +55,7 @@ export class FileStorage { this.saveSync(); } - public removeItem(key: string): void { + removeItem(key: string): void { this.ensureLoaded(); // Only update if the key is actually present (not undefined) @@ -96,15 +96,15 @@ export class StateService implements IStateService { this.fileStorage = new FileStorage(path.join(environmentService.userDataPath, 'storage.json'), error => logService.error(error)); } - public getItem(key: string, defaultValue?: T): T { + getItem(key: string, defaultValue?: T): T { return this.fileStorage.getItem(key, defaultValue); } - public setItem(key: string, data: any): void { + setItem(key: string, data: any): void { this.fileStorage.setItem(key, data); } - public removeItem(key: string): void { + removeItem(key: string): void { this.fileStorage.removeItem(key); } } diff --git a/src/vs/platform/storage/common/storageService.ts b/src/vs/platform/storage/common/storageService.ts index a15769237a5..cd60f29cd2e 100644 --- a/src/vs/platform/storage/common/storageService.ts +++ b/src/vs/platform/storage/common/storageService.ts @@ -21,13 +21,13 @@ export interface IStorage { export class StorageService implements IStorageService { - public _serviceBrand: any; + _serviceBrand: any; - public static readonly COMMON_PREFIX = 'storage://'; - public static readonly GLOBAL_PREFIX = `${StorageService.COMMON_PREFIX}global/`; - public static readonly WORKSPACE_PREFIX = `${StorageService.COMMON_PREFIX}workspace/`; - public static readonly WORKSPACE_IDENTIFIER = 'workspaceidentifier'; - public static readonly NO_WORKSPACE_IDENTIFIER = '__$noWorkspace__'; + static readonly COMMON_PREFIX = 'storage://'; + static readonly GLOBAL_PREFIX = `${StorageService.COMMON_PREFIX}global/`; + static readonly WORKSPACE_PREFIX = `${StorageService.COMMON_PREFIX}workspace/`; + static readonly WORKSPACE_IDENTIFIER = 'workspaceidentifier'; + static readonly NO_WORKSPACE_IDENTIFIER = '__$noWorkspace__'; private _workspaceStorage: IStorage; private _globalStorage: IStorage; @@ -47,11 +47,11 @@ export class StorageService implements IStorageService { this.setWorkspaceId(workspaceId, legacyWorkspaceId); } - public get workspaceId(): string { + get workspaceId(): string { return this._workspaceId; } - public setWorkspaceId(workspaceId: string, legacyWorkspaceId?: number): void { + setWorkspaceId(workspaceId: string, legacyWorkspaceId?: number): void { this._workspaceId = workspaceId; // Calculate workspace storage key @@ -64,11 +64,11 @@ export class StorageService implements IStorageService { } } - public get globalStorage(): IStorage { + get globalStorage(): IStorage { return this._globalStorage; } - public get workspaceStorage(): IStorage { + get workspaceStorage(): IStorage { return this._workspaceStorage; } @@ -124,7 +124,7 @@ export class StorageService implements IStorageService { } } - public store(key: string, value: any, scope = StorageScope.GLOBAL): void { + store(key: string, value: any, scope = StorageScope.GLOBAL): void { const storage = (scope === StorageScope.GLOBAL) ? this._globalStorage : this._workspaceStorage; if (types.isUndefinedOrNull(value)) { @@ -142,7 +142,7 @@ export class StorageService implements IStorageService { } } - public get(key: string, scope = StorageScope.GLOBAL, defaultValue?: any): string { + get(key: string, scope = StorageScope.GLOBAL, defaultValue?: any): string { const storage = (scope === StorageScope.GLOBAL) ? this._globalStorage : this._workspaceStorage; const value = storage.getItem(this.toStorageKey(key, scope)); @@ -153,7 +153,7 @@ export class StorageService implements IStorageService { return value; } - public getInteger(key: string, scope = StorageScope.GLOBAL, defaultValue?: number): number { + getInteger(key: string, scope = StorageScope.GLOBAL, defaultValue?: number): number { const value = this.get(key, scope, defaultValue); if (types.isUndefinedOrNull(value)) { @@ -163,7 +163,7 @@ export class StorageService implements IStorageService { return parseInt(value, 10); } - public getBoolean(key: string, scope = StorageScope.GLOBAL, defaultValue?: boolean): boolean { + getBoolean(key: string, scope = StorageScope.GLOBAL, defaultValue?: boolean): boolean { const value = this.get(key, scope, defaultValue); if (types.isUndefinedOrNull(value)) { @@ -177,7 +177,7 @@ export class StorageService implements IStorageService { return value ? true : false; } - public remove(key: string, scope = StorageScope.GLOBAL): void { + remove(key: string, scope = StorageScope.GLOBAL): void { const storage = (scope === StorageScope.GLOBAL) ? this._globalStorage : this._workspaceStorage; const storageKey = this.toStorageKey(key, scope); @@ -201,11 +201,11 @@ export class InMemoryLocalStorage implements IStorage { this.store = {}; } - public get length() { + get length() { return Object.keys(this.store).length; } - public key(index: number): string { + key(index: number): string { const keys = Object.keys(this.store); if (keys.length > index) { return keys[index]; @@ -214,11 +214,11 @@ export class InMemoryLocalStorage implements IStorage { return null; } - public setItem(key: string, value: any): void { + setItem(key: string, value: any): void { this.store[key] = value.toString(); } - public getItem(key: string): string { + getItem(key: string): string { const item = this.store[key]; if (!types.isUndefinedOrNull(item)) { return item; @@ -227,7 +227,7 @@ export class InMemoryLocalStorage implements IStorage { return null; } - public removeItem(key: string): void { + removeItem(key: string): void { delete this.store[key]; } } diff --git a/src/vs/platform/workspace/common/workspace.ts b/src/vs/platform/workspace/common/workspace.ts index b9b31f4b2a0..2263c848f17 100644 --- a/src/vs/platform/workspace/common/workspace.ts +++ b/src/vs/platform/workspace/common/workspace.ts @@ -141,7 +141,7 @@ export class Workspace implements IWorkspace { this.folders = folders; } - public update(workspace: Workspace) { + update(workspace: Workspace) { this._id = workspace.id; this._name = workspace.name; this._configuration = workspace.configuration; @@ -149,40 +149,40 @@ export class Workspace implements IWorkspace { this.folders = workspace.folders; } - public get folders(): WorkspaceFolder[] { + get folders(): WorkspaceFolder[] { return this._folders; } - public set folders(folders: WorkspaceFolder[]) { + set folders(folders: WorkspaceFolder[]) { this._folders = folders; this.updateFoldersMap(); } - public get id(): string { + get id(): string { return this._id; } - public get ctime(): number { + get ctime(): number { return this._ctime; } - public get name(): string { + get name(): string { return this._name; } - public set name(name: string) { + set name(name: string) { this._name = name; } - public get configuration(): URI { + get configuration(): URI { return this._configuration; } - public set configuration(configuration: URI) { + set configuration(configuration: URI) { this._configuration = configuration; } - public getFolder(resource: URI): IWorkspaceFolder { + getFolder(resource: URI): IWorkspaceFolder { if (!resource) { return null; } @@ -197,7 +197,7 @@ export class Workspace implements IWorkspace { } } - public toJSON(): IWorkspace { + toJSON(): IWorkspace { return { id: this.id, folders: this.folders, name: this.name, configuration: this.configuration }; } } diff --git a/src/vs/platform/workspaces/common/workspacesIpc.ts b/src/vs/platform/workspaces/common/workspacesIpc.ts index 91257d6d12e..898f9d43a29 100644 --- a/src/vs/platform/workspaces/common/workspacesIpc.ts +++ b/src/vs/platform/workspaces/common/workspacesIpc.ts @@ -19,7 +19,7 @@ export class WorkspacesChannel implements IWorkspacesChannel { constructor(private service: IWorkspacesMainService) { } - public call(command: string, arg?: any): TPromise { + call(command: string, arg?: any): TPromise { switch (command) { case 'createWorkspace': { const rawFolders: IWorkspaceFolderCreationData[] = arg; @@ -47,7 +47,7 @@ export class WorkspacesChannelClient implements IWorkspacesService { constructor(private channel: IWorkspacesChannel) { } - public createWorkspace(folders?: IWorkspaceFolderCreationData[]): TPromise { + createWorkspace(folders?: IWorkspaceFolderCreationData[]): TPromise { return this.channel.call('createWorkspace', folders); } } \ No newline at end of file diff --git a/src/vs/platform/workspaces/electron-main/workspacesMainService.ts b/src/vs/platform/workspaces/electron-main/workspacesMainService.ts index ee75f03a42a..45a50ab6543 100644 --- a/src/vs/platform/workspaces/electron-main/workspacesMainService.ts +++ b/src/vs/platform/workspaces/electron-main/workspacesMainService.ts @@ -33,7 +33,7 @@ export interface IStoredWorkspace { export class WorkspacesMainService implements IWorkspacesMainService { - public _serviceBrand: any; + _serviceBrand: any; protected workspacesHome: string; @@ -50,15 +50,15 @@ export class WorkspacesMainService implements IWorkspacesMainService { this._onUntitledWorkspaceDeleted = new Emitter(); } - public get onWorkspaceSaved(): Event { + get onWorkspaceSaved(): Event { return this._onWorkspaceSaved.event; } - public get onUntitledWorkspaceDeleted(): Event { + get onUntitledWorkspaceDeleted(): Event { return this._onUntitledWorkspaceDeleted.event; } - public resolveWorkspaceSync(path: string): IResolvedWorkspace { + resolveWorkspaceSync(path: string): IResolvedWorkspace { if (!this.isWorkspacePath(path)) { return null; // does not look like a valid workspace config file } @@ -115,7 +115,7 @@ export class WorkspacesMainService implements IWorkspacesMainService { return isParent(path, this.environmentService.workspacesHome, !isLinux /* ignore case */); } - public createWorkspace(folders?: IWorkspaceFolderCreationData[]): TPromise { + createWorkspace(folders?: IWorkspaceFolderCreationData[]): TPromise { const { workspace, configParent, storedWorkspace } = this.createUntitledWorkspace(folders); return mkdirp(configParent).then(() => { @@ -123,7 +123,7 @@ export class WorkspacesMainService implements IWorkspacesMainService { }); } - public createWorkspaceSync(folders?: IWorkspaceFolderCreationData[]): IWorkspaceIdentifier { + createWorkspaceSync(folders?: IWorkspaceFolderCreationData[]): IWorkspaceIdentifier { const { workspace, configParent, storedWorkspace } = this.createUntitledWorkspace(folders); if (!existsSync(this.workspacesHome)) { @@ -175,7 +175,7 @@ export class WorkspacesMainService implements IWorkspacesMainService { }; } - public getWorkspaceId(workspaceConfigPath: string): string { + getWorkspaceId(workspaceConfigPath: string): string { if (!isLinux) { workspaceConfigPath = workspaceConfigPath.toLowerCase(); // sanitize for platform file system } @@ -183,11 +183,11 @@ export class WorkspacesMainService implements IWorkspacesMainService { return createHash('md5').update(workspaceConfigPath).digest('hex'); } - public isUntitledWorkspace(workspace: IWorkspaceIdentifier): boolean { + isUntitledWorkspace(workspace: IWorkspaceIdentifier): boolean { return this.isInsideWorkspacesHome(workspace.configPath); } - public saveWorkspace(workspace: IWorkspaceIdentifier, targetConfigPath: string): TPromise { + saveWorkspace(workspace: IWorkspaceIdentifier, targetConfigPath: string): TPromise { // Return early if target is same as source if (isEqual(workspace.configPath, targetConfigPath, !isLinux)) { @@ -242,7 +242,7 @@ export class WorkspacesMainService implements IWorkspacesMainService { }); } - public deleteUntitledWorkspaceSync(workspace: IWorkspaceIdentifier): void { + deleteUntitledWorkspaceSync(workspace: IWorkspaceIdentifier): void { if (!this.isUntitledWorkspace(workspace)) { return; // only supported for untitled workspaces } @@ -262,7 +262,7 @@ export class WorkspacesMainService implements IWorkspacesMainService { } } - public getUntitledWorkspacesSync(): IWorkspaceIdentifier[] { + getUntitledWorkspacesSync(): IWorkspaceIdentifier[] { let untitledWorkspacePaths: string[] = []; try { untitledWorkspacePaths = readdirSync(this.workspacesHome).map(folder => join(this.workspacesHome, folder, UNTITLED_WORKSPACE_NAME)); diff --git a/src/vs/workbench/browser/actions.ts b/src/vs/workbench/browser/actions.ts index 8538ba3afdb..12ec83d310b 100644 --- a/src/vs/workbench/browser/actions.ts +++ b/src/vs/workbench/browser/actions.ts @@ -20,35 +20,35 @@ export class ActionBarContributor { /** * Returns true if this contributor has actions for the given context. */ - public hasActions(context: any): boolean { + hasActions(context: any): boolean { return false; } /** * Returns an array of primary actions in the given context. */ - public getActions(context: any): IAction[] { + getActions(context: any): IAction[] { return []; } /** * Returns true if this contributor has secondary actions for the given context. */ - public hasSecondaryActions(context: any): boolean { + hasSecondaryActions(context: any): boolean { return false; } /** * Returns an array of secondary actions in the given context. */ - public getSecondaryActions(context: any): IAction[] { + getSecondaryActions(context: any): IAction[] { return []; } /** * Can return a specific IActionItem to render the given action. */ - public getActionItem(context: any, action: Action): BaseActionItem { + getActionItem(context: any, action: Action): BaseActionItem { return null; } } @@ -80,7 +80,7 @@ export class ContributableActionProvider implements IActionProvider { }; } - public hasActions(tree: ITree, element: any): boolean { + hasActions(tree: ITree, element: any): boolean { const context = this.toContext(tree, element); const contributors = this.registry.getActionBarContributors(Scope.VIEWER); @@ -94,7 +94,7 @@ export class ContributableActionProvider implements IActionProvider { return false; } - public getActions(tree: ITree, element: any): TPromise { + getActions(tree: ITree, element: any): TPromise { const actions: IAction[] = []; const context = this.toContext(tree, element); @@ -110,7 +110,7 @@ export class ContributableActionProvider implements IActionProvider { return TPromise.as(prepareActions(actions)); } - public hasSecondaryActions(tree: ITree, element: any): boolean { + hasSecondaryActions(tree: ITree, element: any): boolean { const context = this.toContext(tree, element); const contributors = this.registry.getActionBarContributors(Scope.VIEWER); @@ -124,7 +124,7 @@ export class ContributableActionProvider implements IActionProvider { return false; } - public getSecondaryActions(tree: ITree, element: any): TPromise { + getSecondaryActions(tree: ITree, element: any): TPromise { const actions: IAction[] = []; const context = this.toContext(tree, element); @@ -140,7 +140,7 @@ export class ContributableActionProvider implements IActionProvider { return TPromise.as(prepareActions(actions)); } - public getActionItem(tree: ITree, element: any, action: Action): BaseActionItem { + getActionItem(tree: ITree, element: any, action: Action): BaseActionItem { const contributors = this.registry.getActionBarContributors(Scope.VIEWER); const context = this.toContext(tree, element); @@ -279,7 +279,7 @@ class ActionBarRegistry implements IActionBarRegistry { private actionBarContributorInstances: { [scope: string]: ActionBarContributor[] } = Object.create(null); private instantiationService: IInstantiationService; - public setInstantiationService(service: IInstantiationService): void { + setInstantiationService(service: IInstantiationService): void { this.instantiationService = service; while (this.actionBarContributorConstructors.length > 0) { @@ -301,7 +301,7 @@ class ActionBarRegistry implements IActionBarRegistry { return this.actionBarContributorInstances[scope] || []; } - public getActionBarActionsForContext(scope: string, context: any): IAction[] { + getActionBarActionsForContext(scope: string, context: any): IAction[] { const actions: IAction[] = []; // Go through contributors for scope @@ -316,7 +316,7 @@ class ActionBarRegistry implements IActionBarRegistry { return actions; } - public getSecondaryActionBarActionsForContext(scope: string, context: any): IAction[] { + getSecondaryActionBarActionsForContext(scope: string, context: any): IAction[] { const actions: IAction[] = []; // Go through contributors @@ -331,7 +331,7 @@ class ActionBarRegistry implements IActionBarRegistry { return actions; } - public getActionItemForContext(scope: string, context: any, action: Action): BaseActionItem { + getActionItemForContext(scope: string, context: any, action: Action): BaseActionItem { const contributors = this.getContributors(scope); for (let i = 0; i < contributors.length; i++) { const contributor = contributors[i]; @@ -344,7 +344,7 @@ class ActionBarRegistry implements IActionBarRegistry { return null; } - public registerActionBarContributor(scope: string, ctor: IConstructorSignature0): void { + registerActionBarContributor(scope: string, ctor: IConstructorSignature0): void { if (!this.instantiationService) { this.actionBarContributorConstructors.push({ scope: scope, @@ -355,7 +355,7 @@ class ActionBarRegistry implements IActionBarRegistry { } } - public getActionBarContributors(scope: string): ActionBarContributor[] { + getActionBarContributors(scope: string): ActionBarContributor[] { return this.getContributors(scope).slice(0); } } diff --git a/src/vs/workbench/browser/actions/toggleActivityBarVisibility.ts b/src/vs/workbench/browser/actions/toggleActivityBarVisibility.ts index 3018aeda0d8..bb784e89472 100644 --- a/src/vs/workbench/browser/actions/toggleActivityBarVisibility.ts +++ b/src/vs/workbench/browser/actions/toggleActivityBarVisibility.ts @@ -15,8 +15,8 @@ import { IPartService, Parts } from 'vs/workbench/services/part/common/partServi export class ToggleActivityBarVisibilityAction extends Action { - public static readonly ID = 'workbench.action.toggleActivityBarVisibility'; - public static readonly LABEL = nls.localize('toggleActivityBar', "Toggle Activity Bar Visibility"); + static readonly ID = 'workbench.action.toggleActivityBarVisibility'; + static readonly LABEL = nls.localize('toggleActivityBar', "Toggle Activity Bar Visibility"); private static readonly activityBarVisibleKey = 'workbench.activityBar.visible'; @@ -31,7 +31,7 @@ export class ToggleActivityBarVisibilityAction extends Action { this.enabled = !!this.partService; } - public run(): TPromise { + run(): TPromise { const visibility = this.partService.isVisible(Parts.ACTIVITYBAR_PART); const newVisibilityValue = !visibility; diff --git a/src/vs/workbench/browser/actions/toggleCenteredLayout.ts b/src/vs/workbench/browser/actions/toggleCenteredLayout.ts index 663541555e4..2ab19d4ca4d 100644 --- a/src/vs/workbench/browser/actions/toggleCenteredLayout.ts +++ b/src/vs/workbench/browser/actions/toggleCenteredLayout.ts @@ -13,8 +13,8 @@ import { IPartService } from 'vs/workbench/services/part/common/partService'; class ToggleCenteredLayout extends Action { - public static readonly ID = 'workbench.action.toggleCenteredLayout'; - public static readonly LABEL = nls.localize('toggleCenteredLayout', "Toggle Centered Layout"); + static readonly ID = 'workbench.action.toggleCenteredLayout'; + static readonly LABEL = nls.localize('toggleCenteredLayout', "Toggle Centered Layout"); constructor( id: string, @@ -25,7 +25,7 @@ class ToggleCenteredLayout extends Action { this.enabled = !!this.partService; } - public run(): TPromise { + run(): TPromise { this.partService.centerEditorLayout(!this.partService.isEditorLayoutCentered()); return TPromise.as(null); diff --git a/src/vs/workbench/browser/actions/toggleEditorLayout.ts b/src/vs/workbench/browser/actions/toggleEditorLayout.ts index 1e57dc2392a..8f553a8fa22 100644 --- a/src/vs/workbench/browser/actions/toggleEditorLayout.ts +++ b/src/vs/workbench/browser/actions/toggleEditorLayout.ts @@ -19,8 +19,8 @@ import { IEditorGroupsService, GroupOrientation } from 'vs/workbench/services/gr export class ToggleEditorLayoutAction extends Action { - public static readonly ID = 'workbench.action.toggleEditorGroupLayout'; - public static readonly LABEL = nls.localize('flipLayout', "Toggle Vertical/Horizontal Editor Layout"); + static readonly ID = 'workbench.action.toggleEditorGroupLayout'; + static readonly LABEL = nls.localize('flipLayout', "Toggle Vertical/Horizontal Editor Layout"); private toDispose: IDisposable[]; @@ -48,14 +48,14 @@ export class ToggleEditorLayoutAction extends Action { this.enabled = this.editorGroupService.count > 1; } - public run(): TPromise { + run(): TPromise { const newOrientation = (this.editorGroupService.orientation === GroupOrientation.VERTICAL) ? GroupOrientation.HORIZONTAL : GroupOrientation.VERTICAL; this.editorGroupService.setGroupOrientation(newOrientation); return TPromise.as(null); } - public dispose(): void { + dispose(): void { this.toDispose = dispose(this.toDispose); super.dispose(); diff --git a/src/vs/workbench/browser/actions/toggleSidebarPosition.ts b/src/vs/workbench/browser/actions/toggleSidebarPosition.ts index b0a223a0ab6..3de25a53e7e 100644 --- a/src/vs/workbench/browser/actions/toggleSidebarPosition.ts +++ b/src/vs/workbench/browser/actions/toggleSidebarPosition.ts @@ -15,8 +15,8 @@ import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configur export class ToggleSidebarPositionAction extends Action { - public static readonly ID = 'workbench.action.toggleSidebarPosition'; - public static readonly LABEL = nls.localize('toggleSidebarPosition', "Toggle Side Bar Position"); + static readonly ID = 'workbench.action.toggleSidebarPosition'; + static readonly LABEL = nls.localize('toggleSidebarPosition', "Toggle Side Bar Position"); private static readonly sidebarPositionConfigurationKey = 'workbench.sideBar.location'; @@ -31,7 +31,7 @@ export class ToggleSidebarPositionAction extends Action { this.enabled = !!this.partService && !!this.configurationService; } - public run(): TPromise { + run(): TPromise { const position = this.partService.getSideBarPosition(); const newPositionValue = (position === Position.LEFT) ? 'right' : 'left'; diff --git a/src/vs/workbench/browser/actions/toggleSidebarVisibility.ts b/src/vs/workbench/browser/actions/toggleSidebarVisibility.ts index 72afba76346..95f4d8a21e8 100644 --- a/src/vs/workbench/browser/actions/toggleSidebarVisibility.ts +++ b/src/vs/workbench/browser/actions/toggleSidebarVisibility.ts @@ -15,8 +15,8 @@ import { KeyMod, KeyCode } from 'vs/base/common/keyCodes'; export class ToggleSidebarVisibilityAction extends Action { - public static readonly ID = 'workbench.action.toggleSidebarVisibility'; - public static readonly LABEL = nls.localize('toggleSidebar', "Toggle Side Bar Visibility"); + static readonly ID = 'workbench.action.toggleSidebarVisibility'; + static readonly LABEL = nls.localize('toggleSidebar', "Toggle Side Bar Visibility"); constructor( id: string, @@ -28,7 +28,7 @@ export class ToggleSidebarVisibilityAction extends Action { this.enabled = !!this.partService; } - public run(): TPromise { + run(): TPromise { const hideSidebar = this.partService.isVisible(Parts.SIDEBAR_PART); return this.partService.setSideBarHidden(hideSidebar); } diff --git a/src/vs/workbench/browser/actions/toggleStatusbarVisibility.ts b/src/vs/workbench/browser/actions/toggleStatusbarVisibility.ts index da09591e2d0..2fe83369bb8 100644 --- a/src/vs/workbench/browser/actions/toggleStatusbarVisibility.ts +++ b/src/vs/workbench/browser/actions/toggleStatusbarVisibility.ts @@ -15,8 +15,8 @@ import { IPartService, Parts } from 'vs/workbench/services/part/common/partServi export class ToggleStatusbarVisibilityAction extends Action { - public static readonly ID = 'workbench.action.toggleStatusbarVisibility'; - public static readonly LABEL = nls.localize('toggleStatusbar', "Toggle Status Bar Visibility"); + static readonly ID = 'workbench.action.toggleStatusbarVisibility'; + static readonly LABEL = nls.localize('toggleStatusbar', "Toggle Status Bar Visibility"); private static readonly statusbarVisibleKey = 'workbench.statusBar.visible'; @@ -31,7 +31,7 @@ export class ToggleStatusbarVisibilityAction extends Action { this.enabled = !!this.partService; } - public run(): TPromise { + run(): TPromise { const visibility = this.partService.isVisible(Parts.STATUSBAR_PART); const newVisibilityValue = !visibility; diff --git a/src/vs/workbench/browser/actions/toggleTabsVisibility.ts b/src/vs/workbench/browser/actions/toggleTabsVisibility.ts index 9bf5df9e7a3..ebfb647ffab 100644 --- a/src/vs/workbench/browser/actions/toggleTabsVisibility.ts +++ b/src/vs/workbench/browser/actions/toggleTabsVisibility.ts @@ -15,8 +15,8 @@ import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; export class ToggleTabsVisibilityAction extends Action { - public static readonly ID = 'workbench.action.toggleTabsVisibility'; - public static readonly LABEL = nls.localize('toggleTabs', "Toggle Tab Visibility"); + static readonly ID = 'workbench.action.toggleTabsVisibility'; + static readonly LABEL = nls.localize('toggleTabs', "Toggle Tab Visibility"); private static readonly tabsVisibleKey = 'workbench.editor.showTabs'; @@ -28,7 +28,7 @@ export class ToggleTabsVisibilityAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { const visibility = this.configurationService.getValue(ToggleTabsVisibilityAction.tabsVisibleKey); const newVisibilityValue = !visibility; diff --git a/src/vs/workbench/browser/actions/toggleZenMode.ts b/src/vs/workbench/browser/actions/toggleZenMode.ts index 3d58623c10c..955a69799ce 100644 --- a/src/vs/workbench/browser/actions/toggleZenMode.ts +++ b/src/vs/workbench/browser/actions/toggleZenMode.ts @@ -14,8 +14,8 @@ import { IPartService } from 'vs/workbench/services/part/common/partService'; class ToggleZenMode extends Action { - public static readonly ID = 'workbench.action.toggleZenMode'; - public static readonly LABEL = nls.localize('toggleZenMode', "Toggle Zen Mode"); + static readonly ID = 'workbench.action.toggleZenMode'; + static readonly LABEL = nls.localize('toggleZenMode', "Toggle Zen Mode"); constructor( id: string, @@ -26,7 +26,7 @@ class ToggleZenMode extends Action { this.enabled = !!this.partService; } - public run(): TPromise { + run(): TPromise { this.partService.toggleZenMode(); return TPromise.as(null); } diff --git a/src/vs/workbench/browser/actions/workspaceActions.ts b/src/vs/workbench/browser/actions/workspaceActions.ts index a916997520c..bf7b0adc209 100644 --- a/src/vs/workbench/browser/actions/workspaceActions.ts +++ b/src/vs/workbench/browser/actions/workspaceActions.ts @@ -93,7 +93,7 @@ export class AddRootFolderAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { return this.commandService.executeCommand(ADD_ROOT_FOLDER_COMMAND_ID); } } @@ -113,7 +113,7 @@ export class GlobalRemoveRootFolderAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { const state = this.contextService.getWorkbenchState(); // Workspace / Folder @@ -148,7 +148,7 @@ export class SaveWorkspaceAsAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { return this.getNewWorkspaceConfigPath().then(configPath => { if (configPath) { switch (this.contextService.getWorkbenchState()) { @@ -192,15 +192,15 @@ export class OpenWorkspaceAction extends Action { super(id, label); } - public run(event?: any, data?: ITelemetryData): TPromise { + run(event?: any, data?: ITelemetryData): TPromise { return this.windowService.pickWorkspaceAndOpen({ telemetryExtraData: data, dialogOptions: { defaultPath: defaultWorkspacePath(this.contextService, this.historyService, this.environmentService) } }); } } export class OpenWorkspaceConfigFileAction extends Action { - public static readonly ID = 'workbench.action.openWorkspaceConfigFile'; - public static readonly LABEL = nls.localize('openWorkspaceConfigFile', "Open Workspace Configuration File"); + static readonly ID = 'workbench.action.openWorkspaceConfigFile'; + static readonly LABEL = nls.localize('openWorkspaceConfigFile', "Open Workspace Configuration File"); constructor( id: string, @@ -213,15 +213,15 @@ export class OpenWorkspaceConfigFileAction extends Action { this.enabled = !!this.workspaceContextService.getWorkspace().configuration; } - public run(): TPromise { + run(): TPromise { return this.editorService.openEditor({ resource: this.workspaceContextService.getWorkspace().configuration }); } } export class DuplicateWorkspaceInNewWindowAction extends Action { - public static readonly ID = 'workbench.action.duplicateWorkspaceInNewWindow'; - public static readonly LABEL = nls.localize('duplicateWorkspaceInNewWindow', "Duplicate Workspace in New Window"); + static readonly ID = 'workbench.action.duplicateWorkspaceInNewWindow'; + static readonly LABEL = nls.localize('duplicateWorkspaceInNewWindow', "Duplicate Workspace in New Window"); constructor( id: string, @@ -234,7 +234,7 @@ export class DuplicateWorkspaceInNewWindowAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { const folders = this.workspaceContextService.getWorkspace().folders; return this.workspacesService.createWorkspace(folders).then(newWorkspace => { diff --git a/src/vs/workbench/browser/composite.ts b/src/vs/workbench/browser/composite.ts index 006fcc3c3a5..390f7f51b9d 100644 --- a/src/vs/workbench/browser/composite.ts +++ b/src/vs/workbench/browser/composite.ts @@ -12,8 +12,7 @@ import { IComposite, ICompositeControl } from 'vs/workbench/common/composite'; import { Event, Emitter } from 'vs/base/common/event'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IConstructorSignature0, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; -import { IDisposable } from 'vs/base/common/lifecycle'; -import { IFocusTracker, trackFocus, Dimension } from 'vs/base/browser/dom'; +import { trackFocus, Dimension } from 'vs/base/browser/dom'; /** * Composites are layed out in the sidebar and panel part of the workbench. At a time only one composite @@ -26,17 +25,27 @@ import { IFocusTracker, trackFocus, Dimension } from 'vs/base/browser/dom'; * layout and focus call, but only one create and dispose call. */ export abstract class Composite extends Component implements IComposite { - private readonly _onTitleAreaUpdate: Emitter; - private readonly _onDidFocus: Emitter; - private _focusTracker?: IFocusTracker; - private _focusListenerDisposable?: IDisposable; + private readonly _onTitleAreaUpdate: Emitter = this._register(new Emitter()); + get onTitleAreaUpdate(): Event { return this._onTitleAreaUpdate.event; } + + private _onDidFocus: Emitter; + get onDidFocus(): Event { + if (!this._onDidFocus) { + this._onDidFocus = this._register(new Emitter()); + + const focusTracker = this._register(trackFocus(this.getContainer())); + this._register(focusTracker.onDidFocus(() => this._onDidFocus.fire())); + } + + return this._onDidFocus.event; + } + + protected actionRunner: IActionRunner; private visible: boolean; private parent: HTMLElement; - protected actionRunner: IActionRunner; - /** * Create a new composite with the given ID and context. */ @@ -48,11 +57,9 @@ export abstract class Composite extends Component implements IComposite { super(id, themeService); this.visible = false; - this._onTitleAreaUpdate = new Emitter(); - this._onDidFocus = new Emitter(); } - public getTitle(): string { + getTitle(): string { return null; } @@ -60,10 +67,6 @@ export abstract class Composite extends Component implements IComposite { return this._telemetryService; } - public get onTitleAreaUpdate(): Event { - return this._onTitleAreaUpdate.event; - } - /** * Note: Clients should not call this method, the workbench calls this * method. Calling it otherwise may result in unexpected behavior. @@ -73,31 +76,23 @@ export abstract class Composite extends Component implements IComposite { * Note that DOM-dependent calculations should be performed from the setVisible() * call. Only then the composite will be part of the DOM. */ - public create(parent: HTMLElement): TPromise { + create(parent: HTMLElement): TPromise { this.parent = parent; return TPromise.as(null); } - public updateStyles(): void { + updateStyles(): void { super.updateStyles(); } /** * Returns the container this composite is being build in. */ - public getContainer(): HTMLElement { + getContainer(): HTMLElement { return this.parent; } - public get onDidFocus(): Event { - this._focusTracker = trackFocus(this.getContainer()); - this._focusListenerDisposable = this._focusTracker.onDidFocus(() => { - this._onDidFocus.fire(); - }); - return this._onDidFocus.event; - } - /** * Note: Clients should not call this method, the workbench calls this * method. Calling it otherwise may result in unexpected behavior. @@ -110,7 +105,7 @@ export abstract class Composite extends Component implements IComposite { * to do a long running operation from this call. Typically this operation should be * fast though because setVisible might be called many times during a session. */ - public setVisible(visible: boolean): TPromise { + setVisible(visible: boolean): TPromise { this.visible = visible; return TPromise.as(null); @@ -119,19 +114,19 @@ export abstract class Composite extends Component implements IComposite { /** * Called when this composite should receive keyboard focus. */ - public focus(): void { + focus(): void { // Subclasses can implement } /** * Layout the contents of this composite using the provided dimensions. */ - public abstract layout(dimension: Dimension): void; + abstract layout(dimension: Dimension): void; /** * Returns an array of actions to show in the action bar of the composite. */ - public getActions(): IAction[] { + getActions(): IAction[] { return []; } @@ -139,14 +134,14 @@ export abstract class Composite extends Component implements IComposite { * Returns an array of actions to show in the action bar of the composite * in a less prominent way then action from getActions. */ - public getSecondaryActions(): IAction[] { + getSecondaryActions(): IAction[] { return []; } /** * Returns an array of actions to show in the context menu of the composite */ - public getContextMenuActions(): IAction[] { + getContextMenuActions(): IAction[] { return []; } @@ -156,7 +151,7 @@ export abstract class Composite extends Component implements IComposite { * of an action. Returns null to indicate that the action is not rendered through * an action item. */ - public getActionItem(action: IAction): IActionItem { + getActionItem(action: IAction): IActionItem { return null; } @@ -164,7 +159,7 @@ export abstract class Composite extends Component implements IComposite { * Returns the instance of IActionRunner to use with this composite for the * composite tool bar. */ - public getActionRunner(): IActionRunner { + getActionRunner(): IActionRunner { if (!this.actionRunner) { this.actionRunner = new ActionRunner(); } @@ -185,43 +180,28 @@ export abstract class Composite extends Component implements IComposite { /** * Returns true if this composite is currently visible and false otherwise. */ - public isVisible(): boolean { + isVisible(): boolean { return this.visible; } /** * Returns the underlying composite control or null if it is not accessible. */ - public getControl(): ICompositeControl { + getControl(): ICompositeControl { return null; } - - public dispose(): void { - this._onTitleAreaUpdate.dispose(); - this._onDidFocus.dispose(); - - if (this._focusTracker) { - this._focusTracker.dispose(); - } - - if (this._focusListenerDisposable) { - this._focusListenerDisposable.dispose(); - } - - super.dispose(); - } } /** * A composite descriptor is a leightweight descriptor of a composite in the workbench. */ export abstract class CompositeDescriptor { - public id: string; - public name: string; - public cssClass: string; - public order: number; - public keybindingId: string; - public enabled: boolean; + id: string; + name: string; + cssClass: string; + order: number; + keybindingId: string; + enabled: boolean; private ctor: IConstructorSignature0; @@ -235,7 +215,7 @@ export abstract class CompositeDescriptor { this.keybindingId = keybindingId; } - public instantiate(instantiationService: IInstantiationService): T { + instantiate(instantiationService: IInstantiationService): T { return instantiationService.createInstance(this.ctor); } } @@ -243,13 +223,9 @@ export abstract class CompositeDescriptor { export abstract class CompositeRegistry { private readonly _onDidRegister: Emitter> = new Emitter>(); - readonly onDidRegister: Event> = this._onDidRegister.event; + get onDidRegister(): Event> { return this._onDidRegister.event; } - private composites: CompositeDescriptor[]; - - constructor() { - this.composites = []; - } + private composites: CompositeDescriptor[] = []; protected registerComposite(descriptor: CompositeDescriptor): void { if (this.compositeById(descriptor.id) !== null) { @@ -260,7 +236,7 @@ export abstract class CompositeRegistry { this._onDidRegister.fire(descriptor); } - public getComposite(id: string): CompositeDescriptor { + getComposite(id: string): CompositeDescriptor { return this.compositeById(id); } diff --git a/src/vs/workbench/browser/editor.ts b/src/vs/workbench/browser/editor.ts index 525a263c59f..0b3c009786a 100644 --- a/src/vs/workbench/browser/editor.ts +++ b/src/vs/workbench/browser/editor.ts @@ -66,19 +66,19 @@ export class EditorDescriptor implements IEditorDescriptor { this.name = name; } - public instantiate(instantiationService: IInstantiationService): BaseEditor { + instantiate(instantiationService: IInstantiationService): BaseEditor { return instantiationService.createInstance(this.ctor); } - public getId(): string { + getId(): string { return this.id; } - public getName(): string { + getName(): string { return this.name; } - public describes(obj: any): boolean { + describes(obj: any): boolean { return obj instanceof BaseEditor && (obj).getId() === this.id; } } @@ -86,15 +86,11 @@ export class EditorDescriptor implements IEditorDescriptor { const INPUT_DESCRIPTORS_PROPERTY = '__$inputDescriptors'; class EditorRegistry implements IEditorRegistry { - private editors: EditorDescriptor[]; + private editors: EditorDescriptor[] = []; - constructor() { - this.editors = []; - } - - public registerEditor(descriptor: EditorDescriptor, editorInputDescriptor: SyncDescriptor): void; - public registerEditor(descriptor: EditorDescriptor, editorInputDescriptor: SyncDescriptor[]): void; - public registerEditor(descriptor: EditorDescriptor, editorInputDescriptor: any): void { + registerEditor(descriptor: EditorDescriptor, editorInputDescriptor: SyncDescriptor): void; + registerEditor(descriptor: EditorDescriptor, editorInputDescriptor: SyncDescriptor[]): void; + registerEditor(descriptor: EditorDescriptor, editorInputDescriptor: any): void { // Support both non-array and array parameter let inputDescriptors: SyncDescriptor[] = []; @@ -109,7 +105,7 @@ class EditorRegistry implements IEditorRegistry { this.editors.push(descriptor); } - public getEditor(input: EditorInput): EditorDescriptor { + getEditor(input: EditorInput): EditorDescriptor { const findEditorDescriptors = (input: EditorInput, byInstanceOf?: boolean): EditorDescriptor[] => { const matchingDescriptors: EditorDescriptor[] = []; @@ -161,7 +157,7 @@ class EditorRegistry implements IEditorRegistry { return null; } - public getEditorById(editorId: string): EditorDescriptor { + getEditorById(editorId: string): EditorDescriptor { for (let i = 0; i < this.editors.length; i++) { const editor = this.editors[i]; if (editor.getId() === editorId) { @@ -172,15 +168,15 @@ class EditorRegistry implements IEditorRegistry { return null; } - public getEditors(): EditorDescriptor[] { + getEditors(): EditorDescriptor[] { return this.editors.slice(0); } - public setEditors(editorsToSet: EditorDescriptor[]): void { + setEditors(editorsToSet: EditorDescriptor[]): void { this.editors = editorsToSet; } - public getEditorInputs(): any[] { + getEditorInputs(): any[] { const inputClasses: any[] = []; for (let i = 0; i < this.editors.length; i++) { const editor = this.editors[i]; diff --git a/src/vs/workbench/browser/labels.ts b/src/vs/workbench/browser/labels.ts index b71f424b816..0db9f7aae65 100644 --- a/src/vs/workbench/browser/labels.ts +++ b/src/vs/workbench/browser/labels.ts @@ -15,7 +15,6 @@ import { getPathLabel, IWorkspaceFolderProvider } from 'vs/base/common/labels'; import { PLAINTEXT_MODE_ID } from 'vs/editor/common/modes/modesRegistry'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; @@ -40,16 +39,15 @@ export interface IResourceLabelOptions extends IIconLabelValueOptions { export class ResourceLabel extends IconLabel { - private toDispose: IDisposable[]; + private _onDidRender = this._register(new Emitter()); + get onDidRender(): Event { return this._onDidRender.event; } + private label: IResourceLabel; private options: IResourceLabelOptions; private computedIconClasses: string[]; private lastKnownConfiguredLangId: string; private computedPathLabel: string; - private _onDidRender = new Emitter(); - readonly onDidRender: Event = this._onDidRender.event; - constructor( container: HTMLElement, options: IIconLabelCreationOptions, @@ -64,27 +62,25 @@ export class ResourceLabel extends IconLabel { ) { super(container, options); - this.toDispose = []; - this.registerListeners(); } private registerListeners(): void { // update when extensions are registered with potentially new languages - this.toDispose.push(this.extensionService.onDidRegisterExtensions(() => this.render(true /* clear cache */))); + this._register(this.extensionService.onDidRegisterExtensions(() => this.render(true /* clear cache */))); // react to model mode changes - this.toDispose.push(this.modelService.onModelModeChanged(e => this.onModelModeChanged(e))); + this._register(this.modelService.onModelModeChanged(e => this.onModelModeChanged(e))); // react to file decoration changes - this.toDispose.push(this.decorationsService.onDidChangeDecorations(this.onFileDecorationsChanges, this)); + this._register(this.decorationsService.onDidChangeDecorations(this.onFileDecorationsChanges, this)); // react to theme changes - this.toDispose.push(this.themeService.onThemeChange(() => this.render(false))); + this._register(this.themeService.onThemeChange(() => this.render(false))); // react to files.associations changes - this.toDispose.push(this.configurationService.onDidChangeConfiguration(e => { + this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration(FILES_ASSOCIATIONS_CONFIG)) { this.render(true /* clear cache */); } @@ -121,7 +117,7 @@ export class ResourceLabel extends IconLabel { } } - public setLabel(label: IResourceLabel, options?: IResourceLabelOptions): void { + setLabel(label: IResourceLabel, options?: IResourceLabelOptions): void { const hasResourceChanged = this.hasResourceChanged(label, options); this.label = label; @@ -156,7 +152,7 @@ export class ResourceLabel extends IconLabel { return true; } - public clear(): void { + clear(): void { this.label = void 0; this.options = void 0; this.lastKnownConfiguredLangId = void 0; @@ -239,10 +235,9 @@ export class ResourceLabel extends IconLabel { this._onDidRender.fire(); } - public dispose(): void { + dispose(): void { super.dispose(); - this.toDispose = dispose(this.toDispose); this.label = void 0; this.options = void 0; this.lastKnownConfiguredLangId = void 0; @@ -253,7 +248,7 @@ export class ResourceLabel extends IconLabel { export class EditorLabel extends ResourceLabel { - public setEditor(editor: IEditorInput, options?: IResourceLabelOptions): void { + setEditor(editor: IEditorInput, options?: IResourceLabelOptions): void { this.setLabel({ resource: toResource(editor, { supportSideBySide: true }), name: editor.getName(), @@ -286,7 +281,7 @@ export class FileLabel extends ResourceLabel { super(container, options, extensionService, contextService, configurationService, modeService, modelService, environmentService, decorationsService, themeService); } - public setFile(resource: uri, options?: IFileLabelOptions): void { + setFile(resource: uri, options?: IFileLabelOptions): void { const hideLabel = options && options.hideLabel; let name: string; if (!hideLabel) { diff --git a/src/vs/workbench/browser/panel.ts b/src/vs/workbench/browser/panel.ts index 8b05f420b0b..f046282ca36 100644 --- a/src/vs/workbench/browser/panel.ts +++ b/src/vs/workbench/browser/panel.ts @@ -31,28 +31,28 @@ export class PanelRegistry extends CompositeRegistry { /** * Registers a panel to the platform. */ - public registerPanel(descriptor: PanelDescriptor): void { + registerPanel(descriptor: PanelDescriptor): void { super.registerComposite(descriptor); } /** * Returns an array of registered panels known to the platform. */ - public getPanels(): PanelDescriptor[] { + getPanels(): PanelDescriptor[] { return this.getComposites() as PanelDescriptor[]; } /** * Sets the id of the panel that should open on startup by default. */ - public setDefaultPanelId(id: string): void { + setDefaultPanelId(id: string): void { this.defaultPanelId = id; } /** * Gets the id of the panel that should open on startup by default. */ - public getDefaultPanelId(): string { + getDefaultPanelId(): string { return this.defaultPanelId; } } @@ -76,7 +76,7 @@ export abstract class TogglePanelAction extends Action { this.panelId = panelId; } - public run(): TPromise { + run(): TPromise { if (this.isPanelShowing()) { return this.partService.setPanelHidden(true); diff --git a/src/vs/workbench/browser/part.ts b/src/vs/workbench/browser/part.ts index 8f147ff99bc..a7ea04b455e 100644 --- a/src/vs/workbench/browser/part.ts +++ b/src/vs/workbench/browser/part.ts @@ -47,7 +47,7 @@ export abstract class Part extends Component { * * Called to create title and content area of the part. */ - public create(parent: HTMLElement): void { + create(parent: HTMLElement): void { this.parent = parent; this.titleArea = this.createTitleArea(parent); this.contentArea = this.createContentArea(parent); @@ -60,7 +60,7 @@ export abstract class Part extends Component { /** * Returns the overall part container. */ - public getContainer(): HTMLElement { + getContainer(): HTMLElement { return this.parent; } @@ -95,7 +95,7 @@ export abstract class Part extends Component { /** * Layout title and content area in the given dimension. */ - public layout(dimension: Dimension): Dimension[] { + layout(dimension: Dimension): Dimension[] { return this.partLayout.layout(dimension); } } @@ -106,7 +106,7 @@ export class PartLayout { constructor(container: HTMLElement, private options: IPartOptions, titleArea: HTMLElement, private contentArea: HTMLElement) { } - public layout(dimension: Dimension): Dimension[] { + layout(dimension: Dimension): Dimension[] { const { width, height } = dimension; // Return the applied sizes to title and content diff --git a/src/vs/workbench/browser/parts/activitybar/activitybarActions.ts b/src/vs/workbench/browser/parts/activitybar/activitybarActions.ts index 366b81fe440..6d1fa885470 100644 --- a/src/vs/workbench/browser/parts/activitybar/activitybarActions.ts +++ b/src/vs/workbench/browser/parts/activitybar/activitybarActions.ts @@ -21,8 +21,9 @@ import { activeContrastBorder, focusBorder } from 'vs/platform/theme/common/colo import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; -import { ActivityAction, ActivityActionItem, ICompositeBarColors } from 'vs/workbench/browser/parts/compositebar/compositeBarActions'; +import { ActivityAction, ActivityActionItem, ICompositeBarColors, ToggleCompositePinnedAction, ICompositeBar } from 'vs/workbench/browser/parts/compositebar/compositeBarActions'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; +import URI from 'vs/base/common/uri'; export class ViewletActivityAction extends ActivityAction { @@ -39,7 +40,7 @@ export class ViewletActivityAction extends ActivityAction { super(activity); } - public run(event: any): TPromise { + run(event: any): TPromise { if (event instanceof MouseEvent && event.button === 2) { return TPromise.as(false); // do not run on right click } @@ -85,7 +86,7 @@ export class ToggleViewletAction extends Action { super(_viewlet.id, _viewlet.name); } - public run(): TPromise { + run(): TPromise { const sideBarVisible = this.partService.isVisible(Parts.SIDEBAR_PART); const activeViewlet = this.viewletService.getActiveViewlet(); @@ -116,7 +117,7 @@ export class GlobalActivityActionItem extends ActivityActionItem { super(action, { draggable: false, colors, icon: true }, themeService); } - public render(container: HTMLElement): void { + render(container: HTMLElement): void { super.render(container); // Context menus are triggered on mouse down so that an item can be picked @@ -158,6 +159,41 @@ export class GlobalActivityActionItem extends ActivityActionItem { } } +export class PlaceHolderViewletActivityAction extends ViewletActivityAction { + + constructor( + id: string, iconUrl: URI, + @IViewletService viewletService: IViewletService, + @IPartService partService: IPartService, + @ITelemetryService telemetryService: ITelemetryService + ) { + super({ id, name: id, cssClass: `extensionViewlet-placeholder-${id.replace(/\./g, '-')}` }, viewletService, partService, telemetryService); + + const iconClass = `.monaco-workbench > .activitybar .monaco-action-bar .action-label.${this.class}`; // Generate Placeholder CSS to show the icon in the activity bar + DOM.createCSSRule(iconClass, `-webkit-mask: url('${iconUrl || ''}') no-repeat 50% 50%`); + this.enabled = false; + } + + setActivity(activity: IActivity): void { + this.activity = activity; + this.enabled = true; + } +} + +export class PlaceHolderToggleCompositePinnedAction extends ToggleCompositePinnedAction { + + constructor(id: string, compositeBar: ICompositeBar) { + super({ id, name: id, cssClass: void 0 }, compositeBar); + + this.enabled = false; + } + + setActivity(activity: IActivity): void { + this.label = activity.name; + this.enabled = true; + } +} + registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { // Styling with Outline color (e.g. high contrast theme) diff --git a/src/vs/workbench/browser/parts/activitybar/activitybarPart.ts b/src/vs/workbench/browser/parts/activitybar/activitybarPart.ts index f2bfc53e344..13f5812793c 100644 --- a/src/vs/workbench/browser/parts/activitybar/activitybarPart.ts +++ b/src/vs/workbench/browser/parts/activitybar/activitybarPart.ts @@ -10,10 +10,10 @@ import * as nls from 'vs/nls'; import { illegalArgument } from 'vs/base/common/errors'; import { $ } from 'vs/base/browser/builder'; import { ActionsOrientation, ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; -import { GlobalActivityExtensions, IGlobalActivityRegistry, IActivity } from 'vs/workbench/common/activity'; +import { GlobalActivityExtensions, IGlobalActivityRegistry } from 'vs/workbench/common/activity'; import { Registry } from 'vs/platform/registry/common/platform'; import { Part } from 'vs/workbench/browser/part'; -import { GlobalActivityActionItem, GlobalActivityAction, ViewletActivityAction, ToggleViewletAction } from 'vs/workbench/browser/parts/activitybar/activitybarActions'; +import { GlobalActivityActionItem, GlobalActivityAction, ViewletActivityAction, ToggleViewletAction, PlaceHolderToggleCompositePinnedAction, PlaceHolderViewletActivityAction } from 'vs/workbench/browser/parts/activitybar/activitybarActions'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IBadge } from 'vs/workbench/services/activity/common/activity'; import { IPartService, Parts, Position as SideBarPosition } from 'vs/workbench/services/part/common/partService'; @@ -24,12 +24,11 @@ import { IThemeService } from 'vs/platform/theme/common/themeService'; import { ACTIVITY_BAR_BACKGROUND, ACTIVITY_BAR_BORDER, ACTIVITY_BAR_FOREGROUND, ACTIVITY_BAR_BADGE_BACKGROUND, ACTIVITY_BAR_BADGE_FOREGROUND, ACTIVITY_BAR_DRAG_AND_DROP_BACKGROUND } from 'vs/workbench/common/theme'; import { contrastBorder } from 'vs/platform/theme/common/colorRegistry'; import { CompositeBar } from 'vs/workbench/browser/parts/compositebar/compositeBar'; -import { ToggleCompositePinnedAction, ICompositeBar } from 'vs/workbench/browser/parts/compositebar/compositeBarActions'; +import { ToggleCompositePinnedAction } from 'vs/workbench/browser/parts/compositebar/compositeBarActions'; import { ViewletDescriptor } from 'vs/workbench/browser/viewlet'; -import { Dimension, createCSSRule } from 'vs/base/browser/dom'; +import { Dimension } from 'vs/base/browser/dom'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; -import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import URI from 'vs/base/common/uri'; interface IPlaceholderComposite { @@ -39,6 +38,7 @@ interface IPlaceholderComposite { export class ActivitybarPart extends Part { + private static readonly ACTION_HEIGHT = 50; private static readonly PINNED_VIEWLETS = 'workbench.activity.pinnedViewlets'; private static readonly PLACEHOLDER_VIEWLETS = 'workbench.activity.placeholderViewlets'; private static readonly COLORS = { @@ -47,18 +47,15 @@ export class ActivitybarPart extends Part { badgeForeground: ACTIVITY_BAR_BADGE_FOREGROUND, dragAndDropBackground: ACTIVITY_BAR_DRAG_AND_DROP_BACKGROUND }; - private static readonly ACTION_HEIGHT = 50; - - public _serviceBrand: any; private dimension: Dimension; private globalActionBar: ActionBar; - private globalActivityIdToActions: { [globalActivityId: string]: GlobalActivityAction; }; + private globalActivityIdToActions: { [globalActivityId: string]: GlobalActivityAction; } = Object.create(null); private placeholderComposites: IPlaceholderComposite[] = []; private compositeBar: CompositeBar; - private compositeActions: { [compositeId: string]: { activityAction: ViewletActivityAction, pinnedAction: ToggleCompositePinnedAction } }; + private compositeActions: { [compositeId: string]: { activityAction: ViewletActivityAction, pinnedAction: ToggleCompositePinnedAction } } = Object.create(null); constructor( id: string, @@ -67,14 +64,11 @@ export class ActivitybarPart extends Part { @IPartService private partService: IPartService, @IThemeService themeService: IThemeService, @IStorageService private storageService: IStorageService, - @IExtensionService extensionService: IExtensionService + @IExtensionService private extensionService: IExtensionService ) { super(id, { hasTitle: false }, themeService); - this.globalActivityIdToActions = Object.create(null); - - this.compositeActions = Object.create(null); - this.compositeBar = this.instantiationService.createInstance(CompositeBar, { + this.compositeBar = this._register(this.instantiationService.createInstance(CompositeBar, { icon: true, storageId: ActivitybarPart.PINNED_VIEWLETS, orientation: ActionsOrientation.VERTICAL, @@ -88,7 +82,8 @@ export class ActivitybarPart extends Part { compositeSize: 50, colors: ActivitybarPart.COLORS, overflowActionSize: ActivitybarPart.ACTION_HEIGHT - }); + })); + const previousState = this.storageService.get(ActivitybarPart.PLACEHOLDER_VIEWLETS, StorageScope.GLOBAL, void 0); if (previousState) { let parsedPreviousState = JSON.parse(previousState); @@ -107,8 +102,25 @@ export class ActivitybarPart extends Part { this.registerListeners(); this.updateCompositebar(); this.updatePlaceholderComposites(); + } - extensionService.onDidRegisterExtensions(() => this.onDidRegisterExtensions()); + private registerListeners(): void { + this._register(this.viewletService.onDidViewletRegister(() => this.updateCompositebar())); + + // Activate viewlet action on opening of a viewlet + this._register(this.viewletService.onDidViewletOpen(viewlet => this.compositeBar.activateComposite(viewlet.getId()))); + + // Deactivate viewlet action on close + this._register(this.viewletService.onDidViewletClose(viewlet => this.compositeBar.deactivateComposite(viewlet.getId()))); + this._register(this.viewletService.onDidViewletEnablementChange(({ id, enabled }) => { + if (enabled) { + this.compositeBar.addComposite(this.viewletService.getViewlet(id)); + } else { + this.removeComposite(id); + } + })); + + this._register(this.extensionService.onDidRegisterExtensions(() => this.onDidRegisterExtensions())); } private onDidRegisterExtensions(): void { @@ -116,25 +128,7 @@ export class ActivitybarPart extends Part { this.updateCompositebar(); } - private registerListeners(): void { - - this.toUnbind.push(this.viewletService.onDidViewletRegister(() => this.updateCompositebar())); - - // Activate viewlet action on opening of a viewlet - this.toUnbind.push(this.viewletService.onDidViewletOpen(viewlet => this.compositeBar.activateComposite(viewlet.getId()))); - - // Deactivate viewlet action on close - this.toUnbind.push(this.viewletService.onDidViewletClose(viewlet => this.compositeBar.deactivateComposite(viewlet.getId()))); - this.toUnbind.push(this.viewletService.onDidViewletEnablementChange(({ id, enabled }) => { - if (enabled) { - this.compositeBar.addComposite(this.viewletService.getViewlet(id)); - } else { - this.removeComposite(id); - } - })); - } - - public showActivity(viewletOrActionId: string, badge: IBadge, clazz?: string, priority?: number): IDisposable { + showActivity(viewletOrActionId: string, badge: IBadge, clazz?: string, priority?: number): IDisposable { if (this.viewletService.getViewlet(viewletOrActionId)) { return this.compositeBar.showActivity(viewletOrActionId, badge, clazz, priority); } @@ -157,7 +151,7 @@ export class ActivitybarPart extends Part { return toDisposable(() => action.setBadge(undefined)); } - public createContentArea(parent: HTMLElement): HTMLElement { + createContentArea(parent: HTMLElement): HTMLElement { const $el = $(parent); const $result = $('.content').appendTo($el); @@ -170,7 +164,7 @@ export class ActivitybarPart extends Part { return $result.getHTMLElement(); } - public updateStyles(): void { + updateStyles(): void { super.updateStyles(); // Part container @@ -196,13 +190,12 @@ export class ActivitybarPart extends Part { .map(d => this.instantiationService.createInstance(d)) .map(a => new GlobalActivityAction(a)); - this.globalActionBar = new ActionBar(container, { + this.globalActionBar = this._register(new ActionBar(container, { actionItemProvider: a => this.instantiationService.createInstance(GlobalActivityActionItem, a, ActivitybarPart.COLORS), orientation: ActionsOrientation.VERTICAL, ariaLabel: nls.localize('globalActions', "Global Actions"), animated: false - }); - this.toUnbind.push(this.globalActionBar); + })); actions.forEach(a => { this.globalActivityIdToActions[a.id] = a; @@ -226,8 +219,10 @@ export class ActivitybarPart extends Part { pinnedAction: new PlaceHolderToggleCompositePinnedAction(compositeId, this.compositeBar) }; } + this.compositeActions[compositeId] = compositeActions; } + return compositeActions; } @@ -288,14 +283,11 @@ export class ActivitybarPart extends Part { } } - public getPinned(): string[] { + getPinned(): string[] { return this.viewletService.getViewlets().map(v => v.id).filter(id => this.compositeBar.isPinned(id)); } - /** - * Layout title, content and status area in the given dimension. - */ - public layout(dimension: Dimension): Dimension[] { + layout(dimension: Dimension): Dimension[] { if (!this.partService.isVisible(Parts.ACTIVITYBAR_PART)) { return [dimension]; } @@ -315,61 +307,10 @@ export class ActivitybarPart extends Part { return sizes; } - public shutdown(): void { + shutdown(): void { const state = this.viewletService.getViewlets().map(viewlet => ({ id: viewlet.id, iconUrl: viewlet.iconUrl })); this.storageService.store(ActivitybarPart.PLACEHOLDER_VIEWLETS, JSON.stringify(state), StorageScope.GLOBAL); + super.shutdown(); } - - public dispose(): void { - if (this.compositeBar) { - this.compositeBar.dispose(); - this.compositeBar = null; - } - - if (this.globalActionBar) { - this.globalActionBar.dispose(); - this.globalActionBar = null; - } - - super.dispose(); - } } - -class PlaceHolderViewletActivityAction extends ViewletActivityAction { - - constructor( - id: string, iconUrl: URI, - @IViewletService viewletService: IViewletService, - @IPartService partService: IPartService, - @ITelemetryService telemetryService: ITelemetryService - ) { - super({ id, name: id, cssClass: `extensionViewlet-placeholder-${id.replace(/\./g, '-')}` }, viewletService, partService, telemetryService); - // Generate Placeholder CSS to show the icon in the activity bar - const iconClass = `.monaco-workbench > .activitybar .monaco-action-bar .action-label.${this.class}`; - createCSSRule(iconClass, `-webkit-mask: url('${iconUrl || ''}') no-repeat 50% 50%`); - this.enabled = false; - } - - setActivity(activity: IActivity): void { - this.activity = activity; - this.enabled = true; - } - -} - -class PlaceHolderToggleCompositePinnedAction extends ToggleCompositePinnedAction { - - constructor( - id: string, compositeBar: ICompositeBar - ) { - super({ id, name: id, cssClass: void 0 }, compositeBar); - this.enabled = false; - } - - setActivity(activity: IActivity): void { - this.label = activity.name; - this.enabled = true; - } - -} \ No newline at end of file diff --git a/src/vs/workbench/browser/parts/compositePart.ts b/src/vs/workbench/browser/parts/compositePart.ts index 7eba9f60160..386e2981306 100644 --- a/src/vs/workbench/browser/parts/compositePart.ts +++ b/src/vs/workbench/browser/parts/compositePart.ts @@ -51,6 +51,12 @@ export interface ICompositeTitleLabel { } export abstract class CompositePart extends Part { + + protected _onDidCompositeOpen = this._register(new Emitter()); + protected _onDidCompositeClose = this._register(new Emitter()); + + protected toolBar: ToolBar; + private instantiatedCompositeListeners: IDisposable[]; private mapCompositeToCompositeContainer: { [compositeId: string]: Builder; }; private mapActionsBindingToComposite: { [compositeId: string]: () => void; }; @@ -59,13 +65,10 @@ export abstract class CompositePart extends Part { private lastActiveCompositeId: string; private instantiatedComposites: Composite[]; private titleLabel: ICompositeTitleLabel; - protected toolBar: ToolBar; private progressBar: ProgressBar; private contentAreaSize: Dimension; private telemetryActionsListener: IDisposable; private currentCompositeOpenToken: string; - protected _onDidCompositeOpen = new Emitter(); - protected _onDidCompositeClose = new Emitter(); constructor( private notificationService: INotificationService, @@ -400,7 +403,7 @@ export abstract class CompositePart extends Part { }); } - public createTitleArea(parent: HTMLElement): HTMLElement { + createTitleArea(parent: HTMLElement): HTMLElement { // Title Area Container const titleArea = $(parent).div({ @@ -416,11 +419,11 @@ export abstract class CompositePart extends Part { }, div => { // Toolbar - this.toolBar = new ToolBar(div.getHTMLElement(), this.contextMenuService, { + this.toolBar = this._register(new ToolBar(div.getHTMLElement(), this.contextMenuService, { actionItemProvider: action => this.actionItemProvider(action as Action), orientation: ActionsOrientation.HORIZONTAL, getKeyBinding: action => this.keybindingService.lookupKeybinding(action.id) - }); + })); }); return titleArea.getHTMLElement(); @@ -463,12 +466,12 @@ export abstract class CompositePart extends Part { return undefined; } - public createContentArea(parent: HTMLElement): HTMLElement { + createContentArea(parent: HTMLElement): HTMLElement { return $(parent).div({ 'class': 'content' }, div => { - this.progressBar = new ProgressBar(div.getHTMLElement()); - this.toUnbind.push(attachProgressBarStyler(this.progressBar, this.themeService)); + this.progressBar = this._register(new ProgressBar(div.getHTMLElement())); + this._register(attachProgressBarStyler(this.progressBar, this.themeService)); this.progressBar.hide(); }).getHTMLElement(); } @@ -477,7 +480,7 @@ export abstract class CompositePart extends Part { this.notificationService.error(types.isString(error) ? new Error(error) : error); } - public getProgressIndicator(id: string): IProgressService { + getProgressIndicator(id: string): IProgressService { return this.mapProgressServiceToComposite[id]; } @@ -489,7 +492,7 @@ export abstract class CompositePart extends Part { return []; } - public layout(dimension: Dimension): Dimension[] { + layout(dimension: Dimension): Dimension[] { // Pass to super const sizes = super.layout(dimension); @@ -503,13 +506,13 @@ export abstract class CompositePart extends Part { return sizes; } - public shutdown(): void { + shutdown(): void { this.instantiatedComposites.forEach(i => i.shutdown()); super.shutdown(); } - public dispose(): void { + dispose(): void { this.mapCompositeToCompositeContainer = null; this.mapProgressServiceToComposite = null; this.mapActionsBindingToComposite = null; @@ -519,13 +522,8 @@ export abstract class CompositePart extends Part { } this.instantiatedComposites = []; - this.instantiatedCompositeListeners = dispose(this.instantiatedCompositeListeners); - this.progressBar.dispose(); - this.toolBar.dispose(); - - // Super Dispose super.dispose(); } } diff --git a/src/vs/workbench/browser/parts/compositebar/compositeBar.ts b/src/vs/workbench/browser/parts/compositebar/compositeBar.ts index 54b7a6c74e0..54f2748037a 100644 --- a/src/vs/workbench/browser/parts/compositebar/compositeBar.ts +++ b/src/vs/workbench/browser/parts/compositebar/compositeBar.ts @@ -57,17 +57,18 @@ export class CompositeBar extends Widget implements ICompositeBar { @IContextMenuService private contextMenuService: IContextMenuService ) { super(); + this.model = new CompositeBarModel(options); this.storedState = this.loadCompositeItemsFromStorage(); this.visibleComposites = []; this.compositeSizeInBar = new Map(); } - public getCompositesFromStorage(): string[] { + getCompositesFromStorage(): string[] { return this.storedState.map(s => s.id); } - public create(parent: HTMLElement): HTMLElement { + create(parent: HTMLElement): HTMLElement { const actionBarDiv = parent.appendChild($('.composite-bar')); this.compositeSwitcherBar = this._register(new ActionBar(actionBarDiv, { actionItemProvider: (action: Action) => { @@ -102,7 +103,7 @@ export class CompositeBar extends Widget implements ICompositeBar { return actionBarDiv; } - public layout(dimension: Dimension): void { + layout(dimension: Dimension): void { this.dimension = dimension; if (dimension.height === 0 || dimension.width === 0) { // Do not layout if not visible. Otherwise the size measurment would be computed wrongly @@ -118,7 +119,7 @@ export class CompositeBar extends Widget implements ICompositeBar { this.updateCompositeSwitcher(); } - public addComposite({ id, name, order }: { id: string; name: string, order: number }): void { + addComposite({ id, name, order }: { id: string; name: string, order: number }): void { const state = this.storedState.filter(s => s.id === id)[0]; const pinned = state ? state.pinned : true; let index = order >= 0 ? order : this.model.items.length; @@ -147,7 +148,7 @@ export class CompositeBar extends Widget implements ICompositeBar { } } - public removeComposite(id: string): void { + removeComposite(id: string): void { // If it pinned, unpin it first if (this.isPinned(id)) { @@ -160,7 +161,7 @@ export class CompositeBar extends Widget implements ICompositeBar { } } - public activateComposite(id: string): void { + activateComposite(id: string): void { const previousActiveItem = this.model.activeItem; if (this.model.activate(id)) { // Update if current composite is neither visible nor pinned @@ -171,7 +172,7 @@ export class CompositeBar extends Widget implements ICompositeBar { } } - public deactivateComposite(id: string): void { + deactivateComposite(id: string): void { const previousActiveItem = this.model.activeItem; if (this.model.deactivate()) { if (previousActiveItem && !previousActiveItem.pinned) { @@ -180,7 +181,7 @@ export class CompositeBar extends Widget implements ICompositeBar { } } - public showActivity(compositeId: string, badge: IBadge, clazz?: string, priority?: number): IDisposable { + showActivity(compositeId: string, badge: IBadge, clazz?: string, priority?: number): IDisposable { if (!badge) { throw illegalArgument('badge'); } @@ -194,7 +195,7 @@ export class CompositeBar extends Widget implements ICompositeBar { return toDisposable(() => this.model.removeActivity(compositeId, activity)); } - public pin(compositeId: string, open?: boolean): void { + pin(compositeId: string, open?: boolean): void { if (this.model.setPinned(compositeId, true)) { this.updateCompositeSwitcher(); @@ -205,7 +206,7 @@ export class CompositeBar extends Widget implements ICompositeBar { } } - public unpin(compositeId: string): void { + unpin(compositeId: string): void { if (this.model.setPinned(compositeId, false)) { this.updateCompositeSwitcher(); @@ -238,24 +239,22 @@ export class CompositeBar extends Widget implements ICompositeBar { else { this.options.openComposite(this.visibleComposites.filter(cid => cid !== compositeId)[0]); } - } - } - public isPinned(compositeId: string): boolean { + isPinned(compositeId: string): boolean { const item = this.model.findItem(compositeId); return item && item.pinned; } - public move(compositeId: string, toCompositeId: string): void { + move(compositeId: string, toCompositeId: string): void { if (this.model.move(compositeId, toCompositeId)) { // timeout helps to prevent artifacts from showing up setTimeout(() => this.updateCompositeSwitcher(), 0); } } - public getAction(compositeId): ActivityAction { + getAction(compositeId): ActivityAction { const item = this.model.findItem(compositeId); return item && item.activityAction; } diff --git a/src/vs/workbench/browser/parts/compositebar/compositeBarActions.ts b/src/vs/workbench/browser/parts/compositebar/compositeBarActions.ts index 7beeddb156c..d06fa2b65a6 100644 --- a/src/vs/workbench/browser/parts/compositebar/compositeBarActions.ts +++ b/src/vs/workbench/browser/parts/compositebar/compositeBarActions.ts @@ -52,10 +52,15 @@ export interface ICompositeBar { } export class ActivityAction extends Action { + + private _onDidChangeActivity = new Emitter(); + get onDidChangeActivity(): Event { return this._onDidChangeActivity.event; } + + private _onDidChangeBadge = new Emitter(); + get onDidChangeBadge(): Event { return this._onDidChangeBadge.event; } + private badge: IBadge; private clazz: string | undefined; - private _onDidChangeActivity = new Emitter(); - private _onDidChangeBadge = new Emitter(); constructor(private _activity: IActivity) { super(_activity.id, _activity.name, _activity.cssClass); @@ -63,48 +68,47 @@ export class ActivityAction extends Action { this.badge = null; } - public get activity(): IActivity { + get activity(): IActivity { return this._activity; } - public set activity(activity: IActivity) { + set activity(activity: IActivity) { this._activity = activity; this._onDidChangeActivity.fire(this); } - public get onDidChangeActivity(): Event { - return this._onDidChangeActivity.event; - } - - public get onDidChangeBadge(): Event { - return this._onDidChangeBadge.event; - } - - public activate(): void { + activate(): void { if (!this.checked) { this._setChecked(true); } } - public deactivate(): void { + deactivate(): void { if (this.checked) { this._setChecked(false); } } - public getBadge(): IBadge { + getBadge(): IBadge { return this.badge; } - public getClass(): string | undefined { + getClass(): string | undefined { return this.clazz; } - public setBadge(badge: IBadge, clazz?: string): void { + setBadge(badge: IBadge, clazz?: string): void { this.badge = badge; this.clazz = clazz; this._onDidChangeBadge.fire(this); } + + dispose(): void { + this._onDidChangeActivity.dispose(); + this._onDidChangeBadge.dispose(); + + super.dispose(); + } } export interface ICompositeBarColors { @@ -170,7 +174,7 @@ export class ActivityActionItem extends BaseActionItem { } } - public render(container: HTMLElement): void { + render(container: HTMLElement): void { super.render(container); // Make the container tab-able for keyboard navigation @@ -301,7 +305,7 @@ export class ActivityActionItem extends BaseActionItem { }); } - public dispose(): void { + dispose(): void { super.dispose(); if (this.mouseUpTimeout) { @@ -324,7 +328,7 @@ export class CompositeOverflowActivityAction extends ActivityAction { }); } - public run(event: any): TPromise { + run(event: any): TPromise { this.showMenu(); return TPromise.as(true); @@ -347,7 +351,7 @@ export class CompositeOverflowActivityActionItem extends ActivityActionItem { super(action, { icon: true, colors }, themeService); } - public showMenu(): void { + showMenu(): void { if (this.actions) { dispose(this.actions); } @@ -384,7 +388,7 @@ export class CompositeOverflowActivityActionItem extends ActivityActionItem { }); } - public dispose(): void { + dispose(): void { super.dispose(); this.actions = dispose(this.actions); @@ -399,7 +403,7 @@ class ManageExtensionAction extends Action { super('activitybar.manage.extension', nls.localize('manageExtension', "Manage Extension")); } - public run(id: string): TPromise { + run(id: string): TPromise { return this.commandService.executeCommand('_extensions.manage', id); } } @@ -463,7 +467,7 @@ export class CompositeActionItem extends ActivityActionItem { return null; } - public render(container: HTMLElement): void { + render(container: HTMLElement): void { super.render(container); this._updateChecked(); @@ -548,7 +552,7 @@ export class CompositeActionItem extends ActivityActionItem { element.style.backgroundColor = isDragging && dragBackground ? dragBackground.toString() : null; } - public static getDraggedCompositeId(): string { + static getDraggedCompositeId(): string { return CompositeActionItem.draggedCompositeId; } @@ -556,7 +560,7 @@ export class CompositeActionItem extends ActivityActionItem { CompositeActionItem.draggedCompositeId = compositeId; } - public static clearDraggedComposite(): void { + static clearDraggedComposite(): void { CompositeActionItem.draggedCompositeId = void 0; } @@ -582,7 +586,7 @@ export class CompositeActionItem extends ActivityActionItem { }); } - public focus(): void { + focus(): void { this.$container.domFocus(); } @@ -613,7 +617,7 @@ export class CompositeActionItem extends ActivityActionItem { } } - public dispose(): void { + dispose(): void { super.dispose(); CompositeActionItem.clearDraggedComposite(); @@ -633,7 +637,7 @@ export class ToggleCompositePinnedAction extends Action { this.checked = this.activity && this.compositeBar.isPinned(this.activity.id); } - public run(context: string): TPromise { + run(context: string): TPromise { const id = this.activity ? this.activity.id : context; if (this.compositeBar.isPinned(id)) { diff --git a/src/vs/workbench/browser/parts/editor/baseEditor.ts b/src/vs/workbench/browser/parts/editor/baseEditor.ts index 040f588de89..bda6dcf8f1c 100644 --- a/src/vs/workbench/browser/parts/editor/baseEditor.ts +++ b/src/vs/workbench/browser/parts/editor/baseEditor.ts @@ -33,6 +33,8 @@ import { DEFAULT_EDITOR_MIN_DIMENSIONS, DEFAULT_EDITOR_MAX_DIMENSIONS } from 'vs */ export abstract class BaseEditor extends Panel implements IEditor { + private static readonly EDITOR_MEMENTOS: Map> = new Map>(); + readonly minimumWidth = DEFAULT_EDITOR_MIN_DIMENSIONS.width; readonly maximumWidth = DEFAULT_EDITOR_MAX_DIMENSIONS.width; readonly minimumHeight = DEFAULT_EDITOR_MIN_DIMENSIONS.height; @@ -40,8 +42,6 @@ export abstract class BaseEditor extends Panel implements IEditor { readonly onDidSizeConstraintsChange: Event<{ width: number; height: number; }> = Event.None; - private static readonly EDITOR_MEMENTOS: Map> = new Map>(); - protected _input: EditorInput; private _options: EditorOptions; @@ -171,7 +171,6 @@ export abstract class BaseEditor extends Panel implements IEditor { this._input = null; this._options = null; - // Super Dispose super.dispose(); } } diff --git a/src/vs/workbench/browser/parts/editor/binaryDiffEditor.ts b/src/vs/workbench/browser/parts/editor/binaryDiffEditor.ts index 8383ebf5b42..203fb0368aa 100644 --- a/src/vs/workbench/browser/parts/editor/binaryDiffEditor.ts +++ b/src/vs/workbench/browser/parts/editor/binaryDiffEditor.ts @@ -18,7 +18,7 @@ import { BaseBinaryResourceEditor } from 'vs/workbench/browser/parts/editor/bina */ export class BinaryResourceDiffEditor extends SideBySideEditor { - public static readonly ID = BINARY_DIFF_EDITOR_ID; + static readonly ID = BINARY_DIFF_EDITOR_ID; constructor( @ITelemetryService telemetryService: ITelemetryService, @@ -28,7 +28,7 @@ export class BinaryResourceDiffEditor extends SideBySideEditor { super(telemetryService, instantiationService, themeService); } - public getMetadata(): string { + getMetadata(): string { const master = this.masterEditor; const details = this.detailsEditor; diff --git a/src/vs/workbench/browser/parts/editor/binaryEditor.ts b/src/vs/workbench/browser/parts/editor/binaryEditor.ts index 7a66f852922..aa9d7062c83 100644 --- a/src/vs/workbench/browser/parts/editor/binaryEditor.ts +++ b/src/vs/workbench/browser/parts/editor/binaryEditor.ts @@ -32,7 +32,8 @@ export interface IOpenCallbacks { */ export abstract class BaseBinaryResourceEditor extends BaseEditor { - private readonly _onMetadataChanged: Emitter; + private readonly _onMetadataChanged: Emitter = this._register(new Emitter()); + get onMetadataChanged(): Event { return this._onMetadataChanged.event; } private callbacks: IOpenCallbacks; private metadata: string; @@ -49,17 +50,10 @@ export abstract class BaseBinaryResourceEditor extends BaseEditor { ) { super(id, telemetryService, themeService); - this._onMetadataChanged = new Emitter(); - this.toUnbind.push(this._onMetadataChanged); - this.callbacks = callbacks; } - public get onMetadataChanged(): Event { - return this._onMetadataChanged.event; - } - - public getTitle(): string { + getTitle(): string { return this.input ? this.input.getName() : nls.localize('binaryEditor', "Binary Viewer"); } @@ -73,11 +67,11 @@ export abstract class BaseBinaryResourceEditor extends BaseEditor { this.binaryContainer.tabindex(0); // enable focus support from the editor part (do not remove) // Custom Scrollbars - this.scrollbar = new DomScrollableElement(binaryContainerElement, { horizontal: ScrollbarVisibility.Auto, vertical: ScrollbarVisibility.Auto }); + this.scrollbar = this._register(new DomScrollableElement(binaryContainerElement, { horizontal: ScrollbarVisibility.Auto, vertical: ScrollbarVisibility.Auto })); parent.appendChild(this.scrollbar.getDomNode()); } - public setInput(input: EditorInput, options: EditorOptions, token: CancellationToken): Thenable { + setInput(input: EditorInput, options: EditorOptions, token: CancellationToken): Thenable { return super.setInput(input, options, token).then(() => { return input.resolve(true).then(model => { @@ -109,14 +103,15 @@ export abstract class BaseBinaryResourceEditor extends BaseEditor { private handleMetadataChanged(meta: string): void { this.metadata = meta; + this._onMetadataChanged.fire(); } - public getMetadata(): string { + getMetadata(): string { return this.metadata; } - public clearInput(): void { + clearInput(): void { // Clear Meta this.handleMetadataChanged(null); @@ -127,7 +122,7 @@ export abstract class BaseBinaryResourceEditor extends BaseEditor { super.clearInput(); } - public layout(dimension: Dimension): void { + layout(dimension: Dimension): void { // Pass on to Binary Container this.binaryContainer.size(dimension.width, dimension.height); @@ -137,15 +132,14 @@ export abstract class BaseBinaryResourceEditor extends BaseEditor { } } - public focus(): void { + focus(): void { this.binaryContainer.domFocus(); } - public dispose(): void { + dispose(): void { // Destroy Container this.binaryContainer.destroy(); - this.scrollbar.dispose(); super.dispose(); } diff --git a/src/vs/workbench/browser/parts/editor/editor.contribution.ts b/src/vs/workbench/browser/parts/editor/editor.contribution.ts index 342d3af6837..f633777987f 100644 --- a/src/vs/workbench/browser/parts/editor/editor.contribution.ts +++ b/src/vs/workbench/browser/parts/editor/editor.contribution.ts @@ -109,10 +109,9 @@ class UntitledEditorInputFactory implements IEditorInputFactory { constructor( @ITextFileService private textFileService: ITextFileService - ) { - } + ) { } - public serialize(editorInput: EditorInput): string { + serialize(editorInput: EditorInput): string { if (!this.textFileService.isHotExitEnabled) { return null; // never restore untitled unless hot exit is enabled } @@ -134,7 +133,7 @@ class UntitledEditorInputFactory implements IEditorInputFactory { return JSON.stringify(serialized); } - public deserialize(instantiationService: IInstantiationService, serializedEditorInput: string): UntitledEditorInput { + deserialize(instantiationService: IInstantiationService, serializedEditorInput: string): UntitledEditorInput { return instantiationService.invokeFunction(accessor => { const deserialized: ISerializedUntitledEditorInput = JSON.parse(serializedEditorInput); const resource = !!deserialized.resourceJSON ? URI.revive(deserialized.resourceJSON) : URI.parse(deserialized.resource); @@ -163,7 +162,7 @@ interface ISerializedSideBySideEditorInput { // Register Side by Side Editor Input Factory class SideBySideEditorInputFactory implements IEditorInputFactory { - public serialize(editorInput: EditorInput): string { + serialize(editorInput: EditorInput): string { const input = editorInput; if (input.details && input.master) { @@ -191,7 +190,7 @@ class SideBySideEditorInputFactory implements IEditorInputFactory { return null; } - public deserialize(instantiationService: IInstantiationService, serializedEditorInput: string): EditorInput { + deserialize(instantiationService: IInstantiationService, serializedEditorInput: string): EditorInput { const deserialized: ISerializedSideBySideEditorInput = JSON.parse(serializedEditorInput); const registry = Registry.as(EditorInputExtensions.EditorInputFactories); @@ -230,13 +229,13 @@ export class QuickOpenActionContributor extends ActionBarContributor { super(); } - public hasActions(context: any): boolean { + hasActions(context: any): boolean { const entry = this.getEntry(context); return !!entry; } - public getActions(context: any): IAction[] { + getActions(context: any): IAction[] { const actions: Action[] = []; const entry = this.getEntry(context); diff --git a/src/vs/workbench/browser/parts/editor/editorActions.ts b/src/vs/workbench/browser/parts/editor/editorActions.ts index 184d01fe293..f1af1f2d54b 100644 --- a/src/vs/workbench/browser/parts/editor/editorActions.ts +++ b/src/vs/workbench/browser/parts/editor/editorActions.ts @@ -37,7 +37,7 @@ export class ExecuteCommandAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { return this.commandService.executeCommand(this.commandId, this.commandArgs); } } @@ -71,13 +71,13 @@ export class BaseSplitEditorAction extends Action { })); } - public run(context?: IEditorIdentifier): TPromise { + run(context?: IEditorIdentifier): TPromise { splitEditor(this.editorGroupService, this.direction, context); return TPromise.as(true); } - public dispose(): void { + dispose(): void { super.dispose(); this.toDispose = dispose(this.toDispose); @@ -86,8 +86,8 @@ export class BaseSplitEditorAction extends Action { export class SplitEditorAction extends BaseSplitEditorAction { - public static readonly ID = 'workbench.action.splitEditor'; - public static readonly LABEL = nls.localize('splitEditor', "Split Editor"); + static readonly ID = 'workbench.action.splitEditor'; + static readonly LABEL = nls.localize('splitEditor', "Split Editor"); constructor( id: string, @@ -101,8 +101,8 @@ export class SplitEditorAction extends BaseSplitEditorAction { export class SplitEditorOrthogonalAction extends BaseSplitEditorAction { - public static readonly ID = 'workbench.action.splitEditorOrthogonal'; - public static readonly LABEL = nls.localize('splitEditorOrthogonal', "Split Editor Orthogonal"); + static readonly ID = 'workbench.action.splitEditorOrthogonal'; + static readonly LABEL = nls.localize('splitEditorOrthogonal', "Split Editor Orthogonal"); constructor( id: string, @@ -122,8 +122,8 @@ export class SplitEditorOrthogonalAction extends BaseSplitEditorAction { export class SplitEditorLeftAction extends ExecuteCommandAction { - public static readonly ID = SPLIT_EDITOR_LEFT; - public static readonly LABEL = nls.localize('splitEditorGroupLeft', "Split Editor Left"); + static readonly ID = SPLIT_EDITOR_LEFT; + static readonly LABEL = nls.localize('splitEditorGroupLeft', "Split Editor Left"); constructor( id: string, @@ -136,8 +136,8 @@ export class SplitEditorLeftAction extends ExecuteCommandAction { export class SplitEditorRightAction extends ExecuteCommandAction { - public static readonly ID = SPLIT_EDITOR_RIGHT; - public static readonly LABEL = nls.localize('splitEditorGroupRight', "Split Editor Right"); + static readonly ID = SPLIT_EDITOR_RIGHT; + static readonly LABEL = nls.localize('splitEditorGroupRight', "Split Editor Right"); constructor( id: string, @@ -150,8 +150,8 @@ export class SplitEditorRightAction extends ExecuteCommandAction { export class SplitEditorUpAction extends ExecuteCommandAction { - public static readonly ID = SPLIT_EDITOR_UP; - public static readonly LABEL = nls.localize('splitEditorGroupUp', "Split Editor Up"); + static readonly ID = SPLIT_EDITOR_UP; + static readonly LABEL = nls.localize('splitEditorGroupUp', "Split Editor Up"); constructor( id: string, @@ -164,8 +164,8 @@ export class SplitEditorUpAction extends ExecuteCommandAction { export class SplitEditorDownAction extends ExecuteCommandAction { - public static readonly ID = SPLIT_EDITOR_DOWN; - public static readonly LABEL = nls.localize('splitEditorGroupDown', "Split Editor Down"); + static readonly ID = SPLIT_EDITOR_DOWN; + static readonly LABEL = nls.localize('splitEditorGroupDown', "Split Editor Down"); constructor( id: string, @@ -178,8 +178,8 @@ export class SplitEditorDownAction extends ExecuteCommandAction { export class JoinTwoGroupsAction extends Action { - public static readonly ID = 'workbench.action.joinTwoGroups'; - public static readonly LABEL = nls.localize('joinTwoGroups', "Join Editor Group with Next Group"); + static readonly ID = 'workbench.action.joinTwoGroups'; + static readonly LABEL = nls.localize('joinTwoGroups', "Join Editor Group with Next Group"); constructor( id: string, @@ -189,7 +189,7 @@ export class JoinTwoGroupsAction extends Action { super(id, label); } - public run(context?: IEditorIdentifier): TPromise { + run(context?: IEditorIdentifier): TPromise { let sourceGroup: IEditorGroup; if (context && typeof context.groupId === 'number') { sourceGroup = this.editorGroupService.getGroup(context.groupId); @@ -213,8 +213,8 @@ export class JoinTwoGroupsAction extends Action { export class JoinAllGroupsAction extends Action { - public static readonly ID = 'workbench.action.joinAllGroups'; - public static readonly LABEL = nls.localize('joinAllGroups', "Join All Editor Groups"); + static readonly ID = 'workbench.action.joinAllGroups'; + static readonly LABEL = nls.localize('joinAllGroups', "Join All Editor Groups"); constructor( id: string, @@ -224,7 +224,7 @@ export class JoinAllGroupsAction extends Action { super(id, label); } - public run(context?: IEditorIdentifier): TPromise { + run(context?: IEditorIdentifier): TPromise { mergeAllGroups(this.editorGroupService); return TPromise.as(true); @@ -233,8 +233,8 @@ export class JoinAllGroupsAction extends Action { export class NavigateBetweenGroupsAction extends Action { - public static readonly ID = 'workbench.action.navigateEditorGroups'; - public static readonly LABEL = nls.localize('navigateEditorGroups', "Navigate Between Editor Groups"); + static readonly ID = 'workbench.action.navigateEditorGroups'; + static readonly LABEL = nls.localize('navigateEditorGroups', "Navigate Between Editor Groups"); constructor( id: string, @@ -244,7 +244,7 @@ export class NavigateBetweenGroupsAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { const nextGroup = this.editorGroupService.findGroup({ location: GroupLocation.NEXT }, this.editorGroupService.activeGroup, true); nextGroup.focus(); @@ -254,8 +254,8 @@ export class NavigateBetweenGroupsAction extends Action { export class FocusActiveGroupAction extends Action { - public static readonly ID = 'workbench.action.focusActiveEditorGroup'; - public static readonly LABEL = nls.localize('focusActiveEditorGroup', "Focus Active Editor Group"); + static readonly ID = 'workbench.action.focusActiveEditorGroup'; + static readonly LABEL = nls.localize('focusActiveEditorGroup', "Focus Active Editor Group"); constructor( id: string, @@ -265,7 +265,7 @@ export class FocusActiveGroupAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { this.editorGroupService.activeGroup.focus(); return TPromise.as(true); @@ -283,7 +283,7 @@ export abstract class BaseFocusGroupAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { const group = this.editorGroupService.findGroup(this.scope, this.editorGroupService.activeGroup, true); if (group) { group.focus(); @@ -295,8 +295,8 @@ export abstract class BaseFocusGroupAction extends Action { export class FocusFirstGroupAction extends BaseFocusGroupAction { - public static readonly ID = 'workbench.action.focusFirstEditorGroup'; - public static readonly LABEL = nls.localize('focusFirstEditorGroup', "Focus First Editor Group"); + static readonly ID = 'workbench.action.focusFirstEditorGroup'; + static readonly LABEL = nls.localize('focusFirstEditorGroup', "Focus First Editor Group"); constructor( id: string, @@ -309,8 +309,8 @@ export class FocusFirstGroupAction extends BaseFocusGroupAction { export class FocusLastGroupAction extends BaseFocusGroupAction { - public static readonly ID = 'workbench.action.focusLastEditorGroup'; - public static readonly LABEL = nls.localize('focusLastEditorGroup', "Focus Last Editor Group"); + static readonly ID = 'workbench.action.focusLastEditorGroup'; + static readonly LABEL = nls.localize('focusLastEditorGroup', "Focus Last Editor Group"); constructor( id: string, @@ -323,8 +323,8 @@ export class FocusLastGroupAction extends BaseFocusGroupAction { export class FocusNextGroup extends BaseFocusGroupAction { - public static readonly ID = 'workbench.action.focusNextGroup'; - public static readonly LABEL = nls.localize('focusNextGroup', "Focus Next Editor Group"); + static readonly ID = 'workbench.action.focusNextGroup'; + static readonly LABEL = nls.localize('focusNextGroup', "Focus Next Editor Group"); constructor( id: string, @@ -337,8 +337,8 @@ export class FocusNextGroup extends BaseFocusGroupAction { export class FocusPreviousGroup extends BaseFocusGroupAction { - public static readonly ID = 'workbench.action.focusPreviousGroup'; - public static readonly LABEL = nls.localize('focusPreviousGroup', "Focus Previous Editor Group"); + static readonly ID = 'workbench.action.focusPreviousGroup'; + static readonly LABEL = nls.localize('focusPreviousGroup', "Focus Previous Editor Group"); constructor( id: string, @@ -351,8 +351,8 @@ export class FocusPreviousGroup extends BaseFocusGroupAction { export class FocusLeftGroup extends BaseFocusGroupAction { - public static readonly ID = 'workbench.action.focusLeftGroup'; - public static readonly LABEL = nls.localize('focusLeftGroup', "Focus Left Editor Group"); + static readonly ID = 'workbench.action.focusLeftGroup'; + static readonly LABEL = nls.localize('focusLeftGroup', "Focus Left Editor Group"); constructor( id: string, @@ -365,8 +365,8 @@ export class FocusLeftGroup extends BaseFocusGroupAction { export class FocusRightGroup extends BaseFocusGroupAction { - public static readonly ID = 'workbench.action.focusRightGroup'; - public static readonly LABEL = nls.localize('focusRightGroup', "Focus Right Editor Group"); + static readonly ID = 'workbench.action.focusRightGroup'; + static readonly LABEL = nls.localize('focusRightGroup', "Focus Right Editor Group"); constructor( id: string, @@ -379,8 +379,8 @@ export class FocusRightGroup extends BaseFocusGroupAction { export class FocusAboveGroup extends BaseFocusGroupAction { - public static readonly ID = 'workbench.action.focusAboveGroup'; - public static readonly LABEL = nls.localize('focusAboveGroup', "Focus Above Editor Group"); + static readonly ID = 'workbench.action.focusAboveGroup'; + static readonly LABEL = nls.localize('focusAboveGroup', "Focus Above Editor Group"); constructor( id: string, @@ -393,8 +393,8 @@ export class FocusAboveGroup extends BaseFocusGroupAction { export class FocusBelowGroup extends BaseFocusGroupAction { - public static readonly ID = 'workbench.action.focusBelowGroup'; - public static readonly LABEL = nls.localize('focusBelowGroup', "Focus Below Editor Group"); + static readonly ID = 'workbench.action.focusBelowGroup'; + static readonly LABEL = nls.localize('focusBelowGroup', "Focus Below Editor Group"); constructor( id: string, @@ -407,8 +407,8 @@ export class FocusBelowGroup extends BaseFocusGroupAction { export class OpenToSideFromQuickOpenAction extends Action { - public static readonly OPEN_TO_SIDE_ID = 'workbench.action.openToSide'; - public static readonly OPEN_TO_SIDE_LABEL = nls.localize('openToSide', "Open to the Side"); + static readonly OPEN_TO_SIDE_ID = 'workbench.action.openToSide'; + static readonly OPEN_TO_SIDE_LABEL = nls.localize('openToSide', "Open to the Side"); constructor( @IEditorService private editorService: IEditorService, @@ -419,13 +419,13 @@ export class OpenToSideFromQuickOpenAction extends Action { this.updateClass(); } - public updateClass(): void { + updateClass(): void { const preferredDirection = preferredSideBySideGroupDirection(this.configurationService); this.class = (preferredDirection === GroupDirection.RIGHT) ? 'quick-open-sidebyside-vertical' : 'quick-open-sidebyside-horizontal'; } - public run(context: any): TPromise { + run(context: any): TPromise { const entry = toEditorQuickOpenEntry(context); if (entry) { const input = entry.getInput(); @@ -463,8 +463,8 @@ export function toEditorQuickOpenEntry(element: any): IEditorQuickOpenEntry { export class CloseEditorAction extends Action { - public static readonly ID = 'workbench.action.closeActiveEditor'; - public static readonly LABEL = nls.localize('closeEditor', "Close Editor"); + static readonly ID = 'workbench.action.closeActiveEditor'; + static readonly LABEL = nls.localize('closeEditor', "Close Editor"); constructor( id: string, @@ -474,15 +474,15 @@ export class CloseEditorAction extends Action { super(id, label, 'close-editor-action'); } - public run(context?: IEditorCommandsContext): TPromise { + run(context?: IEditorCommandsContext): TPromise { return this.commandService.executeCommand(CLOSE_EDITOR_COMMAND_ID, void 0, context); } } export class CloseOneEditorAction extends Action { - public static readonly ID = 'workbench.action.closeActiveEditor'; - public static readonly LABEL = nls.localize('closeOneEditor', "Close"); + static readonly ID = 'workbench.action.closeActiveEditor'; + static readonly LABEL = nls.localize('closeOneEditor', "Close"); constructor( id: string, @@ -492,7 +492,7 @@ export class CloseOneEditorAction extends Action { super(id, label, 'close-editor-action'); } - public run(context?: IEditorCommandsContext): TPromise { + run(context?: IEditorCommandsContext): TPromise { let group: IEditorGroup; let editorIndex: number; if (context) { @@ -526,8 +526,8 @@ export class CloseOneEditorAction extends Action { export class RevertAndCloseEditorAction extends Action { - public static readonly ID = 'workbench.action.revertAndCloseActiveEditor'; - public static readonly LABEL = nls.localize('revertAndCloseActiveEditor', "Revert and Close Editor"); + static readonly ID = 'workbench.action.revertAndCloseActiveEditor'; + static readonly LABEL = nls.localize('revertAndCloseActiveEditor', "Revert and Close Editor"); constructor( id: string, @@ -537,7 +537,7 @@ export class RevertAndCloseEditorAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { const activeControl = this.editorService.activeControl; if (activeControl) { const editor = activeControl.input; @@ -559,8 +559,8 @@ export class RevertAndCloseEditorAction extends Action { export class CloseLeftEditorsInGroupAction extends Action { - public static readonly ID = 'workbench.action.closeEditorsToTheLeft'; - public static readonly LABEL = nls.localize('closeEditorsToTheLeft', "Close Editors to the Left in Group"); + static readonly ID = 'workbench.action.closeEditorsToTheLeft'; + static readonly LABEL = nls.localize('closeEditorsToTheLeft', "Close Editors to the Left in Group"); constructor( id: string, @@ -571,7 +571,7 @@ export class CloseLeftEditorsInGroupAction extends Action { super(id, label); } - public run(context?: IEditorIdentifier): TPromise { + run(context?: IEditorIdentifier): TPromise { const { group, editor } = getTarget(this.editorService, this.editorGroupService, context); if (group && editor) { return group.closeEditors({ direction: CloseDirection.LEFT, except: editor }); @@ -616,7 +616,7 @@ export abstract class BaseCloseAllAction extends Action { return groupsToClose; } - public run(): TPromise { + run(): TPromise { // Just close all if there are no or one dirty editor if (this.textFileService.getDirty().length < 2) { @@ -651,8 +651,8 @@ export abstract class BaseCloseAllAction extends Action { export class CloseAllEditorsAction extends BaseCloseAllAction { - public static readonly ID = 'workbench.action.closeAllEditors'; - public static readonly LABEL = nls.localize('closeAllEditors', "Close All Editors"); + static readonly ID = 'workbench.action.closeAllEditors'; + static readonly LABEL = nls.localize('closeAllEditors', "Close All Editors"); constructor( id: string, @@ -670,8 +670,8 @@ export class CloseAllEditorsAction extends BaseCloseAllAction { export class CloseAllEditorGroupsAction extends BaseCloseAllAction { - public static readonly ID = 'workbench.action.closeAllGroups'; - public static readonly LABEL = nls.localize('closeAllGroups', "Close All Editor Groups"); + static readonly ID = 'workbench.action.closeAllGroups'; + static readonly LABEL = nls.localize('closeAllGroups', "Close All Editor Groups"); constructor( id: string, @@ -691,8 +691,8 @@ export class CloseAllEditorGroupsAction extends BaseCloseAllAction { export class CloseEditorsInOtherGroupsAction extends Action { - public static readonly ID = 'workbench.action.closeEditorsInOtherGroups'; - public static readonly LABEL = nls.localize('closeEditorsInOtherGroups', "Close Editors in Other Groups"); + static readonly ID = 'workbench.action.closeEditorsInOtherGroups'; + static readonly LABEL = nls.localize('closeEditorsInOtherGroups', "Close Editors in Other Groups"); constructor( id: string, @@ -702,7 +702,7 @@ export class CloseEditorsInOtherGroupsAction extends Action { super(id, label); } - public run(context?: IEditorIdentifier): TPromise { + run(context?: IEditorIdentifier): TPromise { const groupToSkip = context ? this.editorGroupService.getGroup(context.groupId) : this.editorGroupService.activeGroup; return TPromise.join(this.editorGroupService.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE).map(g => { if (g.id === groupToSkip.id) { @@ -725,7 +725,7 @@ export class BaseMoveGroupAction extends Action { super(id, label); } - public run(context?: IEditorIdentifier): TPromise { + run(context?: IEditorIdentifier): TPromise { let sourceGroup: IEditorGroup; if (context && typeof context.groupId === 'number') { sourceGroup = this.editorGroupService.getGroup(context.groupId); @@ -771,8 +771,8 @@ export class BaseMoveGroupAction extends Action { export class MoveGroupLeftAction extends BaseMoveGroupAction { - public static readonly ID = 'workbench.action.moveActiveEditorGroupLeft'; - public static readonly LABEL = nls.localize('moveActiveGroupLeft', "Move Editor Group Left"); + static readonly ID = 'workbench.action.moveActiveEditorGroupLeft'; + static readonly LABEL = nls.localize('moveActiveGroupLeft', "Move Editor Group Left"); constructor( id: string, @@ -785,8 +785,8 @@ export class MoveGroupLeftAction extends BaseMoveGroupAction { export class MoveGroupRightAction extends BaseMoveGroupAction { - public static readonly ID = 'workbench.action.moveActiveEditorGroupRight'; - public static readonly LABEL = nls.localize('moveActiveGroupRight', "Move Editor Group Right"); + static readonly ID = 'workbench.action.moveActiveEditorGroupRight'; + static readonly LABEL = nls.localize('moveActiveGroupRight', "Move Editor Group Right"); constructor( id: string, @@ -799,8 +799,8 @@ export class MoveGroupRightAction extends BaseMoveGroupAction { export class MoveGroupUpAction extends BaseMoveGroupAction { - public static readonly ID = 'workbench.action.moveActiveEditorGroupUp'; - public static readonly LABEL = nls.localize('moveActiveGroupUp', "Move Editor Group Up"); + static readonly ID = 'workbench.action.moveActiveEditorGroupUp'; + static readonly LABEL = nls.localize('moveActiveGroupUp', "Move Editor Group Up"); constructor( id: string, @@ -813,8 +813,8 @@ export class MoveGroupUpAction extends BaseMoveGroupAction { export class MoveGroupDownAction extends BaseMoveGroupAction { - public static readonly ID = 'workbench.action.moveActiveEditorGroupDown'; - public static readonly LABEL = nls.localize('moveActiveGroupDown', "Move Editor Group Down"); + static readonly ID = 'workbench.action.moveActiveEditorGroupDown'; + static readonly LABEL = nls.localize('moveActiveGroupDown', "Move Editor Group Down"); constructor( id: string, @@ -827,14 +827,14 @@ export class MoveGroupDownAction extends BaseMoveGroupAction { export class MinimizeOtherGroupsAction extends Action { - public static readonly ID = 'workbench.action.minimizeOtherEditors'; - public static readonly LABEL = nls.localize('minimizeOtherEditorGroups', "Maximize Editor Group"); + static readonly ID = 'workbench.action.minimizeOtherEditors'; + static readonly LABEL = nls.localize('minimizeOtherEditorGroups', "Maximize Editor Group"); constructor(id: string, label: string, @IEditorGroupsService private editorGroupService: IEditorGroupsService) { super(id, label); } - public run(): TPromise { + run(): TPromise { this.editorGroupService.arrangeGroups(GroupsArrangement.MINIMIZE_OTHERS); return TPromise.as(false); @@ -843,14 +843,14 @@ export class MinimizeOtherGroupsAction extends Action { export class ResetGroupSizesAction extends Action { - public static readonly ID = 'workbench.action.evenEditorWidths'; - public static readonly LABEL = nls.localize('evenEditorGroups', "Reset Editor Group Sizes"); + static readonly ID = 'workbench.action.evenEditorWidths'; + static readonly LABEL = nls.localize('evenEditorGroups', "Reset Editor Group Sizes"); constructor(id: string, label: string, @IEditorGroupsService private editorGroupService: IEditorGroupsService) { super(id, label); } - public run(): TPromise { + run(): TPromise { this.editorGroupService.arrangeGroups(GroupsArrangement.EVEN); return TPromise.as(false); @@ -859,8 +859,8 @@ export class ResetGroupSizesAction extends Action { export class MaximizeGroupAction extends Action { - public static readonly ID = 'workbench.action.maximizeEditor'; - public static readonly LABEL = nls.localize('maximizeEditor', "Maximize Editor Group and Hide Sidebar"); + static readonly ID = 'workbench.action.maximizeEditor'; + static readonly LABEL = nls.localize('maximizeEditor', "Maximize Editor Group and Hide Sidebar"); constructor( id: string, @@ -872,7 +872,7 @@ export class MaximizeGroupAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { if (this.editorService.activeEditor) { this.editorGroupService.arrangeGroups(GroupsArrangement.MINIMIZE_OTHERS); @@ -894,7 +894,7 @@ export abstract class BaseNavigateEditorAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { const result = this.navigate(); if (!result) { return TPromise.as(false); @@ -914,8 +914,8 @@ export abstract class BaseNavigateEditorAction extends Action { export class OpenNextEditor extends BaseNavigateEditorAction { - public static readonly ID = 'workbench.action.nextEditor'; - public static readonly LABEL = nls.localize('openNextEditor', "Open Next Editor"); + static readonly ID = 'workbench.action.nextEditor'; + static readonly LABEL = nls.localize('openNextEditor', "Open Next Editor"); constructor( id: string, @@ -949,8 +949,8 @@ export class OpenNextEditor extends BaseNavigateEditorAction { export class OpenPreviousEditor extends BaseNavigateEditorAction { - public static readonly ID = 'workbench.action.previousEditor'; - public static readonly LABEL = nls.localize('openPreviousEditor', "Open Previous Editor"); + static readonly ID = 'workbench.action.previousEditor'; + static readonly LABEL = nls.localize('openPreviousEditor', "Open Previous Editor"); constructor( id: string, @@ -984,8 +984,8 @@ export class OpenPreviousEditor extends BaseNavigateEditorAction { export class OpenNextEditorInGroup extends BaseNavigateEditorAction { - public static readonly ID = 'workbench.action.nextEditorInGroup'; - public static readonly LABEL = nls.localize('nextEditorInGroup', "Open Next Editor in Group"); + static readonly ID = 'workbench.action.nextEditorInGroup'; + static readonly LABEL = nls.localize('nextEditorInGroup', "Open Next Editor in Group"); constructor( id: string, @@ -1007,8 +1007,8 @@ export class OpenNextEditorInGroup extends BaseNavigateEditorAction { export class OpenPreviousEditorInGroup extends BaseNavigateEditorAction { - public static readonly ID = 'workbench.action.previousEditorInGroup'; - public static readonly LABEL = nls.localize('openPreviousEditorInGroup', "Open Previous Editor in Group"); + static readonly ID = 'workbench.action.previousEditorInGroup'; + static readonly LABEL = nls.localize('openPreviousEditorInGroup', "Open Previous Editor in Group"); constructor( id: string, @@ -1030,8 +1030,8 @@ export class OpenPreviousEditorInGroup extends BaseNavigateEditorAction { export class OpenFirstEditorInGroup extends BaseNavigateEditorAction { - public static readonly ID = 'workbench.action.firstEditorInGroup'; - public static readonly LABEL = nls.localize('firstEditorInGroup', "Open First Editor in Group"); + static readonly ID = 'workbench.action.firstEditorInGroup'; + static readonly LABEL = nls.localize('firstEditorInGroup', "Open First Editor in Group"); constructor( id: string, @@ -1052,8 +1052,8 @@ export class OpenFirstEditorInGroup extends BaseNavigateEditorAction { export class OpenLastEditorInGroup extends BaseNavigateEditorAction { - public static readonly ID = 'workbench.action.lastEditorInGroup'; - public static readonly LABEL = nls.localize('lastEditorInGroup', "Open Last Editor in Group"); + static readonly ID = 'workbench.action.lastEditorInGroup'; + static readonly LABEL = nls.localize('lastEditorInGroup', "Open Last Editor in Group"); constructor( id: string, @@ -1074,14 +1074,14 @@ export class OpenLastEditorInGroup extends BaseNavigateEditorAction { export class NavigateForwardAction extends Action { - public static readonly ID = 'workbench.action.navigateForward'; - public static readonly LABEL = nls.localize('navigateNext', "Go Forward"); + static readonly ID = 'workbench.action.navigateForward'; + static readonly LABEL = nls.localize('navigateNext', "Go Forward"); constructor(id: string, label: string, @IHistoryService private historyService: IHistoryService) { super(id, label); } - public run(): TPromise { + run(): TPromise { this.historyService.forward(); return TPromise.as(null); @@ -1090,14 +1090,14 @@ export class NavigateForwardAction extends Action { export class NavigateBackwardsAction extends Action { - public static readonly ID = 'workbench.action.navigateBack'; - public static readonly LABEL = nls.localize('navigatePrevious', "Go Back"); + static readonly ID = 'workbench.action.navigateBack'; + static readonly LABEL = nls.localize('navigatePrevious', "Go Back"); constructor(id: string, label: string, @IHistoryService private historyService: IHistoryService) { super(id, label); } - public run(): TPromise { + run(): TPromise { this.historyService.back(); return TPromise.as(null); @@ -1106,14 +1106,14 @@ export class NavigateBackwardsAction extends Action { export class NavigateLastAction extends Action { - public static readonly ID = 'workbench.action.navigateLast'; - public static readonly LABEL = nls.localize('navigateLast', "Go Last"); + static readonly ID = 'workbench.action.navigateLast'; + static readonly LABEL = nls.localize('navigateLast', "Go Last"); constructor(id: string, label: string, @IHistoryService private historyService: IHistoryService) { super(id, label); } - public run(): TPromise { + run(): TPromise { this.historyService.last(); return TPromise.as(null); @@ -1122,8 +1122,8 @@ export class NavigateLastAction extends Action { export class ReopenClosedEditorAction extends Action { - public static readonly ID = 'workbench.action.reopenClosedEditor'; - public static readonly LABEL = nls.localize('reopenClosedEditor', "Reopen Closed Editor"); + static readonly ID = 'workbench.action.reopenClosedEditor'; + static readonly LABEL = nls.localize('reopenClosedEditor', "Reopen Closed Editor"); constructor( id: string, @@ -1133,7 +1133,7 @@ export class ReopenClosedEditorAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { this.historyService.reopenLastClosedEditor(); return TPromise.as(false); @@ -1142,8 +1142,8 @@ export class ReopenClosedEditorAction extends Action { export class ClearRecentFilesAction extends Action { - public static readonly ID = 'workbench.action.clearRecentFiles'; - public static readonly LABEL = nls.localize('clearRecentFiles', "Clear Recently Opened"); + static readonly ID = 'workbench.action.clearRecentFiles'; + static readonly LABEL = nls.localize('clearRecentFiles', "Clear Recently Opened"); constructor( id: string, @@ -1153,7 +1153,7 @@ export class ClearRecentFilesAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { this.windowsService.clearRecentlyOpened(); return TPromise.as(false); @@ -1162,8 +1162,8 @@ export class ClearRecentFilesAction extends Action { export class ShowEditorsInActiveGroupAction extends QuickOpenAction { - public static readonly ID = 'workbench.action.showEditorsInActiveGroup'; - public static readonly LABEL = nls.localize('showEditorsInActiveGroup', "Show Editors in Active Group"); + static readonly ID = 'workbench.action.showEditorsInActiveGroup'; + static readonly LABEL = nls.localize('showEditorsInActiveGroup', "Show Editors in Active Group"); constructor( actionId: string, @@ -1176,8 +1176,8 @@ export class ShowEditorsInActiveGroupAction extends QuickOpenAction { export class ShowAllEditorsAction extends QuickOpenAction { - public static readonly ID = 'workbench.action.showAllEditors'; - public static readonly LABEL = nls.localize('showAllEditors', "Show All Editors"); + static readonly ID = 'workbench.action.showAllEditors'; + static readonly LABEL = nls.localize('showAllEditors', "Show All Editors"); constructor(actionId: string, actionLabel: string, @IQuickOpenService quickOpenService: IQuickOpenService) { super(actionId, actionLabel, NAVIGATE_ALL_EDITORS_GROUP_PREFIX, quickOpenService); @@ -1195,7 +1195,7 @@ export class BaseQuickOpenEditorInGroupAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { const keys = this.keybindingService.lookupKeybindings(this.id); @@ -1208,8 +1208,8 @@ export class BaseQuickOpenEditorInGroupAction extends Action { export class OpenPreviousRecentlyUsedEditorInGroupAction extends BaseQuickOpenEditorInGroupAction { - public static readonly ID = 'workbench.action.openPreviousRecentlyUsedEditorInGroup'; - public static readonly LABEL = nls.localize('openPreviousRecentlyUsedEditorInGroup', "Open Previous Recently Used Editor in Group"); + static readonly ID = 'workbench.action.openPreviousRecentlyUsedEditorInGroup'; + static readonly LABEL = nls.localize('openPreviousRecentlyUsedEditorInGroup', "Open Previous Recently Used Editor in Group"); constructor( id: string, @@ -1223,8 +1223,8 @@ export class OpenPreviousRecentlyUsedEditorInGroupAction extends BaseQuickOpenEd export class OpenNextRecentlyUsedEditorInGroupAction extends BaseQuickOpenEditorInGroupAction { - public static readonly ID = 'workbench.action.openNextRecentlyUsedEditorInGroup'; - public static readonly LABEL = nls.localize('openNextRecentlyUsedEditorInGroup', "Open Next Recently Used Editor in Group"); + static readonly ID = 'workbench.action.openNextRecentlyUsedEditorInGroup'; + static readonly LABEL = nls.localize('openNextRecentlyUsedEditorInGroup', "Open Next Recently Used Editor in Group"); constructor( id: string, @@ -1238,8 +1238,8 @@ export class OpenNextRecentlyUsedEditorInGroupAction extends BaseQuickOpenEditor export class OpenPreviousEditorFromHistoryAction extends Action { - public static readonly ID = 'workbench.action.openPreviousEditorFromHistory'; - public static readonly LABEL = nls.localize('navigateEditorHistoryByInput', "Open Previous Editor from History"); + static readonly ID = 'workbench.action.openPreviousEditorFromHistory'; + static readonly LABEL = nls.localize('navigateEditorHistoryByInput', "Open Previous Editor from History"); constructor( id: string, @@ -1250,7 +1250,7 @@ export class OpenPreviousEditorFromHistoryAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { const keys = this.keybindingService.lookupKeybindings(this.id); this.quickOpenService.show(null, { quickNavigateConfiguration: { keybindings: keys } }); @@ -1261,14 +1261,14 @@ export class OpenPreviousEditorFromHistoryAction extends Action { export class OpenNextRecentlyUsedEditorAction extends Action { - public static readonly ID = 'workbench.action.openNextRecentlyUsedEditor'; - public static readonly LABEL = nls.localize('openNextRecentlyUsedEditor', "Open Next Recently Used Editor"); + static readonly ID = 'workbench.action.openNextRecentlyUsedEditor'; + static readonly LABEL = nls.localize('openNextRecentlyUsedEditor', "Open Next Recently Used Editor"); constructor(id: string, label: string, @IHistoryService private historyService: IHistoryService) { super(id, label); } - public run(): TPromise { + run(): TPromise { this.historyService.forward(true); return TPromise.as(null); @@ -1277,14 +1277,14 @@ export class OpenNextRecentlyUsedEditorAction extends Action { export class OpenPreviousRecentlyUsedEditorAction extends Action { - public static readonly ID = 'workbench.action.openPreviousRecentlyUsedEditor'; - public static readonly LABEL = nls.localize('openPreviousRecentlyUsedEditor', "Open Previous Recently Used Editor"); + static readonly ID = 'workbench.action.openPreviousRecentlyUsedEditor'; + static readonly LABEL = nls.localize('openPreviousRecentlyUsedEditor', "Open Previous Recently Used Editor"); constructor(id: string, label: string, @IHistoryService private historyService: IHistoryService) { super(id, label); } - public run(): TPromise { + run(): TPromise { this.historyService.back(true); return TPromise.as(null); @@ -1293,8 +1293,8 @@ export class OpenPreviousRecentlyUsedEditorAction extends Action { export class ClearEditorHistoryAction extends Action { - public static readonly ID = 'workbench.action.clearEditorHistory'; - public static readonly LABEL = nls.localize('clearEditorHistory', "Clear Editor History"); + static readonly ID = 'workbench.action.clearEditorHistory'; + static readonly LABEL = nls.localize('clearEditorHistory', "Clear Editor History"); constructor( id: string, @@ -1304,7 +1304,7 @@ export class ClearEditorHistoryAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { // Editor history this.historyService.clear(); @@ -1315,8 +1315,8 @@ export class ClearEditorHistoryAction extends Action { export class MoveEditorLeftInGroupAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.moveEditorLeftInGroup'; - public static readonly LABEL = nls.localize('moveEditorLeft', "Move Editor Left"); + static readonly ID = 'workbench.action.moveEditorLeftInGroup'; + static readonly LABEL = nls.localize('moveEditorLeft', "Move Editor Left"); constructor( id: string, @@ -1329,8 +1329,8 @@ export class MoveEditorLeftInGroupAction extends ExecuteCommandAction { export class MoveEditorRightInGroupAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.moveEditorRightInGroup'; - public static readonly LABEL = nls.localize('moveEditorRight', "Move Editor Right"); + static readonly ID = 'workbench.action.moveEditorRightInGroup'; + static readonly LABEL = nls.localize('moveEditorRight', "Move Editor Right"); constructor( id: string, @@ -1343,8 +1343,8 @@ export class MoveEditorRightInGroupAction extends ExecuteCommandAction { export class MoveEditorToPreviousGroupAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.moveEditorToPreviousGroup'; - public static readonly LABEL = nls.localize('moveEditorToPreviousGroup', "Move Editor into Previous Group"); + static readonly ID = 'workbench.action.moveEditorToPreviousGroup'; + static readonly LABEL = nls.localize('moveEditorToPreviousGroup', "Move Editor into Previous Group"); constructor( id: string, @@ -1357,8 +1357,8 @@ export class MoveEditorToPreviousGroupAction extends ExecuteCommandAction { export class MoveEditorToNextGroupAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.moveEditorToNextGroup'; - public static readonly LABEL = nls.localize('moveEditorToNextGroup', "Move Editor into Next Group"); + static readonly ID = 'workbench.action.moveEditorToNextGroup'; + static readonly LABEL = nls.localize('moveEditorToNextGroup', "Move Editor into Next Group"); constructor( id: string, @@ -1371,8 +1371,8 @@ export class MoveEditorToNextGroupAction extends ExecuteCommandAction { export class MoveEditorToAboveGroupAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.moveEditorToAboveGroup'; - public static readonly LABEL = nls.localize('moveEditorToAboveGroup', "Move Editor into Above Group"); + static readonly ID = 'workbench.action.moveEditorToAboveGroup'; + static readonly LABEL = nls.localize('moveEditorToAboveGroup', "Move Editor into Above Group"); constructor( id: string, @@ -1385,8 +1385,8 @@ export class MoveEditorToAboveGroupAction extends ExecuteCommandAction { export class MoveEditorToBelowGroupAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.moveEditorToBelowGroup'; - public static readonly LABEL = nls.localize('moveEditorToBelowGroup', "Move Editor into Below Group"); + static readonly ID = 'workbench.action.moveEditorToBelowGroup'; + static readonly LABEL = nls.localize('moveEditorToBelowGroup', "Move Editor into Below Group"); constructor( id: string, @@ -1399,8 +1399,8 @@ export class MoveEditorToBelowGroupAction extends ExecuteCommandAction { export class MoveEditorToLeftGroupAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.moveEditorToLeftGroup'; - public static readonly LABEL = nls.localize('moveEditorToLeftGroup', "Move Editor into Left Group"); + static readonly ID = 'workbench.action.moveEditorToLeftGroup'; + static readonly LABEL = nls.localize('moveEditorToLeftGroup', "Move Editor into Left Group"); constructor( id: string, @@ -1413,8 +1413,8 @@ export class MoveEditorToLeftGroupAction extends ExecuteCommandAction { export class MoveEditorToRightGroupAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.moveEditorToRightGroup'; - public static readonly LABEL = nls.localize('moveEditorToRightGroup', "Move Editor into Right Group"); + static readonly ID = 'workbench.action.moveEditorToRightGroup'; + static readonly LABEL = nls.localize('moveEditorToRightGroup', "Move Editor into Right Group"); constructor( id: string, @@ -1427,8 +1427,8 @@ export class MoveEditorToRightGroupAction extends ExecuteCommandAction { export class MoveEditorToFirstGroupAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.moveEditorToFirstGroup'; - public static readonly LABEL = nls.localize('moveEditorToFirstGroup', "Move Editor into First Group"); + static readonly ID = 'workbench.action.moveEditorToFirstGroup'; + static readonly LABEL = nls.localize('moveEditorToFirstGroup', "Move Editor into First Group"); constructor( id: string, @@ -1441,8 +1441,8 @@ export class MoveEditorToFirstGroupAction extends ExecuteCommandAction { export class MoveEditorToLastGroupAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.moveEditorToLastGroup'; - public static readonly LABEL = nls.localize('moveEditorToLastGroup', "Move Editor into Last Group"); + static readonly ID = 'workbench.action.moveEditorToLastGroup'; + static readonly LABEL = nls.localize('moveEditorToLastGroup', "Move Editor into Last Group"); constructor( id: string, @@ -1455,8 +1455,8 @@ export class MoveEditorToLastGroupAction extends ExecuteCommandAction { export class EditorLayoutSingleAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.editorLayoutSingle'; - public static readonly LABEL = nls.localize('editorLayoutSingle', "Single Column Editor Layout"); + static readonly ID = 'workbench.action.editorLayoutSingle'; + static readonly LABEL = nls.localize('editorLayoutSingle', "Single Column Editor Layout"); constructor( id: string, @@ -1469,8 +1469,8 @@ export class EditorLayoutSingleAction extends ExecuteCommandAction { export class EditorLayoutTwoColumnsAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.editorLayoutTwoColumns'; - public static readonly LABEL = nls.localize('editorLayoutTwoColumns', "Two Columns Editor Layout"); + static readonly ID = 'workbench.action.editorLayoutTwoColumns'; + static readonly LABEL = nls.localize('editorLayoutTwoColumns', "Two Columns Editor Layout"); constructor( id: string, @@ -1483,8 +1483,8 @@ export class EditorLayoutTwoColumnsAction extends ExecuteCommandAction { export class EditorLayoutThreeColumnsAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.editorLayoutThreeColumns'; - public static readonly LABEL = nls.localize('editorLayoutThreeColumns', "Three Columns Editor Layout"); + static readonly ID = 'workbench.action.editorLayoutThreeColumns'; + static readonly LABEL = nls.localize('editorLayoutThreeColumns', "Three Columns Editor Layout"); constructor( id: string, @@ -1497,8 +1497,8 @@ export class EditorLayoutThreeColumnsAction extends ExecuteCommandAction { export class EditorLayoutTwoRowsAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.editorLayoutTwoRows'; - public static readonly LABEL = nls.localize('editorLayoutTwoRows', "Two Rows Editor Layout"); + static readonly ID = 'workbench.action.editorLayoutTwoRows'; + static readonly LABEL = nls.localize('editorLayoutTwoRows', "Two Rows Editor Layout"); constructor( id: string, @@ -1511,8 +1511,8 @@ export class EditorLayoutTwoRowsAction extends ExecuteCommandAction { export class EditorLayoutThreeRowsAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.editorLayoutThreeRows'; - public static readonly LABEL = nls.localize('editorLayoutThreeRows', "Three Rows Editor Layout"); + static readonly ID = 'workbench.action.editorLayoutThreeRows'; + static readonly LABEL = nls.localize('editorLayoutThreeRows', "Three Rows Editor Layout"); constructor( id: string, @@ -1525,8 +1525,8 @@ export class EditorLayoutThreeRowsAction extends ExecuteCommandAction { export class EditorLayoutTwoByTwoGridAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.editorLayoutTwoByTwoGrid'; - public static readonly LABEL = nls.localize('editorLayoutTwoByTwoGrid', "Grid Editor Layout (2x2)"); + static readonly ID = 'workbench.action.editorLayoutTwoByTwoGrid'; + static readonly LABEL = nls.localize('editorLayoutTwoByTwoGrid', "Grid Editor Layout (2x2)"); constructor( id: string, @@ -1539,8 +1539,8 @@ export class EditorLayoutTwoByTwoGridAction extends ExecuteCommandAction { export class EditorLayoutTwoColumnsBottomAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.editorLayoutTwoColumnsBottom'; - public static readonly LABEL = nls.localize('editorLayoutTwoColumnsBottom', "Two Columns Bottom Editor Layout"); + static readonly ID = 'workbench.action.editorLayoutTwoColumnsBottom'; + static readonly LABEL = nls.localize('editorLayoutTwoColumnsBottom', "Two Columns Bottom Editor Layout"); constructor( id: string, @@ -1553,8 +1553,8 @@ export class EditorLayoutTwoColumnsBottomAction extends ExecuteCommandAction { export class EditorLayoutTwoColumnsRightAction extends ExecuteCommandAction { - public static readonly ID = 'workbench.action.editorLayoutTwoColumnsRight'; - public static readonly LABEL = nls.localize('editorLayoutTwoColumnsRight', "Two Columns Right Editor Layout"); + static readonly ID = 'workbench.action.editorLayoutTwoColumnsRight'; + static readonly LABEL = nls.localize('editorLayoutTwoColumnsRight', "Two Columns Right Editor Layout"); constructor( id: string, @@ -1576,7 +1576,7 @@ export class BaseCreateEditorGroupAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { this.editorGroupService.addGroup(this.editorGroupService.activeGroup, this.direction, { activate: true }); return TPromise.as(true); @@ -1585,8 +1585,8 @@ export class BaseCreateEditorGroupAction extends Action { export class NewEditorGroupLeftAction extends BaseCreateEditorGroupAction { - public static readonly ID = 'workbench.action.newGroupLeft'; - public static readonly LABEL = nls.localize('newEditorLeft', "New Editor Group to the Left"); + static readonly ID = 'workbench.action.newGroupLeft'; + static readonly LABEL = nls.localize('newEditorLeft', "New Editor Group to the Left"); constructor( id: string, @@ -1599,8 +1599,8 @@ export class NewEditorGroupLeftAction extends BaseCreateEditorGroupAction { export class NewEditorGroupRightAction extends BaseCreateEditorGroupAction { - public static readonly ID = 'workbench.action.newGroupRight'; - public static readonly LABEL = nls.localize('newEditorRight', "New Editor Group to the Right"); + static readonly ID = 'workbench.action.newGroupRight'; + static readonly LABEL = nls.localize('newEditorRight', "New Editor Group to the Right"); constructor( id: string, @@ -1613,8 +1613,8 @@ export class NewEditorGroupRightAction extends BaseCreateEditorGroupAction { export class NewEditorGroupAboveAction extends BaseCreateEditorGroupAction { - public static readonly ID = 'workbench.action.newGroupAbove'; - public static readonly LABEL = nls.localize('newEditorAbove', "New Editor Group Above"); + static readonly ID = 'workbench.action.newGroupAbove'; + static readonly LABEL = nls.localize('newEditorAbove', "New Editor Group Above"); constructor( id: string, @@ -1627,8 +1627,8 @@ export class NewEditorGroupAboveAction extends BaseCreateEditorGroupAction { export class NewEditorGroupBelowAction extends BaseCreateEditorGroupAction { - public static readonly ID = 'workbench.action.newGroupBelow'; - public static readonly LABEL = nls.localize('newEditorBelow', "New Editor Group Below"); + static readonly ID = 'workbench.action.newGroupBelow'; + static readonly LABEL = nls.localize('newEditorBelow', "New Editor Group Below"); constructor( id: string, diff --git a/src/vs/workbench/browser/parts/editor/editorPart.ts b/src/vs/workbench/browser/parts/editor/editorPart.ts index 7ecdc0e61c0..e5631a42a10 100644 --- a/src/vs/workbench/browser/parts/editor/editorPart.ts +++ b/src/vs/workbench/browser/parts/editor/editorPart.ts @@ -28,9 +28,6 @@ import { Scope } from 'vs/workbench/common/memento'; import { ISerializedEditorGroup, isSerializedEditorGroup } from 'vs/workbench/common/editor/editorGroup'; import { TValueCallback, TPromise } from 'vs/base/common/winjs.base'; import { always } from 'vs/base/common/async'; -import { INotificationService, Severity } from 'vs/platform/notification/common/notification'; -import { IWindowService } from 'vs/platform/windows/common/windows'; -import { ILifecycleService, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { EditorDropTarget } from 'vs/workbench/browser/parts/editor/editorDropTarget'; import { localize } from 'vs/nls'; import { Color } from 'vs/base/common/color'; @@ -144,18 +141,13 @@ export class EditorPart extends Part implements EditorGroupsServiceImpl, IEditor private _whenRestored: TPromise; private whenRestoredComplete: TValueCallback; - private previousUIState: IEditorPartUIState; - constructor( id: string, private restorePreviousState: boolean, @IInstantiationService private instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @IConfigurationService private configurationService: IConfigurationService, - @IStorageService private storageService: IStorageService, - @INotificationService private notificationService: INotificationService, - @IWindowService private windowService: IWindowService, - @ILifecycleService private lifecycleService: ILifecycleService + @IStorageService private storageService: IStorageService ) { super(id, { hasTitle: false }, themeService); @@ -830,29 +822,15 @@ export class EditorPart extends Part implements EditorGroupsServiceImpl, IEditor private doCreateGridControlWithPreviousState(): void { const uiState = this.doGetPreviousState(); if (uiState && uiState.serializedGrid) { - try { - this.previousUIState = uiState; - // MRU - this.mostRecentActiveGroups = uiState.mostRecentActiveGroups; + // MRU + this.mostRecentActiveGroups = uiState.mostRecentActiveGroups; - // Grid Widget - this.doCreateGridControlWithState(uiState.serializedGrid, uiState.activeGroup); + // Grid Widget + this.doCreateGridControlWithState(uiState.serializedGrid, uiState.activeGroup); - // Ensure last active group has focus - this._activeGroup.focus(); - } catch (error) { - if (this.gridWidget) { - this.doSetGridWidget(); - } - - this.groupViews.forEach(group => group.dispose()); - this.groupViews.clear(); - this._activeGroup = void 0; - this.mostRecentActiveGroups = []; - - this.gridError(error); // TODO@ben remove this safe guard once the grid is stable - } + // Ensure last active group has focus + this._activeGroup.focus(); } } @@ -1028,19 +1006,6 @@ export class EditorPart extends Part implements EditorGroupsServiceImpl, IEditor return this.groupViews.size === 1 && this._activeGroup.isEmpty(); } - // TODO@ben this should be removed once the gridwidget is stable - private gridError(error: Error): void { - console.error(error); - - if (this.previousUIState) { - console.error('Serialized Grid State: ', this.previousUIState); - } - - this.lifecycleService.when(LifecyclePhase.Running).then(() => { - this.notificationService.prompt(Severity.Error, `Grid Issue: ${error}. Please report this error stack with reproducible steps.`, [{ label: 'Open DevTools', run: () => this.windowService.openDevTools() }]); - }); - } - layout(dimension: Dimension): Dimension[] { const sizes = super.layout(dimension); @@ -1053,11 +1018,7 @@ export class EditorPart extends Part implements EditorGroupsServiceImpl, IEditor this.dimension = dimension; // Layout Grid - try { - this.centeredLayoutWidget.layout(this.dimension.width, this.dimension.height); - } catch (error) { - this.gridError(error); - } + this.centeredLayoutWidget.layout(this.dimension.width, this.dimension.height); // Event this._onDidLayout.fire(dimension); diff --git a/src/vs/workbench/browser/parts/editor/editorPicker.ts b/src/vs/workbench/browser/parts/editor/editorPicker.ts index a1b7a48374d..edbf302a694 100644 --- a/src/vs/workbench/browser/parts/editor/editorPicker.ts +++ b/src/vs/workbench/browser/parts/editor/editorPicker.ts @@ -32,38 +32,38 @@ export class EditorPickerEntry extends QuickOpenEntryGroup { super(); } - public getLabelOptions(): IIconLabelValueOptions { + getLabelOptions(): IIconLabelValueOptions { return { extraClasses: getIconClasses(this.modelService, this.modeService, this.getResource()), italic: !this._group.isPinned(this.editor) }; } - public getLabel(): string { + getLabel(): string { return this.editor.getName(); } - public getIcon(): string { + getIcon(): string { return this.editor.isDirty() ? 'dirty' : ''; } - public get group(): IEditorGroup { + get group(): IEditorGroup { return this._group; } - public getResource(): URI { + getResource(): URI { return toResource(this.editor, { supportSideBySide: true }); } - public getAriaLabel(): string { + getAriaLabel(): string { return nls.localize('entryAriaLabel', "{0}, editor group picker", this.getLabel()); } - public getDescription(): string { + getDescription(): string { return this.editor.getDescription(); } - public run(mode: Mode, context: IEntryRunContext): boolean { + run(mode: Mode, context: IEntryRunContext): boolean { if (mode === Mode.OPEN) { return this.runOpen(context); } @@ -91,7 +91,7 @@ export abstract class BaseEditorPicker extends QuickOpenHandler { this.scorerCache = Object.create(null); } - public getResults(searchValue: string): TPromise { + getResults(searchValue: string): TPromise { const editorEntries = this.getEditorEntries(); if (!editorEntries.length) { return TPromise.as(null); @@ -142,7 +142,7 @@ export abstract class BaseEditorPicker extends QuickOpenHandler { return TPromise.as(new QuickOpenModel(entries)); } - public onClose(canceled: boolean): void { + onClose(canceled: boolean): void { this.scorerCache = Object.create(null); } @@ -151,7 +151,7 @@ export abstract class BaseEditorPicker extends QuickOpenHandler { export class ActiveEditorGroupPicker extends BaseEditorPicker { - public static readonly ID = 'workbench.picker.activeEditors'; + static readonly ID = 'workbench.picker.activeEditors'; protected getEditorEntries(): EditorPickerEntry[] { return this.group.getEditors(EditorsOrder.MOST_RECENTLY_ACTIVE).map((editor, index) => this.instantiationService.createInstance(EditorPickerEntry, editor, this.group)); @@ -161,7 +161,7 @@ export class ActiveEditorGroupPicker extends BaseEditorPicker { return this.editorGroupService.activeGroup; } - public getEmptyLabel(searchString: string): string { + getEmptyLabel(searchString: string): string { if (searchString) { return nls.localize('noResultsFoundInGroup', "No matching opened editor found in group"); } @@ -169,7 +169,7 @@ export class ActiveEditorGroupPicker extends BaseEditorPicker { return nls.localize('noOpenedEditors', "List of opened editors is currently empty in group"); } - public getAutoFocus(searchValue: string, context: { model: IModel, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus { + getAutoFocus(searchValue: string, context: { model: IModel, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus { if (searchValue || !context.quickNavigateConfiguration) { return { autoFocusFirstEntry: true @@ -201,7 +201,7 @@ export class ActiveEditorGroupPicker extends BaseEditorPicker { export class AllEditorsPicker extends BaseEditorPicker { - public static readonly ID = 'workbench.picker.editors'; + static readonly ID = 'workbench.picker.editors'; protected getEditorEntries(): EditorPickerEntry[] { const entries: EditorPickerEntry[] = []; @@ -215,7 +215,7 @@ export class AllEditorsPicker extends BaseEditorPicker { return entries; } - public getEmptyLabel(searchString: string): string { + getEmptyLabel(searchString: string): string { if (searchString) { return nls.localize('noResultsFound', "No matching opened editor found"); } @@ -223,7 +223,7 @@ export class AllEditorsPicker extends BaseEditorPicker { return nls.localize('noOpenedEditorsAllGroups', "List of opened editors is currently empty"); } - public getAutoFocus(searchValue: string, context: { model: IModel, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus { + getAutoFocus(searchValue: string, context: { model: IModel, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus { if (searchValue) { return { autoFocusFirstEntry: true diff --git a/src/vs/workbench/browser/parts/editor/editorStatus.ts b/src/vs/workbench/browser/parts/editor/editorStatus.ts index 525764c38fa..7b24eca3f73 100644 --- a/src/vs/workbench/browser/parts/editor/editorStatus.ts +++ b/src/vs/workbench/browser/parts/editor/editorStatus.ts @@ -62,11 +62,11 @@ import { IPreferencesService } from 'vs/workbench/services/preferences/common/pr class SideBySideEditorEncodingSupport implements IEncodingSupport { constructor(private master: IEncodingSupport, private details: IEncodingSupport) { } - public getEncoding(): string { + getEncoding(): string { return this.master.getEncoding(); // always report from modified (right hand) side } - public setEncoding(encoding: string, mode: EncodingMode): void { + setEncoding(encoding: string, mode: EncodingMode): void { [this.master, this.details].forEach(s => s.setEncoding(encoding, mode)); } } @@ -128,7 +128,7 @@ class StateChange { this.metadata = false; } - public combine(other: StateChange) { + combine(other: StateChange) { this.indentation = this.indentation || other.indentation; this.selectionStatus = this.selectionStatus || other.selectionStatus; this.mode = this.mode || other.mode; @@ -153,28 +153,28 @@ interface StateDelta { class State { private _selectionStatus: string; - public get selectionStatus(): string { return this._selectionStatus; } + get selectionStatus(): string { return this._selectionStatus; } private _mode: string; - public get mode(): string { return this._mode; } + get mode(): string { return this._mode; } private _encoding: string; - public get encoding(): string { return this._encoding; } + get encoding(): string { return this._encoding; } private _EOL: string; - public get EOL(): string { return this._EOL; } + get EOL(): string { return this._EOL; } private _indentation: string; - public get indentation(): string { return this._indentation; } + get indentation(): string { return this._indentation; } private _tabFocusMode: boolean; - public get tabFocusMode(): boolean { return this._tabFocusMode; } + get tabFocusMode(): boolean { return this._tabFocusMode; } private _screenReaderMode: boolean; - public get screenReaderMode(): boolean { return this._screenReaderMode; } + get screenReaderMode(): boolean { return this._screenReaderMode; } private _metadata: string; - public get metadata(): string { return this._metadata; } + get metadata(): string { return this._metadata; } constructor() { this._selectionStatus = null; @@ -186,7 +186,7 @@ class State { this._metadata = null; } - public update(update: StateDelta): StateChange { + update(update: StateDelta): StateChange { const e = new StateChange(); let somethingChanged = false; @@ -277,7 +277,6 @@ function hide(el: HTMLElement): void { } export class EditorStatus implements IStatusbarItem { - private state: State; private element: HTMLElement; private tabFocusModeElement: HTMLElement; @@ -308,7 +307,7 @@ export class EditorStatus implements IStatusbarItem { this.state = new State(); } - public render(container: HTMLElement): IDisposable { + render(container: HTMLElement): IDisposable { this.element = append(container, $('.editor-statusbar-item')); this.tabFocusModeElement = append(this.element, $('a.editor-status-tabfocusmode.status-bar-info')); @@ -824,8 +823,8 @@ export class ShowLanguageExtensionsAction extends Action { export class ChangeModeAction extends Action { - public static readonly ID = 'workbench.action.editor.changeLanguageMode'; - public static readonly LABEL = nls.localize('changeMode', "Change Language Mode"); + static readonly ID = 'workbench.action.editor.changeLanguageMode'; + static readonly LABEL = nls.localize('changeMode', "Change Language Mode"); constructor( actionId: string, @@ -842,7 +841,7 @@ export class ChangeModeAction extends Action { super(actionId, actionLabel); } - public run(): TPromise { + run(): TPromise { const activeTextEditorWidget = getCodeEditor(this.editorService.activeTextEditorWidget); if (!activeTextEditorWidget) { return this.quickOpenService.pick([{ label: nls.localize('noEditor', "No text editor active at this time") }]); @@ -1037,8 +1036,8 @@ export interface IChangeEOLEntry extends IPickOpenEntry { class ChangeIndentationAction extends Action { - public static readonly ID = 'workbench.action.editor.changeIndentation'; - public static readonly LABEL = nls.localize('changeIndentation', "Change Indentation"); + static readonly ID = 'workbench.action.editor.changeIndentation'; + static readonly LABEL = nls.localize('changeIndentation', "Change Indentation"); constructor( actionId: string, @@ -1049,7 +1048,7 @@ class ChangeIndentationAction extends Action { super(actionId, actionLabel); } - public run(): TPromise { + run(): TPromise { const activeTextEditorWidget = getCodeEditor(this.editorService.activeTextEditorWidget); if (!activeTextEditorWidget) { return this.quickOpenService.pick([{ label: nls.localize('noEditor', "No text editor active at this time") }]); @@ -1087,8 +1086,8 @@ class ChangeIndentationAction extends Action { export class ChangeEOLAction extends Action { - public static readonly ID = 'workbench.action.editor.changeEOL'; - public static readonly LABEL = nls.localize('changeEndOfLine', "Change End of Line Sequence"); + static readonly ID = 'workbench.action.editor.changeEOL'; + static readonly LABEL = nls.localize('changeEndOfLine', "Change End of Line Sequence"); constructor( actionId: string, @@ -1099,7 +1098,7 @@ export class ChangeEOLAction extends Action { super(actionId, actionLabel); } - public run(): TPromise { + run(): TPromise { const activeTextEditorWidget = getCodeEditor(this.editorService.activeTextEditorWidget); if (!activeTextEditorWidget) { return this.quickOpenService.pick([{ label: nls.localize('noEditor', "No text editor active at this time") }]); @@ -1132,8 +1131,8 @@ export class ChangeEOLAction extends Action { export class ChangeEncodingAction extends Action { - public static readonly ID = 'workbench.action.editor.changeEncoding'; - public static readonly LABEL = nls.localize('changeEncoding', "Change File Encoding"); + static readonly ID = 'workbench.action.editor.changeEncoding'; + static readonly LABEL = nls.localize('changeEncoding', "Change File Encoding"); constructor( actionId: string, @@ -1146,7 +1145,7 @@ export class ChangeEncodingAction extends Action { super(actionId, actionLabel); } - public run(): TPromise { + run(): TPromise { if (!getCodeEditor(this.editorService.activeTextEditorWidget)) { return this.quickOpenService.pick([{ label: nls.localize('noEditor', "No text editor active at this time") }]); } @@ -1264,7 +1263,7 @@ class ScreenReaderDetectedExplanation extends Themable { super(themeService); } - public get visible(): boolean { + get visible(): boolean { return this._visible; } @@ -1284,7 +1283,7 @@ class ScreenReaderDetectedExplanation extends Themable { } } - public show(anchorElement: HTMLElement): void { + show(anchorElement: HTMLElement): void { this._visible = true; this.contextViewService.showContextView({ @@ -1308,7 +1307,7 @@ class ScreenReaderDetectedExplanation extends Themable { }); } - public hide(): void { + hide(): void { this.contextViewService.hideContextView(); } diff --git a/src/vs/workbench/browser/parts/editor/rangeDecorations.ts b/src/vs/workbench/browser/parts/editor/rangeDecorations.ts index 6924bfb1f12..7265beb3523 100644 --- a/src/vs/workbench/browser/parts/editor/rangeDecorations.ts +++ b/src/vs/workbench/browser/parts/editor/rangeDecorations.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { IDisposable } from 'vs/base/common/lifecycle'; +import { IDisposable, Disposable } from 'vs/base/common/lifecycle'; import URI from 'vs/base/common/uri'; import { Event, Emitter } from 'vs/base/common/event'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; @@ -19,27 +19,29 @@ export interface IRangeHighlightDecoration { isWholeLine?: boolean; } -export class RangeHighlightDecorations implements IDisposable { +export class RangeHighlightDecorations extends Disposable { private rangeHighlightDecorationId: string = null; private editor: ICodeEditor = null; private editorDisposables: IDisposable[] = []; - private readonly _onHighlightRemoved: Emitter = new Emitter(); - public readonly onHighlghtRemoved: Event = this._onHighlightRemoved.event; + private readonly _onHighlightRemoved: Emitter = this._register(new Emitter()); + get onHighlghtRemoved(): Event { return this._onHighlightRemoved.event; } constructor(@IEditorService private editorService: IEditorService) { + super(); } - public removeHighlightRange() { + removeHighlightRange() { if (this.editor && this.editor.getModel() && this.rangeHighlightDecorationId) { this.editor.deltaDecorations([this.rangeHighlightDecorationId], []); this._onHighlightRemoved.fire(); } + this.rangeHighlightDecorationId = null; } - public highlightRange(range: IRangeHighlightDecoration, editor?: ICodeEditor) { + highlightRange(range: IRangeHighlightDecoration, editor?: ICodeEditor) { editor = editor ? editor : this.getEditor(range); if (editor) { this.doHighlightRange(editor, range); @@ -48,9 +50,11 @@ export class RangeHighlightDecorations implements IDisposable { private doHighlightRange(editor: ICodeEditor, selectionRange: IRangeHighlightDecoration) { this.removeHighlightRange(); + editor.changeDecorations((changeAccessor: IModelDecorationsChangeAccessor) => { this.rangeHighlightDecorationId = changeAccessor.addDecoration(selectionRange.range, this.createRangeHighlightDecoration(selectionRange.isWholeLine)); }); + this.setEditor(editor); } @@ -62,6 +66,7 @@ export class RangeHighlightDecorations implements IDisposable { return this.editorService.activeTextEditorWidget as ICodeEditor; } } + return null; } @@ -107,7 +112,9 @@ export class RangeHighlightDecorations implements IDisposable { return (isWholeLine ? RangeHighlightDecorations._WHOLE_LINE_RANGE_HIGHLIGHT : RangeHighlightDecorations._RANGE_HIGHLIGHT); } - public dispose() { + dispose() { + super.dispose(); + if (this.editor && this.editor.getModel()) { this.removeHighlightRange(); this.disposeEditorListeners(); diff --git a/src/vs/workbench/browser/parts/editor/resourceViewer.ts b/src/vs/workbench/browser/parts/editor/resourceViewer.ts index b7962916769..61c35f3f786 100644 --- a/src/vs/workbench/browser/parts/editor/resourceViewer.ts +++ b/src/vs/workbench/browser/parts/editor/resourceViewer.ts @@ -35,12 +35,12 @@ export interface IResourceDescriptor { } class BinarySize { - public static readonly KB = 1024; - public static readonly MB = BinarySize.KB * BinarySize.KB; - public static readonly GB = BinarySize.MB * BinarySize.KB; - public static readonly TB = BinarySize.GB * BinarySize.KB; + static readonly KB = 1024; + static readonly MB = BinarySize.KB * BinarySize.KB; + static readonly GB = BinarySize.MB * BinarySize.KB; + static readonly TB = BinarySize.GB * BinarySize.KB; - public static formatSize(size: number): string { + static formatSize(size: number): string { if (size < BinarySize.KB) { return nls.localize('sizeB', "{0}B", size); } @@ -73,7 +73,7 @@ export class ResourceViewer { private static readonly MAX_OPEN_INTERNAL_SIZE = BinarySize.MB * 200; // max size until we offer an action to open internally - public static show( + static show( descriptor: IResourceDescriptor, fileService: IFileService, container: HTMLElement, @@ -115,7 +115,7 @@ class ImageView { private static readonly MAX_IMAGE_SIZE = BinarySize.MB; // showing images inline is memory intense, so we have a limit private static readonly BASE64_MARKER = 'base64,'; - public static create( + static create( container: HTMLElement, descriptor: IResourceDescriptor, fileService: IFileService, @@ -153,7 +153,7 @@ class ImageView { } class LargeImageView { - public static create( + static create( container: HTMLElement, descriptor: IResourceDescriptor, openExternalClb: (uri: URI) => void @@ -179,7 +179,7 @@ class LargeImageView { } class FileTooLargeFileView { - public static create( + static create( container: HTMLElement, descriptor: IResourceDescriptor, scrollbar: DomScrollableElement, @@ -202,7 +202,7 @@ class FileTooLargeFileView { } class FileSeemsBinaryFileView { - public static create( + static create( container: HTMLElement, descriptor: IResourceDescriptor, scrollbar: DomScrollableElement, @@ -236,11 +236,12 @@ class FileSeemsBinaryFileView { type Scale = number | 'fit'; class ZoomStatusbarItem extends Themable implements IStatusbarItem { + + static instance: ZoomStatusbarItem; + showTimeout: number; - public static instance: ZoomStatusbarItem; private statusBarItem: HTMLElement; - private onSelectScale?: (scale: Scale) => void; constructor( @@ -249,8 +250,10 @@ class ZoomStatusbarItem extends Themable implements IStatusbarItem { @IThemeService themeService: IThemeService ) { super(themeService); + ZoomStatusbarItem.instance = this; - this.toUnbind.push(editorService.onDidActiveEditorChange(() => this.onActiveEditorChanged())); + + this._register(editorService.onDidActiveEditorChange(() => this.onActiveEditorChanged())); } private onActiveEditorChanged(): void { @@ -258,7 +261,7 @@ class ZoomStatusbarItem extends Themable implements IStatusbarItem { this.onSelectScale = void 0; } - public show(scale: Scale, onSelectScale: (scale: number) => void) { + show(scale: Scale, onSelectScale: (scale: number) => void) { clearTimeout(this.showTimeout); this.showTimeout = setTimeout(() => { this.onSelectScale = onSelectScale; @@ -267,11 +270,11 @@ class ZoomStatusbarItem extends Themable implements IStatusbarItem { }, 0); } - public hide() { + hide() { this.statusBarItem.style.display = 'none'; } - public render(container: HTMLElement): IDisposable { + render(container: HTMLElement): IDisposable { if (!this.statusBarItem && container) { this.statusBarItem = $(container).a() .addClass('.zoom-statusbar-item') @@ -358,7 +361,7 @@ class InlineImageView { */ private static readonly imageStateCache = new LRUCache(100); - public static create( + static create( container: HTMLElement, descriptor: IResourceDescriptor, fileService: IFileService, @@ -563,6 +566,7 @@ class InlineImageView { return fileService.resolveContent(descriptor.resource, { encoding: 'base64' }).then(data => { const mime = getMime(descriptor); + return `data:${mime};base64,${data.value}`; }); } diff --git a/src/vs/workbench/browser/parts/editor/sideBySideEditor.ts b/src/vs/workbench/browser/parts/editor/sideBySideEditor.ts index 48230a73d7b..b262ab1f852 100644 --- a/src/vs/workbench/browser/parts/editor/sideBySideEditor.ts +++ b/src/vs/workbench/browser/parts/editor/sideBySideEditor.ts @@ -44,9 +44,9 @@ export class SideBySideEditor extends BaseEditor { get maximumHeight() { return this.maximumMasterHeight + this.maximumDetailsHeight; } protected masterEditor: BaseEditor; - private masterEditorContainer: HTMLElement; - protected detailsEditor: BaseEditor; + + private masterEditorContainer: HTMLElement; private detailsEditorContainer: HTMLElement; private splitview: SplitView; @@ -54,7 +54,7 @@ export class SideBySideEditor extends BaseEditor { private onDidCreateEditors = this._register(new Emitter<{ width: number; height: number; }>()); private _onDidSizeConstraintsChange = this._register(new Relay<{ width: number; height: number; }>()); - readonly onDidSizeConstraintsChange: Event<{ width: number; height: number; }> = anyEvent(this.onDidCreateEditors.event, this._onDidSizeConstraintsChange.event); + get onDidSizeConstraintsChange(): Event<{ width: number; height: number; }> { return anyEvent(this.onDidCreateEditors.event, this._onDidSizeConstraintsChange.event); } constructor( @ITelemetryService telemetryService: ITelemetryService, @@ -67,8 +67,7 @@ export class SideBySideEditor extends BaseEditor { protected createEditor(parent: HTMLElement): void { DOM.addClass(parent, 'side-by-side-editor'); - this.splitview = new SplitView(parent, { orientation: Orientation.HORIZONTAL }); - this._register(this.splitview); + this.splitview = this._register(new SplitView(parent, { orientation: Orientation.HORIZONTAL })); this._register(this.splitview.onDidSashReset(() => this.splitview.distributeViewSizes())); this.detailsEditorContainer = DOM.$('.details-editor-container'); @@ -158,9 +157,9 @@ export class SideBySideEditor extends BaseEditor { } return this.setNewInput(newInput, options, token); - } else { - return TPromise.join([this.detailsEditor.setInput(newInput.details, null, token), this.masterEditor.setInput(newInput.master, options, token)]).then(() => void 0); } + + return TPromise.join([this.detailsEditor.setInput(newInput.details, null, token), this.masterEditor.setInput(newInput.master, options, token)]).then(() => void 0); } private setNewInput(newInput: SideBySideEditorInput, options: EditorOptions, token: CancellationToken): Thenable { diff --git a/src/vs/workbench/browser/parts/editor/textDiffEditor.ts b/src/vs/workbench/browser/parts/editor/textDiffEditor.ts index 79e99140767..190eb410696 100644 --- a/src/vs/workbench/browser/parts/editor/textDiffEditor.ts +++ b/src/vs/workbench/browser/parts/editor/textDiffEditor.ts @@ -43,7 +43,7 @@ import { EditorMemento } from 'vs/workbench/browser/parts/editor/baseEditor'; */ export class TextDiffEditor extends BaseTextEditor implements ITextDiffEditor { - public static readonly ID = TEXT_DIFF_EDITOR_ID; + static readonly ID = TEXT_DIFF_EDITOR_ID; private diffNavigator: DiffNavigator; private diffNavigatorDisposables: IDisposable[] = []; @@ -64,7 +64,7 @@ export class TextDiffEditor extends BaseTextEditor implements ITextDiffEditor { ) { super(TextDiffEditor.ID, telemetryService, instantiationService, storageService, configurationService, themeService, textFileService, editorService, editorGroupService); - this.toUnbind.push(this._actualConfigurationService.onDidChangeConfiguration((e) => { + this._register(this._actualConfigurationService.onDidChangeConfiguration((e) => { if (e.affectsConfiguration('diffEditor.ignoreTrimWhitespace')) { this.updateIgnoreTrimWhitespaceAction(); } @@ -75,7 +75,7 @@ export class TextDiffEditor extends BaseTextEditor implements ITextDiffEditor { return new EditorMemento(this.getId(), key, Object.create(null), limit, editorGroupService); // do not persist in storage as diff editors are never persisted } - public getTitle(): string { + getTitle(): string { if (this.input) { return this.input.getName(); } @@ -83,7 +83,7 @@ export class TextDiffEditor extends BaseTextEditor implements ITextDiffEditor { return nls.localize('textDiffEditor', "Text Diff Editor"); } - public createEditorControl(parent: HTMLElement, configuration: ICodeEditorOptions): IDiffEditor { + createEditorControl(parent: HTMLElement, configuration: ICodeEditorOptions): IDiffEditor { // Actions this.nextDiffAction = new NavigateAction(this, true); @@ -94,7 +94,7 @@ export class TextDiffEditor extends BaseTextEditor implements ITextDiffEditor { return this.instantiationService.createInstance(DiffEditorWidget, parent, configuration); } - public setInput(input: EditorInput, options: EditorOptions, token: CancellationToken): Thenable { + setInput(input: EditorInput, options: EditorOptions, token: CancellationToken): Thenable { // Dispose previous diff navigator this.diffNavigatorDisposables = dispose(this.diffNavigatorDisposables); @@ -162,7 +162,7 @@ export class TextDiffEditor extends BaseTextEditor implements ITextDiffEditor { }); } - public setOptions(options: EditorOptions): void { + setOptions(options: EditorOptions): void { const textOptions = options; if (textOptions && types.isFunction(textOptions.apply)) { textOptions.apply(this.getControl(), ScrollType.Smooth); @@ -270,7 +270,7 @@ export class TextDiffEditor extends BaseTextEditor implements ITextDiffEditor { return (error).fileOperationResult === FileOperationResult.FILE_IS_BINARY; } - public clearInput(): void { + clearInput(): void { // Dispose previous diff navigator this.diffNavigatorDisposables = dispose(this.diffNavigatorDisposables); @@ -285,11 +285,11 @@ export class TextDiffEditor extends BaseTextEditor implements ITextDiffEditor { super.clearInput(); } - public getDiffNavigator(): DiffNavigator { + getDiffNavigator(): DiffNavigator { return this.diffNavigator; } - public getActions(): IAction[] { + getActions(): IAction[] { return [ this.toggleIgnoreTrimWhitespaceAction, this.previousDiffAction, @@ -297,7 +297,7 @@ export class TextDiffEditor extends BaseTextEditor implements ITextDiffEditor { ]; } - public getControl(): IDiffEditor { + getControl(): IDiffEditor { return super.getControl() as IDiffEditor; } @@ -374,7 +374,7 @@ export class TextDiffEditor extends BaseTextEditor implements ITextDiffEditor { return URI.from({ scheme: 'diff', path: `${btoa(original.toString())}${btoa(modified.toString())}` }); } - public dispose(): void { + dispose(): void { this.diffNavigatorDisposables = dispose(this.diffNavigatorDisposables); super.dispose(); @@ -399,7 +399,7 @@ class NavigateAction extends Action { this.enabled = false; } - public run(): TPromise { + run(): TPromise { if (this.next) { this.editor.getDiffNavigator().next(); } else { @@ -409,7 +409,7 @@ class NavigateAction extends Action { return null; } - public updateEnablement(): void { + updateEnablement(): void { this.enabled = this.editor.getDiffNavigator().canNavigate(); } } @@ -426,12 +426,12 @@ class ToggleIgnoreTrimWhitespaceAction extends Action { this.label = nls.localize('toggleIgnoreTrimWhitespace.label', "Ignore Trim Whitespace"); } - public updateClassName(ignoreTrimWhitespace: boolean): void { + updateClassName(ignoreTrimWhitespace: boolean): void { this._isChecked = ignoreTrimWhitespace; this.class = `textdiff-editor-action toggleIgnoreTrimWhitespace${this._isChecked ? ' is-checked' : ''}`; } - public run(): TPromise { + run(): TPromise { this._configurationService.updateValue(`diffEditor.ignoreTrimWhitespace`, !this._isChecked); return null; } diff --git a/src/vs/workbench/browser/parts/editor/textEditor.ts b/src/vs/workbench/browser/parts/editor/textEditor.ts index 2e95f5f50db..50ff252902e 100644 --- a/src/vs/workbench/browser/parts/editor/textEditor.ts +++ b/src/vs/workbench/browser/parts/editor/textEditor.ts @@ -60,7 +60,7 @@ export abstract class BaseTextEditor extends BaseEditor implements ITextEditor { this.editorMemento = this.getEditorMemento(storageService, editorGroupService, TEXT_EDITOR_VIEW_STATE_PREFERENCE_KEY, 100); - this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => this.handleConfigurationChangeEvent(this.configurationService.getValue(this.getResource())))); + this._register(this.configurationService.onDidChangeConfiguration(e => this.handleConfigurationChangeEvent(this.configurationService.getValue(this.getResource())))); } protected get instantiationService(): IInstantiationService { @@ -130,25 +130,25 @@ export abstract class BaseTextEditor extends BaseEditor implements ITextEditor { // Editor for Text this._editorContainer = parent; - this.editorControl = this.createEditorControl(parent, this.computeConfiguration(this.configurationService.getValue(this.getResource()))); + this.editorControl = this._register(this.createEditorControl(parent, this.computeConfiguration(this.configurationService.getValue(this.getResource())))); // Model & Language changes const codeEditor = getCodeEditor(this.editorControl); if (codeEditor) { - this.toUnbind.push(codeEditor.onDidChangeModelLanguage(e => this.updateEditorConfiguration())); - this.toUnbind.push(codeEditor.onDidChangeModel(e => this.updateEditorConfiguration())); + this._register(codeEditor.onDidChangeModelLanguage(e => this.updateEditorConfiguration())); + this._register(codeEditor.onDidChangeModel(e => this.updateEditorConfiguration())); } // Application & Editor focus change to respect auto save settings if (isCodeEditor(this.editorControl)) { - this.toUnbind.push(this.editorControl.onDidBlurEditorWidget(() => this.onEditorFocusLost())); + this._register(this.editorControl.onDidBlurEditorWidget(() => this.onEditorFocusLost())); } else if (isDiffEditor(this.editorControl)) { - this.toUnbind.push(this.editorControl.getOriginalEditor().onDidBlurEditorWidget(() => this.onEditorFocusLost())); - this.toUnbind.push(this.editorControl.getModifiedEditor().onDidBlurEditorWidget(() => this.onEditorFocusLost())); + this._register(this.editorControl.getOriginalEditor().onDidBlurEditorWidget(() => this.onEditorFocusLost())); + this._register(this.editorControl.getModifiedEditor().onDidBlurEditorWidget(() => this.onEditorFocusLost())); } - this.toUnbind.push(this.editorService.onDidActiveEditorChange(() => this.onEditorFocusLost())); - this.toUnbind.push(DOM.addDisposableListener(window, DOM.EventType.BLUR, () => this.onWindowFocusLost())); + this._register(this.editorService.onDidActiveEditorChange(() => this.onEditorFocusLost())); + this._register(DOM.addDisposableListener(window, DOM.EventType.BLUR, () => this.onWindowFocusLost())); } private onEditorFocusLost(): void { @@ -186,7 +186,7 @@ export abstract class BaseTextEditor extends BaseEditor implements ITextEditor { return this.instantiationService.createInstance(CodeEditorWidget, parent, configuration, {}); } - public setInput(input: EditorInput, options: EditorOptions, token: CancellationToken): Thenable { + setInput(input: EditorInput, options: EditorOptions, token: CancellationToken): Thenable { return super.setInput(input, options, token).then(() => { // Update editor options after having set the input. We do this because there can be @@ -209,17 +209,17 @@ export abstract class BaseTextEditor extends BaseEditor implements ITextEditor { super.setEditorVisible(visible, group); } - public focus(): void { + focus(): void { this.editorControl.focus(); } - public layout(dimension: DOM.Dimension): void { + layout(dimension: DOM.Dimension): void { // Pass on to Editor this.editorControl.layout(dimension); } - public getControl(): IEditor { + getControl(): IEditor { return this.editorControl; } @@ -309,9 +309,8 @@ export abstract class BaseTextEditor extends BaseEditor implements ITextEditor { protected abstract getAriaLabel(): string; - public dispose(): void { + dispose(): void { this.lastAppliedEditorOptions = void 0; - this.editorControl.dispose(); super.dispose(); } diff --git a/src/vs/workbench/browser/parts/editor/textResourceEditor.ts b/src/vs/workbench/browser/parts/editor/textResourceEditor.ts index e58de5a1c6e..2154600d6a8 100644 --- a/src/vs/workbench/browser/parts/editor/textResourceEditor.ts +++ b/src/vs/workbench/browser/parts/editor/textResourceEditor.ts @@ -46,7 +46,7 @@ export class AbstractTextResourceEditor extends BaseTextEditor { super(id, telemetryService, instantiationService, storageService, configurationService, themeService, textFileService, editorService, editorGroupService); } - public getTitle(): string { + getTitle(): string { if (this.input) { return this.input.getName(); } @@ -54,7 +54,7 @@ export class AbstractTextResourceEditor extends BaseTextEditor { return nls.localize('textEditor', "Text Editor"); } - public setInput(input: EditorInput, options: EditorOptions, token: CancellationToken): Thenable { + setInput(input: EditorInput, options: EditorOptions, token: CancellationToken): Thenable { // Remember view settings if input changes this.saveTextResourceEditorViewState(this.input); @@ -104,7 +104,7 @@ export class AbstractTextResourceEditor extends BaseTextEditor { } } - public setOptions(options: EditorOptions): void { + setOptions(options: EditorOptions): void { const textOptions = options; if (textOptions && types.isFunction(textOptions.apply)) { textOptions.apply(this.getControl(), ScrollType.Smooth); @@ -140,7 +140,7 @@ export class AbstractTextResourceEditor extends BaseTextEditor { * This allows users to click on the output panel to stop scrolling when they see something of interest. * To resume, they should scroll to the end of the output panel again. */ - public revealLastLine(smart: boolean): void { + revealLastLine(smart: boolean): void { const codeEditor = this.getControl(); const model = codeEditor.getModel(); @@ -152,7 +152,7 @@ export class AbstractTextResourceEditor extends BaseTextEditor { } } - public clearInput(): void { + clearInput(): void { // Keep editor view state in settings to restore when coming back this.saveTextResourceEditorViewState(this.input); @@ -163,7 +163,7 @@ export class AbstractTextResourceEditor extends BaseTextEditor { super.clearInput(); } - public shutdown(): void { + shutdown(): void { // Save View State (only for untitled) if (this.input instanceof UntitledEditorInput) { @@ -200,7 +200,7 @@ export class AbstractTextResourceEditor extends BaseTextEditor { export class TextResourceEditor extends AbstractTextResourceEditor { - public static readonly ID = 'workbench.editors.textResourceEditor'; + static readonly ID = 'workbench.editors.textResourceEditor'; constructor( @ITelemetryService telemetryService: ITelemetryService, diff --git a/src/vs/workbench/browser/parts/notifications/notificationsActions.ts b/src/vs/workbench/browser/parts/notifications/notificationsActions.ts index 71923117b10..926b168f6a6 100644 --- a/src/vs/workbench/browser/parts/notifications/notificationsActions.ts +++ b/src/vs/workbench/browser/parts/notifications/notificationsActions.ts @@ -18,8 +18,8 @@ import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService export class ClearNotificationAction extends Action { - public static readonly ID = CLEAR_NOTIFICATION; - public static readonly LABEL = localize('clearNotification', "Clear Notification"); + static readonly ID = CLEAR_NOTIFICATION; + static readonly LABEL = localize('clearNotification', "Clear Notification"); constructor( id: string, @@ -29,7 +29,7 @@ export class ClearNotificationAction extends Action { super(id, label, 'clear-notification-action'); } - public run(notification: INotificationViewItem): TPromise { + run(notification: INotificationViewItem): TPromise { this.commandService.executeCommand(CLEAR_NOTIFICATION, notification); return TPromise.as(void 0); @@ -38,8 +38,8 @@ export class ClearNotificationAction extends Action { export class ClearAllNotificationsAction extends Action { - public static readonly ID = CLEAR_ALL_NOTIFICATIONS; - public static readonly LABEL = localize('clearNotifications', "Clear All Notifications"); + static readonly ID = CLEAR_ALL_NOTIFICATIONS; + static readonly LABEL = localize('clearNotifications', "Clear All Notifications"); constructor( id: string, @@ -49,7 +49,7 @@ export class ClearAllNotificationsAction extends Action { super(id, label, 'clear-all-notifications-action'); } - public run(notification: INotificationViewItem): TPromise { + run(notification: INotificationViewItem): TPromise { this.commandService.executeCommand(CLEAR_ALL_NOTIFICATIONS); return TPromise.as(void 0); @@ -58,8 +58,8 @@ export class ClearAllNotificationsAction extends Action { export class HideNotificationsCenterAction extends Action { - public static readonly ID = HIDE_NOTIFICATIONS_CENTER; - public static readonly LABEL = localize('hideNotificationsCenter', "Hide Notifications"); + static readonly ID = HIDE_NOTIFICATIONS_CENTER; + static readonly LABEL = localize('hideNotificationsCenter', "Hide Notifications"); constructor( id: string, @@ -69,7 +69,7 @@ export class HideNotificationsCenterAction extends Action { super(id, label, 'hide-all-notifications-action'); } - public run(notification: INotificationViewItem): TPromise { + run(notification: INotificationViewItem): TPromise { this.commandService.executeCommand(HIDE_NOTIFICATIONS_CENTER); return TPromise.as(void 0); @@ -78,8 +78,8 @@ export class HideNotificationsCenterAction extends Action { export class ExpandNotificationAction extends Action { - public static readonly ID = EXPAND_NOTIFICATION; - public static readonly LABEL = localize('expandNotification', "Expand Notification"); + static readonly ID = EXPAND_NOTIFICATION; + static readonly LABEL = localize('expandNotification', "Expand Notification"); constructor( id: string, @@ -89,7 +89,7 @@ export class ExpandNotificationAction extends Action { super(id, label, 'expand-notification-action'); } - public run(notification: INotificationViewItem): TPromise { + run(notification: INotificationViewItem): TPromise { this.commandService.executeCommand(EXPAND_NOTIFICATION, notification); return TPromise.as(void 0); @@ -98,8 +98,8 @@ export class ExpandNotificationAction extends Action { export class CollapseNotificationAction extends Action { - public static readonly ID = COLLAPSE_NOTIFICATION; - public static readonly LABEL = localize('collapseNotification', "Collapse Notification"); + static readonly ID = COLLAPSE_NOTIFICATION; + static readonly LABEL = localize('collapseNotification', "Collapse Notification"); constructor( id: string, @@ -109,7 +109,7 @@ export class CollapseNotificationAction extends Action { super(id, label, 'collapse-notification-action'); } - public run(notification: INotificationViewItem): TPromise { + run(notification: INotificationViewItem): TPromise { this.commandService.executeCommand(COLLAPSE_NOTIFICATION, notification); return TPromise.as(void 0); @@ -118,8 +118,8 @@ export class CollapseNotificationAction extends Action { export class ConfigureNotificationAction extends Action { - public static readonly ID = 'workbench.action.configureNotification'; - public static readonly LABEL = localize('configureNotification', "Configure Notification"); + static readonly ID = 'workbench.action.configureNotification'; + static readonly LABEL = localize('configureNotification', "Configure Notification"); constructor( id: string, @@ -129,15 +129,15 @@ export class ConfigureNotificationAction extends Action { super(id, label, 'configure-notification-action'); } - public get configurationActions(): IAction[] { + get configurationActions(): IAction[] { return this._configurationActions; } } export class CopyNotificationMessageAction extends Action { - public static readonly ID = 'workbench.action.copyNotificationMessage'; - public static readonly LABEL = localize('copyNotification', "Copy Text"); + static readonly ID = 'workbench.action.copyNotificationMessage'; + static readonly LABEL = localize('copyNotification', "Copy Text"); constructor( id: string, @@ -147,7 +147,7 @@ export class CopyNotificationMessageAction extends Action { super(id, label); } - public run(notification: INotificationViewItem): TPromise { + run(notification: INotificationViewItem): TPromise { this.clipboardService.writeText(notification.message.raw); return TPromise.as(void 0); diff --git a/src/vs/workbench/browser/parts/notifications/notificationsAlerts.ts b/src/vs/workbench/browser/parts/notifications/notificationsAlerts.ts index 9d7e25af5ab..f6c6d6379f3 100644 --- a/src/vs/workbench/browser/parts/notifications/notificationsAlerts.ts +++ b/src/vs/workbench/browser/parts/notifications/notificationsAlerts.ts @@ -8,15 +8,14 @@ import { alert } from 'vs/base/browser/ui/aria/aria'; import { localize } from 'vs/nls'; import { INotificationViewItem, INotificationsModel, NotificationChangeType, INotificationChangeEvent } from 'vs/workbench/common/notifications'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { Severity } from 'vs/platform/notification/common/notification'; -export class NotificationsAlerts { - private toDispose: IDisposable[]; +export class NotificationsAlerts extends Disposable { constructor(private model: INotificationsModel) { - this.toDispose = []; + super(); // Alert initial notifications if any model.notifications.forEach(n => this.ariaAlert(n)); @@ -25,7 +24,7 @@ export class NotificationsAlerts { } private registerListeners(): void { - this.toDispose.push(this.model.onDidNotificationChange(e => this.onDidNotificationChange(e))); + this._register(this.model.onDidNotificationChange(e => this.onDidNotificationChange(e))); } private onDidNotificationChange(e: INotificationChangeEvent): void { @@ -57,8 +56,4 @@ export class NotificationsAlerts { alert(alertText); } - - public dispose(): void { - this.toDispose = dispose(this.toDispose); - } } \ No newline at end of file diff --git a/src/vs/workbench/browser/parts/notifications/notificationsCenter.ts b/src/vs/workbench/browser/parts/notifications/notificationsCenter.ts index 750aeb9764f..fd3ecd2e007 100644 --- a/src/vs/workbench/browser/parts/notifications/notificationsCenter.ts +++ b/src/vs/workbench/browser/parts/notifications/notificationsCenter.ts @@ -29,13 +29,15 @@ export class NotificationsCenter extends Themable { private static MAX_DIMENSIONS = new Dimension(450, 400); + private readonly _onDidChangeVisibility: Emitter = this._register(new Emitter()); + get onDidChangeVisibility(): Event { return this._onDidChangeVisibility.event; } + private notificationsCenterContainer: HTMLElement; private notificationsCenterHeader: HTMLElement; private notificationsCenterTitle: HTMLSpanElement; private notificationsList: NotificationsList; private _isVisible: boolean; private workbenchDimensions: Dimension; - private readonly _onDidChangeVisibility: Emitter; private notificationsCenterVisibleContextKey: IContextKey; constructor( @@ -50,27 +52,20 @@ export class NotificationsCenter extends Themable { ) { super(themeService); - this._onDidChangeVisibility = new Emitter(); - this.toUnbind.push(this._onDidChangeVisibility); - this.notificationsCenterVisibleContextKey = NotificationsCenterVisibleContext.bindTo(contextKeyService); this.registerListeners(); } private registerListeners(): void { - this.toUnbind.push(this.model.onDidNotificationChange(e => this.onDidNotificationChange(e))); + this._register(this.model.onDidNotificationChange(e => this.onDidNotificationChange(e))); } - public get onDidChangeVisibility(): Event { - return this._onDidChangeVisibility.event; - } - - public get isVisible(): boolean { + get isVisible(): boolean { return this._isVisible; } - public show(): void { + show(): void { if (this._isVisible) { this.notificationsList.show(true /* focus */); @@ -138,21 +133,17 @@ export class NotificationsCenter extends Themable { addClass(toolbarContainer, 'notifications-center-header-toolbar'); this.notificationsCenterHeader.appendChild(toolbarContainer); - const actionRunner = this.instantiationService.createInstance(NotificationActionRunner); - this.toUnbind.push(actionRunner); + const actionRunner = this._register(this.instantiationService.createInstance(NotificationActionRunner)); - const notificationsToolBar = new ActionBar(toolbarContainer, { + const notificationsToolBar = this._register(new ActionBar(toolbarContainer, { ariaLabel: localize('notificationsToolbar', "Notification Center Actions"), actionRunner - }); - this.toUnbind.push(notificationsToolBar); + })); - const hideAllAction = this.instantiationService.createInstance(HideNotificationsCenterAction, HideNotificationsCenterAction.ID, HideNotificationsCenterAction.LABEL); - this.toUnbind.push(hideAllAction); + const hideAllAction = this._register(this.instantiationService.createInstance(HideNotificationsCenterAction, HideNotificationsCenterAction.ID, HideNotificationsCenterAction.LABEL)); notificationsToolBar.push(hideAllAction, { icon: true, label: false, keybinding: this.getKeybindingLabel(hideAllAction) }); - const clearAllAction = this.instantiationService.createInstance(ClearAllNotificationsAction, ClearAllNotificationsAction.ID, ClearAllNotificationsAction.LABEL); - this.toUnbind.push(clearAllAction); + const clearAllAction = this._register(this.instantiationService.createInstance(ClearAllNotificationsAction, ClearAllNotificationsAction.ID, ClearAllNotificationsAction.LABEL)); notificationsToolBar.push(clearAllAction, { icon: true, label: false, keybinding: this.getKeybindingLabel(clearAllAction) }); // Notifications List @@ -204,7 +195,7 @@ export class NotificationsCenter extends Themable { } } - public hide(): void { + hide(): void { if (!this._isVisible || !this.notificationsCenterContainer) { return; // already hidden } @@ -244,7 +235,7 @@ export class NotificationsCenter extends Themable { } } - public layout(dimension: Dimension): void { + layout(dimension: Dimension): void { this.workbenchDimensions = dimension; if (this._isVisible && this.notificationsCenterContainer) { @@ -278,7 +269,7 @@ export class NotificationsCenter extends Themable { } } - public clearAll(): void { + clearAll(): void { // Hide notifications center first this.hide(); diff --git a/src/vs/workbench/browser/parts/notifications/notificationsList.ts b/src/vs/workbench/browser/parts/notifications/notificationsList.ts index 3f4cb3ad968..094a62f91fd 100644 --- a/src/vs/workbench/browser/parts/notifications/notificationsList.ts +++ b/src/vs/workbench/browser/parts/notifications/notificationsList.ts @@ -38,7 +38,7 @@ export class NotificationsList extends Themable { this.viewModel = []; } - public show(focus?: boolean): void { + show(focus?: boolean): void { if (this.isVisible) { if (focus) { this.list.domFocus(); @@ -67,47 +67,43 @@ export class NotificationsList extends Themable { this.listContainer = document.createElement('div'); addClass(this.listContainer, 'notifications-list-container'); - const actionRunner = this.instantiationService.createInstance(NotificationActionRunner); - this.toUnbind.push(actionRunner); + const actionRunner = this._register(this.instantiationService.createInstance(NotificationActionRunner)); // Notification Renderer const renderer = this.instantiationService.createInstance(NotificationRenderer, actionRunner); // List - this.list = >this.instantiationService.createInstance( + this.list = this._register(>this.instantiationService.createInstance( WorkbenchList, this.listContainer, new NotificationsListDelegate(this.listContainer), [renderer], this.options - ); - this.toUnbind.push(this.list); + )); // Context menu to copy message - const copyAction = this.instantiationService.createInstance(CopyNotificationMessageAction, CopyNotificationMessageAction.ID, CopyNotificationMessageAction.LABEL); - this.toUnbind.push(copyAction); - this.toUnbind.push(this.list.onContextMenu(e => { + const copyAction = this._register(this.instantiationService.createInstance(CopyNotificationMessageAction, CopyNotificationMessageAction.ID, CopyNotificationMessageAction.LABEL)); + this._register((this.list.onContextMenu(e => { this.contextMenuService.showContextMenu({ getAnchor: () => e.anchor, getActions: () => TPromise.as([copyAction]), getActionsContext: () => e.element, actionRunner }); - })); + }))); // Toggle on double click - this.toUnbind.push(this.list.onMouseDblClick(event => (event.element as INotificationViewItem).toggle())); + this._register((this.list.onMouseDblClick(event => (event.element as INotificationViewItem).toggle()))); // Clear focus when DOM focus moves out // Use document.hasFocus() to not clear the focus when the entire window lost focus // This ensures that when the focus comes back, the notifciation is still focused - const listFocusTracker = trackFocus(this.list.getHTMLElement()); - listFocusTracker.onDidBlur(() => { + const listFocusTracker = this._register(trackFocus(this.list.getHTMLElement())); + this._register(listFocusTracker.onDidBlur(() => { if (document.hasFocus()) { this.list.setFocus([]); } - }); - this.toUnbind.push(listFocusTracker); + })); // Context key NotificationFocusedContext.bindTo(this.list.contextKeyService); @@ -115,7 +111,7 @@ export class NotificationsList extends Themable { // Only allow for focus in notifications, as the // selection is too strong over the contents of // the notification - this.toUnbind.push(this.list.onSelectionChange(e => { + this._register(this.list.onSelectionChange(e => { if (e.indexes.length > 0) { this.list.setSelection([]); } @@ -126,7 +122,7 @@ export class NotificationsList extends Themable { this.updateStyles(); } - public updateNotificationsList(start: number, deleteCount: number, items: INotificationViewItem[] = []) { + updateNotificationsList(start: number, deleteCount: number, items: INotificationViewItem[] = []) { const listHasDOMFocus = isAncestor(document.activeElement, this.listContainer); // Remember focus and relative top of that item @@ -177,7 +173,7 @@ export class NotificationsList extends Themable { } } - public hide(): void { + hide(): void { if (!this.isVisible || !this.list) { return; // already hidden } @@ -192,7 +188,7 @@ export class NotificationsList extends Themable { this.viewModel = []; } - public focusFirst(): void { + focusFirst(): void { if (!this.isVisible || !this.list) { return; // hidden } @@ -201,7 +197,7 @@ export class NotificationsList extends Themable { this.list.domFocus(); } - public hasFocus(): boolean { + hasFocus(): boolean { if (!this.isVisible || !this.list) { return false; // hidden } @@ -222,7 +218,7 @@ export class NotificationsList extends Themable { } } - public layout(width: number, maxHeight?: number): void { + layout(width: number, maxHeight?: number): void { if (this.list) { this.listContainer.style.width = `${width}px`; @@ -234,7 +230,7 @@ export class NotificationsList extends Themable { } } - public dispose(): void { + dispose(): void { this.hide(); super.dispose(); diff --git a/src/vs/workbench/browser/parts/notifications/notificationsStatus.ts b/src/vs/workbench/browser/parts/notifications/notificationsStatus.ts index 32f884d0fc6..fe7e047fc1b 100644 --- a/src/vs/workbench/browser/parts/notifications/notificationsStatus.ts +++ b/src/vs/workbench/browser/parts/notifications/notificationsStatus.ts @@ -7,13 +7,12 @@ import { INotificationsModel, INotificationChangeEvent, NotificationChangeType, INotificationViewItem } from 'vs/workbench/common/notifications'; import { IStatusbarService, StatusbarAlignment } from 'vs/platform/statusbar/common/statusbar'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { IDisposable, Disposable } from 'vs/base/common/lifecycle'; import { HIDE_NOTIFICATIONS_CENTER, SHOW_NOTIFICATIONS_CENTER } from 'vs/workbench/browser/parts/notifications/notificationsCommands'; import { localize } from 'vs/nls'; -export class NotificationsStatus { +export class NotificationsStatus extends Disposable { private statusItem: IDisposable; - private toDispose: IDisposable[]; private isNotificationsCenterVisible: boolean; private _counter: Set; @@ -21,7 +20,8 @@ export class NotificationsStatus { private model: INotificationsModel, @IStatusbarService private statusbarService: IStatusbarService ) { - this.toDispose = []; + super(); + this._counter = new Set(); this.updateNotificationsStatusItem(); @@ -33,7 +33,7 @@ export class NotificationsStatus { return this._counter.size; } - public update(isCenterVisible: boolean): void { + update(isCenterVisible: boolean): void { if (this.isNotificationsCenterVisible !== isCenterVisible) { this.isNotificationsCenterVisible = isCenterVisible; @@ -44,7 +44,7 @@ export class NotificationsStatus { } private registerListeners(): void { - this.toDispose.push(this.model.onDidNotificationChange(e => this.onDidNotificationChange(e))); + this._register(this.model.onDidNotificationChange(e => this.onDidNotificationChange(e))); } private onDidNotificationChange(e: INotificationChangeEvent): void { @@ -101,8 +101,8 @@ export class NotificationsStatus { return localize('notifications', "{0} New Notifications", this.count); } - public dispose() { - this.toDispose = dispose(this.toDispose); + dispose() { + super.dispose(); if (this.statusItem) { this.statusItem.dispose(); diff --git a/src/vs/workbench/browser/parts/notifications/notificationsToasts.ts b/src/vs/workbench/browser/parts/notifications/notificationsToasts.ts index 123c9e5c974..17eb959b455 100644 --- a/src/vs/workbench/browser/parts/notifications/notificationsToasts.ts +++ b/src/vs/workbench/browser/parts/notifications/notificationsToasts.ts @@ -80,7 +80,7 @@ export class NotificationsToasts extends Themable { } private registerListeners(): void { - this.toUnbind.push(this.model.onDidNotificationChange(e => this.onDidNotificationChange(e))); + this._register(this.model.onDidNotificationChange(e => this.onDidNotificationChange(e))); } private onDidNotificationChange(e: INotificationChangeEvent): void { @@ -265,7 +265,7 @@ export class NotificationsToasts extends Themable { this.notificationsToastsVisibleContextKey.set(false); } - public hide(): void { + hide(): void { const focusGroup = isAncestor(document.activeElement, this.notificationsToastsContainer); this.removeToasts(); @@ -275,7 +275,7 @@ export class NotificationsToasts extends Themable { } } - public focus(): boolean { + focus(): boolean { const toasts = this.getToasts(ToastVisibility.VISIBLE); if (toasts.length > 0) { toasts[0].list.focusFirst(); @@ -286,7 +286,7 @@ export class NotificationsToasts extends Themable { return false; } - public focusNext(): boolean { + focusNext(): boolean { const toasts = this.getToasts(ToastVisibility.VISIBLE); for (let i = 0; i < toasts.length; i++) { const toast = toasts[i]; @@ -305,7 +305,7 @@ export class NotificationsToasts extends Themable { return false; } - public focusPrevious(): boolean { + focusPrevious(): boolean { const toasts = this.getToasts(ToastVisibility.VISIBLE); for (let i = 0; i < toasts.length; i++) { const toast = toasts[i]; @@ -324,7 +324,7 @@ export class NotificationsToasts extends Themable { return false; } - public focusFirst(): boolean { + focusFirst(): boolean { const toast = this.getToasts(ToastVisibility.VISIBLE)[0]; if (toast) { toast.list.focusFirst(); @@ -335,7 +335,7 @@ export class NotificationsToasts extends Themable { return false; } - public focusLast(): boolean { + focusLast(): boolean { const toasts = this.getToasts(ToastVisibility.VISIBLE); if (toasts.length > 0) { toasts[toasts.length - 1].list.focusFirst(); @@ -346,7 +346,7 @@ export class NotificationsToasts extends Themable { return false; } - public update(isCenterVisible: boolean): void { + update(isCenterVisible: boolean): void { if (this.isNotificationsCenterVisible !== isCenterVisible) { this.isNotificationsCenterVisible = isCenterVisible; @@ -391,7 +391,7 @@ export class NotificationsToasts extends Themable { return notificationToasts.reverse(); // from newest to oldest } - public layout(dimension: Dimension): void { + layout(dimension: Dimension): void { this.workbenchDimensions = dimension; const maxDimensions = this.computeMaxDimensions(); diff --git a/src/vs/workbench/browser/parts/notifications/notificationsViewer.ts b/src/vs/workbench/browser/parts/notifications/notificationsViewer.ts index 27f01868fbc..2ecb5ec8da0 100644 --- a/src/vs/workbench/browser/parts/notifications/notificationsViewer.ts +++ b/src/vs/workbench/browser/parts/notifications/notificationsViewer.ts @@ -46,7 +46,7 @@ export class NotificationsListDelegate implements IDelegate { - public static readonly TEMPLATE_ID = 'notification'; + static readonly TEMPLATE_ID = 'notification'; constructor( private actionRunner: IActionRunner, @@ -191,11 +191,11 @@ export class NotificationRenderer implements IRenderer { + run(): TPromise { return this.partService.setPanelHidden(true); } } export class TogglePanelAction extends Action { + static readonly ID = 'workbench.action.togglePanel'; static LABEL = nls.localize('togglePanel', "Toggle Panel"); @@ -46,15 +48,15 @@ export class TogglePanelAction extends Action { super(id, name, partService.isVisible(Parts.PANEL_PART) ? 'panel expanded' : 'panel'); } - public run(): TPromise { + run(): TPromise { return this.partService.setPanelHidden(this.partService.isVisible(Parts.PANEL_PART)); } } class FocusPanelAction extends Action { - public static readonly ID = 'workbench.action.focusPanel'; - public static readonly LABEL = nls.localize('focusPanel', "Focus into Panel"); + static readonly ID = 'workbench.action.focusPanel'; + static readonly LABEL = nls.localize('focusPanel', "Focus into Panel"); constructor( id: string, @@ -65,7 +67,7 @@ class FocusPanelAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { // Show panel if (!this.partService.isVisible(Parts.PANEL_PART)) { @@ -83,10 +85,12 @@ class FocusPanelAction extends Action { export class TogglePanelPositionAction extends Action { - public static readonly ID = 'workbench.action.togglePanelPosition'; - public static readonly LABEL = nls.localize('toggledPanelPosition', "Toggle Panel Position"); + static readonly ID = 'workbench.action.togglePanelPosition'; + static readonly LABEL = nls.localize('toggledPanelPosition', "Toggle Panel Position"); + private static readonly MOVE_TO_RIGHT_LABEL = nls.localize('moveToRight', "Move to Right"); private static readonly MOVE_TO_BOTTOM_LABEL = nls.localize('moveToBottom', "Move to Bottom"); + private toDispose: IDisposable[]; constructor( @@ -106,12 +110,12 @@ export class TogglePanelPositionAction extends Action { setClassAndLabel(); } - public run(): TPromise { + run(): TPromise { const position = this.partService.getPanelPosition(); return this.partService.setPanelPosition(position === Position.BOTTOM ? Position.RIGHT : Position.BOTTOM); } - public dispose(): void { + dispose(): void { super.dispose(); this.toDispose = dispose(this.toDispose); } @@ -119,10 +123,12 @@ export class TogglePanelPositionAction extends Action { export class ToggleMaximizedPanelAction extends Action { - public static readonly ID = 'workbench.action.toggleMaximizedPanel'; - public static readonly LABEL = nls.localize('toggleMaximizedPanel', "Toggle Maximized Panel"); + static readonly ID = 'workbench.action.toggleMaximizedPanel'; + static readonly LABEL = nls.localize('toggleMaximizedPanel', "Toggle Maximized Panel"); + private static readonly MAXIMIZE_LABEL = nls.localize('maximizePanel', "Maximize Panel Size"); private static readonly RESTORE_LABEL = nls.localize('minimizePanel', "Restore Panel Size"); + private toDispose: IDisposable[]; constructor( @@ -139,13 +145,12 @@ export class ToggleMaximizedPanelAction extends Action { })); } - public run(): TPromise { - // Show panel + run(): TPromise { return (!this.partService.isVisible(Parts.PANEL_PART) ? this.partService.setPanelHidden(false) : TPromise.as(null)) .then(() => this.partService.toggleMaximizedPanel()); } - public dispose(): void { + dispose(): void { super.dispose(); this.toDispose = dispose(this.toDispose); } @@ -160,7 +165,7 @@ export class PanelActivityAction extends ActivityAction { super(activity); } - public run(event: any): TPromise { + run(event: any): TPromise { return this.panelService.openPanel(this.activity.id, true).then(() => this.activate()); } } diff --git a/src/vs/workbench/browser/parts/panel/panelPart.ts b/src/vs/workbench/browser/parts/panel/panelPart.ts index f076f3a9ff1..40c3fa928ea 100644 --- a/src/vs/workbench/browser/parts/panel/panelPart.ts +++ b/src/vs/workbench/browser/parts/panel/panelPart.ts @@ -30,7 +30,7 @@ import { IBadge } from 'vs/workbench/services/activity/common/activity'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { Dimension } from 'vs/base/browser/dom'; import { localize } from 'vs/nls'; -import { dispose, IDisposable } from 'vs/base/common/lifecycle'; +import { IDisposable } from 'vs/base/common/lifecycle'; import { RawContextKey, IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; const ActivePanleContextId = 'activePanel'; @@ -38,18 +38,18 @@ export const ActivePanelContext = new RawContextKey(ActivePanleContextId export class PanelPart extends CompositePart implements IPanelService { - public static readonly activePanelSettingsKey = 'workbench.panelpart.activepanelid'; + static readonly activePanelSettingsKey = 'workbench.panelpart.activepanelid'; + private static readonly PINNED_PANELS = 'workbench.panel.pinnedPanels'; private static readonly MIN_COMPOSITE_BAR_WIDTH = 50; - public _serviceBrand: any; + _serviceBrand: any; private activePanelContextKey: IContextKey; private blockOpeningPanel: boolean; private compositeBar: CompositeBar; - private compositeActions: { [compositeId: string]: { activityAction: PanelActivityAction, pinnedAction: ToggleCompositePinnedAction } }; + private compositeActions: { [compositeId: string]: { activityAction: PanelActivityAction, pinnedAction: ToggleCompositePinnedAction } } = Object.create(null); private dimension: Dimension; - private disposables: IDisposable[] = []; constructor( id: string, @@ -82,8 +82,7 @@ export class PanelPart extends CompositePart implements IPanelService { { hasTitle: true } ); - this.compositeActions = Object.create(null); - this.compositeBar = this.instantiationService.createInstance(CompositeBar, { + this.compositeBar = this._register(this.instantiationService.createInstance(CompositeBar, { icon: false, storageId: PanelPart.PINNED_PANELS, orientation: ActionsOrientation.HORIZONTAL, @@ -102,31 +101,31 @@ export class PanelPart extends CompositePart implements IPanelService { badgeForeground, dragAndDropBackground: PANEL_DRAG_AND_DROP_BACKGROUND } - }); - this.toUnbind.push(this.compositeBar); + })); + for (const panel of this.getPanels()) { this.compositeBar.addComposite(panel); } + this.activePanelContextKey = ActivePanelContext.bindTo(contextKeyService); - this.onDidPanelOpen(this._onDidPanelOpen, this, this.disposables); - this.onDidPanelClose(this._onDidPanelClose, this, this.disposables); this.registerListeners(); } private registerListeners(): void { + this._register(this.onDidPanelOpen(this._onDidPanelOpen, this)); + this._register(this.onDidPanelClose(this._onDidPanelClose, this)); - this.toUnbind.push(this.registry.onDidRegister(panelDescriptor => this.compositeBar.addComposite(panelDescriptor))); + this._register(this.registry.onDidRegister(panelDescriptor => this.compositeBar.addComposite(panelDescriptor))); // Activate panel action on opening of a panel - this.toUnbind.push(this.onDidPanelOpen(panel => { + this._register(this.onDidPanelOpen(panel => { this.compositeBar.activateComposite(panel.getId()); - // Need to relayout composite bar since different panels have different action bar width - this.layoutCompositeBar(); + this.layoutCompositeBar(); // Need to relayout composite bar since different panels have different action bar width })); // Deactivate panel action on close - this.toUnbind.push(this.onDidPanelClose(panel => this.compositeBar.deactivateComposite(panel.getId()))); + this._register(this.onDidPanelClose(panel => this.compositeBar.deactivateComposite(panel.getId()))); } private _onDidPanelOpen(panel: IPanel): void { @@ -141,15 +140,15 @@ export class PanelPart extends CompositePart implements IPanelService { } } - public get onDidPanelOpen(): Event { + get onDidPanelOpen(): Event { return this._onDidCompositeOpen.event; } - public get onDidPanelClose(): Event { + get onDidPanelClose(): Event { return this._onDidCompositeClose.event; } - public updateStyles(): void { + updateStyles(): void { super.updateStyles(); const container = $(this.getContainer()); @@ -160,7 +159,7 @@ export class PanelPart extends CompositePart implements IPanelService { title.style('border-top-color', this.getColor(PANEL_BORDER) || this.getColor(contrastBorder)); } - public openPanel(id: string, focus?: boolean): TPromise { + openPanel(id: string, focus?: boolean): TPromise { if (this.blockOpeningPanel) { return TPromise.as(null); // Workaround against a potential race condition } @@ -179,7 +178,7 @@ export class PanelPart extends CompositePart implements IPanelService { return promise.then(() => this.openComposite(id, focus)); } - public showActivity(panelId: string, badge: IBadge, clazz?: string): IDisposable { + showActivity(panelId: string, badge: IBadge, clazz?: string): IDisposable { return this.compositeBar.showActivity(panelId, badge, clazz); } @@ -187,13 +186,13 @@ export class PanelPart extends CompositePart implements IPanelService { return this.getPanels().filter(p => p.id === panelId).pop(); } - public getPanels(): PanelDescriptor[] { + getPanels(): PanelDescriptor[] { return Registry.as(PanelExtensions.Panels).getPanels() .filter(p => p.enabled) .sort((v1, v2) => v1.order - v2.order); } - public setPanelEnablement(id: string, enabled: boolean): void { + setPanelEnablement(id: string, enabled: boolean): void { const descriptor = Registry.as(PanelExtensions.Panels).getPanels().filter(p => p.id === id).pop(); if (descriptor && descriptor.enabled !== enabled) { descriptor.enabled = enabled; @@ -213,15 +212,15 @@ export class PanelPart extends CompositePart implements IPanelService { ]; } - public getActivePanel(): IPanel { + getActivePanel(): IPanel { return this.getActiveComposite(); } - public getLastActivePanelId(): string { + getLastActivePanelId(): string { return this.getLastActiveCompositetId(); } - public hideActivePanel(): TPromise { + hideActivePanel(): TPromise { return this.hideActiveComposite().then(composite => void 0); } @@ -242,7 +241,7 @@ export class PanelPart extends CompositePart implements IPanelService { }; } - public layout(dimension: Dimension): Dimension[] { + layout(dimension: Dimension): Dimension[] { if (!this.partService.isVisible(Parts.PANEL_PART)) { return [dimension]; } @@ -299,11 +298,6 @@ export class PanelPart extends CompositePart implements IPanelService { } return this.toolBar.getItemsWidth(); } - - dispose(): void { - super.dispose(); - this.disposables = dispose(this.disposables); - } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { diff --git a/src/vs/workbench/browser/parts/quickinput/quickInput.ts b/src/vs/workbench/browser/parts/quickinput/quickInput.ts index c5ee214aa43..c6eea59e167 100644 --- a/src/vs/workbench/browser/parts/quickinput/quickInput.ts +++ b/src/vs/workbench/browser/parts/quickinput/quickInput.ts @@ -711,8 +711,8 @@ export class QuickInputService extends Component implements IQuickInputService { private enabled = true; private inQuickOpenWidgets: Record = {}; private inQuickOpenContext: IContextKey; - private onDidAcceptEmitter = new Emitter(); - private onDidTriggerButtonEmitter = new Emitter(); + private onDidAcceptEmitter = this._register(new Emitter()); + private onDidTriggerButtonEmitter = this._register(new Emitter()); private controller: QuickInput; @@ -729,11 +729,8 @@ export class QuickInputService extends Component implements IQuickInputService { ) { super(QuickInputService.ID, themeService); this.inQuickOpenContext = new RawContextKey('inQuickOpen', false).bindTo(contextKeyService); - this.toUnbind.push( - this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true)), - this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false)), - this.onDidAcceptEmitter - ); + this._register(this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true))); + this._register(this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false))); } private inQuickOpen(widget: 'quickInput' | 'quickOpen', open: boolean) { @@ -765,25 +762,23 @@ export class QuickInputService extends Component implements IQuickInputService { this.titleBar = dom.append(container, $('.quick-input-titlebar')); - const leftActionBar = new ActionBar(this.titleBar); + const leftActionBar = this._register(new ActionBar(this.titleBar)); leftActionBar.domNode.classList.add('quick-input-left-action-bar'); - this.toUnbind.push(leftActionBar); const title = dom.append(this.titleBar, $('.quick-input-title')); - const rightActionBar = new ActionBar(this.titleBar); + const rightActionBar = this._register(new ActionBar(this.titleBar)); rightActionBar.domNode.classList.add('quick-input-right-action-bar'); - this.toUnbind.push(rightActionBar); const headerContainer = dom.append(container, $('.quick-input-header')); const checkAll = dom.append(headerContainer, $('input.quick-input-check-all')); checkAll.type = 'checkbox'; - this.toUnbind.push(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { + this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { const checked = checkAll.checked; list.setAllVisibleChecked(checked); })); - this.toUnbind.push(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { + this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { if (e.x || e.y) { // Avoid 'click' triggered by 'space'... inputBox.setFocus(); } @@ -791,18 +786,17 @@ export class QuickInputService extends Component implements IQuickInputService { this.filterContainer = dom.append(headerContainer, $('.quick-input-filter')); - const inputBox = new QuickInputBox(this.filterContainer); - this.toUnbind.push(inputBox); + const inputBox = this._register(new QuickInputBox(this.filterContainer)); this.countContainer = dom.append(this.filterContainer, $('.quick-input-count')); const count = new CountBadge(this.countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") }); - this.toUnbind.push(attachBadgeStyler(count, this.themeService)); + this._register(attachBadgeStyler(count, this.themeService)); this.okContainer = dom.append(headerContainer, $('.quick-input-action')); this.ok = new Button(this.okContainer); attachButtonStyler(this.ok, this.themeService); this.ok.label = localize('ok', "OK"); - this.toUnbind.push(this.ok.onDidClick(e => { + this._register(this.ok.onDidClick(e => { this.onDidAcceptEmitter.fire(); })); @@ -810,17 +804,16 @@ export class QuickInputService extends Component implements IQuickInputService { const progressBar = new ProgressBar(container); dom.addClass(progressBar.getContainer(), 'quick-input-progress'); - this.toUnbind.push(attachProgressBarStyler(progressBar, this.themeService)); + this._register(attachProgressBarStyler(progressBar, this.themeService)); - const list = this.instantiationService.createInstance(QuickInputList, container); - this.toUnbind.push(list); - this.toUnbind.push(list.onChangedAllVisibleChecked(checked => { + const list = this._register(this.instantiationService.createInstance(QuickInputList, container)); + this._register(list.onChangedAllVisibleChecked(checked => { checkAll.checked = checked; })); - this.toUnbind.push(list.onChangedCheckedCount(c => { + this._register(list.onChangedCheckedCount(c => { count.setCount(c); })); - this.toUnbind.push(list.onLeave(() => { + this._register(list.onLeave(() => { // Defer to avoid the input field reacting to the triggering key. setTimeout(() => { inputBox.setFocus(); @@ -828,7 +821,7 @@ export class QuickInputService extends Component implements IQuickInputService { }, 0); })); - this.toUnbind.push(dom.addDisposableListener(container, 'focusout', (e: FocusEvent) => { + this._register(dom.addDisposableListener(container, 'focusout', (e: FocusEvent) => { if (e.relatedTarget === container) { (e.target).focus(); return; @@ -842,7 +835,7 @@ export class QuickInputService extends Component implements IQuickInputService { this.hide(true); } })); - this.toUnbind.push(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { + this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Enter: @@ -873,7 +866,7 @@ export class QuickInputService extends Component implements IQuickInputService { } })); - this.toUnbind.push(this.quickOpenService.onShow(() => this.hide(true))); + this._register(this.quickOpenService.onShow(() => this.hide(true))); this.ui = { container, diff --git a/src/vs/workbench/browser/parts/quickopen/quickOpenController.ts b/src/vs/workbench/browser/parts/quickopen/quickOpenController.ts index 59e9137b08a..5bc53c73ece 100644 --- a/src/vs/workbench/browser/parts/quickopen/quickOpenController.ts +++ b/src/vs/workbench/browser/parts/quickopen/quickOpenController.ts @@ -78,23 +78,25 @@ interface IInternalPickOptions { export class QuickOpenController extends Component implements IQuickOpenService { private static readonly MAX_SHORT_RESPONSE_TIME = 500; - - public _serviceBrand: any; - private static readonly ID = 'workbench.component.quickopen'; - private readonly _onShow: Emitter; - private readonly _onHide: Emitter; + _serviceBrand: any; + + private readonly _onShow: Emitter = this._register(new Emitter()); + get onShow(): Event { return this._onShow.event; } + + private readonly _onHide: Emitter = this._register(new Emitter()); + get onHide(): Event { return this._onHide.event; } private quickOpenWidget: QuickOpenWidget; private pickOpenWidget: QuickOpenWidget; private layoutDimensions: Dimension; - private mapResolvedHandlersToPrefix: { [prefix: string]: TPromise; }; - private mapContextKeyToContext: { [id: string]: IContextKey; }; - private handlerOnOpenCalled: { [prefix: string]: boolean; }; + private mapResolvedHandlersToPrefix: { [prefix: string]: TPromise; } = Object.create(null); + private mapContextKeyToContext: { [id: string]: IContextKey; } = Object.create(null); + private handlerOnOpenCalled: { [prefix: string]: boolean; } = Object.create(null); private currentResultToken: string; private currentPickerToken: string; - private promisesToCompleteOnHide: ValueCallback[]; + private promisesToCompleteOnHide: ValueCallback[] = []; private previousActiveHandlerDescriptor: QuickOpenHandlerDescriptor; private actionProvider = new ContributableActionProvider(); private closeOnFocusLost: boolean; @@ -112,26 +114,17 @@ export class QuickOpenController extends Component implements IQuickOpenService ) { super(QuickOpenController.ID, themeService); - this.mapResolvedHandlersToPrefix = {}; - this.handlerOnOpenCalled = {}; - this.mapContextKeyToContext = {}; - - this.promisesToCompleteOnHide = []; - this.editorHistoryHandler = this.instantiationService.createInstance(EditorHistoryHandler); - this._onShow = new Emitter(); - this._onHide = new Emitter(); - this.updateConfiguration(); this.registerListeners(); } private registerListeners(): void { - this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => this.updateConfiguration())); - this.toUnbind.push(this.partService.onTitleBarVisibilityChange(() => this.positionQuickOpenWidget())); - this.toUnbind.push(browser.onDidChangeZoomLevel(() => this.positionQuickOpenWidget())); + this._register(this.configurationService.onDidChangeConfiguration(e => this.updateConfiguration())); + this._register(this.partService.onTitleBarVisibilityChange(() => this.positionQuickOpenWidget())); + this._register(browser.onDidChangeZoomLevel(() => this.positionQuickOpenWidget())); } private updateConfiguration(): void { @@ -142,15 +135,7 @@ export class QuickOpenController extends Component implements IQuickOpenService } } - public get onShow(): Event { - return this._onShow.event; - } - - public get onHide(): Event { - return this._onHide.event; - } - - public navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration): void { + navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration): void { if (this.quickOpenWidget) { this.quickOpenWidget.navigate(next, quickNavigate); } @@ -160,11 +145,11 @@ export class QuickOpenController extends Component implements IQuickOpenService } } - public pick(picks: TPromise, options?: IPickOptions, token?: CancellationToken): TPromise; - public pick(picks: TPromise, options?: IPickOptions, token?: CancellationToken): TPromise; - public pick(picks: string[], options?: IPickOptions, token?: CancellationToken): TPromise; - public pick(picks: T[], options?: IPickOptions, token?: CancellationToken): TPromise; - public pick(arg1: string[] | TPromise | IPickOpenEntry[] | TPromise, options?: IPickOptions, token?: CancellationToken): TPromise { + pick(picks: TPromise, options?: IPickOptions, token?: CancellationToken): TPromise; + pick(picks: TPromise, options?: IPickOptions, token?: CancellationToken): TPromise; + pick(picks: string[], options?: IPickOptions, token?: CancellationToken): TPromise; + pick(picks: T[], options?: IPickOptions, token?: CancellationToken): TPromise; + pick(arg1: string[] | TPromise | IPickOpenEntry[] | TPromise, options?: IPickOptions, token?: CancellationToken): TPromise { if (!options) { options = Object.create(null); } @@ -217,7 +202,7 @@ export class QuickOpenController extends Component implements IQuickOpenService // Create upon first open if (!this.pickOpenWidget) { - this.pickOpenWidget = new QuickOpenWidget( + this.pickOpenWidget = this._register(new QuickOpenWidget( document.getElementById(this.partService.getWorkbenchElementId()), { onOk: () => { /* ignore, handle later */ }, @@ -230,8 +215,8 @@ export class QuickOpenController extends Component implements IQuickOpenService keyboardSupport: false, treeCreator: (container, config, opts) => this.instantiationService.createInstance(WorkbenchTree, container, config, opts) } - ); - this.toUnbind.push(attachQuickOpenStyler(this.pickOpenWidget, this.themeService, { background: SIDE_BAR_BACKGROUND, foreground: SIDE_BAR_FOREGROUND })); + )); + this._register(attachQuickOpenStyler(this.pickOpenWidget, this.themeService, { background: SIDE_BAR_BACKGROUND, foreground: SIDE_BAR_FOREGROUND })); const pickOpenContainer = this.pickOpenWidget.create(); addClass(pickOpenContainer, 'show-file-icons'); @@ -414,7 +399,7 @@ export class QuickOpenController extends Component implements IQuickOpenService }); } - public accept(): void { + accept(): void { [this.quickOpenWidget, this.pickOpenWidget].forEach(w => { if (w && w.isVisible()) { w.accept(); @@ -422,7 +407,7 @@ export class QuickOpenController extends Component implements IQuickOpenService }); } - public focus(): void { + focus(): void { [this.quickOpenWidget, this.pickOpenWidget].forEach(w => { if (w && w.isVisible()) { w.focus(); @@ -430,7 +415,7 @@ export class QuickOpenController extends Component implements IQuickOpenService }); } - public close(): void { + close(): void { [this.quickOpenWidget, this.pickOpenWidget].forEach(w => { if (w && w.isVisible()) { w.hide(HideReason.CANCELED); @@ -446,7 +431,7 @@ export class QuickOpenController extends Component implements IQuickOpenService } } - public show(prefix?: string, options?: IShowOptions): TPromise { + show(prefix?: string, options?: IShowOptions): TPromise { let quickNavigateConfiguration = options ? options.quickNavigateConfiguration : void 0; let inputSelection = options ? options.inputSelection : void 0; let autoFocus = options ? options.autoFocus : void 0; @@ -464,7 +449,7 @@ export class QuickOpenController extends Component implements IQuickOpenService // Create upon first open if (!this.quickOpenWidget) { - this.quickOpenWidget = new QuickOpenWidget( + this.quickOpenWidget = this._register(new QuickOpenWidget( document.getElementById(this.partService.getWorkbenchElementId()), { onOk: () => { /* ignore */ }, @@ -478,8 +463,8 @@ export class QuickOpenController extends Component implements IQuickOpenService keyboardSupport: false, treeCreator: (container, config, opts) => this.instantiationService.createInstance(WorkbenchTree, container, config, opts) } - ); - this.toUnbind.push(attachQuickOpenStyler(this.quickOpenWidget, this.themeService, { background: SIDE_BAR_BACKGROUND, foreground: SIDE_BAR_FOREGROUND })); + )); + this._register(attachQuickOpenStyler(this.quickOpenWidget, this.themeService, { background: SIDE_BAR_BACKGROUND, foreground: SIDE_BAR_FOREGROUND })); const quickOpenContainer = this.quickOpenWidget.create(); addClass(quickOpenContainer, 'show-file-icons'); @@ -557,14 +542,12 @@ export class QuickOpenController extends Component implements IQuickOpenService // Pass to handlers for (let prefix in this.mapResolvedHandlersToPrefix) { - if (this.mapResolvedHandlersToPrefix.hasOwnProperty(prefix)) { - const promise = this.mapResolvedHandlersToPrefix[prefix]; - promise.then(handler => { - this.handlerOnOpenCalled[prefix] = false; + const promise = this.mapResolvedHandlersToPrefix[prefix]; + promise.then(handler => { + this.handlerOnOpenCalled[prefix] = false; - handler.onClose(reason === HideReason.CANCELED); // Don't check if onOpen was called to preserve old behaviour for now - }); - } + handler.onClose(reason === HideReason.CANCELED); // Don't check if onOpen was called to preserve old behaviour for now + }); } // Complete promises that are waiting @@ -879,7 +862,7 @@ export class QuickOpenController extends Component implements IQuickOpenService return this.mapResolvedHandlersToPrefix[id] = TPromise.as(handler.instantiate(this.instantiationService)); } - public layout(dimension: Dimension): void { + layout(dimension: Dimension): void { this.layoutDimensions = dimension; if (this.quickOpenWidget) { this.quickOpenWidget.layout(this.layoutDimensions); @@ -889,18 +872,6 @@ export class QuickOpenController extends Component implements IQuickOpenService this.pickOpenWidget.layout(this.layoutDimensions); } } - - public dispose(): void { - if (this.quickOpenWidget) { - this.quickOpenWidget.dispose(); - } - - if (this.pickOpenWidget) { - this.pickOpenWidget.dispose(); - } - - super.dispose(); - } } class PlaceholderQuickOpenEntry extends QuickOpenEntryGroup { @@ -912,7 +883,7 @@ class PlaceholderQuickOpenEntry extends QuickOpenEntryGroup { this.placeHolderLabel = placeHolderLabel; } - public getLabel(): string { + getLabel(): string { return this.placeHolderLabel; } } @@ -961,7 +932,7 @@ class PickOpenEntry extends PlaceholderQuickOpenEntry implements IPickOpenItem { this.fileKind = fileItem.fileKind; } - public matchesFuzzy(query: string, options: IInternalPickOptions): { labelHighlights: IMatch[], descriptionHighlights: IMatch[], detailHighlights: IMatch[] } { + matchesFuzzy(query: string, options: IInternalPickOptions): { labelHighlights: IMatch[], descriptionHighlights: IMatch[], detailHighlights: IMatch[] } { if (!this.labelOcticons) { this.labelOcticons = parseOcticons(this.getLabel()); // parse on demand } @@ -978,72 +949,72 @@ class PickOpenEntry extends PlaceholderQuickOpenEntry implements IPickOpenItem { }; } - public getPayload(): any { + getPayload(): any { return this.payload; } - public remove(): void { + remove(): void { super.setHidden(true); this.removed = true; this.onRemove(); } - public isHidden(): boolean { + isHidden(): boolean { return this.removed || super.isHidden(); } - public get action(): IAction { + get action(): IAction { return this._action; } - public get index(): number { + get index(): number { return this._index; } - public getLabelOptions(): IIconLabelValueOptions { + getLabelOptions(): IIconLabelValueOptions { return { extraClasses: this.resource ? getIconClasses(this.modelService, this.modeService, this.resource, this.fileKind) : [] }; } - public get shouldRunWithContext(): IEntryRunContext { + get shouldRunWithContext(): IEntryRunContext { return this._shouldRunWithContext; } - public getDescription(): string { + getDescription(): string { return this.description; } - public getDetail(): string { + getDetail(): string { return this.detail; } - public getTooltip(): string { + getTooltip(): string { return this.tooltip; } - public getDescriptionTooltip(): string { + getDescriptionTooltip(): string { return this.descriptionTooltip; } - public showBorder(): boolean { + showBorder(): boolean { return this.hasSeparator; } - public getGroupLabel(): string { + getGroupLabel(): string { return this.separatorLabel; } - public shouldAlwaysShow(): boolean { + shouldAlwaysShow(): boolean { return this.alwaysShow; } - public getResource(): URI { + getResource(): URI { return this.resource; } - public run(mode: Mode, context: IEntryRunContext): boolean { + run(mode: Mode, context: IEntryRunContext): boolean { if (mode === Mode.OPEN) { this._shouldRunWithContext = context; @@ -1059,23 +1030,23 @@ class PickOpenEntry extends PlaceholderQuickOpenEntry implements IPickOpenItem { } class PickOpenActionProvider implements IActionProvider { - public hasActions(tree: ITree, element: PickOpenEntry): boolean { + hasActions(tree: ITree, element: PickOpenEntry): boolean { return !!element.action; } - public getActions(tree: ITree, element: PickOpenEntry): TPromise { + getActions(tree: ITree, element: PickOpenEntry): TPromise { return TPromise.as(element.action ? [element.action] : []); } - public hasSecondaryActions(tree: ITree, element: PickOpenEntry): boolean { + hasSecondaryActions(tree: ITree, element: PickOpenEntry): boolean { return false; } - public getSecondaryActions(tree: ITree, element: PickOpenEntry): TPromise { + getSecondaryActions(tree: ITree, element: PickOpenEntry): TPromise { return TPromise.as([]); } - public getActionItem(tree: ITree, element: PickOpenEntry, action: Action): BaseActionItem { + getActionItem(tree: ITree, element: PickOpenEntry, action: Action): BaseActionItem { return null; } } @@ -1091,7 +1062,7 @@ class EditorHistoryHandler { this.scorerCache = Object.create(null); } - public getResults(searchValue?: string): QuickOpenEntry[] { + getResults(searchValue?: string): QuickOpenEntry[] { // Massage search for scoring const query = prepareQuery(searchValue); @@ -1146,7 +1117,7 @@ class EditorHistoryItemAccessorClass extends QuickOpenItemAccessorClass { super(); } - public getItemDescription(entry: QuickOpenEntry): string { + getItemDescription(entry: QuickOpenEntry): string { return this.allowMatchOnDescription ? entry.getDescription() : void 0; } } @@ -1198,37 +1169,37 @@ export class EditorHistoryEntry extends EditorQuickOpenEntry { } } - public getIcon(): string { + getIcon(): string { return this.dirty ? 'dirty' : ''; } - public getLabel(): string { + getLabel(): string { return this.label; } - public getLabelOptions(): IIconLabelValueOptions { + getLabelOptions(): IIconLabelValueOptions { return { extraClasses: getIconClasses(this.modelService, this.modeService, this.resource) }; } - public getAriaLabel(): string { + getAriaLabel(): string { return nls.localize('entryAriaLabel', "{0}, recently opened", this.getLabel()); } - public getDescription(): string { + getDescription(): string { return this.description; } - public getResource(): URI { + getResource(): URI { return this.resource; } - public getInput(): IEditorInput | IResourceInput { + getInput(): IEditorInput | IResourceInput { return this.input; } - public run(mode: Mode, context: IEntryRunContext): boolean { + run(mode: Mode, context: IEntryRunContext): boolean { if (mode === Mode.OPEN) { const sideBySide = !context.quickNavigateConfiguration && (context.keymods.alt || context.keymods.ctrlCmd); const pinned = !this.configurationService.getValue().workbench.editor.enablePreviewFromQuickOpen || context.keymods.alt; @@ -1260,8 +1231,8 @@ function resourceForEditorHistory(input: EditorInput, fileService: IFileService) export class RemoveFromEditorHistoryAction extends Action { - public static readonly ID = 'workbench.action.removeFromEditorHistory'; - public static readonly LABEL = nls.localize('removeFromEditorHistory', "Remove From History"); + static readonly ID = 'workbench.action.removeFromEditorHistory'; + static readonly LABEL = nls.localize('removeFromEditorHistory', "Remove From History"); constructor( id: string, @@ -1273,7 +1244,7 @@ export class RemoveFromEditorHistoryAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { interface IHistoryPickEntry extends IFilePickOpenEntry { input: IEditorInput | IResourceInput; } diff --git a/src/vs/workbench/browser/parts/quickopen/quickopen.ts b/src/vs/workbench/browser/parts/quickopen/quickopen.ts index a13daae1be5..f0a4175911d 100644 --- a/src/vs/workbench/browser/parts/quickopen/quickopen.ts +++ b/src/vs/workbench/browser/parts/quickopen/quickopen.ts @@ -53,7 +53,7 @@ export class BaseQuickOpenNavigateAction extends Action { super(id, label); } - public run(event?: any): TPromise { + run(event?: any): TPromise { const keys = this.keybindingService.lookupKeybindings(this.id); const quickNavigate = this.quickNavigate ? { keybindings: keys } : void 0; @@ -80,8 +80,8 @@ export function getQuickNavigateHandler(id: string, next?: boolean): ICommandHan export class QuickOpenNavigateNextAction extends BaseQuickOpenNavigateAction { - public static readonly ID = 'workbench.action.quickOpenNavigateNext'; - public static readonly LABEL = nls.localize('quickNavigateNext', "Navigate Next in Quick Open"); + static readonly ID = 'workbench.action.quickOpenNavigateNext'; + static readonly LABEL = nls.localize('quickNavigateNext', "Navigate Next in Quick Open"); constructor( id: string, @@ -96,8 +96,8 @@ export class QuickOpenNavigateNextAction extends BaseQuickOpenNavigateAction { export class QuickOpenNavigatePreviousAction extends BaseQuickOpenNavigateAction { - public static readonly ID = 'workbench.action.quickOpenNavigatePrevious'; - public static readonly LABEL = nls.localize('quickNavigatePrevious', "Navigate Previous in Quick Open"); + static readonly ID = 'workbench.action.quickOpenNavigatePrevious'; + static readonly LABEL = nls.localize('quickNavigatePrevious', "Navigate Previous in Quick Open"); constructor( id: string, @@ -112,8 +112,8 @@ export class QuickOpenNavigatePreviousAction extends BaseQuickOpenNavigateAction export class QuickOpenSelectNextAction extends BaseQuickOpenNavigateAction { - public static readonly ID = 'workbench.action.quickOpenSelectNext'; - public static readonly LABEL = nls.localize('quickSelectNext', "Select Next in Quick Open"); + static readonly ID = 'workbench.action.quickOpenSelectNext'; + static readonly LABEL = nls.localize('quickSelectNext', "Select Next in Quick Open"); constructor( id: string, @@ -128,8 +128,8 @@ export class QuickOpenSelectNextAction extends BaseQuickOpenNavigateAction { export class QuickOpenSelectPreviousAction extends BaseQuickOpenNavigateAction { - public static readonly ID = 'workbench.action.quickOpenSelectPrevious'; - public static readonly LABEL = nls.localize('quickSelectPrevious', "Select Previous in Quick Open"); + static readonly ID = 'workbench.action.quickOpenSelectPrevious'; + static readonly LABEL = nls.localize('quickSelectPrevious', "Select Previous in Quick Open"); constructor( id: string, diff --git a/src/vs/workbench/browser/parts/sidebar/sidebarPart.ts b/src/vs/workbench/browser/parts/sidebar/sidebarPart.ts index d4826a2b8f6..88e7acb9c01 100644 --- a/src/vs/workbench/browser/parts/sidebar/sidebarPart.ts +++ b/src/vs/workbench/browser/parts/sidebar/sidebarPart.ts @@ -32,9 +32,7 @@ import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; export class SidebarPart extends CompositePart { - public static readonly activeViewletSettingsKey = 'workbench.sidebar.activeviewletid'; - - public _serviceBrand: any; + static readonly activeViewletSettingsKey = 'workbench.sidebar.activeviewletid'; private blockOpeningViewlet: boolean; @@ -69,22 +67,22 @@ export class SidebarPart extends CompositePart { ); } - public get onDidViewletOpen(): Event { + get onDidViewletOpen(): Event { return this._onDidCompositeOpen.event as Event; } - public get onDidViewletClose(): Event { + get onDidViewletClose(): Event { return this._onDidCompositeClose.event as Event; } - public createTitleArea(parent: HTMLElement): HTMLElement { + createTitleArea(parent: HTMLElement): HTMLElement { const titleArea = super.createTitleArea(parent); - $(titleArea).on(EventType.CONTEXT_MENU, (e: MouseEvent) => this.onTitleAreaContextMenu(new StandardMouseEvent(e))); + $(titleArea).on(EventType.CONTEXT_MENU, (e: MouseEvent) => this.onTitleAreaContextMenu(new StandardMouseEvent(e)), this.toDispose); return titleArea; } - public updateStyles(): void { + updateStyles(): void { super.updateStyles(); // Part container @@ -103,7 +101,7 @@ export class SidebarPart extends CompositePart { container.style('border-left-color', !isPositionLeft ? borderColor : null); } - public openViewlet(id: string, focus?: boolean): TPromise { + openViewlet(id: string, focus?: boolean): TPromise { if (this.blockOpeningViewlet) { return TPromise.as(null); // Workaround against a potential race condition } @@ -122,19 +120,19 @@ export class SidebarPart extends CompositePart { return promise.then(() => this.openComposite(id, focus)) as TPromise; } - public getActiveViewlet(): IViewlet { + getActiveViewlet(): IViewlet { return this.getActiveComposite(); } - public getLastActiveViewletId(): string { + getLastActiveViewletId(): string { return this.getLastActiveCompositetId(); } - public hideActiveViewlet(): TPromise { + hideActiveViewlet(): TPromise { return this.hideActiveComposite().then(composite => void 0); } - public layout(dimension: Dimension): Dimension[] { + layout(dimension: Dimension): Dimension[] { if (!this.partService.isVisible(Parts.SIDEBAR_PART)) { return [dimension]; } @@ -162,8 +160,8 @@ export class SidebarPart extends CompositePart { class FocusSideBarAction extends Action { - public static readonly ID = 'workbench.action.focusSideBar'; - public static readonly LABEL = nls.localize('focusSideBar', "Focus into Side Bar"); + static readonly ID = 'workbench.action.focusSideBar'; + static readonly LABEL = nls.localize('focusSideBar', "Focus into Side Bar"); constructor( id: string, @@ -174,7 +172,7 @@ class FocusSideBarAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { // Show side bar if (!this.partService.isVisible(Parts.SIDEBAR_PART)) { diff --git a/src/vs/workbench/browser/parts/statusbar/statusbar.ts b/src/vs/workbench/browser/parts/statusbar/statusbar.ts index d46fd03dc31..259eb702089 100644 --- a/src/vs/workbench/browser/parts/statusbar/statusbar.ts +++ b/src/vs/workbench/browser/parts/statusbar/statusbar.ts @@ -17,10 +17,9 @@ export interface IStatusbarItem { export import StatusbarAlignment = statusbarService.StatusbarAlignment; export class StatusbarItemDescriptor { - - public syncDescriptor: SyncDescriptor0; - public alignment: StatusbarAlignment; - public priority: number; + syncDescriptor: SyncDescriptor0; + alignment: StatusbarAlignment; + priority: number; constructor(ctor: IConstructorSignature0, alignment?: StatusbarAlignment, priority?: number) { this.syncDescriptor = createSyncDescriptor(ctor); @@ -42,11 +41,11 @@ class StatusbarRegistry implements IStatusbarRegistry { this._items = []; } - public get items(): StatusbarItemDescriptor[] { + get items(): StatusbarItemDescriptor[] { return this._items; } - public registerStatusbarItem(descriptor: StatusbarItemDescriptor): void { + registerStatusbarItem(descriptor: StatusbarItemDescriptor): void { this._items.push(descriptor); } } diff --git a/src/vs/workbench/browser/parts/statusbar/statusbarPart.ts b/src/vs/workbench/browser/parts/statusbar/statusbarPart.ts index beebc378ade..226ccc2b80d 100644 --- a/src/vs/workbench/browser/parts/statusbar/statusbarPart.ts +++ b/src/vs/workbench/browser/parts/statusbar/statusbarPart.ts @@ -33,7 +33,7 @@ import { INotificationService } from 'vs/platform/notification/common/notificati export class StatusbarPart extends Part implements IStatusbarService { - public _serviceBrand: any; + _serviceBrand: any; private static readonly PRIORITY_PROP = 'priority'; private static readonly ALIGNMENT_PROP = 'alignment'; @@ -55,10 +55,10 @@ export class StatusbarPart extends Part implements IStatusbarService { } private registerListeners(): void { - this.toUnbind.push(this.contextService.onDidChangeWorkbenchState(() => this.updateStyles())); + this._register(this.contextService.onDidChangeWorkbenchState(() => this.updateStyles())); } - public addEntry(entry: IStatusbarEntry, alignment: StatusbarAlignment, priority: number = 0): IDisposable { + addEntry(entry: IStatusbarEntry, alignment: StatusbarAlignment, priority: number = 0): IDisposable { // Render entry in status bar const el = this.doCreateStatusItem(alignment, priority, entry.showBeak ? 'has-beak' : void 0); @@ -112,7 +112,7 @@ export class StatusbarPart extends Part implements IStatusbarService { return entries; } - public createContentArea(parent: HTMLElement): HTMLElement { + createContentArea(parent: HTMLElement): HTMLElement { this.statusItemsContainer = parent; // Fill in initial items that were contributed from the registry @@ -122,16 +122,13 @@ export class StatusbarPart extends Part implements IStatusbarService { const rightDescriptors = registry.items.filter(d => d.alignment === StatusbarAlignment.RIGHT).sort((a, b) => a.priority - b.priority); const descriptors = rightDescriptors.concat(leftDescriptors); // right first because they float - - this.toUnbind.push(...descriptors.map(descriptor => { + descriptors.forEach(descriptor => { const item = this.instantiationService.createInstance(descriptor.syncDescriptor); const el = this.doCreateStatusItem(descriptor.alignment, descriptor.priority); - const dispose = item.render(el); + this._register(item.render(el)); this.statusItemsContainer.appendChild(el); - - return dispose; - })); + }); return this.statusItemsContainer; } @@ -179,7 +176,7 @@ export class StatusbarPart extends Part implements IStatusbarService { return el; } - public setStatusMessage(message: string, autoDisposeAfter: number = -1, delayBy: number = 0): IDisposable { + setStatusMessage(message: string, autoDisposeAfter: number = -1, delayBy: number = 0): IDisposable { if (this.statusMsgDispose) { this.statusMsgDispose.dispose(); // dismiss any previous } @@ -238,7 +235,7 @@ class StatusBarEntryItem implements IStatusbarItem { } } - public render(el: HTMLElement): IDisposable { + render(el: HTMLElement): IDisposable { let toDispose: IDisposable[] = []; addClass(el, 'statusbar-entry'); @@ -324,7 +321,7 @@ class ManageExtensionAction extends Action { super('statusbar.manage.extension', nls.localize('manageExtension', "Manage Extension")); } - public run(extensionId: string): TPromise { + run(extensionId: string): TPromise { return this.commandService.executeCommand('_extensions.manage', extensionId); } } diff --git a/src/vs/workbench/browser/parts/titlebar/titlebarPart.ts b/src/vs/workbench/browser/parts/titlebar/titlebarPart.ts index 7619cce8d02..923c1c25051 100644 --- a/src/vs/workbench/browser/parts/titlebar/titlebarPart.ts +++ b/src/vs/workbench/browser/parts/titlebar/titlebarPart.ts @@ -36,7 +36,7 @@ import { IPartService } from 'vs/workbench/services/part/common/partService'; export class TitlebarPart extends Part implements ITitleService { - public _serviceBrand: any; + _serviceBrand: any; private static readonly NLS_UNSUPPORTED = nls.localize('patchedWindowTitle', "[Unsupported]"); private static readonly NLS_USER_IS_ADMIN = isWindows ? nls.localize('userIsAdmin', "[Administrator]") : nls.localize('userIsSudo', "[Superuser]"); @@ -87,14 +87,14 @@ export class TitlebarPart extends Part implements ITitleService { } private registerListeners(): void { - this.toUnbind.push(addDisposableListener(window, EventType.BLUR, () => this.onBlur())); - this.toUnbind.push(addDisposableListener(window, EventType.FOCUS, () => this.onFocus())); - this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChanged(e))); - this.toUnbind.push(this.editorService.onDidActiveEditorChange(() => this.onActiveEditorChange())); - this.toUnbind.push(this.contextService.onDidChangeWorkspaceFolders(() => this.setTitle(this.getWindowTitle()))); - this.toUnbind.push(this.contextService.onDidChangeWorkbenchState(() => this.setTitle(this.getWindowTitle()))); - this.toUnbind.push(this.contextService.onDidChangeWorkspaceName(() => this.setTitle(this.getWindowTitle()))); - this.toUnbind.push(this.partService.onMenubarVisibilityChange(this.onMenubarVisibilityChanged, this)); + this._register(addDisposableListener(window, EventType.BLUR, () => this.onBlur())); + this._register(addDisposableListener(window, EventType.FOCUS, () => this.onFocus())); + this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChanged(e))); + this._register(this.editorService.onDidActiveEditorChange(() => this.onActiveEditorChange())); + this._register(this.contextService.onDidChangeWorkspaceFolders(() => this.setTitle(this.getWindowTitle()))); + this._register(this.contextService.onDidChangeWorkbenchState(() => this.setTitle(this.getWindowTitle()))); + this._register(this.contextService.onDidChangeWorkspaceName(() => this.setTitle(this.getWindowTitle()))); + this._register(this.partService.onMenubarVisibilityChange(this.onMenubarVisibilityChanged, this)); } private onBlur(): void { @@ -177,7 +177,7 @@ export class TitlebarPart extends Part implements ITitleService { return title; } - public updateProperties(properties: ITitleProperties): void { + updateProperties(properties: ITitleProperties): void { const isAdmin = typeof properties.isAdmin === 'boolean' ? properties.isAdmin : this.properties.isAdmin; const isPure = typeof properties.isPure === 'boolean' ? properties.isPure : this.properties.isPure; @@ -246,7 +246,7 @@ export class TitlebarPart extends Part implements ITitleService { }); } - public createContentArea(parent: HTMLElement): HTMLElement { + createContentArea(parent: HTMLElement): HTMLElement { this.titleContainer = $(parent); // App Icon (Windows/Linux) @@ -417,7 +417,7 @@ export class TitlebarPart extends Part implements ITitleService { return actions; } - public setTitle(title: string): void { + setTitle(title: string): void { // Always set the native window title to identify us properly to the OS window.document.title = title; @@ -506,8 +506,7 @@ export class TitlebarPart extends Part implements ITitleService { } } - public layout(dimension: Dimension): Dimension[] { - + layout(dimension: Dimension): Dimension[] { this.updateLayout(); return super.layout(dimension); @@ -520,7 +519,7 @@ class ShowItemInFolderAction extends Action { super('showItemInFolder.action.id', label); } - public run(): TPromise { + run(): TPromise { return this.windowsService.showItemInFolder(this.path); } } diff --git a/src/vs/workbench/browser/parts/views/customView.ts b/src/vs/workbench/browser/parts/views/customView.ts index e50880f4648..cbde117567a 100644 --- a/src/vs/workbench/browser/parts/views/customView.ts +++ b/src/vs/workbench/browser/parts/views/customView.ts @@ -417,26 +417,26 @@ class TreeDataSource implements IDataSource { ) { } - public getId(tree: ITree, node: ITreeItem): string { + getId(tree: ITree, node: ITreeItem): string { return node.handle; } - public hasChildren(tree: ITree, node: ITreeItem): boolean { + hasChildren(tree: ITree, node: ITreeItem): boolean { return this.treeView.dataProvider && node.collapsibleState !== TreeItemCollapsibleState.None; } - public getChildren(tree: ITree, node: ITreeItem): TPromise { + getChildren(tree: ITree, node: ITreeItem): TPromise { if (this.treeView.dataProvider) { return this.progressService.withProgress({ location: this.container }, () => this.treeView.dataProvider.getChildren(node)); } return TPromise.as([]); } - public shouldAutoexpand(tree: ITree, node: ITreeItem): boolean { + shouldAutoexpand(tree: ITree, node: ITreeItem): boolean { return node.collapsibleState === TreeItemCollapsibleState.Expanded; } - public getParent(tree: ITree, node: any): TPromise { + getParent(tree: ITree, node: any): TPromise { return TPromise.as(null); } } @@ -463,15 +463,15 @@ class TreeRenderer implements IRenderer { ) { } - public getHeight(tree: ITree, element: any): number { + getHeight(tree: ITree, element: any): number { return TreeRenderer.ITEM_HEIGHT; } - public getTemplateId(tree: ITree, element: any): string { + getTemplateId(tree: ITree, element: any): string { return TreeRenderer.TREE_TEMPLATE_ID; } - public renderTemplate(tree: ITree, templateId: string, container: HTMLElement): ITreeExplorerTemplateData { + renderTemplate(tree: ITree, templateId: string, container: HTMLElement): ITreeExplorerTemplateData { DOM.addClass(container, 'custom-view-tree-node-item'); const icon = DOM.append(container, DOM.$('.custom-view-tree-node-item-icon')); @@ -486,7 +486,7 @@ class TreeRenderer implements IRenderer { return { label, resourceLabel, icon, actionBar, aligner: new Aligner(container, tree, this.themeService) }; } - public renderElement(tree: ITree, node: ITreeItem, templateId: string, templateData: ITreeExplorerTemplateData): void { + renderElement(tree: ITree, node: ITreeItem, templateId: string, templateData: ITreeExplorerTemplateData): void { const resource = node.resourceUri ? URI.revive(node.resourceUri) : null; const label = node.label ? node.label : resource ? basename(resource.path) : ''; const icon = this.themeService.getTheme().type === LIGHT ? node.icon : node.iconDark; @@ -528,7 +528,7 @@ class TreeRenderer implements IRenderer { return node.collapsibleState === TreeItemCollapsibleState.Collapsed || node.collapsibleState === TreeItemCollapsibleState.Expanded ? FileKind.FOLDER : FileKind.FILE; } - public disposeTemplate(tree: ITree, templateId: string, templateData: ITreeExplorerTemplateData): void { + disposeTemplate(tree: ITree, templateId: string, templateData: ITreeExplorerTemplateData): void { templateData.resourceLabel.dispose(); templateData.actionBar.dispose(); templateData.aligner.dispose(); @@ -607,7 +607,7 @@ class TreeController extends WorkbenchTreeController { return element.command ? this.isClickOnTwistie(event) : super.shouldToggleExpansion(element, event, origin); } - public onContextMenu(tree: ITree, node: ITreeItem, event: ContextMenuEvent): boolean { + onContextMenu(tree: ITree, node: ITreeItem, event: ContextMenuEvent): boolean { event.preventDefault(); event.stopPropagation(); diff --git a/src/vs/workbench/browser/quickopen.ts b/src/vs/workbench/browser/quickopen.ts index 407acc7b5d5..f942bae0e02 100644 --- a/src/vs/workbench/browser/quickopen.ts +++ b/src/vs/workbench/browser/quickopen.ts @@ -42,21 +42,21 @@ export class QuickOpenHandler { * As such, returning the same model instance across multiple searches will yield best * results in terms of performance when many items are shown. */ - public getResults(searchValue: string): TPromise> { + getResults(searchValue: string): TPromise> { return TPromise.as(null); } /** * The ARIA label to apply when this quick open handler is active in quick open. */ - public getAriaLabel(): string { + getAriaLabel(): string { return null; } /** * Extra CSS class name to add to the quick open widget to do custom styling of entries. */ - public getClass(): string { + getClass(): string { return null; } @@ -64,14 +64,14 @@ export class QuickOpenHandler { * Indicates if the handler can run in the current environment. Return a string if the handler cannot run but has * a good message to show in this case. */ - public canRun(): boolean | string { + canRun(): boolean | string { return true; } /** * Hints to the outside that this quick open handler typically returns results fast. */ - public hasShortResponseTime(): boolean { + hasShortResponseTime(): boolean { return false; } @@ -79,14 +79,14 @@ export class QuickOpenHandler { * Indicates if the handler wishes the quick open widget to automatically select the first result entry or an entry * based on a specific prefix match. */ - public getAutoFocus(searchValue: string, context: { model: IModel, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus { + getAutoFocus(searchValue: string, context: { model: IModel, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus { return {}; } /** * Indicates to the handler that the quick open widget has been opened. */ - public onOpen(): void { + onOpen(): void { return; } @@ -94,21 +94,21 @@ export class QuickOpenHandler { * Indicates to the handler that the quick open widget has been closed. Allows to free up any resources as needed. * The parameter canceled indicates if the quick open widget was closed with an entry being run or not. */ - public onClose(canceled: boolean): void { + onClose(canceled: boolean): void { return; } /** * Allows to return a label that will be placed to the side of the results from this handler or null if none. */ - public getGroupLabel(): string { + getGroupLabel(): string { return null; } /** * Allows to return a label that will be used when there are no results found */ - public getEmptyLabel(searchString: string): string { + getEmptyLabel(searchString: string): string { if (searchString.length > 0) { return nls.localize('noResultsMatching', "No results matching"); } @@ -126,11 +126,11 @@ export interface QuickOpenHandlerHelpEntry { * A lightweight descriptor of a quick open handler. */ export class QuickOpenHandlerDescriptor { - public prefix: string; - public description: string; - public contextKey: string; - public helpEntries: QuickOpenHandlerHelpEntry[]; - public instantProgress: boolean; + prefix: string; + description: string; + contextKey: string; + helpEntries: QuickOpenHandlerHelpEntry[]; + instantProgress: boolean; private id: string; private ctor: IConstructorSignature0; @@ -151,11 +151,11 @@ export class QuickOpenHandlerDescriptor { } } - public getId(): string { + getId(): string { return this.id; } - public instantiate(instantiationService: IInstantiationService): QuickOpenHandler { + instantiate(instantiationService: IInstantiationService): QuickOpenHandler { return instantiationService.createInstance(this.ctor); } } @@ -193,14 +193,10 @@ export interface IQuickOpenRegistry { } class QuickOpenRegistry implements IQuickOpenRegistry { - private handlers: QuickOpenHandlerDescriptor[]; + private handlers: QuickOpenHandlerDescriptor[] = []; private defaultHandler: QuickOpenHandlerDescriptor; - constructor() { - this.handlers = []; - } - - public registerQuickOpenHandler(descriptor: QuickOpenHandlerDescriptor): void { + registerQuickOpenHandler(descriptor: QuickOpenHandlerDescriptor): void { this.handlers.push(descriptor); // sort the handlers by decreasing prefix length, such that longer @@ -208,19 +204,19 @@ class QuickOpenRegistry implements IQuickOpenRegistry { this.handlers.sort((h1, h2) => h2.prefix.length - h1.prefix.length); } - public registerDefaultQuickOpenHandler(descriptor: QuickOpenHandlerDescriptor): void { + registerDefaultQuickOpenHandler(descriptor: QuickOpenHandlerDescriptor): void { this.defaultHandler = descriptor; } - public getQuickOpenHandlers(): QuickOpenHandlerDescriptor[] { + getQuickOpenHandlers(): QuickOpenHandlerDescriptor[] { return this.handlers.slice(0); } - public getQuickOpenHandler(text: string): QuickOpenHandlerDescriptor { + getQuickOpenHandler(text: string): QuickOpenHandlerDescriptor { return text ? arrays.first(this.handlers, h => strings.startsWith(text, h.prefix), null) : null; } - public getDefaultQuickOpenHandler(): QuickOpenHandlerDescriptor { + getDefaultQuickOpenHandler(): QuickOpenHandlerDescriptor { return this.defaultHandler; } } @@ -249,19 +245,19 @@ export class EditorQuickOpenEntry extends QuickOpenEntry implements IEditorQuick super(); } - public get editorService() { + get editorService() { return this._editorService; } - public getInput(): IResourceInput | IEditorInput { + getInput(): IResourceInput | IEditorInput { return null; } - public getOptions(): IEditorOptions { + getOptions(): IEditorOptions { return null; } - public run(mode: Mode, context: IEntryRunContext): boolean { + run(mode: Mode, context: IEntryRunContext): boolean { const hideWidget = (mode === Mode.OPEN); if (mode === Mode.OPEN || mode === Mode.OPEN_IN_BACKGROUND) { @@ -304,11 +300,11 @@ export class EditorQuickOpenEntry extends QuickOpenEntry implements IEditorQuick */ export class EditorQuickOpenEntryGroup extends QuickOpenEntryGroup implements IEditorQuickOpenEntry { - public getInput(): IEditorInput | IResourceInput { + getInput(): IEditorInput | IResourceInput { return null; } - public getOptions(): IEditorOptions { + getOptions(): IEditorOptions { return null; } } @@ -328,7 +324,7 @@ export class QuickOpenAction extends Action { this.enabled = !!this.quickOpenService; } - public run(context?: any): TPromise { + run(context?: any): TPromise { // Show with prefix this.quickOpenService.show(this.prefix); diff --git a/src/vs/workbench/browser/viewlet.ts b/src/vs/workbench/browser/viewlet.ts index 90e103c10bb..7dfd692e56f 100644 --- a/src/vs/workbench/browser/viewlet.ts +++ b/src/vs/workbench/browser/viewlet.ts @@ -30,11 +30,11 @@ export abstract class Viewlet extends Composite implements IViewlet { super(id, telemetryService, themeService); } - public getOptimalWidth(): number { + getOptimalWidth(): number { return null; } - public getContextMenuActions(): IAction[] { + getContextMenuActions(): IAction[] { return [{ id: ToggleSidebarVisibilityAction.ID, label: nls.localize('compositePart.hideSideBarLabel', "Hide Side Bar"), @@ -60,7 +60,7 @@ export class ViewletDescriptor extends CompositeDescriptor { super(ctor, id, name, cssClass, order, id); } - public get iconUrl(): URI { + get iconUrl(): URI { return this._iconUrl; } } @@ -75,35 +75,35 @@ export class ViewletRegistry extends CompositeRegistry { /** * Registers a viewlet to the platform. */ - public registerViewlet(descriptor: ViewletDescriptor): void { + registerViewlet(descriptor: ViewletDescriptor): void { super.registerComposite(descriptor); } /** * Returns the viewlet descriptor for the given id or null if none. */ - public getViewlet(id: string): ViewletDescriptor { + getViewlet(id: string): ViewletDescriptor { return this.getComposite(id) as ViewletDescriptor; } /** * Returns an array of registered viewlets known to the platform. */ - public getViewlets(): ViewletDescriptor[] { + getViewlets(): ViewletDescriptor[] { return this.getComposites() as ViewletDescriptor[]; } /** * Sets the id of the viewlet that should open on startup by default. */ - public setDefaultViewletId(id: string): void { + setDefaultViewletId(id: string): void { this.defaultViewletId = id; } /** * Gets the id of the viewlet that should open on startup by default. */ - public getDefaultViewletId(): string { + getDefaultViewletId(): string { return this.defaultViewletId; } } @@ -129,7 +129,7 @@ export class ToggleViewletAction extends Action { this.enabled = !!this.viewletService && !!this.editorGroupService; } - public run(): TPromise { + run(): TPromise { // Pass focus to viewlet if not open or focused if (this.otherViewletShowing() || !this.sidebarHasFocus()) { diff --git a/src/vs/workbench/common/component.ts b/src/vs/workbench/common/component.ts index 99cafcca30c..f855f0a8a30 100644 --- a/src/vs/workbench/common/component.ts +++ b/src/vs/workbench/common/component.ts @@ -45,7 +45,7 @@ export class Component extends Themable implements IWorkbenchComponent { this.componentMemento = new Memento(this.id); } - public getId(): string { + getId(): string { return this.id; } @@ -73,7 +73,7 @@ export class Component extends Themable implements IWorkbenchComponent { this.componentMemento.saveMemento(); } - public shutdown(): void { + shutdown(): void { // Save Memento this.saveMemento(); diff --git a/src/vs/workbench/common/contributions.ts b/src/vs/workbench/common/contributions.ts index fb6612f3a7c..0b86ba6a484 100644 --- a/src/vs/workbench/common/contributions.ts +++ b/src/vs/workbench/common/contributions.ts @@ -45,7 +45,7 @@ export class WorkbenchContributionsRegistry implements IWorkbenchContributionsRe private toBeInstantiated: Map[]> = new Map[]>(); - public registerWorkbenchContribution(ctor: IWorkbenchContributionSignature, phase: LifecyclePhase = LifecyclePhase.Starting): void { + registerWorkbenchContribution(ctor: IWorkbenchContributionSignature, phase: LifecyclePhase = LifecyclePhase.Starting): void { // Instantiate directly if we are already matching the provided phase if (this.instantiationService && this.lifecycleService && this.lifecycleService.phase >= phase) { @@ -64,7 +64,7 @@ export class WorkbenchContributionsRegistry implements IWorkbenchContributionsRe } } - public start(instantiationService: IInstantiationService, lifecycleService: ILifecycleService): void { + start(instantiationService: IInstantiationService, lifecycleService: ILifecycleService): void { this.instantiationService = instantiationService; this.lifecycleService = lifecycleService; diff --git a/src/vs/workbench/common/editor.ts b/src/vs/workbench/common/editor.ts index 59e35f9be53..2a9380282e9 100644 --- a/src/vs/workbench/common/editor.ts +++ b/src/vs/workbench/common/editor.ts @@ -9,7 +9,7 @@ import { Event, Emitter, once } from 'vs/base/common/event'; import * as objects from 'vs/base/common/objects'; import * as types from 'vs/base/common/types'; import URI from 'vs/base/common/uri'; -import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle'; +import { IDisposable, Disposable } from 'vs/base/common/lifecycle'; import { IEditor as ICodeEditor, IEditorViewState, ScrollType, IDiffEditor } from 'vs/editor/common/editorCommon'; import { IEditorModel, IEditorOptions, ITextEditorOptions, IBaseResourceInput } from 'vs/platform/editor/common/editor'; import { IInstantiationService, IConstructorSignature0 } from 'vs/platform/instantiation/common/instantiation'; @@ -318,46 +318,28 @@ export interface IEditorInput extends IDisposable { * Editor inputs are lightweight objects that can be passed to the workbench API to open inside the editor part. * Each editor input is mapped to an editor that is capable of opening it through the Platform facade. */ -export abstract class EditorInput implements IEditorInput { - private readonly _onDispose: Emitter; - protected _onDidChangeDirty: Emitter; - protected _onDidChangeLabel: Emitter; +export abstract class EditorInput extends Disposable implements IEditorInput { - private disposed: boolean; + protected readonly _onDidChangeDirty: Emitter = this._register(new Emitter()); + get onDidChangeDirty(): Event { return this._onDidChangeDirty.event; } - constructor() { - this._onDidChangeDirty = new Emitter(); - this._onDidChangeLabel = new Emitter(); - this._onDispose = new Emitter(); + protected readonly _onDidChangeLabel: Emitter = this._register(new Emitter()); + get onDidChangeLabel(): Event { return this._onDidChangeLabel.event; } - this.disposed = false; - } + private readonly _onDispose: Emitter = this._register(new Emitter()); + get onDispose(): Event { return this._onDispose.event; } + + private disposed: boolean = false; /** - * Fired when the dirty state of this input changes. + * Returns the unique type identifier of this input. */ - public get onDidChangeDirty(): Event { - return this._onDidChangeDirty.event; - } - - /** - * Fired when the label this input changes. - */ - public get onDidChangeLabel(): Event { - return this._onDidChangeLabel.event; - } - - /** - * Fired when the model gets disposed. - */ - public get onDispose(): Event { - return this._onDispose.event; - } + abstract getTypeId(): string; /** * Returns the associated resource of this input if any. */ - public getResource(): URI { + getResource(): URI { return null; } @@ -365,7 +347,7 @@ export abstract class EditorInput implements IEditorInput { * Returns the name of this input that can be shown to the user. Examples include showing the name of the input * above the editor area when the input is shown. */ - public getName(): string { + getName(): string { return null; } @@ -373,24 +355,23 @@ export abstract class EditorInput implements IEditorInput { * Returns the description of this input that can be shown to the user. Examples include showing the description of * the input above the editor area to the side of the name of the input. */ - public getDescription(verbosity?: Verbosity): string { + getDescription(verbosity?: Verbosity): string { return null; } - public getTitle(verbosity?: Verbosity): string { + /** + * Returns the title of this input that can be shown to the user. Examples include showing the title of + * the input above the editor area as hover over the input label. + */ + getTitle(verbosity?: Verbosity): string { return this.getName(); } - /** - * Returns the unique type identifier of this input. - */ - public abstract getTypeId(): string; - /** * Returns the preferred editor for this input. A list of candidate editors is passed in that whee registered * for the input. This allows subclasses to decide late which editor to use for the input on a case by case basis. */ - public getPreferredEditorId(candidates: string[]): string { + getPreferredEditorId(candidates: string[]): string { if (candidates && candidates.length > 0) { return candidates[0]; } @@ -403,7 +384,7 @@ export abstract class EditorInput implements IEditorInput { * * Subclasses should extend if they can contribute. */ - public getTelemetryDescriptor(): object { + getTelemetryDescriptor(): object { /* __GDPR__FRAGMENT__ "EditorTelemetryDescriptor" : { "typeId" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } @@ -418,75 +399,73 @@ export abstract class EditorInput implements IEditorInput { * if the EditorModel should be refreshed before returning it. Depending on the implementation * this could mean to refresh the editor model contents with the version from disk. */ - public abstract resolve(refresh?: boolean): TPromise; + abstract resolve(refresh?: boolean): TPromise; /** * An editor that is dirty will be asked to be saved once it closes. */ - public isDirty(): boolean { + isDirty(): boolean { return false; } /** * Subclasses should bring up a proper dialog for the user if the editor is dirty and return the result. */ - public confirmSave(): TPromise { + confirmSave(): TPromise { return TPromise.wrap(ConfirmResult.DONT_SAVE); } /** * Saves the editor if it is dirty. Subclasses return a promise with a boolean indicating the success of the operation. */ - public save(): TPromise { + save(): TPromise { return TPromise.as(true); } /** * Reverts the editor if it is dirty. Subclasses return a promise with a boolean indicating the success of the operation. */ - public revert(options?: IRevertOptions): TPromise { + revert(options?: IRevertOptions): TPromise { return TPromise.as(true); } /** * Called when this input is no longer opened in any editor. Subclasses can free resources as needed. */ - public close(): void { + close(): void { this.dispose(); } /** * Subclasses can set this to false if it does not make sense to split the editor input. */ - public supportsSplitEditor(): boolean { + supportsSplitEditor(): boolean { return true; } /** * Returns true if this input is identical to the otherInput. */ - public matches(otherInput: any): boolean { + matches(otherInput: any): boolean { return this === otherInput; } + /** + * Returns whether this input was disposed or not. + */ + isDisposed(): boolean { + return this.disposed; + } + /** * Called when an editor input is no longer needed. Allows to free up any resources taken by * resolving the editor input. */ - public dispose(): void { + dispose(): void { this.disposed = true; this._onDispose.fire(); - this._onDidChangeDirty.dispose(); - this._onDidChangeLabel.dispose(); - this._onDispose.dispose(); - } - - /** - * Returns whether this input was disposed or not. - */ - public isDisposed(): boolean { - return this.disposed; + super.dispose(); } } @@ -544,13 +523,11 @@ export interface IFileEditorInput extends IEditorInput, IEncodingSupport { */ export class SideBySideEditorInput extends EditorInput { - public static readonly ID: string = 'workbench.editorinputs.sidebysideEditorInput'; - - private _toUnbind: IDisposable[]; + static readonly ID: string = 'workbench.editorinputs.sidebysideEditorInput'; constructor(private name: string, private description: string, private _details: EditorInput, private _master: EditorInput) { super(); - this._toUnbind = []; + this.registerListeners(); } @@ -562,23 +539,23 @@ export class SideBySideEditorInput extends EditorInput { return this._details; } - public isDirty(): boolean { + isDirty(): boolean { return this.master.isDirty(); } - public confirmSave(): TPromise { + confirmSave(): TPromise { return this.master.confirmSave(); } - public save(): TPromise { + save(): TPromise { return this.master.save(); } - public revert(): TPromise { + revert(): TPromise { return this.master.revert(); } - public getTelemetryDescriptor(): object { + getTelemetryDescriptor(): object { const descriptor = this.master.getTelemetryDescriptor(); return objects.assign(descriptor, super.getTelemetryDescriptor()); } @@ -587,29 +564,25 @@ export class SideBySideEditorInput extends EditorInput { // When the details or master input gets disposed, dispose this diff editor input const onceDetailsDisposed = once(this.details.onDispose); - this._toUnbind.push(onceDetailsDisposed(() => { + this._register(onceDetailsDisposed(() => { if (!this.isDisposed()) { this.dispose(); } })); const onceMasterDisposed = once(this.master.onDispose); - this._toUnbind.push(onceMasterDisposed(() => { + this._register(onceMasterDisposed(() => { if (!this.isDisposed()) { this.dispose(); } })); // Reemit some events from the master side to the outside - this._toUnbind.push(this.master.onDidChangeDirty(() => this._onDidChangeDirty.fire())); - this._toUnbind.push(this.master.onDidChangeLabel(() => this._onDidChangeLabel.fire())); + this._register(this.master.onDidChangeDirty(() => this._onDidChangeDirty.fire())); + this._register(this.master.onDidChangeLabel(() => this._onDidChangeLabel.fire())); } - public get toUnbind() { - return this._toUnbind; - } - - public resolve(refresh?: boolean): TPromise { + resolve(refresh?: boolean): TPromise { return TPromise.as(null); } @@ -617,15 +590,15 @@ export class SideBySideEditorInput extends EditorInput { return SideBySideEditorInput.ID; } - public getName(): string { + getName(): string { return this.name; } - public getDescription(): string { + getDescription(): string { return this.description; } - public matches(otherInput: any): boolean { + matches(otherInput: any): boolean { if (super.matches(otherInput) === true) { return true; } @@ -641,11 +614,6 @@ export class SideBySideEditorInput extends EditorInput { return false; } - - public dispose(): void { - this._toUnbind = dispose(this._toUnbind); - super.dispose(); - } } export interface ITextEditorModel extends IEditorModel { @@ -658,40 +626,30 @@ export interface ITextEditorModel extends IEditorModel { * are typically cached for some while because they are expensive to construct. */ export class EditorModel extends Disposable implements IEditorModel { - private readonly _onDispose: Emitter; - constructor() { - super(); - this._onDispose = new Emitter(); - } - - /** - * Fired when the model gets disposed. - */ - public get onDispose(): Event { - return this._onDispose.event; - } + private readonly _onDispose: Emitter = this._register(new Emitter()); + get onDispose(): Event { return this._onDispose.event; } /** * Causes this model to load returning a promise when loading is completed. */ - public load(): TPromise { + load(): TPromise { return TPromise.as(this); } /** * Returns whether this model was loaded or not. */ - public isResolved(): boolean { + isResolved(): boolean { return true; } /** * Subclasses should implement to free resources that have been claimed through loading. */ - public dispose(): void { + dispose(): void { this._onDispose.fire(); - this._onDispose.dispose(); + super.dispose(); } } @@ -715,7 +673,7 @@ export class EditorOptions implements IEditorOptions { /** * Helper to create EditorOptions inline. */ - public static create(settings: IEditorOptions): EditorOptions { + static create(settings: IEditorOptions): EditorOptions { const options = new EditorOptions(); options.preserveFocus = settings.preserveFocus; @@ -733,41 +691,41 @@ export class EditorOptions implements IEditorOptions { * Tells the editor to not receive keyboard focus when the editor is being opened. By default, * the editor will receive keyboard focus on open. */ - public preserveFocus: boolean; + preserveFocus: boolean; /** * Tells the editor to replace the editor input in the editor even if it is identical to the one * already showing. By default, the editor will not replace the input if it is identical to the * one showing. */ - public forceOpen: boolean; + forceOpen: boolean; /** * Will reveal the editor if it is already opened and visible in any of the opened editor groups. */ - public revealIfVisible: boolean; + revealIfVisible: boolean; /** * Will reveal the editor if it is already opened (even when not visible) in any of the opened editor groups. */ - public revealIfOpened: boolean; + revealIfOpened: boolean; /** * An editor that is pinned remains in the editor stack even when another editor is being opened. * An editor that is not pinned will always get replaced by another editor that is not pinned. */ - public pinned: boolean; + pinned: boolean; /** * The index in the document stack where to insert the editor into when opening. */ - public index: number; + index: number; /** * An active editor that is opened will show its contents directly. Set to true to open an editor * in the background. */ - public inactive: boolean; + inactive: boolean; } /** @@ -782,7 +740,7 @@ export class TextEditorOptions extends EditorOptions { private revealInCenterIfOutsideViewport: boolean; private editorViewState: IEditorViewState; - public static from(input?: IBaseResourceInput): TextEditorOptions { + static from(input?: IBaseResourceInput): TextEditorOptions { if (!input || !input.options) { return null; } @@ -793,7 +751,7 @@ export class TextEditorOptions extends EditorOptions { /** * Helper to convert options bag to real class */ - public static create(options: ITextEditorOptions = Object.create(null)): TextEditorOptions { + static create(options: ITextEditorOptions = Object.create(null)): TextEditorOptions { const textEditorOptions = new TextEditorOptions(); if (options.selection) { @@ -843,14 +801,14 @@ export class TextEditorOptions extends EditorOptions { /** * Returns if this options object has objects defined for the editor. */ - public hasOptionsDefined(): boolean { + hasOptionsDefined(): boolean { return !!this.editorViewState || (!types.isUndefinedOrNull(this.startLineNumber) && !types.isUndefinedOrNull(this.startColumn)); } /** * Tells the editor to set show the given selection when the editor is being opened. */ - public selection(startLineNumber: number, startColumn: number, endLineNumber: number = startLineNumber, endColumn: number = startColumn): EditorOptions { + selection(startLineNumber: number, startColumn: number, endLineNumber: number = startLineNumber, endColumn: number = startColumn): EditorOptions { this.startLineNumber = startLineNumber; this.startColumn = startColumn; this.endLineNumber = endLineNumber; @@ -862,7 +820,7 @@ export class TextEditorOptions extends EditorOptions { /** * Create a TextEditorOptions inline to be used when the editor is opening. */ - public static fromEditor(editor: ICodeEditor, settings?: IEditorOptions): TextEditorOptions { + static fromEditor(editor: ICodeEditor, settings?: IEditorOptions): TextEditorOptions { const options = TextEditorOptions.create(settings); // View state @@ -876,7 +834,7 @@ export class TextEditorOptions extends EditorOptions { * * @return if something was applied */ - public apply(editor: ICodeEditor, scrollType: ScrollType): boolean { + apply(editor: ICodeEditor, scrollType: ScrollType): boolean { // View state return this.applyViewState(editor, scrollType); @@ -1057,10 +1015,7 @@ class EditorInputFactoryRegistry implements IEditorInputFactoryRegistry { private editorInputFactoryConstructors: { [editorInputId: string]: IConstructorSignature0 } = Object.create(null); private editorInputFactoryInstances: { [editorInputId: string]: IEditorInputFactory } = Object.create(null); - constructor() { - } - - public setInstantiationService(service: IInstantiationService): void { + setInstantiationService(service: IInstantiationService): void { this.instantiationService = service; for (let key in this.editorInputFactoryConstructors) { @@ -1076,15 +1031,15 @@ class EditorInputFactoryRegistry implements IEditorInputFactoryRegistry { this.editorInputFactoryInstances[editorInputId] = instance; } - public registerFileInputFactory(factory: IFileInputFactory): void { + registerFileInputFactory(factory: IFileInputFactory): void { this.fileInputFactory = factory; } - public getFileInputFactory(): IFileInputFactory { + getFileInputFactory(): IFileInputFactory { return this.fileInputFactory; } - public registerEditorInputFactory(editorInputId: string, ctor: IConstructorSignature0): void { + registerEditorInputFactory(editorInputId: string, ctor: IConstructorSignature0): void { if (!this.instantiationService) { this.editorInputFactoryConstructors[editorInputId] = ctor; } else { @@ -1092,7 +1047,7 @@ class EditorInputFactoryRegistry implements IEditorInputFactoryRegistry { } } - public getEditorInputFactory(editorInputId: string): IEditorInputFactory { + getEditorInputFactory(editorInputId: string): IEditorInputFactory { return this.editorInputFactoryInstances[editorInputId]; } } diff --git a/src/vs/workbench/common/editor/binaryEditorModel.ts b/src/vs/workbench/common/editor/binaryEditorModel.ts index d4f34881d8c..061090b27ce 100644 --- a/src/vs/workbench/common/editor/binaryEditorModel.ts +++ b/src/vs/workbench/common/editor/binaryEditorModel.ts @@ -44,39 +44,39 @@ export class BinaryEditorModel extends EditorModel { /** * The name of the binary resource. */ - public getName(): string { + getName(): string { return this.name; } /** * The resource of the binary resource. */ - public getResource(): URI { + getResource(): URI { return this.resource; } /** * The size of the binary resource if known. */ - public getSize(): number { + getSize(): number { return this.size; } /** * The mime of the binary resource if known. */ - public getMime(): string { + getMime(): string { return this.mime; } /** * The etag of the binary resource if known. */ - public getETag(): string { + getETag(): string { return this.etag; } - public load(): TPromise { + load(): TPromise { // Make sure to resolve up to date stat for file resources if (this.fileService.canHandleResource(this.resource)) { diff --git a/src/vs/workbench/common/editor/dataUriEditorInput.ts b/src/vs/workbench/common/editor/dataUriEditorInput.ts index c1d785bd73b..cc8bb4cb10c 100644 --- a/src/vs/workbench/common/editor/dataUriEditorInput.ts +++ b/src/vs/workbench/common/editor/dataUriEditorInput.ts @@ -49,27 +49,27 @@ export class DataUriEditorInput extends EditorInput { } } - public getResource(): URI { + getResource(): URI { return this.resource; } - public getTypeId(): string { + getTypeId(): string { return DataUriEditorInput.ID; } - public getName(): string { + getName(): string { return this.name; } - public getDescription(): string { + getDescription(): string { return this.description; } - public resolve(refresh?: boolean): TPromise { + resolve(refresh?: boolean): TPromise { return this.instantiationService.createInstance(BinaryEditorModel, this.resource, this.getName()).load().then(m => m as BinaryEditorModel); } - public matches(otherInput: any): boolean { + matches(otherInput: any): boolean { if (super.matches(otherInput) === true) { return true; } diff --git a/src/vs/workbench/common/editor/diffEditorInput.ts b/src/vs/workbench/common/editor/diffEditorInput.ts index 7554329bd52..7625ffdf06f 100644 --- a/src/vs/workbench/common/editor/diffEditorInput.ts +++ b/src/vs/workbench/common/editor/diffEditorInput.ts @@ -16,7 +16,7 @@ import { TextDiffEditorModel } from 'vs/workbench/common/editor/textDiffEditorMo */ export class DiffEditorInput extends SideBySideEditorInput { - public static readonly ID = 'workbench.editors.diffEditorInput'; + static readonly ID = 'workbench.editors.diffEditorInput'; private cachedModel: DiffEditorModel; @@ -24,7 +24,7 @@ export class DiffEditorInput extends SideBySideEditorInput { super(name, description, original, modified); } - public getTypeId(): string { + getTypeId(): string { return DiffEditorInput.ID; } @@ -36,7 +36,7 @@ export class DiffEditorInput extends SideBySideEditorInput { return this.master; } - public resolve(refresh?: boolean): TPromise { + resolve(refresh?: boolean): TPromise { let modelPromise: TPromise; // Use Cached Model @@ -63,7 +63,7 @@ export class DiffEditorInput extends SideBySideEditorInput { }); } - public getPreferredEditorId(candidates: string[]): string { + getPreferredEditorId(candidates: string[]): string { return this.forceOpenAsBinary ? BINARY_DIFF_EDITOR_ID : TEXT_DIFF_EDITOR_ID; } @@ -87,7 +87,7 @@ export class DiffEditorInput extends SideBySideEditorInput { }); } - public dispose(): void { + dispose(): void { // Free the diff editor model but do not propagate the dispose() call to the two inputs // We never created the two inputs (original and modified) so we can not dispose diff --git a/src/vs/workbench/common/editor/diffEditorModel.ts b/src/vs/workbench/common/editor/diffEditorModel.ts index 47c74e1daf3..232e915b631 100644 --- a/src/vs/workbench/common/editor/diffEditorModel.ts +++ b/src/vs/workbench/common/editor/diffEditorModel.ts @@ -23,15 +23,15 @@ export class DiffEditorModel extends EditorModel { this._modifiedModel = modifiedModel; } - public get originalModel(): EditorModel { + get originalModel(): EditorModel { return this._originalModel as EditorModel; } - public get modifiedModel(): EditorModel { + get modifiedModel(): EditorModel { return this._modifiedModel as EditorModel; } - public load(): TPromise { + load(): TPromise { return TPromise.join([ this._originalModel.load(), this._modifiedModel.load() @@ -40,11 +40,11 @@ export class DiffEditorModel extends EditorModel { }); } - public isResolved(): boolean { + isResolved(): boolean { return this.originalModel.isResolved() && this.modifiedModel.isResolved(); } - public dispose(): void { + dispose(): void { // Do not propagate the dispose() call to the two models inside. We never created the two models // (original and modified) so we can not dispose them without sideeffects. Rather rely on the diff --git a/src/vs/workbench/common/editor/resourceEditorInput.ts b/src/vs/workbench/common/editor/resourceEditorInput.ts index 0d19259d23a..44a3789a400 100644 --- a/src/vs/workbench/common/editor/resourceEditorInput.ts +++ b/src/vs/workbench/common/editor/resourceEditorInput.ts @@ -40,37 +40,37 @@ export class ResourceEditorInput extends EditorInput { this.resource = resource; } - public getResource(): URI { + getResource(): URI { return this.resource; } - public getTypeId(): string { + getTypeId(): string { return ResourceEditorInput.ID; } - public getName(): string { + getName(): string { return this.name; } - public setName(name: string): void { + setName(name: string): void { if (this.name !== name) { this.name = name; this._onDidChangeLabel.fire(); } } - public getDescription(): string { + getDescription(): string { return this.description; } - public setDescription(description: string): void { + setDescription(description: string): void { if (this.description !== description) { this.description = description; this._onDidChangeLabel.fire(); } } - public getTelemetryDescriptor(): object { + getTelemetryDescriptor(): object { const descriptor = super.getTelemetryDescriptor(); descriptor['resource'] = telemetryURIDescriptor(this.resource, path => this.hashService.createSHA1(path)); @@ -82,7 +82,7 @@ export class ResourceEditorInput extends EditorInput { return descriptor; } - public resolve(refresh?: boolean): TPromise { + resolve(refresh?: boolean): TPromise { if (!this.modelReference) { this.modelReference = this.textModelResolverService.createModelReference(this.resource); } @@ -101,7 +101,7 @@ export class ResourceEditorInput extends EditorInput { }); } - public matches(otherInput: any): boolean { + matches(otherInput: any): boolean { if (super.matches(otherInput) === true) { return true; } @@ -116,7 +116,7 @@ export class ResourceEditorInput extends EditorInput { return false; } - public dispose(): void { + dispose(): void { if (this.modelReference) { this.modelReference.done(ref => ref.dispose()); this.modelReference = null; diff --git a/src/vs/workbench/common/editor/textDiffEditorModel.ts b/src/vs/workbench/common/editor/textDiffEditorModel.ts index 70c3279e8d8..dd26af7c5f2 100644 --- a/src/vs/workbench/common/editor/textDiffEditorModel.ts +++ b/src/vs/workbench/common/editor/textDiffEditorModel.ts @@ -31,7 +31,7 @@ export class TextDiffEditorModel extends DiffEditorModel { return this._modifiedModel as BaseTextEditorModel; } - public load(): TPromise { + load(): TPromise { return super.load().then(() => { this.updateTextDiffEditorModel(); @@ -58,19 +58,19 @@ export class TextDiffEditorModel extends DiffEditorModel { } } - public get textDiffEditorModel(): IDiffEditorModel { + get textDiffEditorModel(): IDiffEditorModel { return this._textDiffEditorModel; } - public isResolved(): boolean { + isResolved(): boolean { return !!this._textDiffEditorModel; } - public isReadonly(): boolean { + isReadonly(): boolean { return this.modifiedModel.isReadonly(); } - public dispose(): void { + dispose(): void { // Free the diff editor model but do not propagate the dispose() call to the two models // inside. We never created the two models (original and modified) so we can not dispose diff --git a/src/vs/workbench/common/editor/textEditorModel.ts b/src/vs/workbench/common/editor/textEditorModel.ts index 20bec65ef18..a5c738bd121 100644 --- a/src/vs/workbench/common/editor/textEditorModel.ts +++ b/src/vs/workbench/common/editor/textEditorModel.ts @@ -19,8 +19,10 @@ import { ITextSnapshot } from 'vs/platform/files/common/files'; * The base text editor model leverages the code editor model. This class is only intended to be subclassed and not instantiated. */ export abstract class BaseTextEditorModel extends EditorModel implements ITextEditorModel { - private textEditorModelHandle: URI; + protected createdEditorModel: boolean; + + private textEditorModelHandle: URI; private modelDisposeListener: IDisposable; constructor( @@ -60,7 +62,7 @@ export abstract class BaseTextEditorModel extends EditorModel implements ITextEd }); } - public get textEditorModel(): ITextModel { + get textEditorModel(): ITextModel { return this.textEditorModelHandle ? this.modelService.getModel(this.textEditorModelHandle) : null; } @@ -124,7 +126,7 @@ export abstract class BaseTextEditorModel extends EditorModel implements ITextEd this.modelService.updateModel(this.textEditorModel, newValue); } - public createSnapshot(): ITextSnapshot { + createSnapshot(): ITextSnapshot { const model = this.textEditorModel; if (model) { return model.createSnapshot(true /* Preserve BOM */); @@ -133,15 +135,15 @@ export abstract class BaseTextEditorModel extends EditorModel implements ITextEd return null; } - public isResolved(): boolean { + isResolved(): boolean { return !!this.textEditorModelHandle; } - public isReadonly(): boolean { + isReadonly(): boolean { return false; } - public dispose(): void { + dispose(): void { if (this.modelDisposeListener) { this.modelDisposeListener.dispose(); // dispose this first because it will trigger another dispose() otherwise this.modelDisposeListener = null; diff --git a/src/vs/workbench/common/editor/untitledEditorInput.ts b/src/vs/workbench/common/editor/untitledEditorInput.ts index a87394cdd84..ee49dbe7211 100644 --- a/src/vs/workbench/common/editor/untitledEditorInput.ts +++ b/src/vs/workbench/common/editor/untitledEditorInput.ts @@ -16,7 +16,6 @@ import { EditorInput, IEncodingSupport, EncodingMode, ConfirmResult, Verbosity } import { UntitledEditorModel } from 'vs/workbench/common/editor/untitledEditorModel'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { Event, Emitter } from 'vs/base/common/event'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { telemetryURIDescriptor } from 'vs/platform/telemetry/common/telemetryUtils'; @@ -28,16 +27,17 @@ import { IHashService } from 'vs/workbench/services/hash/common/hashService'; */ export class UntitledEditorInput extends EditorInput implements IEncodingSupport { - public static readonly ID: string = 'workbench.editors.untitledEditorInput'; + static readonly ID: string = 'workbench.editors.untitledEditorInput'; private _hasAssociatedFilePath: boolean; private cachedModel: UntitledEditorModel; private modelResolve: TPromise; - private readonly _onDidModelChangeContent: Emitter; - private readonly _onDidModelChangeEncoding: Emitter; + private readonly _onDidModelChangeContent: Emitter = this._register(new Emitter()); + get onDidModelChangeContent(): Event { return this._onDidModelChangeContent.event; } - private toUnbind: IDisposable[]; + private readonly _onDidModelChangeEncoding: Emitter = this._register(new Emitter()); + get onDidModelChangeEncoding(): Event { return this._onDidModelChangeEncoding.event; } constructor( private resource: URI, @@ -54,33 +54,21 @@ export class UntitledEditorInput extends EditorInput implements IEncodingSupport super(); this._hasAssociatedFilePath = hasAssociatedFilePath; - this.toUnbind = []; - - this._onDidModelChangeContent = new Emitter(); - this._onDidModelChangeEncoding = new Emitter(); } - public get hasAssociatedFilePath(): boolean { + get hasAssociatedFilePath(): boolean { return this._hasAssociatedFilePath; } - public get onDidModelChangeContent(): Event { - return this._onDidModelChangeContent.event; - } - - public get onDidModelChangeEncoding(): Event { - return this._onDidModelChangeEncoding.event; - } - - public getTypeId(): string { + getTypeId(): string { return UntitledEditorInput.ID; } - public getResource(): URI { + getResource(): URI { return this.resource; } - public getModeId(): string { + getModeId(): string { if (this.cachedModel) { return this.cachedModel.getModeId(); } @@ -88,7 +76,7 @@ export class UntitledEditorInput extends EditorInput implements IEncodingSupport return this.modeId; } - public getName(): string { + getName(): string { return this.hasAssociatedFilePath ? resources.basenameOrAuthority(this.resource) : this.resource.path; } @@ -107,7 +95,7 @@ export class UntitledEditorInput extends EditorInput implements IEncodingSupport return labels.getPathLabel(resources.dirname(this.resource), this.environmentService); } - public getDescription(verbosity: Verbosity = Verbosity.MEDIUM): string { + getDescription(verbosity: Verbosity = Verbosity.MEDIUM): string { if (!this.hasAssociatedFilePath) { return null; } @@ -144,7 +132,7 @@ export class UntitledEditorInput extends EditorInput implements IEncodingSupport return labels.getPathLabel(this.resource, this.environmentService); } - public getTitle(verbosity: Verbosity): string { + getTitle(verbosity: Verbosity): string { if (!this.hasAssociatedFilePath) { return this.getName(); } @@ -165,7 +153,7 @@ export class UntitledEditorInput extends EditorInput implements IEncodingSupport return title; } - public isDirty(): boolean { + isDirty(): boolean { if (this.cachedModel) { return this.cachedModel.isDirty(); } @@ -179,15 +167,15 @@ export class UntitledEditorInput extends EditorInput implements IEncodingSupport return this.hasAssociatedFilePath; } - public confirmSave(): TPromise { + confirmSave(): TPromise { return this.textFileService.confirmSave([this.resource]); } - public save(): TPromise { + save(): TPromise { return this.textFileService.save(this.resource); } - public revert(): TPromise { + revert(): TPromise { if (this.cachedModel) { this.cachedModel.revert(); } @@ -197,7 +185,7 @@ export class UntitledEditorInput extends EditorInput implements IEncodingSupport return TPromise.as(true); } - public suggestFileName(): string { + suggestFileName(): string { if (!this.hasAssociatedFilePath) { if (this.cachedModel) { const modeId = this.cachedModel.getModeId(); @@ -210,7 +198,7 @@ export class UntitledEditorInput extends EditorInput implements IEncodingSupport return this.getName(); } - public getEncoding(): string { + getEncoding(): string { if (this.cachedModel) { return this.cachedModel.getEncoding(); } @@ -218,7 +206,7 @@ export class UntitledEditorInput extends EditorInput implements IEncodingSupport return this.preferredEncoding; } - public setEncoding(encoding: string, mode: EncodingMode /* ignored, we only have Encode */): void { + setEncoding(encoding: string, mode: EncodingMode /* ignored, we only have Encode */): void { this.preferredEncoding = encoding; if (this.cachedModel) { @@ -226,7 +214,7 @@ export class UntitledEditorInput extends EditorInput implements IEncodingSupport } } - public resolve(): TPromise { + resolve(): TPromise { // Join a model resolve if we have had one before if (this.modelResolve) { @@ -241,17 +229,17 @@ export class UntitledEditorInput extends EditorInput implements IEncodingSupport } private createModel(): UntitledEditorModel { - const model = this.instantiationService.createInstance(UntitledEditorModel, this.modeId, this.resource, this.hasAssociatedFilePath, this.initialValue, this.preferredEncoding); + const model = this._register(this.instantiationService.createInstance(UntitledEditorModel, this.modeId, this.resource, this.hasAssociatedFilePath, this.initialValue, this.preferredEncoding)); // re-emit some events from the model - this.toUnbind.push(model.onDidChangeContent(() => this._onDidModelChangeContent.fire())); - this.toUnbind.push(model.onDidChangeDirty(() => this._onDidChangeDirty.fire())); - this.toUnbind.push(model.onDidChangeEncoding(() => this._onDidModelChangeEncoding.fire())); + this._register(model.onDidChangeContent(() => this._onDidModelChangeContent.fire())); + this._register(model.onDidChangeDirty(() => this._onDidChangeDirty.fire())); + this._register(model.onDidChangeEncoding(() => this._onDidModelChangeEncoding.fire())); return model; } - public getTelemetryDescriptor(): object { + getTelemetryDescriptor(): object { const descriptor = super.getTelemetryDescriptor(); descriptor['resource'] = telemetryURIDescriptor(this.getResource(), path => this.hashService.createSHA1(path)); @@ -263,7 +251,7 @@ export class UntitledEditorInput extends EditorInput implements IEncodingSupport return descriptor; } - public matches(otherInput: any): boolean { + matches(otherInput: any): boolean { if (super.matches(otherInput) === true) { return true; } @@ -278,19 +266,7 @@ export class UntitledEditorInput extends EditorInput implements IEncodingSupport return false; } - public dispose(): void { - this._onDidModelChangeContent.dispose(); - this._onDidModelChangeEncoding.dispose(); - - // Listeners - dispose(this.toUnbind); - - // Model - if (this.cachedModel) { - this.cachedModel.dispose(); - this.cachedModel = null; - } - + dispose(): void { this.modelResolve = void 0; super.dispose(); diff --git a/src/vs/workbench/common/editor/untitledEditorModel.ts b/src/vs/workbench/common/editor/untitledEditorModel.ts index c7033b68d95..6d350b615bc 100644 --- a/src/vs/workbench/common/editor/untitledEditorModel.ts +++ b/src/vs/workbench/common/editor/untitledEditorModel.ts @@ -4,7 +4,6 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { TPromise } from 'vs/base/common/winjs.base'; import { IEncodingSupport } from 'vs/workbench/common/editor'; import { BaseTextEditorModel } from 'vs/workbench/common/editor/textEditorModel'; @@ -23,19 +22,20 @@ import { createTextBufferFactory } from 'vs/editor/common/model/textModel'; export class UntitledEditorModel extends BaseTextEditorModel implements IEncodingSupport { - public static DEFAULT_CONTENT_CHANGE_BUFFER_DELAY = CONTENT_CHANGE_EVENT_BUFFER_DELAY; + static DEFAULT_CONTENT_CHANGE_BUFFER_DELAY = CONTENT_CHANGE_EVENT_BUFFER_DELAY; - private toDispose: IDisposable[]; + private readonly _onDidChangeContent: Emitter = this._register(new Emitter()); + get onDidChangeContent(): Event { return this._onDidChangeContent.event; } + + private readonly _onDidChangeDirty: Emitter = this._register(new Emitter()); + get onDidChangeDirty(): Event { return this._onDidChangeDirty.event; } + + private readonly _onDidChangeEncoding: Emitter = this._register(new Emitter()); + get onDidChangeEncoding(): Event { return this._onDidChangeEncoding.event; } private dirty: boolean; - private readonly _onDidChangeContent: Emitter; - private readonly _onDidChangeDirty: Emitter; - private readonly _onDidChangeEncoding: Emitter; - private versionId: number; - private contentChangeEventScheduler: RunOnceScheduler; - private configuredEncoding: string; constructor( @@ -53,35 +53,12 @@ export class UntitledEditorModel extends BaseTextEditorModel implements IEncodin this.dirty = false; this.versionId = 0; - this.toDispose = []; - this._onDidChangeContent = new Emitter(); - this.toDispose.push(this._onDidChangeContent); - - this._onDidChangeDirty = new Emitter(); - this.toDispose.push(this._onDidChangeDirty); - - this._onDidChangeEncoding = new Emitter(); - this.toDispose.push(this._onDidChangeEncoding); - - this.contentChangeEventScheduler = new RunOnceScheduler(() => this._onDidChangeContent.fire(), UntitledEditorModel.DEFAULT_CONTENT_CHANGE_BUFFER_DELAY); - this.toDispose.push(this.contentChangeEventScheduler); + this.contentChangeEventScheduler = this._register(new RunOnceScheduler(() => this._onDidChangeContent.fire(), UntitledEditorModel.DEFAULT_CONTENT_CHANGE_BUFFER_DELAY)); this.registerListeners(); } - public get onDidChangeContent(): Event { - return this._onDidChangeContent.event; - } - - public get onDidChangeDirty(): Event { - return this._onDidChangeDirty.event; - } - - public get onDidChangeEncoding(): Event { - return this._onDidChangeEncoding.event; - } - protected getOrCreateMode(modeService: IModeService, modeId: string, firstLineText?: string): TPromise { if (!modeId || modeId === PLAINTEXT_MODE_ID) { return modeService.getOrCreateModeByFilenameOrFirstLine(this.resource.fsPath, firstLineText); // lookup mode via resource path if the provided modeId is unspecific @@ -93,7 +70,7 @@ export class UntitledEditorModel extends BaseTextEditorModel implements IEncodin private registerListeners(): void { // Config Changes - this.toDispose.push(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChange())); + this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChange())); } private onConfigurationChange(): void { @@ -108,11 +85,11 @@ export class UntitledEditorModel extends BaseTextEditorModel implements IEncodin } } - public getVersionId(): number { + getVersionId(): number { return this.versionId; } - public getModeId(): string { + getModeId(): string { if (this.textEditorModel) { return this.textEditorModel.getLanguageIdentifier().language; } @@ -120,11 +97,11 @@ export class UntitledEditorModel extends BaseTextEditorModel implements IEncodin return null; } - public getEncoding(): string { + getEncoding(): string { return this.preferredEncoding || this.configuredEncoding; } - public setEncoding(encoding: string): void { + setEncoding(encoding: string): void { const oldEncoding = this.getEncoding(); this.preferredEncoding = encoding; @@ -134,7 +111,7 @@ export class UntitledEditorModel extends BaseTextEditorModel implements IEncodin } } - public isDirty(): boolean { + isDirty(): boolean { return this.dirty; } @@ -147,18 +124,18 @@ export class UntitledEditorModel extends BaseTextEditorModel implements IEncodin this._onDidChangeDirty.fire(); } - public getResource(): URI { + getResource(): URI { return this.resource; } - public revert(): void { + revert(): void { this.setDirty(false); // Handle content change event buffered this.contentChangeEventScheduler.schedule(); } - public load(): TPromise { + load(): TPromise { // Check for backups first return this.backupFileService.loadBackupResource(this.resource).then(backupResource => { @@ -185,10 +162,10 @@ export class UntitledEditorModel extends BaseTextEditorModel implements IEncodin this.configuredEncoding = this.configurationService.getValue(this.resource, 'files.encoding'); // Listen to content changes - this.toDispose.push(this.textEditorModel.onDidChangeContent(() => this.onModelContentChanged())); + this._register(this.textEditorModel.onDidChangeContent(() => this.onModelContentChanged())); // Listen to mode changes - this.toDispose.push(this.textEditorModel.onDidChangeLanguage(() => this.onConfigurationChange())); // mode change can have impact on config + this._register(this.textEditorModel.onDidChangeLanguage(() => this.onConfigurationChange())); // mode change can have impact on config return model; }); @@ -227,10 +204,4 @@ export class UntitledEditorModel extends BaseTextEditorModel implements IEncodin // Handle content change event buffered this.contentChangeEventScheduler.schedule(); } - - public dispose(): void { - super.dispose(); - - this.toDispose = dispose(this.toDispose); - } } diff --git a/src/vs/workbench/common/notifications.ts b/src/vs/workbench/common/notifications.ts index 37a912ff71d..1c03a386805 100644 --- a/src/vs/workbench/common/notifications.ts +++ b/src/vs/workbench/common/notifications.ts @@ -8,7 +8,7 @@ import { INotification, INotificationHandle, INotificationActions, INotificationProgress, NoOpNotification, Severity, NotificationMessage } from 'vs/platform/notification/common/notification'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { Event, Emitter, once } from 'vs/base/common/event'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; import { isPromiseCanceledError, isErrorWithActions } from 'vs/base/common/errors'; export interface INotificationsModel { @@ -44,7 +44,9 @@ export interface INotificationChangeEvent { } export class NotificationHandle implements INotificationHandle { + private readonly _onDidClose: Emitter = new Emitter(); + get onDidClose(): Event { return this._onDidClose.event; } constructor(private item: INotificationViewItem, private closeItem: (item: INotificationViewItem) => void) { this.registerListeners(); @@ -57,58 +59,42 @@ export class NotificationHandle implements INotificationHandle { }); } - public get onDidClose(): Event { - return this._onDidClose.event; - } - - public get progress(): INotificationProgress { + get progress(): INotificationProgress { return this.item.progress; } - public updateSeverity(severity: Severity): void { + updateSeverity(severity: Severity): void { this.item.updateSeverity(severity); } - public updateMessage(message: NotificationMessage): void { + updateMessage(message: NotificationMessage): void { this.item.updateMessage(message); } - public updateActions(actions?: INotificationActions): void { + updateActions(actions?: INotificationActions): void { this.item.updateActions(actions); } - public close(): void { + close(): void { this.closeItem(this.item); this._onDidClose.dispose(); } } -export class NotificationsModel implements INotificationsModel { +export class NotificationsModel extends Disposable implements INotificationsModel { private static NO_OP_NOTIFICATION = new NoOpNotification(); - private _notifications: INotificationViewItem[]; + private readonly _onDidNotificationChange: Emitter = this._register(new Emitter()); + get onDidNotificationChange(): Event { return this._onDidNotificationChange.event; } - private readonly _onDidNotificationChange: Emitter; - private toDispose: IDisposable[]; + private _notifications: INotificationViewItem[] = []; - constructor() { - this._notifications = []; - this.toDispose = []; - - this._onDidNotificationChange = new Emitter(); - this.toDispose.push(this._onDidNotificationChange); - } - - public get notifications(): INotificationViewItem[] { + get notifications(): INotificationViewItem[] { return this._notifications; } - public get onDidNotificationChange(): Event { - return this._onDidNotificationChange.event; - } - - public notify(notification: INotification): INotificationHandle { + notify(notification: INotification): INotificationHandle { const item = this.createViewItem(notification); if (!item) { return NotificationsModel.NO_OP_NOTIFICATION; // return early if this is a no-op @@ -187,10 +173,6 @@ export class NotificationsModel implements INotificationsModel { return item; } - - public dispose(): void { - this.toDispose = dispose(this.toDispose); - } } export interface INotificationViewItem { @@ -250,29 +232,23 @@ export interface INotificationViewItemProgress extends INotificationProgress { dispose(): void; } -export class NotificationViewItemProgress implements INotificationViewItemProgress { +export class NotificationViewItemProgress extends Disposable implements INotificationViewItemProgress { private _state: INotificationViewItemProgressState; - private readonly _onDidChange: Emitter; - private toDispose: IDisposable[]; + private readonly _onDidChange: Emitter = this._register(new Emitter()); + get onDidChange(): Event { return this._onDidChange.event; } constructor() { - this.toDispose = []; - this._state = Object.create(null); + super(); - this._onDidChange = new Emitter(); - this.toDispose.push(this._onDidChange); + this._state = Object.create(null); } - public get state(): INotificationViewItemProgressState { + get state(): INotificationViewItemProgressState { return this._state; } - public get onDidChange(): Event { - return this._onDidChange.event; - } - - public infinite(): void { + infinite(): void { if (this._state.infinite) { return; } @@ -286,7 +262,7 @@ export class NotificationViewItemProgress implements INotificationViewItemProgre this._onDidChange.fire(); } - public done(): void { + done(): void { if (this._state.done) { return; } @@ -300,7 +276,7 @@ export class NotificationViewItemProgress implements INotificationViewItemProgre this._onDidChange.fire(); } - public total(value: number): void { + total(value: number): void { if (this._state.total === value) { return; } @@ -313,7 +289,7 @@ export class NotificationViewItemProgress implements INotificationViewItemProgre this._onDidChange.fire(); } - public worked(value: number): void { + worked(value: number): void { if (typeof this._state.worked === 'number') { this._state.worked += value; } else { @@ -325,10 +301,6 @@ export class NotificationViewItemProgress implements INotificationViewItemProgre this._onDidChange.fire(); } - - public dispose(): void { - this.toDispose = dispose(this.toDispose); - } } export interface IMessageLink { @@ -345,7 +317,7 @@ export interface INotificationMessage { links: IMessageLink[]; } -export class NotificationViewItem implements INotificationViewItem { +export class NotificationViewItem extends Disposable implements INotificationViewItem { private static MAX_MESSAGE_LENGTH = 1000; @@ -354,16 +326,20 @@ export class NotificationViewItem implements INotificationViewItem { private static LINK_REGEX = /\[([^\]]+)\]\((https?:\/\/[^\)\s]+)\)/gi; private _expanded: boolean; - private toDispose: IDisposable[]; private _actions: INotificationActions; private _progress: NotificationViewItemProgress; - private readonly _onDidExpansionChange: Emitter; - private readonly _onDidClose: Emitter; - private readonly _onDidLabelChange: Emitter; + private readonly _onDidExpansionChange: Emitter = this._register(new Emitter()); + get onDidExpansionChange(): Event { return this._onDidExpansionChange.event; } - public static create(notification: INotification): INotificationViewItem { + private readonly _onDidClose: Emitter = this._register(new Emitter()); + get onDidClose(): Event { return this._onDidClose.event; } + + private readonly _onDidLabelChange: Emitter = this._register(new Emitter()); + get onDidLabelChange(): Event { return this._onDidLabelChange.event; } + + static create(notification: INotification): INotificationViewItem { if (!notification || !notification.message || isPromiseCanceledError(notification.message)) { return null; // we need a message to show } @@ -426,18 +402,9 @@ export class NotificationViewItem implements INotificationViewItem { } private constructor(private _severity: Severity, private _message: INotificationMessage, private _source: string, actions?: INotificationActions) { - this.toDispose = []; + super(); this.setActions(actions); - - this._onDidExpansionChange = new Emitter(); - this.toDispose.push(this._onDidExpansionChange); - - this._onDidLabelChange = new Emitter(); - this.toDispose.push(this._onDidLabelChange); - - this._onDidClose = new Emitter(); - this.toDispose.push(this._onDidClose); } private setActions(actions: INotificationActions): void { @@ -457,62 +424,49 @@ export class NotificationViewItem implements INotificationViewItem { this._expanded = actions.primary.length > 0; } - public get onDidExpansionChange(): Event { - return this._onDidExpansionChange.event; - } - - public get onDidLabelChange(): Event { - return this._onDidLabelChange.event; - } - - public get onDidClose(): Event { - return this._onDidClose.event; - } - - public get canCollapse(): boolean { + get canCollapse(): boolean { return this._actions.primary.length === 0; } - public get expanded(): boolean { + get expanded(): boolean { return this._expanded; } - public get severity(): Severity { + get severity(): Severity { return this._severity; } - public hasProgress(): boolean { + hasProgress(): boolean { return !!this._progress; } - public get progress(): INotificationViewItemProgress { + get progress(): INotificationViewItemProgress { if (!this._progress) { - this._progress = new NotificationViewItemProgress(); - this.toDispose.push(this._progress); - this.toDispose.push(this._progress.onDidChange(() => this._onDidLabelChange.fire({ kind: NotificationViewItemLabelKind.PROGRESS }))); + this._progress = this._register(new NotificationViewItemProgress()); + this._register(this._progress.onDidChange(() => this._onDidLabelChange.fire({ kind: NotificationViewItemLabelKind.PROGRESS }))); } return this._progress; } - public get message(): INotificationMessage { + get message(): INotificationMessage { return this._message; } - public get source(): string { + get source(): string { return this._source; } - public get actions(): INotificationActions { + get actions(): INotificationActions { return this._actions; } - public updateSeverity(severity: Severity): void { + updateSeverity(severity: Severity): void { this._severity = severity; this._onDidLabelChange.fire({ kind: NotificationViewItemLabelKind.SEVERITY }); } - public updateMessage(input: NotificationMessage): void { + updateMessage(input: NotificationMessage): void { const message = NotificationViewItem.parseNotificationMessage(input); if (!message) { return; @@ -522,13 +476,13 @@ export class NotificationViewItem implements INotificationViewItem { this._onDidLabelChange.fire({ kind: NotificationViewItemLabelKind.MESSAGE }); } - public updateActions(actions?: INotificationActions): void { + updateActions(actions?: INotificationActions): void { this.setActions(actions); this._onDidLabelChange.fire({ kind: NotificationViewItemLabelKind.ACTIONS }); } - public expand(): void { + expand(): void { if (this._expanded || !this.canCollapse) { return; } @@ -537,7 +491,7 @@ export class NotificationViewItem implements INotificationViewItem { this._onDidExpansionChange.fire(); } - public collapse(skipEvents?: boolean): void { + collapse(skipEvents?: boolean): void { if (!this._expanded || !this.canCollapse) { return; } @@ -549,7 +503,7 @@ export class NotificationViewItem implements INotificationViewItem { } } - public toggle(): void { + toggle(): void { if (this._expanded) { this.collapse(); } else { @@ -557,13 +511,13 @@ export class NotificationViewItem implements INotificationViewItem { } } - public close(): void { + close(): void { this._onDidClose.fire(); - this.toDispose = dispose(this.toDispose); + this.dispose(); } - public equals(other: INotificationViewItem): boolean { + equals(other: INotificationViewItem): boolean { if (this.hasProgress() || other.hasProgress()) { return false; } diff --git a/src/vs/workbench/common/resources.ts b/src/vs/workbench/common/resources.ts index 4809497f2a8..1801c5ad38c 100644 --- a/src/vs/workbench/common/resources.ts +++ b/src/vs/workbench/common/resources.ts @@ -63,7 +63,7 @@ export class ResourceContextKey implements IContextKey { this._isFile.reset(); } - public get(): URI { + get(): URI { return this._resourceKey.get(); } } diff --git a/src/vs/workbench/common/theme.ts b/src/vs/workbench/common/theme.ts index 4e92beb9202..cb1b5e23623 100644 --- a/src/vs/workbench/common/theme.ts +++ b/src/vs/workbench/common/theme.ts @@ -5,7 +5,7 @@ import * as nls from 'vs/nls'; import { registerColor, editorBackground, contrastBorder, transparent, editorWidgetBackground, textLinkForeground, lighten, darken, focusBorder } from 'vs/platform/theme/common/colorRegistry'; -import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; import { IThemeService, ITheme } from 'vs/platform/theme/common/themeService'; import { Color } from 'vs/base/common/color'; @@ -455,10 +455,6 @@ export class Themable extends Disposable { this._register(this.themeService.onThemeChange(theme => this.onThemeChange(theme))); } - protected get toUnbind(): IDisposable[] { - return this._toDispose; - } - protected onThemeChange(theme: ITheme): void { this.theme = theme; diff --git a/src/vs/workbench/common/views.ts b/src/vs/workbench/common/views.ts index 2918f2ec44e..ba637549b16 100644 --- a/src/vs/workbench/common/views.ts +++ b/src/vs/workbench/common/views.ts @@ -96,7 +96,7 @@ export interface IViewDescriptor { readonly container: ViewContainer; - // TODO do we really need this?! + // TODO@Sandeep do we really need this?! readonly ctor: any; readonly when?: ContextKeyExpr; diff --git a/src/vs/workbench/electron-browser/actions.ts b/src/vs/workbench/electron-browser/actions.ts index 4a2da932930..c6fb39e0bc0 100644 --- a/src/vs/workbench/electron-browser/actions.ts +++ b/src/vs/workbench/electron-browser/actions.ts @@ -55,14 +55,14 @@ import { INotificationService } from 'vs/platform/notification/common/notificati export class CloseCurrentWindowAction extends Action { - public static readonly ID = 'workbench.action.closeWindow'; - public static readonly LABEL = nls.localize('closeWindow', "Close Window"); + static readonly ID = 'workbench.action.closeWindow'; + static readonly LABEL = nls.localize('closeWindow', "Close Window"); constructor(id: string, label: string, @IWindowService private windowService: IWindowService) { super(id, label); } - public run(): TPromise { + run(): TPromise { this.windowService.closeWindow(); return TPromise.as(true); @@ -142,7 +142,7 @@ export class ToggleMenuBarAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { let currentVisibilityValue = this.configurationService.getValue(ToggleMenuBarAction.menuBarVisibilityKey); if (typeof currentVisibilityValue !== 'string') { currentVisibilityValue = 'default'; @@ -170,7 +170,7 @@ export class ToggleDevToolsAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { return this.windowsService.toggleDevTools(); } } @@ -204,8 +204,8 @@ export abstract class BaseZoomAction extends Action { export class ZoomInAction extends BaseZoomAction { - public static readonly ID = 'workbench.action.zoomIn'; - public static readonly LABEL = nls.localize('zoomIn', "Zoom In"); + static readonly ID = 'workbench.action.zoomIn'; + static readonly LABEL = nls.localize('zoomIn', "Zoom In"); constructor( id: string, @@ -215,7 +215,7 @@ export class ZoomInAction extends BaseZoomAction { super(id, label, configurationService); } - public run(): TPromise { + run(): TPromise { this.setConfiguredZoomLevel(webFrame.getZoomLevel() + 1); return TPromise.as(true); @@ -224,8 +224,8 @@ export class ZoomInAction extends BaseZoomAction { export class ZoomOutAction extends BaseZoomAction { - public static readonly ID = 'workbench.action.zoomOut'; - public static readonly LABEL = nls.localize('zoomOut', "Zoom Out"); + static readonly ID = 'workbench.action.zoomOut'; + static readonly LABEL = nls.localize('zoomOut', "Zoom Out"); constructor( id: string, @@ -235,7 +235,7 @@ export class ZoomOutAction extends BaseZoomAction { super(id, label, configurationService); } - public run(): TPromise { + run(): TPromise { this.setConfiguredZoomLevel(webFrame.getZoomLevel() - 1); return TPromise.as(true); @@ -244,8 +244,8 @@ export class ZoomOutAction extends BaseZoomAction { export class ZoomResetAction extends BaseZoomAction { - public static readonly ID = 'workbench.action.zoomReset'; - public static readonly LABEL = nls.localize('zoomReset', "Reset Zoom"); + static readonly ID = 'workbench.action.zoomReset'; + static readonly LABEL = nls.localize('zoomReset', "Reset Zoom"); constructor( id: string, @@ -255,7 +255,7 @@ export class ZoomResetAction extends BaseZoomAction { super(id, label, configurationService); } - public run(): TPromise { + run(): TPromise { this.setConfiguredZoomLevel(0); return TPromise.as(true); @@ -288,8 +288,8 @@ interface ILoaderEvent { export class ShowStartupPerformance extends Action { - public static readonly ID = 'workbench.action.appPerf'; - public static readonly LABEL = nls.localize('appPerf', "Startup Performance"); + static readonly ID = 'workbench.action.appPerf'; + static readonly LABEL = nls.localize('appPerf', "Startup Performance"); constructor( id: string, @@ -302,7 +302,7 @@ export class ShowStartupPerformance extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { // Show dev tools this.windowService.openDevTools(); @@ -444,10 +444,10 @@ export class ShowStartupPerformance extends Action { class Tick { - public readonly duration: number; - public readonly detail: string; + readonly duration: number; + readonly detail: string; - constructor(public readonly start: ILoaderEvent, public readonly end: ILoaderEvent) { + constructor(private readonly start: ILoaderEvent, private readonly end: ILoaderEvent) { console.assert(start.detail === end.detail); this.duration = this.end.timestamp - this.start.timestamp; @@ -591,7 +591,7 @@ export abstract class BaseSwitchWindow extends Action { protected abstract isQuickNavigate(): boolean; - public run(): TPromise { + run(): TPromise { const currentWindowId = this.windowService.getCurrentWindowId(); return this.windowsService.getWindows().then(windows => { @@ -621,7 +621,7 @@ export abstract class BaseSwitchWindow extends Action { }); } - public dispose(): void { + dispose(): void { super.dispose(); this.closeWindowAction.dispose(); @@ -630,8 +630,8 @@ export abstract class BaseSwitchWindow extends Action { class CloseWindowAction extends Action implements IPickOpenAction { - public static readonly ID = 'workbench.action.closeWindow'; - public static readonly LABEL = nls.localize('close', "Close Window"); + static readonly ID = 'workbench.action.closeWindow'; + static readonly LABEL = nls.localize('close', "Close Window"); constructor( @IWindowsService private windowsService: IWindowsService @@ -641,7 +641,7 @@ class CloseWindowAction extends Action implements IPickOpenAction { this.class = 'action-remove-from-recently-opened'; } - public run(item: IPickOpenItem): TPromise { + run(item: IPickOpenItem): TPromise { return this.windowsService.closeWindow(item.getPayload()).then(() => { item.remove(); @@ -716,7 +716,7 @@ export abstract class BaseOpenRecentAction extends Action { protected abstract isQuickNavigate(): boolean; - public run(): TPromise { + run(): TPromise { return this.windowService.getRecentlyOpened() .then(({ workspaces, files }) => this.openRecent(workspaces, files)); } @@ -774,7 +774,7 @@ export abstract class BaseOpenRecentAction extends Action { }).done(null, errors.onUnexpectedError); } - public dispose(): void { + dispose(): void { super.dispose(); this.removeAction.dispose(); @@ -783,8 +783,8 @@ export abstract class BaseOpenRecentAction extends Action { class RemoveFromRecentlyOpened extends Action implements IPickOpenAction { - public static readonly ID = 'workbench.action.removeFromRecentlyOpened'; - public static readonly LABEL = nls.localize('remove', "Remove from Recently Opened"); + static readonly ID = 'workbench.action.removeFromRecentlyOpened'; + static readonly LABEL = nls.localize('remove', "Remove from Recently Opened"); constructor( @IWindowsService private windowsService: IWindowsService @@ -794,7 +794,7 @@ class RemoveFromRecentlyOpened extends Action implements IPickOpenAction { this.class = 'action-remove-from-recently-opened'; } - public run(item: IPickOpenItem): TPromise { + run(item: IPickOpenItem): TPromise { return this.windowsService.removeFromRecentlyOpened([item.getResource().fsPath]).then(() => { item.remove(); @@ -805,8 +805,8 @@ class RemoveFromRecentlyOpened extends Action implements IPickOpenAction { export class OpenRecentAction extends BaseOpenRecentAction { - public static readonly ID = 'workbench.action.openRecent'; - public static readonly LABEL = nls.localize('openRecent', "Open Recent..."); + static readonly ID = 'workbench.action.openRecent'; + static readonly LABEL = nls.localize('openRecent', "Open Recent..."); constructor( id: string, @@ -828,8 +828,8 @@ export class OpenRecentAction extends BaseOpenRecentAction { export class QuickOpenRecentAction extends BaseOpenRecentAction { - public static readonly ID = 'workbench.action.quickOpenRecent'; - public static readonly LABEL = nls.localize('quickOpenRecent', "Quick Open Recent..."); + static readonly ID = 'workbench.action.quickOpenRecent'; + static readonly LABEL = nls.localize('quickOpenRecent', "Quick Open Recent..."); constructor( id: string, @@ -850,8 +850,8 @@ export class QuickOpenRecentAction extends BaseOpenRecentAction { } export class OpenIssueReporterAction extends Action { - public static readonly ID = 'workbench.action.openIssueReporter'; - public static readonly LABEL = nls.localize({ key: 'reportIssueInEnglish', comment: ['Translate this to "Report Issue in English" in all languages please!'] }, "Report Issue"); + static readonly ID = 'workbench.action.openIssueReporter'; + static readonly LABEL = nls.localize({ key: 'reportIssueInEnglish', comment: ['Translate this to "Report Issue in English" in all languages please!'] }, "Report Issue"); constructor( id: string, @@ -861,15 +861,15 @@ export class OpenIssueReporterAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { return this.issueService.openReporter() .then(() => true); } } export class OpenProcessExplorer extends Action { - public static readonly ID = 'workbench.action.openProcessExplorer'; - public static readonly LABEL = nls.localize('openProcessExplorer', "Open Process Explorer"); + static readonly ID = 'workbench.action.openProcessExplorer'; + static readonly LABEL = nls.localize('openProcessExplorer', "Open Process Explorer"); constructor( id: string, @@ -879,15 +879,15 @@ export class OpenProcessExplorer extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { return this.issueService.openProcessExplorer() .then(() => true); } } export class ReportPerformanceIssueUsingReporterAction extends Action { - public static readonly ID = 'workbench.action.reportPerformanceIssueUsingReporter'; - public static readonly LABEL = nls.localize('reportPerformanceIssue', "Report Performance Issue"); + static readonly ID = 'workbench.action.reportPerformanceIssueUsingReporter'; + static readonly LABEL = nls.localize('reportPerformanceIssue', "Report Performance Issue"); constructor( id: string, @@ -897,7 +897,7 @@ export class ReportPerformanceIssueUsingReporterAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { // TODO: Reporter should send timings table as well return this.issueService.openReporter({ issueType: IssueType.PerformanceIssue }) .then(() => true); @@ -907,8 +907,8 @@ export class ReportPerformanceIssueUsingReporterAction extends Action { // NOTE: This is still used when running --prof-startup, which already opens a dialog, so the reporter is not used. export class ReportPerformanceIssueAction extends Action { - public static readonly ID = 'workbench.action.reportPerformanceIssue'; - public static readonly LABEL = nls.localize('reportPerformanceIssue', "Report Performance Issue"); + static readonly ID = 'workbench.action.reportPerformanceIssue'; + static readonly LABEL = nls.localize('reportPerformanceIssue', "Report Performance Issue"); constructor( id: string, @@ -920,7 +920,7 @@ export class ReportPerformanceIssueAction extends Action { super(id, label); } - public run(appendix?: string): TPromise { + run(appendix?: string): TPromise { this.integrityService.isPure().then(res => { const issueUrl = this.generatePerformanceIssueUrl(product.reportIssueUrl, pkg.name, pkg.version, product.commit, product.date, res.isPure, appendix); @@ -1027,11 +1027,11 @@ ${appendix}` export class KeybindingsReferenceAction extends Action { - public static readonly ID = 'workbench.action.keybindingsReference'; - public static readonly LABEL = nls.localize('keybindingsReference', "Keyboard Shortcuts Reference"); + static readonly ID = 'workbench.action.keybindingsReference'; + static readonly LABEL = nls.localize('keybindingsReference', "Keyboard Shortcuts Reference"); private static readonly URL = isLinux ? product.keyboardShortcutsUrlLinux : isMacintosh ? product.keyboardShortcutsUrlMac : product.keyboardShortcutsUrlWin; - public static readonly AVAILABLE = !!KeybindingsReferenceAction.URL; + static readonly AVAILABLE = !!KeybindingsReferenceAction.URL; constructor( id: string, @@ -1040,7 +1040,7 @@ export class KeybindingsReferenceAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { window.open(KeybindingsReferenceAction.URL); return null; } @@ -1048,11 +1048,11 @@ export class KeybindingsReferenceAction extends Action { export class OpenDocumentationUrlAction extends Action { - public static readonly ID = 'workbench.action.openDocumentationUrl'; - public static readonly LABEL = nls.localize('openDocumentationUrl', "Documentation"); + static readonly ID = 'workbench.action.openDocumentationUrl'; + static readonly LABEL = nls.localize('openDocumentationUrl', "Documentation"); private static readonly URL = product.documentationUrl; - public static readonly AVAILABLE = !!OpenDocumentationUrlAction.URL; + static readonly AVAILABLE = !!OpenDocumentationUrlAction.URL; constructor( id: string, @@ -1061,7 +1061,7 @@ export class OpenDocumentationUrlAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { window.open(OpenDocumentationUrlAction.URL); return null; } @@ -1069,11 +1069,11 @@ export class OpenDocumentationUrlAction extends Action { export class OpenIntroductoryVideosUrlAction extends Action { - public static readonly ID = 'workbench.action.openIntroductoryVideosUrl'; - public static readonly LABEL = nls.localize('openIntroductoryVideosUrl', "Introductory Videos"); + static readonly ID = 'workbench.action.openIntroductoryVideosUrl'; + static readonly LABEL = nls.localize('openIntroductoryVideosUrl', "Introductory Videos"); private static readonly URL = product.introductoryVideosUrl; - public static readonly AVAILABLE = !!OpenIntroductoryVideosUrlAction.URL; + static readonly AVAILABLE = !!OpenIntroductoryVideosUrlAction.URL; constructor( id: string, @@ -1082,7 +1082,7 @@ export class OpenIntroductoryVideosUrlAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { window.open(OpenIntroductoryVideosUrlAction.URL); return null; } @@ -1090,11 +1090,11 @@ export class OpenIntroductoryVideosUrlAction extends Action { export class OpenTipsAndTricksUrlAction extends Action { - public static readonly ID = 'workbench.action.openTipsAndTricksUrl'; - public static readonly LABEL = nls.localize('openTipsAndTricksUrl', "Tips and Tricks"); + static readonly ID = 'workbench.action.openTipsAndTricksUrl'; + static readonly LABEL = nls.localize('openTipsAndTricksUrl', "Tips and Tricks"); private static readonly URL = product.tipsAndTricksUrl; - public static readonly AVAILABLE = !!OpenTipsAndTricksUrlAction.URL; + static readonly AVAILABLE = !!OpenTipsAndTricksUrlAction.URL; constructor( id: string, @@ -1103,7 +1103,7 @@ export class OpenTipsAndTricksUrlAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { window.open(OpenTipsAndTricksUrlAction.URL); return null; } @@ -1141,7 +1141,7 @@ export abstract class BaseNavigationAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { const isEditorFocus = this.partService.hasFocus(Parts.EDITOR_PART); const isPanelFocus = this.partService.hasFocus(Parts.PANEL_PART); const isSidebarFocus = this.partService.hasFocus(Parts.SIDEBAR_PART); @@ -1218,8 +1218,8 @@ export abstract class BaseNavigationAction extends Action { export class NavigateLeftAction extends BaseNavigationAction { - public static readonly ID = 'workbench.action.navigateLeft'; - public static readonly LABEL = nls.localize('navigateLeft', "Navigate to the View on the Left"); + static readonly ID = 'workbench.action.navigateLeft'; + static readonly LABEL = nls.localize('navigateLeft', "Navigate to the View on the Left"); constructor( id: string, @@ -1270,8 +1270,8 @@ export class NavigateLeftAction extends BaseNavigationAction { export class NavigateRightAction extends BaseNavigationAction { - public static readonly ID = 'workbench.action.navigateRight'; - public static readonly LABEL = nls.localize('navigateRight', "Navigate to the View on the Right"); + static readonly ID = 'workbench.action.navigateRight'; + static readonly LABEL = nls.localize('navigateRight', "Navigate to the View on the Right"); constructor( id: string, @@ -1322,8 +1322,8 @@ export class NavigateRightAction extends BaseNavigationAction { export class NavigateUpAction extends BaseNavigationAction { - public static readonly ID = 'workbench.action.navigateUp'; - public static readonly LABEL = nls.localize('navigateUp', "Navigate to the View Above"); + static readonly ID = 'workbench.action.navigateUp'; + static readonly LABEL = nls.localize('navigateUp', "Navigate to the View Above"); constructor( id: string, @@ -1351,8 +1351,8 @@ export class NavigateUpAction extends BaseNavigationAction { export class NavigateDownAction extends BaseNavigationAction { - public static readonly ID = 'workbench.action.navigateDown'; - public static readonly LABEL = nls.localize('navigateDown', "Navigate to the View Below"); + static readonly ID = 'workbench.action.navigateDown'; + static readonly LABEL = nls.localize('navigateDown', "Navigate to the View Below"); constructor( id: string, @@ -1417,8 +1417,8 @@ export abstract class BaseResizeViewAction extends Action { export class IncreaseViewSizeAction extends BaseResizeViewAction { - public static readonly ID = 'workbench.action.increaseViewSize'; - public static readonly LABEL = nls.localize('increaseViewSize', "Increase Current View Size"); + static readonly ID = 'workbench.action.increaseViewSize'; + static readonly LABEL = nls.localize('increaseViewSize', "Increase Current View Size"); constructor( id: string, @@ -1428,7 +1428,7 @@ export class IncreaseViewSizeAction extends BaseResizeViewAction { super(id, label, partService); } - public run(): TPromise { + run(): TPromise { this.resizePart(BaseResizeViewAction.RESIZE_INCREMENT); return TPromise.as(true); } @@ -1436,8 +1436,8 @@ export class IncreaseViewSizeAction extends BaseResizeViewAction { export class DecreaseViewSizeAction extends BaseResizeViewAction { - public static readonly ID = 'workbench.action.decreaseViewSize'; - public static readonly LABEL = nls.localize('decreaseViewSize', "Decrease Current View Size"); + static readonly ID = 'workbench.action.decreaseViewSize'; + static readonly LABEL = nls.localize('decreaseViewSize', "Decrease Current View Size"); constructor( id: string, @@ -1448,7 +1448,7 @@ export class DecreaseViewSizeAction extends BaseResizeViewAction { super(id, label, partService); } - public run(): TPromise { + run(): TPromise { this.resizePart(-BaseResizeViewAction.RESIZE_INCREMENT); return TPromise.as(true); } @@ -1456,8 +1456,8 @@ export class DecreaseViewSizeAction extends BaseResizeViewAction { export class ShowPreviousWindowTab extends Action { - public static readonly ID = 'workbench.action.showPreviousWindowTab'; - public static readonly LABEL = nls.localize('showPreviousTab', "Show Previous Window Tab"); + static readonly ID = 'workbench.action.showPreviousWindowTab'; + static readonly LABEL = nls.localize('showPreviousTab', "Show Previous Window Tab"); constructor( id: string, @@ -1467,15 +1467,15 @@ export class ShowPreviousWindowTab extends Action { super(ShowPreviousWindowTab.ID, ShowPreviousWindowTab.LABEL); } - public run(): TPromise { + run(): TPromise { return this.windowsService.showPreviousWindowTab().then(() => true); } } export class ShowNextWindowTab extends Action { - public static readonly ID = 'workbench.action.showNextWindowTab'; - public static readonly LABEL = nls.localize('showNextWindowTab', "Show Next Window Tab"); + static readonly ID = 'workbench.action.showNextWindowTab'; + static readonly LABEL = nls.localize('showNextWindowTab', "Show Next Window Tab"); constructor( id: string, @@ -1485,15 +1485,15 @@ export class ShowNextWindowTab extends Action { super(ShowNextWindowTab.ID, ShowNextWindowTab.LABEL); } - public run(): TPromise { + run(): TPromise { return this.windowsService.showNextWindowTab().then(() => true); } } export class MoveWindowTabToNewWindow extends Action { - public static readonly ID = 'workbench.action.moveWindowTabToNewWindow'; - public static readonly LABEL = nls.localize('moveWindowTabToNewWindow', "Move Window Tab to New Window"); + static readonly ID = 'workbench.action.moveWindowTabToNewWindow'; + static readonly LABEL = nls.localize('moveWindowTabToNewWindow', "Move Window Tab to New Window"); constructor( id: string, @@ -1503,15 +1503,15 @@ export class MoveWindowTabToNewWindow extends Action { super(MoveWindowTabToNewWindow.ID, MoveWindowTabToNewWindow.LABEL); } - public run(): TPromise { + run(): TPromise { return this.windowsService.moveWindowTabToNewWindow().then(() => true); } } export class MergeAllWindowTabs extends Action { - public static readonly ID = 'workbench.action.mergeAllWindowTabs'; - public static readonly LABEL = nls.localize('mergeAllWindowTabs', "Merge All Windows"); + static readonly ID = 'workbench.action.mergeAllWindowTabs'; + static readonly LABEL = nls.localize('mergeAllWindowTabs', "Merge All Windows"); constructor( id: string, @@ -1521,15 +1521,15 @@ export class MergeAllWindowTabs extends Action { super(MergeAllWindowTabs.ID, MergeAllWindowTabs.LABEL); } - public run(): TPromise { + run(): TPromise { return this.windowsService.mergeAllWindowTabs().then(() => true); } } export class ToggleWindowTabsBar extends Action { - public static readonly ID = 'workbench.action.toggleWindowTabsBar'; - public static readonly LABEL = nls.localize('toggleWindowTabsBar', "Toggle Window Tabs Bar"); + static readonly ID = 'workbench.action.toggleWindowTabsBar'; + static readonly LABEL = nls.localize('toggleWindowTabsBar', "Toggle Window Tabs Bar"); constructor( id: string, @@ -1539,15 +1539,15 @@ export class ToggleWindowTabsBar extends Action { super(ToggleWindowTabsBar.ID, ToggleWindowTabsBar.LABEL); } - public run(): TPromise { + run(): TPromise { return this.windowsService.toggleWindowTabsBar().then(() => true); } } export class OpenTwitterUrlAction extends Action { - public static readonly ID = 'workbench.action.openTwitterUrl'; - public static LABEL = nls.localize('openTwitterUrl', "Join us on Twitter", product.applicationName); + static readonly ID = 'workbench.action.openTwitterUrl'; + static LABEL = nls.localize('openTwitterUrl', "Join us on Twitter", product.applicationName); constructor( id: string, @@ -1567,8 +1567,8 @@ export class OpenTwitterUrlAction extends Action { export class OpenRequestFeatureUrlAction extends Action { - public static readonly ID = 'workbench.action.openRequestFeatureUrl'; - public static LABEL = nls.localize('openUserVoiceUrl', "Search Feature Requests"); + static readonly ID = 'workbench.action.openRequestFeatureUrl'; + static LABEL = nls.localize('openUserVoiceUrl', "Search Feature Requests"); constructor( id: string, @@ -1588,8 +1588,8 @@ export class OpenRequestFeatureUrlAction extends Action { export class OpenLicenseUrlAction extends Action { - public static readonly ID = 'workbench.action.openLicenseUrl'; - public static LABEL = nls.localize('openLicenseUrl', "View License"); + static readonly ID = 'workbench.action.openLicenseUrl'; + static LABEL = nls.localize('openLicenseUrl', "View License"); constructor( id: string, @@ -1615,8 +1615,8 @@ export class OpenLicenseUrlAction extends Action { export class OpenPrivacyStatementUrlAction extends Action { - public static readonly ID = 'workbench.action.openPrivacyStatementUrl'; - public static LABEL = nls.localize('openPrivacyStatement', "Privacy Statement"); + static readonly ID = 'workbench.action.openPrivacyStatementUrl'; + static LABEL = nls.localize('openPrivacyStatement', "Privacy Statement"); constructor( id: string, @@ -1642,8 +1642,8 @@ export class OpenPrivacyStatementUrlAction extends Action { export class ShowAccessibilityOptionsAction extends Action { - public static readonly ID = 'workbench.action.showAccessibilityOptions'; - public static LABEL = nls.localize('accessibilityOptions', "Accessibility Options"); + static readonly ID = 'workbench.action.showAccessibilityOptions'; + static LABEL = nls.localize('accessibilityOptions', "Accessibility Options"); constructor( id: string, @@ -1661,8 +1661,8 @@ export class ShowAccessibilityOptionsAction extends Action { export class ShowAboutDialogAction extends Action { - public static readonly ID = 'workbench.action.showAboutDialog'; - public static LABEL = nls.localize('about', "About {0}", product.applicationName); + static readonly ID = 'workbench.action.showAboutDialog'; + static LABEL = nls.localize('about', "About {0}", product.applicationName); constructor( id: string, @@ -1679,8 +1679,8 @@ export class ShowAboutDialogAction extends Action { export class InspectContextKeysAction extends Action { - public static readonly ID = 'workbench.action.inspectContextKeys'; - public static LABEL = nls.localize('inspect context keys', "Inspect Context Keys"); + static readonly ID = 'workbench.action.inspectContextKeys'; + static LABEL = nls.localize('inspect context keys', "Inspect Context Keys"); constructor( id: string, diff --git a/src/vs/workbench/electron-browser/main.contribution.ts b/src/vs/workbench/electron-browser/main.contribution.ts index 7d34e253ca3..6518e436b43 100644 --- a/src/vs/workbench/electron-browser/main.contribution.ts +++ b/src/vs/workbench/electron-browser/main.contribution.ts @@ -22,9 +22,6 @@ import { inQuickOpenContext, getQuickNavigateHandler } from 'vs/workbench/browse import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; -import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; -import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; -import { HistoryNavigationKeybindingsChangedContribution } from 'vs/workbench/electron-browser/removedKeybindingsContribution'; // Contribute Commands registerCommands(); @@ -70,16 +67,10 @@ if (OpenTipsAndTricksUrlAction.AVAILABLE) { } workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(OpenTwitterUrlAction, OpenTwitterUrlAction.ID, OpenTwitterUrlAction.LABEL), 'Help: Join us on Twitter', helpCategory); - -workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(OpenRequestFeatureUrlAction, OpenRequestFeatureUrlAction.ID, - OpenRequestFeatureUrlAction.LABEL), 'Help: Search Feature Requests', helpCategory); - +workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(OpenRequestFeatureUrlAction, OpenRequestFeatureUrlAction.ID, OpenRequestFeatureUrlAction.LABEL), 'Help: Search Feature Requests', helpCategory); workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(OpenLicenseUrlAction, OpenLicenseUrlAction.ID, OpenLicenseUrlAction.LABEL), 'Help: View License', helpCategory); - workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(OpenPrivacyStatementUrlAction, OpenPrivacyStatementUrlAction.ID, OpenPrivacyStatementUrlAction.LABEL), 'Help: Privacy Statement', helpCategory); - workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ShowAccessibilityOptionsAction, ShowAccessibilityOptionsAction.ID, ShowAccessibilityOptionsAction.LABEL), 'Help: Accessibility Options', helpCategory); - workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ShowAboutDialogAction, ShowAboutDialogAction.ID, ShowAboutDialogAction.LABEL), 'Help: About', helpCategory); workbenchActionsRegistry.registerWorkbenchAction( @@ -524,5 +515,3 @@ configurationRegistry.registerConfiguration({ } } }); - -Registry.as(WorkbenchExtensions.Workbench).registerWorkbenchContribution(HistoryNavigationKeybindingsChangedContribution, LifecyclePhase.Eventually); diff --git a/src/vs/workbench/electron-browser/resources.ts b/src/vs/workbench/electron-browser/resources.ts index fce07d4794d..0c204a94463 100644 --- a/src/vs/workbench/electron-browser/resources.ts +++ b/src/vs/workbench/electron-browser/resources.ts @@ -8,19 +8,20 @@ import URI from 'vs/base/common/uri'; import * as objects from 'vs/base/common/objects'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; import { Event, Emitter } from 'vs/base/common/event'; import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration'; import { ParsedExpression, IExpression, parse } from 'vs/base/common/glob'; import { relative } from 'path'; import { normalize } from 'vs/base/common/paths'; -export class ResourceGlobMatcher { +export class ResourceGlobMatcher extends Disposable { private static readonly NO_ROOT: string = null; - private readonly _onExpressionChange: Emitter; - private toUnbind: IDisposable[]; + private readonly _onExpressionChange: Emitter = this._register(new Emitter()); + get onExpressionChange(): Event { return this._onExpressionChange.event; } + private mapRootToParsedExpression: Map; private mapRootToExpressionConfig: Map; @@ -30,30 +31,24 @@ export class ResourceGlobMatcher { @IWorkspaceContextService private contextService: IWorkspaceContextService, @IConfigurationService private configurationService: IConfigurationService ) { - this.toUnbind = []; + super(); this.mapRootToParsedExpression = new Map(); this.mapRootToExpressionConfig = new Map(); - this._onExpressionChange = new Emitter(); - this.toUnbind.push(this._onExpressionChange); - this.updateExcludes(false); this.registerListeners(); } - public get onExpressionChange(): Event { - return this._onExpressionChange.event; - } - private registerListeners(): void { - this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => { + this._register(this.configurationService.onDidChangeConfiguration(e => { if (this.shouldUpdate(e)) { this.updateExcludes(true); } })); - this.toUnbind.push(this.contextService.onDidChangeWorkspaceFolders(() => this.updateExcludes(true))); + + this._register(this.contextService.onDidChangeWorkspaceFolders(() => this.updateExcludes(true))); } private updateExcludes(fromEvent: boolean): void { @@ -98,7 +93,7 @@ export class ResourceGlobMatcher { } } - public matches(resource: URI): boolean { + matches(resource: URI): boolean { const folder = this.contextService.getWorkspaceFolder(resource); let expressionForRoot: ParsedExpression; @@ -121,8 +116,4 @@ export class ResourceGlobMatcher { return !!expressionForRoot(resourcePathToMatch); } - - public dispose(): void { - this.toUnbind = dispose(this.toUnbind); - } } \ No newline at end of file diff --git a/src/vs/workbench/electron-browser/shell.ts b/src/vs/workbench/electron-browser/shell.ts index 356a0e3a2c5..830a3843c3e 100644 --- a/src/vs/workbench/electron-browser/shell.ts +++ b/src/vs/workbench/electron-browser/shell.ts @@ -10,7 +10,7 @@ import 'vs/css!./media/shell'; import * as platform from 'vs/base/common/platform'; import * as perf from 'vs/base/common/performance'; import * as aria from 'vs/base/browser/ui/aria/aria'; -import { dispose, IDisposable } from 'vs/base/common/lifecycle'; +import { Disposable, toDisposable } from 'vs/base/common/lifecycle'; import * as errors from 'vs/base/common/errors'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import product from 'vs/platform/node/product'; @@ -116,7 +116,7 @@ export interface ICoreServices { * The workbench shell contains the workbench with a rich header containing navigation and the activity bar. * With the Shell being the top level element in the page, it is also responsible for driving the layouting. */ -export class WorkbenchShell { +export class WorkbenchShell extends Disposable { private storageService: IStorageService; private environmentService: IEnvironmentService; private logService: ILogService; @@ -133,7 +133,6 @@ export class WorkbenchShell { private notificationService: INotificationService; private container: HTMLElement; - private toUnbind: IDisposable[]; private previousErrorValue: string; private previousErrorTime: number; private content: HTMLElement; @@ -143,6 +142,8 @@ export class WorkbenchShell { private workbench: Workbench; constructor(container: HTMLElement, coreServices: ICoreServices, mainProcessServices: ServiceCollection, private mainProcessClient: IPCClient, configuration: IWindowConfiguration) { + super(); + this.container = container; this.configuration = configuration; @@ -156,7 +157,6 @@ export class WorkbenchShell { this.mainProcessServices = mainProcessServices; - this.toUnbind = []; this.previousErrorTime = 0; } @@ -176,7 +176,7 @@ export class WorkbenchShell { this.workbench = this.createWorkbench(instantiationService, serviceCollection, parent, workbenchContainer); // Window - this.workbench.getInstantiationService().createInstance(ElectronWindow, this.container); + this.workbench.getInstantiationService().createInstance(ElectronWindow); // Handle case where workbench is not starting up properly const timeoutHandle = setTimeout(() => { @@ -211,13 +211,12 @@ export class WorkbenchShell { eventuallPhaseTimeoutHandle = void 0; this.lifecycleService.phase = LifecyclePhase.Eventually; }, 3000); - this.toUnbind.push({ - dispose: () => { - if (eventuallPhaseTimeoutHandle) { - clearTimeout(eventuallPhaseTimeoutHandle); - } + + this._register(toDisposable(() => { + if (eventuallPhaseTimeoutHandle) { + clearTimeout(eventuallPhaseTimeoutHandle); } - }); + })); // localStorage metrics (TODO@Ben remove me later) if (!this.environmentService.extensionTestsPath && this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) { @@ -331,8 +330,7 @@ export class WorkbenchShell { serviceCollection.set(IWorkspaceContextService, this.contextService); serviceCollection.set(IConfigurationService, this.configurationService); serviceCollection.set(IEnvironmentService, this.environmentService); - serviceCollection.set(ILogService, this.logService); - this.toUnbind.push(this.logService); + serviceCollection.set(ILogService, this._register(this.logService)); serviceCollection.set(ITimerService, this.timerService); serviceCollection.set(IStorageService, this.storageService); @@ -375,18 +373,14 @@ export class WorkbenchShell { piiPaths: [this.environmentService.appRoot, this.environmentService.extensionsPath] }; - const telemetryService = instantiationService.createInstance(TelemetryService, config); - this.telemetryService = telemetryService; - - const errorTelemetry = new ErrorTelemetry(telemetryService); - - this.toUnbind.push(telemetryService, errorTelemetry); + this.telemetryService = this._register(instantiationService.createInstance(TelemetryService, config)); + this._register(new ErrorTelemetry(this.telemetryService)); } else { this.telemetryService = NullTelemetryService; } serviceCollection.set(ITelemetryService, this.telemetryService); - this.toUnbind.push(configurationTelemetry(this.telemetryService, this.configurationService)); + this._register(configurationTelemetry(this.telemetryService, this.configurationService)); let crashReporterService = NullCrashReporterService; if (!this.environmentService.disableCrashReporter && product.crashReporter && product.hockeyApp) { @@ -397,7 +391,7 @@ export class WorkbenchShell { serviceCollection.set(IDialogService, instantiationService.createInstance(DialogService)); const lifecycleService = instantiationService.createInstance(LifecycleService); - this.toUnbind.push(lifecycleService.onShutdown(reason => this.dispose(reason))); + this._register(lifecycleService.onShutdown(reason => this.dispose(reason))); serviceCollection.set(ILifecycleService, lifecycleService); this.lifecycleService = lifecycleService; @@ -406,9 +400,8 @@ export class WorkbenchShell { serviceCollection.set(IExtensionManagementServerService, new SyncDescriptor(ExtensionManagementServerService, extensionManagementChannelClient)); serviceCollection.set(IExtensionManagementService, new SyncDescriptor(MulitExtensionManagementService)); - const extensionEnablementService = instantiationService.createInstance(ExtensionEnablementService); + const extensionEnablementService = this._register(instantiationService.createInstance(ExtensionEnablementService)); serviceCollection.set(IExtensionEnablementService, extensionEnablementService); - this.toUnbind.push(extensionEnablementService); serviceCollection.set(IRequestService, new SyncDescriptor(RequestService)); @@ -460,7 +453,7 @@ export class WorkbenchShell { return [instantiationService, serviceCollection]; } - public open(): void { + open(): void { // Listen on unexpected errors errors.setUnexpectedErrorHandler((error: any) => { @@ -488,14 +481,14 @@ export class WorkbenchShell { private registerListeners(): void { // Resize - this.toUnbind.push(addDisposableListener(window, EventType.RESIZE, e => { + this._register(addDisposableListener(window, EventType.RESIZE, e => { if (e.target === window) { this.layout(); } })); } - public onUnexpectedError(error: any): void { + onUnexpectedError(error: any): void { const errorMsg = toErrorMessage(error, true); if (!errorMsg) { return; @@ -528,10 +521,8 @@ export class WorkbenchShell { this.workbench.layout(); } - public dispose(reason = ShutdownReason.QUIT): void { - - // Dispose bindings - this.toUnbind = dispose(this.toUnbind); + dispose(reason = ShutdownReason.QUIT): void { + super.dispose(); // Keep font info for next startup around saveFontInfo(this.storageService); diff --git a/src/vs/workbench/electron-browser/window.ts b/src/vs/workbench/electron-browser/window.ts index 14c87e54598..ccde056f231 100644 --- a/src/vs/workbench/electron-browser/window.ts +++ b/src/vs/workbench/electron-browser/window.ts @@ -73,7 +73,6 @@ export class ElectronWindow extends Themable { private pendingFoldersToAdd: IAddFoldersRequest[]; constructor( - shellContainer: HTMLElement, @IEditorService private editorService: EditorServiceImpl, @IWindowsService private windowsService: IWindowsService, @IWindowService private windowService: IWindowService, @@ -97,8 +96,7 @@ export class ElectronWindow extends Themable { this.touchBarDisposables = []; this.pendingFoldersToAdd = []; - this.addFoldersScheduler = new RunOnceScheduler(() => this.doAddFolders(), 100); - this.toUnbind.push(this.addFoldersScheduler); + this.addFoldersScheduler = this._register(new RunOnceScheduler(() => this.doAddFolders(), 100)); this.registerListeners(); this.create(); @@ -107,7 +105,7 @@ export class ElectronWindow extends Themable { private registerListeners(): void { // React to editor input changes - this.toUnbind.push(this.editorService.onDidActiveEditorChange(() => this.updateTouchbarMenu())); + this._register(this.editorService.onDidActiveEditorChange(() => this.updateTouchbarMenu())); // prevent opening a real URL inside the shell [DOM.EventType.DRAG_OVER, DOM.EventType.DROP].forEach(event => { @@ -232,7 +230,7 @@ export class ElectronWindow extends Themable { // Zoom level changes this.updateWindowZoomLevel(); - this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => { + this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('window.zoomLevel')) { this.updateWindowZoomLevel(); } @@ -526,7 +524,7 @@ export class ElectronWindow extends Themable { this.configurationService.updateValue(ElectronWindow.AUTO_SAVE_SETTING, newAutoSaveValue, ConfigurationTarget.USER); } - public dispose(): void { + dispose(): void { this.touchBarDisposables = dispose(this.touchBarDisposables); super.dispose(); diff --git a/src/vs/workbench/electron-browser/workbench.ts b/src/vs/workbench/electron-browser/workbench.ts index ac68914351a..6c3e8ab23bd 100644 --- a/src/vs/workbench/electron-browser/workbench.ts +++ b/src/vs/workbench/electron-browser/workbench.ts @@ -233,7 +233,7 @@ export class Workbench extends Disposable implements IPartService { private inZenMode: IContextKey; private sideBarVisibleContext: IContextKey; - private closeEmptyWindowScheduler: RunOnceScheduler = new RunOnceScheduler(() => this.onAllEditorsClosed(), 50); + private closeEmptyWindowScheduler: RunOnceScheduler = this._register(new RunOnceScheduler(() => this.onAllEditorsClosed(), 50)); constructor( private parent: HTMLElement, diff --git a/src/vs/workbench/node/extensionHostMain.ts b/src/vs/workbench/node/extensionHostMain.ts index 4008bae8e48..4aa8811e6f3 100644 --- a/src/vs/workbench/node/extensionHostMain.ts +++ b/src/vs/workbench/node/extensionHostMain.ts @@ -41,8 +41,8 @@ function patchProcess(allowExit: boolean) { console.warn(err.stack); }; } + export function exit(code?: number) { - // TODO@electron // See https://github.com/Microsoft/vscode/issues/32990 // calling process.exit() does not exit the process when the process is being debugged // It waits for the debugger to disconnect, but in our version, the debugger does not @@ -126,6 +126,7 @@ export class ExtensionHostMain { return `${error.name || 'Error'}: ${error.message || ''}${stackTraceMessage}`; }; }); + const mainThreadExtensions = rpcProtocol.getProxy(MainContext.MainThreadExtensionService); const mainThreadErrors = rpcProtocol.getProxy(MainContext.MainThreadErrors); errors.setUnexpectedErrorHandler(err => { @@ -137,14 +138,9 @@ export class ExtensionHostMain { mainThreadErrors.$onUnexpectedError(data); } }); - - // Configure the watchdog to kill our process if the JS event loop is unresponsive for more than 10s - // if (!initData.environment.isExtensionDevelopmentDebug) { - // watchdog.start(10000); - // } } - public start(): TPromise { + start(): TPromise { return this._extensionService.onExtensionAPIReady() .then(() => this.handleEagerExtensions()) .then(() => this.handleExtensionTests()) @@ -153,7 +149,7 @@ export class ExtensionHostMain { }); } - public terminate(): void { + terminate(): void { if (this._isTerminating) { // we are already shutting down... return; @@ -168,9 +164,9 @@ export class ExtensionHostMain { let allPromises: TPromise[] = []; try { - let allExtensions = this._extensionService.getAllExtensionDescriptions(); - let allExtensionsIds = allExtensions.map(ext => ext.id); - let activatedExtensions = allExtensionsIds.filter(id => this._extensionService.isActivated(id)); + const allExtensions = this._extensionService.getAllExtensionDescriptions(); + const allExtensionsIds = allExtensions.map(ext => ext.id); + const activatedExtensions = allExtensionsIds.filter(id => this._extensionService.isActivated(id)); allPromises = activatedExtensions.map((extensionId) => { return this._extensionService.deactivate(extensionId); @@ -179,7 +175,7 @@ export class ExtensionHostMain { // TODO: write to log once we have one } - let extensionsDeactivated = TPromise.join(allPromises).then(() => void 0); + const extensionsDeactivated = TPromise.join(allPromises).then(() => void 0); // Give extensions 1 second to wrap up any async dispose, then exit setTimeout(() => { @@ -192,6 +188,7 @@ export class ExtensionHostMain { this._extensionService.activateByEvent('*', true).then(null, (err) => { console.error(err); }); + return this.handleWorkspaceContainsEagerExtensions(); } @@ -208,7 +205,7 @@ export class ExtensionHostMain { } private handleWorkspaceContainsEagerExtension(desc: IExtensionDescription): TPromise { - let activationEvents = desc.activationEvents; + const activationEvents = desc.activationEvents; if (!activationEvents) { return TPromise.as(void 0); } @@ -218,7 +215,7 @@ export class ExtensionHostMain { for (let i = 0; i < activationEvents.length; i++) { if (/^workspaceContains:/.test(activationEvents[i])) { - let fileNameOrGlob = activationEvents[i].substr('workspaceContains:'.length); + const fileNameOrGlob = activationEvents[i].substr('workspaceContains:'.length); if (fileNameOrGlob.indexOf('*') >= 0 || fileNameOrGlob.indexOf('?') >= 0) { globPatterns.push(fileNameOrGlob); } else { @@ -231,15 +228,15 @@ export class ExtensionHostMain { return TPromise.as(void 0); } - let fileNamePromise = TPromise.join(fileNames.map((fileName) => this.activateIfFileName(desc.id, fileName))).then(() => { }); - let globPatternPromise = this.activateIfGlobPatterns(desc.id, globPatterns); + const fileNamePromise = TPromise.join(fileNames.map((fileName) => this.activateIfFileName(desc.id, fileName))).then(() => { }); + const globPatternPromise = this.activateIfGlobPatterns(desc.id, globPatterns); return TPromise.join([fileNamePromise, globPatternPromise]).then(() => { }); } private async activateIfFileName(extensionId: string, fileName: string): TPromise { - // find exact path + // find exact path for (const { uri } of this._workspace.folders) { if (await pfs.exists(join(URI.revive(uri).fsPath, fileName))) { // the file was found @@ -265,7 +262,7 @@ export class ExtensionHostMain { this._diskSearch = new DiskSearch(false, 1000); } - let includes: glob.IExpression = {}; + const includes: glob.IExpression = {}; globPatterns.forEach((globPattern) => { includes[globPattern] = true; }); @@ -284,7 +281,7 @@ export class ExtensionHostMain { ignoreSymlinks: !followSymlinks }; - let result = await this._diskSearch.search(query); + const result = await this._diskSearch.search(query); if (result.limitHit) { // a file was found matching one of the glob patterns return ( diff --git a/src/vs/workbench/node/extensionHostProcess.ts b/src/vs/workbench/node/extensionHostProcess.ts index fb05c3f3c2e..9035333b54f 100644 --- a/src/vs/workbench/node/extensionHostProcess.ts +++ b/src/vs/workbench/node/extensionHostProcess.ts @@ -13,7 +13,7 @@ import { Protocol } from 'vs/base/parts/ipc/node/ipc.net'; import { createConnection } from 'net'; import { Event, filterEvent } from 'vs/base/common/event'; -// TODO@ben: with Electron 2.x and node.js 8.x the "natives" module +// With Electron 2.x and node.js 8.x the "natives" module // can cause a native crash (see https://github.com/nodejs/node/issues/19891 and // https://github.com/electron/electron/issues/10905). To prevent this from // happening we essentially blocklist this module from getting loaded in any diff --git a/src/vs/workbench/parts/backup/common/backupModelTracker.ts b/src/vs/workbench/parts/backup/common/backupModelTracker.ts index d4b296540d1..df13305cd8d 100644 --- a/src/vs/workbench/parts/backup/common/backupModelTracker.ts +++ b/src/vs/workbench/parts/backup/common/backupModelTracker.ts @@ -8,7 +8,7 @@ import Uri from 'vs/base/common/uri'; import * as errors from 'vs/base/common/errors'; import { IBackupFileService } from 'vs/workbench/services/backup/common/backup'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; import { ITextFileService, TextFileModelChangeEvent, StateChange } from 'vs/workbench/services/textfile/common/textfiles'; import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; @@ -17,12 +17,11 @@ import { IFilesConfiguration, AutoSaveConfiguration, CONTENT_CHANGE_EVENT_BUFFER const AUTO_SAVE_AFTER_DELAY_DISABLED_TIME = CONTENT_CHANGE_EVENT_BUFFER_DELAY + 500; -export class BackupModelTracker implements IWorkbenchContribution { +export class BackupModelTracker extends Disposable implements IWorkbenchContribution { - public _serviceBrand: any; + _serviceBrand: any; private configuredAutoSaveAfterDelay: boolean; - private toDispose: IDisposable[]; constructor( @IBackupFileService private backupFileService: IBackupFileService, @@ -30,7 +29,7 @@ export class BackupModelTracker implements IWorkbenchContribution { @IUntitledEditorService private untitledEditorService: IUntitledEditorService, @IConfigurationService private configurationService: IConfigurationService ) { - this.toDispose = []; + super(); this.registerListeners(); } @@ -38,16 +37,16 @@ export class BackupModelTracker implements IWorkbenchContribution { private registerListeners() { // Listen for text file model changes - this.toDispose.push(this.textFileService.models.onModelContentChanged((e) => this.onTextFileModelChanged(e))); - this.toDispose.push(this.textFileService.models.onModelSaved((e) => this.discardBackup(e.resource))); - this.toDispose.push(this.textFileService.models.onModelDisposed((e) => this.discardBackup(e))); + this._register(this.textFileService.models.onModelContentChanged((e) => this.onTextFileModelChanged(e))); + this._register(this.textFileService.models.onModelSaved((e) => this.discardBackup(e.resource))); + this._register(this.textFileService.models.onModelDisposed((e) => this.discardBackup(e))); // Listen for untitled model changes - this.toDispose.push(this.untitledEditorService.onDidChangeContent((e) => this.onUntitledModelChanged(e))); - this.toDispose.push(this.untitledEditorService.onDidDisposeModel((e) => this.discardBackup(e))); + this._register(this.untitledEditorService.onDidChangeContent((e) => this.onUntitledModelChanged(e))); + this._register(this.untitledEditorService.onDidDisposeModel((e) => this.discardBackup(e))); // Listen to config changes - this.toDispose.push(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChange(this.configurationService.getValue()))); + this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChange(this.configurationService.getValue()))); } private onConfigurationChange(configuration: IFilesConfiguration): void { @@ -85,8 +84,4 @@ export class BackupModelTracker implements IWorkbenchContribution { private discardBackup(resource: Uri): void { this.backupFileService.discardResourceBackup(resource).done(null, errors.onUnexpectedError); } - - public dispose(): void { - this.toDispose = dispose(this.toDispose); - } } \ No newline at end of file diff --git a/src/vs/workbench/parts/comments/electron-browser/commentsPanel.ts b/src/vs/workbench/parts/comments/electron-browser/commentsPanel.ts index a9786dfabd0..5e10e22fbb2 100644 --- a/src/vs/workbench/parts/comments/electron-browser/commentsPanel.ts +++ b/src/vs/workbench/parts/comments/electron-browser/commentsPanel.ts @@ -73,7 +73,7 @@ export class CommentsPanel extends Panel { public getActions(): IAction[] { if (!this.collapseAllAction) { this.collapseAllAction = this.instantiationService.createInstance(CollapseAllAction, this.tree, this.commentsModel.hasCommentThreads()); - this.toUnbind.push(this.collapseAllAction); + this._register(this.collapseAllAction); } return [this.collapseAllAction]; diff --git a/src/vs/workbench/parts/debug/browser/debugActionsWidget.ts b/src/vs/workbench/parts/debug/browser/debugActionsWidget.ts index 74d89fd4687..545751a774d 100644 --- a/src/vs/workbench/parts/debug/browser/debugActionsWidget.ts +++ b/src/vs/workbench/parts/debug/browser/debugActionsWidget.ts @@ -80,7 +80,7 @@ export class DebugActionsWidget extends Themable implements IWorkbenchContributi this.$el.append(actionBarContainter); this.activeActions = []; - this.actionBar = new ActionBar(actionBarContainter.getHTMLElement(), { + this.actionBar = this._register(new ActionBar(actionBarContainter.getHTMLElement(), { orientation: ActionsOrientation.HORIZONTAL, actionItemProvider: (action: IAction) => { if (action.id === FocusSessionAction.ID) { @@ -89,27 +89,26 @@ export class DebugActionsWidget extends Themable implements IWorkbenchContributi return null; } - }); + })); - this.updateScheduler = new RunOnceScheduler(() => { + this.updateScheduler = this._register(new RunOnceScheduler(() => { const state = this.debugService.state; const toolBarLocation = this.configurationService.getValue('debug').toolBarLocation; if (state === State.Inactive || toolBarLocation === 'docked' || toolBarLocation === 'hidden') { return this.hide(); } - const actions = DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService); + const actions = DebugActionsWidget.getActions(this.allActions, this.toDispose, this.debugService, this.keybindingService, this.instantiationService); if (!arrays.equals(actions, this.activeActions, (first, second) => first.id === second.id)) { this.actionBar.clear(); this.actionBar.push(actions, { icon: true, label: false }); this.activeActions = actions; } this.show(); - }, 20); + }, 20)); this.updateStyles(); - this.toUnbind.push(this.actionBar); this.registerListeners(); this.hide(); @@ -117,10 +116,10 @@ export class DebugActionsWidget extends Themable implements IWorkbenchContributi } private registerListeners(): void { - this.toUnbind.push(this.debugService.onDidChangeState(() => this.updateScheduler.schedule())); - this.toUnbind.push(this.debugService.getViewModel().onDidFocusSession(() => this.updateScheduler.schedule())); - this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => this.onDidConfigurationChange(e))); - this.toUnbind.push(this.actionBar.actionRunner.onDidRun((e: IRunEvent) => { + this._register(this.debugService.onDidChangeState(() => this.updateScheduler.schedule())); + this._register(this.debugService.getViewModel().onDidFocusSession(() => this.updateScheduler.schedule())); + this._register(this.configurationService.onDidChangeConfiguration(e => this.onDidConfigurationChange(e))); + this._register(this.actionBar.actionRunner.onDidRun((e: IRunEvent) => { // check for error if (e.error && !errors.isPromiseCanceledError(e.error)) { this.notificationService.error(e.error); @@ -137,7 +136,7 @@ export class DebugActionsWidget extends Themable implements IWorkbenchContributi this.telemetryService.publicLog('workbenchActionExecuted', { id: e.action.id, from: 'debugActionsWidget' }); } })); - $(window).on(dom.EventType.RESIZE, () => this.setCoordinates(), this.toUnbind); + $(window).on(dom.EventType.RESIZE, () => this.setCoordinates(), this.toDispose); this.dragArea.on(dom.EventType.MOUSE_UP, (event: MouseEvent) => { const mouseClickEvent = new StandardMouseEvent(event); @@ -166,8 +165,8 @@ export class DebugActionsWidget extends Themable implements IWorkbenchContributi }); }); - this.toUnbind.push(this.partService.onTitleBarVisibilityChange(() => this.setYCoordinate())); - this.toUnbind.push(browser.onDidChangeZoomLevel(() => this.setYCoordinate())); + this._register(this.partService.onTitleBarVisibilityChange(() => this.setYCoordinate())); + this._register(browser.onDidChangeZoomLevel(() => this.setYCoordinate())); } private storePosition(): void { @@ -253,7 +252,7 @@ export class DebugActionsWidget extends Themable implements IWorkbenchContributi this.$el.hide(); } - public static getActions(allActions: AbstractDebugAction[], toUnbind: IDisposable[], debugService: IDebugService, keybindingService: IKeybindingService, instantiationService: IInstantiationService): AbstractDebugAction[] { + public static getActions(allActions: AbstractDebugAction[], toDispose: IDisposable[], debugService: IDebugService, keybindingService: IKeybindingService, instantiationService: IInstantiationService): AbstractDebugAction[] { if (allActions.length === 0) { allActions.push(new ContinueAction(ContinueAction.ID, ContinueAction.LABEL, debugService, keybindingService)); allActions.push(new PauseAction(PauseAction.ID, PauseAction.LABEL, debugService, keybindingService)); @@ -266,9 +265,7 @@ export class DebugActionsWidget extends Themable implements IWorkbenchContributi allActions.push(new StepBackAction(StepBackAction.ID, StepBackAction.LABEL, debugService, keybindingService)); allActions.push(new ReverseContinueAction(ReverseContinueAction.ID, ReverseContinueAction.LABEL, debugService, keybindingService)); allActions.push(instantiationService.createInstance(FocusSessionAction, FocusSessionAction.ID, FocusSessionAction.LABEL)); - allActions.forEach(a => { - toUnbind.push(a); - }); + allActions.forEach(a => toDispose.push(a)); } const state = debugService.state; diff --git a/src/vs/workbench/parts/debug/browser/debugStatus.ts b/src/vs/workbench/parts/debug/browser/debugStatus.ts index 755b562c84e..970cce4f2cd 100644 --- a/src/vs/workbench/parts/debug/browser/debugStatus.ts +++ b/src/vs/workbench/parts/debug/browser/debugStatus.ts @@ -6,7 +6,7 @@ import * as nls from 'vs/nls'; import * as dom from 'vs/base/browser/dom'; import * as errors from 'vs/base/common/errors'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { IDisposable } from 'vs/base/common/lifecycle'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IStatusbarItem } from 'vs/workbench/browser/parts/statusbar/statusbar'; @@ -18,7 +18,6 @@ import { STATUS_BAR_DEBUGGING_FOREGROUND, isStatusbarInDebugMode } from 'vs/work const $ = dom.$; export class DebugStatus extends Themable implements IStatusbarItem { - private toDispose: IDisposable[]; private container: HTMLElement; private statusBarItem: HTMLElement; private label: HTMLElement; @@ -32,17 +31,16 @@ export class DebugStatus extends Themable implements IStatusbarItem { @IConfigurationService configurationService: IConfigurationService ) { super(themeService); - this.toDispose = []; - this.toDispose.push(this.debugService.getConfigurationManager().onDidSelectConfiguration(e => { + this._register(this.debugService.getConfigurationManager().onDidSelectConfiguration(e => { this.setLabel(); })); - this.toDispose.push(this.debugService.onDidChangeState(state => { + this._register(this.debugService.onDidChangeState(state => { if (state !== State.Inactive && this.showInStatusBar === 'onFirstSessionStart') { this.doRender(); } })); this.showInStatusBar = configurationService.getValue('debug').showInStatusBar; - this.toDispose.push(configurationService.onDidChangeConfiguration(e => { + this._register(configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('debug.showInStatusBar')) { this.showInStatusBar = configurationService.getValue('debug').showInStatusBar; if (this.showInStatusBar === 'always') { @@ -102,9 +100,4 @@ export class DebugStatus extends Themable implements IStatusbarItem { } } } - - public dispose(): void { - super.dispose(); - this.toDispose = dispose(this.toDispose); - } } diff --git a/src/vs/workbench/parts/debug/browser/debugViewlet.ts b/src/vs/workbench/parts/debug/browser/debugViewlet.ts index e1ea8e7a8f8..2cc3d77ddf9 100644 --- a/src/vs/workbench/parts/debug/browser/debugViewlet.ts +++ b/src/vs/workbench/parts/debug/browser/debugViewlet.ts @@ -105,7 +105,7 @@ export class DebugViewlet extends ViewContainerViewlet { return [this.startAction, this.configureAction, this.toggleReplAction]; } - return DebugActionsWidget.getActions(this.allActions, this.toUnbind, this.debugService, this.keybindingService, this.instantiationService); + return DebugActionsWidget.getActions(this.allActions, this.toDispose, this.debugService, this.keybindingService, this.instantiationService); } public get showInitialDebugActions(): boolean { diff --git a/src/vs/workbench/parts/debug/browser/statusbarColorProvider.ts b/src/vs/workbench/parts/debug/browser/statusbarColorProvider.ts index ed2b380111e..afb16080fcd 100644 --- a/src/vs/workbench/parts/debug/browser/statusbarColorProvider.ts +++ b/src/vs/workbench/parts/debug/browser/statusbarColorProvider.ts @@ -49,8 +49,8 @@ export class StatusBarColorProvider extends Themable implements IWorkbenchContri } private registerListeners(): void { - this.toUnbind.push(this.debugService.onDidChangeState(state => this.updateStyles())); - this.toUnbind.push(this.contextService.onDidChangeWorkbenchState(state => this.updateStyles())); + this._register(this.debugService.onDidChangeState(state => this.updateStyles())); + this._register(this.contextService.onDidChangeWorkbenchState(state => this.updateStyles())); } protected updateStyles(): void { diff --git a/src/vs/workbench/parts/debug/electron-browser/repl.ts b/src/vs/workbench/parts/debug/electron-browser/repl.ts index 7ab8d459385..35b974a511b 100644 --- a/src/vs/workbench/parts/debug/electron-browser/repl.ts +++ b/src/vs/workbench/parts/debug/electron-browser/repl.ts @@ -104,10 +104,10 @@ export class Repl extends Panel implements IPrivateReplService, IHistoryNavigati } private registerListeners(): void { - this.toUnbind.push(this.debugService.getModel().onDidChangeReplElements(() => { + this._register(this.debugService.getModel().onDidChangeReplElements(() => { this.refreshReplElements(this.debugService.getModel().getReplElements().length === 0); })); - this.toUnbind.push(this.panelService.onDidPanelOpen(panel => this.refreshReplElements(true))); + this._register(this.panelService.onDidPanelOpen(panel => this.refreshReplElements(true))); } private refreshReplElements(noDelay: boolean): void { @@ -166,7 +166,7 @@ export class Repl extends Panel implements IPrivateReplService, IHistoryNavigati const { scopedContextKeyService, historyNavigationEnablement } = createAndBindHistoryNavigationWidgetScopedContextKeyService(this.contextKeyService, { target: this.replInputContainer, historyNavigator: this }); this.historyNavigationEnablement = historyNavigationEnablement; - this.toUnbind.push(scopedContextKeyService); + this._register(scopedContextKeyService); CONTEXT_IN_DEBUG_REPL.bindTo(scopedContextKeyService).set(true); const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection( @@ -191,19 +191,19 @@ export class Repl extends Panel implements IPrivateReplService, IHistoryNavigati } }); - this.toUnbind.push(this.replInput.onDidScrollChange(e => { + this._register(this.replInput.onDidScrollChange(e => { if (!e.scrollHeightChanged) { return; } this.replInputHeight = Math.max(Repl.REPL_INPUT_INITIAL_HEIGHT, Math.min(Repl.REPL_INPUT_MAX_HEIGHT, e.scrollHeight, this.dimension.height)); this.layout(this.dimension); })); - this.toUnbind.push(this.replInput.onDidChangeModelContent(() => { + this._register(this.replInput.onDidChangeModelContent(() => { this.historyNavigationEnablement.set(this.replInput.getModel().getValue() === ''); })); - this.toUnbind.push(dom.addStandardDisposableListener(this.replInputContainer, dom.EventType.FOCUS, () => dom.addClass(this.replInputContainer, 'synthetic-focus'))); - this.toUnbind.push(dom.addStandardDisposableListener(this.replInputContainer, dom.EventType.BLUR, () => dom.removeClass(this.replInputContainer, 'synthetic-focus'))); + this._register(dom.addStandardDisposableListener(this.replInputContainer, dom.EventType.FOCUS, () => dom.addClass(this.replInputContainer, 'synthetic-focus'))); + this._register(dom.addStandardDisposableListener(this.replInputContainer, dom.EventType.BLUR, () => dom.removeClass(this.replInputContainer, 'synthetic-focus'))); } private navigateHistory(previous: boolean): void { @@ -282,9 +282,7 @@ export class Repl extends Panel implements IPrivateReplService, IHistoryNavigati this.instantiationService.createInstance(ClearReplAction, ClearReplAction.ID, ClearReplAction.LABEL) ]; - this.actions.forEach(a => { - this.toUnbind.push(a); - }); + this.actions.forEach(a => this._register(a)); } return this.actions; diff --git a/src/vs/workbench/parts/feedback/electron-browser/feedback.ts b/src/vs/workbench/parts/feedback/electron-browser/feedback.ts index c9b4a6a03bc..2224b8c6846 100644 --- a/src/vs/workbench/parts/feedback/electron-browser/feedback.ts +++ b/src/vs/workbench/parts/feedback/electron-browser/feedback.ts @@ -342,7 +342,7 @@ export class FeedbackDropdown extends Dropdown { return element; } - public show(): void { + show(): void { super.show(); if (this.options.onFeedbackVisibilityChange) { @@ -356,7 +356,7 @@ export class FeedbackDropdown extends Dropdown { } } - public hide(): void { + hide(): void { if (this.feedbackDescriptionInput) { this.feedback = this.feedbackDescriptionInput.value; } @@ -373,7 +373,7 @@ export class FeedbackDropdown extends Dropdown { super.hide(); } - public onEvent(e: Event, activeElement: HTMLElement): void { + onEvent(e: Event, activeElement: HTMLElement): void { if (e instanceof KeyboardEvent) { const keyboardEvent = e; if (keyboardEvent.keyCode === 27) { // Escape diff --git a/src/vs/workbench/parts/feedback/electron-browser/feedbackStatusbarItem.ts b/src/vs/workbench/parts/feedback/electron-browser/feedbackStatusbarItem.ts index 1a659b36d9a..38b00d07f94 100644 --- a/src/vs/workbench/parts/feedback/electron-browser/feedbackStatusbarItem.ts +++ b/src/vs/workbench/parts/feedback/electron-browser/feedbackStatusbarItem.ts @@ -32,14 +32,14 @@ class TwitterFeedbackService implements IFeedbackService { return TwitterFeedbackService.HASHTAGS.join(','); } - public submitFeedback(feedback: IFeedback): void { + submitFeedback(feedback: IFeedback): void { const queryString = `?${feedback.sentiment === 1 ? `hashtags=${this.combineHashTagsAsString()}&` : null}ref_src=twsrc%5Etfw&related=twitterapi%2Ctwitter&text=${encodeURIComponent(feedback.feedback)}&tw_p=tweetbutton&via=${TwitterFeedbackService.VIA_NAME}`; const url = TwitterFeedbackService.TWITTER_URL + queryString; window.open(url); } - public getCharacterLimit(sentiment: number): number { + getCharacterLimit(sentiment: number): number { let length: number = 0; if (sentiment === 1) { TwitterFeedbackService.HASHTAGS.forEach(element => { @@ -73,15 +73,14 @@ export class FeedbackStatusbarItem extends Themable implements IStatusbarItem { this.enabled = this.configurationService.getValue(FEEDBACK_VISIBLE_CONFIG); - this.hideAction = this.instantiationService.createInstance(HideAction); - this.toUnbind.push(this.hideAction); + this.hideAction = this._register(this.instantiationService.createInstance(HideAction)); this.registerListeners(); } private registerListeners(): void { - this.toUnbind.push(this.contextService.onDidChangeWorkbenchState(() => this.updateStyles())); - this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(e))); + this._register(this.contextService.onDidChangeWorkbenchState(() => this.updateStyles())); + this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(e))); } private onConfigurationUpdated(event: IConfigurationChangeEvent): void { @@ -99,7 +98,7 @@ export class FeedbackStatusbarItem extends Themable implements IStatusbarItem { } } - public render(element: HTMLElement): IDisposable { + render(element: HTMLElement): IDisposable { this.container = element; // Prevent showing dropdown on anything but left click @@ -107,7 +106,7 @@ export class FeedbackStatusbarItem extends Themable implements IStatusbarItem { if (e.button !== 0) { EventHelper.stop(e, true); } - }, this.toUnbind, true); + }, this.toDispose, true); // Offer context menu to hide status bar entry $(this.container).on('contextmenu', e => { @@ -117,7 +116,7 @@ export class FeedbackStatusbarItem extends Themable implements IStatusbarItem { getAnchor: () => this.container, getActions: () => TPromise.as([this.hideAction]) }); - }, this.toUnbind); + }, this.toDispose); return this.update(); } @@ -128,7 +127,7 @@ export class FeedbackStatusbarItem extends Themable implements IStatusbarItem { // Create if (enabled) { if (!this.dropdown) { - this.dropdown = this.instantiationService.createInstance(FeedbackDropdown, this.container, { + this.dropdown = this._register(this.instantiationService.createInstance(FeedbackDropdown, this.container, { contextViewProvider: this.contextViewService, feedbackService: this.instantiationService.createInstance(TwitterFeedbackService), onFeedbackVisibilityChange: visible => { @@ -138,8 +137,7 @@ export class FeedbackStatusbarItem extends Themable implements IStatusbarItem { removeClass(this.container, 'has-beak'); } } - } as IFeedbackDropdownOptions); - this.toUnbind.push(this.dropdown); + } as IFeedbackDropdownOptions)); this.updateStyles(); @@ -166,7 +164,7 @@ class HideAction extends Action { super('feedback.hide', localize('hide', "Hide")); } - public run(extensionId: string): TPromise { + run(extensionId: string): TPromise { return this.configurationService.updateValue(FEEDBACK_VISIBLE_CONFIG, false); } } diff --git a/src/vs/workbench/parts/files/browser/editors/binaryFileEditor.ts b/src/vs/workbench/parts/files/browser/editors/binaryFileEditor.ts index de2b5da49ee..5457bee60b2 100644 --- a/src/vs/workbench/parts/files/browser/editors/binaryFileEditor.ts +++ b/src/vs/workbench/parts/files/browser/editors/binaryFileEditor.ts @@ -21,7 +21,7 @@ import { IEditorService } from 'vs/workbench/services/editor/common/editorServic */ export class BinaryFileEditor extends BaseBinaryResourceEditor { - public static readonly ID = BINARY_FILE_EDITOR_ID; + static readonly ID = BINARY_FILE_EDITOR_ID; constructor( @ITelemetryService telemetryService: ITelemetryService, @@ -59,7 +59,7 @@ export class BinaryFileEditor extends BaseBinaryResourceEditor { }); } - public getTitle(): string { + getTitle(): string { return this.input ? this.input.getName() : nls.localize('binaryFileEditor', "Binary File Viewer"); } } diff --git a/src/vs/workbench/parts/files/browser/editors/fileEditorTracker.ts b/src/vs/workbench/parts/files/browser/editors/fileEditorTracker.ts index 5169f040911..df5857ced33 100644 --- a/src/vs/workbench/parts/files/browser/editors/fileEditorTracker.ts +++ b/src/vs/workbench/parts/files/browser/editors/fileEditorTracker.ts @@ -15,7 +15,7 @@ import { ITextFileService, ITextFileEditorModel } from 'vs/workbench/services/te import { FileOperationEvent, FileOperation, IFileService, FileChangeType, FileChangesEvent } from 'vs/platform/files/common/files'; import { FileEditorInput } from 'vs/workbench/parts/files/common/editors/fileEditorInput'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; import { distinct } from 'vs/base/common/arrays'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; @@ -30,11 +30,10 @@ import { BINARY_FILE_EDITOR_ID } from 'vs/workbench/parts/files/common/files'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IEditorGroupsService, IEditorGroup } from 'vs/workbench/services/group/common/editorGroupsService'; -export class FileEditorTracker implements IWorkbenchContribution { +export class FileEditorTracker extends Disposable implements IWorkbenchContribution { protected closeOnFileDelete: boolean; - private toUnbind: IDisposable[]; private modelLoadQueue: ResourceQueue; private activeOutOfWorkspaceWatchers: ResourceMap; @@ -49,7 +48,8 @@ export class FileEditorTracker implements IWorkbenchContribution { @IWorkspaceContextService private contextService: IWorkspaceContextService, @IWindowService private windowService: IWindowService ) { - this.toUnbind = []; + super(); + this.modelLoadQueue = new ResourceQueue(); this.activeOutOfWorkspaceWatchers = new ResourceMap(); @@ -61,22 +61,22 @@ export class FileEditorTracker implements IWorkbenchContribution { private registerListeners(): void { // Update editors from operation changes - this.toUnbind.push(this.fileService.onAfterOperation(e => this.onFileOperation(e))); + this._register(this.fileService.onAfterOperation(e => this.onFileOperation(e))); // Update editors from disk changes - this.toUnbind.push(this.fileService.onFileChanges(e => this.onFileChanges(e))); + this._register(this.fileService.onFileChanges(e => this.onFileChanges(e))); // Editor changing - this.toUnbind.push(this.editorService.onDidVisibleEditorsChange(() => this.handleOutOfWorkspaceWatchers())); + this._register(this.editorService.onDidVisibleEditorsChange(() => this.handleOutOfWorkspaceWatchers())); // Update visible editors when focus is gained - this.toUnbind.push(this.windowService.onDidChangeFocus(e => this.onWindowFocusChange(e))); + this._register(this.windowService.onDidChangeFocus(e => this.onWindowFocusChange(e))); // Lifecycle this.lifecycleService.onShutdown(this.dispose, this); // Configuration - this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(this.configurationService.getValue()))); + this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(this.configurationService.getValue()))); } private onConfigurationUpdated(configuration: IWorkbenchEditorConfiguration): void { @@ -363,8 +363,8 @@ export class FileEditorTracker implements IWorkbenchContribution { }); } - public dispose(): void { - this.toUnbind = dispose(this.toUnbind); + dispose(): void { + super.dispose(); // Dispose watchers if any this.activeOutOfWorkspaceWatchers.forEach(resource => this.fileService.unwatchFileChanges(resource)); diff --git a/src/vs/workbench/parts/files/browser/editors/textFileEditor.ts b/src/vs/workbench/parts/files/browser/editors/textFileEditor.ts index 4b71f7e2b42..f48ed0f4cf6 100644 --- a/src/vs/workbench/parts/files/browser/editors/textFileEditor.ts +++ b/src/vs/workbench/parts/files/browser/editors/textFileEditor.ts @@ -39,7 +39,7 @@ import { IEditorGroupView } from 'vs/workbench/browser/parts/editor/editor'; */ export class TextFileEditor extends BaseTextEditor { - public static readonly ID = TEXT_FILE_EDITOR_ID; + static readonly ID = TEXT_FILE_EDITOR_ID; constructor( @ITelemetryService telemetryService: ITelemetryService, @@ -59,7 +59,7 @@ export class TextFileEditor extends BaseTextEditor { super(TextFileEditor.ID, telemetryService, instantiationService, storageService, configurationService, themeService, textFileService, editorService, editorGroupService); // Clear view state for deleted files - this.toUnbind.push(this.fileService.onFileChanges(e => this.onFilesChanged(e))); + this._register(this.fileService.onFileChanges(e => this.onFilesChanged(e))); } private onFilesChanged(e: FileChangesEvent): void { @@ -69,11 +69,11 @@ export class TextFileEditor extends BaseTextEditor { } } - public getTitle(): string { + getTitle(): string { return this.input ? this.input.getName() : nls.localize('textFileEditor', "Text File Editor"); } - public get input(): FileEditorInput { + get input(): FileEditorInput { return this._input as FileEditorInput; } @@ -83,21 +83,21 @@ export class TextFileEditor extends BaseTextEditor { // React to editors closing to preserve view state. This needs to happen // in the onWillCloseEditor because at that time the editor has not yet // been disposed and we can safely persist the view state still. - this.toUnbind.push((group as IEditorGroupView).onWillCloseEditor(e => { + this._register((group as IEditorGroupView).onWillCloseEditor(e => { if (e.editor === this.input) { this.doSaveTextEditorViewState(this.input); } })); } - public setOptions(options: EditorOptions): void { + setOptions(options: EditorOptions): void { const textOptions = options; if (textOptions && types.isFunction(textOptions.apply)) { textOptions.apply(this.getControl(), ScrollType.Smooth); } } - public setInput(input: FileEditorInput, options: EditorOptions, token: CancellationToken): Thenable { + setInput(input: FileEditorInput, options: EditorOptions, token: CancellationToken): Thenable { // Remember view settings if input changes this.doSaveTextEditorViewState(this.input); @@ -243,7 +243,7 @@ export class TextFileEditor extends BaseTextEditor { return ariaLabel; } - public clearInput(): void { + clearInput(): void { // Keep editor view state in settings to restore when coming back this.doSaveTextEditorViewState(this.input); @@ -255,7 +255,7 @@ export class TextFileEditor extends BaseTextEditor { super.clearInput(); } - public shutdown(): void { + shutdown(): void { // Save View State this.doSaveTextEditorViewState(this.input); diff --git a/src/vs/workbench/parts/files/common/dirtyFilesTracker.ts b/src/vs/workbench/parts/files/common/dirtyFilesTracker.ts index 34594b0301e..7cfc6f9d7cf 100644 --- a/src/vs/workbench/parts/files/common/dirtyFilesTracker.ts +++ b/src/vs/workbench/parts/files/common/dirtyFilesTracker.ts @@ -12,16 +12,15 @@ import { TextFileModelChangeEvent, ITextFileService, AutoSaveMode, ModelState } import { platform, Platform } from 'vs/base/common/platform'; import { IWindowService } from 'vs/platform/windows/common/windows'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle'; import URI from 'vs/base/common/uri'; import { IActivityService, NumberBadge } from 'vs/workbench/services/activity/common/activity'; import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; import * as arrays from 'vs/base/common/arrays'; import { IEditorService, ACTIVE_GROUP } from 'vs/workbench/services/editor/common/editorService'; -export class DirtyFilesTracker implements IWorkbenchContribution { +export class DirtyFilesTracker extends Disposable implements IWorkbenchContribution { private isDocumentedEdited: boolean; - private toUnbind: IDisposable[]; private lastDirtyCount: number; private badgeHandle: IDisposable; @@ -33,7 +32,8 @@ export class DirtyFilesTracker implements IWorkbenchContribution { @IWindowService private windowService: IWindowService, @IUntitledEditorService private untitledEditorService: IUntitledEditorService ) { - this.toUnbind = []; + super(); + this.isDocumentedEdited = false; this.registerListeners(); @@ -42,11 +42,11 @@ export class DirtyFilesTracker implements IWorkbenchContribution { private registerListeners(): void { // Local text file changes - this.toUnbind.push(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e))); - this.toUnbind.push(this.textFileService.models.onModelsDirty(e => this.onTextFilesDirty(e))); - this.toUnbind.push(this.textFileService.models.onModelsSaved(e => this.onTextFilesSaved(e))); - this.toUnbind.push(this.textFileService.models.onModelsSaveError(e => this.onTextFilesSaveError(e))); - this.toUnbind.push(this.textFileService.models.onModelsReverted(e => this.onTextFilesReverted(e))); + this._register(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e))); + this._register(this.textFileService.models.onModelsDirty(e => this.onTextFilesDirty(e))); + this._register(this.textFileService.models.onModelsSaved(e => this.onTextFilesSaved(e))); + this._register(this.textFileService.models.onModelsSaveError(e => this.onTextFilesSaveError(e))); + this._register(this.textFileService.models.onModelsReverted(e => this.onTextFilesReverted(e))); // Lifecycle this.lifecycleService.onShutdown(this.dispose, this); @@ -142,8 +142,4 @@ export class DirtyFilesTracker implements IWorkbenchContribution { this.windowService.setDocumentEdited(hasDirtyFiles); } } - - public dispose(): void { - this.toUnbind = dispose(this.toUnbind); - } } diff --git a/src/vs/workbench/parts/files/common/editors/fileEditorInput.ts b/src/vs/workbench/parts/files/common/editors/fileEditorInput.ts index e2d09a49e58..df16421d173 100644 --- a/src/vs/workbench/parts/files/common/editors/fileEditorInput.ts +++ b/src/vs/workbench/parts/files/common/editors/fileEditorInput.ts @@ -18,7 +18,7 @@ import { FileOperationError, FileOperationResult } from 'vs/platform/files/commo import { ITextFileService, AutoSaveMode, ModelState, TextFileModelChangeEvent } from 'vs/workbench/services/textfile/common/textfiles'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; -import { IDisposable, dispose, IReference } from 'vs/base/common/lifecycle'; +import { IReference } from 'vs/base/common/lifecycle'; import { telemetryURIDescriptor } from 'vs/platform/telemetry/common/telemetryUtils'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ITextModelService } from 'vs/editor/common/services/resolverService'; @@ -35,7 +35,6 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { private forceOpenAsText: boolean; private textModelReference: TPromise>; private name: string; - private toUnbind: IDisposable[]; /** * An editor input who's contents are retrieved from file services. @@ -52,8 +51,6 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { ) { super(); - this.toUnbind = []; - this.setPreferredEncoding(preferredEncoding); this.registerListeners(); @@ -62,11 +59,11 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { private registerListeners(): void { // Model changes - this.toUnbind.push(this.textFileService.models.onModelDirty(e => this.onDirtyStateChange(e))); - this.toUnbind.push(this.textFileService.models.onModelSaveError(e => this.onDirtyStateChange(e))); - this.toUnbind.push(this.textFileService.models.onModelSaved(e => this.onDirtyStateChange(e))); - this.toUnbind.push(this.textFileService.models.onModelReverted(e => this.onDirtyStateChange(e))); - this.toUnbind.push(this.textFileService.models.onModelOrphanedChanged(e => this.onModelOrphanedChanged(e))); + this._register(this.textFileService.models.onModelDirty(e => this.onDirtyStateChange(e))); + this._register(this.textFileService.models.onModelSaveError(e => this.onDirtyStateChange(e))); + this._register(this.textFileService.models.onModelSaved(e => this.onDirtyStateChange(e))); + this._register(this.textFileService.models.onModelReverted(e => this.onDirtyStateChange(e))); + this._register(this.textFileService.models.onModelOrphanedChanged(e => this.onModelOrphanedChanged(e))); } private onDirtyStateChange(e: TextFileModelChangeEvent): void { @@ -81,11 +78,11 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { } } - public getResource(): URI { + getResource(): URI { return this.resource; } - public setPreferredEncoding(encoding: string): void { + setPreferredEncoding(encoding: string): void { this.preferredEncoding = encoding; if (encoding) { @@ -93,7 +90,7 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { } } - public getEncoding(): string { + getEncoding(): string { const textModel = this.textFileService.models.get(this.resource); if (textModel) { return textModel.getEncoding(); @@ -102,11 +99,11 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { return this.preferredEncoding; } - public getPreferredEncoding(): string { + getPreferredEncoding(): string { return this.preferredEncoding; } - public setEncoding(encoding: string, mode: EncodingMode): void { + setEncoding(encoding: string, mode: EncodingMode): void { this.preferredEncoding = encoding; const textModel = this.textFileService.models.get(this.resource); @@ -115,21 +112,21 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { } } - public setForceOpenAsText(): void { + setForceOpenAsText(): void { this.forceOpenAsText = true; this.forceOpenAsBinary = false; } - public setForceOpenAsBinary(): void { + setForceOpenAsBinary(): void { this.forceOpenAsBinary = true; this.forceOpenAsText = false; } - public getTypeId(): string { + getTypeId(): string { return FILE_EDITOR_INPUT_ID; } - public getName(): string { + getName(): string { if (!this.name) { this.name = resources.basenameOrAuthority(this.resource); } @@ -153,7 +150,7 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { return labels.getPathLabel(resources.dirname(this.resource), this.environmentService, rootProvider); } - public getDescription(verbosity: Verbosity = Verbosity.MEDIUM): string { + getDescription(verbosity: Verbosity = Verbosity.MEDIUM): string { let description: string; switch (verbosity) { case Verbosity.SHORT: @@ -187,7 +184,7 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { return labels.getPathLabel(this.resource, this.environmentService, rootProvider); } - public getTitle(verbosity: Verbosity): string { + getTitle(verbosity: Verbosity): string { let title: string; switch (verbosity) { case Verbosity.SHORT: @@ -213,7 +210,7 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { return label; } - public isDirty(): boolean { + isDirty(): boolean { const model = this.textFileService.models.get(this.resource); if (!model) { return false; @@ -230,23 +227,23 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { return model.isDirty(); } - public confirmSave(): TPromise { + confirmSave(): TPromise { return this.textFileService.confirmSave([this.resource]); } - public save(): TPromise { + save(): TPromise { return this.textFileService.save(this.resource); } - public revert(options?: IRevertOptions): TPromise { + revert(options?: IRevertOptions): TPromise { return this.textFileService.revert(this.resource, options); } - public getPreferredEditorId(candidates: string[]): string { + getPreferredEditorId(candidates: string[]): string { return this.forceOpenAsBinary ? BINARY_FILE_EDITOR_ID : TEXT_FILE_EDITOR_ID; } - public resolve(refresh?: boolean): TPromise { + resolve(refresh?: boolean): TPromise { // Resolve as binary if (this.forceOpenAsBinary) { @@ -287,11 +284,11 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { return this.instantiationService.createInstance(BinaryEditorModel, this.resource, this.getName()).load().then(m => m as BinaryEditorModel); } - public isResolved(): boolean { + isResolved(): boolean { return !!this.textFileService.models.get(this.resource); } - public getTelemetryDescriptor(): object { + getTelemetryDescriptor(): object { const descriptor = super.getTelemetryDescriptor(); descriptor['resource'] = telemetryURIDescriptor(this.getResource(), path => this.hashService.createSHA1(path)); @@ -303,7 +300,7 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { return descriptor; } - public dispose(): void { + dispose(): void { // Model reference if (this.textModelReference) { @@ -311,13 +308,10 @@ export class FileEditorInput extends EditorInput implements IFileEditorInput { this.textModelReference = null; } - // Listeners - this.toUnbind = dispose(this.toUnbind); - super.dispose(); } - public matches(otherInput: any): boolean { + matches(otherInput: any): boolean { if (super.matches(otherInput) === true) { return true; } diff --git a/src/vs/workbench/parts/files/common/files.ts b/src/vs/workbench/parts/files/common/files.ts index d1b128c950b..160584dd829 100644 --- a/src/vs/workbench/parts/files/common/files.ts +++ b/src/vs/workbench/parts/files/common/files.ts @@ -157,7 +157,7 @@ export class FileOnDiskContentProvider implements ITextModelContentProvider { ) { } - public provideTextContent(resource: URI): TPromise { + provideTextContent(resource: URI): TPromise { const fileOnDiskResource = URI.file(resource.fsPath); // Make sure our file from disk is resolved up to date @@ -205,7 +205,7 @@ export class FileOnDiskContentProvider implements ITextModelContentProvider { }); } - public dispose(): void { + dispose(): void { this.fileWatcher = dispose(this.fileWatcher); } } diff --git a/src/vs/workbench/parts/files/electron-browser/saveErrorHandler.ts b/src/vs/workbench/parts/files/electron-browser/saveErrorHandler.ts index ca120f667fc..abba820aaa5 100644 --- a/src/vs/workbench/parts/files/electron-browser/saveErrorHandler.ts +++ b/src/vs/workbench/parts/files/electron-browser/saveErrorHandler.ts @@ -14,7 +14,7 @@ import URI from 'vs/base/common/uri'; import { FileOperationError, FileOperationResult } from 'vs/platform/files/common/files'; import { ITextFileService, ISaveErrorHandler, ITextFileEditorModel } from 'vs/workbench/services/textfile/common/textfiles'; import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel'; import { ITextModelService } from 'vs/editor/common/services/resolverService'; @@ -43,9 +43,8 @@ const LEARN_MORE_DIRTY_WRITE_IGNORE_KEY = 'learnMoreDirtyWriteError'; const conflictEditorHelp = nls.localize('userGuide', "Use the actions in the editor tool bar to either undo your changes or overwrite the content on disk with your changes."); // A handler for save error happening with conflict resolution actions -export class SaveErrorHandler implements ISaveErrorHandler, IWorkbenchContribution { +export class SaveErrorHandler extends Disposable implements ISaveErrorHandler, IWorkbenchContribution { private messages: ResourceMap; - private toUnbind: IDisposable[]; private conflictResolutionContext: IContextKey; private activeConflictResolutionResource: URI; @@ -58,15 +57,13 @@ export class SaveErrorHandler implements ISaveErrorHandler, IWorkbenchContributi @IInstantiationService private instantiationService: IInstantiationService, @IStorageService private storageService: IStorageService ) { - this.toUnbind = []; + super(); + this.messages = new ResourceMap(); this.conflictResolutionContext = new RawContextKey(CONFLICT_RESOLUTION_CONTEXT, false).bindTo(contextKeyService); - const provider = instantiationService.createInstance(FileOnDiskContentProvider); - this.toUnbind.push(provider); - - const registrationDisposal = textModelService.registerTextModelContentProvider(CONFLICT_RESOLUTION_SCHEME, provider); - this.toUnbind.push(registrationDisposal); + const provider = this._register(instantiationService.createInstance(FileOnDiskContentProvider)); + this._register(textModelService.registerTextModelContentProvider(CONFLICT_RESOLUTION_SCHEME, provider)); // Hook into model TextFileEditorModel.setSaveErrorHandler(this); @@ -75,9 +72,9 @@ export class SaveErrorHandler implements ISaveErrorHandler, IWorkbenchContributi } private registerListeners(): void { - this.toUnbind.push(this.textFileService.models.onModelSaved(e => this.onFileSavedOrReverted(e.resource))); - this.toUnbind.push(this.textFileService.models.onModelReverted(e => this.onFileSavedOrReverted(e.resource))); - this.toUnbind.push(this.editorService.onDidActiveEditorChange(() => this.onActiveEditorChanged())); + this._register(this.textFileService.models.onModelSaved(e => this.onFileSavedOrReverted(e.resource))); + this._register(this.textFileService.models.onModelReverted(e => this.onFileSavedOrReverted(e.resource))); + this._register(this.editorService.onDidActiveEditorChange(() => this.onActiveEditorChanged())); } private onActiveEditorChanged(): void { @@ -105,7 +102,7 @@ export class SaveErrorHandler implements ISaveErrorHandler, IWorkbenchContributi } } - public onSaveError(error: any, model: ITextFileEditorModel): void { + onSaveError(error: any, model: ITextFileEditorModel): void { const fileOperationError = error as FileOperationError; const resource = model.getResource(); @@ -181,8 +178,8 @@ export class SaveErrorHandler implements ISaveErrorHandler, IWorkbenchContributi this.messages.set(model.getResource(), handle); } - public dispose(): void { - this.toUnbind = dispose(this.toUnbind); + dispose(): void { + super.dispose(); this.messages.clear(); } @@ -203,7 +200,7 @@ class ResolveConflictLearnMoreAction extends Action { super('workbench.files.action.resolveConflictLearnMore', nls.localize('learnMore', "Learn More")); } - public run(): TPromise { + run(): TPromise { return this.openerService.open(URI.parse('https://go.microsoft.com/fwlink/?linkid=868264')); } } @@ -216,7 +213,7 @@ class DoNotShowResolveConflictLearnMoreAction extends Action { super('workbench.files.action.resolveConflictLearnMoreDoNotShowAgain', nls.localize('dontShowAgain', "Don't Show Again")); } - public run(notification: IDisposable): TPromise { + run(notification: IDisposable): TPromise { this.storageService.store(LEARN_MORE_DIRTY_WRITE_IGNORE_KEY, true); // Hide notification @@ -239,7 +236,7 @@ class ResolveSaveConflictAction extends Action { super('workbench.files.action.resolveConflict', nls.localize('compareChanges', "Compare")); } - public run(): TPromise { + run(): TPromise { if (!this.model.isDisposed()) { const resource = this.model.getResource(); const name = paths.basename(resource.fsPath); @@ -281,7 +278,7 @@ class SaveElevatedAction extends Action { super('workbench.files.action.saveElevated', triedToMakeWriteable ? nls.localize('overwriteElevated', "Overwrite as Admin...") : nls.localize('saveElevated', "Retry as Admin...")); } - public run(): TPromise { + run(): TPromise { if (!this.model.isDisposed()) { this.model.save({ writeElevated: true, @@ -301,7 +298,7 @@ class OverwriteReadonlyAction extends Action { super('workbench.files.action.overwrite', nls.localize('overwrite', "Overwrite")); } - public run(): TPromise { + run(): TPromise { if (!this.model.isDisposed()) { this.model.save({ overwriteReadonly: true }).done(null, errors.onUnexpectedError); } diff --git a/src/vs/workbench/parts/markers/electron-browser/markersPanel.ts b/src/vs/workbench/parts/markers/electron-browser/markersPanel.ts index 22654994ff3..a5976612345 100644 --- a/src/vs/workbench/parts/markers/electron-browser/markersPanel.ts +++ b/src/vs/workbench/parts/markers/electron-browser/markersPanel.ts @@ -72,8 +72,7 @@ export class MarkersPanel extends Panel { public create(parent: HTMLElement): TPromise { super.create(parent); - this.rangeHighlightDecorations = this.instantiationService.createInstance(RangeHighlightDecorations); - this.toUnbind.push(this.rangeHighlightDecorations); + this.rangeHighlightDecorations = this._register(this.instantiationService.createInstance(RangeHighlightDecorations)); dom.addClass(parent, 'markers-panel'); @@ -230,11 +229,11 @@ export class MarkersPanel extends Panel { } private createListeners(): void { - this.toUnbind.push(this.markersWorkbenchService.onDidChange(resources => this.onDidChange(resources))); - this.toUnbind.push(this.editorService.onDidActiveEditorChange(this.onActiveEditorChanged, this)); - this.toUnbind.push(this.tree.onDidChangeSelection(() => this.onSelected())); - this.toUnbind.push(this.filterInputActionItem.onDidChange(() => this.updateFilter())); - this.actions.forEach(a => this.toUnbind.push(a)); + this._register(this.markersWorkbenchService.onDidChange(resources => this.onDidChange(resources))); + this._register(this.editorService.onDidActiveEditorChange(this.onActiveEditorChanged, this)); + this._register(this.tree.onDidChangeSelection(() => this.onSelected())); + this._register(this.filterInputActionItem.onDidChange(() => this.updateFilter())); + this.actions.forEach(a => this._register(a)); } private onDidChange(resources: URI[]) { diff --git a/src/vs/workbench/parts/navigation/common/navigation.contribution.ts b/src/vs/workbench/parts/navigation/common/navigation.contribution.ts new file mode 100644 index 00000000000..87699346f17 --- /dev/null +++ b/src/vs/workbench/parts/navigation/common/navigation.contribution.ts @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Registry } from 'vs/platform/registry/common/platform'; +import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; +import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; +import { HistoryNavigationKeybindingsChangedContribution } from 'vs/workbench/parts/navigation/common/removedKeybindingsContribution'; + +Registry.as(WorkbenchExtensions.Workbench).registerWorkbenchContribution(HistoryNavigationKeybindingsChangedContribution, LifecyclePhase.Eventually); \ No newline at end of file diff --git a/src/vs/workbench/electron-browser/removedKeybindingsContribution.ts b/src/vs/workbench/parts/navigation/common/removedKeybindingsContribution.ts similarity index 98% rename from src/vs/workbench/electron-browser/removedKeybindingsContribution.ts rename to src/vs/workbench/parts/navigation/common/removedKeybindingsContribution.ts index dddac57925f..625bd33cf6c 100644 --- a/src/vs/workbench/electron-browser/removedKeybindingsContribution.ts +++ b/src/vs/workbench/parts/navigation/common/removedKeybindingsContribution.ts @@ -12,6 +12,7 @@ import { IStorageService, StorageScope } from 'vs/platform/storage/common/storag import { localize } from 'vs/nls'; import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences'; +// TODO@Sandeep remove me after a while export class HistoryNavigationKeybindingsChangedContribution implements IWorkbenchContribution { private previousCommands: string[] = [ diff --git a/src/vs/workbench/parts/output/browser/outputPanel.ts b/src/vs/workbench/parts/output/browser/outputPanel.ts index a9151ee685c..0cc33ce78b5 100644 --- a/src/vs/workbench/parts/output/browser/outputPanel.ts +++ b/src/vs/workbench/parts/output/browser/outputPanel.ts @@ -65,9 +65,7 @@ export class OutputPanel extends AbstractTextResourceEditor { this.instantiationService.createInstance(OpenLogOutputFile) ]; - this.actions.forEach(a => { - this.toUnbind.push(a); - }); + this.actions.forEach(a => this._register(a)); } return this.actions; @@ -134,8 +132,7 @@ export class OutputPanel extends AbstractTextResourceEditor { protected createEditor(parent: HTMLElement): void { // First create the scoped instantation service and only then construct the editor using the scoped service - const scopedContextKeyService = this.contextKeyService.createScoped(parent); - this.toUnbind.push(scopedContextKeyService); + const scopedContextKeyService = this._register(this.contextKeyService.createScoped(parent)); this.scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, scopedContextKeyService])); super.createEditor(parent); diff --git a/src/vs/workbench/parts/preferences/browser/preferencesEditor.ts b/src/vs/workbench/parts/preferences/browser/preferencesEditor.ts index fb3f595fa2e..afaa9962fea 100644 --- a/src/vs/workbench/parts/preferences/browser/preferencesEditor.ts +++ b/src/vs/workbench/parts/preferences/browser/preferencesEditor.ts @@ -987,8 +987,8 @@ export class DefaultPreferencesEditor extends BaseTextEditor { const editor = this.instantiationService.createInstance(CodeEditorWidget, parent, configuration, { contributions: DefaultPreferencesEditor._getContributions() }); // Inform user about editor being readonly if user starts type - this.toUnbind.push(editor.onDidType(() => this.showReadonlyHint(editor))); - this.toUnbind.push(editor.onDidPaste(() => this.showReadonlyHint(editor))); + this._register(editor.onDidType(() => this.showReadonlyHint(editor))); + this._register(editor.onDidPaste(() => this.showReadonlyHint(editor))); return editor; } diff --git a/src/vs/workbench/parts/quickopen/browser/commandsHandler.ts b/src/vs/workbench/parts/quickopen/browser/commandsHandler.ts index c978a3b0cc7..e76351076f2 100644 --- a/src/vs/workbench/parts/quickopen/browser/commandsHandler.ts +++ b/src/vs/workbench/parts/quickopen/browser/commandsHandler.ts @@ -58,7 +58,7 @@ function resolveCommandHistory(configurationService: IConfigurationService): num class CommandsHistory { - public static readonly DEFAULT_COMMANDS_HISTORY_LENGTH = 50; + static readonly DEFAULT_COMMANDS_HISTORY_LENGTH = 50; private static readonly PREF_KEY_CACHE = 'commandPalette.mru.cache'; private static readonly PREF_KEY_COUNTER = 'commandPalette.mru.counter'; @@ -120,20 +120,20 @@ class CommandsHistory { this.storageService.store(CommandsHistory.PREF_KEY_COUNTER, commandCounter); } - public push(commandId: string): void { + push(commandId: string): void { // set counter to command commandHistory.set(commandId, commandCounter++); } - public peek(commandId: string): number { + peek(commandId: string): number { return commandHistory.peek(commandId); } } export class ShowAllCommandsAction extends Action { - public static readonly ID = 'workbench.action.showCommands'; - public static readonly LABEL = nls.localize('showTriggerActions', "Show All Commands"); + static readonly ID = 'workbench.action.showCommands'; + static readonly LABEL = nls.localize('showTriggerActions', "Show All Commands"); constructor( id: string, @@ -144,7 +144,7 @@ export class ShowAllCommandsAction extends Action { super(id, label); } - public run(context?: any): TPromise { + run(context?: any): TPromise { const config = this.configurationService.getValue(); const restoreInput = config.workbench && config.workbench.commandPalette && config.workbench.commandPalette.preserveInput === true; @@ -162,8 +162,8 @@ export class ShowAllCommandsAction extends Action { export class ClearCommandHistoryAction extends Action { - public static readonly ID = 'workbench.action.clearCommandHistory'; - public static readonly LABEL = nls.localize('clearCommandHistory', "Clear Command History"); + static readonly ID = 'workbench.action.clearCommandHistory'; + static readonly LABEL = nls.localize('clearCommandHistory', "Clear Command History"); constructor( id: string, @@ -173,7 +173,7 @@ export class ClearCommandHistoryAction extends Action { super(id, label); } - public run(context?: any): TPromise { + run(context?: any): TPromise { const commandHistoryLength = resolveCommandHistory(this.configurationService); if (commandHistoryLength > 0) { commandHistory = new LRUCache(commandHistoryLength); @@ -199,7 +199,7 @@ class CommandPaletteEditorAction extends EditorAction { }); } - public run(accessor: ServicesAccessor, editor: ICodeEditor): TPromise { + run(accessor: ServicesAccessor, editor: ICodeEditor): TPromise { const quickOpenService = accessor.get(IQuickOpenService); // Show with prefix @@ -239,35 +239,35 @@ abstract class BaseCommandEntry extends QuickOpenEntryGroup { this.setHighlights(highlights.label, null, highlights.alias); } - public getCommandId(): string { + getCommandId(): string { return this.commandId; } - public getLabel(): string { + getLabel(): string { return this.label; } - public getSortLabel(): string { + getSortLabel(): string { return this.labelLowercase; } - public getDescription(): string { + getDescription(): string { return this.description; } - public setDescription(description: string): void { + setDescription(description: string): void { this.description = description; } - public getKeybinding(): ResolvedKeybinding { + getKeybinding(): ResolvedKeybinding { return this.keybinding; } - public getDetail(): string { + getDetail(): string { return this.alias; } - public getAriaLabel(): string { + getAriaLabel(): string { if (this.keybindingAriaLabel) { return nls.localize('entryAriaLabelWithKey', "{0}, {1}, commands", this.getLabel(), this.keybindingAriaLabel); } @@ -275,7 +275,7 @@ abstract class BaseCommandEntry extends QuickOpenEntryGroup { return nls.localize('entryAriaLabel', "{0}, commands", this.getLabel()); } - public run(mode: Mode, context: IEntryRunContext): boolean { + run(mode: Mode, context: IEntryRunContext): boolean { if (mode === Mode.OPEN) { this.runAction(this.getAction()); @@ -372,7 +372,7 @@ const wordFilter = or(matchesPrefix, matchesWords, matchesContiguousSubString); export class CommandsHandler extends QuickOpenHandler { - public static readonly ID = 'workbench.picker.commands'; + static readonly ID = 'workbench.picker.commands'; private lastSearchValue: string; private commandHistoryEnabled: boolean; @@ -397,7 +397,7 @@ export class CommandsHandler extends QuickOpenHandler { this.commandHistoryEnabled = resolveCommandHistory(this.configurationService) > 0; } - public getResults(searchValue: string): TPromise { + getResults(searchValue: string): TPromise { searchValue = searchValue.trim(); this.lastSearchValue = searchValue; @@ -540,7 +540,7 @@ export class CommandsHandler extends QuickOpenHandler { return entries; } - public getAutoFocus(searchValue: string, context: { model: IModel, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus { + getAutoFocus(searchValue: string, context: { model: IModel, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus { let autoFocusPrefixMatch = searchValue.trim(); if (autoFocusPrefixMatch && this.commandHistoryEnabled) { @@ -556,11 +556,11 @@ export class CommandsHandler extends QuickOpenHandler { }; } - public getEmptyLabel(searchString: string): string { + getEmptyLabel(searchString: string): string { return nls.localize('noCommandsMatching', "No commands matching"); } - public onClose(canceled: boolean): void { + onClose(canceled: boolean): void { if (canceled) { lastCommandPaletteInput = void 0; // clear last input when user canceled quick open } diff --git a/src/vs/workbench/parts/quickopen/browser/gotoLineHandler.ts b/src/vs/workbench/parts/quickopen/browser/gotoLineHandler.ts index d858f369bd9..2266eddb28e 100644 --- a/src/vs/workbench/parts/quickopen/browser/gotoLineHandler.ts +++ b/src/vs/workbench/parts/quickopen/browser/gotoLineHandler.ts @@ -22,13 +22,14 @@ import { IEditorOptions, RenderLineNumbersType } from 'vs/editor/common/config/e import { IEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService'; import { isCodeEditor, isDiffEditor } from 'vs/editor/browser/editorBrowser'; import { IEditorGroup } from 'vs/workbench/services/group/common/editorGroupsService'; +import { once } from 'vs/base/common/event'; export const GOTO_LINE_PREFIX = ':'; export class GotoLineAction extends QuickOpenAction { - public static readonly ID = 'workbench.action.gotoLine'; - public static readonly LABEL = nls.localize('gotoLine', "Go to Line..."); + static readonly ID = 'workbench.action.gotoLine'; + static readonly LABEL = nls.localize('gotoLine', "Go to Line..."); constructor(actionId: string, actionLabel: string, @IQuickOpenService private readonly _quickOpenService: IQuickOpenService, @@ -37,7 +38,7 @@ export class GotoLineAction extends QuickOpenAction { super(actionId, actionLabel, GOTO_LINE_PREFIX, _quickOpenService); } - public run(): TPromise { + run(): TPromise { let activeTextEditorWidget = this.editorService.activeTextEditorWidget; if (isDiffEditor(activeTextEditorWidget)) { @@ -60,12 +61,7 @@ export class GotoLineAction extends QuickOpenAction { const result = super.run(); if (restoreOptions) { - let toDispose = this._quickOpenService.onHide(() => { - if (!toDispose) { - return; - } - toDispose.dispose(); - toDispose = null; + once(this._quickOpenService.onHide)(() => { activeTextEditorWidget.updateOptions(restoreOptions); }); } @@ -92,7 +88,7 @@ class GotoLineEntry extends EditorQuickOpenEntry { this.column = numbers[1]; } - public getLabel(): string { + getLabel(): string { // Inform user about valid range if input is invalid const maxLineNumber = this.getMaxLineNumber(); @@ -123,7 +119,7 @@ class GotoLineEntry extends EditorQuickOpenEntry { return model && types.isFunction((model).getLineCount) ? (model).getLineCount() : -1; } - public run(mode: Mode, context: IEntryRunContext): boolean { + run(mode: Mode, context: IEntryRunContext): boolean { if (mode === Mode.OPEN) { return this.runOpen(context); } @@ -131,18 +127,18 @@ class GotoLineEntry extends EditorQuickOpenEntry { return this.runPreview(); } - public getInput(): IEditorInput { + getInput(): IEditorInput { return this.editorService.activeEditor; } - public getOptions(pinned?: boolean): ITextEditorOptions { + getOptions(pinned?: boolean): ITextEditorOptions { return { selection: this.toSelection(), pinned }; } - public runOpen(context: IEntryRunContext): boolean { + runOpen(context: IEntryRunContext): boolean { // No-op if range is not valid if (this.invalidRange()) { @@ -166,7 +162,7 @@ class GotoLineEntry extends EditorQuickOpenEntry { return true; } - public runPreview(): boolean { + runPreview(): boolean { // No-op if range is not valid if (this.invalidRange()) { @@ -208,7 +204,7 @@ interface IEditorLineDecoration { export class GotoLineHandler extends QuickOpenHandler { - public static readonly ID = 'workbench.picker.line'; + static readonly ID = 'workbench.picker.line'; private rangeHighlightDecorationId: IEditorLineDecoration; private lastKnownEditorViewState: IEditorViewState; @@ -217,11 +213,11 @@ export class GotoLineHandler extends QuickOpenHandler { super(); } - public getAriaLabel(): string { + getAriaLabel(): string { return nls.localize('gotoLineHandlerAriaLabel', "Type a line number to navigate to."); } - public getResults(searchValue: string): TPromise { + getResults(searchValue: string): TPromise { searchValue = searchValue.trim(); // Remember view state to be able to restore on cancel @@ -233,13 +229,13 @@ export class GotoLineHandler extends QuickOpenHandler { return TPromise.as(new QuickOpenModel([new GotoLineEntry(searchValue, this.editorService, this)])); } - public canRun(): boolean | string { + canRun(): boolean | string { const canRun = !!this.editorService.activeTextEditorWidget; return canRun ? true : nls.localize('cannotRunGotoLine', "Open a text file first to go to a line"); } - public decorateOutline(range: IRange, editor: IEditor, group: IEditorGroup): void { + decorateOutline(range: IRange, editor: IEditor, group: IEditorGroup): void { editor.changeDecorations(changeAccessor => { const deleteDecorations: string[] = []; @@ -284,7 +280,7 @@ export class GotoLineHandler extends QuickOpenHandler { }); } - public clearDecorations(): void { + clearDecorations(): void { if (this.rangeHighlightDecorationId) { this.editorService.visibleControls.forEach(editor => { if (editor.group.id === this.rangeHighlightDecorationId.groupId) { @@ -302,7 +298,7 @@ export class GotoLineHandler extends QuickOpenHandler { } } - public onClose(canceled: boolean): void { + onClose(canceled: boolean): void { // Clear Highlight Decorations if present this.clearDecorations(); @@ -318,7 +314,7 @@ export class GotoLineHandler extends QuickOpenHandler { this.lastKnownEditorViewState = null; } - public getAutoFocus(searchValue: string): IAutoFocus { + getAutoFocus(searchValue: string): IAutoFocus { return { autoFocusFirstEntry: searchValue.trim().length > 0 }; diff --git a/src/vs/workbench/parts/quickopen/browser/gotoSymbolHandler.ts b/src/vs/workbench/parts/quickopen/browser/gotoSymbolHandler.ts index 2b3c830602a..32464070e4e 100644 --- a/src/vs/workbench/parts/quickopen/browser/gotoSymbolHandler.ts +++ b/src/vs/workbench/parts/quickopen/browser/gotoSymbolHandler.ts @@ -32,8 +32,8 @@ export const SCOPE_PREFIX = ':'; export class GotoSymbolAction extends QuickOpenAction { - public static readonly ID = 'workbench.action.gotoSymbol'; - public static readonly LABEL = nls.localize('gotoSymbol', "Go to Symbol in File..."); + static readonly ID = 'workbench.action.gotoSymbol'; + static readonly LABEL = nls.localize('gotoSymbol', "Go to Symbol in File..."); constructor(actionId: string, actionLabel: string, @IQuickOpenService quickOpenService: IQuickOpenService) { super(actionId, actionLabel, GOTO_SYMBOL_PREFIX, quickOpenService); @@ -42,7 +42,7 @@ export class GotoSymbolAction extends QuickOpenAction { class OutlineModel extends QuickOpenModel { - public applyFilter(searchValue: string): void { + applyFilter(searchValue: string): void { // Normalize search let normalizedSearchValue = searchValue; @@ -255,46 +255,46 @@ class SymbolEntry extends EditorQuickOpenEntryGroup { this.handler = handler; } - public getIndex(): number { + getIndex(): number { return this.index; } - public getLabel(): string { + getLabel(): string { return this.name; } - public getAriaLabel(): string { + getAriaLabel(): string { return nls.localize('entryAriaLabel', "{0}, symbols", this.getLabel()); } - public getIcon(): string { + getIcon(): string { return this.icon; } - public getDescription(): string { + getDescription(): string { return this.description; } - public getType(): string { + getType(): string { return this.type; } - public getRange(): IRange { + getRange(): IRange { return this.range; } - public getInput(): IEditorInput { + getInput(): IEditorInput { return this.editorService.activeEditor; } - public getOptions(pinned?: boolean): ITextEditorOptions { + getOptions(pinned?: boolean): ITextEditorOptions { return { selection: this.toSelection(), pinned }; } - public run(mode: Mode, context: IEntryRunContext): boolean { + run(mode: Mode, context: IEntryRunContext): boolean { if (mode === Mode.OPEN) { return this.runOpen(context); } @@ -358,7 +358,7 @@ interface IEditorLineDecoration { export class GotoSymbolHandler extends QuickOpenHandler { - public static readonly ID = 'workbench.picker.filesymbols'; + static readonly ID = 'workbench.picker.filesymbols'; private outlineToModelCache: { [modelId: string]: OutlineModel; }; private rangeHighlightDecorationId: IEditorLineDecoration; @@ -373,7 +373,7 @@ export class GotoSymbolHandler extends QuickOpenHandler { this.outlineToModelCache = {}; } - public getResults(searchValue: string): TPromise { + getResults(searchValue: string): TPromise { searchValue = searchValue.trim(); // Remember view state to be able to restore on cancel @@ -392,7 +392,7 @@ export class GotoSymbolHandler extends QuickOpenHandler { }); } - public getEmptyLabel(searchString: string): string { + getEmptyLabel(searchString: string): string { if (searchString.length > 0) { return nls.localize('noSymbolsMatching', "No symbols matching"); } @@ -400,11 +400,11 @@ export class GotoSymbolHandler extends QuickOpenHandler { return nls.localize('noSymbolsFound', "No symbols found"); } - public getAriaLabel(): string { + getAriaLabel(): string { return nls.localize('gotoSymbolHandlerAriaLabel', "Type to narrow down symbols of the currently active editor."); } - public canRun(): boolean | string { + canRun(): boolean | string { let canRun = false; const activeTextEditorWidget = this.editorService.activeTextEditorWidget; @@ -422,7 +422,7 @@ export class GotoSymbolHandler extends QuickOpenHandler { return canRun ? true : activeTextEditorWidget !== null ? nls.localize('cannotRunGotoSymbolInFile', "No symbol information for the file") : nls.localize('cannotRunGotoSymbol', "Open a text file first to go to a symbol"); } - public getAutoFocus(searchValue: string): IAutoFocus { + getAutoFocus(searchValue: string): IAutoFocus { searchValue = searchValue.trim(); // Remove any type pattern (:) from search value as needed @@ -496,7 +496,7 @@ export class GotoSymbolHandler extends QuickOpenHandler { return TPromise.wrap(null); } - public decorateOutline(fullRange: IRange, startRange: IRange, editor: IEditor, group: IEditorGroup): void { + decorateOutline(fullRange: IRange, startRange: IRange, editor: IEditor, group: IEditorGroup): void { editor.changeDecorations((changeAccessor: IModelDecorationsChangeAccessor) => { const deleteDecorations: string[] = []; @@ -543,7 +543,7 @@ export class GotoSymbolHandler extends QuickOpenHandler { }); } - public clearDecorations(): void { + clearDecorations(): void { if (this.rangeHighlightDecorationId) { this.editorService.visibleControls.forEach(editor => { if (editor.group.id === this.rangeHighlightDecorationId.groupId) { @@ -561,7 +561,7 @@ export class GotoSymbolHandler extends QuickOpenHandler { } } - public onClose(canceled: boolean): void { + onClose(canceled: boolean): void { // Clear Cache this.outlineToModelCache = {}; diff --git a/src/vs/workbench/parts/quickopen/browser/helpHandler.ts b/src/vs/workbench/parts/quickopen/browser/helpHandler.ts index 51881cef7dd..9a0d2482fc9 100644 --- a/src/vs/workbench/parts/quickopen/browser/helpHandler.ts +++ b/src/vs/workbench/parts/quickopen/browser/helpHandler.ts @@ -37,19 +37,19 @@ class HelpEntry extends QuickOpenEntryGroup { this.openOnPreview = openOnPreview; } - public getLabel(): string { + getLabel(): string { return this.prefixLabel; } - public getAriaLabel(): string { + getAriaLabel(): string { return nls.localize('entryAriaLabel', "{0}, picker help", this.getLabel()); } - public getDescription(): string { + getDescription(): string { return this.description; } - public run(mode: Mode, context: IEntryRunContext): boolean { + run(mode: Mode, context: IEntryRunContext): boolean { if (mode === Mode.OPEN || this.openOnPreview) { this.quickOpenService.show(this.prefix); } @@ -60,13 +60,13 @@ class HelpEntry extends QuickOpenEntryGroup { export class HelpHandler extends QuickOpenHandler { - public static readonly ID = 'workbench.picker.help'; + static readonly ID = 'workbench.picker.help'; constructor(@IQuickOpenService private quickOpenService: IQuickOpenService) { super(); } - public getResults(searchValue: string): TPromise { + getResults(searchValue: string): TPromise { searchValue = searchValue.trim(); const registry = (Registry.as(Extensions.Quickopen)); @@ -124,7 +124,7 @@ export class HelpHandler extends QuickOpenHandler { return TPromise.as(new QuickOpenModel([...workbenchScoped, ...editorScoped])); } - public getAutoFocus(searchValue: string): IAutoFocus { + getAutoFocus(searchValue: string): IAutoFocus { searchValue = searchValue.trim(); return { autoFocusFirstEntry: searchValue.length > 0, diff --git a/src/vs/workbench/parts/quickopen/browser/viewPickerHandler.ts b/src/vs/workbench/parts/quickopen/browser/viewPickerHandler.ts index 711590c7b4a..d10d6982577 100644 --- a/src/vs/workbench/parts/quickopen/browser/viewPickerHandler.ts +++ b/src/vs/workbench/parts/quickopen/browser/viewPickerHandler.ts @@ -36,19 +36,19 @@ export class ViewEntry extends QuickOpenEntryGroup { super(); } - public getLabel(): string { + getLabel(): string { return this.label; } - public getCategory(): string { + getCategory(): string { return this.category; } - public getAriaLabel(): string { + getAriaLabel(): string { return nls.localize('entryAriaLabel', "{0}, view picker", this.getLabel()); } - public run(mode: Mode, context: IEntryRunContext): boolean { + run(mode: Mode, context: IEntryRunContext): boolean { if (mode === Mode.OPEN) { return this.runOpen(context); } @@ -67,7 +67,7 @@ export class ViewEntry extends QuickOpenEntryGroup { export class ViewPickerHandler extends QuickOpenHandler { - public static readonly ID = 'workbench.picker.views'; + static readonly ID = 'workbench.picker.views'; constructor( @IViewletService private viewletService: IViewletService, @@ -80,7 +80,7 @@ export class ViewPickerHandler extends QuickOpenHandler { super(); } - public getResults(searchValue: string): TPromise { + getResults(searchValue: string): TPromise { searchValue = searchValue.trim(); const normalizedSearchValueLowercase = stripWildcards(searchValue).toLowerCase(); @@ -179,7 +179,7 @@ export class ViewPickerHandler extends QuickOpenHandler { return viewEntries; } - public getAutoFocus(searchValue: string, context: { model: IModel, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus { + getAutoFocus(searchValue: string, context: { model: IModel, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus { return { autoFocusFirstEntry: !!searchValue || !!context.quickNavigateConfiguration }; @@ -188,8 +188,8 @@ export class ViewPickerHandler extends QuickOpenHandler { export class OpenViewPickerAction extends QuickOpenAction { - public static readonly ID = 'workbench.action.openView'; - public static readonly LABEL = nls.localize('openView', "Open View"); + static readonly ID = 'workbench.action.openView'; + static readonly LABEL = nls.localize('openView', "Open View"); constructor( id: string, @@ -202,8 +202,8 @@ export class OpenViewPickerAction extends QuickOpenAction { export class QuickOpenViewPickerAction extends Action { - public static readonly ID = 'workbench.action.quickOpenView'; - public static readonly LABEL = nls.localize('quickOpenView', "Quick Open View"); + static readonly ID = 'workbench.action.quickOpenView'; + static readonly LABEL = nls.localize('quickOpenView', "Quick Open View"); constructor( id: string, @@ -214,7 +214,7 @@ export class QuickOpenViewPickerAction extends Action { super(id, label); } - public run(): TPromise { + run(): TPromise { const keys = this.keybindingService.lookupKeybindings(this.id); this.quickOpenService.show(VIEW_PICKER_PREFIX, { quickNavigateConfiguration: { keybindings: keys } }); diff --git a/src/vs/workbench/parts/relauncher/electron-browser/relauncher.contribution.ts b/src/vs/workbench/parts/relauncher/electron-browser/relauncher.contribution.ts index cc504052f71..67f0b27804f 100644 --- a/src/vs/workbench/parts/relauncher/electron-browser/relauncher.contribution.ts +++ b/src/vs/workbench/parts/relauncher/electron-browser/relauncher.contribution.ts @@ -5,7 +5,7 @@ 'use strict'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle'; import { IWorkbenchContributionsRegistry, IWorkbenchContribution, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { Registry } from 'vs/platform/registry/common/platform'; import { IWindowsService, IWindowService, IWindowsConfiguration } from 'vs/platform/windows/common/windows'; @@ -30,9 +30,7 @@ interface IConfiguration extends IWindowsConfiguration { files: { useExperimentalFileWatcher: boolean, watcherExclude: object }; } -export class SettingsChangeRelauncher implements IWorkbenchContribution { - - private toDispose: IDisposable[] = []; +export class SettingsChangeRelauncher extends Disposable implements IWorkbenchContribution { private titleBarStyle: 'native' | 'custom'; private nativeTabs: boolean; @@ -59,6 +57,8 @@ export class SettingsChangeRelauncher implements IWorkbenchContribution { @IWorkspaceContextService private contextService: IWorkspaceContextService, @IExtensionService private extensionService: IExtensionService ) { + super(); + const workspace = this.contextService.getWorkspace(); this.firstFolderResource = workspace.folders.length > 0 ? workspace.folders[0].uri : void 0; this.extensionHostRestarter = new RunOnceScheduler(() => this.extensionService.restartExtensionHost(), 10); @@ -70,8 +70,8 @@ export class SettingsChangeRelauncher implements IWorkbenchContribution { } private registerListeners(): void { - this.toDispose.push(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChange(this.configurationService.getValue(), true))); - this.toDispose.push(this.contextService.onDidChangeWorkbenchState(() => setTimeout(() => this.handleWorkbenchState()))); + this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChange(this.configurationService.getValue(), true))); + this._register(this.contextService.onDidChangeWorkbenchState(() => setTimeout(() => this.handleWorkbenchState()))); } private onConfigurationChange(config: IConfiguration, notify: boolean): void { @@ -201,10 +201,6 @@ export class SettingsChangeRelauncher implements IWorkbenchContribution { return void 0; }); } - - public dispose(): void { - this.toDispose = dispose(this.toDispose); - } } const workbenchRegistry = Registry.as(WorkbenchExtensions.Workbench); diff --git a/src/vs/workbench/parts/search/browser/openAnythingHandler.ts b/src/vs/workbench/parts/search/browser/openAnythingHandler.ts index 90652e6854a..7982ff8e2fc 100644 --- a/src/vs/workbench/parts/search/browser/openAnythingHandler.ts +++ b/src/vs/workbench/parts/search/browser/openAnythingHandler.ts @@ -32,7 +32,7 @@ interface ISearchWithRange { export class OpenAnythingHandler extends QuickOpenHandler { - public static readonly ID = 'workbench.picker.anything'; + static readonly ID = 'workbench.picker.anything'; private static readonly LINE_COLON_PATTERN = /[#|:|\(](\d*)([#|:|,](\d*))?\)?$/; @@ -87,7 +87,7 @@ export class OpenAnythingHandler extends QuickOpenHandler { }); } - public getResults(searchValue: string): TPromise { + getResults(searchValue: string): TPromise { this.cancelPendingSearch(); this.isClosed = false; // Treat this call as the handler being in use @@ -164,7 +164,7 @@ export class OpenAnythingHandler extends QuickOpenHandler { return this.hasShortResponseTime() ? promiseFactory() : this.searchDelayer.trigger(promiseFactory, this.includeSymbols ? OpenAnythingHandler.SYMBOL_SEARCH_DELAY : OpenAnythingHandler.FILE_SEARCH_DELAY); } - public hasShortResponseTime(): boolean { + hasShortResponseTime(): boolean { if (!this.includeSymbols) { return this.openFileHandler.hasShortResponseTime(); } @@ -228,22 +228,22 @@ export class OpenAnythingHandler extends QuickOpenHandler { return null; } - public getGroupLabel(): string { + getGroupLabel(): string { return this.includeSymbols ? nls.localize('fileAndTypeResults', "file and symbol results") : nls.localize('fileResults', "file results"); } - public getAutoFocus(searchValue: string): IAutoFocus { + getAutoFocus(searchValue: string): IAutoFocus { return { autoFocusFirstEntry: true }; } - public onOpen(): void { + onOpen(): void { this.openSymbolHandler.onOpen(); this.openFileHandler.onOpen(); } - public onClose(canceled: boolean): void { + onClose(canceled: boolean): void { this.isClosed = true; // Cancel any pending search diff --git a/src/vs/workbench/parts/search/browser/openFileHandler.ts b/src/vs/workbench/parts/search/browser/openFileHandler.ts index 44473ebeb4e..179ea2e6ec3 100644 --- a/src/vs/workbench/parts/search/browser/openFileHandler.ts +++ b/src/vs/workbench/parts/search/browser/openFileHandler.ts @@ -59,41 +59,41 @@ export class FileEntry extends EditorQuickOpenEntry { super(editorService); } - public getLabel(): string { + getLabel(): string { return this.name; } - public getLabelOptions(): IIconLabelValueOptions { + getLabelOptions(): IIconLabelValueOptions { return { extraClasses: getIconClasses(this.modelService, this.modeService, this.resource) }; } - public getAriaLabel(): string { + getAriaLabel(): string { return nls.localize('entryAriaLabel', "{0}, file picker", this.getLabel()); } - public getDescription(): string { + getDescription(): string { return this.description; } - public getIcon(): string { + getIcon(): string { return this.icon; } - public getResource(): URI { + getResource(): URI { return this.resource; } - public setRange(range: IRange): void { + setRange(range: IRange): void { this.range = range; } - public mergeWithEditorHistory(): boolean { + mergeWithEditorHistory(): boolean { return true; } - public getInput(): IResourceInput | EditorInput { + getInput(): IResourceInput | EditorInput { const input: IResourceInput = { resource: this.resource, options: { @@ -132,11 +132,11 @@ export class OpenFileHandler extends QuickOpenHandler { this.queryBuilder = this.instantiationService.createInstance(QueryBuilder); } - public setOptions(options: IOpenFileOptions) { + setOptions(options: IOpenFileOptions) { this.options = options; } - public getResults(searchValue: string, maxSortedResults?: number): TPromise { + getResults(searchValue: string, maxSortedResults?: number): TPromise { const query = prepareQuery(searchValue); // Respond directly to empty search @@ -204,11 +204,11 @@ export class OpenFileHandler extends QuickOpenHandler { return queryOptions; } - public hasShortResponseTime(): boolean { + hasShortResponseTime(): boolean { return this.isCacheLoaded; } - public onOpen(): void { + onOpen(): void { this.cacheState = new CacheState(cacheKey => this.cacheQuery(cacheKey), query => this.searchService.search(query), cacheKey => this.searchService.clearCache(cacheKey), this.cacheState); this.cacheState.load(); } @@ -228,15 +228,15 @@ export class OpenFileHandler extends QuickOpenHandler { return query; } - public get isCacheLoaded(): boolean { + get isCacheLoaded(): boolean { return this.cacheState && this.cacheState.isLoaded; } - public getGroupLabel(): string { + getGroupLabel(): string { return nls.localize('searchResults', "search results"); } - public getAutoFocus(searchValue: string): IAutoFocus { + getAutoFocus(searchValue: string): IAutoFocus { return { autoFocusFirstEntry: true }; @@ -274,21 +274,21 @@ export class CacheState { } } - public get cacheKey(): string { + get cacheKey(): string { return this.loadingPhase === LoadingPhase.Loaded || !this.previous ? this._cacheKey : this.previous.cacheKey; } - public get isLoaded(): boolean { + get isLoaded(): boolean { const isLoaded = this.loadingPhase === LoadingPhase.Loaded; return isLoaded || !this.previous ? isLoaded : this.previous.isLoaded; } - public get isUpdating(): boolean { + get isUpdating(): boolean { const isUpdating = this.loadingPhase === LoadingPhase.Loading; return isUpdating || !this.previous ? isUpdating : this.previous.isUpdating; } - public load(): void { + load(): void { if (this.isUpdating) { return; } @@ -306,7 +306,7 @@ export class CacheState { }); } - public dispose(): void { + dispose(): void { if (this.promise) { this.promise.then(null, () => { }) .then(() => { diff --git a/src/vs/workbench/parts/search/browser/searchView.ts b/src/vs/workbench/parts/search/browser/searchView.ts index 3c7c0ea0c0a..c1af2079000 100644 --- a/src/vs/workbench/parts/search/browser/searchView.ts +++ b/src/vs/workbench/parts/search/browser/searchView.ts @@ -149,9 +149,9 @@ export class SearchView extends Viewlet implements IViewlet, IPanel { this.queryBuilder = this.instantiationService.createInstance(QueryBuilder); this.viewletSettings = this.getMemento(storageService, Scope.WORKSPACE); - this.toUnbind.push(this.fileService.onFileChanges(e => this.onFilesChanged(e))); - this.toUnbind.push(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e))); - this.toUnbind.push(this.contextService.onDidChangeWorkbenchState(() => this.onDidChangeWorkbenchState())); + this._register(this.fileService.onFileChanges(e => this.onFilesChanged(e))); + this._register(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e))); + this._register(this.contextService.onDidChangeWorkbenchState(() => this.onDidChangeWorkbenchState())); this._register(this.searchHistoryService.onDidClearHistory(() => this.clearHistory())); this.selectCurrentMatchEmitter = new Emitter(); @@ -170,7 +170,7 @@ export class SearchView extends Viewlet implements IViewlet, IPanel { public create(parent: HTMLElement): TPromise { super.create(parent); - this.viewModel = this.searchWorkbenchService.searchModel; + this.viewModel = this._register(this.searchWorkbenchService.searchModel); let builder: Builder; $(parent).div({ 'class': 'search-view' @@ -252,10 +252,10 @@ export class SearchView extends Viewlet implements IViewlet, IPanel { let title = nls.localize('searchScope.includes', "files to include"); builder.element('h4', { text: title }); - this.inputPatternIncludes = this.instantiationService.createInstance(PatternInputWidget, builder.getContainer(), this.contextViewService, { + this.inputPatternIncludes = this._register(this.instantiationService.createInstance(PatternInputWidget, builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.includes', 'Search Include Patterns'), history: patternIncludesHistory, - }); + })); this.inputPatternIncludes.setValue(patternIncludes); @@ -274,10 +274,10 @@ export class SearchView extends Viewlet implements IViewlet, IPanel { let title = nls.localize('searchScope.excludes', "files to exclude"); builder.element('h4', { text: title }); - this.inputPatternExcludes = this.instantiationService.createInstance(ExcludePatternInputWidget, builder.getContainer(), this.contextViewService, { + this.inputPatternExcludes = this._register(this.instantiationService.createInstance(ExcludePatternInputWidget, builder.getContainer(), this.contextViewService, { ariaLabel: nls.localize('label.excludes', 'Search Exclude Patterns'), history: patternExclusionsHistory, - }); + })); this.inputPatternExcludes.setValue(patternExclusions); this.inputPatternExcludes.setUseExcludesAndIgnoreFiles(useExcludesAndIgnoreFiles); @@ -311,7 +311,7 @@ export class SearchView extends Viewlet implements IViewlet, IPanel { this.toggleQueryDetails(true, true, true); } - this.toUnbind.push(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event))); + this._register(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event))); return TPromise.as(null); } @@ -343,52 +343,50 @@ export class SearchView extends Viewlet implements IViewlet, IPanel { let searchHistory = history.search || this.viewletSettings['query.searchHistory'] || []; let replaceHistory = history.replace || this.viewletSettings['query.replaceHistory'] || []; - this.searchWidget = this.instantiationService.createInstance(SearchWidget, builder, { + this.searchWidget = this._register(this.instantiationService.createInstance(SearchWidget, builder, { value: contentPattern, isRegex: isRegex, isCaseSensitive: isCaseSensitive, isWholeWords: isWholeWords, searchHistory: searchHistory, replaceHistory: replaceHistory - }); + })); if (this.storageService.getBoolean(SearchView.SHOW_REPLACE_STORAGE_KEY, StorageScope.WORKSPACE, true)) { this.searchWidget.toggleReplace(true); } - this.toUnbind.push(this.searchWidget); + this._register(this.searchWidget.onSearchSubmit((refresh) => this.onQueryChanged(refresh))); + this._register(this.searchWidget.onSearchCancel(() => this.cancelSearch())); + this._register(this.searchWidget.searchInput.onDidOptionChange((viaKeyboard) => this.onQueryChanged(true, viaKeyboard))); - this.toUnbind.push(this.searchWidget.onSearchSubmit((refresh) => this.onQueryChanged(refresh))); - this.toUnbind.push(this.searchWidget.onSearchCancel(() => this.cancelSearch())); - this.toUnbind.push(this.searchWidget.searchInput.onDidOptionChange((viaKeyboard) => this.onQueryChanged(true, viaKeyboard))); - - this.toUnbind.push(this.searchWidget.onReplaceToggled(() => this.onReplaceToggled())); - this.toUnbind.push(this.searchWidget.onReplaceStateChange((state) => { + this._register(this.searchWidget.onReplaceToggled(() => this.onReplaceToggled())); + this._register(this.searchWidget.onReplaceStateChange((state) => { this.viewModel.replaceActive = state; this.tree.refresh(); })); - this.toUnbind.push(this.searchWidget.onReplaceValueChanged((value) => { + this._register(this.searchWidget.onReplaceValueChanged((value) => { this.viewModel.replaceString = this.searchWidget.getReplaceValue(); this.delayedRefresh.trigger(() => this.tree.refresh()); })); - this.toUnbind.push(this.searchWidget.onBlur(() => { + this._register(this.searchWidget.onBlur(() => { this.toggleQueryDetailsButton.focus(); })); - this.toUnbind.push(this.searchWidget.onReplaceAll(() => this.replaceAll())); + this._register(this.searchWidget.onReplaceAll(() => this.replaceAll())); this.trackInputBox(this.searchWidget.searchInputFocusTracker); this.trackInputBox(this.searchWidget.replaceInputFocusTracker); } private trackInputBox(inputFocusTracker: dom.IFocusTracker, contextKey?: IContextKey): void { - this.toUnbind.push(inputFocusTracker.onDidFocus(() => { + this._register(inputFocusTracker.onDidFocus(() => { this.inputBoxFocused.set(true); if (contextKey) { contextKey.set(true); } })); - this.toUnbind.push(inputFocusTracker.onDidBlur(() => { + this._register(inputFocusTracker.onDidBlur(() => { this.inputBoxFocused.set(this.searchWidget.searchInputHasFocus() || this.searchWidget.replaceInputHasFocus() || this.inputPatternIncludes.inputHasFocus() @@ -550,15 +548,11 @@ export class SearchView extends Viewlet implements IViewlet, IPanel { this.results = div; this.results.addClass('show-file-icons'); - let dataSource = this.instantiationService.createInstance(SearchDataSource); - this.toUnbind.push(dataSource); - - let renderer = this.instantiationService.createInstance(SearchRenderer, this.getActionRunner(), this); - this.toUnbind.push(renderer); - + let dataSource = this._register(this.instantiationService.createInstance(SearchDataSource)); + let renderer = this._register(this.instantiationService.createInstance(SearchRenderer, this.getActionRunner(), this)); let dnd = this.instantiationService.createInstance(SimpleFileResourceDragAndDrop, (obj: any) => obj instanceof FileMatch ? obj.resource() : void 0); - this.tree = this.instantiationService.createInstance(WorkbenchTree, div.getHTMLElement(), { + this.tree = this._register(this.instantiationService.createInstance(WorkbenchTree, div.getHTMLElement(), { dataSource: dataSource, renderer: renderer, sorter: new SearchSorter(), @@ -569,10 +563,9 @@ export class SearchView extends Viewlet implements IViewlet, IPanel { }, { ariaLabel: nls.localize('treeAriaLabel', "Search Results"), showLoading: false - }); + })); this.tree.setInput(this.viewModel.searchResult); - this.toUnbind.push(renderer); const searchResultsNavigator = this._register(new TreeResourceNavigator(this.tree, { openOnFocus: true })); this._register(debounceEvent(searchResultsNavigator.openResource, (last, event) => event, 75, true)(options => { @@ -594,7 +587,7 @@ export class SearchView extends Viewlet implements IViewlet, IPanel { treeHasFocus = true; }); - this.toUnbind.push(this.tree.onDidChangeFocus((e: IFocusEvent) => { + this._register(this.tree.onDidChangeFocus((e: IFocusEvent) => { if (treeHasFocus) { const focus = e.focus; this.firstMatchFocused.set(this.tree.getNavigator().first() === focus); @@ -606,7 +599,7 @@ export class SearchView extends Viewlet implements IViewlet, IPanel { } })); - this.toUnbind.push(this.tree.onDidBlur(e => { + this._register(this.tree.onDidBlur(e => { treeHasFocus = false; this.firstMatchFocused.reset(); this.fileMatchOrMatchFocused.reset(); @@ -1573,16 +1566,6 @@ export class SearchView extends Viewlet implements IViewlet, IPanel { public dispose(): void { this.isDisposed = true; - if (this.tree) { - this.tree.dispose(); - } - - this.searchWidget.dispose(); - this.inputPatternIncludes.dispose(); - this.inputPatternExcludes.dispose(); - - this.viewModel.dispose(); - super.dispose(); } } diff --git a/src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts b/src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts index 3497ebd84c6..37c67511039 100644 --- a/src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts +++ b/src/vs/workbench/parts/tasks/electron-browser/task.contribution.ts @@ -119,7 +119,7 @@ class BuildStatusBarItem extends Themable implements IStatusbarItem { } private registerListeners(): void { - this.toUnbind.push(this.contextService.onDidChangeWorkbenchState(() => this.updateStyles())); + this._register(this.contextService.onDidChangeWorkbenchState(() => this.updateStyles())); } protected updateStyles(): void { diff --git a/src/vs/workbench/parts/tasks/electron-browser/terminalTaskSystem.ts b/src/vs/workbench/parts/tasks/electron-browser/terminalTaskSystem.ts index 20524f438ce..6b4da35a3f1 100644 --- a/src/vs/workbench/parts/tasks/electron-browser/terminalTaskSystem.ts +++ b/src/vs/workbench/parts/tasks/electron-browser/terminalTaskSystem.ts @@ -329,9 +329,9 @@ export class TerminalTaskSystem implements ITaskSystem { promise = new TPromise((resolve, reject) => { const problemMatchers = this.resolveMatchers(resolver, task.problemMatchers); let watchingProblemMatcher = new WatchingProblemCollector(problemMatchers, this.markerService, this.modelService); - let toUnbind: IDisposable[] = []; + let toDispose: IDisposable[] = []; let eventCounter: number = 0; - toUnbind.push(watchingProblemMatcher.onDidStateChange((event) => { + toDispose.push(watchingProblemMatcher.onDidStateChange((event) => { if (event.kind === ProblemCollectorEventKind.BackgroundProcessingBegins) { eventCounter++; this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Active, task)); @@ -397,8 +397,8 @@ export class TerminalTaskSystem implements ITaskSystem { if (processStartedSignaled) { this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessEnded, task, exitCode)); } - toUnbind = dispose(toUnbind); - toUnbind = null; + toDispose = dispose(toDispose); + toDispose = null; for (let i = 0; i < eventCounter; i++) { let event = TaskEvent.create(TaskEventKind.Inactive, task); this._onDidStateChange.fire(event); diff --git a/src/vs/workbench/parts/tasks/node/processTaskSystem.ts b/src/vs/workbench/parts/tasks/node/processTaskSystem.ts index 27a7ca1e08b..8ec0759e9e1 100644 --- a/src/vs/workbench/parts/tasks/node/processTaskSystem.ts +++ b/src/vs/workbench/parts/tasks/node/processTaskSystem.ts @@ -233,9 +233,9 @@ export class ProcessTaskSystem implements ITaskSystem { } if (task.isBackground) { let watchingProblemMatcher = new WatchingProblemCollector(this.resolveMatchers(task, task.problemMatchers), this.markerService, this.modelService); - let toUnbind: IDisposable[] = []; + let toDispose: IDisposable[] = []; let eventCounter: number = 0; - toUnbind.push(watchingProblemMatcher.onDidStateChange((event) => { + toDispose.push(watchingProblemMatcher.onDidStateChange((event) => { if (event.kind === ProblemCollectorEventKind.BackgroundProcessingBegins) { eventCounter++; this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Active, task)); @@ -263,8 +263,8 @@ export class ProcessTaskSystem implements ITaskSystem { if (processStartedSignaled) { this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessEnded, task, success.cmdCode)); } - toUnbind = dispose(toUnbind); - toUnbind = null; + toDispose = dispose(toDispose); + toDispose = null; for (let i = 0; i < eventCounter; i++) { this._onDidStateChange.fire(inactiveEvent); } @@ -280,8 +280,8 @@ export class ProcessTaskSystem implements ITaskSystem { }, (error: ErrorData) => { this.childProcessEnded(); watchingProblemMatcher.dispose(); - toUnbind = dispose(toUnbind); - toUnbind = null; + toDispose = dispose(toDispose); + toDispose = null; for (let i = 0; i < eventCounter; i++) { this._onDidStateChange.fire(inactiveEvent); } diff --git a/src/vs/workbench/parts/webview/electron-browser/webviewElement.ts b/src/vs/workbench/parts/webview/electron-browser/webviewElement.ts index 8768f97d9df..d5ee079299b 100644 --- a/src/vs/workbench/parts/webview/electron-browser/webviewElement.ts +++ b/src/vs/workbench/parts/webview/electron-browser/webviewElement.ts @@ -131,7 +131,7 @@ export class WebviewElement extends Disposable { })); } - this._toDispose.push( + this.toDispose.push( addDisposableListener(this._webview, 'console-message', function (e: { level: number; message: string; line: number; sourceId: string; }) { console.log(`[Embedded Page] ${e.message}`); }), @@ -195,7 +195,7 @@ export class WebviewElement extends Disposable { this._webviewFindWidget = this._register(instantiationService.createInstance(WebviewFindWidget, this)); this.style(this._themeService.getTheme()); - this._themeService.onThemeChange(this.style, this, this._toDispose); + this._themeService.onThemeChange(this.style, this, this.toDispose); } public mountTo(parent: HTMLElement) { diff --git a/src/vs/workbench/services/activity/browser/activityService.ts b/src/vs/workbench/services/activity/browser/activityService.ts index c45b8556c40..27bbe40af63 100644 --- a/src/vs/workbench/services/activity/browser/activityService.ts +++ b/src/vs/workbench/services/activity/browser/activityService.ts @@ -21,7 +21,7 @@ export class ActivityService implements IActivityService { @IPanelService private panelService: IPanelService ) { } - public showActivity(compositeOrActionId: string, badge: IBadge, clazz?: string, priority?: number): IDisposable { + showActivity(compositeOrActionId: string, badge: IBadge, clazz?: string, priority?: number): IDisposable { if (this.panelService.getPanels().filter(p => p.id === compositeOrActionId).length) { return this.panelPart.showActivity(compositeOrActionId, badge, clazz); } diff --git a/src/vs/workbench/services/activity/common/activity.ts b/src/vs/workbench/services/activity/common/activity.ts index 6167a730512..27513b65417 100644 --- a/src/vs/workbench/services/activity/common/activity.ts +++ b/src/vs/workbench/services/activity/common/activity.ts @@ -13,19 +13,19 @@ export interface IBadge { } export class BaseBadge implements IBadge { - public descriptorFn: (args: any) => string; + descriptorFn: (args: any) => string; constructor(descriptorFn: (args: any) => string) { this.descriptorFn = descriptorFn; } - public getDescription(): string { + getDescription(): string { return this.descriptorFn(null); } } export class NumberBadge extends BaseBadge { - public number: number; + number: number; constructor(number: number, descriptorFn: (args: any) => string) { super(descriptorFn); @@ -33,13 +33,13 @@ export class NumberBadge extends BaseBadge { this.number = number; } - public getDescription(): string { + getDescription(): string { return this.descriptorFn(this.number); } } export class TextBadge extends BaseBadge { - public text: string; + text: string; constructor(text: string, descriptorFn: (args: any) => string) { super(descriptorFn); diff --git a/src/vs/workbench/services/backup/node/backupFileService.ts b/src/vs/workbench/services/backup/node/backupFileService.ts index 8b2c585dc49..a27a897af10 100644 --- a/src/vs/workbench/services/backup/node/backupFileService.ts +++ b/src/vs/workbench/services/backup/node/backupFileService.ts @@ -32,10 +32,9 @@ export interface IBackupFilesModel { export class BackupSnapshot implements ITextSnapshot { private preambleHandled: boolean; - constructor(private snapshot: ITextSnapshot, private preamble: string) { - } + constructor(private snapshot: ITextSnapshot, private preamble: string) { } - public read(): string { + read(): string { let value = this.snapshot.read(); if (!this.preambleHandled) { this.preambleHandled = true; @@ -54,7 +53,7 @@ export class BackupSnapshot implements ITextSnapshot { export class BackupFilesModel implements IBackupFilesModel { private cache: { [resource: string]: number /* version ID */ } = Object.create(null); - public resolve(backupRoot: string): TPromise { + resolve(backupRoot: string): TPromise { return pfs.readDirsInDir(backupRoot).then(backupSchemas => { // For all supported schemas @@ -74,15 +73,15 @@ export class BackupFilesModel implements IBackupFilesModel { }).then(() => this, error => this); } - public add(resource: Uri, versionId = 0): void { + add(resource: Uri, versionId = 0): void { this.cache[resource.toString()] = versionId; } - public count(): number { + count(): number { return Object.keys(this.cache).length; } - public has(resource: Uri, versionId?: number): boolean { + has(resource: Uri, versionId?: number): boolean { const cachedVersionId = this.cache[resource.toString()]; if (typeof cachedVersionId !== 'number') { return false; // unknown resource @@ -95,15 +94,15 @@ export class BackupFilesModel implements IBackupFilesModel { return true; } - public get(): Uri[] { + get(): Uri[] { return Object.keys(this.cache).map(k => Uri.parse(k)); } - public remove(resource: Uri): void { + remove(resource: Uri): void { delete this.cache[resource.toString()]; } - public clear(): void { + clear(): void { this.cache = Object.create(null); } } @@ -112,7 +111,7 @@ export class BackupFileService implements IBackupFileService { private static readonly META_MARKER = '\n'; - public _serviceBrand: any; + _serviceBrand: any; private backupWorkspacePath: string; @@ -130,7 +129,7 @@ export class BackupFileService implements IBackupFileService { this.initialize(backupWorkspacePath); } - public initialize(backupWorkspacePath: string): void { + initialize(backupWorkspacePath: string): void { this.backupWorkspacePath = backupWorkspacePath; this.ready = this.init(); @@ -142,13 +141,13 @@ export class BackupFileService implements IBackupFileService { return model.resolve(this.backupWorkspacePath); } - public hasBackups(): TPromise { + hasBackups(): TPromise { return this.ready.then(model => { return model.count() > 0; }); } - public loadBackupResource(resource: Uri): TPromise { + loadBackupResource(resource: Uri): TPromise { return this.ready.then(model => { // Return directly if we have a known backup with that resource @@ -161,7 +160,7 @@ export class BackupFileService implements IBackupFileService { }); } - public backupResource(resource: Uri, content: ITextSnapshot, versionId?: number): TPromise { + backupResource(resource: Uri, content: ITextSnapshot, versionId?: number): TPromise { if (this.isShuttingDown) { return TPromise.as(void 0); } @@ -181,7 +180,7 @@ export class BackupFileService implements IBackupFileService { }); } - public discardResourceBackup(resource: Uri): TPromise { + discardResourceBackup(resource: Uri): TPromise { return this.ready.then(model => { const backupResource = this.toBackupResource(resource); @@ -191,7 +190,7 @@ export class BackupFileService implements IBackupFileService { }); } - public discardAllWorkspaceBackups(): TPromise { + discardAllWorkspaceBackups(): TPromise { this.isShuttingDown = true; return this.ready.then(model => { @@ -199,7 +198,7 @@ export class BackupFileService implements IBackupFileService { }); } - public getWorkspaceFileBackups(): TPromise { + getWorkspaceFileBackups(): TPromise { return this.ready.then(model => { const readPromises: TPromise[] = []; @@ -213,7 +212,7 @@ export class BackupFileService implements IBackupFileService { }); } - public resolveBackupContent(backup: Uri): TPromise { + resolveBackupContent(backup: Uri): TPromise { return this.fileService.resolveStreamContent(backup, BACKUP_FILE_RESOLVE_OPTIONS).then(content => { // Add a filter method to filter out everything until the meta marker @@ -236,7 +235,7 @@ export class BackupFileService implements IBackupFileService { }); } - public toBackupResource(resource: Uri): Uri { + toBackupResource(resource: Uri): Uri { return Uri.file(path.join(this.backupWorkspacePath, resource.scheme, this.hashPath(resource))); } @@ -247,7 +246,7 @@ export class BackupFileService implements IBackupFileService { export class InMemoryBackupFileService implements IBackupFileService { - public _serviceBrand: any; + _serviceBrand: any; private backups: Map = new Map(); diff --git a/src/vs/workbench/services/contextview/electron-browser/contextmenuService.ts b/src/vs/workbench/services/contextview/electron-browser/contextmenuService.ts index 5c323ca2409..8832ac16a31 100644 --- a/src/vs/workbench/services/contextview/electron-browser/contextmenuService.ts +++ b/src/vs/workbench/services/contextview/electron-browser/contextmenuService.ts @@ -12,30 +12,29 @@ import * as dom from 'vs/base/browser/dom'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; - import { remote, webFrame } from 'electron'; import { unmnemonicLabel } from 'vs/base/common/labels'; import { Event, Emitter } from 'vs/base/common/event'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IContextMenuDelegate, ContextSubMenu, IEvent } from 'vs/base/browser/contextmenu'; +import { Disposable } from 'vs/base/common/lifecycle'; -export class ContextMenuService implements IContextMenuService { +export class ContextMenuService extends Disposable implements IContextMenuService { - public _serviceBrand: any; - private _onDidContextMenu = new Emitter(); + _serviceBrand: any; + + private _onDidContextMenu = this._register(new Emitter()); + get onDidContextMenu(): Event { return this._onDidContextMenu.event; } constructor( @INotificationService private notificationService: INotificationService, @ITelemetryService private telemetryService: ITelemetryService, @IKeybindingService private keybindingService: IKeybindingService ) { + super(); } - public get onDidContextMenu(): Event { - return this._onDidContextMenu.event; - } - - public showContextMenu(delegate: IContextMenuDelegate): void { + showContextMenu(delegate: IContextMenuDelegate): void { delegate.getActions().then(actions => { if (!actions.length) { return TPromise.as(null); diff --git a/src/vs/workbench/services/crashReporter/electron-browser/crashReporterService.ts b/src/vs/workbench/services/crashReporter/electron-browser/crashReporterService.ts index 627c221fa6c..2b63e252efb 100644 --- a/src/vs/workbench/services/crashReporter/electron-browser/crashReporterService.ts +++ b/src/vs/workbench/services/crashReporter/electron-browser/crashReporterService.ts @@ -54,7 +54,7 @@ export const NullCrashReporterService: ICrashReporterService = { export class CrashReporterService implements ICrashReporterService { - public _serviceBrand: any; + _serviceBrand: any; private options: Electron.CrashReporterStartOptions; private isEnabled: boolean; @@ -114,7 +114,7 @@ export class CrashReporterService implements ICrashReporterService { return submitURL; } - public getChildProcessStartOptions(name: string): Electron.CrashReporterStartOptions { + getChildProcessStartOptions(name: string): Electron.CrashReporterStartOptions { // Experimental crash reporting support for child processes on Mac only for now if (this.isEnabled && isMacintosh) { diff --git a/src/vs/workbench/services/dialogs/electron-browser/dialogService.ts b/src/vs/workbench/services/dialogs/electron-browser/dialogService.ts index df621fb08e1..610c5ef1946 100644 --- a/src/vs/workbench/services/dialogs/electron-browser/dialogService.ts +++ b/src/vs/workbench/services/dialogs/electron-browser/dialogService.ts @@ -31,14 +31,13 @@ interface IMassagedMessageBoxOptions { export class DialogService implements IDialogService { - public _serviceBrand: any; + _serviceBrand: any; constructor( @IWindowService private windowService: IWindowService - ) { - } + ) { } - public confirm(confirmation: IConfirmation): TPromise { + confirm(confirmation: IConfirmation): TPromise { const { options, buttonIndexMap } = this.massageMessageBoxOptions(this.getConfirmOptions(confirmation)); return this.windowService.showMessageBox(options).then(result => { @@ -86,7 +85,7 @@ export class DialogService implements IDialogService { return opts; } - public show(severity: Severity, message: string, buttons: string[], dialogOptions?: IDialogOptions): TPromise { + show(severity: Severity, message: string, buttons: string[], dialogOptions?: IDialogOptions): TPromise { const { options, buttonIndexMap } = this.massageMessageBoxOptions({ message, buttons, diff --git a/src/vs/workbench/services/files/electron-browser/encoding.ts b/src/vs/workbench/services/files/electron-browser/encoding.ts index c1b99f40985..2c9e88b3830 100644 --- a/src/vs/workbench/services/files/electron-browser/encoding.ts +++ b/src/vs/workbench/services/files/electron-browser/encoding.ts @@ -14,7 +14,7 @@ import { join, extname } from 'path'; import { ITextResourceConfigurationService } from 'vs/editor/common/services/resourceConfiguration'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; export interface IEncodingOverride { parent?: uri; @@ -26,9 +26,8 @@ export interface IEncodingOverride { // service and then ideally be passed in as option to the file service // the file service should talk about string | Buffer for reading and writing and only convert // to strings if a encoding is provided -export class ResourceEncodings implements IResourceEncodings { +export class ResourceEncodings extends Disposable implements IResourceEncodings { private encodingOverride: IEncodingOverride[]; - private toDispose: IDisposable[]; constructor( private textResourceConfigurationService: ITextResourceConfigurationService, @@ -36,8 +35,9 @@ export class ResourceEncodings implements IResourceEncodings { private contextService: IWorkspaceContextService, encodingOverride?: IEncodingOverride[] ) { + super(); + this.encodingOverride = encodingOverride || this.getEncodingOverrides(); - this.toDispose = []; this.registerListeners(); } @@ -45,12 +45,12 @@ export class ResourceEncodings implements IResourceEncodings { private registerListeners(): void { // Workspace Folder Change - this.toDispose.push(this.contextService.onDidChangeWorkspaceFolders(() => { + this._register(this.contextService.onDidChangeWorkspaceFolders(() => { this.encodingOverride = this.getEncodingOverrides(); })); } - public getReadEncoding(resource: uri, options: IResolveContentOptions, detected: encoding.IDetectedEncodingResult): string { + getReadEncoding(resource: uri, options: IResolveContentOptions, detected: encoding.IDetectedEncodingResult): string { let preferredEncoding: string; // Encoding passed in as option @@ -79,7 +79,7 @@ export class ResourceEncodings implements IResourceEncodings { return this.getEncodingForResource(resource, preferredEncoding); } - public getWriteEncoding(resource: uri, preferredEncoding?: string): string { + getWriteEncoding(resource: uri, preferredEncoding?: string): string { return this.getEncodingForResource(resource, preferredEncoding); } @@ -138,8 +138,4 @@ export class ResourceEncodings implements IResourceEncodings { return null; } - - public dispose(): void { - this.toDispose = dispose(this.toDispose); - } } \ No newline at end of file diff --git a/src/vs/workbench/services/files/electron-browser/fileService.ts b/src/vs/workbench/services/files/electron-browser/fileService.ts index e6304e771c5..0d7a3655715 100644 --- a/src/vs/workbench/services/files/electron-browser/fileService.ts +++ b/src/vs/workbench/services/files/electron-browser/fileService.ts @@ -22,7 +22,7 @@ import { nfcall, ThrottledDelayer, asWinJSImport } from 'vs/base/common/async'; import uri from 'vs/base/common/uri'; import * as nls from 'vs/nls'; import { isWindows, isLinux, isMacintosh } from 'vs/base/common/platform'; -import { dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; +import { IDisposable, toDisposable, Disposable } from 'vs/base/common/lifecycle'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import * as pfs from 'vs/base/node/pfs'; import * as encoding from 'vs/base/node/encoding'; @@ -76,9 +76,9 @@ export interface IFileServiceTestOptions { encodingOverride?: IEncodingOverride[]; } -export class FileService implements IFileService { +export class FileService extends Disposable implements IFileService { - public _serviceBrand: any; + _serviceBrand: any; private static readonly FS_EVENT_DELAY = 50; // aggregate and only emit events when changes have stopped for this duration (in ms) private static readonly FS_REWATCH_DELAY = 300; // delay to rewatch a file that was renamed or deleted (in ms) @@ -89,11 +89,14 @@ export class FileService implements IFileService { private static readonly ENOSPC_ERROR = 'ENOSPC'; private static readonly ENOSPC_ERROR_IGNORE_KEY = 'ignoreEnospcError'; - protected readonly _onFileChanges: Emitter; - protected readonly _onAfterOperation: Emitter; - protected readonly _onDidChangeFileSystemProviderRegistrations = new Emitter(); + protected readonly _onFileChanges: Emitter = this._register(new Emitter()); + get onFileChanges(): Event { return this._onFileChanges.event; } - protected toDispose: IDisposable[]; + protected readonly _onAfterOperation: Emitter = this._register(new Emitter()); + get onAfterOperation(): Event { return this._onAfterOperation.event; } + + protected readonly _onDidChangeFileSystemProviderRegistrations = this._register(new Emitter()); + get onDidChangeFileSystemProviderRegistrations(): Event { return this._onDidChangeFileSystemProviderRegistrations.event; } private activeWorkspaceFileChangeWatcher: IDisposable; private activeFileChangesWatchers: ResourceMap; @@ -112,13 +115,7 @@ export class FileService implements IFileService { private notificationService: INotificationService, private options: IFileServiceTestOptions = Object.create(null) ) { - this.toDispose = []; - - this._onFileChanges = new Emitter(); - this.toDispose.push(this._onFileChanges); - - this._onAfterOperation = new Emitter(); - this.toDispose.push(this._onAfterOperation); + super(); this.activeFileChangesWatchers = new ResourceMap(); this.fileChangesWatchDelayer = new ThrottledDelayer(FileService.FS_EVENT_DELAY); @@ -129,7 +126,7 @@ export class FileService implements IFileService { this.registerListeners(); } - public get encoding(): ResourceEncodings { + get encoding(): ResourceEncodings { return this._encoding; } @@ -141,7 +138,7 @@ export class FileService implements IFileService { }); // Workbench State Change - this.toDispose.push(this.contextService.onDidChangeWorkbenchState(() => { + this._register(this.contextService.onDidChangeWorkbenchState(() => { if (this.lifecycleService.phase >= LifecyclePhase.Running) { this.setupFileWatching(); } @@ -195,14 +192,6 @@ export class FileService implements IFileService { } } - public get onFileChanges(): Event { - return this._onFileChanges.event; - } - - public get onAfterOperation(): Event { - return this._onAfterOperation.event; - } - private setupFileWatching(): void { // dispose old if any @@ -240,30 +229,28 @@ export class FileService implements IFileService { } } - public readonly onDidChangeFileSystemProviderRegistrations: Event = this._onDidChangeFileSystemProviderRegistrations.event; - - public registerProvider(scheme: string, provider: IFileSystemProvider): IDisposable { + registerProvider(scheme: string, provider: IFileSystemProvider): IDisposable { throw new Error('not implemented'); } - public canHandleResource(resource: uri): boolean { + canHandleResource(resource: uri): boolean { return resource.scheme === Schemas.file; } - public resolveFile(resource: uri, options?: IResolveFileOptions): TPromise { + resolveFile(resource: uri, options?: IResolveFileOptions): TPromise { return this.resolve(resource, options); } - public resolveFiles(toResolve: { resource: uri, options?: IResolveFileOptions }[]): TPromise { + resolveFiles(toResolve: { resource: uri, options?: IResolveFileOptions }[]): TPromise { return TPromise.join(toResolve.map(resourceAndOptions => this.resolve(resourceAndOptions.resource, resourceAndOptions.options) .then(stat => ({ stat, success: true }), error => ({ stat: void 0, success: false })))); } - public existsFile(resource: uri): TPromise { + existsFile(resource: uri): TPromise { return this.resolveFile(resource).then(() => true, () => false); } - public resolveContent(resource: uri, options?: IResolveContentOptions): TPromise { + resolveContent(resource: uri, options?: IResolveContentOptions): TPromise { return this.resolveStreamContent(resource, options).then(streamContent => { return new TPromise((resolve, reject) => { @@ -286,7 +273,7 @@ export class FileService implements IFileService { }); } - public resolveStreamContent(resource: uri, options?: IResolveContentOptions): TPromise { + resolveStreamContent(resource: uri, options?: IResolveContentOptions): TPromise { // Guard early against attempts to resolve an invalid file path if (resource.scheme !== Schemas.file || !resource.fsPath) { @@ -577,7 +564,7 @@ export class FileService implements IFileService { }); } - public updateContent(resource: uri, value: string | ITextSnapshot, options: IUpdateContentOptions = Object.create(null)): TPromise { + updateContent(resource: uri, value: string | ITextSnapshot, options: IUpdateContentOptions = Object.create(null)): TPromise { if (options.writeElevated) { return this.doUpdateContentElevated(resource, value, options); } @@ -739,7 +726,7 @@ export class FileService implements IFileService { }); } - public createFile(resource: uri, content: string = '', options: ICreateFileOptions = Object.create(null)): TPromise { + createFile(resource: uri, content: string = '', options: ICreateFileOptions = Object.create(null)): TPromise { const absolutePath = this.toAbsolutePath(resource); let checkFilePromise: TPromise; @@ -770,7 +757,7 @@ export class FileService implements IFileService { }); } - public createFolder(resource: uri): TPromise { + createFolder(resource: uri): TPromise { // 1.) Create folder const absolutePath = this.toAbsolutePath(resource); @@ -849,11 +836,11 @@ export class FileService implements IFileService { )); } - public moveFile(source: uri, target: uri, overwrite?: boolean): TPromise { + moveFile(source: uri, target: uri, overwrite?: boolean): TPromise { return this.moveOrCopyFile(source, target, false, overwrite); } - public copyFile(source: uri, target: uri, overwrite?: boolean): TPromise { + copyFile(source: uri, target: uri, overwrite?: boolean): TPromise { return this.moveOrCopyFile(source, target, true, overwrite); } @@ -920,7 +907,7 @@ export class FileService implements IFileService { }); } - public del(resource: uri, options?: { useTrash?: boolean, recursive?: boolean }): TPromise { + del(resource: uri, options?: { useTrash?: boolean, recursive?: boolean }): TPromise { if (options && options.useTrash) { return this.doMoveItemToTrash(resource); } @@ -1000,7 +987,7 @@ export class FileService implements IFileService { }); } - public watchFileChanges(resource: uri): void { + watchFileChanges(resource: uri): void { assert.ok(resource && resource.scheme === Schemas.file, `Invalid resource for watching: ${resource}`); // Create or get watcher for provided path @@ -1089,7 +1076,7 @@ export class FileService implements IFileService { }); } - public unwatchFileChanges(resource: uri): void { + unwatchFileChanges(resource: uri): void { const watcher = this.activeFileChangesWatchers.get(resource); if (watcher) { watcher.close(); @@ -1097,8 +1084,8 @@ export class FileService implements IFileService { } } - public dispose(): void { - this.toDispose = dispose(this.toDispose); + dispose(): void { + super.dispose(); if (this.activeWorkspaceFileChangeWatcher) { this.activeWorkspaceFileChangeWatcher.dispose(); @@ -1144,7 +1131,7 @@ export class StatResolver { this.etag = etag(size, mtime); } - public resolve(options: IResolveFileOptions): TPromise { + resolve(options: IResolveFileOptions): TPromise { // General Data const fileStat: IFileStat = { diff --git a/src/vs/workbench/services/files/electron-browser/remoteFileService.ts b/src/vs/workbench/services/files/electron-browser/remoteFileService.ts index 0a4ad3073ab..3f2e2a1806f 100644 --- a/src/vs/workbench/services/files/electron-browser/remoteFileService.ts +++ b/src/vs/workbench/services/files/electron-browser/remoteFileService.ts @@ -6,7 +6,7 @@ import { posix } from 'path'; import { flatten, isFalsyOrEmpty } from 'vs/base/common/arrays'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle'; import { TernarySearchTree, keys } from 'vs/base/common/map'; import { Schemas } from 'vs/base/common/network'; import URI from 'vs/base/common/uri'; @@ -86,9 +86,8 @@ export function toDeepIFileStat(provider: IFileSystemProvider, tuple: [URI, ISta }); } -class WorkspaceWatchLogic { +class WorkspaceWatchLogic extends Disposable { - private _disposables: IDisposable[] = []; private _watches = new Map(); constructor( @@ -96,9 +95,11 @@ class WorkspaceWatchLogic { @IConfigurationService private _configurationService: IConfigurationService, @IWorkspaceContextService private _contextService: IWorkspaceContextService, ) { + super(); + this._refresh(); - this._disposables.push(this._contextService.onDidChangeWorkspaceFolders(e => { + this._register(this._contextService.onDidChangeWorkspaceFolders(e => { for (const removed of e.removed) { this._unwatchWorkspace(removed.uri); } @@ -106,10 +107,10 @@ class WorkspaceWatchLogic { this._watchWorkspace(added.uri); } })); - this._disposables.push(this._contextService.onDidChangeWorkbenchState(e => { + this._register(this._contextService.onDidChangeWorkbenchState(e => { this._refresh(); })); - this._disposables.push(this._configurationService.onDidChangeConfiguration(e => { + this._register(this._configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('files.watcherExclude')) { this._refresh(); } @@ -118,7 +119,7 @@ class WorkspaceWatchLogic { dispose(): void { this._unwatchWorkspaces(); - this._disposables = dispose(this._disposables); + super.dispose(); } private _refresh(): void { @@ -184,7 +185,7 @@ export class RemoteFileService extends FileService { this._provider = new Map(); this._lastKnownSchemes = JSON.parse(this._storageService.get('remote_schemes', undefined, '[]')); - this.toDispose.push(new WorkspaceWatchLogic(this, configurationService, contextService)); + this._register(new WorkspaceWatchLogic(this, configurationService, contextService)); } registerProvider(scheme: string, provider: IFileSystemProvider): IDisposable { @@ -650,7 +651,7 @@ export class RemoteFileService extends FileService { private _activeWatches = new Map, count: number }>(); - public watchFileChanges(resource: URI, opts?: IWatchOptions): void { + watchFileChanges(resource: URI, opts?: IWatchOptions): void { if (resource.scheme === Schemas.file) { return super.watchFileChanges(resource); } @@ -676,7 +677,7 @@ export class RemoteFileService extends FileService { }); } - public unwatchFileChanges(resource: URI): void { + unwatchFileChanges(resource: URI): void { if (resource.scheme === Schemas.file) { return super.unwatchFileChanges(resource); } diff --git a/src/vs/workbench/services/history/electron-browser/history.ts b/src/vs/workbench/services/history/electron-browser/history.ts index 10b941f25af..0cb907bc631 100644 --- a/src/vs/workbench/services/history/electron-browser/history.ts +++ b/src/vs/workbench/services/history/electron-browser/history.ts @@ -16,7 +16,7 @@ import { IHistoryService } from 'vs/workbench/services/history/common/history'; import { FileChangesEvent, IFileService, FileChangeType, FILES_EXCLUDE_CONFIG } from 'vs/platform/files/common/files'; import { Selection } from 'vs/editor/common/core/selection'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { Registry } from 'vs/platform/registry/common/platform'; @@ -49,15 +49,15 @@ export class TextEditorState { } : void 0; } - public get editorInput(): IEditorInput { + get editorInput(): IEditorInput { return this._editorInput; } - public get selection(): ITextEditorSelection { + get selection(): ITextEditorSelection { return this.textEditorSelection; } - public justifiesNewPushState(other: TextEditorState, event?: ICursorPositionChangedEvent): boolean { + justifiesNewPushState(other: TextEditorState, event?: ICursorPositionChangedEvent): boolean { if (event && event.source === 'api') { return true; // always let API source win (e.g. "Go to definition" should add a history entry) } @@ -97,17 +97,15 @@ interface IRecentlyClosedFile { index: number; } -export class HistoryService implements IHistoryService { +export class HistoryService extends Disposable implements IHistoryService { - public _serviceBrand: any; + _serviceBrand: any; private static readonly STORAGE_KEY = 'history.entries'; private static readonly MAX_HISTORY_ITEMS = 200; private static readonly MAX_STACK_ITEMS = 20; private static readonly MAX_RECENTLY_CLOSED_EDITORS = 20; - private toUnbind: IDisposable[]; - private activeEditorListeners: IDisposable[]; private lastActiveEditor: IEditorIdentifier; @@ -135,7 +133,8 @@ export class HistoryService implements IHistoryService { @IWindowsService private windowService: IWindowsService, @IInstantiationService private instantiationService: IInstantiationService, ) { - this.toUnbind = []; + super(); + this.activeEditorListeners = []; this.fileInputFactory = Registry.as(EditorInputExtensions.EditorInputFactories).getFileInputFactory(); @@ -145,11 +144,11 @@ export class HistoryService implements IHistoryService { this.stack = []; this.recentlyClosedFiles = []; this.loaded = false; - this.resourceFilter = instantiationService.createInstance( + this.resourceFilter = this._register(instantiationService.createInstance( ResourceGlobMatcher, (root: URI) => this.getExcludes(root), (event: IConfigurationChangeEvent) => event.affectsConfiguration(FILES_EXCLUDE_CONFIG) || event.affectsConfiguration('search.exclude') - ); + )); this.registerListeners(); } @@ -161,12 +160,12 @@ export class HistoryService implements IHistoryService { } private registerListeners(): void { - this.toUnbind.push(this.editorService.onDidActiveEditorChange(() => this.onActiveEditorChanged())); - this.toUnbind.push(this.editorService.onDidOpenEditorFail(event => this.remove(event.editor))); - this.toUnbind.push(this.editorService.onDidCloseEditor(event => this.onEditorClosed(event))); - this.toUnbind.push(this.lifecycleService.onShutdown(reason => this.saveHistory())); - this.toUnbind.push(this.fileService.onFileChanges(event => this.onFileChanges(event))); - this.toUnbind.push(this.resourceFilter.onExpressionChange(() => this.handleExcludesChange())); + this._register(this.editorService.onDidActiveEditorChange(() => this.onActiveEditorChanged())); + this._register(this.editorService.onDidOpenEditorFail(event => this.remove(event.editor))); + this._register(this.editorService.onDidCloseEditor(event => this.onEditorClosed(event))); + this._register(this.lifecycleService.onShutdown(reason => this.saveHistory())); + this._register(this.fileService.onFileChanges(event => this.onFileChanges(event))); + this._register(this.resourceFilter.onExpressionChange(() => this.handleExcludesChange())); } private onActiveEditorChanged(): void { @@ -236,7 +235,7 @@ export class HistoryService implements IHistoryService { } } - public reopenLastClosedEditor(): void { + reopenLastClosedEditor(): void { this.ensureHistoryLoaded(); let lastClosedFile = this.recentlyClosedFiles.pop(); @@ -249,7 +248,7 @@ export class HistoryService implements IHistoryService { } } - public forward(acrossEditors?: boolean): void { + forward(acrossEditors?: boolean): void { if (this.stack.length > this.index + 1) { if (acrossEditors) { this.doForwardAcrossEditors(); @@ -287,7 +286,7 @@ export class HistoryService implements IHistoryService { } } - public back(acrossEditors?: boolean): void { + back(acrossEditors?: boolean): void { if (this.index > 0) { if (acrossEditors) { this.doBackAcrossEditors(); @@ -297,7 +296,7 @@ export class HistoryService implements IHistoryService { } } - public last(): void { + last(): void { if (this.lastIndex === -1) { this.back(); } else { @@ -329,7 +328,7 @@ export class HistoryService implements IHistoryService { } } - public clear(): void { + clear(): void { this.ensureHistoryLoaded(); this.index = -1; @@ -421,9 +420,9 @@ export class HistoryService implements IHistoryService { this.removeExcludedFromHistory(); } - public remove(input: IEditorInput | IResourceInput): void; - public remove(input: FileChangesEvent): void; - public remove(arg1: IEditorInput | IResourceInput | FileChangesEvent): void { + remove(input: IEditorInput | IResourceInput): void; + remove(input: FileChangesEvent): void; + remove(arg1: IEditorInput | IResourceInput | FileChangesEvent): void { this.removeFromHistory(arg1); this.removeFromStack(arg1); this.removeFromRecentlyClosedFiles(arg1); @@ -502,7 +501,7 @@ export class HistoryService implements IHistoryService { this.add(editor.input); } - public add(input: IEditorInput, selection?: ITextEditorSelection): void { + add(input: IEditorInput, selection?: ITextEditorSelection): void { if (!this.navigatingInStack) { this.addOrReplaceInStack(input, selection); } @@ -667,7 +666,7 @@ export class HistoryService implements IHistoryService { return resourceInput && resourceInput.resource.toString() === resource.toString(); } - public getHistory(): (IEditorInput | IResourceInput)[] { + getHistory(): (IEditorInput | IResourceInput)[] { this.ensureHistoryLoaded(); return this.history.slice(0); @@ -748,7 +747,7 @@ export class HistoryService implements IHistoryService { }).filter(input => !!input); } - public getLastActiveWorkspaceRoot(schemeFilter?: string): URI { + getLastActiveWorkspaceRoot(schemeFilter?: string): URI { // No Folder: return early const folders = this.contextService.getWorkspace().folders; @@ -796,7 +795,7 @@ export class HistoryService implements IHistoryService { return void 0; } - public getLastActiveFile(): URI { + getLastActiveFile(): URI { const history = this.getHistory(); for (let i = 0; i < history.length; i++) { let resource: URI; @@ -815,8 +814,4 @@ export class HistoryService implements IHistoryService { return void 0; } - - public dispose(): void { - this.toUnbind = dispose(this.toUnbind); - } } diff --git a/src/vs/workbench/services/notification/common/notificationService.ts b/src/vs/workbench/services/notification/common/notificationService.ts index 52fbfe0638c..bd0daafa022 100644 --- a/src/vs/workbench/services/notification/common/notificationService.ts +++ b/src/vs/workbench/services/notification/common/notificationService.ts @@ -7,31 +7,22 @@ import { INotificationService, INotification, INotificationHandle, Severity, NotificationMessage, INotificationActions, IPromptChoice } from 'vs/platform/notification/common/notification'; import { INotificationsModel, NotificationsModel } from 'vs/workbench/common/notifications'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { dispose, Disposable } from 'vs/base/common/lifecycle'; import { TPromise } from 'vs/base/common/winjs.base'; import { Action } from 'vs/base/common/actions'; import { once } from 'vs/base/common/event'; -export class NotificationService implements INotificationService { +export class NotificationService extends Disposable implements INotificationService { - public _serviceBrand: any; + _serviceBrand: any; - private _model: INotificationsModel; - private toDispose: IDisposable[]; + private _model: INotificationsModel = this._register(new NotificationsModel()); - constructor() { - this.toDispose = []; - - const model = new NotificationsModel(); - this.toDispose.push(model); - this._model = model; - } - - public get model(): INotificationsModel { + get model(): INotificationsModel { return this._model; } - public info(message: NotificationMessage | NotificationMessage[]): void { + info(message: NotificationMessage | NotificationMessage[]): void { if (Array.isArray(message)) { message.forEach(m => this.info(m)); @@ -41,7 +32,7 @@ export class NotificationService implements INotificationService { this.model.notify({ severity: Severity.Info, message }); } - public warn(message: NotificationMessage | NotificationMessage[]): void { + warn(message: NotificationMessage | NotificationMessage[]): void { if (Array.isArray(message)) { message.forEach(m => this.warn(m)); @@ -51,7 +42,7 @@ export class NotificationService implements INotificationService { this.model.notify({ severity: Severity.Warning, message }); } - public error(message: NotificationMessage | NotificationMessage[]): void { + error(message: NotificationMessage | NotificationMessage[]): void { if (Array.isArray(message)) { message.forEach(m => this.error(m)); @@ -61,11 +52,11 @@ export class NotificationService implements INotificationService { this.model.notify({ severity: Severity.Error, message }); } - public notify(notification: INotification): INotificationHandle { + notify(notification: INotification): INotificationHandle { return this.model.notify(notification); } - public prompt(severity: Severity, message: string, choices: IPromptChoice[], onCancel?: () => void): INotificationHandle { + prompt(severity: Severity, message: string, choices: IPromptChoice[], onCancel?: () => void): INotificationHandle { let handle: INotificationHandle; let choiceClicked = false; @@ -109,8 +100,4 @@ export class NotificationService implements INotificationService { return handle; } - - public dispose(): void { - this.toDispose = dispose(this.toDispose); - } } \ No newline at end of file diff --git a/src/vs/workbench/services/progress/browser/progressService.ts b/src/vs/workbench/services/progress/browser/progressService.ts index 6f6e6b5da76..b68cb4c8b77 100644 --- a/src/vs/workbench/services/progress/browser/progressService.ts +++ b/src/vs/workbench/services/progress/browser/progressService.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import * as lifecycle from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; import { TPromise } from 'vs/base/common/winjs.base'; import * as types from 'vs/base/common/types'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; @@ -21,21 +21,20 @@ interface ProgressState { whileDelay?: number; } -export abstract class ScopedService { - - protected toDispose: lifecycle.IDisposable[]; +export abstract class ScopedService extends Disposable { constructor(private viewletService: IViewletService, private panelService: IPanelService, private scopeId: string) { - this.toDispose = []; + super(); + this.registerListeners(); } - public registerListeners(): void { - this.toDispose.push(this.viewletService.onDidViewletOpen(viewlet => this.onScopeOpened(viewlet.getId()))); - this.toDispose.push(this.panelService.onDidPanelOpen(panel => this.onScopeOpened(panel.getId()))); + registerListeners(): void { + this._register(this.viewletService.onDidViewletOpen(viewlet => this.onScopeOpened(viewlet.getId()))); + this._register(this.panelService.onDidPanelOpen(panel => this.onScopeOpened(panel.getId()))); - this.toDispose.push(this.viewletService.onDidViewletClose(viewlet => this.onScopeClosed(viewlet.getId()))); - this.toDispose.push(this.panelService.onDidPanelClose(panel => this.onScopeClosed(panel.getId()))); + this._register(this.viewletService.onDidViewletClose(viewlet => this.onScopeClosed(viewlet.getId()))); + this._register(this.panelService.onDidPanelClose(panel => this.onScopeClosed(panel.getId()))); } private onScopeClosed(scopeId: string) { @@ -50,13 +49,13 @@ export abstract class ScopedService { } } - public abstract onScopeActivated(): void; + abstract onScopeActivated(): void; - public abstract onScopeDeactivated(): void; + abstract onScopeDeactivated(): void; } export class ScopedProgressService extends ScopedService implements IProgressService { - public _serviceBrand: any; + _serviceBrand: any; private isActive: boolean; private progressbar: ProgressBar; private progressState: ProgressState; @@ -75,11 +74,11 @@ export class ScopedProgressService extends ScopedService implements IProgressSer this.progressState = Object.create(null); } - public onScopeDeactivated(): void { + onScopeDeactivated(): void { this.isActive = false; } - public onScopeActivated(): void { + onScopeActivated(): void { this.isActive = true; // Return early if progress state indicates that progress is done @@ -127,9 +126,9 @@ export class ScopedProgressService extends ScopedService implements IProgressSer this.progressState.whileDelay = void 0; } - public show(infinite: boolean, delay?: number): IProgressRunner; - public show(total: number, delay?: number): IProgressRunner; - public show(infiniteOrTotal: boolean | number, delay?: number): IProgressRunner { + show(infinite: boolean, delay?: number): IProgressRunner; + show(total: number, delay?: number): IProgressRunner; + show(infiniteOrTotal: boolean | number, delay?: number): IProgressRunner { let infinite: boolean; let total: number; @@ -207,7 +206,7 @@ export class ScopedProgressService extends ScopedService implements IProgressSer }; } - public showWhile(promise: TPromise, delay?: number): TPromise { + showWhile(promise: TPromise, delay?: number): TPromise { let stack: boolean = !!this.progressState.whilePromise; // Reset State @@ -252,21 +251,17 @@ export class ScopedProgressService extends ScopedService implements IProgressSer this.progressbar.infinite().show(delay); } } - - public dispose(): void { - this.toDispose = lifecycle.dispose(this.toDispose); - } } export class ProgressService implements IProgressService { - public _serviceBrand: any; + _serviceBrand: any; constructor(private progressbar: ProgressBar) { } - public show(infinite: boolean, delay?: number): IProgressRunner; - public show(total: number, delay?: number): IProgressRunner; - public show(infiniteOrTotal: boolean | number, delay?: number): IProgressRunner { + show(infinite: boolean, delay?: number): IProgressRunner; + show(total: number, delay?: number): IProgressRunner; + show(infiniteOrTotal: boolean | number, delay?: number): IProgressRunner { if (typeof infiniteOrTotal === 'boolean') { this.progressbar.infinite().show(delay); } else { @@ -292,7 +287,7 @@ export class ProgressService implements IProgressService { }; } - public showWhile(promise: TPromise, delay?: number): TPromise { + showWhile(promise: TPromise, delay?: number): TPromise { const stop = () => { this.progressbar.stop().hide(); }; diff --git a/src/vs/workbench/services/textfile/common/textFileEditorModel.ts b/src/vs/workbench/services/textfile/common/textFileEditorModel.ts index 5d4c9496046..cf8b858ec15 100644 --- a/src/vs/workbench/services/textfile/common/textFileEditorModel.ts +++ b/src/vs/workbench/services/textfile/common/textFileEditorModel.ts @@ -12,7 +12,6 @@ import { onUnexpectedError } from 'vs/base/common/errors'; import { guessMimeTypes } from 'vs/base/common/mime'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import URI from 'vs/base/common/uri'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import * as diagnostics from 'vs/base/common/diagnostics'; import * as types from 'vs/base/common/types'; import { IMode } from 'vs/editor/common/modes'; @@ -39,12 +38,18 @@ import { isLinux } from 'vs/base/common/platform'; */ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFileEditorModel { - public static DEFAULT_CONTENT_CHANGE_BUFFER_DELAY = CONTENT_CHANGE_EVENT_BUFFER_DELAY; - public static DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY = 100; + static DEFAULT_CONTENT_CHANGE_BUFFER_DELAY = CONTENT_CHANGE_EVENT_BUFFER_DELAY; + static DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY = 100; private static saveErrorHandler: ISaveErrorHandler; private static saveParticipant: ISaveParticipant; + private readonly _onDidContentChange: Emitter = this._register(new Emitter()); + get onDidContentChange(): Event { return this._onDidContentChange.event; } + + private readonly _onDidStateChange: Emitter = this._register(new Emitter()); + get onDidStateChange(): Event { return this._onDidStateChange.event; } + private resource: URI; private contentEncoding: string; // encoding as reported from disk private preferredEncoding: string; // encoding as chosen by the user @@ -52,7 +57,6 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil private versionId: number; private bufferSavedVersionId: number; private lastResolvedDiskStat: IFileStat; - private toDispose: IDisposable[]; private blockModelContentChange: boolean; private autoSaveAfterMillies: number; private autoSaveAfterMilliesEnabled: boolean; @@ -63,9 +67,6 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil private disposed: boolean; private lastSaveAttemptTime: number; private createTextEditorModelPromise: TPromise; - private readonly _onDidContentChange: Emitter; - private readonly _onDidStateChange: Emitter; - private inConflictMode: boolean; private inOrphanMode: boolean; private inErrorMode: boolean; @@ -87,11 +88,6 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil ) { super(modelService, modeService); this.resource = resource; - this.toDispose = []; - this._onDidContentChange = new Emitter(); - this._onDidStateChange = new Emitter(); - this.toDispose.push(this._onDidContentChange); - this.toDispose.push(this._onDidStateChange); this.preferredEncoding = preferredEncoding; this.inOrphanMode = false; this.dirty = false; @@ -99,11 +95,8 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil this.lastSaveAttemptTime = 0; this.saveSequentializer = new SaveSequentializer(); - this.contentChangeEventScheduler = new RunOnceScheduler(() => this._onDidContentChange.fire(StateChange.CONTENT_CHANGE), TextFileEditorModel.DEFAULT_CONTENT_CHANGE_BUFFER_DELAY); - this.toDispose.push(this.contentChangeEventScheduler); - - this.orphanedChangeEventScheduler = new RunOnceScheduler(() => this._onDidStateChange.fire(StateChange.ORPHANED_CHANGE), TextFileEditorModel.DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY); - this.toDispose.push(this.orphanedChangeEventScheduler); + this.contentChangeEventScheduler = this._register(new RunOnceScheduler(() => this._onDidContentChange.fire(StateChange.CONTENT_CHANGE), TextFileEditorModel.DEFAULT_CONTENT_CHANGE_BUFFER_DELAY)); + this.orphanedChangeEventScheduler = this._register(new RunOnceScheduler(() => this._onDidStateChange.fire(StateChange.ORPHANED_CHANGE), TextFileEditorModel.DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY)); this.updateAutoSaveConfiguration(textFileService.getAutoSaveConfiguration()); @@ -111,10 +104,10 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil } private registerListeners(): void { - this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e))); - this.toDispose.push(this.textFileService.onAutoSaveConfigurationChange(config => this.updateAutoSaveConfiguration(config))); - this.toDispose.push(this.textFileService.onFilesAssociationChange(e => this.onFilesAssociationChange())); - this.toDispose.push(this.onDidStateChange(e => this.onStateChange(e))); + this._register(this.fileService.onFileChanges(e => this.onFileChanges(e))); + this._register(this.textFileService.onAutoSaveConfigurationChange(config => this.updateAutoSaveConfiguration(config))); + this._register(this.textFileService.onFilesAssociationChange(e => this.onFilesAssociationChange())); + this._register(this.onDidStateChange(e => this.onStateChange(e))); } private onStateChange(e: StateChange): void { @@ -208,32 +201,24 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil this.modelService.setMode(this.textEditorModel, mode); } - public get onDidContentChange(): Event { - return this._onDidContentChange.event; - } - - public get onDidStateChange(): Event { - return this._onDidStateChange.event; - } - /** * The current version id of the model. */ - public getVersionId(): number { + getVersionId(): number { return this.versionId; } /** * Set a save error handler to install code that executes when save errors occur. */ - public static setSaveErrorHandler(handler: ISaveErrorHandler): void { + static setSaveErrorHandler(handler: ISaveErrorHandler): void { TextFileEditorModel.saveErrorHandler = handler; } /** * Set a save participant handler to react on models getting saved. */ - public static setSaveParticipant(handler: ISaveParticipant): void { + static setSaveParticipant(handler: ISaveParticipant): void { TextFileEditorModel.saveParticipant = handler; } @@ -242,7 +227,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil * * @param if the parameter soft is true, will not attempt to load the contents from disk. */ - public revert(soft?: boolean): TPromise { + revert(soft?: boolean): TPromise { if (!this.isResolved()) { return TPromise.wrap(null); } @@ -273,7 +258,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil }); } - public load(options?: ILoadOptions): TPromise { + load(options?: ILoadOptions): TPromise { diag('load() - enter', this.resource, new Date()); // It is very important to not reload the model when the model is dirty. We only want to reload the model from the disk @@ -504,7 +489,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil // where `value` was captured in the content change listener closure scope. // Content Change - this.toDispose.push(this.textEditorModel.onDidChangeContent(() => this.onModelContentChanged())); + this._register(this.textEditorModel.onDidChangeContent(() => this.onModelContentChanged())); } private doLoadBackup(backup: URI): TPromise { @@ -608,7 +593,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil /** * Saves the current versionId of this editor model if it is dirty. */ - public save(options: ISaveOptions = Object.create(null)): TPromise { + save(options: ISaveOptions = Object.create(null)): TPromise { if (!this.isResolved()) { return TPromise.wrap(null); } @@ -879,28 +864,28 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil /** * Returns true if the content of this model has changes that are not yet saved back to the disk. */ - public isDirty(): boolean { + isDirty(): boolean { return this.dirty; } /** * Returns the time in millies when this working copy was attempted to be saved. */ - public getLastSaveAttemptTime(): number { + getLastSaveAttemptTime(): number { return this.lastSaveAttemptTime; } /** * Returns the time in millies when this working copy was last modified by the user or some other program. */ - public getETag(): string { + getETag(): string { return this.lastResolvedDiskStat ? this.lastResolvedDiskStat.etag : null; } /** * Answers if this model is in a specific state. */ - public hasState(state: ModelState): boolean { + hasState(state: ModelState): boolean { switch (state) { case ModelState.CONFLICT: return this.inConflictMode; @@ -917,11 +902,11 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil } } - public getEncoding(): string { + getEncoding(): string { return this.preferredEncoding || this.contentEncoding; } - public setEncoding(encoding: string, mode: EncodingMode): void { + setEncoding(encoding: string, mode: EncodingMode): void { if (!this.isNewEncoding(encoding)) { return; // return early if the encoding is already the same } @@ -958,7 +943,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil } } - public updatePreferredEncoding(encoding: string): void { + updatePreferredEncoding(encoding: string): void { if (!this.isNewEncoding(encoding)) { return; } @@ -981,42 +966,41 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil return true; } - public isResolved(): boolean { + isResolved(): boolean { return !types.isUndefinedOrNull(this.lastResolvedDiskStat); } - public isReadonly(): boolean { + isReadonly(): boolean { return this.lastResolvedDiskStat && this.lastResolvedDiskStat.isReadonly; } /** * Returns true if the dispose() method of this model has been called. */ - public isDisposed(): boolean { + isDisposed(): boolean { return this.disposed; } /** * Returns the full resource URI of the file this text file editor model is about. */ - public getResource(): URI { + getResource(): URI { return this.resource; } /** * Stat accessor only used by tests. */ - public getStat(): IFileStat { + getStat(): IFileStat { return this.lastResolvedDiskStat; } - public dispose(): void { + dispose(): void { this.disposed = true; this.inConflictMode = false; this.inOrphanMode = false; this.inErrorMode = false; - this.toDispose = dispose(this.toDispose); this.createTextEditorModelPromise = null; this.cancelAutoSavePromise(); @@ -1041,7 +1025,7 @@ export class SaveSequentializer { private _pendingSave: IPendingSave; private _nextSave: ISaveOperation; - public hasPendingSave(versionId?: number): boolean { + hasPendingSave(versionId?: number): boolean { if (!this._pendingSave) { return false; } @@ -1053,11 +1037,11 @@ export class SaveSequentializer { return !!this._pendingSave; } - public get pendingSave(): TPromise { + get pendingSave(): TPromise { return this._pendingSave ? this._pendingSave.promise : void 0; } - public setPending(versionId: number, promise: TPromise): TPromise { + setPending(versionId: number, promise: TPromise): TPromise { this._pendingSave = { versionId, promise }; promise.done(() => this.donePending(versionId), () => this.donePending(versionId)); @@ -1086,7 +1070,7 @@ export class SaveSequentializer { } } - public setNext(run: () => TPromise): TPromise { + setNext(run: () => TPromise): TPromise { // this is our first next save, so we create associated promise with it // so that we can return a promise that completes when the save operation @@ -1120,7 +1104,7 @@ class DefaultSaveErrorHandler implements ISaveErrorHandler { constructor(@INotificationService private notificationService: INotificationService) { } - public onSaveError(error: any, model: TextFileEditorModel): void { + onSaveError(error: any, model: TextFileEditorModel): void { this.notificationService.error(nls.localize('genericSaveError', "Failed to save '{0}': {1}", path.basename(model.getResource().fsPath), toErrorMessage(error, false))); } } diff --git a/src/vs/workbench/services/textfile/common/textFileEditorModelManager.ts b/src/vs/workbench/services/textfile/common/textFileEditorModelManager.ts index 7b19b9d0a36..c37e191b716 100644 --- a/src/vs/workbench/services/textfile/common/textFileEditorModelManager.ts +++ b/src/vs/workbench/services/textfile/common/textFileEditorModelManager.ts @@ -8,23 +8,37 @@ import { Event, Emitter, debounceEvent } from 'vs/base/common/event'; import { TPromise } from 'vs/base/common/winjs.base'; import URI from 'vs/base/common/uri'; import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel'; -import { dispose, IDisposable } from 'vs/base/common/lifecycle'; +import { dispose, IDisposable, Disposable } from 'vs/base/common/lifecycle'; import { ITextFileEditorModel, ITextFileEditorModelManager, TextFileModelChangeEvent, StateChange, IModelLoadOrCreateOptions, ILoadOptions } from 'vs/workbench/services/textfile/common/textfiles'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ResourceMap } from 'vs/base/common/map'; -export class TextFileEditorModelManager implements ITextFileEditorModelManager { - private toUnbind: IDisposable[]; +export class TextFileEditorModelManager extends Disposable implements ITextFileEditorModelManager { - private readonly _onModelDisposed: Emitter; - private readonly _onModelContentChanged: Emitter; - private readonly _onModelDirty: Emitter; - private readonly _onModelSaveError: Emitter; - private readonly _onModelSaved: Emitter; - private readonly _onModelReverted: Emitter; - private readonly _onModelEncodingChanged: Emitter; - private readonly _onModelOrphanedChanged: Emitter; + private readonly _onModelDisposed: Emitter = this._register(new Emitter()); + get onModelDisposed(): Event { return this._onModelDisposed.event; } + + private readonly _onModelContentChanged: Emitter = this._register(new Emitter()); + get onModelContentChanged(): Event { return this._onModelContentChanged.event; } + + private readonly _onModelDirty: Emitter = this._register(new Emitter()); + get onModelDirty(): Event { return this._onModelDirty.event; } + + private readonly _onModelSaveError: Emitter = this._register(new Emitter()); + get onModelSaveError(): Event { return this._onModelSaveError.event; } + + private readonly _onModelSaved: Emitter = this._register(new Emitter()); + get onModelSaved(): Event { return this._onModelSaved.event; } + + private readonly _onModelReverted: Emitter = this._register(new Emitter()); + get onModelReverted(): Event { return this._onModelReverted.event; } + + private readonly _onModelEncodingChanged: Emitter = this._register(new Emitter()); + get onModelEncodingChanged(): Event { return this._onModelEncodingChanged.event; } + + private readonly _onModelOrphanedChanged: Emitter = this._register(new Emitter()); + get onModelOrphanedChanged(): Event { return this._onModelOrphanedChanged.event; } private _onModelsDirtyEvent: Event; private _onModelsSaveError: Event; @@ -41,25 +55,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager { @ILifecycleService private lifecycleService: ILifecycleService, @IInstantiationService private instantiationService: IInstantiationService ) { - this.toUnbind = []; - - this._onModelDisposed = new Emitter(); - this._onModelContentChanged = new Emitter(); - this._onModelDirty = new Emitter(); - this._onModelSaveError = new Emitter(); - this._onModelSaved = new Emitter(); - this._onModelReverted = new Emitter(); - this._onModelEncodingChanged = new Emitter(); - this._onModelOrphanedChanged = new Emitter(); - - this.toUnbind.push(this._onModelDisposed); - this.toUnbind.push(this._onModelContentChanged); - this.toUnbind.push(this._onModelDirty); - this.toUnbind.push(this._onModelSaveError); - this.toUnbind.push(this._onModelSaved); - this.toUnbind.push(this._onModelReverted); - this.toUnbind.push(this._onModelEncodingChanged); - this.toUnbind.push(this._onModelOrphanedChanged); + super(); this.mapResourceToModel = new ResourceMap(); this.mapResourceToDisposeListener = new ResourceMap(); @@ -76,39 +72,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager { this.lifecycleService.onShutdown(this.dispose, this); } - public get onModelDisposed(): Event { - return this._onModelDisposed.event; - } - - public get onModelContentChanged(): Event { - return this._onModelContentChanged.event; - } - - public get onModelDirty(): Event { - return this._onModelDirty.event; - } - - public get onModelSaveError(): Event { - return this._onModelSaveError.event; - } - - public get onModelSaved(): Event { - return this._onModelSaved.event; - } - - public get onModelReverted(): Event { - return this._onModelReverted.event; - } - - public get onModelEncodingChanged(): Event { - return this._onModelEncodingChanged.event; - } - - public get onModelOrphanedChanged(): Event { - return this._onModelOrphanedChanged.event; - } - - public get onModelsDirty(): Event { + get onModelsDirty(): Event { if (!this._onModelsDirtyEvent) { this._onModelsDirtyEvent = this.debounce(this.onModelDirty); } @@ -116,7 +80,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager { return this._onModelsDirtyEvent; } - public get onModelsSaveError(): Event { + get onModelsSaveError(): Event { if (!this._onModelsSaveError) { this._onModelsSaveError = this.debounce(this.onModelSaveError); } @@ -124,7 +88,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager { return this._onModelsSaveError; } - public get onModelsSaved(): Event { + get onModelsSaved(): Event { if (!this._onModelsSaved) { this._onModelsSaved = this.debounce(this.onModelSaved); } @@ -132,7 +96,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager { return this._onModelsSaved; } - public get onModelsReverted(): Event { + get onModelsReverted(): Event { if (!this._onModelsReverted) { this._onModelsReverted = this.debounce(this.onModelReverted); } @@ -155,11 +119,11 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager { return 250; } - public get(resource: URI): ITextFileEditorModel { + get(resource: URI): ITextFileEditorModel { return this.mapResourceToModel.get(resource); } - public loadOrCreate(resource: URI, options?: IModelLoadOrCreateOptions): TPromise { + loadOrCreate(resource: URI, options?: IModelLoadOrCreateOptions): TPromise { // Return early if model is currently being loaded const pendingLoad = this.mapResourceToPendingModelLoaders.get(resource); @@ -249,7 +213,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager { }); } - public getAll(resource?: URI, filter?: (model: ITextFileEditorModel) => boolean): ITextFileEditorModel[] { + getAll(resource?: URI, filter?: (model: ITextFileEditorModel) => boolean): ITextFileEditorModel[] { if (resource) { const res = this.mapResourceToModel.get(resource); @@ -266,7 +230,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager { return res; } - public add(resource: URI, model: ITextFileEditorModel): void { + add(resource: URI, model: ITextFileEditorModel): void { const knownModel = this.mapResourceToModel.get(resource); if (knownModel === model) { return; // already cached @@ -286,7 +250,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager { })); } - public remove(resource: URI): void { + remove(resource: URI): void { this.mapResourceToModel.delete(resource); const disposeListener = this.mapResourceToDisposeListener.get(resource); @@ -308,7 +272,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager { } } - public clear(): void { + clear(): void { // model caches this.mapResourceToModel.clear(); @@ -327,7 +291,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager { this.mapResourceToModelContentChangeListener.clear(); } - public disposeModel(model: TextFileEditorModel): void { + disposeModel(model: TextFileEditorModel): void { if (!model) { return; // we need data! } @@ -346,8 +310,4 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager { model.dispose(); } - - public dispose(): void { - this.toUnbind = dispose(this.toUnbind); - } } \ No newline at end of file diff --git a/src/vs/workbench/services/textfile/common/textFileService.ts b/src/vs/workbench/services/textfile/common/textFileService.ts index 10628bd5080..6a6b4648038 100644 --- a/src/vs/workbench/services/textfile/common/textFileService.ts +++ b/src/vs/workbench/services/textfile/common/textFileService.ts @@ -20,7 +20,7 @@ import { ILifecycleService, ShutdownReason } from 'vs/platform/lifecycle/common/ import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IFileService, IResolveContentOptions, IFilesConfiguration, FileOperationError, FileOperationResult, AutoSaveConfiguration, HotExitConfiguration } from 'vs/platform/files/common/files'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; -import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; import { UntitledEditorModel } from 'vs/workbench/common/editor/untitledEditorModel'; @@ -44,27 +44,26 @@ export interface IBackupResult { * * It also adds diagnostics and logging around file system operations. */ -export abstract class TextFileService implements ITextFileService { +export abstract class TextFileService extends Disposable implements ITextFileService { - public _serviceBrand: any; + _serviceBrand: any; - private readonly _onWillMove = new Emitter(); - readonly onWillMove: Event = this._onWillMove.event; + private readonly _onFilesAssociationChange: Emitter = this._register(new Emitter()); + get onAutoSaveConfigurationChange(): Event { return this._onAutoSaveConfigurationChange.event; } + + private readonly _onAutoSaveConfigurationChange: Emitter = this._register(new Emitter()); + get onFilesAssociationChange(): Event { return this._onFilesAssociationChange.event; } + + private readonly _onWillMove = this._register(new Emitter()); + get onWillMove(): Event { return this._onWillMove.event; } - private toUnbind: IDisposable[]; private _models: TextFileEditorModelManager; - - private readonly _onFilesAssociationChange: Emitter; private currentFilesAssociationConfig: { [key: string]: string; }; - - private readonly _onAutoSaveConfigurationChange: Emitter; private configuredAutoSaveDelay: number; private configuredAutoSaveOnFocusChange: boolean; private configuredAutoSaveOnWindowChange: boolean; - - private autoSaveContext: IContextKey; - private configuredHotExit: string; + private autoSaveContext: IContextKey; constructor( private lifecycleService: ILifecycleService, @@ -81,13 +80,7 @@ export abstract class TextFileService implements ITextFileService { contextKeyService: IContextKeyService, private modelService: IModelService ) { - this.toUnbind = []; - - this._onAutoSaveConfigurationChange = new Emitter(); - this.toUnbind.push(this._onAutoSaveConfigurationChange); - - this._onFilesAssociationChange = new Emitter(); - this.toUnbind.push(this._onFilesAssociationChange); + super(); this._models = this.instantiationService.createInstance(TextFileEditorModelManager); this.autoSaveContext = AutoSaveContext.bindTo(contextKeyService); @@ -100,7 +93,7 @@ export abstract class TextFileService implements ITextFileService { this.registerListeners(); } - public get models(): ITextFileEditorModelManager { + get models(): ITextFileEditorModelManager { return this._models; } @@ -110,14 +103,6 @@ export abstract class TextFileService implements ITextFileService { abstract confirmSave(resources?: URI[]): TPromise; - public get onAutoSaveConfigurationChange(): Event { - return this._onAutoSaveConfigurationChange.event; - } - - public get onFilesAssociationChange(): Event { - return this._onFilesAssociationChange.event; - } - private registerListeners(): void { // Lifecycle @@ -125,7 +110,7 @@ export abstract class TextFileService implements ITextFileService { this.lifecycleService.onShutdown(this.dispose, this); // Files configuration changes - this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => { + this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('files')) { this.onFilesConfigurationChange(this.configurationService.getValue()); } @@ -368,7 +353,7 @@ export abstract class TextFileService implements ITextFileService { } } - public getDirty(resources?: URI[]): URI[] { + getDirty(resources?: URI[]): URI[] { // Collect files const dirty = this.getDirtyFileModels(resources).map(m => m.getResource()); @@ -379,7 +364,7 @@ export abstract class TextFileService implements ITextFileService { return dirty; } - public isDirty(resource?: URI): boolean { + isDirty(resource?: URI): boolean { // Check for dirty file if (this._models.getAll(resource).some(model => model.isDirty())) { @@ -390,7 +375,7 @@ export abstract class TextFileService implements ITextFileService { return this.untitledEditorService.getDirty().some(dirty => !resource || dirty.toString() === resource.toString()); } - public save(resource: URI, options?: ISaveOptions): TPromise { + save(resource: URI, options?: ISaveOptions): TPromise { // Run a forced save if we detect the file is not dirty so that save participants can still run if (options && options.force && this.fileService.canHandleResource(resource) && !this.isDirty(resource)) { @@ -403,9 +388,9 @@ export abstract class TextFileService implements ITextFileService { return this.saveAll([resource], options).then(result => result.results.length === 1 && result.results[0].success); } - public saveAll(includeUntitled?: boolean, options?: ISaveOptions): TPromise; - public saveAll(resources: URI[], options?: ISaveOptions): TPromise; - public saveAll(arg1?: any, options?: ISaveOptions): TPromise { + saveAll(includeUntitled?: boolean, options?: ISaveOptions): TPromise; + saveAll(resources: URI[], options?: ISaveOptions): TPromise; + saveAll(arg1?: any, options?: ISaveOptions): TPromise { // get all dirty let toSave: URI[] = []; @@ -537,7 +522,7 @@ export abstract class TextFileService implements ITextFileService { return this.getFileModels(arg1).filter(model => model.isDirty()); } - public saveAs(resource: URI, target?: URI, options?: ISaveOptions): TPromise { + saveAs(resource: URI, target?: URI, options?: ISaveOptions): TPromise { // Get to target resource let targetPromise: TPromise; @@ -654,11 +639,11 @@ export abstract class TextFileService implements ITextFileService { return untitledFileName; } - public revert(resource: URI, options?: IRevertOptions): TPromise { + revert(resource: URI, options?: IRevertOptions): TPromise { return this.revertAll([resource], options).then(result => result.results.length === 1 && result.results[0].success); } - public revertAll(resources?: URI[], options?: IRevertOptions): TPromise { + revertAll(resources?: URI[], options?: IRevertOptions): TPromise { // Revert files first return this.doRevertAllFiles(resources, options).then(operation => { @@ -707,13 +692,13 @@ export abstract class TextFileService implements ITextFileService { }); } - public delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): TPromise { + delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): TPromise { const dirtyFiles = this.getDirty().filter(dirty => isEqualOrParent(dirty, resource, !platform.isLinux /* ignorecase */)); return this.revertAll(dirtyFiles, { soft: true }).then(() => this.fileService.del(resource, options)); } - public move(source: URI, target: URI, overwrite?: boolean): TPromise { + move(source: URI, target: URI, overwrite?: boolean): TPromise { const waitForPromises: TPromise[] = []; this._onWillMove.fire({ @@ -790,7 +775,7 @@ export abstract class TextFileService implements ITextFileService { }); } - public getAutoSaveMode(): AutoSaveMode { + getAutoSaveMode(): AutoSaveMode { if (this.configuredAutoSaveOnFocusChange) { return AutoSaveMode.ON_FOCUS_CHANGE; } @@ -806,7 +791,7 @@ export abstract class TextFileService implements ITextFileService { return AutoSaveMode.OFF; } - public getAutoSaveConfiguration(): IAutoSaveConfiguration { + getAutoSaveConfiguration(): IAutoSaveConfiguration { return { autoSaveDelay: this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0 ? this.configuredAutoSaveDelay : void 0, autoSaveFocusChange: this.configuredAutoSaveOnFocusChange, @@ -814,14 +799,15 @@ export abstract class TextFileService implements ITextFileService { }; } - public get isHotExitEnabled(): boolean { + get isHotExitEnabled(): boolean { return !this.environmentService.isExtensionDevelopment && this.configuredHotExit !== HotExitConfiguration.OFF; } - public dispose(): void { - this.toUnbind = dispose(this.toUnbind); + dispose(): void { // Clear all caches this._models.clear(); + + super.dispose(); } } diff --git a/src/vs/workbench/services/textfile/common/textfiles.ts b/src/vs/workbench/services/textfile/common/textfiles.ts index 8d3101bceef..5329c91f2e2 100644 --- a/src/vs/workbench/services/textfile/common/textfiles.ts +++ b/src/vs/workbench/services/textfile/common/textfiles.ts @@ -80,11 +80,11 @@ export class TextFileModelChangeEvent { this._kind = kind; } - public get resource(): URI { + get resource(): URI { return this._resource; } - public get kind(): StateChange { + get kind(): StateChange { return this._kind; } } diff --git a/src/vs/workbench/services/textfile/electron-browser/textFileService.ts b/src/vs/workbench/services/textfile/electron-browser/textFileService.ts index 830c9d74042..b541f828c31 100644 --- a/src/vs/workbench/services/textfile/electron-browser/textFileService.ts +++ b/src/vs/workbench/services/textfile/electron-browser/textFileService.ts @@ -54,7 +54,7 @@ export class TextFileService extends AbstractTextFileService { super(lifecycleService, contextService, configurationService, fileService, untitledEditorService, instantiationService, notificationService, environmentService, backupFileService, windowsService, historyService, contextKeyService, modelService); } - public resolveTextContent(resource: URI, options?: IResolveContentOptions): TPromise { + resolveTextContent(resource: URI, options?: IResolveContentOptions): TPromise { return this.fileService.resolveStreamContent(resource, options).then(streamContent => { return createTextBufferFactoryFromStream(streamContent.value).then(res => { const r: IRawTextContent = { @@ -71,7 +71,7 @@ export class TextFileService extends AbstractTextFileService { }); } - public confirmSave(resources?: URI[]): TPromise { + confirmSave(resources?: URI[]): TPromise { if (this.environmentService.isExtensionDevelopment) { return TPromise.wrap(ConfirmResult.DONT_SAVE); // no veto when we are in extension dev mode because we cannot assum we run interactive (e.g. tests) } @@ -102,7 +102,7 @@ export class TextFileService extends AbstractTextFileService { }); } - public promptForPath(defaultPath: string): TPromise { + promptForPath(defaultPath: string): TPromise { return this.windowService.showSaveDialog(this.getSaveDialogOptions(defaultPath)); } diff --git a/src/vs/workbench/services/textmodelResolver/common/textModelResolverService.ts b/src/vs/workbench/services/textmodelResolver/common/textModelResolverService.ts index c7617a56e68..198aff0bceb 100644 --- a/src/vs/workbench/services/textmodelResolver/common/textModelResolverService.ts +++ b/src/vs/workbench/services/textmodelResolver/common/textModelResolverService.ts @@ -31,7 +31,7 @@ class ResourceModelCollection extends ReferenceCollection { + createReferencedObject(key: string): TPromise { const resource = URI.parse(key); if (this.fileService.canHandleResource(resource)) { return this.textFileService.models.loadOrCreate(resource); @@ -39,7 +39,7 @@ class ResourceModelCollection extends ReferenceCollection this.instantiationService.createInstance(ResourceEditorModel, resource)); } - public destroyReferencedObject(modelPromise: TPromise): void { + destroyReferencedObject(modelPromise: TPromise): void { modelPromise.done(model => { if (model instanceof TextFileEditorModel) { this.textFileService.models.disposeModel(model); @@ -51,7 +51,7 @@ class ResourceModelCollection extends ReferenceCollection> { + createModelReference(resource: URI): TPromise> { return this._createModelReference(resource); } @@ -144,7 +144,7 @@ export class TextModelResolverService implements ITextModelService { ); } - public registerTextModelContentProvider(scheme: string, provider: ITextModelContentProvider): IDisposable { + registerTextModelContentProvider(scheme: string, provider: ITextModelContentProvider): IDisposable { return this.resourceModelCollection.registerTextModelContentProvider(scheme, provider); } } diff --git a/src/vs/workbench/services/untitled/common/untitledEditorService.ts b/src/vs/workbench/services/untitled/common/untitledEditorService.ts index b667bea963a..ecd539c8e66 100644 --- a/src/vs/workbench/services/untitled/common/untitledEditorService.ts +++ b/src/vs/workbench/services/untitled/common/untitledEditorService.ts @@ -15,6 +15,7 @@ import { ResourceMap } from 'vs/base/common/map'; import { TPromise } from 'vs/base/common/winjs.base'; import { UntitledEditorModel } from 'vs/workbench/common/editor/untitledEditorModel'; import { Schemas } from 'vs/base/common/network'; +import { Disposable } from 'vs/base/common/lifecycle'; export const IUntitledEditorService = createDecorator('untitledEditorService'); @@ -104,42 +105,30 @@ export interface IUntitledEditorService { getEncoding(resource: URI): string; } -export class UntitledEditorService implements IUntitledEditorService { +export class UntitledEditorService extends Disposable implements IUntitledEditorService { - public _serviceBrand: any; + _serviceBrand: any; private mapResourceToInput = new ResourceMap(); private mapResourceToAssociatedFilePath = new ResourceMap(); - private readonly _onDidChangeContent: Emitter; - private readonly _onDidChangeDirty: Emitter; - private readonly _onDidChangeEncoding: Emitter; - private readonly _onDidDisposeModel: Emitter; + private readonly _onDidChangeContent: Emitter = this._register(new Emitter()); + get onDidChangeContent(): Event { return this._onDidChangeContent.event; } + + private readonly _onDidChangeDirty: Emitter = this._register(new Emitter()); + get onDidChangeDirty(): Event { return this._onDidChangeDirty.event; } + + private readonly _onDidChangeEncoding: Emitter = this._register(new Emitter()); + get onDidChangeEncoding(): Event { return this._onDidChangeEncoding.event; } + + private readonly _onDidDisposeModel: Emitter = this._register(new Emitter()); + get onDidDisposeModel(): Event { return this._onDidDisposeModel.event; } constructor( @IInstantiationService private instantiationService: IInstantiationService, @IConfigurationService private configurationService: IConfigurationService ) { - this._onDidChangeContent = new Emitter(); - this._onDidChangeDirty = new Emitter(); - this._onDidChangeEncoding = new Emitter(); - this._onDidDisposeModel = new Emitter(); - } - - public get onDidDisposeModel(): Event { - return this._onDidDisposeModel.event; - } - - public get onDidChangeContent(): Event { - return this._onDidChangeContent.event; - } - - public get onDidChangeDirty(): Event { - return this._onDidChangeDirty.event; - } - - public get onDidChangeEncoding(): Event { - return this._onDidChangeEncoding.event; + super(); } protected get(resource: URI): UntitledEditorInput { @@ -154,11 +143,11 @@ export class UntitledEditorService implements IUntitledEditorService { return this.mapResourceToInput.values(); } - public exists(resource: URI): boolean { + exists(resource: URI): boolean { return this.mapResourceToInput.has(resource); } - public revertAll(resources?: URI[], force?: boolean): URI[] { + revertAll(resources?: URI[], force?: boolean): URI[] { const reverted: URI[] = []; const untitledInputs = this.getAll(resources); @@ -174,13 +163,13 @@ export class UntitledEditorService implements IUntitledEditorService { return reverted; } - public isDirty(resource: URI): boolean { + isDirty(resource: URI): boolean { const input = this.get(resource); return input && input.isDirty(); } - public getDirty(resources?: URI[]): URI[] { + getDirty(resources?: URI[]): URI[] { let inputs: UntitledEditorInput[]; if (resources) { inputs = resources.map(r => this.get(r)).filter(i => !!i); @@ -193,11 +182,11 @@ export class UntitledEditorService implements IUntitledEditorService { .map(i => i.getResource()); } - public loadOrCreate(options: IModelLoadOrCreateOptions = Object.create(null)): TPromise { + loadOrCreate(options: IModelLoadOrCreateOptions = Object.create(null)): TPromise { return this.createOrGet(options.resource, options.modeId, options.initialValue, options.encoding, options.useResourcePath).resolve(); } - public createOrGet(resource?: URI, modeId?: string, initialValue?: string, encoding?: string, hasAssociatedFilePath: boolean = false): UntitledEditorInput { + createOrGet(resource?: URI, modeId?: string, initialValue?: string, encoding?: string, hasAssociatedFilePath: boolean = false): UntitledEditorInput { if (resource) { // Massage resource if it comes with a file:// scheme @@ -274,26 +263,19 @@ export class UntitledEditorService implements IUntitledEditorService { return input; } - public hasAssociatedFilePath(resource: URI): boolean { + hasAssociatedFilePath(resource: URI): boolean { return this.mapResourceToAssociatedFilePath.has(resource); } - public suggestFileName(resource: URI): string { + suggestFileName(resource: URI): string { const input = this.get(resource); return input ? input.suggestFileName() : void 0; } - public getEncoding(resource: URI): string { + getEncoding(resource: URI): string { const input = this.get(resource); return input ? input.getEncoding() : void 0; } - - public dispose(): void { - this._onDidChangeContent.dispose(); - this._onDidChangeDirty.dispose(); - this._onDidChangeEncoding.dispose(); - this._onDidDisposeModel.dispose(); - } } diff --git a/src/vs/workbench/services/viewlet/browser/viewletService.ts b/src/vs/workbench/services/viewlet/browser/viewletService.ts index 354410b5820..979b3ca5f19 100644 --- a/src/vs/workbench/services/viewlet/browser/viewletService.ts +++ b/src/vs/workbench/services/viewlet/browser/viewletService.ts @@ -13,40 +13,41 @@ import { Registry } from 'vs/platform/registry/common/platform'; import { ViewletDescriptor, ViewletRegistry, Extensions as ViewletExtensions } from 'vs/workbench/browser/viewlet'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; -import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; +import { Disposable } from 'vs/base/common/lifecycle'; const ActiveViewletContextId = 'activeViewlet'; export const ActiveViewletContext = new RawContextKey(ActiveViewletContextId, ''); -export class ViewletService implements IViewletService { +export class ViewletService extends Disposable implements IViewletService { - public _serviceBrand: any; + _serviceBrand: any; private sidebarPart: SidebarPart; private viewletRegistry: ViewletRegistry; private activeViewletContextKey: IContextKey; private _onDidViewletEnable = new Emitter<{ id: string, enabled: boolean }>(); - private disposables: IDisposable[] = []; - public get onDidViewletRegister(): Event { return >this.viewletRegistry.onDidRegister; } - public get onDidViewletOpen(): Event { return this.sidebarPart.onDidViewletOpen; } - public get onDidViewletClose(): Event { return this.sidebarPart.onDidViewletClose; } - public get onDidViewletEnablementChange(): Event<{ id: string, enabled: boolean }> { return this._onDidViewletEnable.event; } + get onDidViewletRegister(): Event { return >this.viewletRegistry.onDidRegister; } + get onDidViewletOpen(): Event { return this.sidebarPart.onDidViewletOpen; } + get onDidViewletClose(): Event { return this.sidebarPart.onDidViewletClose; } + get onDidViewletEnablementChange(): Event<{ id: string, enabled: boolean }> { return this._onDidViewletEnable.event; } constructor( sidebarPart: SidebarPart, @IContextKeyService contextKeyService: IContextKeyService, @IExtensionService private extensionService: IExtensionService ) { + super(); + this.sidebarPart = sidebarPart; this.viewletRegistry = Registry.as(ViewletExtensions.Viewlets); this.activeViewletContextKey = ActiveViewletContext.bindTo(contextKeyService); - this.onDidViewletOpen(this._onDidViewletOpen, this, this.disposables); - this.onDidViewletClose(this._onDidViewletClose, this, this.disposables); + this._register(this.onDidViewletOpen(this._onDidViewletOpen, this)); + this._register(this.onDidViewletClose(this._onDidViewletClose, this)); } private _onDidViewletOpen(viewlet: IViewlet): void { @@ -61,7 +62,7 @@ export class ViewletService implements IViewletService { } } - public setViewletEnablement(id: string, enabled: boolean): void { + setViewletEnablement(id: string, enabled: boolean): void { const descriptor = this.getAllViewlets().filter(desc => desc.id === id).pop(); if (descriptor && descriptor.enabled !== enabled) { descriptor.enabled = enabled; @@ -69,7 +70,7 @@ export class ViewletService implements IViewletService { } } - public openViewlet(id: string, focus?: boolean): TPromise { + openViewlet(id: string, focus?: boolean): TPromise { if (this.getViewlet(id)) { return this.sidebarPart.openViewlet(id, focus); } @@ -82,11 +83,11 @@ export class ViewletService implements IViewletService { }); } - public getActiveViewlet(): IViewlet { + getActiveViewlet(): IViewlet { return this.sidebarPart.getActiveViewlet(); } - public getViewlets(): ViewletDescriptor[] { + getViewlets(): ViewletDescriptor[] { return this.getAllViewlets() .filter(v => v.enabled); } @@ -96,19 +97,15 @@ export class ViewletService implements IViewletService { .sort((v1, v2) => v1.order - v2.order); } - public getDefaultViewletId(): string { + getDefaultViewletId(): string { return this.viewletRegistry.getDefaultViewletId(); } - public getViewlet(id: string): ViewletDescriptor { + getViewlet(id: string): ViewletDescriptor { return this.getViewlets().filter(viewlet => viewlet.id === id)[0]; } - public getProgressIndicator(id: string): IProgressService { + getProgressIndicator(id: string): IProgressService { return this.sidebarPart.getProgressIndicator(id); } - - dispose(): void { - this.disposables = dispose(this.disposables); - } } diff --git a/src/vs/workbench/services/workspace/node/workspaceEditingService.ts b/src/vs/workbench/services/workspace/node/workspaceEditingService.ts index b9c500f1c5a..598ed4084f2 100644 --- a/src/vs/workbench/services/workspace/node/workspaceEditingService.ts +++ b/src/vs/workbench/services/workspace/node/workspaceEditingService.ts @@ -31,7 +31,7 @@ import { INotificationService, Severity } from 'vs/platform/notification/common/ export class WorkspaceEditingService implements IWorkspaceEditingService { - public _serviceBrand: any; + _serviceBrand: any; constructor( @IJSONEditingService private jsonEditingService: IJSONEditingService, @@ -46,7 +46,7 @@ export class WorkspaceEditingService implements IWorkspaceEditingService { ) { } - public updateFolders(index: number, deleteCount?: number, foldersToAdd?: IWorkspaceFolderCreationData[], donotNotifyError?: boolean): TPromise { + updateFolders(index: number, deleteCount?: number, foldersToAdd?: IWorkspaceFolderCreationData[], donotNotifyError?: boolean): TPromise { const folders = this.contextService.getWorkspace().folders; let foldersToDelete: URI[] = []; @@ -96,7 +96,7 @@ export class WorkspaceEditingService implements IWorkspaceEditingService { .then(() => null, error => donotNotifyError ? TPromise.wrapError(error) : this.handleWorkspaceConfigurationEditingError(error)); } - public addFolders(foldersToAdd: IWorkspaceFolderCreationData[], donotNotifyError: boolean = false): TPromise { + addFolders(foldersToAdd: IWorkspaceFolderCreationData[], donotNotifyError: boolean = false): TPromise { return this.doAddFolders(foldersToAdd, void 0, donotNotifyError); } @@ -122,7 +122,7 @@ export class WorkspaceEditingService implements IWorkspaceEditingService { .then(() => null, error => donotNotifyError ? TPromise.wrapError(error) : this.handleWorkspaceConfigurationEditingError(error)); } - public removeFolders(foldersToRemove: URI[], donotNotifyError: boolean = false): TPromise { + removeFolders(foldersToRemove: URI[], donotNotifyError: boolean = false): TPromise { // If we are in single-folder state and the opened folder is to be removed, // we create an empty workspace and enter it. @@ -144,11 +144,11 @@ export class WorkspaceEditingService implements IWorkspaceEditingService { return false; } - public createAndEnterWorkspace(folders?: IWorkspaceFolderCreationData[], path?: string): TPromise { + createAndEnterWorkspace(folders?: IWorkspaceFolderCreationData[], path?: string): TPromise { return this.doEnterWorkspace(() => this.windowService.createAndEnterWorkspace(folders, path)); } - public saveAndEnterWorkspace(path: string): TPromise { + saveAndEnterWorkspace(path: string): TPromise { return this.doEnterWorkspace(() => this.windowService.saveAndEnterWorkspace(path)); } @@ -199,8 +199,6 @@ export class WorkspaceEditingService implements IWorkspaceEditingService { if (result) { return this.migrate(result.workspace).then(() => { - // TODO@Ben TODO@Sandeep the following requires ugly casts and should probably have a service interface - // Reinitialize backup service if (this.backupFileService instanceof BackupFileService) { this.backupFileService.initialize(result.backupPath); @@ -241,7 +239,7 @@ export class WorkspaceEditingService implements IWorkspaceEditingService { storageImpl.setWorkspaceId(newWorkspaceId); } - public copyWorkspaceSettings(toWorkspace: IWorkspaceIdentifier): TPromise { + copyWorkspaceSettings(toWorkspace: IWorkspaceIdentifier): TPromise { const configurationProperties = Registry.as(ConfigurationExtensions.Configuration).getConfigurationProperties(); const targetWorkspaceConfiguration = {}; for (const key of this.workspaceConfigurationService.keys().workspace) { diff --git a/src/vs/workbench/workbench.main.ts b/src/vs/workbench/workbench.main.ts index f37dbb90cbc..fa632fcf4f3 100644 --- a/src/vs/workbench/workbench.main.ts +++ b/src/vs/workbench/workbench.main.ts @@ -138,6 +138,8 @@ import 'vs/workbench/parts/welcome/overlay/browser/welcomeOverlay'; import 'vs/workbench/parts/outline/electron-browser/outline.contribution'; +import 'vs/workbench/parts/navigation/common/navigation.contribution'; + // services import 'vs/workbench/services/bulkEdit/electron-browser/bulkEditService'; import 'vs/workbench/parts/experiments/electron-browser/experiments.contribution'; \ No newline at end of file