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

import 'vs/css!./media/diffEditor';
7
import * as nls from 'vs/nls';
A
Alex Dima 已提交
8
import * as dom from 'vs/base/browser/dom';
A
Alex Dima 已提交
9
import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode';
J
João Moreno 已提交
10
import { ISashEvent, IVerticalSashLayoutProvider, Sash, SashState, Orientation } from 'vs/base/browser/ui/sash/sash';
11
import { RunOnceScheduler } from 'vs/base/common/async';
A
Alex Dima 已提交
12 13 14 15 16 17 18
import { Color } from 'vs/base/common/color';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import * as objects from 'vs/base/common/objects';
import { URI } from 'vs/base/common/uri';
import { Configuration } from 'vs/editor/browser/config/configuration';
import { StableEditorScrollState } from 'vs/editor/browser/core/editorState';
A
Alex Dima 已提交
19
import * as editorBrowser from 'vs/editor/browser/editorBrowser';
A
Alex Dima 已提交
20
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
A
Alex Dima 已提交
21
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
A
Alex Dima 已提交
22
import { DiffReview } from 'vs/editor/browser/widget/diffReview';
23
import { IDiffEditorOptions, IEditorOptions, EditorLayoutInfo, EditorOption, EditorOptions, EditorFontLigatures, stringSet as validateStringSetOption, boolean as validateBooleanOption } from 'vs/editor/common/config/editorOptions';
A
Alex Dima 已提交
24 25 26 27 28 29 30 31
import { IPosition, Position } from 'vs/editor/common/core/position';
import { IRange, Range } from 'vs/editor/common/core/range';
import { ISelection, Selection } from 'vs/editor/common/core/selection';
import { IStringBuilder, createStringBuilder } from 'vs/editor/common/core/stringBuilder';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { IModelDecorationsChangeAccessor, IModelDeltaDecoration, ITextModel } from 'vs/editor/common/model';
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
import { IDiffComputationResult, IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService';
32
import { OverviewRulerZone } from 'vs/editor/common/view/overviewZoneManager';
A
Alex Dima 已提交
33 34
import { LineDecoration } from 'vs/editor/common/viewLayout/lineDecorations';
import { RenderLineInput, renderViewLine } from 'vs/editor/common/viewLayout/viewLineRenderer';
35
import { IEditorWhitespace } from 'vs/editor/common/viewLayout/linesLayout';
36
import { ILineBreaksComputer, InlineDecoration, InlineDecorationType, IViewModel, ViewLineRenderingData } from 'vs/editor/common/viewModel/viewModel';
A
Alex Dima 已提交
37 38 39
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
40
import { INotificationService } from 'vs/platform/notification/common/notification';
41
import { defaultInsertColor, defaultRemoveColor, diffBorder, diffInserted, diffInsertedOutline, diffRemoved, diffRemovedOutline, scrollbarShadow, scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground, diffDiagonalFill } from 'vs/platform/theme/common/colorRegistry';
M
Martin Aeschlimann 已提交
42
import { IColorTheme, IThemeService, getThemeTypeSelector, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
43 44 45
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IDiffLinesChange, InlineDiffMargin } from 'vs/editor/browser/widget/inlineDiffMargin';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
46
import { Constants } from 'vs/base/common/uint';
47
import { EditorExtensionsRegistry, IDiffEditorContributionDescription } from 'vs/editor/browser/editorExtensions';
A
Alex Dima 已提交
48
import { onUnexpectedError } from 'vs/base/common/errors';
49
import { IEditorProgressService, IProgressRunner } from 'vs/platform/progress/common/progress';
50
import { ElementSizeObserver } from 'vs/editor/browser/config/elementSizeObserver';
M
Martin Aeschlimann 已提交
51
import { Codicon, registerIcon } from 'vs/base/common/codicons';
52
import { MOUSE_CURSOR_TEXT_CSS_CLASS_NAME } from 'vs/base/browser/ui/mouseCursor/mouseCursor';
53 54
import { IViewLineTokens } from 'vs/editor/common/core/lineTokens';
import { FontInfo } from 'vs/editor/common/config/fontInfo';
E
Erich Gamma 已提交
55 56

interface IEditorDiffDecorations {
57
	decorations: IModelDeltaDecoration[];
A
Alex Dima 已提交
58
	overviewZones: OverviewRulerZone[];
E
Erich Gamma 已提交
59 60 61
}

interface IEditorDiffDecorationsWithZones extends IEditorDiffDecorations {
62
	zones: IMyViewZone[];
E
Erich Gamma 已提交
63 64 65
}

interface IEditorsDiffDecorationsWithZones {
J
Johannes Rieken 已提交
66 67
	original: IEditorDiffDecorationsWithZones;
	modified: IEditorDiffDecorationsWithZones;
E
Erich Gamma 已提交
68 69 70
}

interface IEditorsZones {
71 72
	original: IMyViewZone[];
	modified: IMyViewZone[];
E
Erich Gamma 已提交
73 74 75
}

class VisualEditorState {
A
Alex Dima 已提交
76
	private _zones: string[];
A
Renames  
Alex Dima 已提交
77
	private _inlineDiffMargins: InlineDiffMargin[];
J
Johannes Rieken 已提交
78 79
	private _zonesMap: { [zoneId: string]: boolean; };
	private _decorations: string[];
E
Erich Gamma 已提交
80

81 82
	constructor(
		private _contextMenuService: IContextMenuService,
83
		private _clipboardService: IClipboardService
84
	) {
E
Erich Gamma 已提交
85
		this._zones = [];
A
Renames  
Alex Dima 已提交
86
		this._inlineDiffMargins = [];
E
Erich Gamma 已提交
87 88 89 90
		this._zonesMap = {};
		this._decorations = [];
	}

A
Alex Dima 已提交
91
	public getForeignViewZones(allViewZones: IEditorWhitespace[]): IEditorWhitespace[] {
E
Erich Gamma 已提交
92 93 94
		return allViewZones.filter((z) => !this._zonesMap[String(z.id)]);
	}

A
Alex Dima 已提交
95
	public clean(editor: CodeEditorWidget): void {
E
Erich Gamma 已提交
96 97
		// (1) View zones
		if (this._zones.length > 0) {
J
Johannes Rieken 已提交
98
			editor.changeViewZones((viewChangeAccessor: editorBrowser.IViewZoneChangeAccessor) => {
A
Alex Dima 已提交
99 100
				for (const zoneId of this._zones) {
					viewChangeAccessor.removeZone(zoneId);
E
Erich Gamma 已提交
101 102 103 104 105 106 107
				}
			});
		}
		this._zones = [];
		this._zonesMap = {};

		// (2) Model decorations
A
Alex Dima 已提交
108
		this._decorations = editor.deltaDecorations(this._decorations, []);
E
Erich Gamma 已提交
109 110
	}

A
Alex Dima 已提交
111
	public apply(editor: CodeEditorWidget, overviewRuler: editorBrowser.IOverviewRuler, newDecorations: IEditorDiffDecorationsWithZones, restoreScrollState: boolean): void {
A
Alex Dima 已提交
112 113 114

		const scrollState = restoreScrollState ? StableEditorScrollState.capture(editor) : null;

E
Erich Gamma 已提交
115
		// view zones
J
Johannes Rieken 已提交
116
		editor.changeViewZones((viewChangeAccessor: editorBrowser.IViewZoneChangeAccessor) => {
A
Alex Dima 已提交
117 118
			for (const zoneId of this._zones) {
				viewChangeAccessor.removeZone(zoneId);
E
Erich Gamma 已提交
119
			}
A
Renames  
Alex Dima 已提交
120
			for (const inlineDiffMargin of this._inlineDiffMargins) {
A
Alex Dima 已提交
121
				inlineDiffMargin.dispose();
122
			}
E
Erich Gamma 已提交
123 124
			this._zones = [];
			this._zonesMap = {};
A
Renames  
Alex Dima 已提交
125
			this._inlineDiffMargins = [];
A
Alex Dima 已提交
126
			for (let i = 0, length = newDecorations.zones.length; i < length; i++) {
127
				const viewZone = <editorBrowser.IViewZone>newDecorations.zones[i];
128
				viewZone.suppressMouseDown = true;
A
Alex Dima 已提交
129
				const zoneId = viewChangeAccessor.addZone(viewZone);
E
Erich Gamma 已提交
130 131
				this._zones.push(zoneId);
				this._zonesMap[String(zoneId)] = true;
132

133
				if (newDecorations.zones[i].diff && viewZone.marginDomNode) {
134
					viewZone.suppressMouseDown = false;
A
Renames  
Alex Dima 已提交
135
					this._inlineDiffMargins.push(new InlineDiffMargin(zoneId, viewZone.marginDomNode, editor, newDecorations.zones[i].diff!, this._contextMenuService, this._clipboardService));
136
				}
E
Erich Gamma 已提交
137 138 139
			}
		});

A
Alex Dima 已提交
140 141 142 143
		if (scrollState) {
			scrollState.restore(editor);
		}

E
Erich Gamma 已提交
144 145 146 147
		// decorations
		this._decorations = editor.deltaDecorations(this._decorations, newDecorations.decorations);

		// overview ruler
148 149 150
		if (overviewRuler) {
			overviewRuler.setZones(newDecorations.overviewZones);
		}
E
Erich Gamma 已提交
151 152 153
	}
}

A
Alex Dima 已提交
154
let DIFF_EDITOR_ID = 0;
E
Erich Gamma 已提交
155

M
Martin Aeschlimann 已提交
156 157 158 159

const diffInsertIcon = registerIcon('diff-insert', Codicon.add);
const diffRemoveIcon = registerIcon('diff-remove', Codicon.remove);

A
Alex Dima 已提交
160
export class DiffEditorWidget extends Disposable implements editorBrowser.IDiffEditor {
A
Alex Dima 已提交
161

162
	private static readonly ONE_OVERVIEW_WIDTH = 15;
M
Matt Bierner 已提交
163
	public static readonly ENTIRE_DIFF_OVERVIEW_WIDTH = 30;
164
	private static readonly UPDATE_DIFF_DECORATIONS_DELAY = 200; // ms
E
Erich Gamma 已提交
165

A
Alex Dima 已提交
166 167
	private readonly _onDidDispose: Emitter<void> = this._register(new Emitter<void>());
	public readonly onDidDispose: Event<void> = this._onDidDispose.event;
E
Erich Gamma 已提交
168

A
Alex Dima 已提交
169 170 171
	private readonly _onDidUpdateDiff: Emitter<void> = this._register(new Emitter<void>());
	public readonly onDidUpdateDiff: Event<void> = this._onDidUpdateDiff.event;

R
rebornix 已提交
172 173 174
	private readonly _onDidContentSizeChange: Emitter<editorCommon.IContentSizeChangedEvent> = this._register(new Emitter<editorCommon.IContentSizeChangedEvent>());
	public readonly onDidContentSizeChange: Event<editorCommon.IContentSizeChangedEvent> = this._onDidContentSizeChange.event;

A
Renames  
Alex Dima 已提交
175
	private readonly _id: number;
176
	private _state: editorBrowser.DiffEditorState;
177
	private _updatingDiffProgress: IProgressRunner | null;
E
Erich Gamma 已提交
178

179
	private readonly _domElement: HTMLElement;
A
Alex Dima 已提交
180 181 182
	protected readonly _containerDomElement: HTMLElement;
	private readonly _overviewDomElement: HTMLElement;
	private readonly _overviewViewportDomElement: FastDomNode<HTMLElement>;
E
Erich Gamma 已提交
183

184
	private readonly _elementSizeObserver: ElementSizeObserver;
E
Erich Gamma 已提交
185

A
Renames  
Alex Dima 已提交
186
	private readonly _originalEditor: CodeEditorWidget;
A
Alex Dima 已提交
187
	private readonly _originalDomNode: HTMLElement;
188
	private readonly _originalEditorState: VisualEditorState;
A
Alex Dima 已提交
189
	private _originalOverviewRuler: editorBrowser.IOverviewRuler | null;
E
Erich Gamma 已提交
190

A
Renames  
Alex Dima 已提交
191
	private readonly _modifiedEditor: CodeEditorWidget;
A
Alex Dima 已提交
192
	private readonly _modifiedDomNode: HTMLElement;
193
	private readonly _modifiedEditorState: VisualEditorState;
A
Alex Dima 已提交
194
	private _modifiedOverviewRuler: editorBrowser.IOverviewRuler | null;
E
Erich Gamma 已提交
195

J
Johannes Rieken 已提交
196 197 198
	private _currentlyChangingViewZones: boolean;
	private _beginUpdateDecorationsTimeout: number;
	private _diffComputationToken: number;
A
Alex Dima 已提交
199
	private _diffComputationResult: IDiffComputationResult | null;
E
Erich Gamma 已提交
200

J
Johannes Rieken 已提交
201 202
	private _isVisible: boolean;
	private _isHandlingScrollEvent: boolean;
E
Erich Gamma 已提交
203 204

	private _ignoreTrimWhitespace: boolean;
205
	private _originalIsEditable: boolean;
206
	private _diffCodeLens: boolean;
207
	private _diffWordWrap: 'off' | 'on' | 'inherit';
E
Erich Gamma 已提交
208

J
Johannes Rieken 已提交
209
	private _renderSideBySide: boolean;
210
	private _maxComputationTime: number;
211
	private _renderIndicators: boolean;
J
Johannes Rieken 已提交
212
	private _enableSplitViewResizing: boolean;
213 214
	private _wordWrap: 'off' | 'on' | 'wordWrapColumn' | 'bounded' | undefined;
	private _wordWrapMinified: boolean | undefined;
A
Alex Dima 已提交
215
	private _strategy!: DiffEditorWidgetStyle;
E
Erich Gamma 已提交
216

217
	private readonly _updateDecorationsRunner: RunOnceScheduler;
E
Erich Gamma 已提交
218

219
	private readonly _editorWorkerService: IEditorWorkerService;
220
	protected _contextKeyService: IContextKeyService;
221 222 223
	private readonly _codeEditorService: ICodeEditorService;
	private readonly _themeService: IThemeService;
	private readonly _notificationService: INotificationService;
224

225
	private readonly _reviewPane: DiffReview;
A
Alex Dima 已提交
226

227
	constructor(
J
Johannes Rieken 已提交
228
		domElement: HTMLElement,
229
		options: editorBrowser.IDiffEditorConstructionOptions,
230
		@IClipboardService clipboardService: IClipboardService,
231
		@IEditorWorkerService editorWorkerService: IEditorWorkerService,
232
		@IContextKeyService contextKeyService: IContextKeyService,
233
		@IInstantiationService instantiationService: IInstantiationService,
234
		@ICodeEditorService codeEditorService: ICodeEditorService,
235
		@IThemeService themeService: IThemeService,
236 237
		@INotificationService notificationService: INotificationService,
		@IContextMenuService contextMenuService: IContextMenuService,
238
		@IEditorProgressService private readonly _editorProgressService: IEditorProgressService
239
	) {
E
Erich Gamma 已提交
240
		super();
A
Alex Dima 已提交
241

242
		this._editorWorkerService = editorWorkerService;
243
		this._codeEditorService = codeEditorService;
244
		this._contextKeyService = this._register(contextKeyService.createScoped(domElement));
J
Joao Moreno 已提交
245
		this._contextKeyService.createKey('isInDiffEditor', true);
246
		this._themeService = themeService;
247
		this._notificationService = notificationService;
E
Erich Gamma 已提交
248

A
Renames  
Alex Dima 已提交
249
		this._id = (++DIFF_EDITOR_ID);
250
		this._state = editorBrowser.DiffEditorState.Idle;
251
		this._updatingDiffProgress = null;
E
Erich Gamma 已提交
252 253 254 255

		this._domElement = domElement;
		options = options || {};

256 257 258
		this._wordWrap = options.wordWrap;
		this._wordWrapMinified = options.wordWrapMinified;

E
Erich Gamma 已提交
259 260 261 262 263 264
		// renderSideBySide
		this._renderSideBySide = true;
		if (typeof options.renderSideBySide !== 'undefined') {
			this._renderSideBySide = options.renderSideBySide;
		}

265 266 267 268
		// maxComputationTime
		this._maxComputationTime = 5000;
		if (typeof options.maxComputationTime !== 'undefined') {
			this._maxComputationTime = options.maxComputationTime;
269 270
		}

E
Erich Gamma 已提交
271 272 273 274 275 276
		// ignoreTrimWhitespace
		this._ignoreTrimWhitespace = true;
		if (typeof options.ignoreTrimWhitespace !== 'undefined') {
			this._ignoreTrimWhitespace = options.ignoreTrimWhitespace;
		}

277 278 279 280 281 282
		// renderIndicators
		this._renderIndicators = true;
		if (typeof options.renderIndicators !== 'undefined') {
			this._renderIndicators = options.renderIndicators;
		}

283 284
		this._originalIsEditable = validateBooleanOption(options.originalEditable, false);
		this._diffCodeLens = validateBooleanOption(options.diffCodeLens, false);
285 286
		this._diffWordWrap = validateDiffWordWrap(options.diffWordWrap, 'inherit');

R
rebornix 已提交
287 288 289 290 291 292
		if (typeof options.isInEmbeddedEditor !== 'undefined') {
			this._contextKeyService.createKey('isInEmbeddedDiffEditor', options.isInEmbeddedEditor);
		} else {
			this._contextKeyService.createKey('isInEmbeddedDiffEditor', false);
		}

A
Alex Dima 已提交
293
		this._updateDecorationsRunner = this._register(new RunOnceScheduler(() => this._updateDecorations(), 0));
E
Erich Gamma 已提交
294 295

		this._containerDomElement = document.createElement('div');
M
Martin Aeschlimann 已提交
296
		this._containerDomElement.className = DiffEditorWidget._getClassName(this._themeService.getColorTheme(), this._renderSideBySide);
E
Erich Gamma 已提交
297 298 299 300
		this._containerDomElement.style.position = 'relative';
		this._containerDomElement.style.height = '100%';
		this._domElement.appendChild(this._containerDomElement);

A
Alex Dima 已提交
301 302 303
		this._overviewViewportDomElement = createFastDomNode(document.createElement('div'));
		this._overviewViewportDomElement.setClassName('diffViewport');
		this._overviewViewportDomElement.setPosition('absolute');
E
Erich Gamma 已提交
304 305 306 307 308

		this._overviewDomElement = document.createElement('div');
		this._overviewDomElement.className = 'diffOverview';
		this._overviewDomElement.style.position = 'absolute';

A
Alex Dima 已提交
309
		this._overviewDomElement.appendChild(this._overviewViewportDomElement.domNode);
E
Erich Gamma 已提交
310

311
		this._register(dom.addStandardDisposableListener(this._overviewDomElement, 'mousedown', (e) => {
A
Renames  
Alex Dima 已提交
312
			this._modifiedEditor.delegateVerticalScrollbarMouseDown(e);
E
Erich Gamma 已提交
313 314 315
		}));
		this._containerDomElement.appendChild(this._overviewDomElement);

A
Alex Dima 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328
		// Create left side
		this._originalDomNode = document.createElement('div');
		this._originalDomNode.className = 'editor original';
		this._originalDomNode.style.position = 'absolute';
		this._originalDomNode.style.height = '100%';
		this._containerDomElement.appendChild(this._originalDomNode);

		// Create right side
		this._modifiedDomNode = document.createElement('div');
		this._modifiedDomNode.className = 'editor modified';
		this._modifiedDomNode.style.position = 'absolute';
		this._modifiedDomNode.style.height = '100%';
		this._containerDomElement.appendChild(this._modifiedDomNode);
E
Erich Gamma 已提交
329 330 331 332 333

		this._beginUpdateDecorationsTimeout = -1;
		this._currentlyChangingViewZones = false;
		this._diffComputationToken = 0;

334 335
		this._originalEditorState = new VisualEditorState(contextMenuService, clipboardService);
		this._modifiedEditorState = new VisualEditorState(contextMenuService, clipboardService);
E
Erich Gamma 已提交
336 337 338 339

		this._isVisible = true;
		this._isHandlingScrollEvent = false;

340 341 342 343
		this._elementSizeObserver = this._register(new ElementSizeObserver(this._containerDomElement, undefined, () => this._onDidContainerSizeChanged()));
		if (options.automaticLayout) {
			this._elementSizeObserver.startObserving();
		}
E
Erich Gamma 已提交
344

A
Alex Dima 已提交
345
		this._diffComputationResult = null;
E
Erich Gamma 已提交
346

347
		const leftContextKeyService = this._contextKeyService.createScoped();
J
Joao Moreno 已提交
348

349 350 351
		const leftServices = new ServiceCollection();
		leftServices.set(IContextKeyService, leftContextKeyService);
		const leftScopedInstantiationService = instantiationService.createChild(leftServices);
J
Joao Moreno 已提交
352

353 354 355 356 357 358
		const rightContextKeyService = this._contextKeyService.createScoped();

		const rightServices = new ServiceCollection();
		rightServices.set(IContextKeyService, rightContextKeyService);
		const rightScopedInstantiationService = instantiationService.createChild(rightServices);

A
Renames  
Alex Dima 已提交
359 360
		this._originalEditor = this._createLeftHandSideEditor(options, leftScopedInstantiationService, leftContextKeyService);
		this._modifiedEditor = this._createRightHandSideEditor(options, rightScopedInstantiationService, rightContextKeyService);
A
Alex Dima 已提交
361 362 363

		this._originalOverviewRuler = null;
		this._modifiedOverviewRuler = null;
E
Erich Gamma 已提交
364

365 366 367
		this._reviewPane = new DiffReview(this);
		this._containerDomElement.appendChild(this._reviewPane.domNode.domNode);
		this._containerDomElement.appendChild(this._reviewPane.shadow.domNode);
368
		this._containerDomElement.appendChild(this._reviewPane.actionBarContainer.domNode);
369

E
Erich Gamma 已提交
370 371 372 373 374 375 376
		// enableSplitViewResizing
		this._enableSplitViewResizing = true;
		if (typeof options.enableSplitViewResizing !== 'undefined') {
			this._enableSplitViewResizing = options.enableSplitViewResizing;
		}

		if (this._renderSideBySide) {
H
Howard Hung 已提交
377
			this._setStrategy(new DiffEditorWidgetSideBySide(this._createDataSource(), this._enableSplitViewResizing));
E
Erich Gamma 已提交
378
		} else {
H
Howard Hung 已提交
379
			this._setStrategy(new DiffEditorWidgetInline(this._createDataSource(), this._enableSplitViewResizing));
E
Erich Gamma 已提交
380
		}
381

M
Martin Aeschlimann 已提交
382
		this._register(themeService.onDidColorThemeChange(t => {
383 384 385
			if (this._strategy && this._strategy.applyColors(t)) {
				this._updateDecorationsRunner.schedule();
			}
M
Martin Aeschlimann 已提交
386
			this._containerDomElement.className = DiffEditorWidget._getClassName(this._themeService.getColorTheme(), this._renderSideBySide);
387
		}));
388

389 390
		const contributions: IDiffEditorContributionDescription[] = EditorExtensionsRegistry.getDiffEditorContributions();
		for (const desc of contributions) {
A
Alex Dima 已提交
391
			try {
392
				this._register(instantiationService.createInstance(desc.ctor, this));
A
Alex Dima 已提交
393 394 395 396 397
			} catch (err) {
				onUnexpectedError(err);
			}
		}

398
		this._codeEditorService.addDiffEditor(this);
E
Erich Gamma 已提交
399 400
	}

401 402 403 404 405 406 407 408
	public get ignoreTrimWhitespace(): boolean {
		return this._ignoreTrimWhitespace;
	}

	public get renderSideBySide(): boolean {
		return this._renderSideBySide;
	}

409 410 411 412
	public get maxComputationTime(): number {
		return this._maxComputationTime;
	}

413 414 415 416
	public get renderIndicators(): boolean {
		return this._renderIndicators;
	}

R
rebornix 已提交
417
	public getContentHeight(): number {
A
Renames  
Alex Dima 已提交
418
		return this._modifiedEditor.getContentHeight();
R
rebornix 已提交
419 420
	}

421
	private _setState(newState: editorBrowser.DiffEditorState): void {
422
		if (this._state === newState) {
423 424 425
			return;
		}
		this._state = newState;
426 427 428 429 430 431 432 433 434

		if (this._updatingDiffProgress) {
			this._updatingDiffProgress.done();
			this._updatingDiffProgress = null;
		}

		if (this._state === editorBrowser.DiffEditorState.ComputingDiff) {
			this._updatingDiffProgress = this._editorProgressService.show(true, 1000);
		}
435 436
	}

A
Alex Dima 已提交
437 438 439 440 441 442 443 444 445 446 447 448
	public hasWidgetFocus(): boolean {
		return dom.isAncestor(document.activeElement, this._domElement);
	}

	public diffReviewNext(): void {
		this._reviewPane.next();
	}

	public diffReviewPrev(): void {
		this._reviewPane.prev();
	}

M
Martin Aeschlimann 已提交
449
	private static _getClassName(theme: IColorTheme, renderSideBySide: boolean): string {
A
Alex Dima 已提交
450
		let result = 'monaco-diff-editor monaco-editor-background ';
E
Erich Gamma 已提交
451 452 453
		if (renderSideBySide) {
			result += 'side-by-side ';
		}
454
		result += getThemeTypeSelector(theme.type);
E
Erich Gamma 已提交
455 456 457 458 459 460 461 462
		return result;
	}

	private _recreateOverviewRulers(): void {
		if (this._originalOverviewRuler) {
			this._overviewDomElement.removeChild(this._originalOverviewRuler.getDomNode());
			this._originalOverviewRuler.dispose();
		}
A
Renames  
Alex Dima 已提交
463 464
		if (this._originalEditor.hasModel()) {
			this._originalOverviewRuler = this._originalEditor.createOverviewRuler('original diffOverviewRuler')!;
A
Alex Dima 已提交
465 466
			this._overviewDomElement.appendChild(this._originalOverviewRuler.getDomNode());
		}
E
Erich Gamma 已提交
467 468 469 470 471

		if (this._modifiedOverviewRuler) {
			this._overviewDomElement.removeChild(this._modifiedOverviewRuler.getDomNode());
			this._modifiedOverviewRuler.dispose();
		}
A
Renames  
Alex Dima 已提交
472 473
		if (this._modifiedEditor.hasModel()) {
			this._modifiedOverviewRuler = this._modifiedEditor.createOverviewRuler('modified diffOverviewRuler')!;
A
Alex Dima 已提交
474 475
			this._overviewDomElement.appendChild(this._modifiedOverviewRuler.getDomNode());
		}
E
Erich Gamma 已提交
476 477 478 479

		this._layoutOverviewRulers();
	}

480
	private _createLeftHandSideEditor(options: editorBrowser.IDiffEditorConstructionOptions, instantiationService: IInstantiationService, contextKeyService: IContextKeyService): CodeEditorWidget {
481
		const editor = this._createInnerEditor(instantiationService, this._originalDomNode, this._adjustOptionsForLeftHandSide(options));
A
Alex Dima 已提交
482

A
Alex Dima 已提交
483
		this._register(editor.onDidScrollChange((e) => {
A
Alex Dima 已提交
484 485 486
			if (this._isHandlingScrollEvent) {
				return;
			}
487
			if (!e.scrollTopChanged && !e.scrollLeftChanged && !e.scrollHeightChanged) {
A
Alex Dima 已提交
488 489 490
				return;
			}
			this._isHandlingScrollEvent = true;
A
Renames  
Alex Dima 已提交
491
			this._modifiedEditor.setScrollPosition({
A
Alex Dima 已提交
492 493 494 495
				scrollLeft: e.scrollLeft,
				scrollTop: e.scrollTop
			});
			this._isHandlingScrollEvent = false;
496 497

			this._layoutOverviewViewport();
A
Alex Dima 已提交
498 499
		}));

A
Alex Dima 已提交
500
		this._register(editor.onDidChangeViewZones(() => {
A
Alex Dima 已提交
501 502 503
			this._onViewZonesChanged();
		}));

504 505 506 507
		this._register(editor.onDidChangeConfiguration((e) => {
			if (!editor.getModel()) {
				return;
			}
508
			if (e.hasChanged(EditorOption.fontInfo)) {
509 510
				this._updateDecorationsRunner.schedule();
			}
511 512 513 514
			if (e.hasChanged(EditorOption.wrappingInfo)) {
				this._updateDecorationsRunner.cancel();
				this._updateDecorations();
			}
515 516
		}));

A
Alex Dima 已提交
517
		this._register(editor.onDidChangeModelContent(() => {
A
Alex Dima 已提交
518 519 520 521
			if (this._isVisible) {
				this._beginUpdateDecorationsSoon();
			}
		}));
A
Alex Dima 已提交
522

523
		const isInDiffLeftEditorKey = contextKeyService.createKey<boolean>('isInDiffLeftEditor', undefined);
A
Alex Dima 已提交
524 525
		this._register(editor.onDidFocusEditorWidget(() => isInDiffLeftEditorKey.set(true)));
		this._register(editor.onDidBlurEditorWidget(() => isInDiffLeftEditorKey.set(false)));
526

527
		this._register(editor.onDidContentSizeChange(e => {
A
Renames  
Alex Dima 已提交
528 529
			const width = this._originalEditor.getContentWidth() + this._modifiedEditor.getContentWidth() + DiffEditorWidget.ONE_OVERVIEW_WIDTH;
			const height = Math.max(this._modifiedEditor.getContentHeight(), this._originalEditor.getContentHeight());
530 531 532 533 534 535 536 537 538

			this._onDidContentSizeChange.fire({
				contentHeight: height,
				contentWidth: width,
				contentHeightChanged: e.contentHeightChanged,
				contentWidthChanged: e.contentWidthChanged
			});
		}));

A
Alex Dima 已提交
539
		return editor;
E
Erich Gamma 已提交
540 541
	}

542
	private _createRightHandSideEditor(options: editorBrowser.IDiffEditorConstructionOptions, instantiationService: IInstantiationService, contextKeyService: IContextKeyService): CodeEditorWidget {
543
		const editor = this._createInnerEditor(instantiationService, this._modifiedDomNode, this._adjustOptionsForRightHandSide(options));
A
Alex Dima 已提交
544

A
Alex Dima 已提交
545
		this._register(editor.onDidScrollChange((e) => {
A
Alex Dima 已提交
546 547 548
			if (this._isHandlingScrollEvent) {
				return;
			}
549
			if (!e.scrollTopChanged && !e.scrollLeftChanged && !e.scrollHeightChanged) {
A
Alex Dima 已提交
550 551 552
				return;
			}
			this._isHandlingScrollEvent = true;
A
Renames  
Alex Dima 已提交
553
			this._originalEditor.setScrollPosition({
A
Alex Dima 已提交
554 555 556 557 558 559 560 561
				scrollLeft: e.scrollLeft,
				scrollTop: e.scrollTop
			});
			this._isHandlingScrollEvent = false;

			this._layoutOverviewViewport();
		}));

A
Alex Dima 已提交
562
		this._register(editor.onDidChangeViewZones(() => {
A
Alex Dima 已提交
563 564 565
			this._onViewZonesChanged();
		}));

A
Alex Dima 已提交
566
		this._register(editor.onDidChangeConfiguration((e) => {
567 568 569
			if (!editor.getModel()) {
				return;
			}
570
			if (e.hasChanged(EditorOption.fontInfo)) {
571
				this._updateDecorationsRunner.schedule();
A
Alex Dima 已提交
572
			}
573 574 575 576
			if (e.hasChanged(EditorOption.wrappingInfo)) {
				this._updateDecorationsRunner.cancel();
				this._updateDecorations();
			}
A
Alex Dima 已提交
577 578
		}));

A
Alex Dima 已提交
579
		this._register(editor.onDidChangeModelContent(() => {
A
Alex Dima 已提交
580 581 582 583
			if (this._isVisible) {
				this._beginUpdateDecorationsSoon();
			}
		}));
A
Alex Dima 已提交
584

585 586 587 588 589 590
		this._register(editor.onDidChangeModelOptions((e) => {
			if (e.tabSize) {
				this._updateDecorationsRunner.schedule();
			}
		}));

591
		const isInDiffRightEditorKey = contextKeyService.createKey<boolean>('isInDiffRightEditor', undefined);
A
Alex Dima 已提交
592 593
		this._register(editor.onDidFocusEditorWidget(() => isInDiffRightEditorKey.set(true)));
		this._register(editor.onDidBlurEditorWidget(() => isInDiffRightEditorKey.set(false)));
594

R
rebornix 已提交
595
		this._register(editor.onDidContentSizeChange(e => {
A
Renames  
Alex Dima 已提交
596 597
			const width = this._originalEditor.getContentWidth() + this._modifiedEditor.getContentWidth() + DiffEditorWidget.ONE_OVERVIEW_WIDTH;
			const height = Math.max(this._modifiedEditor.getContentHeight(), this._originalEditor.getContentHeight());
R
rebornix 已提交
598 599 600 601 602 603 604 605 606

			this._onDidContentSizeChange.fire({
				contentHeight: height,
				contentWidth: width,
				contentHeightChanged: e.contentHeightChanged,
				contentWidthChanged: e.contentWidthChanged
			});
		}));

A
Alex Dima 已提交
607
		return editor;
E
Erich Gamma 已提交
608 609
	}

610
	protected _createInnerEditor(instantiationService: IInstantiationService, container: HTMLElement, options: IEditorOptions): CodeEditorWidget {
611
		return instantiationService.createInstance(CodeEditorWidget, container, options, {});
A
Alex Dima 已提交
612 613
	}

E
Erich Gamma 已提交
614
	public dispose(): void {
615 616
		this._codeEditorService.removeDiffEditor(this);

617 618 619 620 621
		if (this._beginUpdateDecorationsTimeout !== -1) {
			window.clearTimeout(this._beginUpdateDecorationsTimeout);
			this._beginUpdateDecorationsTimeout = -1;
		}

E
Erich Gamma 已提交
622 623
		this._cleanViewZonesAndDecorations();

624 625 626 627 628 629 630 631
		if (this._originalOverviewRuler) {
			this._overviewDomElement.removeChild(this._originalOverviewRuler.getDomNode());
			this._originalOverviewRuler.dispose();
		}
		if (this._modifiedOverviewRuler) {
			this._overviewDomElement.removeChild(this._modifiedOverviewRuler.getDomNode());
			this._modifiedOverviewRuler.dispose();
		}
632 633
		this._overviewDomElement.removeChild(this._overviewViewportDomElement.domNode);
		this._containerDomElement.removeChild(this._overviewDomElement);
E
Erich Gamma 已提交
634

635
		this._containerDomElement.removeChild(this._originalDomNode);
A
Renames  
Alex Dima 已提交
636
		this._originalEditor.dispose();
637 638

		this._containerDomElement.removeChild(this._modifiedDomNode);
A
Renames  
Alex Dima 已提交
639
		this._modifiedEditor.dispose();
E
Erich Gamma 已提交
640 641 642

		this._strategy.dispose();

643 644 645
		this._containerDomElement.removeChild(this._reviewPane.domNode.domNode);
		this._containerDomElement.removeChild(this._reviewPane.shadow.domNode);
		this._containerDomElement.removeChild(this._reviewPane.actionBarContainer.domNode);
646 647
		this._reviewPane.dispose();

648 649
		this._domElement.removeChild(this._containerDomElement);

A
Alex Dima 已提交
650
		this._onDidDispose.fire();
A
Alex Dima 已提交
651

E
Erich Gamma 已提交
652 653 654 655 656 657
		super.dispose();
	}

	//------------ begin IDiffEditor methods

	public getId(): string {
A
Renames  
Alex Dima 已提交
658
		return this.getEditorType() + ':' + this._id;
E
Erich Gamma 已提交
659 660 661
	}

	public getEditorType(): string {
A
Alex Dima 已提交
662
		return editorCommon.EditorType.IDiffEditor;
E
Erich Gamma 已提交
663 664
	}

A
Alex Dima 已提交
665
	public getLineChanges(): editorCommon.ILineChange[] | null {
A
Alex Dima 已提交
666 667 668 669
		if (!this._diffComputationResult) {
			return null;
		}
		return this._diffComputationResult.changes;
E
Erich Gamma 已提交
670 671
	}

672 673 674 675
	public getDiffComputationResult(): IDiffComputationResult | null {
		return this._diffComputationResult;
	}

A
Alex Dima 已提交
676
	public getOriginalEditor(): editorBrowser.ICodeEditor {
A
Renames  
Alex Dima 已提交
677
		return this._originalEditor;
E
Erich Gamma 已提交
678 679
	}

A
Alex Dima 已提交
680
	public getModifiedEditor(): editorBrowser.ICodeEditor {
A
Renames  
Alex Dima 已提交
681
		return this._modifiedEditor;
E
Erich Gamma 已提交
682 683
	}

684
	public updateOptions(newOptions: IDiffEditorOptions): void {
E
Erich Gamma 已提交
685

686 687 688
		this._wordWrap = typeof newOptions.wordWrap !== 'undefined' ? newOptions.wordWrap : this._wordWrap;
		this._wordWrapMinified = typeof newOptions.wordWrapMinified !== 'undefined' ? newOptions.wordWrapMinified : this._wordWrapMinified;

E
Erich Gamma 已提交
689
		// Handle side by side
A
Alex Dima 已提交
690
		let renderSideBySideChanged = false;
E
Erich Gamma 已提交
691 692 693 694 695 696 697
		if (typeof newOptions.renderSideBySide !== 'undefined') {
			if (this._renderSideBySide !== newOptions.renderSideBySide) {
				this._renderSideBySide = newOptions.renderSideBySide;
				renderSideBySideChanged = true;
			}
		}

698 699
		if (typeof newOptions.maxComputationTime !== 'undefined') {
			this._maxComputationTime = newOptions.maxComputationTime;
700 701 702
			if (this._isVisible) {
				this._beginUpdateDecorationsSoon();
			}
703 704
		}

705 706
		let beginUpdateDecorations = false;

E
Erich Gamma 已提交
707 708 709 710
		if (typeof newOptions.ignoreTrimWhitespace !== 'undefined') {
			if (this._ignoreTrimWhitespace !== newOptions.ignoreTrimWhitespace) {
				this._ignoreTrimWhitespace = newOptions.ignoreTrimWhitespace;
				// Begin comparing
711 712 713 714 715 716 717 718
				beginUpdateDecorations = true;
			}
		}

		if (typeof newOptions.renderIndicators !== 'undefined') {
			if (this._renderIndicators !== newOptions.renderIndicators) {
				this._renderIndicators = newOptions.renderIndicators;
				beginUpdateDecorations = true;
E
Erich Gamma 已提交
719 720 721
			}
		}

722 723 724 725
		if (beginUpdateDecorations) {
			this._beginUpdateDecorations();
		}

726 727
		this._originalIsEditable = validateBooleanOption(newOptions.originalEditable, this._originalIsEditable);
		this._diffCodeLens = validateBooleanOption(newOptions.diffCodeLens, this._diffCodeLens);
728
		this._diffWordWrap = validateDiffWordWrap(newOptions.diffWordWrap, this._diffWordWrap);
729

730 731
		this._modifiedEditor.updateOptions(this._adjustOptionsForRightHandSide(newOptions));
		this._originalEditor.updateOptions(this._adjustOptionsForLeftHandSide(newOptions));
E
Erich Gamma 已提交
732 733 734 735 736 737 738 739 740 741

		// enableSplitViewResizing
		if (typeof newOptions.enableSplitViewResizing !== 'undefined') {
			this._enableSplitViewResizing = newOptions.enableSplitViewResizing;
		}
		this._strategy.setEnableSplitViewResizing(this._enableSplitViewResizing);

		// renderSideBySide
		if (renderSideBySideChanged) {
			if (this._renderSideBySide) {
H
Howard Hung 已提交
742
				this._setStrategy(new DiffEditorWidgetSideBySide(this._createDataSource(), this._enableSplitViewResizing));
E
Erich Gamma 已提交
743
			} else {
H
Howard Hung 已提交
744
				this._setStrategy(new DiffEditorWidgetInline(this._createDataSource(), this._enableSplitViewResizing));
E
Erich Gamma 已提交
745
			}
746
			// Update class name
M
Martin Aeschlimann 已提交
747
			this._containerDomElement.className = DiffEditorWidget._getClassName(this._themeService.getColorTheme(), this._renderSideBySide);
E
Erich Gamma 已提交
748 749 750
		}
	}

A
Alex Dima 已提交
751
	public getModel(): editorCommon.IDiffEditorModel {
E
Erich Gamma 已提交
752
		return {
A
Renames  
Alex Dima 已提交
753 754
			original: this._originalEditor.getModel()!,
			modified: this._modifiedEditor.getModel()!
E
Erich Gamma 已提交
755 756 757
		};
	}

J
Johannes Rieken 已提交
758
	public setModel(model: editorCommon.IDiffEditorModel): void {
E
Erich Gamma 已提交
759 760 761 762 763 764 765 766 767
		// Guard us against partial null model
		if (model && (!model.original || !model.modified)) {
			throw new Error(!model.original ? 'DiffEditorWidget.setModel: Original model is null' : 'DiffEditorWidget.setModel: Modified model is null');
		}

		// Remove all view zones & decorations
		this._cleanViewZonesAndDecorations();

		// Update code editor models
A
Renames  
Alex Dima 已提交
768 769
		this._originalEditor.setModel(model ? model.original : null);
		this._modifiedEditor.setModel(model ? model.modified : null);
E
Erich Gamma 已提交
770 771
		this._updateDecorationsRunner.cancel();

772 773
		// this.originalEditor.onDidChangeModelOptions

E
Erich Gamma 已提交
774
		if (model) {
A
Renames  
Alex Dima 已提交
775 776
			this._originalEditor.setScrollTop(0);
			this._modifiedEditor.setScrollTop(0);
E
Erich Gamma 已提交
777 778 779
		}

		// Disable any diff computations that will come in
A
Alex Dima 已提交
780
		this._diffComputationResult = null;
E
Erich Gamma 已提交
781
		this._diffComputationToken++;
782
		this._setState(editorBrowser.DiffEditorState.Idle);
E
Erich Gamma 已提交
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797

		if (model) {
			this._recreateOverviewRulers();

			// Begin comparing
			this._beginUpdateDecorations();
		}

		this._layoutOverviewViewport();
	}

	public getDomNode(): HTMLElement {
		return this._domElement;
	}

A
Alex Dima 已提交
798
	public getVisibleColumnFromPosition(position: IPosition): number {
A
Renames  
Alex Dima 已提交
799
		return this._modifiedEditor.getVisibleColumnFromPosition(position);
E
Erich Gamma 已提交
800 801
	}

802
	public getStatusbarColumn(position: IPosition): number {
A
Renames  
Alex Dima 已提交
803
		return this._modifiedEditor.getStatusbarColumn(position);
804 805
	}

A
Alex Dima 已提交
806
	public getPosition(): Position | null {
A
Renames  
Alex Dima 已提交
807
		return this._modifiedEditor.getPosition();
E
Erich Gamma 已提交
808 809
	}

810
	public setPosition(position: IPosition): void {
A
Renames  
Alex Dima 已提交
811
		this._modifiedEditor.setPosition(position);
E
Erich Gamma 已提交
812 813
	}

814
	public revealLine(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
815
		this._modifiedEditor.revealLine(lineNumber, scrollType);
E
Erich Gamma 已提交
816 817
	}

818
	public revealLineInCenter(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
819
		this._modifiedEditor.revealLineInCenter(lineNumber, scrollType);
E
Erich Gamma 已提交
820 821
	}

822
	public revealLineInCenterIfOutsideViewport(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
823
		this._modifiedEditor.revealLineInCenterIfOutsideViewport(lineNumber, scrollType);
E
Erich Gamma 已提交
824 825
	}

826
	public revealLineNearTop(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
827
		this._modifiedEditor.revealLineNearTop(lineNumber, scrollType);
828 829
	}

830
	public revealPosition(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
831
		this._modifiedEditor.revealPosition(position, scrollType);
E
Erich Gamma 已提交
832 833
	}

834
	public revealPositionInCenter(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
835
		this._modifiedEditor.revealPositionInCenter(position, scrollType);
E
Erich Gamma 已提交
836 837
	}

838
	public revealPositionInCenterIfOutsideViewport(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
839
		this._modifiedEditor.revealPositionInCenterIfOutsideViewport(position, scrollType);
E
Erich Gamma 已提交
840 841
	}

842
	public revealPositionNearTop(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
843
		this._modifiedEditor.revealPositionNearTop(position, scrollType);
844 845
	}

A
Alex Dima 已提交
846
	public getSelection(): Selection | null {
A
Renames  
Alex Dima 已提交
847
		return this._modifiedEditor.getSelection();
E
Erich Gamma 已提交
848 849
	}

A
Alex Dima 已提交
850
	public getSelections(): Selection[] | null {
A
Renames  
Alex Dima 已提交
851
		return this._modifiedEditor.getSelections();
E
Erich Gamma 已提交
852 853
	}

854 855 856 857 858
	public setSelection(range: IRange): void;
	public setSelection(editorRange: Range): void;
	public setSelection(selection: ISelection): void;
	public setSelection(editorSelection: Selection): void;
	public setSelection(something: any): void {
A
Renames  
Alex Dima 已提交
859
		this._modifiedEditor.setSelection(something);
E
Erich Gamma 已提交
860 861
	}

862
	public setSelections(ranges: readonly ISelection[]): void {
A
Renames  
Alex Dima 已提交
863
		this._modifiedEditor.setSelections(ranges);
E
Erich Gamma 已提交
864 865
	}

866
	public revealLines(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
867
		this._modifiedEditor.revealLines(startLineNumber, endLineNumber, scrollType);
E
Erich Gamma 已提交
868 869
	}

870
	public revealLinesInCenter(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
871
		this._modifiedEditor.revealLinesInCenter(startLineNumber, endLineNumber, scrollType);
E
Erich Gamma 已提交
872 873
	}

874
	public revealLinesInCenterIfOutsideViewport(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
875
		this._modifiedEditor.revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType);
E
Erich Gamma 已提交
876 877
	}

878
	public revealLinesNearTop(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
879
		this._modifiedEditor.revealLinesNearTop(startLineNumber, endLineNumber, scrollType);
880 881
	}

882
	public revealRange(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth, revealVerticalInCenter: boolean = false, revealHorizontal: boolean = true): void {
A
Renames  
Alex Dima 已提交
883
		this._modifiedEditor.revealRange(range, scrollType, revealVerticalInCenter, revealHorizontal);
E
Erich Gamma 已提交
884 885
	}

886
	public revealRangeInCenter(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
887
		this._modifiedEditor.revealRangeInCenter(range, scrollType);
E
Erich Gamma 已提交
888 889
	}

890
	public revealRangeInCenterIfOutsideViewport(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
891
		this._modifiedEditor.revealRangeInCenterIfOutsideViewport(range, scrollType);
E
Erich Gamma 已提交
892 893
	}

894
	public revealRangeNearTop(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
895
		this._modifiedEditor.revealRangeNearTop(range, scrollType);
896 897
	}

898
	public revealRangeNearTopIfOutsideViewport(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
899
		this._modifiedEditor.revealRangeNearTopIfOutsideViewport(range, scrollType);
900 901
	}

902
	public revealRangeAtTop(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
A
Renames  
Alex Dima 已提交
903
		this._modifiedEditor.revealRangeAtTop(range, scrollType);
904 905
	}

A
Alex Dima 已提交
906
	public getSupportedActions(): editorCommon.IEditorAction[] {
A
Renames  
Alex Dima 已提交
907
		return this._modifiedEditor.getSupportedActions();
908 909
	}

A
Alex Dima 已提交
910
	public saveViewState(): editorCommon.IDiffEditorViewState {
A
Alex Dima 已提交
911 912
		const originalViewState = this._originalEditor.saveViewState();
		const modifiedViewState = this._modifiedEditor.saveViewState();
E
Erich Gamma 已提交
913 914 915 916 917 918
		return {
			original: originalViewState,
			modified: modifiedViewState
		};
	}

A
Alex Dima 已提交
919
	public restoreViewState(s: editorCommon.IDiffEditorViewState): void {
A
Alex Dima 已提交
920
		if (s.original && s.modified) {
A
Alex Dima 已提交
921
			const diffEditorState = <editorCommon.IDiffEditorViewState>s;
A
Renames  
Alex Dima 已提交
922 923
			this._originalEditor.restoreViewState(diffEditorState.original);
			this._modifiedEditor.restoreViewState(diffEditorState.modified);
E
Erich Gamma 已提交
924 925 926
		}
	}

J
Johannes Rieken 已提交
927
	public layout(dimension?: editorCommon.IDimension): void {
928
		this._elementSizeObserver.observe(dimension);
E
Erich Gamma 已提交
929 930 931
	}

	public focus(): void {
A
Renames  
Alex Dima 已提交
932
		this._modifiedEditor.focus();
E
Erich Gamma 已提交
933 934
	}

A
Alex Dima 已提交
935
	public hasTextFocus(): boolean {
A
Renames  
Alex Dima 已提交
936
		return this._originalEditor.hasTextFocus() || this._modifiedEditor.hasTextFocus();
E
Erich Gamma 已提交
937 938 939 940
	}

	public onVisible(): void {
		this._isVisible = true;
A
Renames  
Alex Dima 已提交
941 942
		this._originalEditor.onVisible();
		this._modifiedEditor.onVisible();
E
Erich Gamma 已提交
943 944 945 946 947 948
		// Begin comparing
		this._beginUpdateDecorations();
	}

	public onHide(): void {
		this._isVisible = false;
A
Renames  
Alex Dima 已提交
949 950
		this._originalEditor.onHide();
		this._modifiedEditor.onHide();
E
Erich Gamma 已提交
951 952 953 954
		// Remove all view zones & decorations
		this._cleanViewZonesAndDecorations();
	}

A
Alex Dima 已提交
955
	public trigger(source: string | null | undefined, handlerId: string, payload: any): void {
A
Renames  
Alex Dima 已提交
956
		this._modifiedEditor.trigger(source, handlerId, payload);
E
Erich Gamma 已提交
957 958
	}

959
	public changeDecorations(callback: (changeAccessor: IModelDecorationsChangeAccessor) => any): any {
A
Renames  
Alex Dima 已提交
960
		return this._modifiedEditor.changeDecorations(callback);
E
Erich Gamma 已提交
961 962 963 964 965 966 967 968
	}

	//------------ end IDiffEditor methods



	//------------ begin layouting methods

969
	private _onDidContainerSizeChanged(): void {
E
Erich Gamma 已提交
970 971 972
		this._doLayout();
	}

973 974 975 976
	private _getReviewHeight(): number {
		return this._reviewPane.isVisible() ? this._elementSizeObserver.getHeight() : 0;
	}

E
Erich Gamma 已提交
977
	private _layoutOverviewRulers(): void {
A
Alex Dima 已提交
978 979 980
		if (!this._originalOverviewRuler || !this._modifiedOverviewRuler) {
			return;
		}
981 982 983
		const height = this._elementSizeObserver.getHeight();
		const reviewHeight = this._getReviewHeight();

A
Alex Dima 已提交
984 985
		const freeSpace = DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH - 2 * DiffEditorWidget.ONE_OVERVIEW_WIDTH;
		const layoutInfo = this._modifiedEditor.getLayoutInfo();
E
Erich Gamma 已提交
986
		if (layoutInfo) {
A
Alex Dima 已提交
987
			this._originalOverviewRuler.setLayout({
E
Erich Gamma 已提交
988 989 990
				top: 0,
				width: DiffEditorWidget.ONE_OVERVIEW_WIDTH,
				right: freeSpace + DiffEditorWidget.ONE_OVERVIEW_WIDTH,
991
				height: (height - reviewHeight)
A
Alex Dima 已提交
992 993
			});
			this._modifiedOverviewRuler.setLayout({
E
Erich Gamma 已提交
994 995 996
				top: 0,
				right: 0,
				width: DiffEditorWidget.ONE_OVERVIEW_WIDTH,
997
				height: (height - reviewHeight)
A
Alex Dima 已提交
998
			});
E
Erich Gamma 已提交
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
		}
	}

	//------------ end layouting methods

	private _onViewZonesChanged(): void {
		if (this._currentlyChangingViewZones) {
			return;
		}
		this._updateDecorationsRunner.schedule();
	}

A
Alex Dima 已提交
1011 1012 1013 1014 1015 1016 1017 1018 1019
	private _beginUpdateDecorationsSoon(): void {
		// Clear previous timeout if necessary
		if (this._beginUpdateDecorationsTimeout !== -1) {
			window.clearTimeout(this._beginUpdateDecorationsTimeout);
			this._beginUpdateDecorationsTimeout = -1;
		}
		this._beginUpdateDecorationsTimeout = window.setTimeout(() => this._beginUpdateDecorations(), DiffEditorWidget.UPDATE_DIFF_DECORATIONS_DELAY);
	}

1020 1021
	private _lastOriginalWarning: URI | null = null;
	private _lastModifiedWarning: URI | null = null;
1022

A
Alex Dima 已提交
1023
	private static _equals(a: URI | null, b: URI | null): boolean {
1024 1025 1026 1027 1028 1029 1030 1031 1032
		if (!a && !b) {
			return true;
		}
		if (!a || !b) {
			return false;
		}
		return (a.toString() === b.toString());
	}

E
Erich Gamma 已提交
1033 1034
	private _beginUpdateDecorations(): void {
		this._beginUpdateDecorationsTimeout = -1;
A
Renames  
Alex Dima 已提交
1035 1036
		const currentOriginalModel = this._originalEditor.getModel();
		const currentModifiedModel = this._modifiedEditor.getModel();
1037
		if (!currentOriginalModel || !currentModifiedModel) {
E
Erich Gamma 已提交
1038 1039 1040 1041 1042 1043 1044
			return;
		}

		// Prevent old diff requests to come if a new request has been initiated
		// The best method would be to call cancel on the Promise, but this is not
		// yet supported, so using tokens for now.
		this._diffComputationToken++;
A
Alex Dima 已提交
1045
		const currentToken = this._diffComputationToken;
1046
		this._setState(editorBrowser.DiffEditorState.ComputingDiff);
E
Erich Gamma 已提交
1047

1048 1049 1050 1051 1052 1053 1054
		if (!this._editorWorkerService.canComputeDiff(currentOriginalModel.uri, currentModifiedModel.uri)) {
			if (
				!DiffEditorWidget._equals(currentOriginalModel.uri, this._lastOriginalWarning)
				|| !DiffEditorWidget._equals(currentModifiedModel.uri, this._lastModifiedWarning)
			) {
				this._lastOriginalWarning = currentOriginalModel.uri;
				this._lastModifiedWarning = currentModifiedModel.uri;
1055
				this._notificationService.warn(nls.localize("diff.tooLarge", "Cannot compare files because one file is too large."));
1056 1057 1058 1059
			}
			return;
		}

1060
		this._editorWorkerService.computeDiff(currentOriginalModel.uri, currentModifiedModel.uri, this._ignoreTrimWhitespace, this._maxComputationTime).then((result) => {
1061
			if (currentToken === this._diffComputationToken
A
Renames  
Alex Dima 已提交
1062 1063
				&& currentOriginalModel === this._originalEditor.getModel()
				&& currentModifiedModel === this._modifiedEditor.getModel()
J
Johannes Rieken 已提交
1064
			) {
1065
				this._setState(editorBrowser.DiffEditorState.DiffComputed);
A
Alex Dima 已提交
1066
				this._diffComputationResult = result;
1067
				this._updateDecorationsRunner.schedule();
A
Alex Dima 已提交
1068
				this._onDidUpdateDiff.fire();
1069 1070 1071
			}
		}, (error) => {
			if (currentToken === this._diffComputationToken
A
Renames  
Alex Dima 已提交
1072 1073
				&& currentOriginalModel === this._originalEditor.getModel()
				&& currentModifiedModel === this._modifiedEditor.getModel()
J
Johannes Rieken 已提交
1074
			) {
1075
				this._setState(editorBrowser.DiffEditorState.DiffComputed);
A
Alex Dima 已提交
1076
				this._diffComputationResult = null;
E
Erich Gamma 已提交
1077 1078
				this._updateDecorationsRunner.schedule();
			}
1079
		});
E
Erich Gamma 已提交
1080 1081 1082
	}

	private _cleanViewZonesAndDecorations(): void {
A
Renames  
Alex Dima 已提交
1083 1084
		this._originalEditorState.clean(this._originalEditor);
		this._modifiedEditorState.clean(this._modifiedEditor);
E
Erich Gamma 已提交
1085 1086 1087
	}

	private _updateDecorations(): void {
A
Renames  
Alex Dima 已提交
1088
		if (!this._originalEditor.getModel() || !this._modifiedEditor.getModel() || !this._originalOverviewRuler || !this._modifiedOverviewRuler) {
1089 1090
			return;
		}
A
Alex Dima 已提交
1091
		const lineChanges = (this._diffComputationResult ? this._diffComputationResult.changes : []);
E
Erich Gamma 已提交
1092

A
Alex Dima 已提交
1093 1094
		const foreignOriginal = this._originalEditorState.getForeignViewZones(this._originalEditor.getWhitespaces());
		const foreignModified = this._modifiedEditorState.getForeignViewZones(this._modifiedEditor.getWhitespaces());
E
Erich Gamma 已提交
1095

A
Alex Dima 已提交
1096
		const diffDecorations = this._strategy.getEditorsDiffDecorations(lineChanges, this._ignoreTrimWhitespace, this._renderIndicators, foreignOriginal, foreignModified);
E
Erich Gamma 已提交
1097 1098 1099

		try {
			this._currentlyChangingViewZones = true;
A
Renames  
Alex Dima 已提交
1100 1101
			this._originalEditorState.apply(this._originalEditor, this._originalOverviewRuler, diffDecorations.original, false);
			this._modifiedEditorState.apply(this._modifiedEditor, this._modifiedOverviewRuler, diffDecorations.modified, true);
E
Erich Gamma 已提交
1102 1103 1104 1105 1106
		} finally {
			this._currentlyChangingViewZones = false;
		}
	}

1107
	private _adjustOptionsForSubEditor(options: editorBrowser.IDiffEditorConstructionOptions): editorBrowser.IDiffEditorConstructionOptions {
A
Alex Dima 已提交
1108
		const clonedOptions: editorBrowser.IDiffEditorConstructionOptions = objects.deepClone(options || {});
A
Alex Dima 已提交
1109
		clonedOptions.inDiffEditor = true;
E
Erich Gamma 已提交
1110 1111 1112
		clonedOptions.automaticLayout = false;
		clonedOptions.scrollbar = clonedOptions.scrollbar || {};
		clonedOptions.scrollbar.vertical = 'visible';
A
Alex Dima 已提交
1113
		clonedOptions.folding = false;
1114
		clonedOptions.codeLens = this._diffCodeLens;
J
Joao Moreno 已提交
1115
		clonedOptions.fixedOverflowWidgets = true;
1116
		clonedOptions.overflowWidgetsDomNode = options.overflowWidgetsDomNode;
1117
		// clonedOptions.lineDecorationsWidth = '2ch';
1118 1119 1120
		if (!clonedOptions.minimap) {
			clonedOptions.minimap = {};
		}
1121
		clonedOptions.minimap.enabled = false;
E
Erich Gamma 已提交
1122 1123 1124
		return clonedOptions;
	}

1125
	private _adjustOptionsForLeftHandSide(options: editorBrowser.IDiffEditorConstructionOptions): editorBrowser.IEditorConstructionOptions {
A
Alex Dima 已提交
1126
		const result = this._adjustOptionsForSubEditor(options);
1127 1128 1129 1130
		if (!this._renderSideBySide) {
			// do not wrap hidden editor
			result.wordWrap = 'off';
			result.wordWrapMinified = false;
1131
		} else if (this._diffWordWrap === 'inherit') {
1132 1133
			result.wordWrap = this._wordWrap;
			result.wordWrapMinified = this._wordWrapMinified;
1134 1135 1136
		} else {
			result.wordWrap = this._diffWordWrap;
			result.wordWrapMinified = this._wordWrapMinified;
1137
		}
1138
		result.readOnly = !this._originalIsEditable;
1139
		result.extraEditorClassName = 'original-in-monaco-diff-editor';
1140 1141 1142
		return result;
	}

1143
	private _adjustOptionsForRightHandSide(options: editorBrowser.IDiffEditorConstructionOptions): editorBrowser.IEditorConstructionOptions {
A
Alex Dima 已提交
1144
		const result = this._adjustOptionsForSubEditor(options);
1145 1146 1147 1148 1149
		if (this._diffWordWrap === 'inherit') {
			result.wordWrap = this._wordWrap;
		} else {
			result.wordWrap = this._diffWordWrap;
		}
A
Alex Dima 已提交
1150
		result.revealHorizontalRightPadding = EditorOptions.revealHorizontalRightPadding.defaultValue + DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH;
A
Alex Dima 已提交
1151
		result.scrollbar!.verticalHasArrows = false;
1152
		result.extraEditorClassName = 'modified-in-monaco-diff-editor';
1153
		return result;
E
Erich Gamma 已提交
1154 1155
	}

1156
	public doLayout(): void {
1157 1158
		this._elementSizeObserver.observe();
		this._doLayout();
1159 1160
	}

E
Erich Gamma 已提交
1161
	private _doLayout(): void {
1162 1163 1164 1165
		const width = this._elementSizeObserver.getWidth();
		const height = this._elementSizeObserver.getHeight();
		const reviewHeight = this._getReviewHeight();

A
Alex Dima 已提交
1166
		const splitPoint = this._strategy.layout();
E
Erich Gamma 已提交
1167 1168 1169 1170

		this._originalDomNode.style.width = splitPoint + 'px';
		this._originalDomNode.style.left = '0px';

1171
		this._modifiedDomNode.style.width = (width - splitPoint) + 'px';
E
Erich Gamma 已提交
1172 1173 1174
		this._modifiedDomNode.style.left = splitPoint + 'px';

		this._overviewDomElement.style.top = '0px';
1175
		this._overviewDomElement.style.height = (height - reviewHeight) + 'px';
E
Erich Gamma 已提交
1176
		this._overviewDomElement.style.width = DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH + 'px';
1177
		this._overviewDomElement.style.left = (width - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH) + 'px';
A
Alex Dima 已提交
1178 1179
		this._overviewViewportDomElement.setWidth(DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH);
		this._overviewViewportDomElement.setHeight(30);
E
Erich Gamma 已提交
1180

A
Renames  
Alex Dima 已提交
1181 1182
		this._originalEditor.layout({ width: splitPoint, height: (height - reviewHeight) });
		this._modifiedEditor.layout({ width: width - splitPoint - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH, height: (height - reviewHeight) });
E
Erich Gamma 已提交
1183 1184 1185 1186 1187

		if (this._originalOverviewRuler || this._modifiedOverviewRuler) {
			this._layoutOverviewRulers();
		}

1188
		this._reviewPane.layout(height - reviewHeight, width, reviewHeight);
A
Alex Dima 已提交
1189

E
Erich Gamma 已提交
1190 1191 1192 1193
		this._layoutOverviewViewport();
	}

	private _layoutOverviewViewport(): void {
A
Alex Dima 已提交
1194
		const layout = this._computeOverviewViewport();
E
Erich Gamma 已提交
1195
		if (!layout) {
A
Alex Dima 已提交
1196 1197
			this._overviewViewportDomElement.setTop(0);
			this._overviewViewportDomElement.setHeight(0);
E
Erich Gamma 已提交
1198
		} else {
A
Alex Dima 已提交
1199 1200
			this._overviewViewportDomElement.setTop(layout.top);
			this._overviewViewportDomElement.setHeight(layout.height);
E
Erich Gamma 已提交
1201 1202 1203
		}
	}

A
Alex Dima 已提交
1204
	private _computeOverviewViewport(): { height: number; top: number; } | null {
A
Alex Dima 已提交
1205
		const layoutInfo = this._modifiedEditor.getLayoutInfo();
E
Erich Gamma 已提交
1206 1207 1208 1209
		if (!layoutInfo) {
			return null;
		}

A
Alex Dima 已提交
1210 1211
		const scrollTop = this._modifiedEditor.getScrollTop();
		const scrollHeight = this._modifiedEditor.getScrollHeight();
E
Erich Gamma 已提交
1212

A
Alex Dima 已提交
1213 1214 1215
		const computedAvailableSize = Math.max(0, layoutInfo.height);
		const computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * 0);
		const computedRatio = scrollHeight > 0 ? (computedRepresentableSize / scrollHeight) : 0;
E
Erich Gamma 已提交
1216

A
Alex Dima 已提交
1217 1218
		const computedSliderSize = Math.max(0, Math.floor(layoutInfo.height * computedRatio));
		const computedSliderPosition = Math.floor(scrollTop * computedRatio);
E
Erich Gamma 已提交
1219 1220 1221 1222 1223 1224 1225

		return {
			height: computedSliderSize,
			top: computedSliderPosition
		};
	}

J
Johannes Rieken 已提交
1226
	private _createDataSource(): IDataSource {
E
Erich Gamma 已提交
1227 1228
		return {
			getWidth: () => {
1229
				return this._elementSizeObserver.getWidth();
E
Erich Gamma 已提交
1230 1231 1232
			},

			getHeight: () => {
1233
				return (this._elementSizeObserver.getHeight() - this._getReviewHeight());
E
Erich Gamma 已提交
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
			},

			getContainerDomNode: () => {
				return this._containerDomElement;
			},

			relayoutEditors: () => {
				this._doLayout();
			},

			getOriginalEditor: () => {
A
Renames  
Alex Dima 已提交
1245
				return this._originalEditor;
E
Erich Gamma 已提交
1246 1247 1248
			},

			getModifiedEditor: () => {
A
Renames  
Alex Dima 已提交
1249
				return this._modifiedEditor;
E
Erich Gamma 已提交
1250 1251 1252 1253
			}
		};
	}

A
Alex Dima 已提交
1254
	private _setStrategy(newStrategy: DiffEditorWidgetStyle): void {
E
Erich Gamma 已提交
1255 1256 1257 1258 1259
		if (this._strategy) {
			this._strategy.dispose();
		}

		this._strategy = newStrategy;
M
Martin Aeschlimann 已提交
1260
		newStrategy.applyColors(this._themeService.getColorTheme());
E
Erich Gamma 已提交
1261

A
Alex Dima 已提交
1262
		if (this._diffComputationResult) {
E
Erich Gamma 已提交
1263 1264 1265 1266
			this._updateDecorations();
		}

		// Just do a layout, the strategy might need it
1267
		this._doLayout();
E
Erich Gamma 已提交
1268 1269
	}

A
Alex Dima 已提交
1270
	private _getLineChangeAtOrBeforeLineNumber(lineNumber: number, startLineNumberExtractor: (lineChange: editorCommon.ILineChange) => number): editorCommon.ILineChange | null {
A
Alex Dima 已提交
1271 1272
		const lineChanges = (this._diffComputationResult ? this._diffComputationResult.changes : []);
		if (lineChanges.length === 0 || lineNumber < startLineNumberExtractor(lineChanges[0])) {
E
Erich Gamma 已提交
1273 1274 1275 1276
			// There are no changes or `lineNumber` is before the first change
			return null;
		}

A
Alex Dima 已提交
1277 1278
		let min = 0;
		let max = lineChanges.length - 1;
E
Erich Gamma 已提交
1279
		while (min < max) {
A
Alex Dima 已提交
1280 1281 1282
			const mid = Math.floor((min + max) / 2);
			const midStart = startLineNumberExtractor(lineChanges[mid]);
			const midEnd = (mid + 1 <= max ? startLineNumberExtractor(lineChanges[mid + 1]) : Constants.MAX_SAFE_SMALL_INTEGER);
E
Erich Gamma 已提交
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293

			if (lineNumber < midStart) {
				max = mid - 1;
			} else if (lineNumber >= midEnd) {
				min = mid + 1;
			} else {
				// HIT!
				min = mid;
				max = mid;
			}
		}
A
Alex Dima 已提交
1294
		return lineChanges[min];
E
Erich Gamma 已提交
1295 1296 1297
	}

	private _getEquivalentLineForOriginalLineNumber(lineNumber: number): number {
A
Alex Dima 已提交
1298
		const lineChange = this._getLineChangeAtOrBeforeLineNumber(lineNumber, (lineChange) => lineChange.originalStartLineNumber);
E
Erich Gamma 已提交
1299 1300 1301 1302 1303

		if (!lineChange) {
			return lineNumber;
		}

A
Alex Dima 已提交
1304 1305 1306 1307
		const originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0);
		const modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0);
		const lineChangeOriginalLength = (lineChange.originalEndLineNumber > 0 ? (lineChange.originalEndLineNumber - lineChange.originalStartLineNumber + 1) : 0);
		const lineChangeModifiedLength = (lineChange.modifiedEndLineNumber > 0 ? (lineChange.modifiedEndLineNumber - lineChange.modifiedStartLineNumber + 1) : 0);
E
Erich Gamma 已提交
1308 1309


A
Alex Dima 已提交
1310
		const delta = lineNumber - originalEquivalentLineNumber;
E
Erich Gamma 已提交
1311 1312 1313 1314 1315

		if (delta <= lineChangeOriginalLength) {
			return modifiedEquivalentLineNumber + Math.min(delta, lineChangeModifiedLength);
		}

J
Johannes Rieken 已提交
1316
		return modifiedEquivalentLineNumber + lineChangeModifiedLength - lineChangeOriginalLength + delta;
E
Erich Gamma 已提交
1317 1318 1319
	}

	private _getEquivalentLineForModifiedLineNumber(lineNumber: number): number {
A
Alex Dima 已提交
1320
		const lineChange = this._getLineChangeAtOrBeforeLineNumber(lineNumber, (lineChange) => lineChange.modifiedStartLineNumber);
E
Erich Gamma 已提交
1321 1322 1323 1324 1325

		if (!lineChange) {
			return lineNumber;
		}

A
Alex Dima 已提交
1326 1327 1328 1329
		const originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0);
		const modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0);
		const lineChangeOriginalLength = (lineChange.originalEndLineNumber > 0 ? (lineChange.originalEndLineNumber - lineChange.originalStartLineNumber + 1) : 0);
		const lineChangeModifiedLength = (lineChange.modifiedEndLineNumber > 0 ? (lineChange.modifiedEndLineNumber - lineChange.modifiedStartLineNumber + 1) : 0);
E
Erich Gamma 已提交
1330 1331


A
Alex Dima 已提交
1332
		const delta = lineNumber - modifiedEquivalentLineNumber;
E
Erich Gamma 已提交
1333 1334 1335 1336 1337

		if (delta <= lineChangeModifiedLength) {
			return originalEquivalentLineNumber + Math.min(delta, lineChangeOriginalLength);
		}

J
Johannes Rieken 已提交
1338
		return originalEquivalentLineNumber + lineChangeOriginalLength - lineChangeModifiedLength + delta;
E
Erich Gamma 已提交
1339 1340
	}

A
Alex Dima 已提交
1341
	public getDiffLineInformationForOriginal(lineNumber: number): editorBrowser.IDiffLineInformation | null {
A
Alex Dima 已提交
1342
		if (!this._diffComputationResult) {
E
Erich Gamma 已提交
1343 1344 1345 1346 1347 1348 1349 1350
			// Cannot answer that which I don't know
			return null;
		}
		return {
			equivalentLineNumber: this._getEquivalentLineForOriginalLineNumber(lineNumber)
		};
	}

A
Alex Dima 已提交
1351
	public getDiffLineInformationForModified(lineNumber: number): editorBrowser.IDiffLineInformation | null {
A
Alex Dima 已提交
1352
		if (!this._diffComputationResult) {
E
Erich Gamma 已提交
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
			// Cannot answer that which I don't know
			return null;
		}
		return {
			equivalentLineNumber: this._getEquivalentLineForModifiedLineNumber(lineNumber)
		};
	}
}

interface IDataSource {
	getWidth(): number;
	getHeight(): number;
	getContainerDomNode(): HTMLElement;
	relayoutEditors(): void;

A
Alex Dima 已提交
1368 1369
	getOriginalEditor(): CodeEditorWidget;
	getModifiedEditor(): CodeEditorWidget;
E
Erich Gamma 已提交
1370 1371
}

A
Alex Dima 已提交
1372
abstract class DiffEditorWidgetStyle extends Disposable {
E
Erich Gamma 已提交
1373

A
Renames  
Alex Dima 已提交
1374 1375 1376
	protected _dataSource: IDataSource;
	protected _insertColor: Color | null;
	protected _removeColor: Color | null;
E
Erich Gamma 已提交
1377

J
Johannes Rieken 已提交
1378
	constructor(dataSource: IDataSource) {
A
Alex Dima 已提交
1379
		super();
E
Erich Gamma 已提交
1380
		this._dataSource = dataSource;
A
Alex Dima 已提交
1381 1382
		this._insertColor = null;
		this._removeColor = null;
E
Erich Gamma 已提交
1383 1384
	}

M
Martin Aeschlimann 已提交
1385
	public applyColors(theme: IColorTheme): boolean {
A
Alex Dima 已提交
1386 1387 1388
		const newInsertColor = (theme.getColor(diffInserted) || defaultInsertColor).transparent(2);
		const newRemoveColor = (theme.getColor(diffRemoved) || defaultRemoveColor).transparent(2);
		const hasChanges = !newInsertColor.equals(this._insertColor) || !newRemoveColor.equals(this._removeColor);
1389 1390 1391 1392 1393
		this._insertColor = newInsertColor;
		this._removeColor = newRemoveColor;
		return hasChanges;
	}

A
Alex Dima 已提交
1394
	public getEditorsDiffDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, renderIndicators: boolean, originalWhitespaces: IEditorWhitespace[], modifiedWhitespaces: IEditorWhitespace[]): IEditorsDiffDecorationsWithZones {
E
Erich Gamma 已提交
1395 1396 1397 1398 1399 1400 1401
		// Get view zones
		modifiedWhitespaces = modifiedWhitespaces.sort((a, b) => {
			return a.afterLineNumber - b.afterLineNumber;
		});
		originalWhitespaces = originalWhitespaces.sort((a, b) => {
			return a.afterLineNumber - b.afterLineNumber;
		});
A
Alex Dima 已提交
1402
		const zones = this._getViewZones(lineChanges, originalWhitespaces, modifiedWhitespaces, renderIndicators);
E
Erich Gamma 已提交
1403 1404

		// Get decorations & overview ruler zones
A
Alex Dima 已提交
1405 1406
		const originalDecorations = this._getOriginalEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators);
		const modifiedDecorations = this._getModifiedEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators);
E
Erich Gamma 已提交
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421

		return {
			original: {
				decorations: originalDecorations.decorations,
				overviewZones: originalDecorations.overviewZones,
				zones: zones.original
			},
			modified: {
				decorations: modifiedDecorations.decorations,
				overviewZones: modifiedDecorations.overviewZones,
				zones: zones.modified
			}
		};
	}

A
Alex Dima 已提交
1422 1423 1424
	protected abstract _getViewZones(lineChanges: editorCommon.ILineChange[], originalForeignVZ: IEditorWhitespace[], modifiedForeignVZ: IEditorWhitespace[], renderIndicators: boolean): IEditorsZones;
	protected abstract _getOriginalEditorDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, renderIndicators: boolean): IEditorDiffDecorations;
	protected abstract _getModifiedEditorDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, renderIndicators: boolean): IEditorDiffDecorations;
A
Alex Dima 已提交
1425 1426 1427

	public abstract setEnableSplitViewResizing(enableSplitViewResizing: boolean): void;
	public abstract layout(): number;
E
Erich Gamma 已提交
1428 1429
}

A
Alex Dima 已提交
1430
interface IMyViewZone {
E
Erich Gamma 已提交
1431
	shouldNotShrink?: boolean;
A
Alex Dima 已提交
1432
	afterLineNumber: number;
1433
	afterColumn?: number;
A
Alex Dima 已提交
1434 1435 1436 1437
	heightInLines: number;
	minWidthInPx?: number;
	domNode: HTMLElement | null;
	marginDomNode?: HTMLElement | null;
1438
	diff?: IDiffLinesChange;
E
Erich Gamma 已提交
1439 1440 1441 1442 1443
}

class ForeignViewZonesIterator {

	private _index: number;
1444
	private readonly _source: IEditorWhitespace[];
A
Alex Dima 已提交
1445
	public current: IEditorWhitespace | null;
E
Erich Gamma 已提交
1446

A
Alex Dima 已提交
1447
	constructor(source: IEditorWhitespace[]) {
E
Erich Gamma 已提交
1448 1449
		this._source = source;
		this._index = -1;
A
Alex Dima 已提交
1450
		this.current = null;
E
Erich Gamma 已提交
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
		this.advance();
	}

	public advance(): void {
		this._index++;
		if (this._index < this._source.length) {
			this.current = this._source[this._index];
		} else {
			this.current = null;
		}
	}
}

1464
abstract class ViewZonesComputer {
E
Erich Gamma 已提交
1465

A
Alex Dima 已提交
1466
	constructor(
1467 1468 1469
		private readonly _lineChanges: editorCommon.ILineChange[],
		private readonly _originalForeignVZ: IEditorWhitespace[],
		private readonly _modifiedForeignVZ: IEditorWhitespace[],
A
Alex Dima 已提交
1470 1471
		protected readonly _originalEditor: CodeEditorWidget,
		protected readonly _modifiedEditor: CodeEditorWidget
A
Alex Dima 已提交
1472
	) {
1473 1474 1475 1476 1477 1478 1479 1480 1481
	}

	private static _getViewLineCount(editor: CodeEditorWidget, startLineNumber: number, endLineNumber: number): number {
		const model = editor.getModel();
		const viewModel = editor._getViewModel();
		if (model && viewModel) {
			const viewRange = getViewRange(model, viewModel, startLineNumber, endLineNumber);
			return (viewRange.endLineNumber - viewRange.startLineNumber + 1);
		}
E
Erich Gamma 已提交
1482

1483
		return (endLineNumber - startLineNumber + 1);
E
Erich Gamma 已提交
1484 1485 1486
	}

	public getViewZones(): IEditorsZones {
1487 1488
		const originalLineHeight = this._originalEditor.getOption(EditorOption.lineHeight);
		const modifiedLineHeight = this._modifiedEditor.getOption(EditorOption.lineHeight);
1489
		const originalHasWrapping = (this._originalEditor.getOption(EditorOption.wrappingInfo).wrappingColumn !== -1);
1490
		const modifiedHasWrapping = (this._modifiedEditor.getOption(EditorOption.wrappingInfo).wrappingColumn !== -1);
1491 1492 1493 1494 1495
		const hasWrapping = (originalHasWrapping || modifiedHasWrapping);
		const originalModel = this._originalEditor.getModel()!;
		const originalCoordinatesConverter = this._originalEditor._getViewModel()!.coordinatesConverter;
		const modifiedCoordinatesConverter = this._modifiedEditor._getViewModel()!.coordinatesConverter;

A
Alex Dima 已提交
1496
		const result: { original: IMyViewZone[]; modified: IMyViewZone[]; } = {
E
Erich Gamma 已提交
1497 1498 1499 1500
			original: [],
			modified: []
		};

A
Alex Dima 已提交
1501 1502 1503 1504 1505 1506 1507
		let lineChangeModifiedLength: number = 0;
		let lineChangeOriginalLength: number = 0;
		let originalEquivalentLineNumber: number = 0;
		let modifiedEquivalentLineNumber: number = 0;
		let originalEndEquivalentLineNumber: number = 0;
		let modifiedEndEquivalentLineNumber: number = 0;

A
Alex Dima 已提交
1508
		const sortMyViewZones = (a: IMyViewZone, b: IMyViewZone) => {
E
Erich Gamma 已提交
1509 1510 1511
			return a.afterLineNumber - b.afterLineNumber;
		};

A
Alex Dima 已提交
1512
		const addAndCombineIfPossible = (destination: IMyViewZone[], item: IMyViewZone) => {
E
Erich Gamma 已提交
1513
			if (item.domNode === null && destination.length > 0) {
A
Alex Dima 已提交
1514
				const lastItem = destination[destination.length - 1];
E
Erich Gamma 已提交
1515 1516 1517 1518 1519 1520 1521 1522
				if (lastItem.afterLineNumber === item.afterLineNumber && lastItem.domNode === null) {
					lastItem.heightInLines += item.heightInLines;
					return;
				}
			}
			destination.push(item);
		};

A
Alex Dima 已提交
1523 1524
		const modifiedForeignVZ = new ForeignViewZonesIterator(this._modifiedForeignVZ);
		const originalForeignVZ = new ForeignViewZonesIterator(this._originalForeignVZ);
E
Erich Gamma 已提交
1525

1526 1527
		let lastOriginalLineNumber = 1;
		let lastModifiedLineNumber = 1;
E
Erich Gamma 已提交
1528 1529

		// In order to include foreign view zones after the last line change, the for loop will iterate once more after the end of the `lineChanges` array
A
Renames  
Alex Dima 已提交
1530
		for (let i = 0, length = this._lineChanges.length; i <= length; i++) {
A
Alex Dima 已提交
1531
			const lineChange = (i < length ? this._lineChanges[i] : null);
E
Erich Gamma 已提交
1532 1533 1534 1535

			if (lineChange !== null) {
				originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0);
				modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0);
1536 1537
				lineChangeOriginalLength = (lineChange.originalEndLineNumber > 0 ? ViewZonesComputer._getViewLineCount(this._originalEditor, lineChange.originalStartLineNumber, lineChange.originalEndLineNumber) : 0);
				lineChangeModifiedLength = (lineChange.modifiedEndLineNumber > 0 ? ViewZonesComputer._getViewLineCount(this._modifiedEditor, lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber) : 0);
E
Erich Gamma 已提交
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
				originalEndEquivalentLineNumber = Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber);
				modifiedEndEquivalentLineNumber = Math.max(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber);
			} else {
				// Increase to very large value to get the producing tests of foreign view zones running
				originalEquivalentLineNumber += 10000000 + lineChangeOriginalLength;
				modifiedEquivalentLineNumber += 10000000 + lineChangeModifiedLength;
				originalEndEquivalentLineNumber = originalEquivalentLineNumber;
				modifiedEndEquivalentLineNumber = modifiedEquivalentLineNumber;
			}

			// Each step produces view zones, and after producing them, we try to cancel them out, to avoid empty-empty view zone cases
A
Alex Dima 已提交
1549 1550
			let stepOriginal: IMyViewZone[] = [];
			let stepModified: IMyViewZone[] = [];
E
Erich Gamma 已提交
1551 1552 1553

			// ---------------------------- PRODUCE VIEW ZONES

1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
			// [PRODUCE] View zones due to line mapping differences (equal lines but wrapped differently)
			if (hasWrapping) {
				let count: number;
				if (lineChange) {
					if (lineChange.originalEndLineNumber > 0) {
						count = lineChange.originalStartLineNumber - lastOriginalLineNumber;
					} else {
						count = lineChange.modifiedStartLineNumber - lastModifiedLineNumber;
					}
				} else {
					count = originalModel.getLineCount() - lastOriginalLineNumber;
				}

				for (let i = 0; i < count; i++) {
					const originalLineNumber = lastOriginalLineNumber + i;
					const modifiedLineNumber = lastModifiedLineNumber + i;

					const originalViewLineCount = originalCoordinatesConverter.getModelLineViewLineCount(originalLineNumber);
					const modifiedViewLineCount = modifiedCoordinatesConverter.getModelLineViewLineCount(modifiedLineNumber);

					if (originalViewLineCount < modifiedViewLineCount) {
						stepOriginal.push({
							afterLineNumber: originalLineNumber,
							heightInLines: modifiedViewLineCount - originalViewLineCount,
							domNode: null,
							marginDomNode: null
						});
					} else if (originalViewLineCount > modifiedViewLineCount) {
						stepModified.push({
							afterLineNumber: modifiedLineNumber,
							heightInLines: originalViewLineCount - modifiedViewLineCount,
							domNode: null,
							marginDomNode: null
						});
					}
				}
				if (lineChange) {
					lastOriginalLineNumber = (lineChange.originalEndLineNumber > 0 ? lineChange.originalEndLineNumber : lineChange.originalStartLineNumber) + 1;
					lastModifiedLineNumber = (lineChange.modifiedEndLineNumber > 0 ? lineChange.modifiedEndLineNumber : lineChange.modifiedStartLineNumber) + 1;
				}
			}

E
Erich Gamma 已提交
1596 1597
			// [PRODUCE] View zone(s) in original-side due to foreign view zone(s) in modified-side
			while (modifiedForeignVZ.current && modifiedForeignVZ.current.afterLineNumber <= modifiedEndEquivalentLineNumber) {
A
Alex Dima 已提交
1598
				let viewZoneLineNumber: number;
E
Erich Gamma 已提交
1599 1600 1601 1602 1603
				if (modifiedForeignVZ.current.afterLineNumber <= modifiedEquivalentLineNumber) {
					viewZoneLineNumber = originalEquivalentLineNumber - modifiedEquivalentLineNumber + modifiedForeignVZ.current.afterLineNumber;
				} else {
					viewZoneLineNumber = originalEndEquivalentLineNumber;
				}
A
Alex Dima 已提交
1604

1605
				let marginDomNode: HTMLDivElement | null = null;
A
Alex Dima 已提交
1606 1607 1608 1609
				if (lineChange && lineChange.modifiedStartLineNumber <= modifiedForeignVZ.current.afterLineNumber && modifiedForeignVZ.current.afterLineNumber <= lineChange.modifiedEndLineNumber) {
					marginDomNode = this._createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion();
				}

E
Erich Gamma 已提交
1610 1611
				stepOriginal.push({
					afterLineNumber: viewZoneLineNumber,
1612
					heightInLines: modifiedForeignVZ.current.height / modifiedLineHeight,
A
Alex Dima 已提交
1613 1614
					domNode: null,
					marginDomNode: marginDomNode
E
Erich Gamma 已提交
1615 1616 1617 1618 1619 1620
				});
				modifiedForeignVZ.advance();
			}

			// [PRODUCE] View zone(s) in modified-side due to foreign view zone(s) in original-side
			while (originalForeignVZ.current && originalForeignVZ.current.afterLineNumber <= originalEndEquivalentLineNumber) {
A
Alex Dima 已提交
1621
				let viewZoneLineNumber: number;
E
Erich Gamma 已提交
1622 1623 1624 1625 1626 1627 1628
				if (originalForeignVZ.current.afterLineNumber <= originalEquivalentLineNumber) {
					viewZoneLineNumber = modifiedEquivalentLineNumber - originalEquivalentLineNumber + originalForeignVZ.current.afterLineNumber;
				} else {
					viewZoneLineNumber = modifiedEndEquivalentLineNumber;
				}
				stepModified.push({
					afterLineNumber: viewZoneLineNumber,
1629
					heightInLines: originalForeignVZ.current.height / originalLineHeight,
E
Erich Gamma 已提交
1630 1631 1632 1633 1634 1635
					domNode: null
				});
				originalForeignVZ.advance();
			}

			if (lineChange !== null && isChangeOrInsert(lineChange)) {
A
Alex Dima 已提交
1636
				const r = this._produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength);
E
Erich Gamma 已提交
1637 1638 1639 1640 1641 1642
				if (r) {
					stepOriginal.push(r);
				}
			}

			if (lineChange !== null && isChangeOrDelete(lineChange)) {
A
Alex Dima 已提交
1643
				const r = this._produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength);
E
Erich Gamma 已提交
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
				if (r) {
					stepModified.push(r);
				}
			}

			// ---------------------------- END PRODUCE VIEW ZONES


			// ---------------------------- EMIT MINIMAL VIEW ZONES

			// [CANCEL & EMIT] Try to cancel view zones out
A
Alex Dima 已提交
1655 1656
			let stepOriginalIndex = 0;
			let stepModifiedIndex = 0;
E
Erich Gamma 已提交
1657 1658 1659 1660 1661

			stepOriginal = stepOriginal.sort(sortMyViewZones);
			stepModified = stepModified.sort(sortMyViewZones);

			while (stepOriginalIndex < stepOriginal.length && stepModifiedIndex < stepModified.length) {
A
Alex Dima 已提交
1662 1663
				const original = stepOriginal[stepOriginalIndex];
				const modified = stepModified[stepModifiedIndex];
E
Erich Gamma 已提交
1664

A
Alex Dima 已提交
1665 1666
				const originalDelta = original.afterLineNumber - originalEquivalentLineNumber;
				const modifiedDelta = modified.afterLineNumber - modifiedEquivalentLineNumber;
E
Erich Gamma 已提交
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707

				if (originalDelta < modifiedDelta) {
					addAndCombineIfPossible(result.original, original);
					stepOriginalIndex++;
				} else if (modifiedDelta < originalDelta) {
					addAndCombineIfPossible(result.modified, modified);
					stepModifiedIndex++;
				} else if (original.shouldNotShrink) {
					addAndCombineIfPossible(result.original, original);
					stepOriginalIndex++;
				} else if (modified.shouldNotShrink) {
					addAndCombineIfPossible(result.modified, modified);
					stepModifiedIndex++;
				} else {
					if (original.heightInLines >= modified.heightInLines) {
						// modified view zone gets removed
						original.heightInLines -= modified.heightInLines;
						stepModifiedIndex++;
					} else {
						// original view zone gets removed
						modified.heightInLines -= original.heightInLines;
						stepOriginalIndex++;
					}
				}
			}

			// [EMIT] Remaining original view zones
			while (stepOriginalIndex < stepOriginal.length) {
				addAndCombineIfPossible(result.original, stepOriginal[stepOriginalIndex]);
				stepOriginalIndex++;
			}

			// [EMIT] Remaining modified view zones
			while (stepModifiedIndex < stepModified.length) {
				addAndCombineIfPossible(result.modified, stepModified[stepModifiedIndex]);
				stepModifiedIndex++;
			}

			// ---------------------------- END EMIT MINIMAL VIEW ZONES
		}

A
Alex Dima 已提交
1708 1709 1710 1711 1712 1713
		return {
			original: ViewZonesComputer._ensureDomNodes(result.original),
			modified: ViewZonesComputer._ensureDomNodes(result.modified),
		};
	}

1714
	private static _ensureDomNodes(zones: IMyViewZone[]): IMyViewZone[] {
A
Alex Dima 已提交
1715
		return zones.map((z) => {
E
Erich Gamma 已提交
1716 1717 1718
			if (!z.domNode) {
				z.domNode = createFakeLinesDiv();
			}
1719
			return z;
A
Alex Dima 已提交
1720
		});
E
Erich Gamma 已提交
1721 1722
	}

A
Alex Dima 已提交
1723
	protected abstract _createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion(): HTMLDivElement | null;
A
Alex Dima 已提交
1724

A
Alex Dima 已提交
1725
	protected abstract _produceOriginalFromDiff(lineChange: editorCommon.ILineChange, lineChangeOriginalLength: number, lineChangeModifiedLength: number): IMyViewZone | null;
E
Erich Gamma 已提交
1726

A
Alex Dima 已提交
1727
	protected abstract _produceModifiedFromDiff(lineChange: editorCommon.ILineChange, lineChangeOriginalLength: number, lineChangeModifiedLength: number): IMyViewZone | null;
E
Erich Gamma 已提交
1728 1729
}

A
Renames  
Alex Dima 已提交
1730
function createDecoration(startLineNumber: number, startColumn: number, endLineNumber: number, endColumn: number, options: ModelDecorationOptions) {
1731 1732 1733 1734 1735 1736
	return {
		range: new Range(startLineNumber, startColumn, endLineNumber, endColumn),
		options: options
	};
}

A
Renames  
Alex Dima 已提交
1737
const DECORATIONS = {
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761

	charDelete: ModelDecorationOptions.register({
		className: 'char-delete'
	}),
	charDeleteWholeLine: ModelDecorationOptions.register({
		className: 'char-delete',
		isWholeLine: true
	}),

	charInsert: ModelDecorationOptions.register({
		className: 'char-insert'
	}),
	charInsertWholeLine: ModelDecorationOptions.register({
		className: 'char-insert',
		isWholeLine: true
	}),

	lineInsert: ModelDecorationOptions.register({
		className: 'line-insert',
		marginClassName: 'line-insert',
		isWholeLine: true
	}),
	lineInsertWithSign: ModelDecorationOptions.register({
		className: 'line-insert',
M
Martin Aeschlimann 已提交
1762
		linesDecorationsClassName: 'insert-sign ' + diffInsertIcon.classNames,
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
		marginClassName: 'line-insert',
		isWholeLine: true
	}),

	lineDelete: ModelDecorationOptions.register({
		className: 'line-delete',
		marginClassName: 'line-delete',
		isWholeLine: true
	}),
	lineDeleteWithSign: ModelDecorationOptions.register({
		className: 'line-delete',
M
Martin Aeschlimann 已提交
1774
		linesDecorationsClassName: 'delete-sign ' + diffRemoveIcon.classNames,
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
		marginClassName: 'line-delete',
		isWholeLine: true

	}),
	lineDeleteMargin: ModelDecorationOptions.register({
		marginClassName: 'line-delete',
	})

};

A
Alex Dima 已提交
1785
class DiffEditorWidgetSideBySide extends DiffEditorWidgetStyle implements IVerticalSashLayoutProvider {
E
Erich Gamma 已提交
1786

1787
	static readonly MINIMUM_EDITOR_WIDTH = 100;
E
Erich Gamma 已提交
1788 1789

	private _disableSash: boolean;
1790
	private readonly _sash: Sash;
A
Alex Dima 已提交
1791 1792
	private _sashRatio: number | null;
	private _sashPosition: number | null;
A
Alex Dima 已提交
1793
	private _startSashPosition: number | null;
E
Erich Gamma 已提交
1794

J
Johannes Rieken 已提交
1795
	constructor(dataSource: IDataSource, enableSplitViewResizing: boolean) {
E
Erich Gamma 已提交
1796 1797 1798 1799 1800
		super(dataSource);

		this._disableSash = (enableSplitViewResizing === false);
		this._sashRatio = null;
		this._sashPosition = null;
A
Alex Dima 已提交
1801
		this._startSashPosition = null;
J
João Moreno 已提交
1802
		this._sash = this._register(new Sash(this._dataSource.getContainerDomNode(), this, { orientation: Orientation.VERTICAL }));
E
Erich Gamma 已提交
1803 1804

		if (this._disableSash) {
J
Joao Moreno 已提交
1805
			this._sash.state = SashState.Disabled;
E
Erich Gamma 已提交
1806 1807
		}

A
Renames  
Alex Dima 已提交
1808 1809 1810 1811
		this._sash.onDidStart(() => this._onSashDragStart());
		this._sash.onDidChange((e: ISashEvent) => this._onSashDrag(e));
		this._sash.onDidEnd(() => this._onSashDragEnd());
		this._sash.onDidReset(() => this._onSashReset());
E
Erich Gamma 已提交
1812 1813
	}

J
Johannes Rieken 已提交
1814
	public setEnableSplitViewResizing(enableSplitViewResizing: boolean): void {
A
Alex Dima 已提交
1815
		const newDisableSash = (enableSplitViewResizing === false);
E
Erich Gamma 已提交
1816 1817
		if (this._disableSash !== newDisableSash) {
			this._disableSash = newDisableSash;
J
Joao Moreno 已提交
1818
			this._sash.state = this._disableSash ? SashState.Disabled : SashState.Enabled;
E
Erich Gamma 已提交
1819 1820 1821
		}
	}

A
Alex Dima 已提交
1822
	public layout(sashRatio: number | null = this._sashRatio): number {
A
Alex Dima 已提交
1823 1824
		const w = this._dataSource.getWidth();
		const contentWidth = w - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH;
E
Erich Gamma 已提交
1825

A
Alex Dima 已提交
1826
		let sashPosition = Math.floor((sashRatio || 0.5) * contentWidth);
A
Alex Dima 已提交
1827
		const midPoint = Math.floor(0.5 * contentWidth);
E
Erich Gamma 已提交
1828

A
Alex Dima 已提交
1829
		sashPosition = this._disableSash ? midPoint : sashPosition || midPoint;
E
Erich Gamma 已提交
1830

H
Howard Hung 已提交
1831 1832 1833
		if (contentWidth > DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH * 2) {
			if (sashPosition < DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) {
				sashPosition = DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH;
E
Erich Gamma 已提交
1834 1835
			}

H
Howard Hung 已提交
1836 1837
			if (sashPosition > contentWidth - DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) {
				sashPosition = contentWidth - DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH;
E
Erich Gamma 已提交
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
			}
		} else {
			sashPosition = midPoint;
		}

		if (this._sashPosition !== sashPosition) {
			this._sashPosition = sashPosition;
			this._sash.layout();
		}

		return this._sashPosition;
	}

A
Renames  
Alex Dima 已提交
1851
	private _onSashDragStart(): void {
A
Alex Dima 已提交
1852
		this._startSashPosition = this._sashPosition!;
E
Erich Gamma 已提交
1853 1854
	}

A
Renames  
Alex Dima 已提交
1855
	private _onSashDrag(e: ISashEvent): void {
A
Alex Dima 已提交
1856 1857 1858
		const w = this._dataSource.getWidth();
		const contentWidth = w - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH;
		const sashPosition = this.layout((this._startSashPosition! + (e.currentX - e.startX)) / contentWidth);
E
Erich Gamma 已提交
1859 1860 1861 1862 1863 1864

		this._sashRatio = sashPosition / contentWidth;

		this._dataSource.relayoutEditors();
	}

A
Renames  
Alex Dima 已提交
1865
	private _onSashDragEnd(): void {
M
Maxime Quandalle 已提交
1866 1867 1868
		this._sash.layout();
	}

A
Renames  
Alex Dima 已提交
1869
	private _onSashReset(): void {
M
Maxime Quandalle 已提交
1870 1871
		this._sashRatio = 0.5;
		this._dataSource.relayoutEditors();
E
Erich Gamma 已提交
1872 1873 1874
		this._sash.layout();
	}

A
Alex Dima 已提交
1875
	public getVerticalSashTop(sash: Sash): number {
E
Erich Gamma 已提交
1876 1877 1878
		return 0;
	}

A
Alex Dima 已提交
1879
	public getVerticalSashLeft(sash: Sash): number {
A
Alex Dima 已提交
1880
		return this._sashPosition!;
E
Erich Gamma 已提交
1881 1882
	}

A
Alex Dima 已提交
1883
	public getVerticalSashHeight(sash: Sash): number {
E
Erich Gamma 已提交
1884 1885 1886
		return this._dataSource.getHeight();
	}

A
Alex Dima 已提交
1887 1888 1889 1890
	protected _getViewZones(lineChanges: editorCommon.ILineChange[], originalForeignVZ: IEditorWhitespace[], modifiedForeignVZ: IEditorWhitespace[]): IEditorsZones {
		const originalEditor = this._dataSource.getOriginalEditor();
		const modifiedEditor = this._dataSource.getModifiedEditor();
		const c = new SideBySideViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor);
E
Erich Gamma 已提交
1891 1892 1893
		return c.getViewZones();
	}

A
Alex Dima 已提交
1894 1895
	protected _getOriginalEditorDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, renderIndicators: boolean): IEditorDiffDecorations {
		const originalEditor = this._dataSource.getOriginalEditor();
A
Alex Dima 已提交
1896
		const overviewZoneColor = String(this._removeColor);
E
Erich Gamma 已提交
1897

A
Alex Dima 已提交
1898
		const result: IEditorDiffDecorations = {
J
Johannes Rieken 已提交
1899 1900
			decorations: [],
			overviewZones: []
P
Peng Lyu 已提交
1901
		};
A
Alex Dima 已提交
1902

A
Alex Dima 已提交
1903
		const originalModel = originalEditor.getModel()!;
1904
		const originalViewModel = originalEditor._getViewModel()!;
A
Alex Dima 已提交
1905

A
Alex Dima 已提交
1906
		for (const lineChange of lineChanges) {
E
Erich Gamma 已提交
1907 1908

			if (isChangeOrDelete(lineChange)) {
1909
				result.decorations.push({
1910
					range: new Range(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, Constants.MAX_SAFE_SMALL_INTEGER),
1911
					options: (renderIndicators ? DECORATIONS.lineDeleteWithSign : DECORATIONS.lineDelete)
1912
				});
E
Erich Gamma 已提交
1913
				if (!isChangeOrInsert(lineChange) || !lineChange.charChanges) {
1914
					result.decorations.push(createDecoration(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, Constants.MAX_SAFE_SMALL_INTEGER, DECORATIONS.charDeleteWholeLine));
E
Erich Gamma 已提交
1915 1916
				}

1917 1918
				const viewRange = getViewRange(originalModel, originalViewModel, lineChange.originalStartLineNumber, lineChange.originalEndLineNumber);
				result.overviewZones.push(new OverviewRulerZone(viewRange.startLineNumber, viewRange.endLineNumber, overviewZoneColor));
E
Erich Gamma 已提交
1919 1920

				if (lineChange.charChanges) {
A
Alex Dima 已提交
1921
					for (const charChange of lineChange.charChanges) {
E
Erich Gamma 已提交
1922 1923
						if (isChangeOrDelete(charChange)) {
							if (ignoreTrimWhitespace) {
A
Alex Dima 已提交
1924 1925 1926
								for (let lineNumber = charChange.originalStartLineNumber; lineNumber <= charChange.originalEndLineNumber; lineNumber++) {
									let startColumn: number;
									let endColumn: number;
E
Erich Gamma 已提交
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
									if (lineNumber === charChange.originalStartLineNumber) {
										startColumn = charChange.originalStartColumn;
									} else {
										startColumn = originalModel.getLineFirstNonWhitespaceColumn(lineNumber);
									}
									if (lineNumber === charChange.originalEndLineNumber) {
										endColumn = charChange.originalEndColumn;
									} else {
										endColumn = originalModel.getLineLastNonWhitespaceColumn(lineNumber);
									}
1937
									result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charDelete));
E
Erich Gamma 已提交
1938 1939
								}
							} else {
1940
								result.decorations.push(createDecoration(charChange.originalStartLineNumber, charChange.originalStartColumn, charChange.originalEndLineNumber, charChange.originalEndColumn, DECORATIONS.charDelete));
E
Erich Gamma 已提交
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
							}
						}
					}
				}
			}
		}

		return result;
	}

A
Alex Dima 已提交
1951 1952
	protected _getModifiedEditorDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, renderIndicators: boolean): IEditorDiffDecorations {
		const modifiedEditor = this._dataSource.getModifiedEditor();
A
Alex Dima 已提交
1953
		const overviewZoneColor = String(this._insertColor);
E
Erich Gamma 已提交
1954

A
Alex Dima 已提交
1955
		const result: IEditorDiffDecorations = {
J
Johannes Rieken 已提交
1956 1957
			decorations: [],
			overviewZones: []
A
Alex Dima 已提交
1958 1959
		};

A
Alex Dima 已提交
1960
		const modifiedModel = modifiedEditor.getModel()!;
1961
		const modifiedViewModel = modifiedEditor._getViewModel()!;
A
Alex Dima 已提交
1962

A
Alex Dima 已提交
1963
		for (const lineChange of lineChanges) {
E
Erich Gamma 已提交
1964 1965 1966

			if (isChangeOrInsert(lineChange)) {

1967
				result.decorations.push({
1968
					range: new Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, Constants.MAX_SAFE_SMALL_INTEGER),
1969
					options: (renderIndicators ? DECORATIONS.lineInsertWithSign : DECORATIONS.lineInsert)
1970
				});
E
Erich Gamma 已提交
1971
				if (!isChangeOrDelete(lineChange) || !lineChange.charChanges) {
1972
					result.decorations.push(createDecoration(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, Constants.MAX_SAFE_SMALL_INTEGER, DECORATIONS.charInsertWholeLine));
E
Erich Gamma 已提交
1973
				}
1974 1975 1976

				const viewRange = getViewRange(modifiedModel, modifiedViewModel, lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber);
				result.overviewZones.push(new OverviewRulerZone(viewRange.startLineNumber, viewRange.endLineNumber, overviewZoneColor));
E
Erich Gamma 已提交
1977 1978

				if (lineChange.charChanges) {
A
Alex Dima 已提交
1979
					for (const charChange of lineChange.charChanges) {
E
Erich Gamma 已提交
1980 1981
						if (isChangeOrInsert(charChange)) {
							if (ignoreTrimWhitespace) {
A
Alex Dima 已提交
1982 1983 1984
								for (let lineNumber = charChange.modifiedStartLineNumber; lineNumber <= charChange.modifiedEndLineNumber; lineNumber++) {
									let startColumn: number;
									let endColumn: number;
E
Erich Gamma 已提交
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
									if (lineNumber === charChange.modifiedStartLineNumber) {
										startColumn = charChange.modifiedStartColumn;
									} else {
										startColumn = modifiedModel.getLineFirstNonWhitespaceColumn(lineNumber);
									}
									if (lineNumber === charChange.modifiedEndLineNumber) {
										endColumn = charChange.modifiedEndColumn;
									} else {
										endColumn = modifiedModel.getLineLastNonWhitespaceColumn(lineNumber);
									}
1995
									result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charInsert));
E
Erich Gamma 已提交
1996 1997
								}
							} else {
1998
								result.decorations.push(createDecoration(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn, DECORATIONS.charInsert));
E
Erich Gamma 已提交
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
							}
						}
					}
				}

			}
		}
		return result;
	}
}

class SideBySideViewZonesComputer extends ViewZonesComputer {

A
Alex Dima 已提交
2012 2013 2014 2015 2016 2017 2018 2019
	constructor(
		lineChanges: editorCommon.ILineChange[],
		originalForeignVZ: IEditorWhitespace[],
		modifiedForeignVZ: IEditorWhitespace[],
		originalEditor: CodeEditorWidget,
		modifiedEditor: CodeEditorWidget,
	) {
		super(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor);
E
Erich Gamma 已提交
2020 2021
	}

A
Alex Dima 已提交
2022
	protected _createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion(): HTMLDivElement | null {
A
Alex Dima 已提交
2023 2024 2025
		return null;
	}

A
Alex Dima 已提交
2026
	protected _produceOriginalFromDiff(lineChange: editorCommon.ILineChange, lineChangeOriginalLength: number, lineChangeModifiedLength: number): IMyViewZone | null {
E
Erich Gamma 已提交
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
		if (lineChangeModifiedLength > lineChangeOriginalLength) {
			return {
				afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber),
				heightInLines: (lineChangeModifiedLength - lineChangeOriginalLength),
				domNode: null
			};
		}
		return null;
	}

A
Alex Dima 已提交
2037
	protected _produceModifiedFromDiff(lineChange: editorCommon.ILineChange, lineChangeOriginalLength: number, lineChangeModifiedLength: number): IMyViewZone | null {
E
Erich Gamma 已提交
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
		if (lineChangeOriginalLength > lineChangeModifiedLength) {
			return {
				afterLineNumber: Math.max(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber),
				heightInLines: (lineChangeOriginalLength - lineChangeModifiedLength),
				domNode: null
			};
		}
		return null;
	}
}

A
Alex Dima 已提交
2049
class DiffEditorWidgetInline extends DiffEditorWidgetStyle {
E
Erich Gamma 已提交
2050

A
Renames  
Alex Dima 已提交
2051
	private _decorationsLeft: number;
E
Erich Gamma 已提交
2052

J
Johannes Rieken 已提交
2053
	constructor(dataSource: IDataSource, enableSplitViewResizing: boolean) {
E
Erich Gamma 已提交
2054 2055
		super(dataSource);

A
Renames  
Alex Dima 已提交
2056
		this._decorationsLeft = dataSource.getOriginalEditor().getLayoutInfo().decorationsLeft;
E
Erich Gamma 已提交
2057

2058
		this._register(dataSource.getOriginalEditor().onDidLayoutChange((layoutInfo: EditorLayoutInfo) => {
A
Renames  
Alex Dima 已提交
2059 2060
			if (this._decorationsLeft !== layoutInfo.decorationsLeft) {
				this._decorationsLeft = layoutInfo.decorationsLeft;
E
Erich Gamma 已提交
2061 2062 2063 2064 2065
				dataSource.relayoutEditors();
			}
		}));
	}

J
Johannes Rieken 已提交
2066
	public setEnableSplitViewResizing(enableSplitViewResizing: boolean): void {
E
Erich Gamma 已提交
2067 2068 2069
		// Nothing to do..
	}

A
Alex Dima 已提交
2070 2071 2072
	protected _getViewZones(lineChanges: editorCommon.ILineChange[], originalForeignVZ: IEditorWhitespace[], modifiedForeignVZ: IEditorWhitespace[], renderIndicators: boolean): IEditorsZones {
		const originalEditor = this._dataSource.getOriginalEditor();
		const modifiedEditor = this._dataSource.getModifiedEditor();
A
Alex Dima 已提交
2073
		const computer = new InlineViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators);
E
Erich Gamma 已提交
2074 2075 2076
		return computer.getViewZones();
	}

A
Alex Dima 已提交
2077
	protected _getOriginalEditorDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, renderIndicators: boolean): IEditorDiffDecorations {
A
Alex Dima 已提交
2078
		const overviewZoneColor = String(this._removeColor);
A
Alex Dima 已提交
2079

A
Alex Dima 已提交
2080
		const result: IEditorDiffDecorations = {
J
Johannes Rieken 已提交
2081 2082
			decorations: [],
			overviewZones: []
A
Alex Dima 已提交
2083
		};
E
Erich Gamma 已提交
2084

2085 2086 2087 2088
		const originalEditor = this._dataSource.getOriginalEditor();
		const originalModel = originalEditor.getModel()!;
		const originalViewModel = originalEditor._getViewModel()!;

A
Alex Dima 已提交
2089
		for (const lineChange of lineChanges) {
E
Erich Gamma 已提交
2090 2091 2092

			// Add overview zones in the overview ruler
			if (isChangeOrDelete(lineChange)) {
2093
				result.decorations.push({
2094
					range: new Range(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, Constants.MAX_SAFE_SMALL_INTEGER),
2095
					options: DECORATIONS.lineDeleteMargin
2096 2097
				});

2098 2099
				const viewRange = getViewRange(originalModel, originalViewModel, lineChange.originalStartLineNumber, lineChange.originalEndLineNumber);
				result.overviewZones.push(new OverviewRulerZone(viewRange.startLineNumber, viewRange.endLineNumber, overviewZoneColor));
E
Erich Gamma 已提交
2100 2101 2102 2103 2104 2105
			}
		}

		return result;
	}

A
Alex Dima 已提交
2106 2107
	protected _getModifiedEditorDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, renderIndicators: boolean): IEditorDiffDecorations {
		const modifiedEditor = this._dataSource.getModifiedEditor();
A
Alex Dima 已提交
2108
		const overviewZoneColor = String(this._insertColor);
E
Erich Gamma 已提交
2109

A
Alex Dima 已提交
2110
		const result: IEditorDiffDecorations = {
J
Johannes Rieken 已提交
2111 2112
			decorations: [],
			overviewZones: []
A
Alex Dima 已提交
2113 2114
		};

A
Alex Dima 已提交
2115
		const modifiedModel = modifiedEditor.getModel()!;
2116
		const modifiedViewModel = modifiedEditor._getViewModel()!;
A
Alex Dima 已提交
2117

A
Alex Dima 已提交
2118
		for (const lineChange of lineChanges) {
E
Erich Gamma 已提交
2119 2120 2121

			// Add decorations & overview zones
			if (isChangeOrInsert(lineChange)) {
2122
				result.decorations.push({
2123
					range: new Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, Constants.MAX_SAFE_SMALL_INTEGER),
2124
					options: (renderIndicators ? DECORATIONS.lineInsertWithSign : DECORATIONS.lineInsert)
2125
				});
E
Erich Gamma 已提交
2126

2127 2128
				const viewRange = getViewRange(modifiedModel, modifiedViewModel, lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber);
				result.overviewZones.push(new OverviewRulerZone(viewRange.startLineNumber, viewRange.endLineNumber, overviewZoneColor));
E
Erich Gamma 已提交
2129 2130

				if (lineChange.charChanges) {
A
Alex Dima 已提交
2131
					for (const charChange of lineChange.charChanges) {
E
Erich Gamma 已提交
2132 2133
						if (isChangeOrInsert(charChange)) {
							if (ignoreTrimWhitespace) {
A
Alex Dima 已提交
2134 2135 2136
								for (let lineNumber = charChange.modifiedStartLineNumber; lineNumber <= charChange.modifiedEndLineNumber; lineNumber++) {
									let startColumn: number;
									let endColumn: number;
E
Erich Gamma 已提交
2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
									if (lineNumber === charChange.modifiedStartLineNumber) {
										startColumn = charChange.modifiedStartColumn;
									} else {
										startColumn = modifiedModel.getLineFirstNonWhitespaceColumn(lineNumber);
									}
									if (lineNumber === charChange.modifiedEndLineNumber) {
										endColumn = charChange.modifiedEndColumn;
									} else {
										endColumn = modifiedModel.getLineLastNonWhitespaceColumn(lineNumber);
									}
2147
									result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charInsert));
E
Erich Gamma 已提交
2148 2149
								}
							} else {
2150
								result.decorations.push(createDecoration(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn, DECORATIONS.charInsert));
E
Erich Gamma 已提交
2151 2152 2153 2154
							}
						}
					}
				} else {
2155
					result.decorations.push(createDecoration(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, Constants.MAX_SAFE_SMALL_INTEGER, DECORATIONS.charInsertWholeLine));
E
Erich Gamma 已提交
2156 2157 2158 2159 2160 2161 2162 2163 2164
				}
			}
		}

		return result;
	}

	public layout(): number {
		// An editor should not be smaller than 5px
A
Renames  
Alex Dima 已提交
2165
		return Math.max(5, this._decorationsLeft);
E
Erich Gamma 已提交
2166 2167 2168 2169
	}

}

A
Alex Dima 已提交
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
interface InlineModifiedViewZone extends IMyViewZone {
	shouldNotShrink: boolean;
	afterLineNumber: number;
	heightInLines: number;
	minWidthInPx: number;
	domNode: HTMLElement;
	marginDomNode: HTMLElement;
	diff: IDiffLinesChange;
}

E
Erich Gamma 已提交
2180 2181
class InlineViewZonesComputer extends ViewZonesComputer {

A
Renames  
Alex Dima 已提交
2182 2183
	private readonly _originalModel: ITextModel;
	private readonly _renderIndicators: boolean;
2184 2185 2186
	private readonly _pendingLineChange: editorCommon.ILineChange[];
	private readonly _pendingViewZones: InlineModifiedViewZone[];
	private readonly _lineBreaksComputer: ILineBreaksComputer;
E
Erich Gamma 已提交
2187

A
Alex Dima 已提交
2188 2189 2190 2191 2192 2193 2194 2195 2196
	constructor(
		lineChanges: editorCommon.ILineChange[],
		originalForeignVZ: IEditorWhitespace[],
		modifiedForeignVZ: IEditorWhitespace[],
		originalEditor: CodeEditorWidget,
		modifiedEditor: CodeEditorWidget,
		renderIndicators: boolean
	) {
		super(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor);
A
Renames  
Alex Dima 已提交
2197 2198
		this._originalModel = originalEditor.getModel()!;
		this._renderIndicators = renderIndicators;
2199 2200 2201
		this._pendingLineChange = [];
		this._pendingViewZones = [];
		this._lineBreaksComputer = this._modifiedEditor._getViewModel()!.createLineBreaksComputer();
E
Erich Gamma 已提交
2202 2203
	}

A
Alex Dima 已提交
2204 2205
	public getViewZones(): IEditorsZones {
		const result = super.getViewZones();
2206
		this._finalize(result);
A
Alex Dima 已提交
2207
		return result;
E
Erich Gamma 已提交
2208 2209
	}

A
Alex Dima 已提交
2210
	protected _createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion(): HTMLDivElement | null {
A
Alex Dima 已提交
2211
		const result = document.createElement('div');
A
Alex Dima 已提交
2212 2213 2214 2215
		result.className = 'inline-added-margin-view-zone';
		return result;
	}

A
Alex Dima 已提交
2216
	protected _produceOriginalFromDiff(lineChange: editorCommon.ILineChange, lineChangeOriginalLength: number, lineChangeModifiedLength: number): IMyViewZone | null {
A
Alex Dima 已提交
2217
		const marginDomNode = document.createElement('div');
2218 2219
		marginDomNode.className = 'inline-added-margin-view-zone';

E
Erich Gamma 已提交
2220
		return {
J
Johannes Rieken 已提交
2221
			afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber),
E
Erich Gamma 已提交
2222
			heightInLines: lineChangeModifiedLength,
2223 2224
			domNode: document.createElement('div'),
			marginDomNode: marginDomNode
E
Erich Gamma 已提交
2225 2226 2227
		};
	}

A
Alex Dima 已提交
2228
	protected _produceModifiedFromDiff(lineChange: editorCommon.ILineChange, lineChangeOriginalLength: number, lineChangeModifiedLength: number): IMyViewZone | null {
A
Alex Dima 已提交
2229
		const domNode = document.createElement('div');
2230
		domNode.className = `view-lines line-delete ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`;
E
Erich Gamma 已提交
2231

A
Alex Dima 已提交
2232
		const marginDomNode = document.createElement('div');
2233 2234
		marginDomNode.className = 'inline-deleted-margin-view-zone';

A
Alex Dima 已提交
2235
		const viewZone: InlineModifiedViewZone = {
E
Erich Gamma 已提交
2236 2237 2238
			shouldNotShrink: true,
			afterLineNumber: (lineChange.modifiedEndLineNumber === 0 ? lineChange.modifiedStartLineNumber : lineChange.modifiedStartLineNumber - 1),
			heightInLines: lineChangeOriginalLength,
A
Alex Dima 已提交
2239
			minWidthInPx: 0,
2240
			domNode: domNode,
2241 2242 2243 2244 2245 2246
			marginDomNode: marginDomNode,
			diff: {
				originalStartLineNumber: lineChange.originalStartLineNumber,
				originalEndLineNumber: lineChange.originalEndLineNumber,
				modifiedStartLineNumber: lineChange.modifiedStartLineNumber,
				modifiedEndLineNumber: lineChange.modifiedEndLineNumber,
2247 2248
				originalModel: this._originalModel,
				viewLineCounts: null,
2249
			}
E
Erich Gamma 已提交
2250
		};
A
Alex Dima 已提交
2251

2252 2253 2254 2255
		for (let lineNumber = lineChange.originalStartLineNumber; lineNumber <= lineChange.originalEndLineNumber; lineNumber++) {
			this._lineBreaksComputer.addRequest(this._originalModel.getLineContent(lineNumber), null);
		}

A
Alex Dima 已提交
2256 2257 2258 2259
		this._pendingLineChange.push(lineChange);
		this._pendingViewZones.push(viewZone);

		return viewZone;
E
Erich Gamma 已提交
2260 2261
	}

2262
	private _finalize(result: IEditorsZones): void {
A
Alex Dima 已提交
2263
		const modifiedEditorOptions = this._modifiedEditor.getOptions();
2264
		const tabSize = this._modifiedEditor.getModel()!.getOptions().tabSize;
A
Alex Dima 已提交
2265
		const fontInfo = modifiedEditorOptions.get(EditorOption.fontInfo);
2266
		const disableMonospaceOptimizations = modifiedEditorOptions.get(EditorOption.disableMonospaceOptimizations);
A
Alex Dima 已提交
2267 2268
		const typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
		const scrollBeyondLastColumn = modifiedEditorOptions.get(EditorOption.scrollBeyondLastColumn);
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
		const mightContainNonBasicASCII = this._originalModel.mightContainNonBasicASCII();
		const mightContainRTL = this._originalModel.mightContainRTL();
		const lineHeight = modifiedEditorOptions.get(EditorOption.lineHeight);
		const layoutInfo = modifiedEditorOptions.get(EditorOption.layoutInfo);
		const lineDecorationsWidth = layoutInfo.decorationsWidth;
		const stopRenderingLineAfter = modifiedEditorOptions.get(EditorOption.stopRenderingLineAfter);
		const renderWhitespace = modifiedEditorOptions.get(EditorOption.renderWhitespace);
		const renderControlCharacters = modifiedEditorOptions.get(EditorOption.renderControlCharacters);
		const fontLigatures = modifiedEditorOptions.get(EditorOption.fontLigatures);

		const lineBreaks = this._lineBreaksComputer.finalize();
		let lineBreakIndex = 0;
A
Alex Dima 已提交
2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302

		for (let i = 0; i < this._pendingLineChange.length; i++) {
			const lineChange = this._pendingLineChange[i];
			const viewZone = this._pendingViewZones[i];
			const domNode = viewZone.domNode;
			Configuration.applyFontInfoSlow(domNode, fontInfo);

			const marginDomNode = viewZone.marginDomNode;
			Configuration.applyFontInfoSlow(marginDomNode, fontInfo);

			const decorations: InlineDecoration[] = [];
			if (lineChange.charChanges) {
				for (const charChange of lineChange.charChanges) {
					if (isChangeOrDelete(charChange)) {
						decorations.push(new InlineDecoration(
							new Range(charChange.originalStartLineNumber, charChange.originalStartColumn, charChange.originalEndLineNumber, charChange.originalEndColumn),
							'char-delete',
							InlineDecorationType.Regular
						));
					}
				}
			}
2303
			const hasCharChanges = (decorations.length > 0);
A
Alex Dima 已提交
2304 2305 2306

			const sb = createStringBuilder(10000);
			let maxCharsPerLine = 0;
2307
			let renderedLineCount = 0;
2308
			let viewLineCounts: number[] | null = null;
A
Alex Dima 已提交
2309
			for (let lineNumber = lineChange.originalStartLineNumber; lineNumber <= lineChange.originalEndLineNumber; lineNumber++) {
2310
				const lineIndex = lineNumber - lineChange.originalStartLineNumber;
2311 2312 2313 2314 2315
				const lineTokens = this._originalModel.getLineTokens(lineNumber);
				const lineContent = lineTokens.getLineContent();
				const lineBreakData = lineBreaks[lineBreakIndex++];
				const actualDecorations = LineDecoration.filter(decorations, lineNumber, 1, lineContent.length + 1);

2316
				if (lineBreakData) {
2317 2318 2319 2320 2321 2322 2323 2324
					let lastBreakOffset = 0;
					for (const breakOffset of lineBreakData.breakOffsets) {
						const viewLineTokens = lineTokens.sliceAndInflate(lastBreakOffset, breakOffset, 0);
						const viewLineContent = lineContent.substring(lastBreakOffset, breakOffset);
						maxCharsPerLine = Math.max(maxCharsPerLine, this._renderOriginalLine(
							renderedLineCount++,
							viewLineContent,
							viewLineTokens,
2325 2326
							LineDecoration.extractWrapped(actualDecorations, lastBreakOffset, breakOffset),
							hasCharChanges,
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
							mightContainNonBasicASCII,
							mightContainRTL,
							fontInfo,
							disableMonospaceOptimizations,
							lineHeight,
							lineDecorationsWidth,
							stopRenderingLineAfter,
							renderWhitespace,
							renderControlCharacters,
							fontLigatures,
							tabSize,
							sb,
							marginDomNode
						));
						lastBreakOffset = breakOffset;
					}
2343 2344 2345 2346 2347 2348 2349 2350
					if (!viewLineCounts) {
						viewLineCounts = [];
					}
					// make sure all lines before this one have an entry in `viewLineCounts`
					while (viewLineCounts.length < lineIndex) {
						viewLineCounts[viewLineCounts.length] = 1;
					}
					viewLineCounts[lineIndex] = lineBreakData.breakOffsets.length;
2351
					viewZone.heightInLines += (lineBreakData.breakOffsets.length - 1);
2352 2353 2354 2355 2356 2357 2358 2359 2360
					const marginDomNode2 = document.createElement('div');
					marginDomNode2.className = 'line-delete';
					result.original.push({
						afterLineNumber: lineNumber,
						afterColumn: 0,
						heightInLines: lineBreakData.breakOffsets.length - 1,
						domNode: createFakeLinesDiv(),
						marginDomNode: marginDomNode2
					});
2361 2362 2363 2364 2365 2366
				} else {
					maxCharsPerLine = Math.max(maxCharsPerLine, this._renderOriginalLine(
						renderedLineCount++,
						lineContent,
						lineTokens,
						actualDecorations,
2367
						hasCharChanges,
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
						mightContainNonBasicASCII,
						mightContainRTL,
						fontInfo,
						disableMonospaceOptimizations,
						lineHeight,
						lineDecorationsWidth,
						stopRenderingLineAfter,
						renderWhitespace,
						renderControlCharacters,
						fontLigatures,
						tabSize,
						sb,
						marginDomNode
					));
A
Alex Dima 已提交
2382 2383 2384 2385 2386 2387
				}
			}
			maxCharsPerLine += scrollBeyondLastColumn;

			domNode.innerHTML = sb.build();
			viewZone.minWidthInPx = (maxCharsPerLine * typicalHalfwidthCharacterWidth);
2388 2389 2390 2391 2392 2393 2394 2395 2396

			if (viewLineCounts) {
				// make sure all lines have an entry in `viewLineCounts`
				const cnt = lineChange.originalEndLineNumber - lineChange.originalStartLineNumber;
				while (viewLineCounts.length <= cnt) {
					viewLineCounts[viewLineCounts.length] = 1;
				}
			}
			viewZone.diff.viewLineCounts = viewLineCounts;
A
Alex Dima 已提交
2397
		}
A
Alex Dima 已提交
2398

2399 2400 2401
		result.original.sort((a, b) => {
			return a.afterLineNumber - b.afterLineNumber;
		});
E
Erich Gamma 已提交
2402 2403
	}

2404 2405 2406 2407 2408
	private _renderOriginalLine(
		renderedLineCount: number,
		lineContent: string,
		lineTokens: IViewLineTokens,
		decorations: LineDecoration[],
2409
		hasCharChanges: boolean,
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
		mightContainNonBasicASCII: boolean,
		mightContainRTL: boolean,
		fontInfo: FontInfo,
		disableMonospaceOptimizations: boolean,
		lineHeight: number,
		lineDecorationsWidth: number,
		stopRenderingLineAfter: number,
		renderWhitespace: 'selection' | 'none' | 'boundary' | 'trailing' | 'all',
		renderControlCharacters: boolean,
		fontLigatures: string,
		tabSize: number,
		sb: IStringBuilder,
		marginDomNode: HTMLElement
	): number {
A
Alex Dima 已提交
2424

2425
		sb.appendASCIIString('<div class="view-line');
2426
		if (!hasCharChanges) {
2427 2428 2429 2430
			// No char changes
			sb.appendASCIIString(' char-delete');
		}
		sb.appendASCIIString('" style="top:');
2431
		sb.appendASCIIString(String(renderedLineCount * lineHeight));
2432 2433
		sb.appendASCIIString('px;width:1000000px;">');

2434 2435
		const isBasicASCII = ViewLineRenderingData.isBasicASCII(lineContent, mightContainNonBasicASCII);
		const containsRTL = ViewLineRenderingData.containsRTL(lineContent, isBasicASCII, mightContainRTL);
2436
		const output = renderViewLine(new RenderLineInput(
2437
			(fontInfo.isMonospace && !disableMonospaceOptimizations),
2438
			fontInfo.canUseHalfwidthRightwardsArrow,
A
Alex Dima 已提交
2439
			lineContent,
A
Alex Dima 已提交
2440
			false,
2441 2442
			isBasicASCII,
			containsRTL,
2443
			0,
A
Alex Dima 已提交
2444
			lineTokens,
2445
			decorations,
A
Alex Dima 已提交
2446
			tabSize,
2447
			0,
2448
			fontInfo.spaceWidth,
2449
			fontInfo.middotWidth,
2450
			fontInfo.wsmiddotWidth,
2451 2452 2453 2454
			stopRenderingLineAfter,
			renderWhitespace,
			renderControlCharacters,
			fontLigatures !== EditorFontLigatures.OFF,
2455
			null // Send no selections, original line cannot be selected
2456
		), sb);
E
Erich Gamma 已提交
2457

2458
		sb.appendASCIIString('</div>');
2459

2460 2461 2462 2463 2464 2465 2466
		if (this._renderIndicators) {
			const marginElement = document.createElement('div');
			marginElement.className = `delete-sign ${diffRemoveIcon.classNames}`;
			marginElement.setAttribute('style', `position:absolute;top:${renderedLineCount * lineHeight}px;width:${lineDecorationsWidth}px;height:${lineHeight}px;right:0;`);
			marginDomNode.appendChild(marginElement);
		}

2467 2468
		const absoluteOffsets = output.characterMapping.getAbsoluteOffsets();
		return absoluteOffsets.length > 0 ? absoluteOffsets[absoluteOffsets.length - 1] : 0;
E
Erich Gamma 已提交
2469 2470 2471
	}
}

2472
function validateDiffWordWrap(value: 'off' | 'on' | 'inherit' | undefined, defaultValue: 'off' | 'on' | 'inherit'): 'off' | 'on' | 'inherit' {
2473
	return validateStringSetOption<'off' | 'on' | 'inherit'>(value, defaultValue, ['off', 'on', 'inherit']);
2474 2475
}

A
Renames  
Alex Dima 已提交
2476
function isChangeOrInsert(lineChange: editorCommon.IChange): boolean {
E
Erich Gamma 已提交
2477 2478 2479
	return lineChange.modifiedEndLineNumber > 0;
}

A
Renames  
Alex Dima 已提交
2480
function isChangeOrDelete(lineChange: editorCommon.IChange): boolean {
E
Erich Gamma 已提交
2481 2482 2483 2484
	return lineChange.originalEndLineNumber > 0;
}

function createFakeLinesDiv(): HTMLElement {
A
Alex Dima 已提交
2485
	const r = document.createElement('div');
E
Erich Gamma 已提交
2486 2487 2488
	r.className = 'diagonal-fill';
	return r;
}
2489

2490 2491 2492 2493 2494 2495 2496
function getViewRange(model: ITextModel, viewModel: IViewModel, startLineNumber: number, endLineNumber: number): Range {
	return viewModel.coordinatesConverter.convertModelRangeToViewRange(new Range(
		startLineNumber, model.getLineMinColumn(startLineNumber),
		endLineNumber, model.getLineMaxColumn(endLineNumber)
	));
}

2497
registerThemingParticipant((theme, collector) => {
2498
	const added = theme.getColor(diffInserted);
2499 2500
	if (added) {
		collector.addRule(`.monaco-editor .line-insert, .monaco-editor .char-insert { background-color: ${added}; }`);
A
Alex Dima 已提交
2501
		collector.addRule(`.monaco-diff-editor .line-insert, .monaco-diff-editor .char-insert { background-color: ${added}; }`);
2502 2503
		collector.addRule(`.monaco-editor .inline-added-margin-view-zone { background-color: ${added}; }`);
	}
2504 2505

	const removed = theme.getColor(diffRemoved);
2506 2507
	if (removed) {
		collector.addRule(`.monaco-editor .line-delete, .monaco-editor .char-delete { background-color: ${removed}; }`);
A
Alex Dima 已提交
2508
		collector.addRule(`.monaco-diff-editor .line-delete, .monaco-diff-editor .char-delete { background-color: ${removed}; }`);
2509 2510
		collector.addRule(`.monaco-editor .inline-deleted-margin-view-zone { background-color: ${removed}; }`);
	}
2511 2512

	const addedOutline = theme.getColor(diffInsertedOutline);
2513
	if (addedOutline) {
2514
		collector.addRule(`.monaco-editor .line-insert, .monaco-editor .char-insert { border: 1px ${theme.type === 'hc' ? 'dashed' : 'solid'} ${addedOutline}; }`);
2515
	}
2516 2517

	const removedOutline = theme.getColor(diffRemovedOutline);
2518
	if (removedOutline) {
2519
		collector.addRule(`.monaco-editor .line-delete, .monaco-editor .char-delete { border: 1px ${theme.type === 'hc' ? 'dashed' : 'solid'} ${removedOutline}; }`);
2520
	}
2521 2522

	const shadow = theme.getColor(scrollbarShadow);
2523 2524 2525
	if (shadow) {
		collector.addRule(`.monaco-diff-editor.side-by-side .editor.modified { box-shadow: -6px 0 5px -5px ${shadow}; }`);
	}
2526

M
Matt Bierner 已提交
2527
	const border = theme.getColor(diffBorder);
2528 2529 2530
	if (border) {
		collector.addRule(`.monaco-diff-editor.side-by-side .editor.modified { border-left: 1px solid ${border}; }`);
	}
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558

	const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground);
	if (scrollbarSliderBackgroundColor) {
		collector.addRule(`
			.monaco-diff-editor .diffViewport {
				background: ${scrollbarSliderBackgroundColor};
			}
		`);
	}

	const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground);
	if (scrollbarSliderHoverBackgroundColor) {
		collector.addRule(`
			.monaco-diff-editor .diffViewport:hover {
				background: ${scrollbarSliderHoverBackgroundColor};
			}
		`);
	}

	const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground);
	if (scrollbarSliderActiveBackgroundColor) {
		collector.addRule(`
			.monaco-diff-editor .diffViewport:active {
				background: ${scrollbarSliderActiveBackgroundColor};
			}
		`);
	}

2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571
	const diffDiagonalFillColor = theme.getColor(diffDiagonalFill);
	collector.addRule(`
	.monaco-editor .diagonal-fill {
		background-image: linear-gradient(
			-45deg,
			${diffDiagonalFillColor} 12.5%,
			#0000 12.5%, #0000 50%,
			${diffDiagonalFillColor} 50%, ${diffDiagonalFillColor} 62.5%,
			#0000 62.5%, #0000 100%
		);
		background-size: 8px 8px;
	}
	`);
2572
});