Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: ddc510715fdf2a828e49c77cb6dd10cec15b3e65 (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
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
/*******************************************************************************
 * Copyright (c) 2010, 2015 SAP AG and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Mathias Kinzler (SAP AG) - initial implementation
 *    Thomas Wolf <thomas.wolf@paranor.ch> - Bug 479108
 *    Simon Scholz <simon.scholz@vogella.com> - Bug 476505
 *******************************************************************************/
package org.eclipse.egit.ui.internal.repository;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.egit.core.Activator;
import org.eclipse.egit.core.RepositoryUtil;
import org.eclipse.egit.ui.UIUtils;
import org.eclipse.egit.ui.internal.UIIcons;
import org.eclipse.egit.ui.internal.UIText;
import org.eclipse.egit.ui.internal.components.CachedCheckboxTreeViewer;
import org.eclipse.egit.ui.internal.components.FilteredCheckboxTree;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.resource.LocalResourceManager;
import org.eclipse.jface.resource.ResourceManager;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IColorProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.jgit.lib.RepositoryCache.FileKey;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.FileUtils;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.PatternFilter;
import org.osgi.service.prefs.BackingStoreException;

/**
 * Searches for Git directories under a path that can be selected by the user
 */
public class RepositorySearchDialog extends WizardPage {

	private static final String PREF_DEEP_SEARCH = "RepositorySearchDialogDeepSearch"; //$NON-NLS-1$

	private static final String PREF_PATH = "RepositorySearchDialogSearchPath"; //$NON-NLS-1$

	private final Set<String> fExistingDirectories = new HashSet<String>();

	private final boolean fillSearch;

	private Set<String> fResult;

	private FilteredCheckboxTree fTree;

	private CachedCheckboxTreeViewer fTreeViewer;

	private Text dir;

	private Button lookForNestedButton;

	private Button searchButton;

	private ToolItem checkAllItem;

	private ToolItem uncheckAllItem;

	private final ResourceManager fImageCache = new LocalResourceManager(
			JFaceResources.getResources());

	private final IEclipsePreferences prefs = InstanceScope.INSTANCE
			.getNode(Activator.getPluginId());

	private static final class ContentProvider implements ITreeContentProvider {

		private final Object[] children = new Object[0];

		@Override
		@SuppressWarnings("unchecked")
		public Object[] getElements(Object inputElement) {
			return ((Set<String>) inputElement).toArray();
		}

		@Override
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
			// nothing
		}

		@Override
		public void dispose() {
			// nothing
		}

		@Override
		public Object[] getChildren(Object parentElement) {
			// do not return null due to a bug in FilteredTree
			return children;
		}

		@Override
		public Object getParent(Object element) {
			// nothing
			return null;
		}

		@Override
		public boolean hasChildren(Object element) {
			// nothing
			return false;
		}

	}

	private final class RepositoryLabelProvider extends LabelProvider implements
			IColorProvider {

		@Override
		public Image getImage(Object element) {
			return fImageCache.createImage(UIIcons.REPOSITORY);
		}

		@Override
		public String getText(Object element) {
			return element.toString();
		}

		@Override
		public Color getBackground(Object element) {
			return null;
		}

		@Override
		public Color getForeground(Object element) {
			if (fExistingDirectories.contains(element))
				return getShell().getDisplay().getSystemColor(SWT.COLOR_GRAY);

			return null;
		}

		@Override
		public void dispose() {
			fImageCache.dispose();
		}

	}

	/**
	 * @param existingDirs
	 */
	public RepositorySearchDialog(Collection<String> existingDirs) {
		this(existingDirs, false);
	}

	/**
	 * @param existingDirs
	 * @param fillSearch true to fill search results when initially displayed
	 */
	public RepositorySearchDialog(Collection<String> existingDirs,
			boolean fillSearch) {
		super(
				"searchPage", UIText.RepositorySearchDialog_SearchTitle, UIIcons.WIZBAN_IMPORT_REPO); //$NON-NLS-1$
		this.fExistingDirectories.addAll(existingDirs);
		this.fillSearch = fillSearch;
	}

	/**
	 *
	 * @return the directories
	 */
	public Set<String> getDirectories() {
		return fResult;
	}

	@Override
	public void dispose() {
		fResult = getCheckedItems();
		super.dispose();
	}

	@Override
	public void createControl(Composite parent) {
		setMessage(UIText.RepositorySearchDialog_searchRepositoriesMessage);

		Composite main = new Composite(parent, SWT.NONE);
		main.setLayout(new GridLayout(1, false));
		main.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

		Group searchGroup = new Group(main, SWT.SHADOW_ETCHED_IN);
		searchGroup.setText(UIText.RepositorySearchDialog_SearchCriteriaGroup);
		searchGroup.setLayout(new GridLayout(4, false));
		GridDataFactory.fillDefaults().grab(true, false)
				.minSize(SWT.DEFAULT, SWT.DEFAULT).applyTo(searchGroup);

		Label dirLabel = new Label(searchGroup, SWT.NONE);
		dirLabel.setText(UIText.RepositorySearchDialog_directory);
		dir = new Text(searchGroup, SWT.BORDER);
		GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER)
				.grab(true, false).hint(300, SWT.DEFAULT)
				.minSize(100, SWT.DEFAULT).applyTo(dir);
		dir.setToolTipText(UIText.RepositorySearchDialog_EnterDirectoryToolTip);

		String defaultRepoPath = RepositoryUtil.getDefaultRepositoryDir();

		String initialPath = prefs.get(PREF_PATH, defaultRepoPath);

		dir.setText(initialPath);

		Button browse = new Button(searchGroup, SWT.PUSH);
		browse.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				1, 1));
		browse.setText(UIText.RepositorySearchDialog_browse);
		browse.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				DirectoryDialog dd = new DirectoryDialog(getShell());
				dd.setFilterPath(dir.getText());
				String directory = dd.open();
				if (directory != null) {
					dir.setText(directory);
					prefs.put(PREF_PATH, directory);
					try {
						prefs.flush();
					} catch (BackingStoreException e1) {
						// ignore here
					}
					doSearch();
				}
			}

		});

		searchButton = new Button(searchGroup, SWT.PUSH);
		searchButton.setText(UIText.RepositorySearchDialog_Search);
		searchButton
				.setToolTipText(UIText.RepositorySearchDialog_SearchTooltip);
		searchButton.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				doSearch();
			}
		});

		lookForNestedButton = new Button(searchGroup, SWT.CHECK);
		lookForNestedButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER,
				false, false, 4, 1));
		lookForNestedButton.setSelection(prefs.getBoolean(PREF_DEEP_SEARCH,
				false));
		lookForNestedButton
				.setText(UIText.RepositorySearchDialog_DeepSearch_button);
		lookForNestedButton
				.setToolTipText(UIText.RepositorySearchDialog_SearchRecursiveToolTip);

		lookForNestedButton.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				prefs.putBoolean(PREF_DEEP_SEARCH, lookForNestedButton
						.getSelection());
				try {
					prefs.flush();
				} catch (BackingStoreException e1) {
					// ignore
				}
				setNeedsSearch();
			}

		});

		Group searchResultGroup = new Group(main, SWT.SHADOW_ETCHED_IN);
		searchResultGroup
				.setText(UIText.RepositorySearchDialog_SearchResultGroup);
		searchResultGroup.setLayout(new GridLayout(2, false));
		GridDataFactory.fillDefaults().grab(true, true).minSize(SWT.DEFAULT, 0)
				.applyTo(searchResultGroup);

		PatternFilter filter = new PatternFilter() {

			@Override
			public boolean isElementVisible(Viewer viewer, Object element) {
				if (getCheckedItems().contains(element)) {
						return true;
				}
				return super.isElementVisible(viewer, element);
			}
		};

		fTree = new FilteredCheckboxTree(searchResultGroup, null, SWT.NONE,
				filter);
		fTreeViewer = fTree.getCheckboxTreeViewer();
		fTreeViewer.addCheckStateListener(new ICheckStateListener() {

			@Override
			public void checkStateChanged(CheckStateChangedEvent event) {
				enableOk();
			}
		});

		// Set a reasonable minimum height here; otherwise the dialog comes up
		// with a tree that has only a few rows visible.
		GridDataFactory.fillDefaults().grab(true, true).minSize(0, 300)
				.applyTo(fTree);

		ToolBar toolbar = new ToolBar(searchResultGroup, SWT.FLAT
				| SWT.VERTICAL);
		GridDataFactory.fillDefaults().align(SWT.FILL, SWT.BEGINNING).applyTo(
				toolbar);

		checkAllItem = new ToolItem(toolbar, SWT.PUSH);
		checkAllItem
				.setToolTipText(UIText.RepositorySearchDialog_CheckAllRepositories);
		checkAllItem.setEnabled(false);
		Image checkImage = UIIcons.CHECK_ALL.createImage();
		UIUtils.hookDisposal(checkAllItem, checkImage);
		checkAllItem.setImage(checkImage);
		checkAllItem.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				fTreeViewer.setAllChecked(true);
				enableOk();
			}

		});

		uncheckAllItem = new ToolItem(toolbar, SWT.PUSH);
		uncheckAllItem
				.setToolTipText(UIText.RepositorySearchDialog_UncheckAllRepositories);
		uncheckAllItem.setEnabled(false);
		Image uncheckImage = UIIcons.UNCHECK_ALL.createImage();
		UIUtils.hookDisposal(uncheckAllItem, uncheckImage);
		uncheckAllItem.setImage(uncheckImage);
		uncheckAllItem.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				fTreeViewer.setAllChecked(false);
				enableOk();
			}

		});

		// TODO this isn't the most optimal way of handling this... ideally we
		// should have some type of delay
		// if we could use databinding an observeDelayedValue would totally work
		// here
		dir.addModifyListener(new ModifyListener() {

			@Override
			public void modifyText(ModifyEvent e) {
				setNeedsSearch();
			}

		});

		fTreeViewer.setContentProvider(new ContentProvider());
		fTreeViewer.setLabelProvider(new RepositoryLabelProvider());

		setControl(main);

		if (fillSearch)
			PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {

				@Override
				public void run() {
					if (!getControl().isDisposed())
						doSearch();
				}
			});
	}

	private void findGitDirsRecursive(File root, Set<File> strings,
			IProgressMonitor monitor, boolean lookForNestedRepositories) {

		if (!root.exists() || !root.isDirectory()) {
			return;
		}
		File[] children = root.listFiles();
		// simply ignore null
		if (children == null)
			return;

		for (File child : children) {
			if (monitor.isCanceled())
				return;
			if (!child.isDirectory())
				continue;

			File resolved = FileKey.resolve(child, FS.DETECTED);
			if (resolved != null) {
				strings.add(resolved.getAbsoluteFile());
				monitor.setTaskName(NLS.bind(
						UIText.RepositorySearchDialog_RepositoriesFound_message,
						Integer.valueOf(strings.size())));
			}
			else if (lookForNestedRepositories) {
				monitor.subTask(child.getPath());
				findGitDirsRecursive(child, strings, monitor,
						lookForNestedRepositories);
			}
		}
	}

	private HashSet<String> getCheckedItems() {
		HashSet<String> ret = new HashSet<String>();
		for (Object item : fTreeViewer.getCheckedLeafElements())
			ret.add((String) item);
		return ret;
	}

	private void doSearch() {
		setMessage(UIText.RepositorySearchDialog_searchRepositoriesMessage);
		setErrorMessage(null);
		// perform the search...
		final Set<File> directories = new HashSet<>();
		final File file = new File(dir.getText());
		final boolean lookForNested = lookForNestedButton.getSelection();
		if(!file.exists())
			return;

		prefs.put(PREF_PATH, file.getAbsolutePath());
		try {
			prefs.flush();
		} catch (BackingStoreException e1) {
			// ignore here
		}

		final TreeSet<String> validDirs = new TreeSet<String>(getCheckedItems());

		IRunnableWithProgress action = new IRunnableWithProgress() {

			@Override
			public void run(IProgressMonitor monitor)
					throws InvocationTargetException, InterruptedException {
				monitor.beginTask(
						UIText.RepositorySearchDialog_ScanningForRepositories_message,
						IProgressMonitor.UNKNOWN);
				try {
					findGitDirsRecursive(file, directories, monitor,
							lookForNested);
				} catch (Exception ex) {
					throw new InvocationTargetException(ex);
				}
				if (monitor.isCanceled()) {
					throw new InterruptedException();
				}
			}
		};
		try {
			getContainer().run(true, true, action);
		} catch (InvocationTargetException e1) {
			org.eclipse.egit.ui.Activator.handleError(
					UIText.RepositorySearchDialog_errorOccurred, e1.getCause(),
					true);
		} catch (InterruptedException e1) {
			// ignore
		}

		int foundOld = 0;

		for (File foundDir : directories) {
			String absolutePath = foundDir.getAbsolutePath();
			if (!fExistingDirectories.contains(absolutePath)
					&& !fExistingDirectories.contains(FileUtils
							.canonicalize(foundDir).getAbsolutePath())) {
				validDirs.add(absolutePath);
			} else {
				foundOld++;
			}
		}

		if (foundOld > 0) {
			String message = NLS.bind(
					UIText.RepositorySearchDialog_SomeDirectoriesHiddenMessage,
					Integer.valueOf(foundOld));
			setMessage(message, IMessageProvider.INFORMATION);
		} else if (directories.isEmpty())
			setMessage(UIText.RepositorySearchDialog_NothingFoundMessage,
					IMessageProvider.INFORMATION);

		checkAllItem.setEnabled(!validDirs.isEmpty());
		uncheckAllItem.setEnabled(!validDirs.isEmpty());
		fTree.clearFilter();
		// Remove the minimum height that was set initially so that we get a
		// scrollbar when the dialog is resized.
		GridDataFactory.fillDefaults().grab(true, true).applyTo(fTree);
		fTreeViewer.setInput(validDirs);

		if (!validDirs.isEmpty()) {
			fTree.getFilterControl().setFocus();
		}

		enableOk();
	}

	private void setNeedsSearch() {
		fTreeViewer.setInput(null);
		final File file = new File(dir.getText());
		if (!file.exists()) {
			setErrorMessage(NLS.bind(
					UIText.RepositorySearchDialog_DirectoryNotFoundMessage, dir
							.getText()));
		} else {
			setErrorMessage(null);
			setMessage(UIText.RepositorySearchDialog_NoSearchAvailableMessage,
					IMessageProvider.INFORMATION);
		}
		enableOk();
	}

	private void enableOk() {
		boolean enable = fTreeViewer.getCheckedElements().length > 0;
		setPageComplete(enable);
	}
}

Back to the top