Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: e6341b24f8f262ce0c66e1f6be1d7d0c241217a7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
141
142
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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
252
253
254
255
256
257
258
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*******************************************************************************
 * Copyright (C) 2011, 2016 Mathias Kinzler <mathias.kinzler@sap.com> and others.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *    Thomas Wolf <thomas.wolf@paranor.ch> - Bug 486594
 *******************************************************************************/
package org.eclipse.egit.ui.internal.actions;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Stream;

import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.internal.CommonUtils;
import org.eclipse.egit.ui.internal.UIIcons;
import org.eclipse.egit.ui.internal.UIText;
import org.eclipse.egit.ui.internal.branch.BranchOperationUI;
import org.eclipse.egit.ui.internal.dialogs.CheckoutDialog;
import org.eclipse.egit.ui.internal.repository.CreateBranchWizard;
import org.eclipse.egit.ui.internal.selection.SelectionUtils;
import org.eclipse.jface.action.ContributionItem;
import org.eclipse.jface.resource.ResourceManager;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.jgit.lib.CheckoutEntry;
import org.eclipse.jgit.lib.ConfigConstants;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.ReflogEntry;
import org.eclipse.jgit.lib.ReflogReader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.menus.IWorkbenchContribution;
import org.eclipse.ui.services.IServiceLocator;

/**
 * Dynamically builds the "Switch to..." sub-menu
 */
public class SwitchToMenu extends ContributionItem implements
		IWorkbenchContribution {
	/** the maximum number of branches to show in the sub-menu */
	static final int MAX_NUM_MENU_ENTRIES = 20;

	private IHandlerService handlerService;

	private final Image branchImage;

	private final Image newBranchImage;

	private final Image checkedOutImage;

	/**
	 */
	public SwitchToMenu() {
		this(null);
	}

	/**
	 * @param id
	 */
	public SwitchToMenu(String id) {
		super(id);
		ResourceManager pluginResources = Activator.getDefault()
				.getResourceManager();
		branchImage = UIIcons.getImage(pluginResources, UIIcons.BRANCH);
		newBranchImage = UIIcons.getImage(pluginResources,
				UIIcons.CREATE_BRANCH);
		checkedOutImage = UIIcons.getImage(pluginResources,
				UIIcons.CHECKED_OUT_BRANCH);
	}

	@Override
	public void fill(Menu menu, int index) {
		if (handlerService == null)
			return;

		Repository[] repositories = SelectionUtils
				.getAllRepositories(handlerService.getCurrentState());

		if (repositories.length > 0) {
			createDynamicMenu(menu, repositories);
		}
	}

	private void createDynamicMenu(Menu menu, final Repository[] repositories) {

		if (!isMultipleSelection(repositories)) {
			Repository repository = repositories[0];
			createNewBranchMenuItem(menu, repository);
			if (hasBranches(repository)) {
				createSeparator(menu);
			}
		}

		int itemCount = createMostActiveBranchesMenuItems(menu, repositories);

		if (!isMultipleSelection(repositories) && itemCount > 0) {
			createSeparator(menu);
			createOtherMenuItem(menu, repositories[0]);
		}

		if (itemCount == 0 && isMultipleSelection(repositories)) {
			// If the menu would be empty, add a disabled menuItem to inform the
			// user that no common branches among the selection were found
			createDisabledMenu(menu, UIText.SwitchToMenu_NoCommonBranchesFound);
		}
	}

	private boolean hasBranches(Repository repository) {
		try {
			return !repository.getRefDatabase().getRefs(Constants.R_HEADS)
					.isEmpty();
		} catch (IOException e) {
			Activator.handleError(e.getMessage(), e, true);
			return false;
		}
	}

	private void createNewBranchMenuItem(Menu menu, Repository repository) {
		MenuItem newBranch = new MenuItem(menu, SWT.PUSH);
		newBranch.setText(UIText.SwitchToMenu_NewBranchMenuLabel);
		newBranch.setImage(newBranchImage);
		newBranch.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				String sourceRef = repository.getConfig().getString(
						ConfigConstants.CONFIG_WORKFLOW_SECTION, null,
						ConfigConstants.CONFIG_KEY_DEFBRANCHSTARTPOINT);
				CreateBranchWizard wiz = null;
				try {
					Ref ref = null;
					if (sourceRef != null) {
						ref = repository.findRef(sourceRef);
					}
					if (ref != null) {
						wiz = new CreateBranchWizard(repository, ref.getName());
					} else {
						wiz = new CreateBranchWizard(repository,
								repository.getFullBranch());
					}
				} catch (IOException e1) {
					// Ignore
				}
				if (wiz == null) {
					wiz = new CreateBranchWizard(repository);
				}
				WizardDialog dlg = new WizardDialog(e.display.getActiveShell(),
						wiz);
				dlg.setHelpAvailable(false);
				dlg.open();
			}
		});

	}

	private int createMostActiveBranchesMenuItems(Menu menu,
			Repository[] repositories) {
		int itemCount = 0;
		try {
			List<Map<String, Ref>> activeBranches = new ArrayList<>();

			for (Repository repository : repositories) {
				Map<String, Ref> branchRefMapping = getMostActiveBranches(
						repository, MAX_NUM_MENU_ENTRIES);
				activeBranches.add(branchRefMapping);
			}

			Set<String> activeBranchIntersection = getBranchNameIntersection(
					activeBranches);
			for (String branchName : activeBranchIntersection) {
				itemCount++;
				createMenuItemMultiple(menu, repositories, branchName);
			}

			if (itemCount >= MAX_NUM_MENU_ENTRIES) {
				return itemCount;
			}

			List<Map<String, Ref>> localBranchMapping = new ArrayList<>();
			for (Repository repository : repositories) {
				Map<String, Ref> localBranches = repository.getRefDatabase()
						.getRefs(Constants.R_HEADS);
				localBranchMapping.add(localBranches);
			}

			// A separator between recently used branches and local branches is
			// nice but only if we have both recently used branches and other
			// local branches
			Set<String> localBranchNameIntersection = getBranchNameIntersection(
					localBranchMapping);
			localBranchNameIntersection.removeAll(activeBranchIntersection);
			if (itemCount > 0 && !localBranchNameIntersection.isEmpty()) {
				createSeparator(menu);
			}

			for (String localBranchName : localBranchNameIntersection) {
				itemCount++;
				if (itemCount > MAX_NUM_MENU_ENTRIES) {
					break;
				}

				createMenuItemMultiple(menu, repositories, localBranchName);
			}
		} catch (IOException e) {
			Activator.handleError(e.getMessage(), e, true);
		}

		return itemCount;
	}

	private Set<String> getBranchNameIntersection(
			List<Map<String, Ref>> refMapping) {
		Iterator<Map<String, Ref>> iterator = refMapping.iterator();
		if (!iterator.hasNext()) {
			return Collections.emptySet();
		}

		Set<String> intersection = new TreeSet<>(
				CommonUtils.STRING_ASCENDING_COMPARATOR);
		intersection.addAll(iterator.next().keySet());
		iterator.forEachRemaining(map -> intersection.retainAll(map.keySet()));
		return intersection;
	}

	private void createOtherMenuItem(Menu menu, Repository repository) {
		MenuItem others = new MenuItem(menu, SWT.PUSH);
		others.setText(UIText.SwitchToMenu_OtherMenuLabel);
		others.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				CheckoutDialog dialog = new CheckoutDialog(
						e.display.getActiveShell(), repository);
				if (dialog.open() == Window.OK) {
					BranchOperationUI.checkout(repository, dialog.getRefName())
							.start();
				}

			}
		});
	}

	private void createDisabledMenu(Menu menu, String text) {
		MenuItem disabled = new MenuItem(menu, SWT.PUSH);
		disabled.setText(text);
		disabled.setImage(branchImage);
		disabled.setEnabled(false);
	}

	private static MenuItem createSeparator(Menu menu) {
		return new MenuItem(menu, SWT.SEPARATOR);
	}

	private void createMenuItemMultiple(Menu menu, Repository[] repositories,
			String shortName) {

		MenuItem item = new MenuItem(menu, SWT.PUSH);
		item.setText(shortName);

		boolean allRepositoriesCheckedOut = Stream.of(repositories)
				.allMatch(r -> shortName.equals(getBranch(r)));

		if (allRepositoriesCheckedOut) {
			item.setImage(checkedOutImage);
		} else {
			item.setImage(branchImage);
		}
		item.setEnabled(!allRepositoriesCheckedOut);

		item.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				BranchOperationUI.checkout(repositories, shortName).start();
			}
		});
	}

	private String getBranch(Repository repo) {
		try {
			return repo.getBranch();
		} catch (IOException e) {
			return ""; //$NON-NLS-1$
		}
	}

	private Map<String, Ref> getMostActiveBranches(final Repository repository,
			int maximumBranchCount) throws IOException {
		Map<String, Ref> localBranches = repository.getRefDatabase()
				.getRefs(Constants.R_HEADS);
		Map<String, Ref> activeRefs = new HashMap<>();

		ReflogReader reflogReader = repository.getReflogReader(Constants.HEAD);
		List<ReflogEntry> reflogEntries;
		if (reflogReader == null) {
			return Collections.emptyMap();
		}

		reflogEntries = reflogReader.getReverseEntries();

		for (ReflogEntry entry : reflogEntries) {
			CheckoutEntry checkout = entry.parseCheckout();
			if (checkout != null) {
				Ref ref = localBranches.get(checkout.getFromBranch());
				if (ref != null && activeRefs.size() < maximumBranchCount) {
					activeRefs.put(checkout.getFromBranch(), ref);
				}
				ref = localBranches.get(checkout.getToBranch());
				if (ref != null && activeRefs.size() < maximumBranchCount) {
					activeRefs.put(checkout.getToBranch(), ref);
				}
			}
		}

		return activeRefs;
	}

	private boolean isMultipleSelection(Repository[] repositories) {
		return repositories.length > 1;
	}

	@Override
	public boolean isDynamic() {
		return true;
	}

	@Override
	public void initialize(IServiceLocator serviceLocator) {
		handlerService = CommonUtils.getService(serviceLocator, IHandlerService.class);
	}

}

Back to the top