outputServices.ts 22.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';
8 9
import * as strings from 'vs/base/common/strings';
import * as extfs from 'vs/base/node/extfs';
10
import * as fs from 'fs';
J
Johannes Rieken 已提交
11 12
import { TPromise } from 'vs/base/common/winjs.base';
import Event, { Emitter } from 'vs/base/common/event';
13
import URI from 'vs/base/common/uri';
14
import { IDisposable, dispose, Disposable, toDisposable } from 'vs/base/common/lifecycle';
J
Johannes Rieken 已提交
15 16
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
17
import { Registry } from 'vs/platform/registry/common/platform';
J
Johannes Rieken 已提交
18
import { EditorOptions } from 'vs/workbench/common/editor';
19
import { IOutputChannelIdentifier, IOutputChannel, IOutputService, Extensions, OUTPUT_PANEL_ID, IOutputChannelRegistry, OUTPUT_SCHEME, OUTPUT_MIME, MAX_OUTPUT_LENGTH, LOG_SCHEME } from 'vs/workbench/parts/output/common/output';
J
Johannes Rieken 已提交
20 21 22 23 24
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';
25
import { ITextModelService, ITextModelContentProvider } from 'vs/editor/common/services/resolverService';
26 27
import { IModel } from 'vs/editor/common/editorCommon';
import { IModeService } from 'vs/editor/common/services/modeService';
28
import { RunOnceScheduler, ThrottledDelayer } from 'vs/base/common/async';
29 30
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Position } from 'vs/editor/common/core/position';
31
import { IFileService } from 'vs/platform/files/common/files';
32 33
import { IPanel } from 'vs/workbench/common/panel';
import { ResourceEditorInput } from 'vs/workbench/common/editor/resourceEditorInput';
34 35 36
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { RotatingLogger } from 'spdlog';
import { toLocalISOString } from 'vs/base/common/date';
37
import { IWindowService } from 'vs/platform/windows/common/windows';
38 39 40
import { ILogService } from 'vs/platform/log/common/log';
import { binarySearch } from 'vs/base/common/arrays';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
41
import { Schemas } from 'vs/base/common/network';
42 43

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

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
let watchingOutputDir = false;
let callbacks = [];
function watchOutputDirectory(outputDir: string, logService: ILogService, onChange: (eventType: string, fileName: string) => void): IDisposable {
	callbacks.push(onChange);
	if (!watchingOutputDir) {
		try {
			const watcher = extfs.watch(outputDir, (eventType, fileName) => {
				for (const callback of callbacks) {
					callback(eventType, fileName);
				}
			});
			watcher.on('error', (code: number, signal: string) => logService.error(`Error watching ${outputDir}: (${code}, ${signal})`));
			watchingOutputDir = true;
			return toDisposable(() => {
				callbacks = [];
				watcher.removeAllListeners();
				watcher.close();
			});
		} catch (error) {
			logService.error(`Error watching ${outputDir}:  (${error.toString()})`);
		}
66
	}
67
	return toDisposable(() => { });
68 69
}

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
const fileWatchers: Map<string, any[]> = new Map<string, any[]>();
function watchFile(file: string, callback: () => void): IDisposable {

	const onFileChange = (file: string) => {
		for (const callback of fileWatchers.get(file)) {
			callback();
		}
	};

	let callbacks = fileWatchers.get(file);
	if (!callbacks) {
		callbacks = [];
		fileWatchers.set(file, callbacks);
		fs.watchFile(file, { interval: 1000 }, (current, previous) => {
			if ((previous && !current) || (!previous && !current)) {
				onFileChange(file);
				return;
			}
			if (previous && current && previous.mtime !== current.mtime) {
				onFileChange(file);
				return;
			}
		});
	}
	callbacks.push(callback);
	return toDisposable(() => {
		let allCallbacks = fileWatchers.get(file);
		allCallbacks.splice(allCallbacks.indexOf(callback), 1);
		if (!allCallbacks.length) {
			fs.unwatchFile(file);
			fileWatchers.delete(file);
		}
	});
}

function unWatchAllFiles(): void {
	fileWatchers.forEach((value, file) => fs.unwatchFile(file));
	fileWatchers.clear();
}
109

110
interface OutputChannel extends IOutputChannel {
S
Sandeep Somavarapu 已提交
111
	readonly file: URI;
112
	readonly onDidAppendedContent: Event<void>;
S
Sandeep Somavarapu 已提交
113
	readonly onDispose: Event<void>;
114
	loadModel(): TPromise<IModel>;
115
}
116

117
abstract class AbstractFileOutputChannel extends Disposable {
118 119

	scrollLock: boolean = false;
120

121 122 123
	protected _onDidAppendedContent: Emitter<void> = new Emitter<void>();
	readonly onDidAppendedContent: Event<void> = this._onDidAppendedContent.event;

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

127 128
	protected modelUpdater: RunOnceScheduler;
	protected model: IModel;
S
Sandeep Somavarapu 已提交
129
	readonly file: URI;
130 131
	protected startOffset: number = 0;
	protected endOffset: number = 0;
132 133

	constructor(
134
		protected readonly outputChannelIdentifier: IOutputChannelIdentifier,
135
		private readonly modelUri: URI,
136
		protected fileService: IFileService,
137 138
		protected modelService: IModelService,
		protected modeService: IModeService,
139 140
	) {
		super();
141
		this.file = this.outputChannelIdentifier.file;
142
		this.modelUpdater = new RunOnceScheduler(() => this.updateModel(), 300);
143
		this._register(toDisposable(() => this.modelUpdater.cancel()));
144 145 146 147 148 149 150 151 152 153
	}

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

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

154
	clear(): void {
155 156 157
		if (this.modelUpdater.isScheduled()) {
			this.modelUpdater.cancel();
		}
158 159
		if (this.model) {
			this.model.setValue('');
160
		}
161
		this.startOffset = this.endOffset;
162 163
	}

164
	loadModel(): TPromise<IModel> {
165 166
		return this.fileService.resolveContent(this.file, { position: this.startOffset })
			.then(content => {
167 168 169 170 171 172 173
				if (this.model) {
					this.model.setValue(content.value);
				} else {
					this.model = this.createModel(content.value);
				}
				this.endOffset = this.startOffset + new Buffer(this.model.getValueLength()).byteLength;
				return this.model;
174
			});
175 176
	}

177 178 179 180 181 182 183 184 185 186
	resetModel(): TPromise<void> {
		this.startOffset = 0;
		this.endOffset = 0;
		if (this.model) {
			return this.loadModel() as TPromise;
		}
		return TPromise.as(null);
	}

	private createModel(content: string): IModel {
187
		const model = this.modelService.createModel(content, this.modeService.getOrCreateMode(OUTPUT_MIME), this.modelUri);
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
		this.onModelCreated(model);
		const disposables: IDisposable[] = [];
		disposables.push(model.onWillDispose(() => {
			this.onModelWillDispose(model);
			this.model = null;
			dispose(disposables);
		}));
		return model;
	}

	appendToModel(content: string): void {
		if (this.model && content) {
			const lastLine = this.model.getLineCount();
			const lastLineMaxColumn = this.model.getLineMaxColumn(lastLine);
			this.model.applyEdits([EditOperation.insert(new Position(lastLine, lastLineMaxColumn), content)]);
203
			this.endOffset = this.endOffset + new Buffer(content).byteLength;
204
			this._onDidAppendedContent.fire();
205
		}
206 207
	}

208 209 210 211 212 213 214
	protected onModelCreated(model: IModel) { }
	protected onModelWillDispose(model: IModel) { }
	protected updateModel() { }

	dispose(): void {
		this._onDispose.fire();
		super.dispose();
215
	}
216 217
}

218 219 220 221
/**
 * An output channel that stores appended messages in a backup file.
 */
class OutputChannelBackedByFile extends AbstractFileOutputChannel implements OutputChannel {
222

223 224 225
	private outputWriter: RotatingLogger;
	private appendedMessage = '';
	private loadingFromFileInProgress: boolean = false;
226
	private resettingDelayer: ThrottledDelayer<void>;
227 228 229

	constructor(
		outputChannelIdentifier: IOutputChannelIdentifier,
230
		modelUri: URI,
231 232 233
		@IFileService fileService: IFileService,
		@IModelService modelService: IModelService,
		@IModeService modeService: IModeService,
234
		@ILogService logService: ILogService
235
	) {
236
		super(outputChannelIdentifier, modelUri, fileService, modelService, modeService);
237

238
		// Use one rotating file to check for main file reset
S
Sandeep Somavarapu 已提交
239
		this.outputWriter = new RotatingLogger(this.id, this.file.fsPath, 1024 * 1024 * 30, 1);
240 241
		this.outputWriter.clearFormatters();
		this._register(watchOutputDirectory(paths.dirname(this.file.fsPath), logService, (eventType, file) => this.onFileChangedInOutputDirector(eventType, file)));
242 243

		this.resettingDelayer = new ThrottledDelayer<void>(50);
244 245 246
	}

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

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

	loadModel(): TPromise<IModel> {
		this.startLoadingFromFile();
		return super.loadModel()
			.then(model => {
				this.finishedLoadingFromFile();
				return model;
			});
272 273 274
	}

	protected updateModel(): void {
275 276 277
		if (this.model && this.appendedMessage) {
			this.appendToModel(this.appendedMessage);
			this.appendedMessage = '';
278
		}
279 280
	}

281 282 283 284 285 286 287
	private startLoadingFromFile(): void {
		this.loadingFromFileInProgress = true;
		this.outputWriter.flush();
		if (this.modelUpdater.isScheduled()) {
			this.modelUpdater.cancel();
		}
		this.appendedMessage = '';
288 289
	}

290 291 292 293 294 295 296
	private finishedLoadingFromFile(): void {
		if (this.appendedMessage) {
			this.outputWriter.critical(this.appendedMessage);
			this.appendToModel(this.appendedMessage);
			this.appendedMessage = '';
		}
		this.loadingFromFileInProgress = false;
297 298
	}

299
	private onFileChangedInOutputDirector(eventType: string, fileName: string): void {
300 301 302
		// Check if rotating file has changed. It changes only when the main file exceeds its limit.
		if (`${paths.basename(this.file.fsPath)}.1` === fileName) {
			this.resettingDelayer.trigger(() => this.resetModel());
303
		}
304 305 306
	}
}

307 308 309 310
class OutputFileListener extends Disposable {

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

312
	private watching: boolean = false;
313 314 315 316 317 318 319 320 321
	private disposables: IDisposable[] = [];

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

	watch(): void {
322 323 324 325
		if (!this.watching) {
			this.disposables.push(watchFile(this.file.fsPath, () => this._onDidChange.fire()));
			this.watching = true;
		}
326 327 328
	}

	unwatch(): void {
329 330 331 332
		if (this.watching) {
			this.disposables = dispose(this.disposables);
			this.watching = false;
		}
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
	}

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

/**
 * An output channel driven by a file and does not support appending messages.
 */
class FileOutputChannel extends AbstractFileOutputChannel implements OutputChannel {

	private readonly fileHandler: OutputFileListener;

	private updateInProgress: boolean = false;
349 350 351

	constructor(
		outputChannelIdentifier: IOutputChannelIdentifier,
352
		modelUri: URI,
353 354
		@IFileService fileService: IFileService,
		@IModelService modelService: IModelService,
355 356
		@IModeService modeService: IModeService,
		@ILogService logService: ILogService,
357
	) {
358
		super(outputChannelIdentifier, modelUri, fileService, modelService, modeService);
359

360
		this.fileHandler = this._register(new OutputFileListener(this.file));
361 362
		this._register(this.fileHandler.onDidContentChange(() => this.onDidContentChange()));
		this._register(toDisposable(() => this.fileHandler.unwatch()));
363 364 365
	}

	append(message: string): void {
366 367 368 369 370 371 372 373 374 375 376 377
		throw new Error('Not supported');
	}

	protected updateModel(): void {
		if (this.model) {
			this.fileService.resolveContent(this.file, { position: this.endOffset })
				.then(content => {
					this.appendToModel(content.value);
					this.updateInProgress = false;
				}, () => this.updateInProgress = false);
		} else {
			this.updateInProgress = false;
378 379 380
		}
	}

381 382
	protected onModelCreated(model: IModel): void {
		this.fileHandler.watch();
383 384
	}

385 386
	protected onModelWillDispose(model: IModel): void {
		this.fileHandler.unwatch();
387 388
	}

389 390 391 392
	private onDidContentChange(): void {
		if (!this.updateInProgress) {
			this.updateInProgress = true;
			this.modelUpdater.schedule();
393 394 395 396
		}
	}
}

397
export class OutputService extends Disposable implements IOutputService, ITextModelContentProvider {
398

399 400 401 402
	public _serviceBrand: any;

	private channels: Map<string, OutputChannel> = new Map<string, OutputChannel>();
	private activeChannelId: string;
403
	private readonly outputDir: string;
404 405 406 407 408

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

	private _outputPanel: OutputPanel;
409 410

	constructor(
411 412 413 414 415
		@IStorageService private storageService: IStorageService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IPanelService private panelService: IPanelService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@ITextModelService textModelResolverService: ITextModelService,
416 417 418
		@IEnvironmentService environmentService: IEnvironmentService,
		@IWindowService windowService: IWindowService,
		@ITelemetryService private telemetryService: ITelemetryService,
419
		@ILogService private logService: ILogService
420
	) {
421
		super();
422 423 424 425 426 427 428 429 430 431 432
		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);
433
		this.outputDir = paths.join(environmentService.logsPath, `output_${windowService.getCurrentWindowId()}_${toLocalISOString(new Date()).replace(/-|:|\.\d+Z$/g, '')}`);
434

435
		this._register(toDisposable(() => unWatchAllFiles()));
436 437
	}

438 439
	provideTextContent(resource: URI): TPromise<IModel> {
		const channel = <OutputChannel>this.getChannel(resource.fsPath);
440 441 442 443
		if (channel) {
			return channel.loadModel();
		}
		return TPromise.as(null);
444 445 446 447 448 449 450 451 452 453 454 455 456
	}

	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;
457
		}
458
		return promise.then(() => this._onActiveOutputChannel.fire(id));
459 460
	}

461 462 463
	getChannel(id: string): IOutputChannel {
		if (!this.channels.has(id)) {
			this.channels.set(id, this.createChannel(id));
464
		}
465 466 467 468 469
		return this.channels.get(id);
	}

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

472 473
	getActiveChannel(): IOutputChannel {
		return this.getChannel(this.activeChannelId);
474
	}
475

476 477 478
	private createChannel(id: string): OutputChannel {
		const channelDisposables = [];
		const channel = this.instantiateChannel(id);
479 480 481 482 483 484 485 486
		channel.onDidAppendedContent(() => {
			if (!channel.scrollLock) {
				const panel = this.panelService.getActivePanel();
				if (panel && panel.getId() === OUTPUT_PANEL_ID && this.isChannelShown(id)) {
					(<OutputPanel>panel).revealLastLine();
				}
			}
		}, channelDisposables);
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
		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);
505
		const uri = URI.from({ scheme: OUTPUT_SCHEME, path: id });
506
		if (channelData && channelData.file) {
507
			return this.instantiationService.createInstance(FileOutputChannel, channelData, uri);
508
		}
509 510
		const file = URI.file(paths.join(this.outputDir, `${id}.log`));
		try {
511
			return this.instantiationService.createInstance(OutputChannelBackedByFile, { id, label: channelData ? channelData.label : '', file }, uri);
512 513 514 515 516
		} catch (e) {
			this.logService.error(e);
			this.telemetryService.publicLog('output.used.bufferedChannel');
			return this.instantiationService.createInstance(BufferredOutputChannel, { id, label: channelData ? channelData.label : '' });
		}
517
	}
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554

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

557 558 559 560 561
export class LogContentProvider {

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

	constructor(
562
		@IInstantiationService private instantiationService: IInstantiationService
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
	) {
	}

	provideTextContent(resource: URI): TPromise<IModel> {
		if (resource.scheme === LOG_SCHEME) {
			let channel = this.getChannel(resource);
			if (channel) {
				return channel.loadModel();
			}
		}
		return TPromise.as(null);
	}

	private getChannel(resource: URI): OutputChannel {
		const id = resource.path;
		let channel = this.channels.get(id);
		if (!channel) {
			const channelDisposables = [];
			channel = this.instantiationService.createInstance(FileOutputChannel, { id, label: '', file: resource.with({ scheme: Schemas.file }) }, resource);
			channel.onDispose(() => dispose(channelDisposables), channelDisposables);
			this.channels.set(id, channel);
		}
		return channel;
	}
}

589 590 591 592 593
// Remove this channel when there are no issues using Output channel backed by file
class BufferredOutputChannel extends Disposable implements OutputChannel {

	readonly id: string;
	readonly label: string;
S
Sandeep Somavarapu 已提交
594
	readonly file: URI = null;
595 596
	scrollLock: boolean = false;

597 598 599
	protected _onDidAppendedContent: Emitter<void> = new Emitter<void>();
	readonly onDidAppendedContent: Event<void> = this._onDidAppendedContent.event;

600 601 602 603 604 605 606 607 608 609 610
	private _onDispose: Emitter<void> = new Emitter<void>();
	readonly onDispose: Event<void> = this._onDispose.event;

	private modelUpdater: RunOnceScheduler;
	private model: IModel;
	private readonly bufferredContent: BufferedContent;
	private lastReadId: number = void 0;

	constructor(
		protected readonly outputChannelIdentifier: IOutputChannelIdentifier,
		@IModelService private modelService: IModelService,
611
		@IModeService private modeService: IModeService
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
	) {
		super();

		this.id = outputChannelIdentifier.id;
		this.label = outputChannelIdentifier.label;

		this.modelUpdater = new RunOnceScheduler(() => this.updateModel(), 300);
		this._register(toDisposable(() => this.modelUpdater.cancel()));

		this.bufferredContent = new BufferedContent();
		this._register(toDisposable(() => this.bufferredContent.clear()));
	}

	append(output: string) {
		this.bufferredContent.append(output);
		if (!this.modelUpdater.isScheduled()) {
			this.modelUpdater.schedule();
		}
	}

	clear(): void {
		if (this.modelUpdater.isScheduled()) {
			this.modelUpdater.cancel();
		}
		if (this.model) {
			this.model.setValue('');
		}
		this.bufferredContent.clear();
		this.lastReadId = void 0;
	}

	loadModel(): TPromise<IModel> {
		const { value, id } = this.bufferredContent.getDelta(this.lastReadId);
		if (this.model) {
			this.model.setValue(value);
		} else {
			this.model = this.createModel(value);
		}
		this.lastReadId = id;
		return TPromise.as(this.model);
	}

	private createModel(content: string): IModel {
		const model = this.modelService.createModel(content, this.modeService.getOrCreateMode(OUTPUT_MIME), URI.from({ scheme: OUTPUT_SCHEME, path: this.id }));
		const disposables: IDisposable[] = [];
		disposables.push(model.onWillDispose(() => {
			this.model = null;
			dispose(disposables);
		}));
		return model;
	}

	private updateModel(): void {
		if (this.model) {
			const { value, id } = this.bufferredContent.getDelta(this.lastReadId);
			this.lastReadId = id;
			const lastLine = this.model.getLineCount();
			const lastLineMaxColumn = this.model.getLineMaxColumn(lastLine);
			this.model.applyEdits([EditOperation.insert(new Position(lastLine, lastLineMaxColumn), value)]);
671
			this._onDidAppendedContent.fire();
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
		}
	}

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

class BufferedContent {

	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 {
		if (this.length < MAX_OUTPUT_LENGTH * 1.2) {
			return;
		}

		while (this.length > MAX_OUTPUT_LENGTH) {
			this.dataIds.shift();
			const removed = this.data.shift();
			this.length -= removed.length;
		}
	}

	public getDelta(previousId?: number): { value: string, id: number } {
		let idx = -1;
		if (previousId !== void 0) {
			idx = binarySearch(this.dataIds, previousId, (a, b) => a - b);
		}

		const id = this.idPool;
		if (idx >= 0) {
			const value = strings.removeAnsiEscapeCodes(this.data.slice(idx + 1).join(''));
			return { value, id };
		} else {
			const value = strings.removeAnsiEscapeCodes(this.data.join(''));
			return { value, id };
		}
	}
728
}