mirror of
https://github.com/ckaczor/azuredatastudio.git
synced 2026-03-26 23:00:29 -04:00
Merge VS Code 1.26.1 (#2394)
* Squash merge commits for 1.26 (#1) (#2323) * Polish tag search as per feedback (#55269) * Polish tag search as per feedback * Updated regex * Allow users to opt-out of features that send online requests in the background (#55097) * settings sweep #54690 * Minor css tweaks to enable eoverflow elipsis in more places (#55277) * fix an issue with titlebarheight when not scaling with zoom * Settings descriptions update #54690 * fixes #55209 * Settings editor - many padding fixes * More space above level 2 label * Fixing Cannot debug npm script using Yarn #55103 * Settings editor - show ellipsis when description overflows * Settings editor - ... fix measuring around links, relayout * Setting descriptions * Settings editor - fix ... for some short lines, fix select container width * Settings editor - overlay trees so scrollable shadow is full width * Fix #54133 - missing extension settings after reload * Settings color token description tweak * Settings editor - disable overflow indicator temporarily, needs to be faster * Added command to Run the selected npm script * fixes #54452 * fixes #54929 * fixes #55248 * prefix command with extension name * Contribute run selected to the context menu * node-debug@1.26.6 * Allow terminal rendererType to be swapped out at runtime Part of #53274 Fixes #55344 * Settings editor - fix not focusing search when restoring editor setInput must be actually async. Will be fixed naturally when we aren't using winJS promises... * Settings editor - TOC should only expand the section with a selected item * Bump node-debug2 * Settings editor - Tree focus outlines * Settings editor - don't blink the scrollbar when toc selection changes And hide TOC correctly when the editor is narrow * Settings editor - header rows should not be selectable * fixes #54877 * change debug assignee to isi * Settings sweep (#54690) * workaround for #55051 * Settings sweep (#54690) * settings sweep #54690 * Don't try closing tags when you type > after another > * Describe what implementation code lens does Fixes #55370 * fix javadoc formatter setting description * fixes #55325 * update to officical TS version * Settings editor - Even more padding, use semibold instead of bold * Fix #55357 - fix TOC twistie * fixes #55288 * explorer: refresh on di change file system provider registration fixes #53256 * Disable push to Linux repo to test standalone publisher * New env var to notify log level to extensions #54001 * Disable snippets in extension search (when not in suggest dropdown) (#55281) * Disable snippits in extension search (when not in suggest dropdown) * Add monaco input contributions * Fix bug preventing snippetSuggestions from taking effect in sub-editors * Latest emmet helper to fix #52366 * Fix comment updates for threads within same file * Allow extensions to log telemetry to log files #54001 * Pull latest css grammar * files.exclude control - use same style for "add" vs "edit" * files.exclude control - focus/keyboard behavior * don't show menubar too early * files.exclude - better styling * Place cursor at end of extensions search box on autofill (#55254) * Place cursor at end of extensions search box on autofill * Use position instead of selection * fix linux build issue (empty if block) * Settings editor - fix extension category prefixes * Settings editor - add simple ellipsis for first line that overflows, doesn't cover case when first line does not overflow but there is more text, TODO * File/Text search provider docs * Fixes #52655 * Include epoch (#55008) * Fixes #53385 * Fixes #49480 * VS Code Insiders (Users) not opening Fixes #55353 * Better handling of the case when the extension host fails to start * Fixes #53966 * Remove confusing Start from wordPartLeft commands ID * vscode-xterm@3.6.0-beta12 Fixes #55488 * Initial size is set to infinity!! Fixes #55461 * Polish embeddedEditorBackground * configuration service misses event * Fix #55224 - fix duplicate results in multiroot workspace from splitting the diskseach query * Select all not working in issue reporter on mac, fixes #55424 * Disable fuzzy matching for extensions autosuggest (#55498) * Fix clipping of extensions search border in some third party themes (#55504) * fixes #55538 * Fix bug causing an aria alert to not be shown the third time (and odd numbers thereafter) * Settings editor - work around rendering glitch with webkit-line-clamp * Settings editor - revert earlier '...' changes * Settings editor - move enumDescription to its own div, because it disturbs -webkit-line-clamp for some reason * Settings editor - better overflow indicator * Don't show existing filters in autocomplete (#55495) * Dont show existing filters in autocomplete * Simplify * Settings Editor: Add aria labels for input elements Fixes: #54836 (#55543) * fixes #55223 * Update vscode-css-languageservice to 3.0.10-next.1 * Fix #55509 - settings navigation * Fix #55519 * Fix #55520 * FIx #55524 * Fix #55556 - include wordSeparators in all search queries, so findTextInFiles can respect isWordMatch correctly * oss updates for endgame * Fix unit tests * fixes #55522 * Avoid missing manifest error from bubbling up #54757 * Settings format crawl * Search provider - Fix FileSearchProvider to return array, not progress * Fix #55598 * Settings editor - fix NPE rendering settings with no description * dont render inden guides in search box (#55600) * fixes #55454 * More settings crawl * Another change for #55598 - maxResults applies to FileSearch and TextSearch but not FileIndex * Fix FileSearchProvider unit tests for progress change * fixes #55561 * Settings description update for #54690 * Update setting descriptions for online services * Minor edits * fixes #55513 * fixes #55451 * Fix #55612 - fix findTextInFiles cancellation * fixes #55539 * More setting description tweaks * Setting to disable online experiments #54354 * fixes #55507 * fixes #55515 * Show online services action only in Insiders for now * Settings editor - change toc behavior default to 'filter' * Settings editor - nicer filter count style during search * Fix #55617 - search viewlet icons * Settings editor - better styling for element count indicator * SearchProvider - fix NPE when searching extraFileResources * Allow extends to work without json suffix Fixes #16905 * Remove accessability options logic entirely Follow up on #55451 * use latest version of DAP * fixes #55490 * fixes #55122 * fixes #52332 * Avoid assumptions about git: URIs (fixes #36236) * relative path for descriptions * resourece: get rid of isFile context key fixes #48275 * Register previous ids for compatibility (#53497) * more tuning for #48275 * no need to always re-read "files explorer" fixes #52003 * read out active composites properly fixes #51967 * Update link colors for hc theme to meet color contrast ratio, fixes #55651 Also updated link color for `textLinkActiveForeground` to be the same as `textLinkForeground` as it wasn't properly updated * detect 'winpty-agent.exe'; fixes #55672 * node-debug@1.26.7 * reset counter on new label * Settings editor - fix multiple setting links in one description * Settings editor - color code blocks in setting descriptions, fix #55532 * Settings editor - hover color in TOC * Settings editor - fix navigation NPE * Settings editor - fix text control width * Settings editor - maybe fix #55684 * Fix bug causing cursor to not move on paste * fixes #53582 * Use ctrlCmd instead of ctrl for go down from search box * fixes #55264 * fixes #55456 * filter for spcaes before triggering search (#55611) * Fix #55698 - don't lose filtered TOC counts when refreshing TOC * fixes #55421 * fixes #28979 * fixes #55576 * only add check for updates to windows/linux help * readonly files: append decoration to label fixes #53022 * debug: do not show toolbar while initialising fixes #55026 * Opening launch.json should not activate debug extensions fixes #55029 * fixes #55435 * fixes #55434 * fixes #55439 * trigger menu only on altkey up * Fix #50555 - fix settings editor memory leak * Fix #55712 - no need to focus 'a' anymore when restoring control focus after tree render * fixes #55335 * proper fix for readonly model fixes #53022 * improve FoldingRangeKind spec (for #55686) * Use class with static fields (fixes #55494) * Fixes #53671 * fixes #54630 * [html] should disable ionic suggestions by default. Currently forces deprecated Ionic v1 suggestions in .html files while typing. Fixes #53324 * cleanup deps * debug issues back to andre * update electron for smoketest * Fix #55757 - prevent settings tabs from overflowing * Fix #53897 - revert setting menu defaults to old editor * Add enum descriptions to `typescript.preferences.importModuleSpecifier` * Fix #55767 - leaking style elements from settings editor * Fix #55521 - prevent flashing when clicking in exclude control * Update Git modified color for contrast ratio, fixes #53140 * Revert "Merge branch 'master' of github.com:Microsoft/vscode" This reverts commit bf46b6bfbae0cab99c2863e1244a916181fa9fbc, reversing changes made to e275a424483dfb4ed33b428c97d5e2c441d6b917. * Revert "Revert "Merge branch 'master' of github.com:Microsoft/vscode"" This reverts commit 53949d963f39e40757557c6526332354a31d9154. * don't ask to install an incomplete menu * Fix NPE in terminal AccessibilityManager Fixes #55744 * don't display fallback menu unless we've closed the last window * fixes #55547 * Fix smoke tests for extension search box * Update OSSREADME.json for Electron 2.0.5 * Update distro Includes Chromium license changes * fix #55455 * fix #55865 * fixes #55893 * Fix bug causing workspace recommendations to go away upon ignoring a recommendation (#55805) * Fix bug causing workspace recommendations to go away upon ignoring a recommendation * ONly show on @recommended or @recommended:workspace * Make more consistant * Fix #55911 * Understand json activity (#55926) * Understand json file activity * Refactoring * adding composer.json * Distro update for experiments * use terminal.processId for auto-attach; fixes #55918 * Reject invalid URI with vscode.openFolder (for #55891) * improve win32 setup system vs user detection fixes #55840 fixes #55840 delay winreg import related to #55840 show notification earlier related to #55840 fix #55840 update inno setup message related to #55840 * Fix #55593 - this code only operates on local paths, so use fsPath and Uri.file instead * Bring back the old menu due to electron 2.0 issues (#55913) * add the old menu back for native menus * make menu labels match * `vscode.openFolder`: treat missing URI schema gracefully (for #55891) * delay EH reattach; fixes #55955 * Mark all json files under appSettingsHome as settings * Use localized strings for telemetry opt-out * Exception when saving file editor opened from remote file provider (fixes #55051) * Remove terminal menu from stable Fixes 56003 * VSCode Insiders crashes on open with TypeError: Cannot read property 'lastIndexOf' of undefined. Fixes #54933 * improve fix for #55891 * fix #55916 * Improve #55891 * increase EH debugging restart delay; fixes #55955 * Revert "Don't include non-resource entries in history quick pick" This reverts commit 37209a838e9f7e9abe6dc53ed73cdf1e03b72060. * Diff editor: horizontal scrollbar height is smaller (fixes #56062) * improve openFolder uri fix (correctly treat backslashes) * fixes #56116 repair ipc for native menubar keybindings * Fix #56240 - Open the JSON settings editor instead of the UI editor * Fix #55536 * uriDisplay: if no formatter is registered fall back to getPathlabel fixes #56104 * VSCode hangs when opening python file. Fixes #56377 * VS Code Hangs When Opening Specific PowerShell File. Fixes #56430 * Fix #56433 - search extraFileResources even when no folders open * Workaround #55649 * Fix in master #56371 * Fix tests #56371 * Fix in master #56317 * increase version to 1.26.1 * Fixes #56387: Handle SIGPIPE in extension host * fixes #56185 * Fix merge issues (part 1) * Fix build breaks (part 1) * Build breaks (part 2) * Build breaks (part 3) * More build breaks (part 4) * Fix build breaks (part 5) * WIP * Fix menus * Render query result and message panels (#2363) * Put back query editor hot exit changes * Fix grid changes that broke profiler (#2365) * Update APIs for saving query editor state * Fix restore view state for profiler and edit data * Updating custom default themes to support 4.5:1 contrast ratio * Test updates * Fix Extension Manager and Windows Setup * Update license headers * Add appveyor and travis files back * Fix hidden modal dropdown issue
This commit is contained in:
@@ -6,21 +6,30 @@
|
||||
'use strict';
|
||||
|
||||
import { Promise, TPromise } from 'vs/base/common/winjs.base';
|
||||
import { IDisposable, toDisposable } from 'vs/base/common/lifecycle';
|
||||
import { Event, Emitter, once, filterEvent } from 'vs/base/common/event';
|
||||
import { IDisposable, toDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { Event, Emitter, once, filterEvent, toPromise, Relay } from 'vs/base/common/event';
|
||||
|
||||
enum MessageType {
|
||||
RequestCommon,
|
||||
RequestCancel,
|
||||
RequestPromise,
|
||||
RequestPromiseCancel,
|
||||
ResponseInitialize,
|
||||
ResponseSuccess,
|
||||
ResponseProgress,
|
||||
ResponseError,
|
||||
ResponseErrorObj
|
||||
ResponsePromiseSuccess,
|
||||
ResponsePromiseProgress,
|
||||
ResponsePromiseError,
|
||||
ResponsePromiseErrorObj,
|
||||
|
||||
RequestEventListen,
|
||||
RequestEventDispose,
|
||||
ResponseEventFire,
|
||||
}
|
||||
|
||||
function isResponse(messageType: MessageType): boolean {
|
||||
return messageType >= MessageType.ResponseInitialize;
|
||||
return messageType === MessageType.ResponseInitialize
|
||||
|| messageType === MessageType.ResponsePromiseSuccess
|
||||
|| messageType === MessageType.ResponsePromiseProgress
|
||||
|| messageType === MessageType.ResponsePromiseError
|
||||
|| messageType === MessageType.ResponsePromiseErrorObj
|
||||
|| messageType === MessageType.ResponseEventFire;
|
||||
}
|
||||
|
||||
interface IRawMessage {
|
||||
@@ -36,7 +45,6 @@ interface IRawRequest extends IRawMessage {
|
||||
|
||||
interface IRequest {
|
||||
raw: IRawRequest;
|
||||
emitter?: Emitter<any>;
|
||||
flush?: () => void;
|
||||
}
|
||||
|
||||
@@ -65,7 +73,8 @@ enum State {
|
||||
* with at most one single return value.
|
||||
*/
|
||||
export interface IChannel {
|
||||
call(command: string, arg?: any): TPromise<any>;
|
||||
call<T>(command: string, arg?: any): TPromise<T>;
|
||||
listen<T>(event: string, arg?: any): Event<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -90,7 +99,8 @@ export interface IChannelClient {
|
||||
* channels (each from a separate client) to pick from.
|
||||
*/
|
||||
export interface IClientRouter {
|
||||
route(command: string, arg: any): string;
|
||||
routeCall(command: string, arg: any): TPromise<string>;
|
||||
routeEvent(event: string, arg: any): TPromise<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -104,6 +114,8 @@ export interface IRoutingChannelClient {
|
||||
getChannel<T extends IChannel>(channelName: string, router: IClientRouter): T;
|
||||
}
|
||||
|
||||
// TODO@joao cleanup this mess!
|
||||
|
||||
export class ChannelServer implements IChannelServer, IDisposable {
|
||||
|
||||
private channels: { [name: string]: IChannel } = Object.create(null);
|
||||
@@ -121,17 +133,22 @@ export class ChannelServer implements IChannelServer, IDisposable {
|
||||
|
||||
private onMessage(request: IRawRequest): void {
|
||||
switch (request.type) {
|
||||
case MessageType.RequestCommon:
|
||||
this.onCommonRequest(request);
|
||||
case MessageType.RequestPromise:
|
||||
this.onPromise(request);
|
||||
break;
|
||||
|
||||
case MessageType.RequestCancel:
|
||||
this.onCancelRequest(request);
|
||||
case MessageType.RequestEventListen:
|
||||
this.onEventListen(request);
|
||||
break;
|
||||
|
||||
case MessageType.RequestPromiseCancel:
|
||||
case MessageType.RequestEventDispose:
|
||||
this.disposeActiveRequest(request);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private onCommonRequest(request: IRawRequest): void {
|
||||
private onPromise(request: IRawRequest): void {
|
||||
const channel = this.channels[request.channelName];
|
||||
let promise: Promise;
|
||||
|
||||
@@ -144,7 +161,7 @@ export class ChannelServer implements IChannelServer, IDisposable {
|
||||
const id = request.id;
|
||||
|
||||
const requestPromise = promise.then(data => {
|
||||
this.protocol.send(<IRawResponse>{ id, data, type: MessageType.ResponseSuccess });
|
||||
this.protocol.send(<IRawResponse>{ id, data, type: MessageType.ResponsePromiseSuccess });
|
||||
delete this.activeRequests[request.id];
|
||||
}, data => {
|
||||
if (data instanceof Error) {
|
||||
@@ -153,21 +170,31 @@ export class ChannelServer implements IChannelServer, IDisposable {
|
||||
message: data.message,
|
||||
name: data.name,
|
||||
stack: data.stack ? (data.stack.split ? data.stack.split('\n') : data.stack) : void 0
|
||||
}, type: MessageType.ResponseError
|
||||
}, type: MessageType.ResponsePromiseError
|
||||
});
|
||||
} else {
|
||||
this.protocol.send(<IRawResponse>{ id, data, type: MessageType.ResponseErrorObj });
|
||||
this.protocol.send(<IRawResponse>{ id, data, type: MessageType.ResponsePromiseErrorObj });
|
||||
}
|
||||
|
||||
delete this.activeRequests[request.id];
|
||||
}, data => {
|
||||
this.protocol.send(<IRawResponse>{ id, data, type: MessageType.ResponseProgress });
|
||||
this.protocol.send(<IRawResponse>{ id, data, type: MessageType.ResponsePromiseProgress });
|
||||
});
|
||||
|
||||
this.activeRequests[request.id] = toDisposable(() => requestPromise.cancel());
|
||||
}
|
||||
|
||||
private onCancelRequest(request: IRawRequest): void {
|
||||
private onEventListen(request: IRawRequest): void {
|
||||
const channel = this.channels[request.channelName];
|
||||
|
||||
const id = request.id;
|
||||
const event = channel.listen(request.name, request.arg);
|
||||
const disposable = event(data => this.protocol.send(<IRawResponse>{ id, data, type: MessageType.ResponseEventFire }));
|
||||
|
||||
this.activeRequests[request.id] = disposable;
|
||||
}
|
||||
|
||||
private disposeActiveRequest(request: IRawRequest): void {
|
||||
const disposable = this.activeRequests[request.id];
|
||||
|
||||
if (disposable) {
|
||||
@@ -190,63 +217,86 @@ export class ChannelServer implements IChannelServer, IDisposable {
|
||||
|
||||
export class ChannelClient implements IChannelClient, IDisposable {
|
||||
|
||||
private state: State;
|
||||
private activeRequests: Promise[];
|
||||
private bufferedRequests: IRequest[];
|
||||
private handlers: { [id: number]: IHandler; };
|
||||
private lastRequestId: number;
|
||||
private state: State = State.Uninitialized;
|
||||
private activeRequests: IDisposable[] = [];
|
||||
private bufferedRequests: IRequest[] = [];
|
||||
private handlers: { [id: number]: IHandler; } = Object.create(null);
|
||||
private lastRequestId: number = 0;
|
||||
private protocolListener: IDisposable;
|
||||
|
||||
private _onDidInitialize = new Emitter<void>();
|
||||
readonly onDidInitialize = this._onDidInitialize.event;
|
||||
|
||||
constructor(private protocol: IMessagePassingProtocol) {
|
||||
this.state = State.Uninitialized;
|
||||
this.activeRequests = [];
|
||||
this.bufferedRequests = [];
|
||||
this.handlers = Object.create(null);
|
||||
this.lastRequestId = 0;
|
||||
this.protocolListener = this.protocol.onMessage(r => this.onMessage(r));
|
||||
}
|
||||
|
||||
getChannel<T extends IChannel>(channelName: string): T {
|
||||
const call = (command: string, arg: any) => this.request(channelName, command, arg);
|
||||
return { call } as T;
|
||||
const call = (command: string, arg: any) => this.requestPromise(channelName, command, arg);
|
||||
const listen = (event: string, arg: any) => this.requestEvent(channelName, event, arg);
|
||||
|
||||
return { call, listen } as T;
|
||||
}
|
||||
|
||||
private request(channelName: string, name: string, arg: any): Promise {
|
||||
const request = {
|
||||
raw: {
|
||||
id: this.lastRequestId++,
|
||||
type: MessageType.RequestCommon,
|
||||
channelName,
|
||||
name,
|
||||
arg
|
||||
}
|
||||
};
|
||||
private requestPromise(channelName: string, name: string, arg: any): TPromise<any> {
|
||||
const id = this.lastRequestId++;
|
||||
const type = MessageType.RequestPromise;
|
||||
const request = { raw: { id, type, channelName, name, arg } };
|
||||
|
||||
const activeRequest = this.state === State.Uninitialized
|
||||
? this.bufferRequest(request)
|
||||
: this.doRequest(request);
|
||||
|
||||
this.activeRequests.push(activeRequest);
|
||||
const disposable = toDisposable(() => activeRequest.cancel());
|
||||
this.activeRequests.push(disposable);
|
||||
|
||||
activeRequest
|
||||
.then(null, _ => null)
|
||||
.done(() => this.activeRequests = this.activeRequests.filter(i => i !== activeRequest));
|
||||
.done(() => this.activeRequests = this.activeRequests.filter(el => el !== disposable));
|
||||
|
||||
return activeRequest;
|
||||
}
|
||||
|
||||
private requestEvent(channelName: string, name: string, arg: any): Event<any> {
|
||||
const id = this.lastRequestId++;
|
||||
const type = MessageType.RequestEventListen;
|
||||
const request = { raw: { id, type, channelName, name, arg } };
|
||||
|
||||
let uninitializedPromise: TPromise<any> | null = null;
|
||||
const emitter = new Emitter<any>({
|
||||
onFirstListenerAdd: () => {
|
||||
uninitializedPromise = this.whenInitialized();
|
||||
uninitializedPromise.then(() => {
|
||||
uninitializedPromise = null;
|
||||
this.send(request.raw);
|
||||
});
|
||||
},
|
||||
onLastListenerRemove: () => {
|
||||
if (uninitializedPromise) {
|
||||
uninitializedPromise.cancel();
|
||||
uninitializedPromise = null;
|
||||
} else {
|
||||
this.send({ id, type: MessageType.RequestEventDispose });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.handlers[id] = response => emitter.fire(response.data);
|
||||
return emitter.event;
|
||||
}
|
||||
|
||||
private doRequest(request: IRequest): Promise {
|
||||
const id = request.raw.id;
|
||||
|
||||
return new TPromise((c, e, p) => {
|
||||
this.handlers[id] = response => {
|
||||
switch (response.type) {
|
||||
case MessageType.ResponseSuccess:
|
||||
case MessageType.ResponsePromiseSuccess:
|
||||
delete this.handlers[id];
|
||||
c(response.data);
|
||||
break;
|
||||
|
||||
case MessageType.ResponseError:
|
||||
case MessageType.ResponsePromiseError:
|
||||
delete this.handlers[id];
|
||||
const error = new Error(response.data.message);
|
||||
(<any>error).stack = response.data.stack;
|
||||
@@ -254,12 +304,12 @@ export class ChannelClient implements IChannelClient, IDisposable {
|
||||
e(error);
|
||||
break;
|
||||
|
||||
case MessageType.ResponseErrorObj:
|
||||
case MessageType.ResponsePromiseErrorObj:
|
||||
delete this.handlers[id];
|
||||
e(response.data);
|
||||
break;
|
||||
|
||||
case MessageType.ResponseProgress:
|
||||
case MessageType.ResponsePromiseProgress:
|
||||
p(response.data);
|
||||
break;
|
||||
}
|
||||
@@ -267,7 +317,7 @@ export class ChannelClient implements IChannelClient, IDisposable {
|
||||
|
||||
this.send(request.raw);
|
||||
},
|
||||
() => this.send({ id, type: MessageType.RequestCancel }));
|
||||
() => this.send({ id, type: MessageType.RequestPromiseCancel }));
|
||||
}
|
||||
|
||||
private bufferRequest(request: IRequest): Promise {
|
||||
@@ -309,6 +359,7 @@ export class ChannelClient implements IChannelClient, IDisposable {
|
||||
|
||||
if (this.state === State.Uninitialized && response.type === MessageType.ResponseInitialize) {
|
||||
this.state = State.Idle;
|
||||
this._onDidInitialize.fire();
|
||||
this.bufferedRequests.forEach(r => r.flush && r.flush());
|
||||
this.bufferedRequests = null;
|
||||
return;
|
||||
@@ -328,12 +379,19 @@ export class ChannelClient implements IChannelClient, IDisposable {
|
||||
}
|
||||
}
|
||||
|
||||
private whenInitialized(): TPromise<void> {
|
||||
if (this.state === State.Idle) {
|
||||
return TPromise.as(null);
|
||||
} else {
|
||||
return toPromise(this.onDidInitialize);
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.protocolListener.dispose();
|
||||
this.protocolListener = null;
|
||||
|
||||
this.activeRequests.forEach(r => r.cancel());
|
||||
this.activeRequests = [];
|
||||
this.activeRequests = dispose(this.activeRequests);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -381,16 +439,24 @@ export class IPCServer implements IChannelServer, IRoutingChannelClient, IDispos
|
||||
|
||||
getChannel<T extends IChannel>(channelName: string, router: IClientRouter): T {
|
||||
const call = (command: string, arg: any) => {
|
||||
const id = router.route(command, arg);
|
||||
const channelPromise = router.routeCall(command, arg)
|
||||
.then(id => this.getClient(id))
|
||||
.then(client => client.getChannel(channelName));
|
||||
|
||||
if (!id) {
|
||||
return TPromise.wrapError(new Error('Client id should be provided'));
|
||||
}
|
||||
|
||||
return this.getClient(id).then(client => client.getChannel(channelName).call(command, arg));
|
||||
return getDelayedChannel(channelPromise)
|
||||
.call(command, arg);
|
||||
};
|
||||
|
||||
return { call } as T;
|
||||
const listen = (event: string, arg: any) => {
|
||||
const channelPromise = router.routeEvent(event, arg)
|
||||
.then(id => this.getClient(id))
|
||||
.then(client => client.getChannel(channelName));
|
||||
|
||||
return getDelayedChannel(channelPromise)
|
||||
.listen(event, arg);
|
||||
};
|
||||
|
||||
return { call, listen } as T;
|
||||
}
|
||||
|
||||
registerChannel(channelName: string, channel: IChannel): void {
|
||||
@@ -398,6 +464,10 @@ export class IPCServer implements IChannelServer, IRoutingChannelClient, IDispos
|
||||
}
|
||||
|
||||
private getClient(clientId: string): TPromise<IChannelClient> {
|
||||
if (!clientId) {
|
||||
return TPromise.wrapError(new Error('Client id should be provided'));
|
||||
}
|
||||
|
||||
const client = this.channelClients[clientId];
|
||||
|
||||
if (client) {
|
||||
@@ -453,7 +523,13 @@ export class IPCClient implements IChannelClient, IChannelServer, IDisposable {
|
||||
|
||||
export function getDelayedChannel<T extends IChannel>(promise: TPromise<T>): T {
|
||||
const call = (command: string, arg: any) => promise.then(c => c.call(command, arg));
|
||||
return { call } as T;
|
||||
const listen = (event: string, arg: any) => {
|
||||
const relay = new Relay<any>();
|
||||
promise.then(c => relay.input = c.listen(event, arg));
|
||||
return relay.event;
|
||||
};
|
||||
|
||||
return { call, listen } as T;
|
||||
}
|
||||
|
||||
export function getNextTickChannel<T extends IChannel>(channel: T): T {
|
||||
@@ -469,34 +545,19 @@ export function getNextTickChannel<T extends IChannel>(channel: T): T {
|
||||
.then(() => channel.call(command, arg));
|
||||
};
|
||||
|
||||
return { call } as T;
|
||||
}
|
||||
|
||||
export type Serializer<T, R> = (obj: T) => R;
|
||||
export type Deserializer<T, R> = (raw: R) => T;
|
||||
|
||||
export function eventToCall<T>(event: Event<T>, serializer: Serializer<T, any> = t => t): TPromise<void> {
|
||||
let disposable: IDisposable;
|
||||
|
||||
return new TPromise(
|
||||
(c, e, p) => disposable = event(t => p(serializer(t))),
|
||||
() => disposable.dispose()
|
||||
);
|
||||
}
|
||||
|
||||
export function eventFromCall<T>(channel: IChannel, name: string, arg: any = null, deserializer: Deserializer<T, any> = t => t): Event<T> {
|
||||
let promise: Promise;
|
||||
|
||||
const emitter = new Emitter<any>({
|
||||
onFirstListenerAdd: () => {
|
||||
promise = channel.call(name, arg)
|
||||
.then(null, err => null, e => emitter.fire(deserializer(e)));
|
||||
},
|
||||
onLastListenerRemove: () => {
|
||||
promise.cancel();
|
||||
promise = null;
|
||||
const listen = (event: string, arg: any): Event<any> => {
|
||||
if (didTick) {
|
||||
return channel.listen(event, arg);
|
||||
}
|
||||
});
|
||||
|
||||
return emitter.event;
|
||||
const relay = new Relay();
|
||||
|
||||
TPromise.timeout(0)
|
||||
.then(() => didTick = true)
|
||||
.then(() => relay.input = channel.listen(event, arg));
|
||||
|
||||
return relay.event;
|
||||
};
|
||||
|
||||
return { call, listen } as T;
|
||||
}
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import { ChildProcess, fork } from 'child_process';
|
||||
import { IDisposable } from 'vs/base/common/lifecycle';
|
||||
import { ChildProcess, fork, ForkOptions } from 'child_process';
|
||||
import { IDisposable, toDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { TPromise } from 'vs/base/common/winjs.base';
|
||||
import { Delayer } from 'vs/base/common/async';
|
||||
import { deepClone, assign } from 'vs/base/common/objects';
|
||||
import { Emitter, fromNodeEventEmitter } from 'vs/base/common/event';
|
||||
import { Emitter, fromNodeEventEmitter, Event } from 'vs/base/common/event';
|
||||
import { createQueuedSender } from 'vs/base/node/processes';
|
||||
import { ChannelServer as IPCServer, ChannelClient as IPCClient, IChannelClient, IChannel } from 'vs/base/parts/ipc/common/ipc';
|
||||
import { isRemoteConsoleLog, log } from 'vs/base/node/console';
|
||||
@@ -74,11 +74,14 @@ export interface IIPCOptions {
|
||||
export class Client implements IChannelClient, IDisposable {
|
||||
|
||||
private disposeDelayer: Delayer<void>;
|
||||
private activeRequests: TPromise<void>[];
|
||||
private activeRequests: IDisposable[];
|
||||
private child: ChildProcess;
|
||||
private _client: IPCClient;
|
||||
private channels: { [name: string]: IChannel };
|
||||
|
||||
private _onDidProcessExit = new Emitter<{ code: number, signal: string }>();
|
||||
readonly onDidProcessExit = this._onDidProcessExit.event;
|
||||
|
||||
constructor(private modulePath: string, private options: IIPCOptions) {
|
||||
const timeout = options && options.timeout ? options.timeout : 60000;
|
||||
this.disposeDelayer = new Delayer<void>(timeout);
|
||||
@@ -89,11 +92,12 @@ export class Client implements IChannelClient, IDisposable {
|
||||
}
|
||||
|
||||
getChannel<T extends IChannel>(channelName: string): T {
|
||||
const call = (command: string, arg: any) => this.request(channelName, command, arg);
|
||||
return { call } as T;
|
||||
const call = (command: string, arg: any) => this.requestPromise(channelName, command, arg);
|
||||
const listen = (event: string, arg: any) => this.requestEvent(channelName, event, arg);
|
||||
return { call, listen } as IChannel as T;
|
||||
}
|
||||
|
||||
protected request(channelName: string, name: string, arg: any): TPromise<void> {
|
||||
protected requestPromise(channelName: string, name: string, arg: any): TPromise<void> {
|
||||
if (!this.disposeDelayer) {
|
||||
return TPromise.wrapError(new Error('disposed'));
|
||||
}
|
||||
@@ -110,7 +114,7 @@ export class Client implements IChannelClient, IDisposable {
|
||||
return;
|
||||
}
|
||||
|
||||
this.activeRequests.splice(this.activeRequests.indexOf(result), 1);
|
||||
this.activeRequests.splice(this.activeRequests.indexOf(disposable), 1);
|
||||
|
||||
if (this.activeRequests.length === 0) {
|
||||
this.disposeDelayer.trigger(() => this.disposeClient());
|
||||
@@ -118,14 +122,49 @@ export class Client implements IChannelClient, IDisposable {
|
||||
});
|
||||
}, () => request.cancel());
|
||||
|
||||
this.activeRequests.push(result);
|
||||
const disposable = toDisposable(() => result.cancel());
|
||||
this.activeRequests.push(disposable);
|
||||
return result;
|
||||
}
|
||||
|
||||
protected requestEvent<T>(channelName: string, name: string, arg: any): Event<T> {
|
||||
if (!this.disposeDelayer) {
|
||||
return Event.None;
|
||||
}
|
||||
|
||||
this.disposeDelayer.cancel();
|
||||
|
||||
let listener: IDisposable;
|
||||
const emitter = new Emitter<any>({
|
||||
onFirstListenerAdd: () => {
|
||||
const channel = this.channels[channelName] || (this.channels[channelName] = this.client.getChannel(channelName));
|
||||
const event: Event<T> = channel.listen(name, arg);
|
||||
|
||||
listener = event(emitter.fire, emitter);
|
||||
this.activeRequests.push(listener);
|
||||
|
||||
},
|
||||
onLastListenerRemove: () => {
|
||||
if (!this.activeRequests) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.activeRequests.splice(this.activeRequests.indexOf(listener), 1);
|
||||
listener.dispose();
|
||||
|
||||
if (this.activeRequests.length === 0) {
|
||||
this.disposeDelayer.trigger(() => this.disposeClient());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return emitter.event;
|
||||
}
|
||||
|
||||
private get client(): IPCClient {
|
||||
if (!this._client) {
|
||||
const args = this.options && this.options.args ? this.options.args : [];
|
||||
const forkOpts = Object.create(null);
|
||||
const forkOpts: ForkOptions = Object.create(null);
|
||||
|
||||
forkOpts.env = assign(deepClone(process.env), { 'VSCODE_PARENT_PID': String(process.pid) });
|
||||
|
||||
@@ -178,15 +217,16 @@ export class Client implements IChannelClient, IDisposable {
|
||||
process.removeListener('exit', onExit);
|
||||
|
||||
if (this.activeRequests) {
|
||||
this.activeRequests.forEach(req => req.cancel());
|
||||
this.activeRequests = [];
|
||||
this.activeRequests = dispose(this.activeRequests);
|
||||
}
|
||||
|
||||
if (code !== 0 && signal !== 'SIGTERM') {
|
||||
console.warn('IPC "' + this.options.serverName + '" crashed with exit code ' + code);
|
||||
console.warn('IPC "' + this.options.serverName + '" crashed with exit code ' + code + ' and signal ' + signal);
|
||||
this.disposeDelayer.cancel();
|
||||
this.disposeClient();
|
||||
}
|
||||
|
||||
this._onDidProcessExit.fire({ code, signal });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -203,6 +243,7 @@ export class Client implements IChannelClient, IDisposable {
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this._onDidProcessExit.dispose();
|
||||
this.disposeDelayer.cancel();
|
||||
this.disposeDelayer = null;
|
||||
this.disposeClient();
|
||||
|
||||
@@ -12,28 +12,41 @@ import { IMessagePassingProtocol, ClientConnectionEvent, IPCServer, IPCClient }
|
||||
import { join } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
import { generateUuid } from 'vs/base/common/uuid';
|
||||
import { IDisposable } from 'vs/base/common/lifecycle';
|
||||
import { TimeoutTimer } from 'vs/base/common/async';
|
||||
|
||||
export function generateRandomPipeName(): string {
|
||||
const randomSuffix = generateUuid();
|
||||
if (process.platform === 'win32') {
|
||||
return `\\\\.\\pipe\\vscode-${randomSuffix}-sock`;
|
||||
return `\\\\.\\pipe\\vscode-ipc-${randomSuffix}-sock`;
|
||||
} else {
|
||||
// Mac/Unix: use socket file
|
||||
return join(tmpdir(), `vscode-${randomSuffix}.sock`);
|
||||
return join(tmpdir(), `vscode-ipc-${randomSuffix}.sock`);
|
||||
}
|
||||
}
|
||||
|
||||
export class Protocol implements IMessagePassingProtocol {
|
||||
export class Protocol implements IDisposable, IMessagePassingProtocol {
|
||||
|
||||
private static readonly _headerLen = 17;
|
||||
private static readonly _headerLen = 5;
|
||||
|
||||
private _isDisposed: boolean;
|
||||
private _chunks: Buffer[];
|
||||
|
||||
private _firstChunkTimer: TimeoutTimer;
|
||||
private _socketDataListener: (data: Buffer) => void;
|
||||
private _socketEndListener: () => void;
|
||||
private _socketCloseListener: () => void;
|
||||
|
||||
private _onMessage = new Emitter<any>();
|
||||
|
||||
readonly onMessage: Event<any> = this._onMessage.event;
|
||||
|
||||
constructor(private _socket: Socket) {
|
||||
private _onClose = new Emitter<void>();
|
||||
readonly onClose: Event<void> = this._onClose.event;
|
||||
|
||||
constructor(private _socket: Socket, firstDataChunk?: Buffer) {
|
||||
this._isDisposed = false;
|
||||
this._chunks = [];
|
||||
|
||||
let chunks: Buffer[] = [];
|
||||
let totalLength = 0;
|
||||
|
||||
const state = {
|
||||
@@ -42,18 +55,18 @@ export class Protocol implements IMessagePassingProtocol {
|
||||
bodyLen: -1,
|
||||
};
|
||||
|
||||
_socket.on('data', (data: Buffer) => {
|
||||
const acceptChunk = (data: Buffer) => {
|
||||
|
||||
chunks.push(data);
|
||||
this._chunks.push(data);
|
||||
totalLength += data.length;
|
||||
|
||||
while (totalLength > 0) {
|
||||
|
||||
if (state.readHead) {
|
||||
// expecting header -> read 17bytes for header
|
||||
// expecting header -> read 5bytes for header
|
||||
// information: `bodyIsJson` and `bodyLen`
|
||||
if (totalLength >= Protocol._headerLen) {
|
||||
const all = Buffer.concat(chunks);
|
||||
const all = Buffer.concat(this._chunks);
|
||||
|
||||
state.bodyIsJson = all.readInt8(0) === 1;
|
||||
state.bodyLen = all.readInt32BE(1);
|
||||
@@ -61,7 +74,7 @@ export class Protocol implements IMessagePassingProtocol {
|
||||
|
||||
const rest = all.slice(Protocol._headerLen);
|
||||
totalLength = rest.length;
|
||||
chunks = [rest];
|
||||
this._chunks = [rest];
|
||||
|
||||
} else {
|
||||
break;
|
||||
@@ -73,27 +86,79 @@ export class Protocol implements IMessagePassingProtocol {
|
||||
// the actual message or wait for more data
|
||||
if (totalLength >= state.bodyLen) {
|
||||
|
||||
const all = Buffer.concat(chunks);
|
||||
const all = Buffer.concat(this._chunks);
|
||||
let message = all.toString('utf8', 0, state.bodyLen);
|
||||
if (state.bodyIsJson) {
|
||||
message = JSON.parse(message);
|
||||
}
|
||||
this._onMessage.fire(message);
|
||||
|
||||
// ensure the public getBuffer returns a valid value if invoked from the event listeners
|
||||
const rest = all.slice(state.bodyLen);
|
||||
totalLength = rest.length;
|
||||
chunks = [rest];
|
||||
this._chunks = [rest];
|
||||
|
||||
state.bodyIsJson = false;
|
||||
state.bodyLen = -1;
|
||||
state.readHead = true;
|
||||
|
||||
this._onMessage.fire(message);
|
||||
|
||||
if (this._isDisposed) {
|
||||
// check if an event listener lead to our disposal
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const acceptFirstDataChunk = () => {
|
||||
if (firstDataChunk && firstDataChunk.length > 0) {
|
||||
let tmp = firstDataChunk;
|
||||
firstDataChunk = null;
|
||||
acceptChunk(tmp);
|
||||
}
|
||||
};
|
||||
|
||||
// Make sure to always handle the firstDataChunk if no more `data` event comes in
|
||||
this._firstChunkTimer = new TimeoutTimer();
|
||||
this._firstChunkTimer.setIfNotSet(() => {
|
||||
acceptFirstDataChunk();
|
||||
}, 0);
|
||||
|
||||
this._socketDataListener = (data: Buffer) => {
|
||||
acceptFirstDataChunk();
|
||||
acceptChunk(data);
|
||||
};
|
||||
_socket.on('data', this._socketDataListener);
|
||||
|
||||
this._socketEndListener = () => {
|
||||
acceptFirstDataChunk();
|
||||
};
|
||||
_socket.on('end', this._socketEndListener);
|
||||
|
||||
this._socketCloseListener = () => {
|
||||
this._onClose.fire();
|
||||
};
|
||||
_socket.once('close', this._socketCloseListener);
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
this._isDisposed = true;
|
||||
this._firstChunkTimer.dispose();
|
||||
this._socket.removeListener('data', this._socketDataListener);
|
||||
this._socket.removeListener('end', this._socketEndListener);
|
||||
this._socket.removeListener('close', this._socketCloseListener);
|
||||
}
|
||||
|
||||
public end(): void {
|
||||
this._socket.end();
|
||||
}
|
||||
|
||||
public getBuffer(): Buffer {
|
||||
return Buffer.concat(this._chunks);
|
||||
}
|
||||
|
||||
public send(message: any): void {
|
||||
@@ -106,10 +171,10 @@ export class Protocol implements IMessagePassingProtocol {
|
||||
// ensure string
|
||||
if (typeof message !== 'string') {
|
||||
message = JSON.stringify(message);
|
||||
header.writeInt8(1, 0);
|
||||
header.writeInt8(1, 0, true);
|
||||
}
|
||||
const data = Buffer.from(message);
|
||||
header.writeInt32BE(data.length, 1);
|
||||
header.writeInt32BE(data.length, 1, true);
|
||||
|
||||
this._writeSoon(header, data);
|
||||
}
|
||||
@@ -176,18 +241,19 @@ export class Server extends IPCServer {
|
||||
|
||||
export class Client extends IPCClient {
|
||||
|
||||
private _onClose = new Emitter<void>();
|
||||
get onClose(): Event<void> { return this._onClose.event; }
|
||||
public static fromSocket(socket: Socket, id: string): Client {
|
||||
return new Client(new Protocol(socket), id);
|
||||
}
|
||||
|
||||
constructor(private socket: Socket, id: string) {
|
||||
super(new Protocol(socket), id);
|
||||
socket.once('close', () => this._onClose.fire());
|
||||
get onClose(): Event<void> { return this.protocol.onClose; }
|
||||
|
||||
constructor(private protocol: Protocol, id: string) {
|
||||
super(protocol, id);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
super.dispose();
|
||||
this.socket.end();
|
||||
this.socket = null;
|
||||
this.protocol.end();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,13 +271,14 @@ export function serve(hook: any): TPromise<Server> {
|
||||
});
|
||||
}
|
||||
|
||||
export function connect(options: { host: string, port: number }, clientId: string): TPromise<Client>;
|
||||
export function connect(port: number, clientId: string): TPromise<Client>;
|
||||
export function connect(namedPipe: string, clientId: string): TPromise<Client>;
|
||||
export function connect(hook: any, clientId: string): TPromise<Client> {
|
||||
return new TPromise<Client>((c, e) => {
|
||||
const socket = createConnection(hook, () => {
|
||||
socket.removeListener('error', e);
|
||||
c(new Client(socket, clientId));
|
||||
c(Client.fromSocket(socket, clientId));
|
||||
});
|
||||
|
||||
socket.once('error', e);
|
||||
|
||||
@@ -87,4 +87,39 @@ suite('IPC, Socket Protocol', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('can devolve to a socket and evolve again without losing data', () => {
|
||||
let resolve: (v: void) => void;
|
||||
let result = new TPromise<void>((_resolve, _reject) => {
|
||||
resolve = _resolve;
|
||||
});
|
||||
const sender = new Protocol(stream);
|
||||
const receiver1 = new Protocol(stream);
|
||||
|
||||
assert.equal(stream.listenerCount('data'), 2);
|
||||
assert.equal(stream.listenerCount('end'), 2);
|
||||
|
||||
receiver1.onMessage((msg) => {
|
||||
assert.equal(msg.value, 1);
|
||||
|
||||
let buffer = receiver1.getBuffer();
|
||||
receiver1.dispose();
|
||||
|
||||
assert.equal(stream.listenerCount('data'), 1);
|
||||
assert.equal(stream.listenerCount('end'), 1);
|
||||
|
||||
const receiver2 = new Protocol(stream, buffer);
|
||||
receiver2.onMessage((msg) => {
|
||||
assert.equal(msg.value, 2);
|
||||
resolve(void 0);
|
||||
});
|
||||
});
|
||||
|
||||
const msg1 = { value: 1 };
|
||||
const msg2 = { value: 2 };
|
||||
sender.send(msg1);
|
||||
sender.send(msg2);
|
||||
|
||||
return result;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,10 +24,6 @@ suite('IPC', () => {
|
||||
suite('child process', () => {
|
||||
|
||||
test('createChannel', () => {
|
||||
if (process.env['VSCODE_PID']) {
|
||||
return undefined; // this test fails when run from within VS Code
|
||||
}
|
||||
|
||||
const client = createClient();
|
||||
const channel = client.getChannel<ITestChannel>('test');
|
||||
const service = new TestServiceClient(channel);
|
||||
@@ -41,10 +37,6 @@ suite('IPC', () => {
|
||||
});
|
||||
|
||||
test('cancellation', () => {
|
||||
if (process.env['VSCODE_PID']) {
|
||||
return undefined; // this test fails when run from within VS Code
|
||||
}
|
||||
|
||||
const client = createClient();
|
||||
const channel = client.getChannel<ITestChannel>('test');
|
||||
const service = new TestServiceClient(channel);
|
||||
@@ -61,10 +53,6 @@ suite('IPC', () => {
|
||||
});
|
||||
|
||||
test('events', () => {
|
||||
if (process.env['VSCODE_PID']) {
|
||||
return undefined; // this test fails when run from within VS Code
|
||||
}
|
||||
|
||||
const client = createClient();
|
||||
const channel = client.getChannel<ITestChannel>('test');
|
||||
const service = new TestServiceClient(channel);
|
||||
@@ -87,10 +75,6 @@ suite('IPC', () => {
|
||||
});
|
||||
|
||||
test('event dispose', () => {
|
||||
if (process.env['VSCODE_PID']) {
|
||||
return undefined; // this test fails when run from within VS Code
|
||||
}
|
||||
|
||||
const client = createClient();
|
||||
const channel = client.getChannel<ITestChannel>('test');
|
||||
const service = new TestServiceClient(channel);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
'use strict';
|
||||
|
||||
import { TPromise, PPromise } from 'vs/base/common/winjs.base';
|
||||
import { IChannel, eventToCall, eventFromCall } from 'vs/base/parts/ipc/common/ipc';
|
||||
import { IChannel } from 'vs/base/parts/ipc/common/ipc';
|
||||
import { Event, Emitter } from 'vs/base/common/event';
|
||||
|
||||
export interface IMarcoPoloEvent {
|
||||
@@ -68,6 +68,9 @@ export class TestService implements ITestService {
|
||||
}
|
||||
|
||||
export interface ITestChannel extends IChannel {
|
||||
listen<IMarcoPoloEvent>(event: 'marco'): Event<IMarcoPoloEvent>;
|
||||
listen<T>(event: string, arg?: any): Event<T>;
|
||||
|
||||
call(command: 'marco'): TPromise<any>;
|
||||
call(command: 'pong', ping: string): TPromise<any>;
|
||||
call(command: 'cancelMe'): TPromise<any>;
|
||||
@@ -79,12 +82,19 @@ export class TestChannel implements ITestChannel {
|
||||
|
||||
constructor(private testService: ITestService) { }
|
||||
|
||||
listen(event: string, arg?: any): Event<any> {
|
||||
switch (event) {
|
||||
case 'marco': return this.testService.onMarco;
|
||||
}
|
||||
|
||||
throw new Error('Event not found');
|
||||
}
|
||||
|
||||
call(command: string, ...args: any[]): TPromise<any> {
|
||||
switch (command) {
|
||||
case 'pong': return this.testService.pong(args[0]);
|
||||
case 'cancelMe': return this.testService.cancelMe();
|
||||
case 'marco': return this.testService.marco();
|
||||
case 'event:marco': return eventToCall(this.testService.onMarco);
|
||||
case 'batchPerf': return this.testService.batchPerf(args[0].batches, args[0].size, args[0].dataSize);
|
||||
default: return TPromise.wrapError(new Error('command not found'));
|
||||
}
|
||||
@@ -93,12 +103,9 @@ export class TestChannel implements ITestChannel {
|
||||
|
||||
export class TestServiceClient implements ITestService {
|
||||
|
||||
private _onMarco: Event<IMarcoPoloEvent>;
|
||||
get onMarco(): Event<IMarcoPoloEvent> { return this._onMarco; }
|
||||
get onMarco(): Event<IMarcoPoloEvent> { return this.channel.listen('marco'); }
|
||||
|
||||
constructor(private channel: ITestChannel) {
|
||||
this._onMarco = eventFromCall<IMarcoPoloEvent>(channel, 'event:marco');
|
||||
}
|
||||
constructor(private channel: ITestChannel) { }
|
||||
|
||||
marco(): TPromise<string> {
|
||||
return this.channel.call('marco');
|
||||
|
||||
@@ -37,15 +37,15 @@ let IDS = 0;
|
||||
|
||||
export class QuickOpenItemAccessorClass implements IItemAccessor<QuickOpenEntry> {
|
||||
|
||||
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,72 @@ 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 {
|
||||
return this.getLabel();
|
||||
getAriaLabel(): string {
|
||||
return [this.getLabel(), this.getDescription(), this.getDetail()]
|
||||
.filter(s => !!s)
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 +143,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 +173,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 +183,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 +192,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 +213,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<IAction[]> {
|
||||
getActions(tree: ITree, element: any): TPromise<IAction[]> {
|
||||
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<IAction[]> {
|
||||
getSecondaryActions(tree: ITree, element: any): TPromise<IAction[]> {
|
||||
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 +335,7 @@ class Renderer implements IRenderer<QuickOpenEntry> {
|
||||
this.actionRunner = actionRunner;
|
||||
}
|
||||
|
||||
public getHeight(entry: QuickOpenEntry): number {
|
||||
getHeight(entry: QuickOpenEntry): number {
|
||||
if (entry.getDetail()) {
|
||||
return 44;
|
||||
}
|
||||
@@ -341,7 +343,7 @@ class Renderer implements IRenderer<QuickOpenEntry> {
|
||||
return 22;
|
||||
}
|
||||
|
||||
public getTemplateId(entry: QuickOpenEntry): string {
|
||||
getTemplateId(entry: QuickOpenEntry): string {
|
||||
if (entry instanceof QuickOpenEntryGroup) {
|
||||
return templateEntryGroup;
|
||||
}
|
||||
@@ -349,7 +351,7 @@ class Renderer implements IRenderer<QuickOpenEntry> {
|
||||
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 +412,7 @@ class Renderer implements IRenderer<QuickOpenEntry> {
|
||||
};
|
||||
}
|
||||
|
||||
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 +482,7 @@ class Renderer implements IRenderer<QuickOpenEntry> {
|
||||
}
|
||||
}
|
||||
|
||||
public disposeTemplate(templateId: string, templateData: IQuickOpenEntryGroupTemplateData): void {
|
||||
disposeTemplate(templateId: string, templateData: IQuickOpenEntryGroupTemplateData): void {
|
||||
const data = templateData as IQuickOpenEntryGroupTemplateData;
|
||||
data.actionBar.dispose();
|
||||
data.actionBar = null;
|
||||
@@ -501,7 +503,8 @@ export class QuickOpenModel implements
|
||||
IModel<QuickOpenEntry>,
|
||||
IDataSource<QuickOpenEntry>,
|
||||
IFilter<QuickOpenEntry>,
|
||||
IRunner<QuickOpenEntry>
|
||||
IRunner<QuickOpenEntry>,
|
||||
IAccessiblityProvider<QuickOpenEntry>
|
||||
{
|
||||
private _entries: QuickOpenEntry[];
|
||||
private _dataSource: IDataSource<QuickOpenEntry>;
|
||||
@@ -519,21 +522,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 +545,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 +556,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 +564,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 +581,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<any[]> {
|
||||
getChildren(tree: ITree, element: any): TPromise<any[]> {
|
||||
const model = this.modelProvider.getModel();
|
||||
return TPromise.as(model === element ? model.entries : []);
|
||||
}
|
||||
|
||||
public getParent(tree: ITree, element: any): TPromise<any> {
|
||||
getParent(tree: ITree, element: any): TPromise<any> {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -103,12 +103,12 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
private inputBox: InputBox;
|
||||
private inputContainer: Builder;
|
||||
private helpText: Builder;
|
||||
private resultCount: Builder;
|
||||
private treeContainer: Builder;
|
||||
private progressBar: ProgressBar;
|
||||
private visible: boolean;
|
||||
private isLoosingFocus: boolean;
|
||||
private callbacks: IQuickOpenCallbacks;
|
||||
private toUnbind: IDisposable[];
|
||||
private quickNavigateConfiguration: IQuickNavigateConfiguration;
|
||||
private container: HTMLElement;
|
||||
private treeElement: HTMLElement;
|
||||
@@ -120,8 +120,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 +131,19 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
this.model = null;
|
||||
}
|
||||
|
||||
public getElement(): HTMLElement {
|
||||
getElement(): HTMLElement {
|
||||
return $(this.builder).getHTMLElement();
|
||||
}
|
||||
|
||||
public getModel(): IModel<any> {
|
||||
getModel(): IModel<any> {
|
||||
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
|
||||
@@ -152,6 +153,15 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
DOM.EventHelper.stop(e, true);
|
||||
|
||||
this.hide(HideReason.CANCELED);
|
||||
} else if (keyboardEvent.keyCode === KeyCode.Tab && !keyboardEvent.altKey && !keyboardEvent.ctrlKey && !keyboardEvent.metaKey) {
|
||||
const stops = e.currentTarget.querySelectorAll('input, .monaco-tree, .monaco-tree-row.focused .action-label.icon');
|
||||
if (keyboardEvent.shiftKey && keyboardEvent.target === stops[0]) {
|
||||
DOM.EventHelper.stop(e, true);
|
||||
stops[stops.length - 1].focus();
|
||||
} else if (!keyboardEvent.shiftKey && keyboardEvent.target === stops[stops.length - 1]) {
|
||||
DOM.EventHelper.stop(e, true);
|
||||
stops[0].focus();
|
||||
}
|
||||
}
|
||||
})
|
||||
.on(DOM.EventType.CONTEXT_MENU, (e: Event) => DOM.EventHelper.stop(e, true)) // Do this to fix an issue on Mac where the menu goes into the way
|
||||
@@ -159,13 +169,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 +187,7 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
inputValidationWarningBorder: this.styles.inputValidationWarningBorder,
|
||||
inputValidationErrorBackground: this.styles.inputValidationErrorBackground,
|
||||
inputValidationErrorBorder: this.styles.inputValidationErrorBorder
|
||||
});
|
||||
}));
|
||||
|
||||
// ARIA
|
||||
this.inputElement = this.inputBox.inputElement;
|
||||
@@ -223,13 +233,19 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
});
|
||||
});
|
||||
|
||||
// Result count for screen readers
|
||||
this.resultCount = div.div({
|
||||
'class': 'quick-open-result-count',
|
||||
'aria-live': 'polite'
|
||||
}).clone();
|
||||
|
||||
// Tree
|
||||
this.treeContainer = div.div({
|
||||
'class': 'quick-open-tree'
|
||||
}, 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)),
|
||||
@@ -243,17 +259,17 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
horizontalScrollMode: ScrollbarVisibility.Hidden,
|
||||
ariaLabel: nls.localize('treeAriaLabel', "Quick Picker"),
|
||||
keyboardSupport: this.options.keyboardSupport,
|
||||
preventRootFocus: true
|
||||
});
|
||||
preventRootFocus: false
|
||||
}));
|
||||
|
||||
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;
|
||||
@@ -348,13 +364,13 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) {
|
||||
DOM.EventHelper.stop(e, true);
|
||||
this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey);
|
||||
this.inputBox.inputElement.focus();
|
||||
this.treeElement.focus();
|
||||
}
|
||||
});
|
||||
return this.builder.getHTMLElement();
|
||||
}
|
||||
|
||||
public style(styles: IQuickOpenStyles): void {
|
||||
style(styles: IQuickOpenStyles): void {
|
||||
this.styles = styles;
|
||||
|
||||
this.applyStyles();
|
||||
@@ -442,7 +458,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 +564,9 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
};
|
||||
}
|
||||
|
||||
public show(prefix: string, options?: IShowOptions): void;
|
||||
public show(input: IModel<any>, options?: IShowOptions): void;
|
||||
public show(param: any, options?: IShowOptions): void {
|
||||
show(prefix: string, options?: IShowOptions): void;
|
||||
show(input: IModel<any>, options?: IShowOptions): void;
|
||||
show(param: any, options?: IShowOptions): void {
|
||||
this.visible = true;
|
||||
this.isLoosingFocus = false;
|
||||
this.quickNavigateConfiguration = options ? options.quickNavigateConfiguration : void 0;
|
||||
@@ -619,9 +635,12 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
// Indicate entries to tree
|
||||
this.tree.layout();
|
||||
|
||||
const entries = input ? input.entries.filter(e => this.isElementVisible(input, e)) : [];
|
||||
this.updateResultCount(entries.length);
|
||||
|
||||
// Handle auto focus
|
||||
if (input && input.entries.some(e => this.isElementVisible(input, e))) {
|
||||
this.autoFocus(input, autoFocus);
|
||||
if (entries.length) {
|
||||
this.autoFocus(input, entries, autoFocus);
|
||||
}
|
||||
}, errors.onUnexpectedError);
|
||||
}
|
||||
@@ -634,8 +653,7 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
return input.filter.isVisible(e);
|
||||
}
|
||||
|
||||
private autoFocus(input: IModel<any>, autoFocus: IAutoFocus = {}): void {
|
||||
const entries = input.entries.filter(e => this.isElementVisible(input, e));
|
||||
private autoFocus(input: IModel<any>, entries: any[], autoFocus: IAutoFocus = {}): void {
|
||||
|
||||
// First check for auto focus of prefix matches
|
||||
if (autoFocus.autoFocusPrefixMatch) {
|
||||
@@ -696,7 +714,7 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
}
|
||||
}
|
||||
|
||||
public refresh(input?: IModel<any>, autoFocus?: IAutoFocus): void {
|
||||
refresh(input?: IModel<any>, autoFocus?: IAutoFocus): void {
|
||||
if (!this.isVisible()) {
|
||||
return;
|
||||
}
|
||||
@@ -716,11 +734,13 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
// Indicate entries to tree
|
||||
this.tree.layout();
|
||||
|
||||
const entries = input ? input.entries.filter(e => this.isElementVisible(input, e)) : [];
|
||||
this.updateResultCount(entries.length);
|
||||
|
||||
// Handle auto focus
|
||||
if (autoFocus) {
|
||||
let doAutoFocus = autoFocus && input && input.entries.some(e => this.isElementVisible(input, e));
|
||||
if (doAutoFocus) {
|
||||
this.autoFocus(input, autoFocus);
|
||||
if (entries.length) {
|
||||
this.autoFocus(input, entries, autoFocus);
|
||||
}
|
||||
}
|
||||
}, errors.onUnexpectedError);
|
||||
@@ -760,7 +780,11 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
return height;
|
||||
}
|
||||
|
||||
public hide(reason?: HideReason): void {
|
||||
updateResultCount(count: number) {
|
||||
this.resultCount.text(nls.localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results", count));
|
||||
}
|
||||
|
||||
hide(reason?: HideReason): void {
|
||||
if (!this.isVisible()) {
|
||||
return;
|
||||
}
|
||||
@@ -801,17 +825,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 +849,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<any>, autoFocus: IAutoFocus, ariaLabel?: string): void {
|
||||
setInput(input: IModel<any>, autoFocus: IAutoFocus, ariaLabel?: string): void {
|
||||
if (!this.isVisible()) {
|
||||
return;
|
||||
}
|
||||
@@ -864,29 +888,29 @@ export class QuickOpenWidget implements IModelProvider {
|
||||
}, 500);
|
||||
}
|
||||
|
||||
public getInput(): IModel<any> {
|
||||
getInput(): IModel<any> {
|
||||
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 +919,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 +941,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 +995,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,11 @@
|
||||
height: 25px;
|
||||
}
|
||||
|
||||
.monaco-quick-open-widget .quick-open-result-count {
|
||||
position: absolute;
|
||||
left: -10000px;
|
||||
}
|
||||
|
||||
.monaco-quick-open-widget .quick-open-tree {
|
||||
line-height: 22px;
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ export interface ITree {
|
||||
onDidExpandItem: Event<IItemExpandEvent>;
|
||||
onDidCollapseItem: Event<IItemCollapseEvent>;
|
||||
onDidDispose: Event<void>;
|
||||
onDidScroll: Event<void>;
|
||||
|
||||
/**
|
||||
* Returns the tree's DOM element.
|
||||
@@ -108,13 +109,6 @@ export interface ITree {
|
||||
*/
|
||||
collapseAll(elements?: any[], recursive?: boolean): WinJS.Promise;
|
||||
|
||||
/**
|
||||
* Collapses several elements.
|
||||
* Collapses all elements at the greatest tree depth that has expanded elements.
|
||||
* The returned promise returns a boolean for whether the elements were collapsed or not.
|
||||
*/
|
||||
collapseDeepestExpandedLevel(): WinJS.Promise;
|
||||
|
||||
/**
|
||||
* Toggles an element's expansion state.
|
||||
*/
|
||||
@@ -148,6 +142,11 @@ export interface ITree {
|
||||
*/
|
||||
getRelativeTop(element: any): number;
|
||||
|
||||
/**
|
||||
* Returns the top-most visible element.
|
||||
*/
|
||||
getFirstVisibleElement(): any;
|
||||
|
||||
/**
|
||||
* Returns a number between 0 and 1 representing how much the tree is scroll down. 0 means all the way
|
||||
* to the top; 1 means all the way down.
|
||||
@@ -695,6 +694,7 @@ export interface ITreeOptions extends ITreeStyles {
|
||||
ariaLabel?: string;
|
||||
keyboardSupport?: boolean;
|
||||
preventRootFocus?: boolean;
|
||||
showLoading?: boolean;
|
||||
}
|
||||
|
||||
export interface ITreeStyler {
|
||||
|
||||
@@ -14,7 +14,7 @@ import * as dom from 'vs/base/browser/dom';
|
||||
import * as mouse from 'vs/base/browser/mouseEvent';
|
||||
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
|
||||
import * as _ from 'vs/base/parts/tree/browser/tree';
|
||||
import { KeyCode, KeyMod, Keybinding, createKeybinding, SimpleKeybinding } from 'vs/base/common/keyCodes';
|
||||
import { KeyCode, KeyMod, Keybinding, createKeybinding, SimpleKeybinding, createSimpleKeybinding } from 'vs/base/common/keyCodes';
|
||||
|
||||
export interface IKeyBindingCallback {
|
||||
(tree: _.ITree, event: IKeyboardEvent): void;
|
||||
@@ -62,7 +62,17 @@ export class KeybindingDispatcher {
|
||||
this._arr = [];
|
||||
}
|
||||
|
||||
public set(keybinding: number, callback: IKeyBindingCallback) {
|
||||
public has(keybinding: KeyCode): boolean {
|
||||
let target = createSimpleKeybinding(keybinding, platform.OS);
|
||||
for (const a of this._arr) {
|
||||
if (target.equals(a.keybinding)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public set(keybinding: KeyCode, callback: IKeyBindingCallback) {
|
||||
this._arr.push({
|
||||
keybinding: createKeybinding(keybinding, platform.OS),
|
||||
callback: callback
|
||||
@@ -124,6 +134,10 @@ export class DefaultController implements _.IController {
|
||||
return false; // Ignore event if target is a form input field (avoids browser specific issues)
|
||||
}
|
||||
|
||||
if (dom.findParentWithClass(event.target, 'scrollbar', 'monaco-tree')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (dom.findParentWithClass(event.target, 'monaco-action-bar', 'row')) { // TODO@Joao not very nice way of checking for the action bar (implicit knowledge)
|
||||
return false; // Ignore event if target is over an action bar of the row
|
||||
}
|
||||
@@ -158,17 +172,16 @@ export class DefaultController implements _.IController {
|
||||
}
|
||||
|
||||
protected onLeftClick(tree: _.ITree, element: any, eventish: ICancelableEvent, origin: string = 'mouse'): boolean {
|
||||
const payload = { origin: origin, originalEvent: eventish };
|
||||
const event = <mouse.IMouseEvent>eventish;
|
||||
const isDoubleClick = (origin === 'mouse' && event.detail === 2);
|
||||
const payload = { origin: origin, originalEvent: eventish, didClickOnTwistie: this.isClickOnTwistie(event) };
|
||||
|
||||
if (tree.getInput() === element) {
|
||||
tree.clearFocus(payload);
|
||||
tree.clearSelection(payload);
|
||||
} else {
|
||||
const isMouseDown = eventish && event.browserEvent && event.browserEvent.type === 'mousedown';
|
||||
if (!isMouseDown) {
|
||||
eventish.preventDefault(); // we cannot preventDefault onMouseDown because this would break DND otherwise
|
||||
const isSingleMouseDown = eventish && event.browserEvent && event.browserEvent.type === 'mousedown' && event.browserEvent.detail === 1;
|
||||
if (!isSingleMouseDown) {
|
||||
eventish.preventDefault(); // we cannot preventDefault onMouseDown with single click because this would break DND otherwise
|
||||
}
|
||||
eventish.stopPropagation();
|
||||
|
||||
@@ -176,7 +189,7 @@ export class DefaultController implements _.IController {
|
||||
tree.setSelection([element], payload);
|
||||
tree.setFocus(element, payload);
|
||||
|
||||
if (this.openOnSingleClick || isDoubleClick || this.isClickOnTwistie(event)) {
|
||||
if (this.shouldToggleExpansion(element, event, origin)) {
|
||||
if (tree.isExpanded(element)) {
|
||||
tree.collapse(element).done(null, errors.onUnexpectedError);
|
||||
} else {
|
||||
@@ -188,6 +201,11 @@ export class DefaultController implements _.IController {
|
||||
return true;
|
||||
}
|
||||
|
||||
protected shouldToggleExpansion(element: any, event: mouse.IMouseEvent, origin: string): boolean {
|
||||
const isDoubleClick = (origin === 'mouse' && event.detail === 2);
|
||||
return this.openOnSingleClick || isDoubleClick || this.isClickOnTwistie(event);
|
||||
}
|
||||
|
||||
protected setOpenMode(openMode: OpenMode) {
|
||||
this.options.openMode = openMode;
|
||||
}
|
||||
@@ -197,13 +215,20 @@ export class DefaultController implements _.IController {
|
||||
}
|
||||
|
||||
protected isClickOnTwistie(event: mouse.IMouseEvent): boolean {
|
||||
const target = event.target as HTMLElement;
|
||||
let element = event.target as HTMLElement;
|
||||
|
||||
// There is no way to find out if the ::before element is clicked where
|
||||
// the twistie is drawn, but the <div class="content"> element in the
|
||||
// tree item is the only thing we get back as target when the user clicks
|
||||
// on the twistie.
|
||||
return target && target.className === 'content' && dom.hasClass(target.parentElement, 'monaco-tree-row');
|
||||
if (!dom.hasClass(element, 'content')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const twistieStyle = window.getComputedStyle(element, ':before');
|
||||
|
||||
if (twistieStyle.backgroundImage === 'none' || twistieStyle.display === 'none') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const twistieWidth = parseInt(twistieStyle.width) + parseInt(twistieStyle.paddingRight);
|
||||
return event.browserEvent.offsetX <= twistieWidth;
|
||||
}
|
||||
|
||||
public onContextMenu(tree: _.ITree, element: any, event: _.ContextMenuEvent): boolean {
|
||||
|
||||
@@ -92,6 +92,7 @@ export class Tree implements _.ITree {
|
||||
options.alwaysFocused = options.alwaysFocused === true ? true : false;
|
||||
options.useShadows = options.useShadows === false ? false : true;
|
||||
options.paddingOnRow = options.paddingOnRow === false ? false : true;
|
||||
options.showLoading = options.showLoading === false ? false : true;
|
||||
|
||||
this.context = new TreeContext(this, configuration, options);
|
||||
this.model = new Model.TreeModel(this.context);
|
||||
@@ -118,6 +119,10 @@ export class Tree implements _.ITree {
|
||||
return this.view && this.view.onDOMBlur;
|
||||
}
|
||||
|
||||
get onDidScroll(): Event<void> {
|
||||
return this.view && this.view.onDidScroll;
|
||||
}
|
||||
|
||||
public getHTMLElement(): HTMLElement {
|
||||
return this.view.getHTMLElement();
|
||||
}
|
||||
@@ -179,10 +184,6 @@ export class Tree implements _.ITree {
|
||||
return this.model.collapseAll(elements, recursive);
|
||||
}
|
||||
|
||||
public collapseDeepestExpandedLevel(): WinJS.Promise {
|
||||
return this.model.collapseDeepestExpandedLevel();
|
||||
}
|
||||
|
||||
public toggleExpansion(element: any, recursive: boolean = false): WinJS.Promise {
|
||||
return this.model.toggleExpansion(element, recursive);
|
||||
}
|
||||
@@ -208,6 +209,11 @@ export class Tree implements _.ITree {
|
||||
return this.view.getRelativeTop(item);
|
||||
}
|
||||
|
||||
public getFirstVisibleElement(): any {
|
||||
return this.view.getFirstVisibleElement();
|
||||
|
||||
}
|
||||
|
||||
public getScrollPosition(): number {
|
||||
return this.view.getScrollPosition();
|
||||
}
|
||||
|
||||
@@ -507,6 +507,7 @@ export class Item {
|
||||
return child.doRefresh(recursive, true);
|
||||
}));
|
||||
} else {
|
||||
this.mapEachChild(child => child.updateVisibility());
|
||||
return WinJS.TPromise.as(null);
|
||||
}
|
||||
});
|
||||
@@ -522,13 +523,17 @@ export class Item {
|
||||
private doRefresh(recursive: boolean, safe: boolean = false): WinJS.Promise {
|
||||
this.doesHaveChildren = this.context.dataSource.hasChildren(this.context.tree, this.element);
|
||||
this.height = this._getHeight();
|
||||
this.setVisible(this._isVisible());
|
||||
this.updateVisibility();
|
||||
|
||||
this._onDidRefresh.fire(this);
|
||||
|
||||
return this.refreshChildren(recursive, safe);
|
||||
}
|
||||
|
||||
private updateVisibility(): void {
|
||||
this.setVisible(this._isVisible());
|
||||
}
|
||||
|
||||
public refresh(recursive: boolean): WinJS.Promise {
|
||||
return this.doRefresh(recursive);
|
||||
}
|
||||
@@ -554,17 +559,6 @@ export class Item {
|
||||
return result;
|
||||
}
|
||||
|
||||
public getChildren(): Item[] {
|
||||
var child = this.firstChild;
|
||||
var results = [];
|
||||
while (child) {
|
||||
results.push(child);
|
||||
child = child.next;
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private isAncestorOf(item: Item): boolean {
|
||||
while (item) {
|
||||
if (item.id === this.id) {
|
||||
@@ -1035,27 +1029,6 @@ export class TreeModel {
|
||||
return WinJS.Promise.join(promises);
|
||||
}
|
||||
|
||||
public collapseDeepestExpandedLevel(): WinJS.Promise {
|
||||
var levelToCollapse = this.findDeepestExpandedLevel(this.input, 0);
|
||||
|
||||
var items = [this.input];
|
||||
for (var i = 0; i < levelToCollapse; i++) {
|
||||
items = arrays.flatten(items.map(node => node.getChildren()));
|
||||
}
|
||||
|
||||
var promises = items.map(child => this.collapse(child, false));
|
||||
return WinJS.Promise.join(promises);
|
||||
}
|
||||
|
||||
private findDeepestExpandedLevel(item: Item, currentLevel: number): number {
|
||||
var expandedChildren = item.getChildren().filter(child => child.isExpanded());
|
||||
if (!expandedChildren.length) {
|
||||
return currentLevel;
|
||||
}
|
||||
|
||||
return Math.max(...expandedChildren.map(child => this.findDeepestExpandedLevel(child, currentLevel + 1)));
|
||||
}
|
||||
|
||||
public toggleExpansion(element: any, recursive: boolean = false): WinJS.Promise {
|
||||
return this.isExpanded(element) ? this.collapse(element, recursive) : this.expand(element);
|
||||
}
|
||||
|
||||
37
src/vs/base/parts/tree/browser/treeUtils.ts
Normal file
37
src/vs/base/parts/tree/browser/treeUtils.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
import * as _ from 'vs/base/parts/tree/browser/tree';
|
||||
|
||||
export function collapseAll(tree: _.ITree, except?: any): void {
|
||||
const nav = tree.getNavigator();
|
||||
let cur;
|
||||
while (cur = nav.next()) {
|
||||
if (!except || !isEqualOrParent(tree, except, cur)) {
|
||||
tree.collapse(cur);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function isEqualOrParent(tree: _.ITree, element: any, candidateParent: any): boolean {
|
||||
const nav = tree.getNavigator(element);
|
||||
|
||||
do {
|
||||
if (element === candidateParent) {
|
||||
return true;
|
||||
}
|
||||
} while (element = nav.parent());
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function expandAll(tree: _.ITree): void {
|
||||
const nav = tree.getNavigator();
|
||||
let cur;
|
||||
while (cur = nav.next()) {
|
||||
tree.expand(cur);
|
||||
}
|
||||
}
|
||||
@@ -220,7 +220,7 @@ export class ViewItem implements IViewItem {
|
||||
this.element.removeAttribute('id');
|
||||
}
|
||||
if (this.model.hasChildren()) {
|
||||
this.element.setAttribute('aria-expanded', String(!!this.model.isExpanded()));
|
||||
this.element.setAttribute('aria-expanded', String(!!this._styles['expanded']));
|
||||
} else {
|
||||
this.element.removeAttribute('aria-expanded');
|
||||
}
|
||||
@@ -445,6 +445,9 @@ export class TreeView extends HeightMap {
|
||||
private readonly _onDOMBlur: Emitter<void> = new Emitter<void>();
|
||||
get onDOMBlur(): Event<void> { return this._onDOMBlur.event; }
|
||||
|
||||
private readonly _onDidScroll: Emitter<void> = new Emitter<void>();
|
||||
get onDidScroll(): Event<void> { return this._onDidScroll.event; }
|
||||
|
||||
constructor(context: _.ITreeContext, container: HTMLElement) {
|
||||
super();
|
||||
|
||||
@@ -510,6 +513,7 @@ export class TreeView extends HeightMap {
|
||||
});
|
||||
this.scrollableElement.onScroll((e) => {
|
||||
this.render(e.scrollTop, e.height, e.scrollLeft, e.width, e.scrollWidth);
|
||||
this._onDidScroll.fire();
|
||||
});
|
||||
|
||||
if (Browser.isIE) {
|
||||
@@ -649,6 +653,11 @@ export class TreeView extends HeightMap {
|
||||
}
|
||||
}
|
||||
|
||||
public getFirstVisibleElement(): any {
|
||||
const item = this.itemAtIndex(this.indexAt(this.lastRenderTop));
|
||||
return item && item.model.getElement();
|
||||
}
|
||||
|
||||
private render(scrollTop: number, viewHeight: number, scrollLeft: number, viewWidth: number, scrollWidth: number): void {
|
||||
var i: number;
|
||||
var stop: number;
|
||||
@@ -867,7 +876,7 @@ export class TreeView extends HeightMap {
|
||||
var item = <Model.Item>e.item;
|
||||
var viewItem = this.items[item.id];
|
||||
|
||||
if (viewItem) {
|
||||
if (viewItem && this.context.options.showLoading) {
|
||||
viewItem.loadingTimer = setTimeout(() => {
|
||||
viewItem.loadingTimer = 0;
|
||||
viewItem.loading = true;
|
||||
@@ -915,13 +924,16 @@ export class TreeView extends HeightMap {
|
||||
let doToInsertItemsAlreadyExist: boolean;
|
||||
|
||||
if (!skipDiff) {
|
||||
const lcs = new Diff.LcsDiff({
|
||||
getLength: () => previousChildrenIds.length,
|
||||
getElementHash: (i: number) => previousChildrenIds[i]
|
||||
}, {
|
||||
const lcs = new Diff.LcsDiff(
|
||||
{
|
||||
getLength: () => previousChildrenIds.length,
|
||||
getElementAtIndex: (i: number) => previousChildrenIds[i]
|
||||
}, {
|
||||
getLength: () => afterModelItems.length,
|
||||
getElementHash: (i: number) => afterModelItems[i].id
|
||||
}, null);
|
||||
getElementAtIndex: (i: number) => afterModelItems[i].id
|
||||
},
|
||||
null
|
||||
);
|
||||
|
||||
diff = lcs.ComputeDiff(false);
|
||||
|
||||
|
||||
@@ -613,23 +613,6 @@ suite('TreeModel - Expansion', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('collapseDeepestExpandedLevel', () => {
|
||||
return model.setInput(SAMPLE.DEEP2).then(() => {
|
||||
return model.expand(SAMPLE.DEEP2.children[0]).then(() => {
|
||||
return model.expand(SAMPLE.DEEP2.children[0].children[0]).then(() => {
|
||||
|
||||
assert(model.isExpanded(SAMPLE.DEEP2.children[0]));
|
||||
assert(model.isExpanded(SAMPLE.DEEP2.children[0].children[0]));
|
||||
|
||||
return model.collapseDeepestExpandedLevel().then(() => {
|
||||
assert(model.isExpanded(SAMPLE.DEEP2.children[0]));
|
||||
assert(!model.isExpanded(SAMPLE.DEEP2.children[0].children[0]));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('auto expand single child folders', () => {
|
||||
return model.setInput(SAMPLE.DEEP).then(() => {
|
||||
return model.expand(SAMPLE.DEEP.children[0]).then(() => {
|
||||
@@ -1695,4 +1678,42 @@ suite('TreeModel - bugs', () => {
|
||||
assert.equal(counter.count, 0);
|
||||
});
|
||||
});
|
||||
|
||||
test('collapsed resolved parent should also update all children visibility on refresh', async function () {
|
||||
const counter = new EventCounter();
|
||||
const dataModel = new DynamicModel();
|
||||
|
||||
let isSonVisible = true;
|
||||
const filter: _.IFilter = {
|
||||
isVisible(_, element) {
|
||||
return element !== 'son' || isSonVisible;
|
||||
}
|
||||
};
|
||||
|
||||
const model = new TreeModel({ dataSource: dataModel, filter });
|
||||
|
||||
dataModel.addChild('root', 'father');
|
||||
dataModel.addChild('father', 'son');
|
||||
|
||||
await model.setInput('root');
|
||||
await model.expand('father');
|
||||
|
||||
let nav = model.getNavigator();
|
||||
assert.equal(nav.next().id, 'father');
|
||||
assert.equal(nav.next().id, 'son');
|
||||
assert.equal(nav.next(), null);
|
||||
|
||||
await model.collapse('father');
|
||||
isSonVisible = false;
|
||||
|
||||
await model.refresh(undefined, true);
|
||||
await model.expand('father');
|
||||
|
||||
nav = model.getNavigator();
|
||||
assert.equal(nav.next().id, 'father');
|
||||
assert.equal(nav.next(), null);
|
||||
|
||||
counter.dispose();
|
||||
model.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user