outputServices.ts 12.7 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

J
Johannes Rieken 已提交
6
import { TPromise } from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
7
import strings = require('vs/base/common/strings');
J
Johannes Rieken 已提交
8
import Event, { Emitter } from 'vs/base/common/event';
9
import { binarySearch } from 'vs/base/common/arrays';
10 11
import URI from 'vs/base/common/uri';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
J
Johannes Rieken 已提交
12 13 14 15 16
import { IEditor } from 'vs/platform/editor/common/editor';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { Registry } from 'vs/platform/platform';
import { EditorOptions } from 'vs/workbench/common/editor';
17
import { IOutputChannelIdentifier, OutputEditors, IOutputEvent, IOutputChannel, IOutputService, IOutputDelta, Extensions, OUTPUT_PANEL_ID, IOutputChannelRegistry, MAX_OUTPUT_LENGTH, OUTPUT_SCHEME, OUTPUT_MIME } from 'vs/workbench/parts/output/common/output';
J
Johannes Rieken 已提交
18 19 20 21 22
import { OutputPanel } from 'vs/workbench/parts/output/browser/outputPanel';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { OutputLinkProvider } from 'vs/workbench/parts/output/common/outputLinkProvider';
23
import { ITextModelService, ITextModelContentProvider } from 'vs/editor/common/services/resolverService';
24 25 26 27 28
import { IModel } from 'vs/editor/common/editorCommon';
import { IModeService } from 'vs/editor/common/services/modeService';
import { RunOnceScheduler } from 'vs/base/common/async';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Position } from 'vs/editor/common/core/position';
29 30

const OUTPUT_ACTIVE_CHANNEL_KEY = 'output.activechannel';
E
Erich Gamma 已提交
31

I
isidor 已提交
32
export class BufferedContent {
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

	private data: string[] = [];
	private dataIds: number[] = [];
	private idPool = 0;
	private length = 0;

	public append(content: string): void {
		this.data.push(content);
		this.dataIds.push(++this.idPool);
		this.length += content.length;
		this.trim();
	}

	public clear(): void {
		this.data.length = 0;
		this.dataIds.length = 0;
		this.length = 0;
	}

	private trim(): void {
I
isidor 已提交
53
		if (this.length < MAX_OUTPUT_LENGTH * 1.2) {
54 55 56
			return;
		}

I
isidor 已提交
57
		while (this.length > MAX_OUTPUT_LENGTH) {
58 59 60 61 62 63
			this.dataIds.shift();
			const removed = this.data.shift();
			this.length -= removed.length;
		}
	}

I
isidor 已提交
64
	public getDelta(previousDelta?: IOutputDelta): IOutputDelta {
65 66 67 68 69 70
		let idx = -1;
		if (previousDelta) {
			idx = binarySearch(this.dataIds, previousDelta.id, (a, b) => a - b);
		}

		const id = this.idPool;
I
isidor 已提交
71 72
		if (idx >= 0) {
			const value = strings.removeAnsiEscapeCodes(this.data.slice(idx + 1).join(''));
73 74 75 76 77 78 79 80
			return { value, id, append: true };
		} else {
			const value = strings.removeAnsiEscapeCodes(this.data.join(''));
			return { value, id };
		}
	}
}

E
Erich Gamma 已提交
81
export class OutputService implements IOutputService {
B
Benjamin Pasero 已提交
82

83
	public _serviceBrand: any;
E
Erich Gamma 已提交
84

85 86
	private receivedOutput: Map<string, BufferedContent> = new Map<string, BufferedContent>();
	private channels: Map<string, IOutputChannel> = new Map<string, IOutputChannel>();
E
Erich Gamma 已提交
87

I
isidor 已提交
88
	private activeChannelId: string;
E
Erich Gamma 已提交
89

90 91
	private _onOutput: Emitter<IOutputEvent>;
	private _onOutputChannel: Emitter<string>;
I
isidor 已提交
92
	private _onActiveOutputChannel: Emitter<string>;
E
Erich Gamma 已提交
93

94
	private _outputLinkDetector: OutputLinkProvider;
95
	private _outputContentProvider: OutputContentProvider;
96
	private _outputPanel: OutputPanel;
97

E
Erich Gamma 已提交
98
	constructor(
99
		@IStorageService private storageService: IStorageService,
E
Erich Gamma 已提交
100
		@IInstantiationService private instantiationService: IInstantiationService,
101
		@IPanelService private panelService: IPanelService,
J
Johannes Rieken 已提交
102
		@IWorkspaceContextService contextService: IWorkspaceContextService,
103
		@IModelService modelService: IModelService,
104
		@ITextModelService textModelResolverService: ITextModelService
E
Erich Gamma 已提交
105
	) {
106 107
		this._onOutput = new Emitter<IOutputEvent>();
		this._onOutputChannel = new Emitter<string>();
I
isidor 已提交
108
		this._onActiveOutputChannel = new Emitter<string>();
E
Erich Gamma 已提交
109

110
		const channels = this.getChannels();
I
isidor 已提交
111
		this.activeChannelId = this.storageService.get(OUTPUT_ACTIVE_CHANNEL_KEY, StorageScope.WORKSPACE, channels && channels.length > 0 ? channels[0].id : null);
112 113

		this._outputLinkDetector = new OutputLinkProvider(contextService, modelService);
114

115 116
		this._outputContentProvider = instantiationService.createInstance(OutputContentProvider, this);

117
		// Register as text model content provider for output
118
		textModelResolverService.registerTextModelContentProvider(OUTPUT_SCHEME, this._outputContentProvider);
E
Erich Gamma 已提交
119 120
	}

121 122
	public get onOutput(): Event<IOutputEvent> {
		return this._onOutput.event;
E
Erich Gamma 已提交
123 124
	}

125 126
	public get onOutputChannel(): Event<string> {
		return this._onOutputChannel.event;
E
Erich Gamma 已提交
127 128
	}

I
isidor 已提交
129 130 131 132
	public get onActiveOutputChannel(): Event<string> {
		return this._onActiveOutputChannel.event;
	}

I
isidor 已提交
133
	public getChannel(id: string): IOutputChannel {
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
		if (!this.channels.has(id)) {
			const channelData = Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannel(id);

			const self = this;
			this.channels.set(id, {
				id,
				label: channelData ? channelData.label : id,
				getOutput(before?: IOutputDelta) {
					return self.getOutput(id, before);
				},
				get scrollLock() {
					return self._outputContentProvider.scrollLock(id);
				},
				set scrollLock(value: boolean) {
					self._outputContentProvider.setScrollLock(id, value);
				},
				append: (output: string) => this.append(id, output),
				show: (preserveFocus: boolean) => this.showOutput(id, preserveFocus),
				clear: () => this.clearOutput(id),
				dispose: () => this.removeOutput(id)
			});
		}

		return this.channels.get(id);
I
isidor 已提交
158 159
	}

160 161 162 163
	public getChannels(): IOutputChannelIdentifier[] {
		return Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannels();
	}

I
isidor 已提交
164
	private append(channelId: string, output: string): void {
B
Benjamin Pasero 已提交
165

E
Erich Gamma 已提交
166
		// Initialize
I
isidor 已提交
167
		if (!this.receivedOutput.has(channelId)) {
168
			this.receivedOutput.set(channelId, new BufferedContent());
E
Erich Gamma 已提交
169

I
isidor 已提交
170
			this._onOutputChannel.fire(channelId); // emit event that we have a new channel
E
Erich Gamma 已提交
171 172 173 174
		}

		// Store
		if (output) {
175 176
			const channel = this.receivedOutput.get(channelId);
			channel.append(output);
E
Erich Gamma 已提交
177 178
		}

179
		this._onOutput.fire({ channelId: channelId, isClear: false });
E
Erich Gamma 已提交
180 181
	}

I
isidor 已提交
182 183
	public getActiveChannel(): IOutputChannel {
		return this.getChannel(this.activeChannelId);
E
Erich Gamma 已提交
184 185
	}

I
isidor 已提交
186
	private getOutput(channelId: string, previousDelta: IOutputDelta): IOutputDelta {
187
		if (this.receivedOutput.has(channelId)) {
I
isidor 已提交
188
			return this.receivedOutput.get(channelId).getDelta(previousDelta);
189 190 191
		}

		return undefined;
I
isidor 已提交
192 193
	}

194
	private clearOutput(channelId: string): void {
195 196 197 198
		if (this.receivedOutput.has(channelId)) {
			this.receivedOutput.get(channelId).clear();
			this._onOutput.fire({ channelId: channelId, isClear: true });
		}
E
Erich Gamma 已提交
199 200
	}

201 202 203 204 205 206
	private removeOutput(channelId: string): void {
		this.receivedOutput.delete(channelId);
		Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).removeChannel(channelId);
		if (this.activeChannelId === channelId) {
			const channels = this.getChannels();
			this.activeChannelId = channels.length ? channels[0].id : undefined;
207 208 209
			if (this._outputPanel && this.activeChannelId) {
				this._outputPanel.setInput(OutputEditors.getInstance(this.instantiationService, this.getChannel(this.activeChannelId)), EditorOptions.create({ preserveFocus: true }));
			}
210 211 212 213 214 215
			this._onActiveOutputChannel.fire(this.activeChannelId);
		}

		this._onOutputChannel.fire(channelId);
	}

216
	private showOutput(channelId: string, preserveFocus?: boolean): TPromise<IEditor> {
217
		const panel = this.panelService.getActivePanel();
218
		if (this.activeChannelId === channelId && panel && panel.getId() === OUTPUT_PANEL_ID) {
219 220
			return TPromise.as(<OutputPanel>panel);
		}
I
isidor 已提交
221

222
		this.activeChannelId = channelId;
I
isidor 已提交
223
		this.storageService.store(OUTPUT_ACTIVE_CHANNEL_KEY, this.activeChannelId, StorageScope.WORKSPACE);
224
		this._onActiveOutputChannel.fire(channelId); // emit event that a new channel is active
225

226
		return this.panelService.openPanel(OUTPUT_PANEL_ID, !preserveFocus).then((outputPanel: OutputPanel) => {
227 228
			this._outputPanel = outputPanel;
			return outputPanel && outputPanel.setInput(OutputEditors.getInstance(this.instantiationService, this.getChannel(this.activeChannelId)), EditorOptions.create({ preserveFocus: preserveFocus })).
229
				then(() => outputPanel);
I
isidor 已提交
230 231
		});
	}
232 233 234 235 236 237
}

class OutputContentProvider implements ITextModelContentProvider {

	private static OUTPUT_DELAY = 300;

238
	private bufferedOutput = new Map<string, IOutputDelta>();
239
	private appendOutputScheduler: { [channel: string]: RunOnceScheduler; };
240
	private channelIdsWithScrollLock: Set<string> = new Set<string>();
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
	private toDispose: IDisposable[];

	constructor(
		private outputService: IOutputService,
		@IModelService private modelService: IModelService,
		@IModeService private modeService: IModeService,
		@IPanelService private panelService: IPanelService
	) {
		this.appendOutputScheduler = Object.create(null);
		this.toDispose = [];

		this.registerListeners();
	}

	private registerListeners(): void {
		this.toDispose.push(this.outputService.onOutput(e => this.onOutputReceived(e)));
		this.toDispose.push(this.outputService.onActiveOutputChannel(channel => this.scheduleOutputAppend(channel)));
		this.toDispose.push(this.panelService.onDidPanelOpen(panel => {
			if (panel.getId() === OUTPUT_PANEL_ID) {
				this.appendOutput();
			}
		}));
	}

	private onOutputReceived(e: IOutputEvent): void {
		const model = this.getModel(e.channelId);
		if (!model) {
			return; // only react if we have a known model
		}

		// Append to model
272
		if (e.isClear) {
273
			model.setValue('');
274 275
		} else {
			this.scheduleOutputAppend(e.channelId);
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
		}
	}

	private getModel(channel: string): IModel {
		return this.modelService.getModel(URI.from({ scheme: OUTPUT_SCHEME, path: channel }));
	}

	private scheduleOutputAppend(channel: string): void {
		if (!this.isVisible(channel)) {
			return; // only if the output channel is visible
		}

		let scheduler = this.appendOutputScheduler[channel];
		if (!scheduler) {
			scheduler = new RunOnceScheduler(() => {
				if (this.isVisible(channel)) {
					this.appendOutput(channel);
				}
			}, OutputContentProvider.OUTPUT_DELAY);

			this.appendOutputScheduler[channel] = scheduler;
			this.toDispose.push(scheduler);
		}

		if (scheduler.isScheduled()) {
			return; // only if not already scheduled
		}

		scheduler.schedule();
	}

	private appendOutput(channel?: string): void {
		if (!channel) {
			const activeChannel = this.outputService.getActiveChannel();
			channel = activeChannel && activeChannel.id;
		}

		if (!channel) {
			return; // return if we do not have a valid channel to append to
		}

		const model = this.getModel(channel);
		if (!model) {
			return; // only react if we have a known model
		}

322 323 324 325 326
		const bufferedOutput = this.bufferedOutput.get(channel);
		const newOutput = this.outputService.getChannel(channel).getOutput(bufferedOutput);
		if (!newOutput) {
			model.setValue('');
			return;
327
		}
328
		this.bufferedOutput.set(channel, newOutput);
329 330

		// just fill in the full (trimmed) output if we exceed max length
331 332
		if (!newOutput.append) {
			model.setValue(newOutput.value);
333 334 335 336 337 338 339
		}

		// otherwise append
		else {
			const lastLine = model.getLineCount();
			const lastLineMaxColumn = model.getLineMaxColumn(lastLine);

340
			model.applyEdits([EditOperation.insert(new Position(lastLine, lastLineMaxColumn), newOutput.value)]);
341 342
		}

343 344 345
		if (!this.channelIdsWithScrollLock.has(channel)) {
			// reveal last line
			const panel = this.panelService.getActivePanel();
346
			(<OutputPanel>panel).revealLastLine();
347
		}
348 349 350 351 352 353 354 355
	}

	private isVisible(channel: string): boolean {
		const panel = this.panelService.getActivePanel();

		return panel && panel.getId() === OUTPUT_PANEL_ID && this.outputService.getActiveChannel().id === channel;
	}

356
	public scrollLock(channelId): boolean {
357 358 359 360 361
		return this.channelIdsWithScrollLock.has(channelId);
	}

	public setScrollLock(channelId: string, value: boolean): void {
		if (value) {
362
			this.channelIdsWithScrollLock.add(channelId);
363 364
		} else {
			this.channelIdsWithScrollLock.delete(channelId);
365 366 367
		}
	}

368
	public provideTextContent(resource: URI): TPromise<IModel> {
369 370
		const output = this.outputService.getChannel(resource.fsPath).getOutput();
		const content = output ? output.value : '';
371 372 373 374 375 376 377 378 379 380 381 382

		let codeEditorModel = this.modelService.getModel(resource);
		if (!codeEditorModel) {
			codeEditorModel = this.modelService.createModel(content, this.modeService.getOrCreateMode(OUTPUT_MIME), resource);
		}

		return TPromise.as(codeEditorModel);
	}

	public dispose(): void {
		this.toDispose = dispose(this.toDispose);
	}
383
}