changesView.ts 15.7 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

import 'vs/css!./changesView';
import nls = require('vs/nls');
import Platform = require('vs/base/common/platform');
import Lifecycle = require('vs/base/common/lifecycle');
import EventEmitter = require('vs/base/common/eventEmitter');
import Strings = require('vs/base/common/strings');
import Errors = require('vs/base/common/errors');
15
import * as paths from 'vs/base/common/paths';
E
Erich Gamma 已提交
16 17 18 19 20
import WinJS = require('vs/base/common/winjs.base');
import Builder = require('vs/base/browser/builder');
import Keyboard = require('vs/base/browser/keyboardEvent');
import Actions = require('vs/base/common/actions');
import ActionBar = require('vs/base/browser/ui/actionbar/actionbar');
J
Joao Moreno 已提交
21
import Tree = require('vs/base/parts/tree/browser/tree');
E
Erich Gamma 已提交
22
import TreeImpl = require('vs/base/parts/tree/browser/treeImpl');
23
import WorkbenchEvents = require('vs/workbench/common/events');
E
Erich Gamma 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
import git = require('vs/workbench/parts/git/common/git');
import GitView = require('vs/workbench/parts/git/browser/views/view');
import GitActions = require('vs/workbench/parts/git/browser/gitActions');
import GitModel = require('vs/workbench/parts/git/common/gitModel');
import Viewer = require('vs/workbench/parts/git/browser/views/changes/changesViewer');
import GitEditorInputs = require('vs/workbench/parts/git/browser/gitEditorInputs');
import Files = require('vs/workbench/parts/files/common/files');
import {IOutputService} from 'vs/workbench/parts/output/common/output';
import WorkbenchEditorCommon = require('vs/workbench/common/editor');
import InputBox = require('vs/base/browser/ui/inputbox/inputBox');
import Severity from 'vs/base/common/severity';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {IContextViewService} from 'vs/platform/contextview/browser/contextView';
import {IEditorInput} from 'vs/platform/editor/common/editor';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IMessageService} from 'vs/platform/message/common/message';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {ISelection, StructuredSelection} from 'vs/platform/selection/common/selection';
import {IEventService} from 'vs/platform/event/common/event';
import {CommonKeybindings} from 'vs/base/common/keyCodes';
import {IKeyboardEvent} from 'vs/base/browser/dom';

import IGitService = git.IGitService;

var $ = Builder.$;

export class ChangesView extends EventEmitter.EventEmitter implements GitView.IView, GitActions.ICommitState {

	public ID = 'changes';

	private static COMMIT_KEYBINDING = Platform.isMacintosh ? 'Cmd+Enter' : 'Ctrl+Enter';
	private static NEED_MESSAGE = nls.localize('needMessage', "Please provide a commit message. You can always press **{0}** to commit changes. If there are any staged changes, only those will be committed; otherwise, all changes will.", ChangesView.COMMIT_KEYBINDING);
	private static NOTHING_TO_COMMIT = nls.localize('nothingToCommit', "Once there are some changes to commit, type in the commit message and either press **{0}** to commit changes. If there are any staged changes, only those will be committed; otherwise, all changes will.", ChangesView.COMMIT_KEYBINDING);

	private instantiationService: IInstantiationService;
	private editorService: IWorkbenchEditorService;
	private messageService: IMessageService;
	private contextViewService: IContextViewService;
	private contextService: IWorkspaceContextService;
	private gitService: IGitService;
	private outputService: IOutputService;

	private $el: Builder.Builder;
	private $commitView: Builder.Builder;
	private $statusView: Builder.Builder;
	private commitInputBox: InputBox.InputBox;
	private tree: Tree.ITree;

	private visible: boolean;
	private currentDimension: Builder.Dimension;

	private smartCommitAction: GitActions.SmartCommitAction;
	private actions: Actions.IAction[];
	private secondaryActions: Actions.IAction[];
	private actionRunner: Actions.IActionRunner;

	private toDispose: Lifecycle.IDisposable[];

	constructor(actionRunner: Actions.IActionRunner,
		@IInstantiationService instantiationService: IInstantiationService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IMessageService messageService: IMessageService,
		@IContextViewService contextViewService: IContextViewService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IGitService gitService: IGitService,
		@IOutputService outputService: IOutputService,
		@IEventService eventService: IEventService
	) {
		super();

		this.instantiationService = instantiationService;
		this.editorService = editorService;
		this.messageService = messageService;
		this.contextViewService = contextViewService;
		this.contextService = contextService;
		this.gitService = gitService;
		this.outputService = outputService;

		this.visible = false;
		this.currentDimension = null;
		this.actionRunner = actionRunner;

		this.toDispose = [
			this.smartCommitAction = this.instantiationService.createInstance(GitActions.SmartCommitAction, this),
			eventService.addListener2(WorkbenchEvents.EventType.EDITOR_INPUT_CHANGED, (e:WorkbenchEvents.EditorEvent) => this.onEditorInputChanged(e.editorInput).done(null, Errors.onUnexpectedError)),
			this.gitService.addListener2(git.ServiceEvents.OPERATION_START, (e) => this.onGitOperationStart(e)),
			this.gitService.addListener2(git.ServiceEvents.OPERATION_END, (e) => this.onGitOperationEnd(e)),
			this.gitService.getModel().addListener2(git.ModelEvents.MODEL_UPDATED, this.onGitModelUpdate.bind(this))
		];
	}

	// IView

	public get element():HTMLElement {
		this.render();
		return this.$el.getHTMLElement();
	}

	private render(): void {
		if (this.$el) {
			return;
		}

		this.$el = $('.changes-view');
		this.$commitView = $('.commit-view').appendTo(this.$el);

		// Commit view

		this.commitInputBox = new InputBox.InputBox(this.$commitView.getHTMLElement(), this.contextViewService, {
			placeholder: nls.localize('commitMessage', "Message (press {0} to commit)", ChangesView.COMMIT_KEYBINDING),
			validationOptions: {
				showMessage: true,
				validation: (): InputBox.IMessage => null
			},
			flexibleHeight: true
		});

A
Alex Dima 已提交
141 142
		this.commitInputBox.onDidChange((value) => this.emit('change', value));
		this.commitInputBox.onDidHeightChange((value) => this.emit('heightchange', value));
E
Erich Gamma 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

		$(this.commitInputBox.inputElement).on('keydown', (e:KeyboardEvent) => {
			var keyboardEvent = new Keyboard.StandardKeyboardEvent(e);

			if (keyboardEvent.equals(CommonKeybindings.CTRLCMD_ENTER) || keyboardEvent.equals(CommonKeybindings.CTRLCMD_S)) {
				if (this.smartCommitAction.enabled) {
					this.actionRunner.run(this.smartCommitAction).done();
				} else {
					this.commitInputBox.showMessage({ content: ChangesView.NOTHING_TO_COMMIT, formatContent: true, type: InputBox.MessageType.INFO });
				}
			}
		}).on('blur', () => {
			this.commitInputBox.hideMessage();
		});

		// Status view

		this.$statusView = $('.status-view').appendTo(this.$el);

		var actionProvider = this.instantiationService.createInstance(Viewer.ActionProvider);
		var renderer = this.instantiationService.createInstance(Viewer.Renderer, actionProvider, this.actionRunner);
		var dnd = this.instantiationService.createInstance(Viewer.DragAndDrop);
		var controller = this.instantiationService.createInstance(Viewer.Controller, actionProvider);

		this.tree = new TreeImpl.Tree(this.$statusView.getHTMLElement(), {
			dataSource: new Viewer.DataSource(),
			renderer: renderer,
			filter: new Viewer.Filter(),
			sorter: new Viewer.Sorter(),
			dnd: dnd,
			controller: controller
		}, {
			indentPixels: 0,
B
Benjamin Pasero 已提交
176 177
			twistiePixels: 20,
			ariaLabel: nls.localize('treeAriaLabel', "Changes View")
E
Erich Gamma 已提交
178 179 180 181 182 183
		});

		this.tree.setInput(this.gitService.getModel().getStatus());
		this.tree.expandAll(this.gitService.getModel().getStatus().getGroups());

		this.toDispose.push(this.tree.addListener2('selection', (e) => this.onSelection(e)));
A
Alex Dima 已提交
184
		this.toDispose.push(this.commitInputBox.onDidHeightChange(() => this.layout()));
E
Erich Gamma 已提交
185 186 187 188 189
	}

	public focus():void {
		var selection = this.tree.getSelection();
		if (selection.length > 0) {
J
Joao Moreno 已提交
190
			this.tree.reveal(selection[0], 0.5).done(null, Errors.onUnexpectedError);
E
Erich Gamma 已提交
191 192 193 194 195 196 197 198 199 200 201 202
		}

		this.commitInputBox.focus();
	}

	public layout(dimension:Builder.Dimension = this.currentDimension):void {
		if (!dimension) {
			return;
		}

		this.currentDimension = dimension;

203
		this.commitInputBox.layout();
204
		var statusViewHeight = dimension.height - (this.commitInputBox.height + 12 /* margin */);
E
Erich Gamma 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
		this.$statusView.size(dimension.width, statusViewHeight);
		this.tree.layout(statusViewHeight);

		if (this.commitInputBox.height === 134) {
			this.$commitView.addClass('scroll');
		} else {
			this.$commitView.removeClass('scroll');
		}
	}

	public setVisible(visible:boolean): WinJS.TPromise<void> {
		this.visible = visible;

		if (visible) {
			this.tree.onVisible();
			return this.onEditorInputChanged(this.editorService.getActiveEditorInput());

		} else {
			this.tree.onHidden();
			return WinJS.Promise.as(null);
		}
	}

	public getSelection():ISelection {
		return new StructuredSelection(this.tree.getSelection());
	}

	public getControl(): Tree.ITree {
		return this.tree;
	}

	public getActions(): Actions.IAction[] {
		if (!this.actions) {
			this.actions = [
				this.smartCommitAction,
				this.instantiationService.createInstance(GitActions.RefreshAction)
			];

			this.actions.forEach(a => this.toDispose.push(a));
		}

		return this.actions;
	}

	public getSecondaryActions(): Actions.IAction[] {
		if (!this.secondaryActions) {
			this.secondaryActions = [
252
				this.instantiationService.createInstance(GitActions.SyncAction, GitActions.SyncAction.ID, GitActions.SyncAction.LABEL),
J
Joao Moreno 已提交
253 254
				this.instantiationService.createInstance(GitActions.PullAction, GitActions.PullAction.ID, GitActions.PullAction.LABEL),
				this.instantiationService.createInstance(GitActions.PullWithRebaseAction),
J
Joao Moreno 已提交
255
				this.instantiationService.createInstance(GitActions.PushAction, GitActions.PushAction.ID, GitActions.PushAction.LABEL),
E
Erich Gamma 已提交
256
				new ActionBar.Separator(),
J
Joao Moreno 已提交
257
				this.instantiationService.createInstance(GitActions.PublishAction, GitActions.PublishAction.ID, GitActions.PublishAction.LABEL),
J
Joao Moreno 已提交
258
				new ActionBar.Separator(),
E
Erich Gamma 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
				this.instantiationService.createInstance(GitActions.CommitAction, this),
				this.instantiationService.createInstance(GitActions.StageAndCommitAction, this),
				this.instantiationService.createInstance(GitActions.UndoLastCommitAction),
				new ActionBar.Separator(),
				this.instantiationService.createInstance(GitActions.GlobalUnstageAction),
				this.instantiationService.createInstance(GitActions.GlobalUndoAction),
				new ActionBar.Separator(),
				new Actions.Action('show.gitOutput', nls.localize('showOutput', "Show Git Output"), null, true, () => this.outputService.showOutput('Git'))
			];

			this.secondaryActions.forEach(a => this.toDispose.push(a));
		}

		return this.secondaryActions;
	}

	// ICommitState

	public getCommitMessage(): string {
		return Strings.trim(this.commitInputBox.value);
	}

	public onEmptyCommitMessage(): void {
		this.commitInputBox.focus();
		this.commitInputBox.showMessage({ content: ChangesView.NEED_MESSAGE, formatContent: true, type: InputBox.MessageType.INFO });
	}

	// Events

	private onGitModelUpdate(): void {
		if (this.tree) {
			this.tree.refresh().done(() => {
				return this.tree.expandAll(this.gitService.getModel().getStatus().getGroups());
			});
		}
	}

	private onEditorInputChanged(input: IEditorInput): WinJS.Promise {
		if (!this.tree) {
			return WinJS.Promise.as(null);
		}

		var status = this.getStatusFromInput(input);

		if (!status) {
			this.tree.clearSelection();
			this.tree.clearFocus();
		}

		if (this.visible && this.tree.getSelection().indexOf(status) === -1) {
			return this.tree.reveal(status, 0.5).then(() => {
				this.tree.setSelection([status], { origin: 'implicit' });
				this.tree.setFocus(status);
			});
		}

		return WinJS.Promise.as(null);
	}

	private onSelection(e: Tree.ISelectionEvent): void {
		if (e.payload && e.payload && e.payload.origin === 'implicit') {
			return;
		}

		if (e.selection.length !== 1) {
			return;
		}

		var element = e.selection[0];

		if (!(element instanceof GitModel.FileStatus)) {
			return;
		}

333
		if (e.payload && e.payload.origin === 'keyboard' && !(<IKeyboardEvent>e.payload.originalEvent).equals(CommonKeybindings.ENTER)) {
E
Erich Gamma 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
			return;
		}

		var isMouseOrigin = e.payload && (e.payload.origin === 'mouse');

		if (isMouseOrigin && (e.payload.originalEvent.metaKey || e.payload.originalEvent.shiftKey)) {
			return;
		}

		var status = <git.IFileStatus> element;

		this.gitService.getInput(status).done((input) => {
			var options = new WorkbenchEditorCommon.TextDiffEditorOptions();

			if (isMouseOrigin) {
				options.preserveFocus = true;

				var originalEvent:MouseEvent = e && e.payload && e.payload.origin === 'mouse' && e.payload.originalEvent;
				if (originalEvent && originalEvent.detail === 2) {
					options.preserveFocus = false;
					originalEvent.preventDefault(); // focus moves to editor, we need to prevent default
				}
			}

			options.forceOpen = true;

			var sideBySide = (e && e.payload && e.payload.originalEvent && e.payload.originalEvent.altKey);

			return this.editorService.openEditor(input, options, sideBySide);
		}, (e) => {
			if (e.gitErrorCode === git.GitErrorCodes.CantOpenResource) {
				this.messageService.show(Severity.Warning, e);
				return;
			}

			this.messageService.show(Severity.Error, e);
		});
	}

	private onGitOperationStart(operation: git.IGitOperation): void {
		if (operation.id === git.ServiceOperations.COMMIT) {
			if (this.commitInputBox) {
				this.commitInputBox.disable();
			}
		}
	}

	private onGitOperationEnd(e: { operation: git.IGitOperation; error: any; }): void {
		if (e.operation.id === git.ServiceOperations.COMMIT) {
			if (this.commitInputBox) {
				this.commitInputBox.enable();

				if (!e.error) {
					this.commitInputBox.value = '';
				}
			}
		}
	}

	// Misc

	private getStatusFromInput(input: IEditorInput): git.IFileStatus {
		if (!input) {
			return null;
		}

		if (input instanceof GitEditorInputs.GitDiffEditorInput) {
			return (<GitEditorInputs.GitDiffEditorInput> input).getFileStatus();
A
Alex Dima 已提交
402
		}
E
Erich Gamma 已提交
403 404 405

		if (input instanceof GitEditorInputs.NativeGitIndexStringEditorInput) {
			return (<GitEditorInputs.NativeGitIndexStringEditorInput> input).getFileStatus() || null;
A
Alex Dima 已提交
406
		}
E
Erich Gamma 已提交
407 408

		if (input instanceof Files.FileEditorInput) {
409 410
			const fileInput = <Files.FileEditorInput> input;
			const resource = fileInput.getResource();
E
Erich Gamma 已提交
411

412
			const workspaceRoot = this.contextService.getWorkspace().resource.fsPath;
J
npe  
Joao Moreno 已提交
413
			if (!workspaceRoot || !paths.isEqualOrParent(resource.fsPath, workspaceRoot)) {
E
Erich Gamma 已提交
414 415 416
				return null; // out of workspace not yet supported
			}

417
			const repositoryRoot = this.gitService.getModel().getRepositoryRoot();
J
npe  
Joao Moreno 已提交
418
			if (!repositoryRoot || !paths.isEqualOrParent(resource.fsPath, repositoryRoot)) {
419 420 421 422 423 424
				return null; // out of repository not supported
			}

			const repositoryRelativePath = paths.normalize(paths.relative(repositoryRoot, resource.fsPath));

			var status = this.gitService.getModel().getStatus().getWorkingTreeStatus().find(repositoryRelativePath);
E
Erich Gamma 已提交
425 426 427 428
			if (status && (status.getStatus() === git.Status.UNTRACKED || status.getStatus() === git.Status.IGNORED)) {
				return status;
			}

429
			status = this.gitService.getModel().getStatus().getMergeStatus().find(repositoryRelativePath);
E
Erich Gamma 已提交
430 431 432
			if (status) {
				return status;
			}
A
Alex Dima 已提交
433
		}
E
Erich Gamma 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448

		return null;
	}

	public dispose(): void {
		if (this.$el) {
			this.$el.dispose();
			this.$el = null;
		}

		this.toDispose = Lifecycle.disposeAll(this.toDispose);

		super.dispose();
	}
}