outputServices.ts 15.5 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.
 *--------------------------------------------------------------------------------------------*/

6 7 8
import * as nls from 'vs/nls';
import * as fs from 'fs';
import * as paths from 'vs/base/common/paths';
J
Johannes Rieken 已提交
9 10
import { TPromise } from 'vs/base/common/winjs.base';
import Event, { Emitter } from 'vs/base/common/event';
11
import URI from 'vs/base/common/uri';
12
import { IDisposable, dispose, Disposable, toDisposable } from 'vs/base/common/lifecycle';
J
Johannes Rieken 已提交
13 14
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
15
import { Registry } from 'vs/platform/registry/common/platform';
J
Johannes Rieken 已提交
16
import { EditorOptions } from 'vs/workbench/common/editor';
17
import { IOutputChannelIdentifier, IOutputChannel, IOutputService, Extensions, OUTPUT_PANEL_ID, IOutputChannelRegistry, 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';
S
Sandeep Somavarapu 已提交
29
import { IFileService, FileChangeType } from 'vs/platform/files/common/files';
30 31
import { IPanel } from 'vs/workbench/common/panel';
import { ResourceEditorInput } from 'vs/workbench/common/editor/resourceEditorInput';
32
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
33 34 35
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { RotatingLogger } from 'spdlog';
import { toLocalISOString } from 'vs/base/common/date';
36 37

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

39
export class OutputService implements IOutputService, ITextModelContentProvider {
B
Benjamin Pasero 已提交
40

41
	public _serviceBrand: any;
E
Erich Gamma 已提交
42

S
Sandeep Somavarapu 已提交
43
	private channels: Map<string, OutputChannel> = new Map<string, OutputChannel>();
I
isidor 已提交
44
	private activeChannelId: string;
E
Erich Gamma 已提交
45

46 47
	private _onDidChannelContentChange: Emitter<string> = new Emitter<string>();
	readonly onDidChannelContentChange: Event<string> = this._onDidChannelContentChange.event;
S
Sandeep Somavarapu 已提交
48 49 50

	private _onActiveOutputChannel: Emitter<string> = new Emitter<string>();
	readonly onActiveOutputChannel: Event<string> = this._onActiveOutputChannel.event;
E
Erich Gamma 已提交
51

52
	private _outputPanel: OutputPanel;
53

E
Erich Gamma 已提交
54
	constructor(
55
		@IStorageService private storageService: IStorageService,
E
Erich Gamma 已提交
56
		@IInstantiationService private instantiationService: IInstantiationService,
57
		@IPanelService private panelService: IPanelService,
J
Johannes Rieken 已提交
58
		@IWorkspaceContextService contextService: IWorkspaceContextService,
59 60
		@IModelService private modelService: IModelService,
		@IModeService private modeService: IModeService,
61 62
		@ITextModelService textModelResolverService: ITextModelService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
63
		@IEnvironmentService private environmentService: IEnvironmentService
E
Erich Gamma 已提交
64
	) {
65
		const channels = this.getChannels();
I
isidor 已提交
66
		this.activeChannelId = this.storageService.get(OUTPUT_ACTIVE_CHANNEL_KEY, StorageScope.WORKSPACE, channels && channels.length > 0 ? channels[0].id : null);
67

B
Benjamin Pasero 已提交
68
		instantiationService.createInstance(OutputLinkProvider);
69 70

		// Register as text model content provider for output
71
		textModelResolverService.registerTextModelContentProvider(OUTPUT_SCHEME, this);
E
Erich Gamma 已提交
72

73 74 75
		this.onDidPanelOpen(this.panelService.getActivePanel());
		panelService.onDidPanelOpen(this.onDidPanelOpen, this);
		panelService.onDidPanelClose(this.onDidPanelClose, this);
E
Erich Gamma 已提交
76 77
	}

78 79 80 81 82 83
	provideTextContent(resource: URI): TPromise<IModel> {
		const channel = <OutputChannel>this.getChannel(resource.fsPath);
		return channel.getOutputDelta()
			.then(outputDelta => this.modelService.createModel(outputDelta.value, this.modeService.getOrCreateMode(OUTPUT_MIME), resource));
	}

S
Sandeep Somavarapu 已提交
84
	showChannel(id: string, preserveFocus?: boolean): TPromise<void> {
85
		if (this.isChannelShown(id)) {
S
Sandeep Somavarapu 已提交
86 87 88 89
			return TPromise.as(null);
		}

		if (this.activeChannelId) {
S
Sandeep Somavarapu 已提交
90
			this.doHideChannel(this.activeChannelId);
S
Sandeep Somavarapu 已提交
91
		}
E
Erich Gamma 已提交
92

S
Sandeep Somavarapu 已提交
93
		this.activeChannelId = id;
S
Sandeep Somavarapu 已提交
94 95
		const promise: TPromise<any> = this._outputPanel ? this.doShowChannel(id, preserveFocus) : this.panelService.openPanel(OUTPUT_PANEL_ID);
		return promise.then(() => this._onActiveOutputChannel.fire(id));
I
isidor 已提交
96 97
	}

98 99 100 101
	showChannelInEditor(channelId: string): TPromise<void> {
		return this.editorService.openEditor(this.createInput(channelId)) as TPromise;
	}

S
Sandeep Somavarapu 已提交
102
	getChannel(id: string): IOutputChannel {
103
		if (!this.channels.has(id)) {
104
			this.channels.set(id, this.createChannel(id));
S
Sandeep Somavarapu 已提交
105
		}
106
		return this.channels.get(id);
I
isidor 已提交
107 108
	}

S
Sandeep Somavarapu 已提交
109
	getChannels(): IOutputChannelIdentifier[] {
110 111 112
		return Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannels();
	}

S
Sandeep Somavarapu 已提交
113
	getActiveChannel(): IOutputChannel {
I
isidor 已提交
114
		return this.getChannel(this.activeChannelId);
E
Erich Gamma 已提交
115 116
	}

117 118 119
	private createChannel(id: string): OutputChannel {
		const channelDisposables = [];
		const channelData = Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannel(id);
120 121 122
		const file = channelData && channelData.file ? channelData.file : URI.file(paths.join(this.environmentService.userDataPath, 'outputs', toLocalISOString(new Date()).replace(/-|:|\.\d+Z$/g, ''), `${id}.output.log`));
		const channel = channelData && channelData.file ? this.instantiationService.createInstance(OutputChannel, channelData) :
			this.instantiationService.createInstance(WritableOutputChannel, { id, label: channelData ? channelData.label : '', file });
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
		channelDisposables.push(this.instantiationService.createInstance(ChannelModelUpdater, channel));
		channel.onDidChange(() => this._onDidChannelContentChange.fire(id), channelDisposables);
		channel.onDispose(() => {
			Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).removeChannel(id);
			if (this.activeChannelId === id) {
				const channels = this.getChannels();
				if (this._outputPanel && channels.length) {
					this.showChannel(channels[0].id);
				} else {
					this._onActiveOutputChannel.fire(void 0);
				}
			}
			dispose(channelDisposables);
		}, channelDisposables);

		return channel;
	}

141

142 143 144 145 146 147 148
	private isChannelShown(channelId: string): boolean {
		const panel = this.panelService.getActivePanel();
		return panel && panel.getId() === OUTPUT_PANEL_ID && this.activeChannelId === channelId;
	}

	private onDidPanelClose(panel: IPanel): void {
		if (this._outputPanel && panel.getId() === OUTPUT_PANEL_ID) {
S
Sandeep Somavarapu 已提交
149 150 151
			if (this.activeChannelId) {
				this.doHideChannel(this.activeChannelId);
			}
152 153 154 155 156 157 158 159 160 161 162 163 164 165
			this._outputPanel.clearInput();
		}
	}

	private onDidPanelOpen(panel: IPanel): void {
		if (panel && panel.getId() === OUTPUT_PANEL_ID) {
			this._outputPanel = <OutputPanel>this.panelService.getActivePanel();
			if (this.activeChannelId) {
				this.doShowChannel(this.activeChannelId, true);
			}
		}
	}

	private doShowChannel(channelId: string, preserveFocus: boolean): TPromise<void> {
S
Sandeep Somavarapu 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178
		if (this._outputPanel) {
			const channel = <OutputChannel>this.getChannel(channelId);
			return channel.show()
				.then(() => {
					this.storageService.store(OUTPUT_ACTIVE_CHANNEL_KEY, channelId, StorageScope.WORKSPACE);
					this._outputPanel.setInput(this.createInput(channelId), EditorOptions.create({ preserveFocus: preserveFocus }));
					if (!preserveFocus) {
						this._outputPanel.focus();
					}
				});
		} else {
			return TPromise.as(null);
		}
179 180
	}

S
Sandeep Somavarapu 已提交
181 182 183 184 185 186 187
	private doHideChannel(channelId): void {
		const channel = <OutputChannel>this.getChannel(channelId);
		if (channel) {
			channel.hide();
		}
	}

188
	private createInput(channelId: string): ResourceEditorInput {
189
		const resource = URI.from({ scheme: OUTPUT_SCHEME, path: channelId });
190
		const channelData = Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannel(channelId);
191 192
		const label = channelData ? channelData.label : channelId;
		return this.instantiationService.createInstance(ResourceEditorInput, nls.localize('output', "{0} - Output", label), nls.localize('channel', "Output channel for '{0}'", label), resource);
I
isidor 已提交
193
	}
194 195
}

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 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 272 273 274 275 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 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
export interface IOutputDelta {
	readonly value: string;
	readonly id: number;
	readonly append?: boolean;
}

class OutputFileListener extends Disposable {

	private _onDidChange: Emitter<void> = new Emitter<void>();
	readonly onDidChange: Event<void> = this._onDidChange.event;

	private disposables: IDisposable[] = [];

	constructor(
		private readonly file: URI,
		private fileService: IFileService
	) {
		super();
	}

	watch(): void {
		this.fileService.watchFileChanges(this.file);
		this.disposables.push(this.fileService.onFileChanges(changes => {
			if (changes.contains(this.file, FileChangeType.UPDATED)) {
				this._onDidChange.fire();
			}
		}));
	}

	loadContent(from: number): TPromise<string> {
		return this.fileService.resolveContent(this.file)
			.then(({ value }) => value.substring(from));
	}

	unwatch(): void {
		this.fileService.unwatchFileChanges(this.file);
		this.disposables = dispose(this.disposables);
	}

	dispose(): void {
		this.unwatch();
		super.dispose();
	}
}

class OutputChannel extends Disposable implements IOutputChannel {

	protected _onDidChange: Emitter<void> = new Emitter<void>();
	readonly onDidChange: Event<void> = this._onDidChange.event;

	protected _onDidClear: Emitter<void> = new Emitter<void>();
	readonly onDidClear: Event<void> = this._onDidClear.event;

	protected _onDispose: Emitter<void> = new Emitter<void>();
	readonly onDispose: Event<void> = this._onDispose.event;

	scrollLock: boolean = false;

	protected readonly file: URI;
	private disposables: IDisposable[] = [];
	protected shown: boolean = false;

	private contentResolver: TPromise<string>;
	private startOffset: number;
	private endOffset: number;

	constructor(
		private readonly outputChannelIdentifier: IOutputChannelIdentifier,
		@IFileService protected fileService: IFileService
	) {
		super();
		this.file = outputChannelIdentifier.file;
		this.startOffset = 0;
		this.endOffset = 0;
	}

	get id(): string {
		return this.outputChannelIdentifier.id;
	}

	get label(): string {
		return this.outputChannelIdentifier.label;
	}

	show(): TPromise<void> {
		if (!this.shown) {
			this.shown = true;
			this.watch();
			return this.resolve() as TPromise;
		}
		return TPromise.as(null);
	}

	hide(): void {
		if (this.shown) {
			this.shown = false;
			this.unwatch();
			this.contentResolver = null;
		}
	}

	append(message: string): void {
		throw new Error(nls.localize('appendNotSupported', "Append is not supported on File output channel"));
	}

	getOutputDelta(previousId?: number): TPromise<IOutputDelta> {
		return this.resolve()
			.then(content => {
				const startOffset = previousId !== void 0 ? previousId : this.startOffset;
				if (this.startOffset === this.endOffset) {
					// Content cleared
					return { append: false, id: this.endOffset, value: '' };
				}
				if (startOffset === this.endOffset) {
					// Content not changed
					return { append: true, id: this.endOffset, value: '' };
				}
				if (startOffset > 0 && startOffset < this.endOffset) {
					// Delta
					const value = content.substring(startOffset, this.endOffset);
					return { append: true, value, id: this.endOffset };
				}
				// Replace
				return { append: false, value: content, id: this.endOffset };
			});
	}

	clear(): void {
		this.startOffset = this.endOffset;
		this._onDidClear.fire();
	}

	private resolve(): TPromise<string> {
		if (!this.contentResolver) {
			this.contentResolver = this.fileService.resolveContent(this.file)
				.then(result => {
					const content = result.value;
					if (this.endOffset !== content.length) {
						this.endOffset = content.length;
						this._onDidChange.fire();
					}
					return content;
				});
		}
		return this.contentResolver;
	}

	private watch(): void {
		this.fileService.watchFileChanges(this.file);
		this.disposables.push(this.fileService.onFileChanges(changes => {
			if (changes.contains(this.file, FileChangeType.UPDATED)) {
				this.contentResolver = null;
				this._onDidChange.fire();
			}
		}));
	}

	private unwatch(): void {
		this.fileService.unwatchFileChanges(this.file);
		this.disposables = dispose(this.disposables);
	}

	dispose(): void {
		this.hide();
		this._onDispose.fire();
		super.dispose();
	}
}

class WritableOutputChannel extends OutputChannel implements IOutputChannel {

	private outputWriter: RotatingLogger;
	private flushScheduler: RunOnceScheduler;

	constructor(
		outputChannelIdentifier: IOutputChannelIdentifier,
		@IFileService fileService: IFileService
	) {
		super(outputChannelIdentifier, fileService);
		this.outputWriter = new RotatingLogger(this.id, this.file.fsPath, 1024 * 1024 * 5, 1);
		this.outputWriter.clearFormatters();
		this.flushScheduler = new RunOnceScheduler(() => this.outputWriter.flush(), 300);
	}

	append(message: string): void {
		this.outputWriter.critical(message);
		if (this.shown && !this.flushScheduler.isScheduled()) {
			this.flushScheduler.schedule();
		}
	}

	show(): TPromise<void> {
		if (!this.flushScheduler.isScheduled()) {
			this.flushScheduler.schedule();
		}
		return super.show();
	}
}

395
class ChannelModelUpdater extends Disposable {
396

397 398 399
	private updateInProgress: boolean = false;
	private modelUpdater: RunOnceScheduler;
	private lastReadId: number;
400 401

	constructor(
402
		private channel: OutputChannel,
403 404 405
		@IModelService private modelService: IModelService,
		@IPanelService private panelService: IPanelService
	) {
406 407 408 409 410
		super();
		this.modelUpdater = new RunOnceScheduler(() => this.doUpdate(), 300);
		this._register(channel.onDidChange(() => this.onDidChange()));
		this._register(channel.onDidClear(() => this.onDidClear()));
		this._register(toDisposable(() => this.modelUpdater.cancel()));
411
		this._register(this.modelService.onModelRemoved(this.onModelRemoved, this));
412 413
	}

414 415 416 417
	private onDidChange(): void {
		if (!this.updateInProgress) {
			this.updateInProgress = true;
			this.modelUpdater.schedule();
418 419 420
		}
	}

421 422 423 424 425 426 427
	private onDidClear(): void {
		this.modelUpdater.cancel();
		this.updateInProgress = true;
		this.doUpdate();
	}

	private doUpdate(): void {
428 429 430 431
		const model = this.getModel(this.channel.id);
		if (model && !model.isDisposed()) {
			this.channel.getOutputDelta(this.lastReadId)
				.then(delta => {
432 433 434 435 436 437 438 439 440 441 442 443 444
					if (delta) {
						if (delta.append) {
							const lastLine = model.getLineCount();
							const lastLineMaxColumn = model.getLineMaxColumn(lastLine);
							model.applyEdits([EditOperation.insert(new Position(lastLine, lastLineMaxColumn), delta.value)]);
						} else {
							model.setValue(delta.value);
						}
						this.lastReadId = delta.id;
						if (!this.channel.scrollLock) {
							(<OutputPanel>this.panelService.getActivePanel()).revealLastLine();
						}
					}
445 446 447 448 449
					this.updateInProgress = false;
				}, () => this.updateInProgress = false);
		} else {
			this.updateInProgress = false;
		}
450 451
	}

452 453
	private getModel(channel: string): IModel {
		return this.modelService.getModel(URI.from({ scheme: OUTPUT_SCHEME, path: channel }));
454
	}
455 456 457 458 459 460

	private onModelRemoved(model: IModel): void {
		if (model.uri.fsPath === this.channel.id) {
			this.lastReadId = void 0;
		}
	}
461
}