dirtydiffDecorator.ts 39.5 KB
Newer Older
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

8
import * as nls from 'vs/nls';
9

J
Joao Moreno 已提交
10
import 'vs/css!./media/dirtydiffDecorator';
J
Joao Moreno 已提交
11
import { ThrottledDelayer, always, first } from 'vs/base/common/async';
J
Joao Moreno 已提交
12
import { IDisposable, dispose, toDisposable, Disposable, combinedDisposable } from 'vs/base/common/lifecycle';
13
import { TPromise } from 'vs/base/common/winjs.base';
M
Matt Bierner 已提交
14
import { Event, Emitter, anyEvent as anyEvent, filterEvent, once } from 'vs/base/common/event';
15
import * as ext from 'vs/workbench/common/contributions';
A
Alex Dima 已提交
16
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
17
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
18
import { ITextModelService } from 'vs/editor/common/services/resolverService';
19
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
20
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService';
21
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
22
import { URI } from 'vs/base/common/uri';
J
Joao Moreno 已提交
23
import { ISCMService, ISCMRepository } from 'vs/workbench/services/scm/common/scm';
A
Alex Dima 已提交
24
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
J
Joao Moreno 已提交
25
import { registerThemingParticipant, ITheme, ICssStyleCollector, themeColorFromId, IThemeService } from 'vs/platform/theme/common/themeService';
26
import { registerColor } from 'vs/platform/theme/common/colorRegistry';
27
import { Color, RGBA } from 'vs/base/common/color';
J
Joao Moreno 已提交
28
import { ICodeEditor, IEditorMouseEvent, MouseTargetType } from 'vs/editor/browser/editorBrowser';
29
import { registerEditorAction, registerEditorContribution, ServicesAccessor, EditorAction } from 'vs/editor/browser/editorExtensions';
30
import { PeekViewWidget, getOuterEditor } from 'vs/editor/contrib/referenceSearch/peekViewWidget';
J
Joao Moreno 已提交
31
import { IContextKeyService, IContextKey, ContextKeyExpr, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
J
Joao Moreno 已提交
32 33
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
J
Joao Moreno 已提交
34 35
import { Position } from 'vs/editor/common/core/position';
import { rot } from 'vs/base/common/numbers';
36
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
37
import { peekViewBorder, peekViewTitleBackground, peekViewTitleForeground, peekViewTitleInfoForeground } from 'vs/editor/contrib/referenceSearch/referencesWidget';
J
Joao Moreno 已提交
38 39
import { EmbeddedDiffEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget';
import { IDiffEditorOptions } from 'vs/editor/common/config/editorOptions';
J
Joao Moreno 已提交
40
import { Action, IAction, ActionRunner } from 'vs/base/common/actions';
J
Joao Moreno 已提交
41
import { IActionBarOptions, ActionsOrientation, IActionItem } from 'vs/base/browser/ui/actionbar/actionbar';
42
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
J
Joao Moreno 已提交
43
import { basename } from 'vs/base/common/paths';
J
Joao Moreno 已提交
44
import { MenuId, IMenuService, IMenu, MenuItemAction } from 'vs/platform/actions/common/actions';
45
import { MenuItemActionItem, fillInActionBarActions } from 'vs/platform/actions/browser/menuItemActionItem';
46
import { IChange, IEditorModel, ScrollType, IEditorContribution } from 'vs/editor/common/editorCommon';
A
Alex Dima 已提交
47
import { OverviewRulerLane, ITextModel, IModelDecorationOptions } from 'vs/editor/common/model';
J
Joao Moreno 已提交
48
import { sortedDiff, firstIndex } from 'vs/base/common/arrays';
J
Joao Moreno 已提交
49
import { IMarginData } from 'vs/editor/browser/controller/mouseTarget';
50
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
J
Joao Moreno 已提交
51
import { ISplice } from 'vs/base/common/sequence';
I
isidor 已提交
52
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
53
import { INotificationService } from 'vs/platform/notification/common/notification';
54
import { createStyleSheet } from 'vs/base/browser/dom';
J
Joao Moreno 已提交
55 56 57 58 59 60 61 62 63 64 65 66

// TODO@Joao
// Need to subclass MenuItemActionItem in order to respect
// the action context coming from any action bar, without breaking
// existing users
class DiffMenuItemActionItem extends MenuItemActionItem {

	onClick(event: MouseEvent): void {
		event.preventDefault();
		event.stopPropagation();

		this.actionRunner.run(this._commandAction, this._context)
67
			.then(undefined, err => this._notificationService.error(err));
J
Joao Moreno 已提交
68 69
	}
}
J
Joao Moreno 已提交
70

J
Joao Moreno 已提交
71 72 73 74 75 76 77 78 79 80 81
class DiffActionRunner extends ActionRunner {

	runAction(action: IAction, context: any): TPromise<any> {
		if (action instanceof MenuItemAction) {
			return action.run(...context);
		}

		return super.runAction(action, context);
	}
}

J
Joao Moreno 已提交
82
export interface IModelRegistry {
J
Joao Moreno 已提交
83
	getModel(editorModel: IEditorModel): DirtyDiffModel;
J
Joao Moreno 已提交
84 85
}

J
Joao Moreno 已提交
86 87
export const isDirtyDiffVisible = new RawContextKey<boolean>('dirtyDiffVisible', false);

J
Joao Moreno 已提交
88
function getChangeHeight(change: IChange): number {
J
Joao Moreno 已提交
89 90 91 92 93 94 95 96 97 98 99 100
	const modified = change.modifiedEndLineNumber - change.modifiedStartLineNumber + 1;
	const original = change.originalEndLineNumber - change.originalStartLineNumber + 1;

	if (change.originalEndLineNumber === 0) {
		return modified;
	} else if (change.modifiedEndLineNumber === 0) {
		return original;
	} else {
		return modified + original;
	}
}

J
Joao Moreno 已提交
101
function getModifiedEndLineNumber(change: IChange): number {
J
Joao Moreno 已提交
102
	if (change.modifiedEndLineNumber === 0) {
J
Joao Moreno 已提交
103
		return change.modifiedStartLineNumber === 0 ? 1 : change.modifiedStartLineNumber;
J
Joao Moreno 已提交
104 105 106 107 108
	} else {
		return change.modifiedEndLineNumber;
	}
}

J
Joao Moreno 已提交
109 110 111 112 113 114 115 116 117
function lineIntersectsChange(lineNumber: number, change: IChange): boolean {
	// deletion at the beginning of the file
	if (lineNumber === 1 && change.modifiedStartLineNumber === 0 && change.modifiedEndLineNumber === 0) {
		return true;
	}

	return lineNumber >= change.modifiedStartLineNumber && lineNumber <= (change.modifiedEndLineNumber || change.modifiedStartLineNumber);
}

J
Joao Moreno 已提交
118 119
class UIEditorAction extends Action {

120
	private editor: ICodeEditor;
121 122 123
	private action: EditorAction;
	private instantiationService: IInstantiationService;

J
Joao Moreno 已提交
124
	constructor(
125
		editor: ICodeEditor,
126
		action: EditorAction,
J
Joao Moreno 已提交
127
		cssClass: string,
128 129
		@IKeybindingService keybindingService: IKeybindingService,
		@IInstantiationService instantiationService: IInstantiationService
J
Joao Moreno 已提交
130
	) {
131 132 133 134 135 136 137 138
		const keybinding = keybindingService.lookupKeybinding(action.id);
		const label = action.label + (keybinding ? ` (${keybinding.getLabel()})` : '');

		super(action.id, label, cssClass);

		this.instantiationService = instantiationService;
		this.action = action;
		this.editor = editor;
J
Joao Moreno 已提交
139 140 141 142 143 144 145
	}

	run(): TPromise<any> {
		return TPromise.wrap(this.instantiationService.invokeFunction(accessor => this.action.run(accessor, this.editor, null)));
	}
}

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
enum ChangeType {
	Modify,
	Add,
	Delete
}

function getChangeType(change: IChange): ChangeType {
	if (change.originalEndLineNumber === 0) {
		return ChangeType.Add;
	} else if (change.modifiedEndLineNumber === 0) {
		return ChangeType.Delete;
	} else {
		return ChangeType.Modify;
	}
}

function getChangeTypeColor(theme: ITheme, changeType: ChangeType): Color {
	switch (changeType) {
		case ChangeType.Modify: return theme.getColor(editorGutterModifiedBackground);
		case ChangeType.Add: return theme.getColor(editorGutterAddedBackground);
		case ChangeType.Delete: return theme.getColor(editorGutterDeletedBackground);
	}
}

170
function getOuterEditorFromDiffEditor(accessor: ServicesAccessor): ICodeEditor {
J
Joao Moreno 已提交
171 172 173
	const diffEditors = accessor.get(ICodeEditorService).listDiffEditors();

	for (const diffEditor of diffEditors) {
A
Alex Dima 已提交
174
		if (diffEditor.hasTextFocus() && diffEditor instanceof EmbeddedDiffEditorWidget) {
J
Joao Moreno 已提交
175 176 177 178 179 180 181
			return diffEditor.getParentEditor();
		}
	}

	return getOuterEditor(accessor);
}

J
Joao Moreno 已提交
182 183
class DirtyDiffWidget extends PeekViewWidget {

J
Joao Moreno 已提交
184
	private diffEditor: EmbeddedDiffEditorWidget;
J
Joao Moreno 已提交
185
	private title: string;
J
Joao Moreno 已提交
186
	private menu: IMenu;
J
Joao Moreno 已提交
187
	private index: number;
J
Joao Moreno 已提交
188
	private change: IChange;
J
Joao Moreno 已提交
189
	private height: number | undefined = undefined;
J
Joao Moreno 已提交
190
	private contextKeyService: IContextKeyService;
191

J
Joao Moreno 已提交
192 193 194
	constructor(
		editor: ICodeEditor,
		private model: DirtyDiffModel,
195
		@IThemeService private themeService: IThemeService,
J
Joao Moreno 已提交
196
		@IInstantiationService private instantiationService: IInstantiationService,
J
Joao Moreno 已提交
197
		@IMenuService menuService: IMenuService,
J
Joao Moreno 已提交
198
		@IKeybindingService private keybindingService: IKeybindingService,
199
		@INotificationService private notificationService: INotificationService,
I
isidor 已提交
200 201
		@IContextKeyService contextKeyService: IContextKeyService,
		@IContextMenuService private contextMenuService: IContextMenuService
J
Joao Moreno 已提交
202
	) {
J
Joao Moreno 已提交
203
		super(editor, { isResizeable: true, frameWidth: 1, keepEditorSelection: true });
J
Joao Moreno 已提交
204

J
Joao Moreno 已提交
205 206 207
		themeService.onThemeChange(this._applyTheme, this, this._disposables);
		this._applyTheme(themeService.getTheme());

J
Joao Moreno 已提交
208 209 210
		this.contextKeyService = contextKeyService.createScoped();
		this.contextKeyService.createKey('originalResourceScheme', this.model.original.uri.scheme);
		this.menu = menuService.createMenu(MenuId.SCMChangeContext, this.contextKeyService);
J
Joao Moreno 已提交
211

J
Joao Moreno 已提交
212
		this.create();
J
Joao Moreno 已提交
213 214
		this.title = basename(editor.getModel().uri.fsPath);
		this.setTitle(this.title);
J
Joao Moreno 已提交
215

J
Joao Moreno 已提交
216
		model.onDidChange(this.renderTitle, this, this._disposables);
J
Joao Moreno 已提交
217 218
	}

J
Joao Moreno 已提交
219 220
	showChange(index: number): void {
		const change = this.model.changes[index];
J
Joao Moreno 已提交
221
		this.index = index;
J
Joao Moreno 已提交
222 223 224
		this.change = change;

		const originalModel = this.model.original;
225 226 227 228 229

		if (!originalModel) {
			return;
		}

230 231 232 233 234 235
		const onFirstDiffUpdate = once(this.diffEditor.onDidUpdateDiff);

		// TODO@joao TODO@alex need this setTimeout probably because the
		// non-side-by-side diff still hasn't created the view zones
		onFirstDiffUpdate(() => setTimeout(() => this.revealChange(change), 0));

J
Joao Moreno 已提交
236
		this.diffEditor.setModel(this.model);
237

J
Joao Moreno 已提交
238
		const position = new Position(getModifiedEndLineNumber(change), 1);
J
Joao Moreno 已提交
239 240 241 242 243

		const lineHeight = this.editor.getConfiguration().lineHeight;
		const editorHeight = this.editor.getLayoutInfo().height;
		const editorHeightInLines = Math.floor(editorHeight / lineHeight);
		const height = Math.min(getChangeHeight(change) + /* padding */ 8, Math.floor(editorHeightInLines / 3));
J
Joao Moreno 已提交
244

J
Joao Moreno 已提交
245
		this.renderTitle();
246 247 248

		const changeType = getChangeType(change);
		const changeTypeColor = getChangeTypeColor(this.themeService.getTheme(), changeType);
J
Joao Moreno 已提交
249
		this.style({ frameColor: changeTypeColor, arrowColor: changeTypeColor });
250

J
Joao Moreno 已提交
251
		this._actionbarWidget.context = [this.model.modified.uri, this.model.changes, index];
J
Joao Moreno 已提交
252
		this.show(position, height);
J
Joao Moreno 已提交
253
		this.editor.focus();
J
Joao Moreno 已提交
254 255 256
	}

	private renderTitle(): void {
J
Joao Moreno 已提交
257
		const detail = this.model.changes.length > 1
258 259
			? nls.localize('changes', "{0} of {1} changes", this.index + 1, this.model.changes.length)
			: nls.localize('change', "{0} of {1} change", this.index + 1, this.model.changes.length);
J
Joao Moreno 已提交
260

J
Joao Moreno 已提交
261
		this.setTitle(this.title, detail);
262 263
	}

J
Joao Moreno 已提交
264 265 266
	protected _fillHead(container: HTMLElement): void {
		super._fillHead(container);

267 268
		const previous = this.instantiationService.createInstance(UIEditorAction, this.editor, new ShowPreviousChangeAction(), 'show-previous-change octicon octicon-chevron-up');
		const next = this.instantiationService.createInstance(UIEditorAction, this.editor, new ShowNextChangeAction(), 'show-next-change octicon octicon-chevron-down');
J
Joao Moreno 已提交
269 270 271 272

		this._disposables.push(previous);
		this._disposables.push(next);
		this._actionbarWidget.push([previous, next], { label: false, icon: true });
J
Joao Moreno 已提交
273 274

		const actions: IAction[] = [];
275
		fillInActionBarActions(this.menu, { shouldForwardArgs: true }, actions);
J
Joao Moreno 已提交
276
		this._actionbarWidget.push(actions, { label: false, icon: true });
J
Joao Moreno 已提交
277 278 279 280
	}

	protected _getActionBarOptions(): IActionBarOptions {
		return {
J
Joao Moreno 已提交
281
			actionRunner: new DiffActionRunner(),
J
Joao Moreno 已提交
282
			actionItemProvider: action => this.getActionItem(action),
J
Joao Moreno 已提交
283 284 285 286
			orientation: ActionsOrientation.HORIZONTAL_REVERSE
		};
	}

J
Joao Moreno 已提交
287 288 289 290 291
	getActionItem(action: IAction): IActionItem {
		if (!(action instanceof MenuItemAction)) {
			return undefined;
		}

292
		return new DiffMenuItemActionItem(action, this.keybindingService, this.notificationService, this.contextMenuService);
J
Joao Moreno 已提交
293 294
	}

295
	protected _fillBody(container: HTMLElement): void {
J
Joao Moreno 已提交
296
		const options: IDiffEditorOptions = {
J
Joao Moreno 已提交
297
			scrollBeyondLastLine: true,
J
Joao Moreno 已提交
298 299 300 301 302 303 304 305 306 307
			scrollbar: {
				verticalScrollbarSize: 14,
				horizontal: 'auto',
				useShadows: true,
				verticalHasArrows: false,
				horizontalHasArrows: false
			},
			overviewRulerLanes: 2,
			fixedOverflowWidgets: true,
			minimap: { enabled: false },
J
Joao Moreno 已提交
308 309
			renderSideBySide: false,
			readOnly: true
J
Joao Moreno 已提交
310 311 312 313 314
		};

		this.diffEditor = this.instantiationService.createInstance(EmbeddedDiffEditorWidget, container, options, this.editor);
	}

J
Joao Moreno 已提交
315 316 317 318 319 320 321 322 323 324 325
	_onWidth(width: number): void {
		if (typeof this.height === 'undefined') {
			return;
		}

		this.diffEditor.layout({ height: this.height, width });
	}

	protected _doLayoutBody(height: number, width: number): void {
		super._doLayoutBody(height, width);
		this.diffEditor.layout({ height, width });
J
Joao Moreno 已提交
326

J
Joao Moreno 已提交
327
		if (typeof this.height === 'undefined') {
J
Joao Moreno 已提交
328 329
			this.revealChange(this.change);
		}
J
Joao Moreno 已提交
330 331

		this.height = height;
J
Joao Moreno 已提交
332 333
	}

J
Joao Moreno 已提交
334
	private revealChange(change: IChange): void {
J
Joao Moreno 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348
		let start: number, end: number;

		if (change.modifiedEndLineNumber === 0) { // deletion
			start = change.modifiedStartLineNumber;
			end = change.modifiedStartLineNumber + 1;
		} else if (change.originalEndLineNumber > 0) { // modification
			start = change.modifiedStartLineNumber - 1;
			end = change.modifiedEndLineNumber + 1;
		} else { // insertion
			start = change.modifiedStartLineNumber;
			end = change.modifiedEndLineNumber;
		}

		this.diffEditor.revealLinesInCenter(start, end, ScrollType.Immediate);
J
Joao Moreno 已提交
349
	}
J
Joao Moreno 已提交
350 351 352 353 354 355 356 357 358 359 360

	private _applyTheme(theme: ITheme) {
		let borderColor = theme.getColor(peekViewBorder) || Color.transparent;
		this.style({
			arrowColor: borderColor,
			frameColor: borderColor,
			headerBackgroundColor: theme.getColor(peekViewTitleBackground) || Color.transparent,
			primaryHeadingColor: theme.getColor(peekViewTitleForeground),
			secondaryHeadingColor: theme.getColor(peekViewTitleInfoForeground)
		});
	}
J
Joao Moreno 已提交
361 362 363 364

	protected revealLine(lineNumber: number) {
		this.editor.revealLineInCenterIfOutsideViewport(lineNumber, ScrollType.Smooth);
	}
J
Joao Moreno 已提交
365 366
}

J
Joao Moreno 已提交
367
export class ShowPreviousChangeAction extends EditorAction {
J
Joao Moreno 已提交
368 369 370

	constructor() {
		super({
J
Joao Moreno 已提交
371 372 373
			id: 'editor.action.dirtydiff.previous',
			label: nls.localize('show previous change', "Show Previous Change"),
			alias: 'Show Previous Change',
J
Joao Moreno 已提交
374
			precondition: null,
375
			kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyMod.Shift | KeyMod.Alt | KeyCode.F3, weight: KeybindingWeight.EditorContrib }
J
Joao Moreno 已提交
376 377 378
		});
	}

379
	run(accessor: ServicesAccessor, editor: ICodeEditor): void {
J
Joao Moreno 已提交
380 381 382 383 384 385 386
		const outerEditor = getOuterEditorFromDiffEditor(accessor);

		if (!outerEditor) {
			return;
		}

		const controller = DirtyDiffController.get(outerEditor);
J
Joao Moreno 已提交
387 388 389 390 391

		if (!controller) {
			return;
		}

J
Joao Moreno 已提交
392 393 394 395
		if (!controller.canNavigate()) {
			return;
		}

J
Joao Moreno 已提交
396 397 398
		controller.previous();
	}
}
399
registerEditorAction(ShowPreviousChangeAction);
J
Joao Moreno 已提交
400

J
Joao Moreno 已提交
401
export class ShowNextChangeAction extends EditorAction {
J
Joao Moreno 已提交
402 403 404

	constructor() {
		super({
J
Joao Moreno 已提交
405 406 407
			id: 'editor.action.dirtydiff.next',
			label: nls.localize('show next change', "Show Next Change"),
			alias: 'Show Next Change',
J
Joao Moreno 已提交
408
			precondition: null,
409
			kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyMod.Alt | KeyCode.F3, weight: KeybindingWeight.EditorContrib }
J
Joao Moreno 已提交
410 411 412
		});
	}

413
	run(accessor: ServicesAccessor, editor: ICodeEditor): void {
J
Joao Moreno 已提交
414 415 416 417 418 419 420
		const outerEditor = getOuterEditorFromDiffEditor(accessor);

		if (!outerEditor) {
			return;
		}

		const controller = DirtyDiffController.get(outerEditor);
J
Joao Moreno 已提交
421 422 423 424 425

		if (!controller) {
			return;
		}

J
Joao Moreno 已提交
426 427 428 429
		if (!controller.canNavigate()) {
			return;
		}

J
Joao Moreno 已提交
430
		controller.next();
J
Joao Moreno 已提交
431 432
	}
}
433
registerEditorAction(ShowNextChangeAction);
J
Joao Moreno 已提交
434

J
Joao Moreno 已提交
435 436 437 438 439 440 441 442
export class MoveToPreviousChangeAction extends EditorAction {

	constructor() {
		super({
			id: 'workbench.action.editor.previousChange',
			label: nls.localize('move to previous change', "Move to Previous Change"),
			alias: 'Move to Previous Change',
			precondition: null,
443
			kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyMod.Shift | KeyMod.Alt | KeyCode.F5, weight: KeybindingWeight.EditorContrib }
J
Joao Moreno 已提交
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
		});
	}

	run(accessor: ServicesAccessor, editor: ICodeEditor): void {
		const outerEditor = getOuterEditorFromDiffEditor(accessor);

		if (!outerEditor) {
			return;
		}

		const controller = DirtyDiffController.get(outerEditor);

		if (!controller || !controller.modelRegistry) {
			return;
		}

		const lineNumber = outerEditor.getPosition().lineNumber;
		const model = controller.modelRegistry.getModel(outerEditor.getModel());
J
Joao Moreno 已提交
462 463 464 465 466

		if (model.changes.length === 0) {
			return;
		}

J
Joao Moreno 已提交
467 468 469
		const index = model.findPreviousClosestChange(lineNumber, false);
		const change = model.changes[index];

J
Joao Moreno 已提交
470 471 472
		const position = new Position(change.modifiedStartLineNumber, 1);
		outerEditor.setPosition(position);
		outerEditor.revealPosition(position);
J
Joao Moreno 已提交
473 474 475 476 477 478 479 480 481 482 483 484
	}
}
registerEditorAction(MoveToPreviousChangeAction);

export class MoveToNextChangeAction extends EditorAction {

	constructor() {
		super({
			id: 'workbench.action.editor.nextChange',
			label: nls.localize('move to next change', "Move to Next Change"),
			alias: 'Move to Next Change',
			precondition: null,
485
			kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyMod.Alt | KeyCode.F5, weight: KeybindingWeight.EditorContrib }
J
Joao Moreno 已提交
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
		});
	}

	run(accessor: ServicesAccessor, editor: ICodeEditor): void {
		const outerEditor = getOuterEditorFromDiffEditor(accessor);

		if (!outerEditor) {
			return;
		}

		const controller = DirtyDiffController.get(outerEditor);

		if (!controller || !controller.modelRegistry) {
			return;
		}

		const lineNumber = outerEditor.getPosition().lineNumber;
		const model = controller.modelRegistry.getModel(outerEditor.getModel());
J
Joao Moreno 已提交
504 505 506 507 508

		if (model.changes.length === 0) {
			return;
		}

J
Joao Moreno 已提交
509 510 511
		const index = model.findNextClosestChange(lineNumber, false);
		const change = model.changes[index];

J
Joao Moreno 已提交
512 513 514
		const position = new Position(change.modifiedStartLineNumber, 1);
		outerEditor.setPosition(position);
		outerEditor.revealPosition(position);
J
Joao Moreno 已提交
515 516 517 518
	}
}
registerEditorAction(MoveToNextChangeAction);

J
Joao Moreno 已提交
519 520
KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: 'closeDirtyDiff',
521
	weight: KeybindingWeight.EditorContrib + 50,
J
Joao Moreno 已提交
522 523
	primary: KeyCode.Escape,
	secondary: [KeyMod.Shift | KeyCode.Escape],
J
Joao Moreno 已提交
524
	when: ContextKeyExpr.and(isDirtyDiffVisible),
J
Joao Moreno 已提交
525
	handler: (accessor: ServicesAccessor) => {
J
Joao Moreno 已提交
526 527 528
		const outerEditor = getOuterEditorFromDiffEditor(accessor);

		if (!outerEditor) {
J
Joao Moreno 已提交
529 530 531
			return;
		}

J
Joao Moreno 已提交
532
		const controller = DirtyDiffController.get(outerEditor);
J
Joao Moreno 已提交
533 534 535 536 537 538 539 540 541

		if (!controller) {
			return;
		}

		controller.close();
	}
});

J
Joao Moreno 已提交
542
export class DirtyDiffController implements IEditorContribution {
J
Joao Moreno 已提交
543

544
	private static readonly ID = 'editor.contrib.dirtydiff';
J
Joao Moreno 已提交
545

546
	static get(editor: ICodeEditor): DirtyDiffController {
J
Joao Moreno 已提交
547 548 549
		return editor.getContribution<DirtyDiffController>(DirtyDiffController.ID);
	}

J
Joao Moreno 已提交
550
	modelRegistry: IModelRegistry | null = null;
J
Joao Moreno 已提交
551

J
Joao Moreno 已提交
552
	private model: DirtyDiffModel | null = null;
J
Joao Moreno 已提交
553
	private widget: DirtyDiffWidget | null = null;
J
Joao Moreno 已提交
554
	private currentIndex: number = -1;
J
Joao Moreno 已提交
555
	private readonly isDirtyDiffVisible: IContextKey<boolean>;
J
Joao Moreno 已提交
556
	private session: IDisposable = Disposable.None;
J
Joao Moreno 已提交
557
	private mouseDownInfo: { lineNumber: number } | null = null;
J
Joao Moreno 已提交
558
	private enabled = false;
J
Joao Moreno 已提交
559
	private disposables: IDisposable[] = [];
J
Joao Moreno 已提交
560

J
Joao Moreno 已提交
561 562
	constructor(
		private editor: ICodeEditor,
J
Joao Moreno 已提交
563
		@IContextKeyService contextKeyService: IContextKeyService,
J
Joao Moreno 已提交
564
		@IInstantiationService private instantiationService: IInstantiationService
J
Joao Moreno 已提交
565
	) {
J
Joao Moreno 已提交
566 567 568 569 570 571
		this.enabled = !contextKeyService.getContextKeyValue('isInDiffEditor');

		if (this.enabled) {
			this.isDirtyDiffVisible = isDirtyDiffVisible.bindTo(contextKeyService);
			this.disposables.push(editor.onMouseDown(e => this.onEditorMouseDown(e)));
			this.disposables.push(editor.onMouseUp(e => this.onEditorMouseUp(e)));
J
Joao Moreno 已提交
572
			this.disposables.push(editor.onDidChangeModel(() => this.close()));
J
Joao Moreno 已提交
573
		}
J
Joao Moreno 已提交
574
	}
J
Joao Moreno 已提交
575

J
Joao Moreno 已提交
576 577
	getId(): string {
		return DirtyDiffController.ID;
J
Joao Moreno 已提交
578 579
	}

J
Joao Moreno 已提交
580 581 582 583
	canNavigate(): boolean {
		return this.currentIndex === -1 || this.model.changes.length > 1;
	}

J
Joao Moreno 已提交
584
	next(lineNumber?: number): void {
J
Joao Moreno 已提交
585
		if (!this.assertWidget()) {
J
Joao Moreno 已提交
586 587 588
			return;
		}

J
Joao Moreno 已提交
589
		if (typeof lineNumber === 'number' || this.currentIndex === -1) {
J
Joao Moreno 已提交
590
			this.currentIndex = this.model.findNextClosestChange(typeof lineNumber === 'number' ? lineNumber : this.editor.getPosition().lineNumber);
J
Joao Moreno 已提交
591
		} else {
J
Joao Moreno 已提交
592
			this.currentIndex = rot(this.currentIndex + 1, this.model.changes.length);
J
Joao Moreno 已提交
593 594
		}

J
Joao Moreno 已提交
595
		this.widget.showChange(this.currentIndex);
J
Joao Moreno 已提交
596 597
	}

J
Joao Moreno 已提交
598
	previous(lineNumber?: number): void {
J
Joao Moreno 已提交
599
		if (!this.assertWidget()) {
J
Joao Moreno 已提交
600 601 602
			return;
		}

J
Joao Moreno 已提交
603
		if (typeof lineNumber === 'number' || this.currentIndex === -1) {
J
Joao Moreno 已提交
604
			this.currentIndex = this.model.findPreviousClosestChange(typeof lineNumber === 'number' ? lineNumber : this.editor.getPosition().lineNumber);
J
Joao Moreno 已提交
605
		} else {
J
Joao Moreno 已提交
606
			this.currentIndex = rot(this.currentIndex - 1, this.model.changes.length);
J
Joao Moreno 已提交
607 608
		}

J
Joao Moreno 已提交
609
		this.widget.showChange(this.currentIndex);
J
Joao Moreno 已提交
610 611 612 613
	}

	close(): void {
		this.session.dispose();
J
Joao Moreno 已提交
614
		this.session = Disposable.None;
J
Joao Moreno 已提交
615 616 617
	}

	private assertWidget(): boolean {
J
Joao Moreno 已提交
618 619 620 621
		if (!this.enabled) {
			return false;
		}

J
Joao Moreno 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634
		if (this.widget) {
			if (this.model.changes.length === 0) {
				this.close();
				return false;
			}

			return true;
		}

		if (!this.modelRegistry) {
			return false;
		}

J
Joao Moreno 已提交
635 636 637
		const editorModel = this.editor.getModel();

		if (!editorModel) {
J
Joao Moreno 已提交
638
			return false;
J
Joao Moreno 已提交
639 640
		}

J
Joao Moreno 已提交
641
		const model = this.modelRegistry.getModel(editorModel);
J
Joao Moreno 已提交
642 643

		if (!model) {
J
Joao Moreno 已提交
644 645 646 647 648
			return false;
		}

		if (model.changes.length === 0) {
			return false;
J
Joao Moreno 已提交
649 650
		}

J
Joao Moreno 已提交
651
		this.currentIndex = -1;
J
Joao Moreno 已提交
652
		this.model = model;
J
Joao Moreno 已提交
653
		this.widget = this.instantiationService.createInstance(DirtyDiffWidget, this.editor, model);
J
Joao Moreno 已提交
654 655 656 657
		this.isDirtyDiffVisible.set(true);

		const disposables: IDisposable[] = [];
		once(this.widget.onDidClose)(this.close, this, disposables);
J
Joao Moreno 已提交
658
		model.onDidChange(this.onDidModelChange, this, disposables);
J
Joao Moreno 已提交
659 660

		disposables.push(
J
Joao Moreno 已提交
661
			this.widget,
J
Joao Moreno 已提交
662 663 664 665 666
			toDisposable(() => {
				this.model = null;
				this.widget = null;
				this.currentIndex = -1;
				this.isDirtyDiffVisible.set(false);
J
Joao Moreno 已提交
667
				this.editor.focus();
J
Joao Moreno 已提交
668
			})
J
Joao Moreno 已提交
669
		);
J
Joao Moreno 已提交
670

J
Joao Moreno 已提交
671 672
		this.session = combinedDisposable(disposables);
		return true;
J
Joao Moreno 已提交
673 674
	}

J
Joao Moreno 已提交
675
	private onDidModelChange(splices: ISplice<IChange>[]): void {
J
Joao Moreno 已提交
676 677 678 679 680 681
		for (const splice of splices) {
			if (splice.start <= this.currentIndex) {
				if (this.currentIndex < splice.start + splice.deleteCount) {
					this.currentIndex = -1;
					this.next();
				} else {
J
Joao Moreno 已提交
682
					this.currentIndex = rot(this.currentIndex + splice.toInsert.length - splice.deleteCount - 1, this.model.changes.length);
J
Joao Moreno 已提交
683 684 685 686
					this.next();
				}
			}
		}
J
Joao Moreno 已提交
687 688
	}

J
Joao Moreno 已提交
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
	private onEditorMouseDown(e: IEditorMouseEvent): void {
		this.mouseDownInfo = null;

		const range = e.target.range;

		if (!range) {
			return;
		}

		if (!e.event.leftButton) {
			return;
		}

		if (e.target.type !== MouseTargetType.GUTTER_LINE_DECORATIONS) {
			return;
		}

706 707 708 709
		if (e.target.element.className.indexOf('dirty-diff-glyph') < 0) {
			return;
		}

J
Joao Moreno 已提交
710
		const data = e.target.detail as IMarginData;
711 712
		const offsetLeftInGutter = (e.target.element as HTMLElement).offsetLeft;
		const gutterOffsetX = data.offsetX - offsetLeftInGutter;
J
Joao Moreno 已提交
713 714

		// TODO@joao TODO@alex TODO@martin this is such that we don't collide with folding
715
		if (gutterOffsetX < -3 || gutterOffsetX > 6) { // dirty diff decoration on hover is 9px wide
J
Joao Moreno 已提交
716 717 718
			return;
		}

J
Joao Moreno 已提交
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
		this.mouseDownInfo = { lineNumber: range.startLineNumber };
	}

	private onEditorMouseUp(e: IEditorMouseEvent): void {
		if (!this.mouseDownInfo) {
			return;
		}

		const { lineNumber } = this.mouseDownInfo;
		this.mouseDownInfo = null;

		const range = e.target.range;

		if (!range || range.startLineNumber !== lineNumber) {
			return;
		}

		if (e.target.type !== MouseTargetType.GUTTER_LINE_DECORATIONS) {
			return;
		}

J
Joao Moreno 已提交
740 741 742 743
		if (!this.modelRegistry) {
			return;
		}

J
Joao Moreno 已提交
744 745 746 747 748 749 750 751 752 753 754 755
		const editorModel = this.editor.getModel();

		if (!editorModel) {
			return;
		}

		const model = this.modelRegistry.getModel(editorModel);

		if (!model) {
			return;
		}

J
Joao Moreno 已提交
756 757 758
		const index = firstIndex(model.changes, change => lineIntersectsChange(lineNumber, change));

		if (index < 0) {
J
Joao Moreno 已提交
759 760 761
			return;
		}

J
Joao Moreno 已提交
762 763 764 765 766
		if (index === this.currentIndex) {
			this.close();
		} else {
			this.next(lineNumber);
		}
J
Joao Moreno 已提交
767 768
	}

J
Joao Moreno 已提交
769
	dispose(): void {
770
		this.disposables = dispose(this.disposables);
J
Joao Moreno 已提交
771 772
	}
}
773

774
export const editorGutterModifiedBackground = registerColor('editorGutter.modifiedBackground', {
J
Joao Moreno 已提交
775 776 777
	dark: new Color(new RGBA(12, 125, 157)),
	light: new Color(new RGBA(102, 175, 224)),
	hc: new Color(new RGBA(0, 73, 122))
778
}, nls.localize('editorGutterModifiedBackground', "Editor gutter background color for lines that are modified."));
779 780

export const editorGutterAddedBackground = registerColor('editorGutter.addedBackground', {
J
Joao Moreno 已提交
781 782 783
	dark: new Color(new RGBA(88, 124, 12)),
	light: new Color(new RGBA(129, 184, 139)),
	hc: new Color(new RGBA(27, 82, 37))
784
}, nls.localize('editorGutterAddedBackground', "Editor gutter background color for lines that are added."));
785 786

export const editorGutterDeletedBackground = registerColor('editorGutter.deletedBackground', {
J
Joao Moreno 已提交
787 788 789
	dark: new Color(new RGBA(148, 21, 27)),
	light: new Color(new RGBA(202, 75, 81)),
	hc: new Color(new RGBA(141, 14, 20))
790
}, nls.localize('editorGutterDeletedBackground', "Editor gutter background color for lines that are deleted."));
791

792 793 794 795 796
const overviewRulerDefault = new Color(new RGBA(0, 122, 204, 0.6));
export const overviewRulerModifiedForeground = registerColor('editorOverviewRuler.modifiedForeground', { dark: overviewRulerDefault, light: overviewRulerDefault, hc: overviewRulerDefault }, nls.localize('overviewRulerModifiedForeground', 'Overview ruler marker color for modified content.'));
export const overviewRulerAddedForeground = registerColor('editorOverviewRuler.addedForeground', { dark: overviewRulerDefault, light: overviewRulerDefault, hc: overviewRulerDefault }, nls.localize('overviewRulerAddedForeground', 'Overview ruler marker color for added content.'));
export const overviewRulerDeletedForeground = registerColor('editorOverviewRuler.deletedForeground', { dark: overviewRulerDefault, light: overviewRulerDefault, hc: overviewRulerDefault }, nls.localize('overviewRulerDeletedForeground', 'Overview ruler marker color for deleted content.'));

J
Joao Moreno 已提交
797
class DirtyDiffDecorator {
798

J
Joao Moreno 已提交
799 800 801 802 803 804 805
	static createDecoration(className: string, foregroundColor: string, options: { gutter: boolean, overview: boolean }): ModelDecorationOptions {
		const decorationOptions: IModelDecorationOptions = {
			isWholeLine: true,
		};

		if (options.gutter) {
			decorationOptions.linesDecorationsClassName = `dirty-diff-glyph ${className}`;
806
		}
J
Joao Moreno 已提交
807 808 809

		if (options.overview) {
			decorationOptions.overviewRuler = {
810
				color: themeColorFromId(foregroundColor),
J
Joao Moreno 已提交
811 812
				position: OverviewRulerLane.Left
			};
813 814
		}

J
Joao Moreno 已提交
815 816 817 818 819 820
		return ModelDecorationOptions.createDynamic(decorationOptions);
	}

	private modifiedOptions: ModelDecorationOptions;
	private addedOptions: ModelDecorationOptions;
	private deletedOptions: ModelDecorationOptions;
J
Joao Moreno 已提交
821
	private decorations: string[] = [];
J
Joao Moreno 已提交
822 823 824
	private disposables: IDisposable[] = [];

	constructor(
A
Alex Dima 已提交
825
		private editorModel: ITextModel,
J
Joao Moreno 已提交
826 827
		private model: DirtyDiffModel,
		@IConfigurationService configurationService: IConfigurationService
J
Joao Moreno 已提交
828
	) {
J
Joao Moreno 已提交
829 830 831 832 833 834 835 836 837
		const decorations = configurationService.getValue<string>('scm.diffDecorations');
		const gutter = decorations === 'all' || decorations === 'gutter';
		const overview = decorations === 'all' || decorations === 'overview';
		const options = { gutter, overview };

		this.modifiedOptions = DirtyDiffDecorator.createDecoration('dirty-diff-modified', overviewRulerModifiedForeground, options);
		this.addedOptions = DirtyDiffDecorator.createDecoration('dirty-diff-added', overviewRulerAddedForeground, options);
		this.deletedOptions = DirtyDiffDecorator.createDecoration('dirty-diff-deleted', overviewRulerDeletedForeground, options);

J
Joao Moreno 已提交
838 839 840
		model.onDidChange(this.onDidChange, this, this.disposables);
	}

J
Joao Moreno 已提交
841 842
	private onDidChange(): void {
		const decorations = this.model.changes.map((change) => {
843
			const changeType = getChangeType(change);
J
Joao Moreno 已提交
844 845 846
			const startLineNumber = change.modifiedStartLineNumber;
			const endLineNumber = change.modifiedEndLineNumber || startLineNumber;

847 848 849 850 851 852 853
			switch (changeType) {
				case ChangeType.Add:
					return {
						range: {
							startLineNumber: startLineNumber, startColumn: 1,
							endLineNumber: endLineNumber, endColumn: 1
						},
J
Joao Moreno 已提交
854
						options: this.addedOptions
855 856 857 858 859 860 861
					};
				case ChangeType.Delete:
					return {
						range: {
							startLineNumber: startLineNumber, startColumn: 1,
							endLineNumber: startLineNumber, endColumn: 1
						},
J
Joao Moreno 已提交
862
						options: this.deletedOptions
863 864 865 866 867 868 869
					};
				case ChangeType.Modify:
					return {
						range: {
							startLineNumber: startLineNumber, startColumn: 1,
							endLineNumber: endLineNumber, endColumn: 1
						},
J
Joao Moreno 已提交
870
						options: this.modifiedOptions
871
					};
J
Joao Moreno 已提交
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
			}
		});

		this.decorations = this.editorModel.deltaDecorations(this.decorations, decorations);
	}

	dispose(): void {
		this.disposables = dispose(this.disposables);

		if (this.editorModel && !this.editorModel.isDisposed()) {
			this.editorModel.deltaDecorations(this.decorations, []);
		}

		this.editorModel = null;
		this.decorations = [];
	}
}

J
Joao Moreno 已提交
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
function compareChanges(a: IChange, b: IChange): number {
	let result = a.modifiedStartLineNumber - b.modifiedStartLineNumber;

	if (result !== 0) {
		return result;
	}

	result = a.modifiedEndLineNumber - b.modifiedEndLineNumber;

	if (result !== 0) {
		return result;
	}

	result = a.originalStartLineNumber - b.originalStartLineNumber;

	if (result !== 0) {
		return result;
	}

	return a.originalEndLineNumber - b.originalEndLineNumber;
}

J
Joao Moreno 已提交
912 913
export class DirtyDiffModel {

A
Alex Dima 已提交
914 915 916
	private _originalModel: ITextModel;
	get original(): ITextModel { return this._originalModel; }
	get modified(): ITextModel { return this._editorModel; }
917

J
Joao Moreno 已提交
918
	private diffDelayer: ThrottledDelayer<IChange[]>;
919
	private _originalURIPromise: TPromise<URI>;
J
Joao Moreno 已提交
920
	private repositoryDisposables = new Set<IDisposable[]>();
J
Joao Moreno 已提交
921
	private disposables: IDisposable[] = [];
922

J
Joao Moreno 已提交
923 924
	private _onDidChange = new Emitter<ISplice<IChange>[]>();
	readonly onDidChange: Event<ISplice<IChange>[]> = this._onDidChange.event;
J
Joao Moreno 已提交
925

J
Joao Moreno 已提交
926 927
	private _changes: IChange[] = [];
	get changes(): IChange[] {
J
Joao Moreno 已提交
928 929 930
		return this._changes;
	}

931
	constructor(
A
Alex Dima 已提交
932
		private _editorModel: ITextModel,
J
Joao Moreno 已提交
933
		@ISCMService private scmService: ISCMService,
934
		@IEditorWorkerService private editorWorkerService: IEditorWorkerService,
J
Joao Moreno 已提交
935 936
		@ITextModelService private textModelResolverService: ITextModelService,
		@IConfigurationService private configurationService: IConfigurationService
937
	) {
J
Joao Moreno 已提交
938
		this.diffDelayer = new ThrottledDelayer<IChange[]>(200);
J
Joao Moreno 已提交
939

J
Joao Moreno 已提交
940
		this.disposables.push(_editorModel.onDidChangeContent(() => this.triggerDiff()));
J
Joao Moreno 已提交
941
		scmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);
J
Joao Moreno 已提交
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
		scmService.repositories.forEach(r => this.onDidAddRepository(r));

		this.triggerDiff();
	}

	private onDidAddRepository(repository: ISCMRepository): void {
		const disposables: IDisposable[] = [];

		this.repositoryDisposables.add(disposables);
		disposables.push(toDisposable(() => this.repositoryDisposables.delete(disposables)));

		const onDidChange = anyEvent(repository.provider.onDidChange, repository.provider.onDidChangeResources);
		onDidChange(this.triggerDiff, this, disposables);

		const onDidRemoveThis = filterEvent(this.scmService.onDidRemoveRepository, r => r === repository);
957
		onDidRemoveThis(() => dispose(disposables), null, disposables);
J
Joao Moreno 已提交
958 959

		this.triggerDiff();
960 961
	}

962
	private triggerDiff(): TPromise<any> {
963
		if (!this.diffDelayer) {
964
			return TPromise.as(null);
965 966
		}

J
Joao Moreno 已提交
967 968
		return this.diffDelayer
			.trigger(() => this.diff())
J
Joao Moreno 已提交
969
			.then((changes: IChange[]) => {
J
Joao Moreno 已提交
970
				if (!this._editorModel || this._editorModel.isDisposed() || !this._originalModel || this._originalModel.isDisposed()) {
971
					return undefined; // disposed
J
Joao Moreno 已提交
972
				}
J
Joao Moreno 已提交
973

974
				if (this._originalModel.getValueLength() === 0) {
J
Joao Moreno 已提交
975
					changes = [];
J
Joao Moreno 已提交
976
				}
977

J
Joao Moreno 已提交
978
				const diff = sortedDiff(this._changes, changes, compareChanges);
J
Joao Moreno 已提交
979
				this._changes = changes;
J
Joao Moreno 已提交
980 981 982 983

				if (diff.length > 0) {
					this._onDidChange.fire(diff);
				}
J
Joao Moreno 已提交
984 985
			});
	}
986

J
Joao Moreno 已提交
987
	private diff(): TPromise<IChange[]> {
J
Joao Moreno 已提交
988
		return this.getOriginalURIPromise().then(originalURI => {
J
Joao Moreno 已提交
989
			if (!this._editorModel || this._editorModel.isDisposed() || !originalURI) {
990
				return TPromise.as([]); // disposed
J
Joao Moreno 已提交
991
			}
992

J
Joao Moreno 已提交
993
			if (!this.editorWorkerService.canComputeDirtyDiff(originalURI, this._editorModel.uri)) {
994
				return TPromise.as([]); // Files too large
995 996
			}

J
Joao Moreno 已提交
997 998 999
			const ignoreTrimWhitespace = this.configurationService.getValue<boolean>('diffEditor.ignoreTrimWhitespace');

			return this.editorWorkerService.computeDirtyDiff(originalURI, this._editorModel.uri, ignoreTrimWhitespace);
J
Joao Moreno 已提交
1000
		});
1001 1002
	}

1003
	private getOriginalURIPromise(): TPromise<URI> {
J
Joao Moreno 已提交
1004 1005 1006 1007
		if (this._originalURIPromise) {
			return this._originalURIPromise;
		}

1008
		this._originalURIPromise = this.getOriginalResource()
J
Joao Moreno 已提交
1009
			.then(originalUri => {
1010 1011 1012 1013
				if (!this._editorModel) { // disposed
					return null;
				}

J
Joao Moreno 已提交
1014
				if (!originalUri) {
1015
					this._originalModel = null;
J
Joao Moreno 已提交
1016 1017 1018 1019 1020
					return null;
				}

				return this.textModelResolverService.createModelReference(originalUri)
					.then(ref => {
1021 1022 1023 1024
						if (!this._editorModel) { // disposed
							return null;
						}

1025
						this._originalModel = ref.object.textEditorModel;
J
Joao Moreno 已提交
1026

J
Joao Moreno 已提交
1027 1028
						this.disposables.push(ref);
						this.disposables.push(ref.object.textEditorModel.onDidChangeContent(() => this.triggerDiff()));
J
Joao Moreno 已提交
1029

J
Joao Moreno 已提交
1030 1031 1032
						return originalUri;
					});
			});
J
Joao Moreno 已提交
1033 1034 1035 1036 1037 1038

		return always(this._originalURIPromise, () => {
			this._originalURIPromise = null;
		});
	}

J
Joao Moreno 已提交
1039
	private getOriginalResource(): TPromise<URI> {
J
Joao Moreno 已提交
1040
		if (!this._editorModel) {
J
fix NPE  
Joao Moreno 已提交
1041
			return TPromise.as(null);
J
Joao Moreno 已提交
1042 1043
		}

J
Joao Moreno 已提交
1044 1045
		const uri = this._editorModel.uri;
		return first(this.scmService.repositories.map(r => () => r.provider.getOriginalResource(uri)));
1046 1047
	}

J
Joao Moreno 已提交
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
	findNextClosestChange(lineNumber: number, inclusive = true): number {
		for (let i = 0; i < this.changes.length; i++) {
			const change = this.changes[i];

			if (inclusive) {
				if (getModifiedEndLineNumber(change) >= lineNumber) {
					return i;
				}
			} else {
				if (change.modifiedStartLineNumber > lineNumber) {
					return i;
				}
			}
		}

		return 0;
	}

	findPreviousClosestChange(lineNumber: number, inclusive = true): number {
		for (let i = this.changes.length - 1; i >= 0; i--) {
			const change = this.changes[i];

			if (inclusive) {
				if (change.modifiedStartLineNumber <= lineNumber) {
					return i;
				}
			} else {
				if (getModifiedEndLineNumber(change) < lineNumber) {
					return i;
				}
			}
		}

		return this.changes.length - 1;
	}

1084
	dispose(): void {
J
Joao Moreno 已提交
1085
		this.disposables = dispose(this.disposables);
J
Joao Moreno 已提交
1086

J
Joao Moreno 已提交
1087
		this._editorModel = null;
1088
		this._originalModel = null;
J
Joao Moreno 已提交
1089

1090 1091 1092 1093
		if (this.diffDelayer) {
			this.diffDelayer.cancel();
			this.diffDelayer = null;
		}
J
Joao Moreno 已提交
1094 1095 1096

		this.repositoryDisposables.forEach(d => dispose(d));
		this.repositoryDisposables.clear();
1097 1098 1099
	}
}

J
Joao Moreno 已提交
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
class DirtyDiffItem {

	constructor(readonly model: DirtyDiffModel, readonly decorator: DirtyDiffDecorator) { }

	dispose(): void {
		this.decorator.dispose();
		this.model.dispose();
	}
}

export class DirtyDiffWorkbenchController implements ext.IWorkbenchContribution, IModelRegistry {
1111

1112
	private enabled = false;
A
Alex Dima 已提交
1113
	private models: ITextModel[] = [];
J
Joao Moreno 已提交
1114
	private items: { [modelId: string]: DirtyDiffItem; } = Object.create(null);
1115
	private transientDisposables: IDisposable[] = [];
J
Joao Moreno 已提交
1116
	private stylesheet: HTMLStyleElement;
J
Joao Moreno 已提交
1117
	private disposables: IDisposable[] = [];
1118 1119

	constructor(
1120
		@IEditorService private editorService: IEditorService,
1121 1122
		@IInstantiationService private instantiationService: IInstantiationService,
		@IConfigurationService private configurationService: IConfigurationService
1123
	) {
J
Joao Moreno 已提交
1124 1125
		this.stylesheet = createStyleSheet();
		this.disposables.push(toDisposable(() => this.stylesheet.parentElement.removeChild(this.stylesheet)));
1126

J
Joao Moreno 已提交
1127
		const onDidChangeConfiguration = filterEvent(configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('scm.diffDecorations'));
J
Joao Moreno 已提交
1128 1129
		onDidChangeConfiguration(this.onDidChangeConfiguration, this, this.disposables);
		this.onDidChangeConfiguration();
1130

J
Joao Moreno 已提交
1131
		const onDidChangeDiffWidthConfiguration = filterEvent(configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('scm.diffDecorationsGutterWidth'));
1132 1133
		onDidChangeDiffWidthConfiguration(this.onDidChangeDiffWidthConfiguration, this);
		this.onDidChangeDiffWidthConfiguration();
1134 1135
	}

J
Joao Moreno 已提交
1136 1137
	private onDidChangeConfiguration(): void {
		const enabled = this.configurationService.getValue<string>('scm.diffDecorations') !== 'none';
1138 1139 1140 1141 1142 1143 1144 1145

		if (enabled) {
			this.enable();
		} else {
			this.disable();
		}
	}

1146
	private onDidChangeDiffWidthConfiguration(): void {
J
Joao Moreno 已提交
1147
		let width = this.configurationService.getValue<number>('scm.diffDecorationsGutterWidth');
1148 1149 1150 1151 1152

		if (isNaN(width) || width <= 0 || width > 5) {
			width = 3;
		}

J
Joao Moreno 已提交
1153
		this.stylesheet.innerHTML = `.monaco-editor .dirty-diff-modified,.monaco-editor .dirty-diff-added{border-left-width:${width}px;}`;
1154 1155
	}

1156 1157
	private enable(): void {
		if (this.enabled) {
J
Joao Moreno 已提交
1158
			this.disable();
1159
		}
1160

B
Benjamin Pasero 已提交
1161
		this.transientDisposables.push(this.editorService.onDidVisibleEditorsChange(() => this.onEditorsChanged()));
1162 1163 1164
		this.onEditorsChanged();
		this.enabled = true;
	}
1165

1166 1167
	private disable(): void {
		if (!this.enabled) {
1168 1169 1170
			return;
		}

1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
		this.transientDisposables = dispose(this.transientDisposables);
		this.models.forEach(m => this.items[m.id].dispose());
		this.models = [];
		this.items = Object.create(null);
		this.enabled = false;
	}

	// HACK: This is the best current way of figuring out whether to draw these decorations
	// or not. Needs context from the editor, to know whether it is a diff editor, in place editor
	// etc.
	private onEditorsChanged(): void {
1182
		const models = this.editorService.visibleTextEditorWidgets
1183 1184

			// only interested in code editor widgets
A
Alex Dima 已提交
1185
			.filter(c => c instanceof CodeEditorWidget)
1186

J
Joao Moreno 已提交
1187 1188
			// set model registry and map to models
			.map(editor => {
A
Alex Dima 已提交
1189
				const codeEditor = editor as CodeEditorWidget;
J
Joao Moreno 已提交
1190 1191 1192 1193
				const controller = DirtyDiffController.get(codeEditor);
				controller.modelRegistry = this;
				return codeEditor.getModel();
			})
1194 1195

			// remove nulls and duplicates
J
Joao Moreno 已提交
1196
			.filter((m, i, a) => !!m && !!m.uri && a.indexOf(m, i + 1) === -1);
1197

J
Joao Moreno 已提交
1198 1199
		const newModels = models.filter(o => this.models.every(m => o !== m));
		const oldModels = this.models.filter(m => models.every(o => o !== m));
1200 1201

		oldModels.forEach(m => this.onModelInvisible(m));
J
Joao Moreno 已提交
1202
		newModels.forEach(m => this.onModelVisible(m));
1203

J
Joao Moreno 已提交
1204
		this.models = models;
1205 1206
	}

A
Alex Dima 已提交
1207
	private onModelVisible(editorModel: ITextModel): void {
J
Joao Moreno 已提交
1208
		const model = this.instantiationService.createInstance(DirtyDiffModel, editorModel);
J
Joao Moreno 已提交
1209
		const decorator = new DirtyDiffDecorator(editorModel, model, this.configurationService);
J
Joao Moreno 已提交
1210 1211

		this.items[editorModel.id] = new DirtyDiffItem(model, decorator);
1212 1213
	}

A
Alex Dima 已提交
1214
	private onModelInvisible(editorModel: ITextModel): void {
J
Joao Moreno 已提交
1215 1216 1217 1218
		this.items[editorModel.id].dispose();
		delete this.items[editorModel.id];
	}

A
Alex Dima 已提交
1219
	getModel(editorModel: ITextModel): DirtyDiffModel | null {
J
Joao Moreno 已提交
1220 1221 1222 1223 1224 1225 1226
		const item = this.items[editorModel.id];

		if (!item) {
			return null;
		}

		return item.model;
1227 1228 1229
	}

	dispose(): void {
1230
		this.disable();
J
Joao Moreno 已提交
1231
		this.disposables = dispose(this.disposables);
1232 1233
	}
}
B
Benjamin Pasero 已提交
1234

1235 1236
registerEditorContribution(DirtyDiffController);

B
Benjamin Pasero 已提交
1237 1238 1239
registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
	const editorGutterModifiedBackgroundColor = theme.getColor(editorGutterModifiedBackground);
	if (editorGutterModifiedBackgroundColor) {
J
Joao Moreno 已提交
1240
		collector.addRule(`
J
Joao Moreno 已提交
1241
			.monaco-editor .dirty-diff-modified {
J
Joao Moreno 已提交
1242 1243
				border-left: 3px solid ${editorGutterModifiedBackgroundColor};
			}
J
Joao Moreno 已提交
1244
			.monaco-editor .dirty-diff-modified:before {
J
Joao Moreno 已提交
1245 1246 1247
				background: ${editorGutterModifiedBackgroundColor};
			}
		`);
B
Benjamin Pasero 已提交
1248 1249 1250 1251
	}

	const editorGutterAddedBackgroundColor = theme.getColor(editorGutterAddedBackground);
	if (editorGutterAddedBackgroundColor) {
J
Joao Moreno 已提交
1252
		collector.addRule(`
J
Joao Moreno 已提交
1253
			.monaco-editor .dirty-diff-added {
J
Joao Moreno 已提交
1254 1255
				border-left: 3px solid ${editorGutterAddedBackgroundColor};
			}
J
Joao Moreno 已提交
1256
			.monaco-editor .dirty-diff-added:before {
J
Joao Moreno 已提交
1257 1258 1259
				background: ${editorGutterAddedBackgroundColor};
			}
		`);
B
Benjamin Pasero 已提交
1260 1261
	}

1262
	const editorGutteDeletedBackgroundColor = theme.getColor(editorGutterDeletedBackground);
B
Benjamin Pasero 已提交
1263 1264
	if (editorGutteDeletedBackgroundColor) {
		collector.addRule(`
J
Joao Moreno 已提交
1265
			.monaco-editor .dirty-diff-deleted:after {
B
Benjamin Pasero 已提交
1266 1267
				border-left: 4px solid ${editorGutteDeletedBackgroundColor};
			}
J
Joao Moreno 已提交
1268
			.monaco-editor .dirty-diff-deleted:before {
J
Joao Moreno 已提交
1269 1270
				background: ${editorGutteDeletedBackgroundColor};
			}
B
Benjamin Pasero 已提交
1271 1272
		`);
	}
1273
});