outputServices.ts 14.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
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
import { IMessageService, Severity } from 'vs/platform/message/common/message';
36
import { IWindowService } from 'vs/platform/windows/common/windows';
37 38

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

40
class OutputFileListener extends Disposable {
41 42

	private _onDidChange: Emitter<void> = new Emitter<void>();
43
	readonly onDidContentChange: Event<void> = this._onDidChange.event;
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 72 73

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

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

79 80 81
abstract class AbstractOutputChannel extends Disposable {

	scrollLock: boolean = false;
82 83 84 85 86 87

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

	protected readonly file: URI;

88 89 90
	protected startOffset: number = 0;
	protected endOffset: number = 0;
	protected modelUpdater: RunOnceScheduler;
91 92

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

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

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

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

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

125 126 127 128 129 130 131 132 133 134 135 136 137
	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;
			});
138 139
	}

140 141 142 143 144 145 146 147
	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) {
148 149 150 151
				const panel = this.panelService.getActivePanel();
				if (panel && panel.getId() === OUTPUT_PANEL_ID) {
					(<OutputPanel>panel).revealLastLine();
				}
152
			}
153
		}
154 155
	}

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

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

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

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);
185

186 187 188 189 190 191 192 193 194 195
		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 {
196 197
		let model = this.getModel();
		if (model) {
198
			this.fileService.resolveContent(this.file, { position: this.endOffset })
199
				.then(content => {
200
					this.appendContent(content.value);
201 202 203 204 205
					this.updateInProgress = false;
				}, () => this.updateInProgress = false);
		} else {
			this.updateInProgress = false;
		}
206 207
	}

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

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

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

224
class AppendableFileOutputChannel extends AbstractOutputChannel implements OutputChannel {
225 226

	private outputWriter: RotatingLogger;
227
	private appendedMessage = '';
228 229 230

	constructor(
		outputChannelIdentifier: IOutputChannelIdentifier,
231 232
		@IFileService fileService: IFileService,
		@IModelService modelService: IModelService,
233
		@IModeService modeService: IModeService,
234 235
		@IPanelService panelService: IPanelService,
		@IMessageService private messageService: IMessageService
236
	) {
237
		super(outputChannelIdentifier, fileService, modelService, modeService, panelService);
238 239
		try {
			this.outputWriter = new RotatingLogger(this.id, this.file.fsPath, 1024 * 1024 * 30, 5);
S
Sandeep Somavarapu 已提交
240
			this.outputWriter.clearFormatters();
241 242 243
		} catch (e) {
			this.messageService.show(Severity.Error, e);
		}
244 245 246
	}

	append(message: string): void {
247 248 249 250 251 252 253 254
		if (this.outputWriter) {
			this.outputWriter.critical(message);
			const model = this.getModel();
			if (model) {
				this.appendedMessage += message;
				if (!this.modelUpdater.isScheduled()) {
					this.modelUpdater.schedule();
				}
255 256 257 258 259 260 261 262 263 264
			}
		}
	}

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

	createModel(): TPromise<IModel> {
265 266 267 268 269 270
		if (this.outputWriter) {
			this.outputWriter.flush();
			this.appendedMessage = '';
			return super.createModel();
		}
		return TPromise.as(this.modelService.createModel('', this.modeService.getOrCreateMode(OUTPUT_MIME), URI.from({ scheme: OUTPUT_SCHEME, path: this.id })));
271 272 273 274 275 276 277 278 279
	}

	protected updateModel(): void {
		let model = this.getModel();
		if (model) {
			if (this.appendedMessage) {
				this.appendContent(this.appendedMessage);
				this.appendedMessage = '';
			}
280 281 282 283
		}
	}
}

284
export class OutputService extends Disposable implements IOutputService, ITextModelContentProvider {
285

286 287 288 289
	public _serviceBrand: any;

	private channels: Map<string, OutputChannel> = new Map<string, OutputChannel>();
	private activeChannelId: string;
290
	private readonly windowSession: string;
291 292 293 294 295

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

	private _outputPanel: OutputPanel;
296 297

	constructor(
298 299 300 301 302 303
		@IStorageService private storageService: IStorageService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IPanelService private panelService: IPanelService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@ITextModelService textModelResolverService: ITextModelService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
304 305
		@IEnvironmentService private environmentService: IEnvironmentService,
		@IWindowService private windowService: IWindowService,
306
	) {
307
		super();
308 309 310 311 312 313 314 315 316 317 318
		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);
319 320

		this.windowSession = `${this.windowService.getCurrentWindowId()}_${toLocalISOString(new Date()).replace(/-|:|\.\d+Z$/g, '')}`;
321 322
	}

323 324
	provideTextContent(resource: URI): TPromise<IModel> {
		const channel = <OutputChannel>this.getChannel(resource.fsPath);
325
		return channel.createModel();
326 327 328 329 330 331 332 333 334 335 336 337 338
	}

	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;
339
		}
340
		return promise.then(() => this._onActiveOutputChannel.fire(id));
341 342
	}

343 344
	showChannelInEditor(channelId: string): TPromise<void> {
		return this.editorService.openEditor(this.createInput(channelId)) as TPromise;
345 346
	}

347 348 349
	getChannel(id: string): IOutputChannel {
		if (!this.channels.has(id)) {
			this.channels.set(id, this.createChannel(id));
350
		}
351 352 353 354 355
		return this.channels.get(id);
	}

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

358 359
	getActiveChannel(): IOutputChannel {
		return this.getChannel(this.activeChannelId);
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
	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);
385
		}
386
		const file = URI.file(paths.join(this.environmentService.logsPath, `outputs_${this.windowSession}`, `${id}.log`));
387
		return this.instantiationService.createInstance(AppendableFileOutputChannel, { id, label: channelData ? channelData.label : '', file });
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 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427


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