outputServices.ts 13.9 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
import * as nls from 'vs/nls';
import * as paths from 'vs/base/common/paths';
J
Johannes Rieken 已提交
8 9
import { TPromise } from 'vs/base/common/winjs.base';
import Event, { Emitter } from 'vs/base/common/event';
10
import URI from 'vs/base/common/uri';
11
import { IDisposable, dispose, Disposable, toDisposable } from 'vs/base/common/lifecycle';
J
Johannes Rieken 已提交
12 13
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
14
import { Registry } from 'vs/platform/registry/common/platform';
J
Johannes Rieken 已提交
15
import { EditorOptions } from 'vs/workbench/common/editor';
16
import { IOutputChannelIdentifier, IOutputChannel, IOutputService, Extensions, OUTPUT_PANEL_ID, IOutputChannelRegistry, OUTPUT_SCHEME, OUTPUT_MIME } from 'vs/workbench/parts/output/common/output';
J
Johannes Rieken 已提交
17 18 19 20 21
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';
22
import { ITextModelService, ITextModelContentProvider } from 'vs/editor/common/services/resolverService';
23 24 25 26 27
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 已提交
28
import { IFileService, FileChangeType } from 'vs/platform/files/common/files';
29 30
import { IPanel } from 'vs/workbench/common/panel';
import { ResourceEditorInput } from 'vs/workbench/common/editor/resourceEditorInput';
31
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
32 33 34
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { RotatingLogger } from 'spdlog';
import { toLocalISOString } from 'vs/base/common/date';
35 36

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

38
class OutputFileListener extends Disposable {
39 40

	private _onDidChange: Emitter<void> = new Emitter<void>();
41
	readonly onDidContentChange: Event<void> = this._onDidChange.event;
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

	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();
			}
		}));
	}

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

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

72 73
interface OutputChannel extends IOutputChannel {
	readonly onDispose: Event<void>;
74
	createModel(): TPromise<IModel>;
75
}
76

77 78 79
abstract class AbstractOutputChannel extends Disposable {

	scrollLock: boolean = false;
80 81 82 83 84 85

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

	protected readonly file: URI;

86 87 88
	protected startOffset: number = 0;
	protected endOffset: number = 0;
	protected modelUpdater: RunOnceScheduler;
89 90

	constructor(
91 92 93 94 95
		protected readonly outputChannelIdentifier: IOutputChannelIdentifier,
		protected fileService: IFileService,
		private modelService: IModelService,
		private modeService: IModeService,
		private panelService: IPanelService
96 97 98
	) {
		super();
		this.file = outputChannelIdentifier.file;
99

100
		this.modelUpdater = new RunOnceScheduler(() => this.updateModel(), 300);
101
		this._register(toDisposable(() => this.modelUpdater.cancel()));
102 103 104 105 106 107 108 109 110 111
	}

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

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

112
	clear(): void {
113 114 115
		if (this.modelUpdater.isScheduled()) {
			this.modelUpdater.cancel();
		}
116 117 118 119
		this.startOffset = this.endOffset;
		const model = this.getModel();
		if (model) {
			model.setValue('');
120 121 122
		}
	}

123 124 125 126 127 128 129 130 131 132 133 134 135
	createModel(): TPromise<IModel> {
		return this.fileService.resolveContent(this.file, { position: this.startOffset })
			.then(content => {
				const model = this.modelService.createModel(content.value, this.modeService.getOrCreateMode(OUTPUT_MIME), URI.from({ scheme: OUTPUT_SCHEME, path: this.id }));
				this.endOffset = this.startOffset + new Buffer(model.getValueLength()).byteLength;
				this.onModelCreated(model);
				const disposables: IDisposable[] = [];
				disposables.push(model.onWillDispose(() => {
					this.onModelWillDispose(model);
					dispose(disposables);
				}));
				return model;
			});
136 137
	}

138 139 140 141 142 143 144 145
	protected appendContent(content: string): void {
		const model = this.getModel();
		if (model && content) {
			const lastLine = model.getLineCount();
			const lastLineMaxColumn = model.getLineMaxColumn(lastLine);
			model.applyEdits([EditOperation.insert(new Position(lastLine, lastLineMaxColumn), content)]);
			this.endOffset = this.endOffset + new Buffer(content).byteLength;
			if (!this.scrollLock) {
146 147 148 149
				const panel = this.panelService.getActivePanel();
				if (panel && panel.getId() === OUTPUT_PANEL_ID) {
					(<OutputPanel>panel).revealLastLine();
				}
150
			}
151
		}
152 153
	}

154 155 156
	protected getModel(): IModel {
		const model = this.modelService.getModel(URI.from({ scheme: OUTPUT_SCHEME, path: this.id }));
		return model && !model.isDisposed() ? model : null;
157 158
	}

159 160 161 162 163 164 165
	protected onModelCreated(model: IModel) { }
	protected onModelWillDispose(model: IModel) { }
	protected updateModel() { }

	dispose(): void {
		this._onDispose.fire();
		super.dispose();
166
	}
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
}

class FileOutputChannel extends AbstractOutputChannel implements OutputChannel {

	private readonly fileHandler: OutputFileListener;

	private updateInProgress: boolean = false;

	constructor(
		outputChannelIdentifier: IOutputChannelIdentifier,
		@IFileService fileService: IFileService,
		@IModelService modelService: IModelService,
		@IModeService modeService: IModeService,
		@IPanelService panelService: IPanelService
	) {
		super(outputChannelIdentifier, fileService, modelService, modeService, panelService);
183

184 185 186 187 188 189 190 191 192 193
		this.fileHandler = this._register(new OutputFileListener(this.file, fileService));
		this._register(this.fileHandler.onDidContentChange(() => this.onDidContentChange()));
		this._register(toDisposable(() => this.fileHandler.unwatch()));
	}

	append(message: string): void {
		throw new Error('Not supported');
	}

	protected updateModel(): void {
194 195
		let model = this.getModel();
		if (model) {
196
			this.fileService.resolveContent(this.file, { position: this.endOffset })
197
				.then(content => {
198
					this.appendContent(content.value);
199 200 201 202 203
					this.updateInProgress = false;
				}, () => this.updateInProgress = false);
		} else {
			this.updateInProgress = false;
		}
204 205
	}

206 207
	protected onModelCreated(model: IModel): void {
		this.fileHandler.watch();
208 209
	}

210 211
	protected onModelWillDispose(model: IModel): void {
		this.fileHandler.unwatch();
212 213
	}

214 215 216 217 218
	private onDidContentChange(): void {
		if (!this.updateInProgress) {
			this.updateInProgress = true;
			this.modelUpdater.schedule();
		}
219 220 221
	}
}

222
class AppendableFileOutputChannel extends AbstractOutputChannel implements OutputChannel {
223 224

	private outputWriter: RotatingLogger;
225
	private appendedMessage = '';
226 227 228

	constructor(
		outputChannelIdentifier: IOutputChannelIdentifier,
229 230
		@IFileService fileService: IFileService,
		@IModelService modelService: IModelService,
231 232
		@IModeService modeService: IModeService,
		@IPanelService panelService: IPanelService
233
	) {
234 235
		super(outputChannelIdentifier, fileService, modelService, modeService, panelService);

236
		this.outputWriter = new RotatingLogger(this.id, this.file.fsPath, 1024 * 1024 * 30, 5);
237 238 239 240 241
		this.outputWriter.clearFormatters();
	}

	append(message: string): void {
		this.outputWriter.critical(message);
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
		const model = this.getModel();
		if (model) {
			this.appendedMessage += message;
			if (!this.modelUpdater.isScheduled()) {
				this.modelUpdater.schedule();
			}
		}
	}

	clear(): void {
		super.clear();
		this.appendedMessage = '';
	}

	createModel(): TPromise<IModel> {
		this.outputWriter.flush();
		this.appendedMessage = '';
		return super.createModel();
	}

	protected updateModel(): void {
		let model = this.getModel();
		if (model) {
			if (this.appendedMessage) {
				this.appendContent(this.appendedMessage);
				this.appendedMessage = '';
			}
269 270 271 272
		}
	}
}

273
export class OutputService implements IOutputService, ITextModelContentProvider {
274

275 276 277 278 279 280 281 282 283
	public _serviceBrand: any;

	private channels: Map<string, OutputChannel> = new Map<string, OutputChannel>();
	private activeChannelId: string;

	private _onActiveOutputChannel: Emitter<string> = new Emitter<string>();
	readonly onActiveOutputChannel: Event<string> = this._onActiveOutputChannel.event;

	private _outputPanel: OutputPanel;
284 285

	constructor(
286 287 288 289 290 291 292
		@IStorageService private storageService: IStorageService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IPanelService private panelService: IPanelService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@ITextModelService textModelResolverService: ITextModelService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IEnvironmentService private environmentService: IEnvironmentService
293
	) {
294 295 296 297 298 299 300 301 302 303 304
		const channels = this.getChannels();
		this.activeChannelId = this.storageService.get(OUTPUT_ACTIVE_CHANNEL_KEY, StorageScope.WORKSPACE, channels && channels.length > 0 ? channels[0].id : null);

		instantiationService.createInstance(OutputLinkProvider);

		// Register as text model content provider for output
		textModelResolverService.registerTextModelContentProvider(OUTPUT_SCHEME, this);

		this.onDidPanelOpen(this.panelService.getActivePanel());
		panelService.onDidPanelOpen(this.onDidPanelOpen, this);
		panelService.onDidPanelClose(this.onDidPanelClose, this);
305 306
	}

307 308
	provideTextContent(resource: URI): TPromise<IModel> {
		const channel = <OutputChannel>this.getChannel(resource.fsPath);
309
		return channel.createModel();
310 311 312 313 314 315 316 317 318 319 320 321 322
	}

	showChannel(id: string, preserveFocus?: boolean): TPromise<void> {
		if (this.isChannelShown(id)) {
			return TPromise.as(null);
		}

		this.activeChannelId = id;
		let promise = TPromise.as(null);
		if (this._outputPanel) {
			this.doShowChannel(id, preserveFocus);
		} else {
			promise = this.panelService.openPanel(OUTPUT_PANEL_ID) as TPromise;
323
		}
324
		return promise.then(() => this._onActiveOutputChannel.fire(id));
325 326
	}

327 328
	showChannelInEditor(channelId: string): TPromise<void> {
		return this.editorService.openEditor(this.createInput(channelId)) as TPromise;
329 330
	}

331 332 333
	getChannel(id: string): IOutputChannel {
		if (!this.channels.has(id)) {
			this.channels.set(id, this.createChannel(id));
334
		}
335 336 337 338 339
		return this.channels.get(id);
	}

	getChannels(): IOutputChannelIdentifier[] {
		return Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannels();
340 341
	}

342 343
	getActiveChannel(): IOutputChannel {
		return this.getChannel(this.activeChannelId);
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
	private createChannel(id: string): OutputChannel {
		const channelDisposables = [];
		const channel = this.instantiateChannel(id);
		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;
	}

	private instantiateChannel(id: string): OutputChannel {
		const channelData = Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannel(id);
		if (channelData && channelData.file) {
			return this.instantiationService.createInstance(FileOutputChannel, channelData);
369
		}
370 371
		const sessionId = toLocalISOString(new Date()).replace(/-|:|\.\d+Z$/g, '');
		const file = URI.file(paths.join(this.environmentService.logsPath, 'outputs', `${id}.${sessionId}.log`));
372
		return this.instantiationService.createInstance(AppendableFileOutputChannel, { id, label: channelData ? channelData.label : '', file });
373
	}
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412


	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) {
			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): void {
		if (this._outputPanel) {
			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();
			}
		}
	}

	private createInput(channelId: string): ResourceEditorInput {
		const resource = URI.from({ scheme: OUTPUT_SCHEME, path: channelId });
		const channelData = Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannel(channelId);
		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);
	}
}