repositoryPane.ts 49.4 KB
Newer Older
J
Joao Moreno 已提交
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/scmViewlet';
J
Joao Moreno 已提交
7
import { Event, Emitter } from 'vs/base/common/event';
J
João Moreno 已提交
8
import { basename, dirname, isEqual } from 'vs/base/common/resources';
9
import { IDisposable, Disposable, DisposableStore, combinedDisposable } from 'vs/base/common/lifecycle';
S
SteVen Batten 已提交
10
import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer';
J
Joao Moreno 已提交
11
import { append, $, addClass, toggleClass, trackFocus, removeClass } from 'vs/base/browser/dom';
12
import { IListVirtualDelegate, IIdentityProvider } from 'vs/base/browser/ui/list/list';
J
Joao Moreno 已提交
13
import { ISCMRepository, ISCMResourceGroup, ISCMResource, InputValidationType } from 'vs/workbench/contrib/scm/common/scm';
J
Joao Moreno 已提交
14 15 16 17 18 19 20 21 22
import { ResourceLabels, IResourceLabel } from 'vs/workbench/browser/labels';
import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { MenuItemAction, IMenuService } from 'vs/platform/actions/common/actions';
J
Joao Moreno 已提交
23
import { IAction, IActionViewItem, ActionRunner, Action } from 'vs/base/common/actions';
J
Joao Moreno 已提交
24 25 26
import { ContextAwareMenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { SCMMenus } from './menus';
import { ActionBar, IActionViewItemProvider } from 'vs/base/browser/ui/actionbar/actionbar';
27
import { IThemeService, LIGHT, registerThemingParticipant, IFileIconTheme } from 'vs/platform/theme/common/themeService';
J
Joao Moreno 已提交
28
import { isSCMResource, isSCMResourceGroup, connectPrimaryMenuToInlineActionBar } from './util';
J
Joao Moreno 已提交
29
import { attachBadgeStyler } from 'vs/platform/theme/common/styler';
J
João Moreno 已提交
30
import { WorkbenchCompressibleObjectTree, TreeResourceNavigator, IOpenEvent } from 'vs/platform/list/browser/listService';
J
João Moreno 已提交
31
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
J
Joao Moreno 已提交
32
import { disposableTimeout, ThrottledDelayer } from 'vs/base/common/async';
J
Joao Moreno 已提交
33
import { INotificationService } from 'vs/platform/notification/common/notification';
34
import { ITreeNode, ITreeFilter, ITreeSorter, ITreeContextMenuEvent } from 'vs/base/browser/ui/tree/tree';
35
import { ResourceTree, IResourceNode } from 'vs/base/common/resourceTree';
36
import { ISequence, ISplice } from 'vs/base/common/sequence';
J
Joao Moreno 已提交
37
import { ICompressibleTreeRenderer, ICompressibleKeyboardNavigationLabelProvider } from 'vs/base/browser/ui/tree/objectTree';
J
João Moreno 已提交
38
import { Iterable } from 'vs/base/common/iterator';
J
Joao Moreno 已提交
39 40 41 42
import { ICompressedTreeNode, ICompressedTreeElement } from 'vs/base/browser/ui/tree/compressedObjectTreeModel';
import { URI } from 'vs/base/common/uri';
import { FileKind } from 'vs/platform/files/common/files';
import { compareFileNames } from 'vs/base/common/comparers';
43
import { FuzzyScore, createMatches, IMatch } from 'vs/base/common/filters';
44
import { IViewDescriptor, IViewDescriptorService } from 'vs/workbench/common/views';
J
Joao Moreno 已提交
45
import { localize } from 'vs/nls';
J
Joao Moreno 已提交
46
import { flatten, find } from 'vs/base/common/arrays';
J
Joao Moreno 已提交
47
import { memoize } from 'vs/base/common/decorators';
J
Joao Moreno 已提交
48
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
J
Joao Moreno 已提交
49
import { toResource, SideBySideEditor } from 'vs/workbench/common/editor';
J
Joao Moreno 已提交
50
import { SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme';
J
Joao Moreno 已提交
51
import { Hasher } from 'vs/base/common/hash';
J
Joao Moreno 已提交
52 53 54 55 56
import { CodeEditorWidget, ICodeEditorWidgetOptions } from 'vs/editor/browser/widget/codeEditorWidget';
import { ITextModel } from 'vs/editor/common/model';
import { IEditorConstructionOptions } from 'vs/editor/common/config/editorOptions';
import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions';
import { IModelService } from 'vs/editor/common/services/modelService';
J
Joao Moreno 已提交
57 58 59 60
import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions';
import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer';
import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard';
import { ContextMenuController } from 'vs/editor/contrib/contextmenu/contextmenu';
S
Sandeep Somavarapu 已提交
61
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
J
Joao Moreno 已提交
62 63
import * as platform from 'vs/base/common/platform';
import { format } from 'vs/base/common/strings';
J
Joao Moreno 已提交
64
import { inputPlaceholderForeground, inputValidationInfoBorder, inputValidationWarningBorder, inputValidationErrorBorder, inputValidationInfoBackground, inputValidationInfoForeground, inputValidationWarningBackground, inputValidationWarningForeground, inputValidationErrorBackground, inputValidationErrorForeground, inputBackground, inputForeground, inputBorder, focusBorder } from 'vs/platform/theme/common/colorRegistry';
65 66
import { SuggestController } from 'vs/editor/contrib/suggest/suggestController';
import { SnippetController2 } from 'vs/editor/contrib/snippet/snippetController2';
67
import { Schemas } from 'vs/base/common/network';
J
Joao Moreno 已提交
68
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
J
jeanp413 已提交
69 70 71
import { ModesHoverController } from 'vs/editor/contrib/hover/hover';
import { ColorDetector } from 'vs/editor/contrib/colorPicker/colorDetector';
import { LinkDetector } from 'vs/editor/contrib/links/links';
72
import { IOpenerService } from 'vs/platform/opener/common/opener';
73
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
J
João Moreno 已提交
74
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
J
João Moreno 已提交
75
import { IModeService } from 'vs/editor/common/services/modeService';
J
João Moreno 已提交
76
import { ILabelService } from 'vs/platform/label/common/label';
J
Joao Moreno 已提交
77

78
type TreeElement = ISCMResourceGroup | IResourceNode<ISCMResource, ISCMResourceGroup> | ISCMResource;
J
Joao Moreno 已提交
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
function splitMatches(uri: URI, filterData: FuzzyScore | undefined): [IMatch[] | undefined, IMatch[] | undefined] {
	let matches: IMatch[] | undefined;
	let descriptionMatches: IMatch[] | undefined;

	if (filterData) {
		matches = [];
		descriptionMatches = [];

		const fileName = basename(uri);
		const allMatches = createMatches(filterData);

		for (const match of allMatches) {
			if (match.end <= fileName.length) {
				matches!.push(match);
			} else {
				descriptionMatches!.push(
					{
						start: match.start - fileName.length,
						end: match.end - fileName.length
					}
				);
			}
		}
	}

	return [matches, descriptionMatches];
}

J
Joao Moreno 已提交
108
interface ResourceGroupTemplate {
J
Joao Moreno 已提交
109 110 111
	readonly name: HTMLElement;
	readonly count: CountBadge;
	readonly actionBar: ActionBar;
J
Joao Moreno 已提交
112
	elementDisposables: IDisposable;
J
Joao Moreno 已提交
113
	readonly disposables: IDisposable;
J
Joao Moreno 已提交
114 115 116 117
}

class ResourceGroupRenderer implements ICompressibleTreeRenderer<ISCMResourceGroup, FuzzyScore, ResourceGroupTemplate> {

118
	static readonly TEMPLATE_ID = 'resource group';
J
Joao Moreno 已提交
119 120 121 122 123 124 125 126 127
	get templateId(): string { return ResourceGroupRenderer.TEMPLATE_ID; }

	constructor(
		private actionViewItemProvider: IActionViewItemProvider,
		private themeService: IThemeService,
		private menus: SCMMenus
	) { }

	renderTemplate(container: HTMLElement): ResourceGroupTemplate {
128 129 130
		// hack
		addClass(container.parentElement!.parentElement!.querySelector('.monaco-tl-twistie')! as HTMLElement, 'force-twistie');

J
Joao Moreno 已提交
131 132 133 134 135 136 137
		const element = append(container, $('.resource-group'));
		const name = append(element, $('.name'));
		const actionsContainer = append(element, $('.actions'));
		const actionBar = new ActionBar(actionsContainer, { actionViewItemProvider: this.actionViewItemProvider });
		const countContainer = append(element, $('.count'));
		const count = new CountBadge(countContainer);
		const styler = attachBadgeStyler(count, this.themeService);
J
Joao Moreno 已提交
138 139
		const elementDisposables = Disposable.None;
		const disposables = combinedDisposable(actionBar, styler);
J
Joao Moreno 已提交
140

J
Joao Moreno 已提交
141
		return { name, count, actionBar, elementDisposables, disposables };
J
Joao Moreno 已提交
142 143 144
	}

	renderElement(node: ITreeNode<ISCMResourceGroup, FuzzyScore>, index: number, template: ResourceGroupTemplate): void {
J
Joao Moreno 已提交
145
		template.elementDisposables.dispose();
J
Joao Moreno 已提交
146 147 148 149 150

		const group = node.element;
		template.name.textContent = group.label;
		template.actionBar.clear();
		template.actionBar.context = group;
J
Joao Moreno 已提交
151
		template.count.setCount(group.elements.length);
J
Joao Moreno 已提交
152 153 154 155

		const disposables = new DisposableStore();
		disposables.add(connectPrimaryMenuToInlineActionBar(this.menus.getResourceGroupMenu(group), template.actionBar));

J
Joao Moreno 已提交
156
		template.elementDisposables = disposables;
J
Joao Moreno 已提交
157 158 159 160 161 162 163
	}

	renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ISCMResourceGroup>, FuzzyScore>, index: number, templateData: ResourceGroupTemplate, height: number | undefined): void {
		throw new Error('Should never happen since node is incompressible');
	}

	disposeElement(group: ITreeNode<ISCMResourceGroup, FuzzyScore>, index: number, template: ResourceGroupTemplate): void {
J
Joao Moreno 已提交
164
		template.elementDisposables.dispose();
J
Joao Moreno 已提交
165 166 167
	}

	disposeTemplate(template: ResourceGroupTemplate): void {
J
Joao Moreno 已提交
168
		template.elementDisposables.dispose();
J
Joao Moreno 已提交
169
		template.disposables.dispose();
J
Joao Moreno 已提交
170 171 172 173 174 175 176 177 178
	}
}

interface ResourceTemplate {
	element: HTMLElement;
	name: HTMLElement;
	fileLabel: IResourceLabel;
	decorationIcon: HTMLElement;
	actionBar: ActionBar;
J
Joao Moreno 已提交
179 180
	elementDisposables: IDisposable;
	disposables: IDisposable;
J
Joao Moreno 已提交
181 182
}

J
Joao Moreno 已提交
183
class RepositoryPaneActionRunner extends ActionRunner {
J
Joao Moreno 已提交
184

J
João Moreno 已提交
185
	constructor(private getSelectedResources: () => (ISCMResource | IResourceNode<ISCMResource, ISCMResourceGroup>)[]) {
J
Joao Moreno 已提交
186 187 188
		super();
	}

J
Joao Moreno 已提交
189
	async runAction(action: IAction, context: ISCMResource | IResourceNode<ISCMResource, ISCMResourceGroup>): Promise<any> {
J
Joao Moreno 已提交
190 191 192 193 194
		if (!(action instanceof MenuItemAction)) {
			return super.runAction(action, context);
		}

		const selection = this.getSelectedResources();
195 196
		const contextIsSelected = selection.some(s => s === context);
		const actualContext = contextIsSelected ? selection : [context];
197
		const args = flatten(actualContext.map(e => ResourceTree.isResourceNode(e) ? ResourceTree.collect(e) : [e]));
J
Joao Moreno 已提交
198
		await action.run(...args);
J
Joao Moreno 已提交
199 200 201
	}
}

202
class ResourceRenderer implements ICompressibleTreeRenderer<ISCMResource | IResourceNode<ISCMResource, ISCMResourceGroup>, FuzzyScore, ResourceTemplate> {
J
Joao Moreno 已提交
203

204
	static readonly TEMPLATE_ID = 'resource';
J
Joao Moreno 已提交
205 206 207
	get templateId(): string { return ResourceRenderer.TEMPLATE_ID; }

	constructor(
J
Joao Moreno 已提交
208
		private viewModelProvider: () => ViewModel,
J
Joao Moreno 已提交
209 210
		private labels: ResourceLabels,
		private actionViewItemProvider: IActionViewItemProvider,
J
João Moreno 已提交
211
		private actionRunner: ActionRunner,
J
Joao Moreno 已提交
212 213 214 215 216 217 218
		private themeService: IThemeService,
		private menus: SCMMenus
	) { }

	renderTemplate(container: HTMLElement): ResourceTemplate {
		const element = append(container, $('.resource'));
		const name = append(element, $('.name'));
219
		const fileLabel = this.labels.create(name, { supportDescriptionHighlights: true, supportHighlights: true });
J
Joao Moreno 已提交
220 221 222
		const actionsContainer = append(fileLabel.element, $('.actions'));
		const actionBar = new ActionBar(actionsContainer, {
			actionViewItemProvider: this.actionViewItemProvider,
J
João Moreno 已提交
223
			actionRunner: this.actionRunner
J
Joao Moreno 已提交
224 225 226
		});

		const decorationIcon = append(element, $('.decoration-icon'));
J
Joao Moreno 已提交
227
		const disposables = combinedDisposable(actionBar, fileLabel);
J
Joao Moreno 已提交
228

J
Joao Moreno 已提交
229
		return { element, name, fileLabel, decorationIcon, actionBar, elementDisposables: Disposable.None, disposables };
J
Joao Moreno 已提交
230 231
	}

232
	renderElement(node: ITreeNode<ISCMResource, FuzzyScore> | ITreeNode<ISCMResource | IResourceNode<ISCMResource, ISCMResourceGroup>, FuzzyScore>, index: number, template: ResourceTemplate): void {
J
Joao Moreno 已提交
233
		template.elementDisposables.dispose();
J
Joao Moreno 已提交
234

J
Joao Moreno 已提交
235
		const elementDisposables = new DisposableStore();
J
Joao Moreno 已提交
236
		const resourceOrFolder = node.element;
M
Martin Aeschlimann 已提交
237
		const theme = this.themeService.getColorTheme();
J
Joao Moreno 已提交
238 239
		const iconResource = ResourceTree.isResourceNode(resourceOrFolder) ? resourceOrFolder.element : resourceOrFolder;
		const icon = iconResource && (theme.type === LIGHT ? iconResource.decorations.icon : iconResource.decorations.iconDark);
J
Joao Moreno 已提交
240

241 242
		const uri = ResourceTree.isResourceNode(resourceOrFolder) ? resourceOrFolder.uri : resourceOrFolder.sourceUri;
		const fileKind = ResourceTree.isResourceNode(resourceOrFolder) ? FileKind.FOLDER : FileKind.FILE;
J
Joao Moreno 已提交
243 244
		const viewModel = this.viewModelProvider();

245
		const [matches, descriptionMatches] = splitMatches(uri, node.filterData);
J
Joao Moreno 已提交
246 247
		template.fileLabel.setFile(uri, {
			fileDecorations: { colors: false, badges: !icon },
J
Joao Moreno 已提交
248
			hidePath: viewModel.mode === ViewModelMode.Tree,
J
Joao Moreno 已提交
249
			fileKind,
250 251
			matches,
			descriptionMatches
J
Joao Moreno 已提交
252
		});
J
Joao Moreno 已提交
253

J
Joao Moreno 已提交
254
		template.actionBar.clear();
J
Joao Moreno 已提交
255
		template.actionBar.context = resourceOrFolder;
J
Joao Moreno 已提交
256

257
		if (ResourceTree.isResourceNode(resourceOrFolder)) {
J
Joao Moreno 已提交
258 259 260 261 262 263 264 265 266
			if (resourceOrFolder.element) {
				elementDisposables.add(connectPrimaryMenuToInlineActionBar(this.menus.getResourceMenu(resourceOrFolder.element.resourceGroup), template.actionBar));
				toggleClass(template.name, 'strike-through', resourceOrFolder.element.decorations.strikeThrough);
				toggleClass(template.element, 'faded', resourceOrFolder.element.decorations.faded);
			} else {
				elementDisposables.add(connectPrimaryMenuToInlineActionBar(this.menus.getResourceFolderMenu(resourceOrFolder.context), template.actionBar));
				removeClass(template.name, 'strike-through');
				removeClass(template.element, 'faded');
			}
J
Joao Moreno 已提交
267
		} else {
J
Joao Moreno 已提交
268 269 270
			elementDisposables.add(connectPrimaryMenuToInlineActionBar(this.menus.getResourceMenu(resourceOrFolder.resourceGroup), template.actionBar));
			toggleClass(template.name, 'strike-through', resourceOrFolder.decorations.strikeThrough);
			toggleClass(template.element, 'faded', resourceOrFolder.decorations.faded);
J
Joao Moreno 已提交
271 272
		}

273
		const tooltip = !ResourceTree.isResourceNode(resourceOrFolder) && resourceOrFolder.decorations.tooltip || '';
J
Joao Moreno 已提交
274 275 276 277 278 279 280 281

		if (icon) {
			template.decorationIcon.style.display = '';
			template.decorationIcon.style.backgroundImage = `url('${icon}')`;
			template.decorationIcon.title = tooltip;
		} else {
			template.decorationIcon.style.display = 'none';
			template.decorationIcon.style.backgroundImage = '';
J
Joao Moreno 已提交
282
			template.decorationIcon.title = '';
J
Joao Moreno 已提交
283 284 285
		}

		template.element.setAttribute('data-tooltip', tooltip);
J
Joao Moreno 已提交
286
		template.elementDisposables = elementDisposables;
J
Joao Moreno 已提交
287 288
	}

289
	disposeElement(resource: ITreeNode<ISCMResource, FuzzyScore> | ITreeNode<IResourceNode<ISCMResource, ISCMResourceGroup>, FuzzyScore>, index: number, template: ResourceTemplate): void {
J
Joao Moreno 已提交
290
		template.elementDisposables.dispose();
J
Joao Moreno 已提交
291
	}
J
Joao Moreno 已提交
292

293
	renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ISCMResource> | ICompressedTreeNode<IResourceNode<ISCMResource, ISCMResourceGroup>>, FuzzyScore>, index: number, template: ResourceTemplate, height: number | undefined): void {
J
Joao Moreno 已提交
294 295 296
		template.elementDisposables.dispose();

		const elementDisposables = new DisposableStore();
297
		const compressed = node.element as ICompressedTreeNode<IResourceNode<ISCMResource, ISCMResourceGroup>>;
J
Joao Moreno 已提交
298
		const folder = compressed.elements[compressed.elements.length - 1];
J
Joao Moreno 已提交
299 300 301

		const label = compressed.elements.map(e => e.name).join('/');
		const fileKind = FileKind.FOLDER;
J
Joao Moreno 已提交
302

303
		const [matches, descriptionMatches] = splitMatches(folder.uri, node.filterData);
J
Joao Moreno 已提交
304
		template.fileLabel.setResource({ resource: folder.uri, name: label }, {
J
Joao Moreno 已提交
305 306
			fileDecorations: { colors: false, badges: true },
			fileKind,
307 308
			matches,
			descriptionMatches
J
Joao Moreno 已提交
309
		});
J
Joao Moreno 已提交
310

J
Joao Moreno 已提交
311
		template.actionBar.clear();
J
Joao Moreno 已提交
312
		template.actionBar.context = folder;
J
Joao Moreno 已提交
313

J
Joao Moreno 已提交
314
		elementDisposables.add(connectPrimaryMenuToInlineActionBar(this.menus.getResourceFolderMenu(folder.context), template.actionBar));
J
Joao Moreno 已提交
315

J
Joao Moreno 已提交
316 317
		removeClass(template.name, 'strike-through');
		removeClass(template.element, 'faded');
J
Joao Moreno 已提交
318 319 320
		template.decorationIcon.style.display = 'none';
		template.decorationIcon.style.backgroundImage = '';

J
Joao Moreno 已提交
321 322
		template.element.setAttribute('data-tooltip', '');
		template.elementDisposables = elementDisposables;
J
Joao Moreno 已提交
323 324
	}

325
	disposeCompressedElements(node: ITreeNode<ICompressedTreeNode<ISCMResource> | ICompressedTreeNode<IResourceNode<ISCMResource, ISCMResourceGroup>>, FuzzyScore>, index: number, template: ResourceTemplate, height: number | undefined): void {
J
Joao Moreno 已提交
326
		template.elementDisposables.dispose();
J
Joao Moreno 已提交
327 328 329
	}

	disposeTemplate(template: ResourceTemplate): void {
J
Joao Moreno 已提交
330 331
		template.elementDisposables.dispose();
		template.disposables.dispose();
J
Joao Moreno 已提交
332 333 334 335 336 337 338 339
	}
}

class ProviderListDelegate implements IListVirtualDelegate<TreeElement> {

	getHeight() { return 22; }

	getTemplateId(element: TreeElement) {
340
		if (ResourceTree.isResourceNode(element) || isSCMResource(element)) {
J
Joao Moreno 已提交
341 342 343 344 345 346 347 348 349 350
			return ResourceRenderer.TEMPLATE_ID;
		} else {
			return ResourceGroupRenderer.TEMPLATE_ID;
		}
	}
}

class SCMTreeFilter implements ITreeFilter<TreeElement> {

	filter(element: TreeElement): boolean {
351
		if (ResourceTree.isResourceNode(element)) {
J
Joao Moreno 已提交
352 353 354 355 356 357 358 359 360 361 362
			return true;
		} else if (isSCMResourceGroup(element)) {
			return element.elements.length > 0 || !element.hideWhenEmpty;
		} else {
			return true;
		}
	}
}

export class SCMTreeSorter implements ITreeSorter<TreeElement> {

J
Joao Moreno 已提交
363 364 365 366 367
	@memoize
	private get viewModel(): ViewModel { return this.viewModelProvider(); }

	constructor(private viewModelProvider: () => ViewModel) { }

J
Joao Moreno 已提交
368
	compare(one: TreeElement, other: TreeElement): number {
J
Joao Moreno 已提交
369 370 371 372
		if (this.viewModel.mode === ViewModelMode.List) {
			return 0;
		}

J
Joao Moreno 已提交
373 374 375 376
		if (isSCMResourceGroup(one) && isSCMResourceGroup(other)) {
			return 0;
		}

377 378
		const oneIsDirectory = ResourceTree.isResourceNode(one);
		const otherIsDirectory = ResourceTree.isResourceNode(other);
J
Joao Moreno 已提交
379 380 381 382 383

		if (oneIsDirectory !== otherIsDirectory) {
			return oneIsDirectory ? -1 : 1;
		}

384 385
		const oneName = ResourceTree.isResourceNode(one) ? one.name : basename((one as ISCMResource).sourceUri);
		const otherName = ResourceTree.isResourceNode(other) ? other.name : basename((other as ISCMResource).sourceUri);
J
Joao Moreno 已提交
386 387 388 389 390

		return compareFileNames(oneName, otherName);
	}
}

391
export class SCMTreeKeyboardNavigationLabelProvider implements ICompressibleKeyboardNavigationLabelProvider<TreeElement> {
J
Joao Moreno 已提交
392

393 394
	constructor(@ILabelService private readonly labelService: ILabelService) { }

J
Joao Moreno 已提交
395
	getKeyboardNavigationLabel(element: TreeElement): { toString(): string; } | undefined {
396
		if (ResourceTree.isResourceNode(element)) {
397 398
			return element.name;
		} else if (isSCMResourceGroup(element)) {
J
Joao Moreno 已提交
399
			return element.label;
400
		} else {
401 402 403 404 405 406
			// Since a match in the file name takes precedence over a match
			// in the folder name we are returning the label as file/folder.
			const fileName = basename(element.sourceUri);
			const filePath = this.labelService.getUriLabel(dirname(element.sourceUri), { relative: true });

			return filePath.length !== 0 ? `${fileName}${filePath}` : fileName;
J
Joao Moreno 已提交
407
		}
408
	}
J
Joao Moreno 已提交
409

410
	getCompressedNodeKeyboardNavigationLabel(elements: TreeElement[]): { toString(): string | undefined; } | undefined {
411
		const folders = elements as IResourceNode<ISCMResource, ISCMResourceGroup>[];
412
		return folders.map(e => e.name).join('/');
J
Joao Moreno 已提交
413 414 415
	}
}

J
Joao Moreno 已提交
416 417 418
class SCMResourceIdentityProvider implements IIdentityProvider<TreeElement> {

	getId(element: TreeElement): string {
419
		if (ResourceTree.isResourceNode(element)) {
J
Joao Moreno 已提交
420 421 422 423
			const group = element.context;
			return `${group.provider.contextValue}/${group.id}/$FOLDER/${element.uri.toString()}`;
		} else if (isSCMResource(element)) {
			const group = element.resourceGroup;
J
Joao Moreno 已提交
424
			const provider = group.provider;
J
Joao Moreno 已提交
425
			return `${provider.contextValue}/${group.id}/${element.sourceUri.toString()}`;
J
Joao Moreno 已提交
426
		} else {
J
Joao Moreno 已提交
427 428
			const provider = element.provider;
			return `${provider.contextValue}/${element.id}`;
J
Joao Moreno 已提交
429 430
		}
	}
J
Joao Moreno 已提交
431
}
J
Joao Moreno 已提交
432

J
João Moreno 已提交
433
export class SCMAccessibilityProvider implements IListAccessibilityProvider<TreeElement> {
J
João Moreno 已提交
434

J
João Moreno 已提交
435 436
	constructor(@ILabelService private readonly labelService: ILabelService) { }

437 438 439 440
	getWidgetAriaLabel(): string {
		return localize('scm', "Source Control Management");
	}

J
João Moreno 已提交
441 442
	getAriaLabel(element: TreeElement): string {
		if (ResourceTree.isResourceNode(element)) {
J
João Moreno 已提交
443
			return this.labelService.getUriLabel(element.uri, { relative: true, noPrefix: true }) || element.name;
J
João Moreno 已提交
444 445 446
		} else if (isSCMResourceGroup(element)) {
			return element.label;
		} else {
J
João Moreno 已提交
447 448
			const result: string[] = [];

I
isidor 已提交
449 450
			result.push(basename(element.sourceUri));

J
João Moreno 已提交
451 452 453 454 455 456 457 458 459 460 461
			if (element.decorations.tooltip) {
				result.push(element.decorations.tooltip);
			}

			const path = this.labelService.getUriLabel(dirname(element.sourceUri), { relative: true, noPrefix: true });

			if (path) {
				result.push(path);
			}

			return result.join(', ');
J
João Moreno 已提交
462 463 464 465
		}
	}
}

J
Joao Moreno 已提交
466 467 468
interface IGroupItem {
	readonly group: ISCMResourceGroup;
	readonly resources: ISCMResource[];
J
Joao Moreno 已提交
469
	readonly tree: ResourceTree<ISCMResource, ISCMResourceGroup>;
J
Joao Moreno 已提交
470 471 472
	readonly disposable: IDisposable;
}

J
Joao Moreno 已提交
473 474
function groupItemAsTreeElement(item: IGroupItem, mode: ViewModelMode): ICompressedTreeElement<TreeElement> {
	const children = mode === ViewModelMode.List
J
João Moreno 已提交
475 476
		? Iterable.map(item.resources, element => ({ element, incompressible: true }))
		: Iterable.map(item.tree.root.children, node => asTreeElement(node, true));
477

J
Joao Moreno 已提交
478
	return { element: item.group, children, incompressible: true, collapsible: true };
479 480
}

481 482
function asTreeElement(node: IResourceNode<ISCMResource, ISCMResourceGroup>, forceIncompressible: boolean): ICompressedTreeElement<TreeElement> {
	return {
J
Joao Moreno 已提交
483
		element: (node.childrenCount === 0 && node.element) ? node.element : node,
J
João Moreno 已提交
484
		children: Iterable.map(node.children, node => asTreeElement(node, false)),
J
Joao Moreno 已提交
485
		incompressible: !!node.element || forceIncompressible
486
	};
J
Joao Moreno 已提交
487 488
}

J
Joao Moreno 已提交
489
const enum ViewModelMode {
J
Joao Moreno 已提交
490 491
	List = 'list',
	Tree = 'tree'
J
Joao Moreno 已提交
492 493
}

494
class ViewModel {
J
Joao Moreno 已提交
495

496
	private readonly _onDidChangeMode = new Emitter<ViewModelMode>();
J
Joao Moreno 已提交
497 498 499 500 501
	readonly onDidChangeMode = this._onDidChangeMode.event;

	get mode(): ViewModelMode { return this._mode; }
	set mode(mode: ViewModelMode) {
		this._mode = mode;
502 503 504 505 506 507 508 509 510 511 512

		for (const item of this.items) {
			item.tree.clear();

			if (mode === ViewModelMode.Tree) {
				for (const resource of item.resources) {
					item.tree.add(resource.sourceUri, resource);
				}
			}
		}

J
Joao Moreno 已提交
513 514 515 516
		this.refresh();
		this._onDidChangeMode.fire(mode);
	}

J
Joao Moreno 已提交
517
	private items: IGroupItem[] = [];
518
	private visibilityDisposables = new DisposableStore();
J
Joao Moreno 已提交
519
	private scrollTop: number | undefined;
J
Joao Moreno 已提交
520
	private firstVisible = true;
J
Joao Moreno 已提交
521 522 523
	private disposables = new DisposableStore();

	constructor(
524
		private groups: ISequence<ISCMResourceGroup>,
J
Joao Moreno 已提交
525
		private tree: WorkbenchCompressibleObjectTree<TreeElement, FuzzyScore>,
J
Joao Moreno 已提交
526 527 528
		private _mode: ViewModelMode,
		@IEditorService protected editorService: IEditorService,
		@IConfigurationService protected configurationService: IConfigurationService,
529
	) { }
J
Joao Moreno 已提交
530 531 532 533 534

	private onDidSpliceGroups({ start, deleteCount, toInsert }: ISplice<ISCMResourceGroup>): void {
		const itemsToInsert: IGroupItem[] = [];

		for (const group of toInsert) {
J
Joao Moreno 已提交
535
			const tree = new ResourceTree<ISCMResource, ISCMResourceGroup>(group, group.provider.rootUri || URI.file('/'));
J
Joao Moreno 已提交
536 537
			const resources: ISCMResource[] = [...group.elements];
			const disposable = combinedDisposable(
538
				group.onDidChange(() => this.tree.refilter()),
J
Joao Moreno 已提交
539 540
				group.onDidSplice(splice => this.onDidSpliceGroup(item, splice))
			);
541

542
			const item: IGroupItem = { group, resources, tree, disposable };
543

544 545 546 547
			if (this._mode === ViewModelMode.Tree) {
				for (const resource of resources) {
					item.tree.add(resource.sourceUri, resource);
				}
548
			}
J
Joao Moreno 已提交
549 550 551 552 553 554 555 556 557 558

			itemsToInsert.push(item);
		}

		const itemsToDispose = this.items.splice(start, deleteCount, ...itemsToInsert);

		for (const item of itemsToDispose) {
			item.disposable.dispose();
		}

559
		this.refresh();
J
Joao Moreno 已提交
560 561 562 563 564
	}

	private onDidSpliceGroup(item: IGroupItem, { start, deleteCount, toInsert }: ISplice<ISCMResource>): void {
		const deleted = item.resources.splice(start, deleteCount, ...toInsert);

565 566 567 568
		if (this._mode === ViewModelMode.Tree) {
			for (const resource of deleted) {
				item.tree.delete(resource.sourceUri);
			}
J
Joao Moreno 已提交
569 570 571 572

			for (const resource of toInsert) {
				item.tree.add(resource.sourceUri, resource);
			}
J
Joao Moreno 已提交
573 574
		}

575 576
		this.refresh(item);
	}
J
Joao Moreno 已提交
577

578 579 580
	setVisible(visible: boolean): void {
		if (visible) {
			this.visibilityDisposables = new DisposableStore();
581 582
			this.groups.onDidSplice(this.onDidSpliceGroups, this, this.visibilityDisposables);
			this.onDidSpliceGroups({ start: 0, deleteCount: this.items.length, toInsert: this.groups.elements });
J
Joao Moreno 已提交
583 584 585 586 587

			if (typeof this.scrollTop === 'number') {
				this.tree.scrollTop = this.scrollTop;
				this.scrollTop = undefined;
			}
J
Joao Moreno 已提交
588 589 590

			this.editorService.onDidActiveEditorChange(this.onDidActiveEditorChange, this, this.visibilityDisposables);
			this.onDidActiveEditorChange();
591 592 593
		} else {
			this.visibilityDisposables.dispose();
			this.onDidSpliceGroups({ start: 0, deleteCount: this.items.length, toInsert: [] });
J
Joao Moreno 已提交
594
			this.scrollTop = this.tree.scrollTop;
595 596
		}
	}
J
Joao Moreno 已提交
597

598 599
	private refresh(item?: IGroupItem): void {
		if (item) {
J
Joao Moreno 已提交
600
			this.tree.setChildren(item.group, groupItemAsTreeElement(item, this.mode).children);
601
		} else {
J
Joao Moreno 已提交
602
			this.tree.setChildren(null, this.items.map(item => groupItemAsTreeElement(item, this.mode)));
603
		}
J
Joao Moreno 已提交
604 605
	}

J
Joao Moreno 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
	private onDidActiveEditorChange(): void {
		if (!this.configurationService.getValue<boolean>('scm.autoReveal')) {
			return;
		}

		if (this.firstVisible) {
			this.firstVisible = false;
			this.visibilityDisposables.add(disposableTimeout(() => this.onDidActiveEditorChange(), 250));
			return;
		}

		const editor = this.editorService.activeEditor;

		if (!editor) {
			return;
		}

		const uri = toResource(editor, { supportSideBySide: SideBySideEditor.MASTER });

		if (!uri) {
			return;
		}

		// go backwards from last group
630
		for (let i = this.items.length - 1; i >= 0; i--) {
J
Joao Moreno 已提交
631 632 633 634 635 636 637 638 639
			const item = this.items[i];
			const resource = this.mode === ViewModelMode.Tree
				? item.tree.getNode(uri)?.element
				: find(item.resources, r => isEqual(r.sourceUri, uri));

			if (resource) {
				this.tree.reveal(resource);
				this.tree.setSelection([resource]);
				this.tree.setFocus([resource]);
640
				return;
J
Joao Moreno 已提交
641 642 643 644
			}
		}
	}

J
Joao Moreno 已提交
645
	dispose(): void {
646 647
		this.visibilityDisposables.dispose();
		this.disposables.dispose();
J
Joao Moreno 已提交
648 649 650 651 652 653

		for (const item of this.items) {
			item.disposable.dispose();
		}

		this.items = [];
J
Joao Moreno 已提交
654 655 656
	}
}

J
Joao Moreno 已提交
657 658 659
export class ToggleViewModeAction extends Action {

	static readonly ID = 'workbench.scm.action.toggleViewMode';
660
	static readonly LABEL = localize('toggleViewMode', "Toggle View Mode");
J
Joao Moreno 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673

	constructor(private viewModel: ViewModel) {
		super(ToggleViewModeAction.ID, ToggleViewModeAction.LABEL);

		this._register(this.viewModel.onDidChangeMode(this.onDidChangeMode, this));
		this.onDidChangeMode(this.viewModel.mode);
	}

	async run(): Promise<void> {
		this.viewModel.mode = this.viewModel.mode === ViewModelMode.List ? ViewModelMode.Tree : ViewModelMode.List;
	}

	private onDidChangeMode(mode: ViewModelMode): void {
M
Miguel Solorio 已提交
674
		const iconClass = mode === ViewModelMode.List ? 'codicon-list-tree' : 'codicon-list-flat';
J
Joao Moreno 已提交
675
		this.class = `scm-action toggle-view-mode ${iconClass}`;
J
Joao Moreno 已提交
676 677 678
	}
}

S
SteVen Batten 已提交
679
export class RepositoryPane extends ViewPane {
680
	private readonly defaultInputFontFamily = 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "Ubuntu", "Droid Sans", sans-serif';
J
Joao Moreno 已提交
681 682 683

	private cachedHeight: number | undefined = undefined;
	private cachedWidth: number | undefined = undefined;
J
Joao Moreno 已提交
684
	private inputContainer!: HTMLElement;
J
Joao Moreno 已提交
685
	private validationContainer!: HTMLElement;
J
Joao Moreno 已提交
686 687
	private inputEditor!: CodeEditorWidget;
	private inputModel!: ITextModel;
J
Joao Moreno 已提交
688
	private listContainer!: HTMLElement;
J
Joao Moreno 已提交
689
	private tree!: WorkbenchCompressibleObjectTree<TreeElement, FuzzyScore>;
J
Joao Moreno 已提交
690 691
	private viewModel!: ViewModel;
	private listLabels!: ResourceLabels;
J
Joao Moreno 已提交
692
	private menus: SCMMenus;
J
Joao Moreno 已提交
693
	private toggleViewModelModeAction: ToggleViewModeAction | undefined;
J
Joao Moreno 已提交
694
	protected contextKeyService: IContextKeyService;
695
	private commitTemplate = '';
J
Joao Moreno 已提交
696 697 698

	constructor(
		readonly repository: ISCMRepository,
S
SteVen Batten 已提交
699
		options: IViewPaneOptions,
J
Joao Moreno 已提交
700
		@IKeybindingService protected keybindingService: IKeybindingService,
701
		@IThemeService protected themeService: IThemeService,
J
Joao Moreno 已提交
702 703 704 705 706 707
		@IContextMenuService protected contextMenuService: IContextMenuService,
		@IContextViewService protected contextViewService: IContextViewService,
		@ICommandService protected commandService: ICommandService,
		@INotificationService private readonly notificationService: INotificationService,
		@IEditorService protected editorService: IEditorService,
		@IInstantiationService protected instantiationService: IInstantiationService,
708
		@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
J
Joao Moreno 已提交
709 710
		@IConfigurationService protected configurationService: IConfigurationService,
		@IContextKeyService contextKeyService: IContextKeyService,
J
Joao Moreno 已提交
711
		@IMenuService protected menuService: IMenuService,
J
Joao Moreno 已提交
712
		@IStorageService private storageService: IStorageService,
J
Joao Moreno 已提交
713
		@IModelService private modelService: IModelService,
J
João Moreno 已提交
714
		@IModeService private modeService: IModeService,
715
		@IOpenerService openerService: IOpenerService,
716
		@ITelemetryService telemetryService: ITelemetryService,
J
Joao Moreno 已提交
717
	) {
718
		super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService);
J
Joao Moreno 已提交
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750

		this.menus = instantiationService.createInstance(SCMMenus, this.repository.provider);
		this._register(this.menus);
		this._register(this.menus.onDidChangeTitle(this._onDidChangeTitleArea.fire, this._onDidChangeTitleArea));

		this.contextKeyService = contextKeyService.createScoped(this.element);
		this.contextKeyService.createKey('scmRepository', this.repository);
	}

	render(): void {
		super.render();
		this._register(this.menus.onDidChangeTitle(this.updateActions, this));
	}

	protected renderHeaderTitle(container: HTMLElement): void {
		let title: string;
		let type: string;

		if (this.repository.provider.rootUri) {
			title = basename(this.repository.provider.rootUri);
			type = this.repository.provider.label;
		} else {
			title = this.repository.provider.label;
			type = '';
		}

		super.renderHeaderTitle(container, title);
		addClass(container, 'scm-provider');
		append(container, $('span.type', undefined, type));
	}

	protected renderBody(container: HTMLElement): void {
J
Joao Moreno 已提交
751 752
		super.renderBody(container);

J
Joao Moreno 已提交
753 754 755 756 757
		const focusTracker = trackFocus(container);
		this._register(focusTracker.onDidFocus(() => this.repository.focus()));
		this._register(focusTracker);

		// Input
J
Joao Moreno 已提交
758 759
		this.inputContainer = append(container, $('.scm-editor'));
		const editorContainer = append(this.inputContainer, $('.scm-editor-container'));
J
Joao Moreno 已提交
760

J
Joao Moreno 已提交
761
		const placeholderTextContainer = append(editorContainer, $('.scm-editor-placeholder'));
J
Joao Moreno 已提交
762
		const updatePlaceholder = () => {
J
Joao Moreno 已提交
763 764 765
			const binding = this.keybindingService.lookupKeybinding('scm.acceptInput');
			const label = binding ? binding.getLabel() : (platform.isMacintosh ? 'Cmd+Enter' : 'Ctrl+Enter');
			const placeholderText = format(this.repository.input.placeholder, label);
J
Joao Moreno 已提交
766

I
isidor 已提交
767
			this.inputEditor.updateOptions({ ariaLabel: placeholderText });
J
Joao Moreno 已提交
768
			placeholderTextContainer.textContent = placeholderText;
J
Joao Moreno 已提交
769 770
		};

J
Joao Moreno 已提交
771 772
		this.validationContainer = append(editorContainer, $('.scm-editor-validation'));

J
Joao Moreno 已提交
773 774 775 776 777 778 779 780
		const validationDelayer = new ThrottledDelayer<any>(200);
		const validate = () => {
			const position = this.inputEditor.getSelection()?.getStartPosition();
			const offset = position && this.inputModel.getOffsetAt(position);
			const value = this.inputModel.getValue();

			return this.repository.input.validateInput(value, offset || 0).then(result => {
				if (!result) {
J
Joao Moreno 已提交
781 782 783 784 785 786 787
					removeClass(editorContainer, 'validation-info');
					removeClass(editorContainer, 'validation-warning');
					removeClass(editorContainer, 'validation-error');
					removeClass(this.validationContainer, 'validation-info');
					removeClass(this.validationContainer, 'validation-warning');
					removeClass(this.validationContainer, 'validation-error');
					this.validationContainer.textContent = null;
J
Joao Moreno 已提交
788
				} else {
J
Joao Moreno 已提交
789 790 791 792 793 794 795
					toggleClass(editorContainer, 'validation-info', result.type === InputValidationType.Information);
					toggleClass(editorContainer, 'validation-warning', result.type === InputValidationType.Warning);
					toggleClass(editorContainer, 'validation-error', result.type === InputValidationType.Error);
					toggleClass(this.validationContainer, 'validation-info', result.type === InputValidationType.Information);
					toggleClass(this.validationContainer, 'validation-warning', result.type === InputValidationType.Warning);
					toggleClass(this.validationContainer, 'validation-error', result.type === InputValidationType.Error);
					this.validationContainer.textContent = result.message;
J
Joao Moreno 已提交
796 797 798
				}
			});
		};
J
Joao Moreno 已提交
799

J
Joao Moreno 已提交
800
		const triggerValidation = () => validationDelayer.trigger(validate);
J
Joao Moreno 已提交
801 802

		const editorOptions: IEditorConstructionOptions = {
J
Joao Moreno 已提交
803 804 805
			...getSimpleEditorOptions(),
			lineDecorationsWidth: 4,
			dragAndDrop: false,
J
Joao Moreno 已提交
806 807 808
			cursorWidth: 1,
			fontSize: 13,
			lineHeight: 20,
809
			fontFamily: this.getInputEditorFontFamily(),
810
			wrappingStrategy: 'advanced',
811
			wrappingIndent: 'none',
812
			padding: { top: 3, bottom: 3 },
A
Alex Ross 已提交
813
			quickSuggestions: false
J
Joao Moreno 已提交
814 815
		};
		const codeEditorWidgetOptions: ICodeEditorWidgetOptions = {
J
Joao Moreno 已提交
816 817
			isSimpleWidget: true,
			contributions: EditorExtensionsRegistry.getSomeEditorContributions([
818 819
				SuggestController.ID,
				SnippetController2.ID,
J
Joao Moreno 已提交
820 821
				MenuPreventer.ID,
				SelectionClipboardContributionID,
J
Joao Moreno 已提交
822
				ContextMenuController.ID,
J
jeanp413 已提交
823 824 825
				ColorDetector.ID,
				ModesHoverController.ID,
				LinkDetector.ID
J
Joao Moreno 已提交
826
			])
J
Joao Moreno 已提交
827 828
		};

J
Joao Moreno 已提交
829 830 831
		const services = new ServiceCollection([IContextKeyService, this.contextKeyService]);
		const instantiationService = this.instantiationService.createChild(services);
		this.inputEditor = instantiationService.createInstance(CodeEditorWidget, editorContainer, editorOptions, codeEditorWidgetOptions);
J
Joao Moreno 已提交
832 833 834 835 836

		this._register(this.inputEditor);

		this._register(this.inputEditor.onDidFocusEditorText(() => addClass(editorContainer, 'synthetic-focus')));
		this._register(this.inputEditor.onDidBlurEditorText(() => removeClass(editorContainer, 'synthetic-focus')));
J
Joao Moreno 已提交
837

838 839 840
		const onInputFontFamilyChanged = Event.filter(this.configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('scm.inputFontFamily'));
		this._register(onInputFontFamilyChanged(() => this.inputEditor.updateOptions({ fontFamily: this.getInputEditorFontFamily() })));

841 842 843 844 845 846 847 848 849 850 851 852
		let query: string | undefined;

		if (this.repository.provider.rootUri) {
			query = `rootUri=${encodeURIComponent(this.repository.provider.rootUri.toString())}`;
		}

		const uri = URI.from({
			scheme: Schemas.vscode,
			path: `scm/${this.repository.provider.contextValue}/${this.repository.provider.id}/input`,
			query
		});

J
João Moreno 已提交
853
		this.configurationService.updateValue('editor.wordBasedSuggestions', false, { resource: uri }, ConfigurationTarget.MEMORY);
J
João Moreno 已提交
854 855 856

		const mode = this.modeService.create('scminput');
		this.inputModel = this.modelService.getModel(uri) || this.modelService.createModel('', mode, uri);
J
Joao Moreno 已提交
857
		this.inputEditor.setModel(this.inputModel);
J
Joao Moreno 已提交
858

J
Joao Moreno 已提交
859
		this._register(this.inputEditor.onDidChangeCursorPosition(triggerValidation));
J
Joao Moreno 已提交
860

861 862
		// Keep model in sync with API
		this.inputModel.setValue(this.repository.input.value);
J
jeanp413 已提交
863 864 865 866 867
		this._register(this.repository.input.onDidChange(value => {
			if (value === this.inputModel.getValue()) {
				return;
			}
			this.inputModel.setValue(value);
J
João Moreno 已提交
868
			this.inputEditor.setPosition(this.inputModel.getFullModelRange().getEndPosition());
J
jeanp413 已提交
869
		}));
J
Joao Moreno 已提交
870

871
		// Keep API in sync with model and update placeholder and validation
J
Joao Moreno 已提交
872
		toggleClass(placeholderTextContainer, 'hidden', this.inputModel.getValueLength() > 0);
J
Joao Moreno 已提交
873
		this.inputModel.onDidChangeContent(() => {
874
			this.repository.input.value = this.inputModel.getValue();
J
Joao Moreno 已提交
875
			toggleClass(placeholderTextContainer, 'hidden', this.inputModel.getValueLength() > 0);
876
			triggerValidation();
J
Joao Moreno 已提交
877 878
		});

J
Joao Moreno 已提交
879 880 881 882
		updatePlaceholder();
		this._register(this.repository.input.onDidChangePlaceholder(updatePlaceholder, null));
		this._register(this.keybindingService.onDidUpdateKeybindings(updatePlaceholder, null));

883
		const onDidChangeContentHeight = Event.filter(this.inputEditor.onDidContentSizeChange, e => e.contentHeightChanged);
J
Joao Moreno 已提交
884
		this._register(onDidChangeContentHeight(() => this.layoutBody()));
J
Joao Moreno 已提交
885

886
		this._register(this.repository.provider.onDidChangeCommitTemplate(this.onDidChangeCommitTemplate, this));
J
Joao Moreno 已提交
887

J
Joao Moreno 已提交
888
		this.onDidChangeCommitTemplate();
J
Joao Moreno 已提交
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907

		// Input box visibility
		this._register(this.repository.input.onDidChangeVisibility(this.updateInputBoxVisibility, this));
		this.updateInputBoxVisibility();

		// List
		this.listContainer = append(container, $('.scm-status.show-file-icons'));

		const updateActionsVisibility = () => toggleClass(this.listContainer, 'show-actions', this.configurationService.getValue<boolean>('scm.alwaysShowActions'));
		Event.filter(this.configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('scm.alwaysShowActions'))(updateActionsVisibility);
		updateActionsVisibility();

		const delegate = new ProviderListDelegate();

		const actionViewItemProvider = (action: IAction) => this.getActionViewItem(action);

		this.listLabels = this.instantiationService.createInstance(ResourceLabels, { onDidChangeVisibility: this.onDidChangeBodyVisibility });
		this._register(this.listLabels);

J
João Moreno 已提交
908 909
		const actionRunner = new RepositoryPaneActionRunner(() => this.getSelectedResources());
		this._register(actionRunner);
J
João Moreno 已提交
910
		this._register(actionRunner.onDidBeforeRun(() => this.tree.domFocus()));
J
João Moreno 已提交
911

J
Joao Moreno 已提交
912 913
		const renderers = [
			new ResourceGroupRenderer(actionViewItemProvider, this.themeService, this.menus),
J
João Moreno 已提交
914
			new ResourceRenderer(() => this.viewModel, this.listLabels, actionViewItemProvider, actionRunner, this.themeService, this.menus)
J
Joao Moreno 已提交
915 916 917
		];

		const filter = new SCMTreeFilter();
J
Joao Moreno 已提交
918
		const sorter = new SCMTreeSorter(() => this.viewModel);
919
		const keyboardNavigationLabelProvider = this.instantiationService.createInstance(SCMTreeKeyboardNavigationLabelProvider);
J
Joao Moreno 已提交
920
		const identityProvider = new SCMResourceIdentityProvider();
J
Joao Moreno 已提交
921

J
João Moreno 已提交
922
		this.tree = this.instantiationService.createInstance(
J
Joao Moreno 已提交
923
			WorkbenchCompressibleObjectTree,
J
Joao Moreno 已提交
924
			'SCM Tree Repo',
J
Joao Moreno 已提交
925 926 927 928
			this.listContainer,
			delegate,
			renderers,
			{
J
Joao Moreno 已提交
929
				identityProvider,
J
Joao Moreno 已提交
930 931 932
				horizontalScrolling: false,
				filter,
				sorter,
J
Joao Moreno 已提交
933 934 935
				keyboardNavigationLabelProvider,
				overrideStyles: {
					listBackground: SIDE_BAR_BACKGROUND
J
João Moreno 已提交
936
				},
J
João Moreno 已提交
937
				accessibilityProvider: this.instantiationService.createInstance(SCMAccessibilityProvider)
J
João Moreno 已提交
938
			}) as WorkbenchCompressibleObjectTree<TreeElement, FuzzyScore>;
J
Joao Moreno 已提交
939

J
João Moreno 已提交
940 941
		const navigator = this._register(new TreeResourceNavigator(this.tree, { openOnSelection: false }));
		this._register(navigator.onDidOpenResource(this.open, this));
J
Joao Moreno 已提交
942

J
Joao Moreno 已提交
943 944
		this._register(Event.chain(this.tree.onDidPin)
			.map(e => e.elements[0])
945
			.filter(e => !!e && !isSCMResourceGroup(e) && !ResourceTree.isResourceNode(e))
J
Joao Moreno 已提交
946
			.on(this.pin, this));
J
Joao Moreno 已提交
947

948
		this._register(this.tree.onContextMenu(this.onListContextMenu, this));
J
Joao Moreno 已提交
949 950
		this._register(this.tree);

J
rename  
João Moreno 已提交
951
		let viewMode = this.configurationService.getValue<'tree' | 'list'>('scm.defaultViewMode') === 'list' ? ViewModelMode.List : ViewModelMode.Tree;
J
Joao Moreno 已提交
952

953
		const rootUri = this.repository.provider.rootUri;
J
Joao Moreno 已提交
954

955 956
		if (typeof rootUri !== 'undefined') {
			const storageMode = this.storageService.get(`scm.repository.viewMode:${rootUri.toString()}`, StorageScope.WORKSPACE) as ViewModelMode;
J
Joao Moreno 已提交
957

958
			if (typeof storageMode === 'string') {
J
rename  
João Moreno 已提交
959
				viewMode = storageMode;
J
Joao Moreno 已提交
960 961 962
			}
		}

J
rename  
João Moreno 已提交
963
		this.viewModel = this.instantiationService.createInstance(ViewModel, this.repository.provider.groups, this.tree, viewMode);
964
		this._register(this.viewModel);
J
Joao Moreno 已提交
965

966 967 968
		addClass(this.listContainer, 'file-icon-themable-tree');
		addClass(this.listContainer, 'show-file-icons');

J
Joao Moreno 已提交
969 970 971
		this.updateIndentStyles(this.themeService.getFileIconTheme());
		this._register(this.themeService.onDidFileIconThemeChange(this.updateIndentStyles, this));
		this._register(this.viewModel.onDidChangeMode(this.onDidChangeMode, this));
972

973 974
		this.toggleViewModelModeAction = new ToggleViewModeAction(this.viewModel);
		this._register(this.toggleViewModelModeAction);
J
Joao Moreno 已提交
975

976
		this._register(this.onDidChangeBodyVisibility(this._onDidChangeVisibility, this));
J
Joao Moreno 已提交
977 978

		this.updateActions();
J
Joao Moreno 已提交
979 980
	}

J
Joao Moreno 已提交
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
	private updateIndentStyles(theme: IFileIconTheme): void {
		toggleClass(this.listContainer, 'list-view-mode', this.viewModel.mode === ViewModelMode.List);
		toggleClass(this.listContainer, 'tree-view-mode', this.viewModel.mode === ViewModelMode.Tree);
		toggleClass(this.listContainer, 'align-icons-and-twisties', this.viewModel.mode === ViewModelMode.Tree && theme.hasFileIcons && !theme.hasFolderIcons);
		toggleClass(this.listContainer, 'hide-arrows', this.viewModel.mode === ViewModelMode.Tree && theme.hidesExplorerArrows === true);
	}

	private onDidChangeMode(): void {
		this.updateIndentStyles(this.themeService.getFileIconTheme());

		const rootUri = this.repository.provider.rootUri;

		if (typeof rootUri === 'undefined') {
			return;
		}

		this.storageService.store(`scm.repository.viewMode:${rootUri.toString()}`, this.viewModel.mode, StorageScope.WORKSPACE);
	}

J
Joao Moreno 已提交
1000 1001 1002 1003 1004
	layoutBody(height: number | undefined = this.cachedHeight, width: number | undefined = this.cachedWidth): void {
		if (height === undefined) {
			return;
		}

J
João Moreno 已提交
1005 1006 1007 1008
		if (width !== undefined) {
			super.layoutBody(height, width);
		}

J
Joao Moreno 已提交
1009
		this.cachedHeight = height;
J
Joao Moreno 已提交
1010
		this.cachedWidth = width;
J
Joao Moreno 已提交
1011 1012

		if (this.repository.input.visible) {
J
Joao Moreno 已提交
1013
			removeClass(this.inputContainer, 'hidden');
J
Joao Moreno 已提交
1014

1015
			const editorContentHeight = this.inputEditor.getContentHeight();
1016
			const editorHeight = Math.min(editorContentHeight, 134);
J
Joao Moreno 已提交
1017
			this.inputEditor.layout({ height: editorHeight, width: width! - 12 - 16 - 2 });
J
Joao Moreno 已提交
1018

J
Joao Moreno 已提交
1019 1020
			this.validationContainer.style.top = `${editorHeight + 1}px`;

J
Joao Moreno 已提交
1021
			const listHeight = height - (editorHeight + 5 + 2 + 5);
J
Joao Moreno 已提交
1022 1023 1024
			this.listContainer.style.height = `${listHeight}px`;
			this.tree.layout(listHeight, width);
		} else {
J
Joao Moreno 已提交
1025
			addClass(this.inputContainer, 'hidden');
J
Joao Moreno 已提交
1026

J
Joao Moreno 已提交
1027
			this.inputEditor.onHide();
J
Joao Moreno 已提交
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
			this.listContainer.style.height = `${height}px`;
			this.tree.layout(height, width);
		}
	}

	focus(): void {
		super.focus();

		if (this.isExpanded()) {
			if (this.repository.input.visible) {
J
Joao Moreno 已提交
1038
				this.inputEditor.focus();
J
Joao Moreno 已提交
1039 1040 1041 1042 1043 1044 1045 1046
			} else {
				this.tree.domFocus();
			}

			this.repository.focus();
		}
	}

1047 1048
	private _onDidChangeVisibility(visible: boolean): void {
		this.viewModel.setVisible(visible);
J
Joao Moreno 已提交
1049 1050 1051 1052 1053 1054

		if (this.repository.input.visible && visible) {
			this.inputEditor.onVisible();
		} else {
			this.inputEditor.onHide();
		}
1055 1056
	}

J
Joao Moreno 已提交
1057
	getActions(): IAction[] {
J
Joao Moreno 已提交
1058 1059 1060 1061 1062 1063 1064 1065 1066
		if (this.toggleViewModelModeAction) {

			return [
				this.toggleViewModelModeAction,
				...this.menus.getTitleActions()
			];
		} else {
			return this.menus.getTitleActions();
		}
J
Joao Moreno 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
	}

	getSecondaryActions(): IAction[] {
		return this.menus.getTitleSecondaryActions();
	}

	getActionViewItem(action: IAction): IActionViewItem | undefined {
		if (!(action instanceof MenuItemAction)) {
			return undefined;
		}

		return new ContextAwareMenuEntryActionViewItem(action, this.keybindingService, this.notificationService, this.contextMenuService);
	}

	getActionsContext(): any {
		return this.repository.provider;
	}

J
João Moreno 已提交
1085 1086 1087 1088 1089 1090
	private open(e: IOpenEvent<TreeElement | null>): void {
		if (!e.element || isSCMResourceGroup(e.element) || ResourceTree.isResourceNode(e.element)) {
			return;
		}

		e.element.open(!!e.editorOptions.preserveFocus);
J
Joao Moreno 已提交
1091 1092
	}

J
Joao Moreno 已提交
1093
	private pin(): void {
1094
		const activeEditorPane = this.editorService.activeEditorPane;
J
Joao Moreno 已提交
1095

1096 1097
		if (activeEditorPane) {
			activeEditorPane.group.pinEditor(activeEditorPane.input);
J
Joao Moreno 已提交
1098 1099
		}
	}
J
Joao Moreno 已提交
1100

J
Joao Moreno 已提交
1101
	private onListContextMenu(e: ITreeContextMenuEvent<TreeElement | null>): void {
1102 1103 1104
		if (!e.element) {
			return;
		}
J
Joao Moreno 已提交
1105

1106
		const element = e.element;
J
Joao Moreno 已提交
1107
		let actions: IAction[] = [];
J
Joao Moreno 已提交
1108

1109 1110 1111
		if (isSCMResourceGroup(element)) {
			actions = this.menus.getResourceGroupContextActions(element);
		} else if (ResourceTree.isResourceNode(element)) {
J
Joao Moreno 已提交
1112 1113 1114 1115 1116
			if (element.element) {
				actions = this.menus.getResourceContextActions(element.element);
			} else {
				actions = this.menus.getResourceFolderContextActions(element.context);
			}
1117
		} else {
1118
			actions = this.menus.getResourceContextActions(element);
1119
		}
J
Joao Moreno 已提交
1120

J
João Moreno 已提交
1121
		const actionRunner = new RepositoryPaneActionRunner(() => this.getSelectedResources());
J
João Moreno 已提交
1122
		actionRunner.onDidBeforeRun(() => this.tree.domFocus());
J
João Moreno 已提交
1123

1124 1125 1126 1127
		this.contextMenuService.showContextMenu({
			getAnchor: () => e.anchor,
			getActions: () => actions,
			getActionsContext: () => element,
J
João Moreno 已提交
1128
			actionRunner
1129 1130
		});
	}
J
Joao Moreno 已提交
1131

1132
	private getSelectedResources(): (ISCMResource | IResourceNode<ISCMResource, ISCMResourceGroup>)[] {
J
Joao Moreno 已提交
1133
		return this.tree.getSelection()
1134
			.filter(r => !!r && !isSCMResourceGroup(r))! as any;
J
Joao Moreno 已提交
1135 1136
	}

J
Joao Moreno 已提交
1137
	private onDidChangeCommitTemplate(): void {
1138 1139 1140 1141 1142 1143
		if (typeof this.repository.provider.commitTemplate === 'undefined' || !this.repository.input.visible) {
			return;
		}

		const oldCommitTemplate = this.commitTemplate;
		this.commitTemplate = this.repository.provider.commitTemplate;
J
Joao Moreno 已提交
1144

1145
		const value = this.inputModel.getValue();
J
Joao Moreno 已提交
1146

1147 1148 1149
		if (value && value !== oldCommitTemplate) {
			return;
		}
J
Joao Moreno 已提交
1150

1151
		this.inputModel.setValue(this.commitTemplate);
J
Joao Moreno 已提交
1152 1153 1154 1155 1156 1157 1158
	}

	private updateInputBoxVisibility(): void {
		if (this.cachedHeight) {
			this.layoutBody(this.cachedHeight);
		}
	}
1159 1160 1161 1162

	private getInputEditorFontFamily(): string {
		const inputFontFamily = this.configurationService.getValue<string>('scm.inputFontFamily');

1163
		if (inputFontFamily.toLowerCase() === 'editor') {
1164 1165 1166 1167 1168 1169 1170 1171 1172
			return this.configurationService.getValue<string>('editor.fontFamily');
		}

		if (inputFontFamily.length !== 0 && inputFontFamily.toLowerCase() !== 'default') {
			return inputFontFamily;
		}

		return this.defaultInputFontFamily;
	}
J
Joao Moreno 已提交
1173 1174 1175 1176 1177 1178 1179 1180
}

export class RepositoryViewDescriptor implements IViewDescriptor {

	private static counter = 0;

	readonly id: string;
	readonly name: string;
S
Sandeep Somavarapu 已提交
1181
	readonly ctorDescriptor: SyncDescriptor<RepositoryPane>;
J
Joao Moreno 已提交
1182 1183 1184 1185 1186 1187
	readonly canToggleVisibility = true;
	readonly order = -500;
	readonly workspace = true;

	constructor(readonly repository: ISCMRepository, readonly hideByDefault: boolean) {
		const repoId = repository.provider.rootUri ? repository.provider.rootUri.toString() : `#${RepositoryViewDescriptor.counter++}`;
J
Joao Moreno 已提交
1188 1189 1190 1191
		const hasher = new Hasher();
		hasher.hash(repository.provider.label);
		hasher.hash(repoId);
		this.id = `scm:repository:${hasher.value}`;
J
Joao Moreno 已提交
1192 1193
		this.name = repository.provider.rootUri ? basename(repository.provider.rootUri) : repository.provider.label;

S
Sandeep Somavarapu 已提交
1194
		this.ctorDescriptor = new SyncDescriptor(RepositoryPane, [repository]);
J
Joao Moreno 已提交
1195 1196
	}
}
J
Joao Moreno 已提交
1197 1198

registerThemingParticipant((theme, collector) => {
J
Joao Moreno 已提交
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
	const inputBackgroundColor = theme.getColor(inputBackground);
	if (inputBackgroundColor) {
		collector.addRule(`.scm-viewlet .scm-editor-container .monaco-editor-background,
		.scm-viewlet .scm-editor-container .monaco-editor,
		.scm-viewlet .scm-editor-container .monaco-editor .margin
		{ background-color: ${inputBackgroundColor}; }`);
	}

	const inputForegroundColor = theme.getColor(inputForeground);
	if (inputForegroundColor) {
		collector.addRule(`.scm-viewlet .scm-editor-container .mtk1 { color: ${inputForegroundColor}; }`);
	}

	const inputBorderColor = theme.getColor(inputBorder);
	if (inputBorderColor) {
		collector.addRule(`.scm-viewlet .scm-editor-container { outline: 1px solid ${inputBorderColor}; }`);
	}

	const focusBorderColor = theme.getColor(focusBorder);
	if (focusBorderColor) {
		collector.addRule(`.scm-viewlet .scm-editor-container.synthetic-focus { outline: 1px solid ${focusBorderColor}; }`);
	}

J
Joao Moreno 已提交
1222
	const inputPlaceholderForegroundColor = theme.getColor(inputPlaceholderForeground);
J
Joao Moreno 已提交
1223 1224 1225
	if (inputPlaceholderForegroundColor) {
		collector.addRule(`.scm-viewlet .scm-editor-placeholder { color: ${inputPlaceholderForegroundColor}; }`);
	}
J
Joao Moreno 已提交
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273

	const inputValidationInfoBorderColor = theme.getColor(inputValidationInfoBorder);
	if (inputValidationInfoBorderColor) {
		collector.addRule(`.scm-viewlet .scm-editor-container.validation-info { outline: 1px solid ${inputValidationInfoBorderColor}; }`);
		collector.addRule(`.scm-viewlet .scm-editor-validation.validation-info { border: 1px solid ${inputValidationInfoBorderColor}; }`);
	}

	const inputValidationInfoBackgroundColor = theme.getColor(inputValidationInfoBackground);
	if (inputValidationInfoBackgroundColor) {
		collector.addRule(`.scm-viewlet .scm-editor-validation.validation-info { background-color: ${inputValidationInfoBackgroundColor}; }`);
	}

	const inputValidationInfoForegroundColor = theme.getColor(inputValidationInfoForeground);
	if (inputValidationInfoForegroundColor) {
		collector.addRule(`.scm-viewlet .scm-editor-validation.validation-info { color: ${inputValidationInfoForegroundColor}; }`);
	}

	const inputValidationWarningBorderColor = theme.getColor(inputValidationWarningBorder);
	if (inputValidationWarningBorderColor) {
		collector.addRule(`.scm-viewlet .scm-editor-container.validation-warning { outline: 1px solid ${inputValidationWarningBorderColor}; }`);
		collector.addRule(`.scm-viewlet .scm-editor-validation.validation-warning { border: 1px solid ${inputValidationWarningBorderColor}; }`);
	}

	const inputValidationWarningBackgroundColor = theme.getColor(inputValidationWarningBackground);
	if (inputValidationWarningBackgroundColor) {
		collector.addRule(`.scm-viewlet .scm-editor-validation.validation-warning { background-color: ${inputValidationWarningBackgroundColor}; }`);
	}

	const inputValidationWarningForegroundColor = theme.getColor(inputValidationWarningForeground);
	if (inputValidationWarningForegroundColor) {
		collector.addRule(`.scm-viewlet .scm-editor-validation.validation-warning { color: ${inputValidationWarningForegroundColor}; }`);
	}

	const inputValidationErrorBorderColor = theme.getColor(inputValidationErrorBorder);
	if (inputValidationErrorBorderColor) {
		collector.addRule(`.scm-viewlet .scm-editor-container.validation-error { outline: 1px solid ${inputValidationErrorBorderColor}; }`);
		collector.addRule(`.scm-viewlet .scm-editor-validation.validation-error { border: 1px solid ${inputValidationErrorBorderColor}; }`);
	}

	const inputValidationErrorBackgroundColor = theme.getColor(inputValidationErrorBackground);
	if (inputValidationErrorBackgroundColor) {
		collector.addRule(`.scm-viewlet .scm-editor-validation.validation-error { background-color: ${inputValidationErrorBackgroundColor}; }`);
	}

	const inputValidationErrorForegroundColor = theme.getColor(inputValidationErrorForeground);
	if (inputValidationErrorForegroundColor) {
		collector.addRule(`.scm-viewlet .scm-editor-validation.validation-error { color: ${inputValidationErrorForegroundColor}; }`);
	}
J
Joao Moreno 已提交
1274
});