Git Repositories View: fix Branch Creation page
[egit.git] / org.eclipse.egit.ui / src / org / eclipse / egit / ui / internal / repository / RepositoriesView.java
blob1a1be45080f25773b4fd593bf89f0fb6dc43e0db
1 /*******************************************************************************
2 * Copyright (c) 2010 SAP AG.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
8 * Contributors:
9 * Mathias Kinzler (SAP AG) - initial implementation
10 *******************************************************************************/
11 package org.eclipse.egit.ui.internal.repository;
13 import java.io.File;
14 import java.io.IOException;
15 import java.lang.reflect.InvocationTargetException;
16 import java.net.URISyntaxException;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.HashSet;
21 import java.util.List;
22 import java.util.Set;
23 import java.util.StringTokenizer;
24 import java.util.TreeSet;
26 import org.eclipse.core.filesystem.EFS;
27 import org.eclipse.core.filesystem.IFileStore;
28 import org.eclipse.core.resources.IProject;
29 import org.eclipse.core.resources.IResource;
30 import org.eclipse.core.resources.IWorkspace;
31 import org.eclipse.core.resources.IWorkspaceRunnable;
32 import org.eclipse.core.resources.ResourcesPlugin;
33 import org.eclipse.core.runtime.CoreException;
34 import org.eclipse.core.runtime.IAdaptable;
35 import org.eclipse.core.runtime.IPath;
36 import org.eclipse.core.runtime.IProgressMonitor;
37 import org.eclipse.core.runtime.IStatus;
38 import org.eclipse.core.runtime.NullProgressMonitor;
39 import org.eclipse.core.runtime.Path;
40 import org.eclipse.core.runtime.Status;
41 import org.eclipse.core.runtime.jobs.IJobChangeEvent;
42 import org.eclipse.core.runtime.jobs.Job;
43 import org.eclipse.core.runtime.jobs.JobChangeAdapter;
44 import org.eclipse.core.runtime.preferences.IEclipsePreferences;
45 import org.eclipse.core.runtime.preferences.InstanceScope;
46 import org.eclipse.egit.core.op.BranchOperation;
47 import org.eclipse.egit.core.project.RepositoryMapping;
48 import org.eclipse.egit.ui.Activator;
49 import org.eclipse.egit.ui.UIIcons;
50 import org.eclipse.egit.ui.UIText;
51 import org.eclipse.egit.ui.internal.clone.GitCloneWizard;
52 import org.eclipse.egit.ui.internal.clone.GitCreateProjectViaWizardWizard;
53 import org.eclipse.egit.ui.internal.repository.RepositoryTreeNode.RepositoryTreeNodeType;
54 import org.eclipse.jface.action.Action;
55 import org.eclipse.jface.action.IAction;
56 import org.eclipse.jface.action.IToolBarManager;
57 import org.eclipse.jface.action.Separator;
58 import org.eclipse.jface.dialogs.MessageDialog;
59 import org.eclipse.jface.dialogs.ProgressMonitorDialog;
60 import org.eclipse.jface.operation.IRunnableWithProgress;
61 import org.eclipse.jface.viewers.IOpenListener;
62 import org.eclipse.jface.viewers.ISelection;
63 import org.eclipse.jface.viewers.ISelectionChangedListener;
64 import org.eclipse.jface.viewers.ISelectionProvider;
65 import org.eclipse.jface.viewers.IStructuredSelection;
66 import org.eclipse.jface.viewers.ITreeContentProvider;
67 import org.eclipse.jface.viewers.OpenEvent;
68 import org.eclipse.jface.viewers.SelectionChangedEvent;
69 import org.eclipse.jface.viewers.StructuredSelection;
70 import org.eclipse.jface.viewers.TreeViewer;
71 import org.eclipse.jface.window.Window;
72 import org.eclipse.jface.wizard.Wizard;
73 import org.eclipse.jface.wizard.WizardDialog;
74 import org.eclipse.jgit.lib.Constants;
75 import org.eclipse.jgit.lib.Ref;
76 import org.eclipse.jgit.lib.RefUpdate;
77 import org.eclipse.jgit.lib.Repository;
78 import org.eclipse.jgit.lib.RepositoryCache;
79 import org.eclipse.jgit.lib.RepositoryConfig;
80 import org.eclipse.jgit.transport.RemoteConfig;
81 import org.eclipse.osgi.util.NLS;
82 import org.eclipse.swt.SWT;
83 import org.eclipse.swt.dnd.Clipboard;
84 import org.eclipse.swt.dnd.TextTransfer;
85 import org.eclipse.swt.dnd.Transfer;
86 import org.eclipse.swt.events.MenuDetectEvent;
87 import org.eclipse.swt.events.MenuDetectListener;
88 import org.eclipse.swt.events.SelectionAdapter;
89 import org.eclipse.swt.events.SelectionEvent;
90 import org.eclipse.swt.graphics.Point;
91 import org.eclipse.swt.widgets.Composite;
92 import org.eclipse.swt.widgets.Display;
93 import org.eclipse.swt.widgets.Menu;
94 import org.eclipse.swt.widgets.MenuItem;
95 import org.eclipse.swt.widgets.TreeItem;
96 import org.eclipse.ui.IEditorInput;
97 import org.eclipse.ui.IEditorPart;
98 import org.eclipse.ui.IFileEditorInput;
99 import org.eclipse.ui.IPageLayout;
100 import org.eclipse.ui.ISelectionListener;
101 import org.eclipse.ui.ISelectionService;
102 import org.eclipse.ui.IViewPart;
103 import org.eclipse.ui.IWorkbenchPart;
104 import org.eclipse.ui.PartInitException;
105 import org.eclipse.ui.PlatformUI;
106 import org.eclipse.ui.actions.ActionFactory;
107 import org.eclipse.ui.editors.text.EditorsUI;
108 import org.eclipse.ui.ide.FileStoreEditorInput;
109 import org.eclipse.ui.ide.IDE;
110 import org.eclipse.ui.part.IShowInTarget;
111 import org.eclipse.ui.part.ShowInContext;
112 import org.eclipse.ui.part.ViewPart;
113 import org.eclipse.ui.progress.IWorkbenchSiteProgressService;
114 import org.eclipse.ui.views.properties.IPropertySheetPage;
115 import org.eclipse.ui.views.properties.PropertySheet;
116 import org.eclipse.ui.views.properties.PropertySheetPage;
117 import org.osgi.service.prefs.BackingStoreException;
121 * The Git Repositories view.
122 * <p>
123 * This keeps track of a bunch of local directory names each of which represent
124 * a Git Repository. This list is stored in some Preferences object and used to
125 * build the tree in the view.
126 * <p>
127 * Implements {@link ISelectionProvider} in order to integrate with the
128 * Properties view.
129 * <p>
130 * TODO
131 * <li>Clarification whether to show projects, perhaps configurable switch</li>
134 public class RepositoriesView extends ViewPart implements ISelectionProvider,
135 IShowInTarget {
137 /** The view ID */
138 public static final String VIEW_ID = "org.eclipse.egit.ui.RepositoriesView"; //$NON-NLS-1$
140 // TODO central constants? RemoteConfig ones are private
141 static final String REMOTE = "remote"; //$NON-NLS-1$
143 static final String URL = "url"; //$NON-NLS-1$
145 static final String PUSHURL = "pushurl"; //$NON-NLS-1$
147 static final String FETCH = "fetch"; //$NON-NLS-1$
149 static final String PUSH = "push"; //$NON-NLS-1$
151 private static final String PREFS_DIRECTORIES = "GitRepositoriesView.GitDirectories"; //$NON-NLS-1$
153 private static final String PREFS_SYNCED = "GitRepositoriesView.SyncWithSelection"; //$NON-NLS-1$
155 private final List<ISelectionChangedListener> selectionListeners = new ArrayList<ISelectionChangedListener>();
157 private ISelection currentSelection = new StructuredSelection();
159 private Job scheduledJob;
161 private TreeViewer tv;
163 private IAction importAction;
165 private IAction addAction;
167 private IAction refreshAction;
169 private IAction linkWithSelectionAction;
171 private IAction copyAction;
173 private IAction pasteAction;
176 * TODO move to utility class
178 * @return the directories as configured for this view
180 public static List<String> getDirs() {
181 List<String> resultStrings = new ArrayList<String>();
182 String dirs = getPrefs().get(PREFS_DIRECTORIES, ""); //$NON-NLS-1$
183 if (dirs != null && dirs.length() > 0) {
184 StringTokenizer tok = new StringTokenizer(dirs, File.pathSeparator);
185 while (tok.hasMoreTokens()) {
186 String dirName = tok.nextToken();
187 File testFile = new File(dirName);
188 if (testFile.exists()) {
189 resultStrings.add(dirName);
193 Collections.sort(resultStrings);
194 return resultStrings;
197 private static void removeDir(File file) {
199 String dir;
200 try {
201 dir = file.getCanonicalPath();
202 } catch (IOException e1) {
203 dir = file.getAbsolutePath();
206 IEclipsePreferences prefs = getPrefs();
208 TreeSet<String> resultStrings = new TreeSet<String>();
209 String dirs = prefs.get(PREFS_DIRECTORIES, ""); //$NON-NLS-1$
210 if (dirs != null && dirs.length() > 0) {
211 StringTokenizer tok = new StringTokenizer(dirs, File.pathSeparator);
212 while (tok.hasMoreTokens()) {
213 String dirName = tok.nextToken();
214 File testFile = new File(dirName);
215 if (testFile.exists()) {
216 try {
217 resultStrings.add(testFile.getCanonicalPath());
218 } catch (IOException e) {
219 resultStrings.add(testFile.getAbsolutePath());
225 if (resultStrings.remove(dir)) {
226 StringBuilder sb = new StringBuilder();
227 for (String gitDirString : resultStrings) {
228 sb.append(gitDirString);
229 sb.append(File.pathSeparatorChar);
232 prefs.put(PREFS_DIRECTORIES, sb.toString());
233 try {
234 prefs.flush();
235 } catch (BackingStoreException e) {
236 IStatus error = new Status(IStatus.ERROR, Activator
237 .getPluginId(), e.getMessage(), e);
238 Activator.getDefault().getLog().log(error);
244 @Override
245 public Object getAdapter(Class adapter) {
246 // integrate with Properties view
247 if (adapter == IPropertySheetPage.class) {
248 PropertySheetPage page = new PropertySheetPage();
249 page
250 .setPropertySourceProvider(new RepositoryPropertySourceProvider(
251 page));
252 return page;
255 return super.getAdapter(adapter);
258 @Override
259 public void createPartControl(Composite parent) {
260 tv = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
261 tv.setContentProvider(new RepositoriesViewContentProvider());
262 // the label provider registers itself
263 new RepositoriesViewLabelProvider(tv);
265 getSite().setSelectionProvider(this);
267 tv.addSelectionChangedListener(new ISelectionChangedListener() {
269 public void selectionChanged(SelectionChangedEvent event) {
271 copyAction.setEnabled(false);
273 IStructuredSelection ssel = (IStructuredSelection) event
274 .getSelection();
275 if (ssel.size() == 1) {
276 RepositoryTreeNode node = (RepositoryTreeNode) ssel
277 .getFirstElement();
278 // allow copy on repository, file, or folder (copying the
279 // directory)
280 if (node.getType() == RepositoryTreeNodeType.REPO
281 || node.getType() == RepositoryTreeNodeType.WORKINGDIR
282 || node.getType() == RepositoryTreeNodeType.FOLDER
283 || node.getType() == RepositoryTreeNodeType.FILE) {
284 copyAction.setEnabled(true);
286 setSelection(new StructuredSelection(ssel.getFirstElement()));
287 } else {
288 setSelection(new StructuredSelection());
293 tv.addOpenListener(new IOpenListener() {
294 public void open(OpenEvent event) {
295 IStructuredSelection selection = (IStructuredSelection) event
296 .getSelection();
297 if (selection.isEmpty()) {
298 // nothing selected, ignore
299 return;
302 Object element = selection.getFirstElement();
303 ITreeContentProvider contentProvider = (ITreeContentProvider) tv
304 .getContentProvider();
305 if (contentProvider.hasChildren(element)) {
306 // this element has children, expand/collapse it
307 tv.setExpandedState(element, !tv.getExpandedState(element));
308 } else {
309 Object[] selectionArray = selection.toArray();
310 for (Object selectedElement : selectionArray) {
311 RepositoryTreeNode node = (RepositoryTreeNode) selectedElement;
312 // if any of the selected elements are not files, ignore
313 // the open request
314 if (node.getType() != RepositoryTreeNodeType.FILE
315 && node.getType() != RepositoryTreeNodeType.REF
316 && node.getType() != RepositoryTreeNodeType.TAG) {
317 return;
321 // open the files the user has selected
322 for (Object selectedElement : selectionArray) {
323 RepositoryTreeNode node = (RepositoryTreeNode) selectedElement;
324 if (node.getType() == RepositoryTreeNodeType.FILE)
325 openFile((File) node.getObject());
326 else if (node.getType() == RepositoryTreeNodeType.REF
327 || node.getType() == RepositoryTreeNodeType.TAG) {
328 Ref ref = (Ref) node.getObject();
329 if (!isBare(node.getRepository())
330 && ref.getName().startsWith(
331 Constants.R_REFS))
332 checkoutBranch(node, ref.getName());
339 addContextMenu();
341 addActionsToToolbar();
343 scheduleRefresh();
345 ISelectionService srv = (ISelectionService) getSite().getService(
346 ISelectionService.class);
347 srv.addPostSelectionListener(new ISelectionListener() {
349 public void selectionChanged(IWorkbenchPart part,
350 ISelection selection) {
352 // if the "link with selection" toggle is off, we're done
353 if (linkWithSelectionAction == null
354 || !linkWithSelectionAction.isChecked())
355 return;
357 // this may happen if we switch between editors
358 if (part instanceof IEditorPart) {
359 IEditorInput input = ((IEditorPart) part).getEditorInput();
360 if (input instanceof IFileEditorInput)
361 reactOnSelection(new StructuredSelection(
362 ((IFileEditorInput) input).getFile()));
364 } else {
365 reactOnSelection(selection);
372 private void reactOnSelection(ISelection selection) {
373 if (selection instanceof StructuredSelection) {
374 StructuredSelection ssel = (StructuredSelection) selection;
375 if (ssel.size() != 1)
376 return;
377 if (ssel.getFirstElement() instanceof IResource) {
378 showResource((IResource) ssel.getFirstElement());
380 if (ssel.getFirstElement() instanceof IAdaptable) {
381 IResource adapted = (IResource) ((IAdaptable) ssel
382 .getFirstElement()).getAdapter(IResource.class);
383 if (adapted != null)
384 showResource(adapted);
389 private void addContextMenu() {
390 tv.getTree().addMenuDetectListener(new MenuDetectListener() {
392 public void menuDetected(MenuDetectEvent e) {
393 Menu men = tv.getTree().getMenu();
394 if (men != null) {
395 men.dispose();
397 men = new Menu(tv.getTree());
399 TreeItem testItem = tv.getTree().getItem(
400 tv.getTree().toControl(new Point(e.x, e.y)));
401 if (testItem == null) {
402 addMenuItemsForPanel(men);
403 } else {
404 addMenuItemsForTreeSelection(men);
407 tv.getTree().setMenu(men);
412 private void addMenuItemsForPanel(Menu men) {
414 MenuItem importItem = new MenuItem(men, SWT.PUSH);
415 importItem.setText(UIText.RepositoriesView_ImportRepository_MenuItem);
416 importItem.addSelectionListener(new SelectionAdapter() {
418 @Override
419 public void widgetSelected(SelectionEvent e) {
420 importAction.run();
425 MenuItem addItem = new MenuItem(men, SWT.PUSH);
426 addItem.setText(UIText.RepositoriesView_AddRepository_MenuItem);
427 addItem.addSelectionListener(new SelectionAdapter() {
429 @Override
430 public void widgetSelected(SelectionEvent e) {
431 addAction.run();
436 MenuItem pasteItem = new MenuItem(men, SWT.PUSH);
437 pasteItem.setText(UIText.RepositoriesView_PasteMenu);
438 pasteItem.addSelectionListener(new SelectionAdapter() {
440 @Override
441 public void widgetSelected(SelectionEvent e) {
442 pasteAction.run();
447 MenuItem refreshItem = new MenuItem(men, SWT.PUSH);
448 refreshItem.setText(refreshAction.getText());
449 refreshItem.addSelectionListener(new SelectionAdapter() {
451 @Override
452 public void widgetSelected(SelectionEvent e) {
453 refreshAction.run();
460 private void addMenuItemsForTreeSelection(Menu men) {
462 final IStructuredSelection sel = (IStructuredSelection) tv
463 .getSelection();
465 boolean repoOnly = true;
466 for (Object selected : sel.toArray()) {
468 if (((RepositoryTreeNode) selected).getType() != RepositoryTreeNodeType.REPO) {
469 repoOnly = false;
470 break;
474 if (sel.size() > 1 && repoOnly) {
475 List nodes = sel.toList();
476 final Repository[] repos = new Repository[nodes.size()];
477 for (int i = 0; i < sel.size(); i++)
478 repos[i] = ((RepositoryTreeNode) nodes.get(i)).getRepository();
480 MenuItem remove = new MenuItem(men, SWT.PUSH);
481 remove.setText(UIText.RepositoriesView_Remove_MenuItem);
482 remove.addSelectionListener(new SelectionAdapter() {
484 @Override
485 public void widgetSelected(SelectionEvent e) {
486 // TODO progress monitoring/cancellation
487 removeRepository(new NullProgressMonitor(), repos);
493 // from here on, we only deal with single selection
494 if (sel.size() > 1)
495 return;
497 final RepositoryTreeNode node = (RepositoryTreeNode) sel
498 .getFirstElement();
500 final boolean isBare = isBare(node.getRepository());
502 if (node.getType() == RepositoryTreeNodeType.REF) {
504 final Ref ref = (Ref) node.getObject();
506 // we don't check out symbolic references
507 if (!ref.isSymbolic()) {
509 if (!isBare) {
510 MenuItem checkout = new MenuItem(men, SWT.PUSH);
511 checkout.setText(UIText.RepositoriesView_CheckOut_MenuItem);
513 checkout.setEnabled(!isRefCheckedOut(node.getRepository(),
514 ref.getName()));
516 checkout.addSelectionListener(new SelectionAdapter() {
518 @Override
519 public void widgetSelected(SelectionEvent e) {
520 checkoutBranch(node, ref.getLeaf().getName());
524 new MenuItem(men, SWT.SEPARATOR);
527 createCreateBranchItem(men, node);
528 createDeleteBranchItem(men, node);
533 if (node.getType() == RepositoryTreeNodeType.TAG) {
535 final Ref ref = (Ref) node.getObject();
537 MenuItem checkout = new MenuItem(men, SWT.PUSH);
538 checkout.setText(UIText.RepositoriesView_CheckOut_MenuItem);
540 checkout.setEnabled(!isRefCheckedOut(node.getRepository(), ref
541 .getName()));
543 checkout.addSelectionListener(new SelectionAdapter() {
545 @Override
546 public void widgetSelected(SelectionEvent e) {
547 checkoutBranch(node, ref.getLeaf().getName());
552 if (node.getType() == RepositoryTreeNodeType.BRANCHES
553 || node.getType() == RepositoryTreeNodeType.LOCALBRANCHES)
554 // offering this on the "Remote Branches" node would probably be
555 // confusing
556 createCreateBranchItem(men, node);
558 // for Repository: import existing projects, remove, (delete), open
559 // properties
560 if (node.getType() == RepositoryTreeNodeType.REPO) {
562 final Repository repo = (Repository) node.getObject();
564 // TODO "import existing plug-in" menu item
566 MenuItem remove = new MenuItem(men, SWT.PUSH);
567 remove.setText(UIText.RepositoriesView_Remove_MenuItem);
568 remove.addSelectionListener(new SelectionAdapter() {
570 @Override
571 public void widgetSelected(SelectionEvent e) {
572 // TODO progress monitoring/cancellation
573 removeRepository(new NullProgressMonitor(), repo);
577 // TODO delete does not work because of file locks on .pack-files
578 // Shawn Pearce has added the following thoughts:
580 // Hmm. We probably can't active detect file locks on pack files on
581 // Windows, can we?
582 // It would be nice if we could support a delete, but only if the
583 // repository is
584 // reasonably believed to be not-in-use right now.
586 // Within EGit you might be able to check GitProjectData and its
587 // repositoryCache to
588 // see if the repository is open by this workspace. If it is, then
589 // we know we shouldn't
590 // try to delete it.
592 // Some coding might look like this:
594 // MenuItem deleteRepo = new MenuItem(men, SWT.PUSH);
595 // deleteRepo.setText("Delete");
596 // deleteRepo.addSelectionListener(new SelectionAdapter() {
598 // @Override
599 // public void widgetSelected(SelectionEvent e) {
601 // boolean confirmed = MessageDialog.openConfirm(getSite()
602 // .getShell(), "Confirm",
603 // "This will delete the repository, continue?");
605 // if (!confirmed)
606 // return;
608 // IWorkspaceRunnable wsr = new IWorkspaceRunnable() {
610 // public void run(IProgressMonitor monitor)
611 // throws CoreException {
612 // File workDir = repos.get(0).getRepository()
613 // .getWorkDir();
615 // File gitDir = repos.get(0).getRepository()
616 // .getDirectory();
618 // IPath wdPath = new Path(workDir.getAbsolutePath());
619 // for (IProject prj : ResourcesPlugin.getWorkspace()
620 // .getRoot().getProjects()) {
621 // if (wdPath.isPrefixOf(prj.getLocation())) {
622 // prj.delete(false, false, monitor);
623 // }
624 // }
626 // repos.get(0).getRepository().close();
628 // boolean deleted = deleteRecursively(gitDir, monitor);
629 // if (!deleted) {
630 // MessageDialog.openError(getSite().getShell(),
631 // "Error",
632 // "Could not delete Git Repository");
633 // }
635 // deleted = deleteRecursively(workDir, monitor);
636 // if (!deleted) {
637 // MessageDialog
638 // .openError(getSite().getShell(),
639 // "Error",
640 // "Could not delete Git Working Directory");
641 // }
643 // scheduleRefresh();
644 // }
646 // private boolean deleteRecursively(File fileToDelete,
647 // IProgressMonitor monitor) {
648 // if (fileToDelete.isDirectory()) {
649 // for (File file : fileToDelete.listFiles()) {
650 // if (!deleteRecursively(file, monitor)) {
651 // return false;
652 // }
653 // }
654 // }
655 // monitor.setTaskName(fileToDelete.getAbsolutePath());
656 // boolean deleted = fileToDelete.delete();
657 // if (!deleted) {
658 // System.err.println("Could not delete "
659 // + fileToDelete.getAbsolutePath());
660 // }
661 // return deleted;
662 // }
663 // };
665 // try {
666 // ResourcesPlugin.getWorkspace().run(wsr,
667 // ResourcesPlugin.getWorkspace().getRoot(),
668 // IWorkspace.AVOID_UPDATE,
669 // new NullProgressMonitor());
670 // } catch (CoreException e1) {
671 // // TODO Exception handling
672 // e1.printStackTrace();
673 // }
675 // }
677 // });
679 new MenuItem(men, SWT.SEPARATOR);
681 if (!isBare) {
682 createImportProjectItem(men, repo, repo.getWorkDir().getPath());
684 new MenuItem(men, SWT.SEPARATOR);
687 MenuItem openPropsView = new MenuItem(men, SWT.PUSH);
688 openPropsView.setText(UIText.RepositoriesView_OpenPropertiesMenu);
689 openPropsView.addSelectionListener(new SelectionAdapter() {
691 @Override
692 public void widgetSelected(SelectionEvent e) {
693 try {
694 PlatformUI.getWorkbench().getActiveWorkbenchWindow()
695 .getActivePage().showView(
696 IPageLayout.ID_PROP_SHEET);
697 } catch (PartInitException e1) {
698 // just ignore
704 new MenuItem(men, SWT.SEPARATOR);
706 createCopyPathItem(men, repo.getDirectory().getPath());
709 if (node.getType() == RepositoryTreeNodeType.REMOTES) {
711 MenuItem remoteConfig = new MenuItem(men, SWT.PUSH);
712 remoteConfig.setText(UIText.RepositoriesView_NewRemoteMenu);
713 remoteConfig.addSelectionListener(new SelectionAdapter() {
715 @Override
716 public void widgetSelected(SelectionEvent e) {
718 WizardDialog dlg = new WizardDialog(getSite().getShell(),
719 new NewRemoteWizard(node.getRepository()));
720 if (dlg.open() == Window.OK)
721 scheduleRefresh();
728 if (node.getType() == RepositoryTreeNodeType.REMOTE) {
730 final String configName = (String) node.getObject();
732 RemoteConfig rconfig;
733 try {
734 rconfig = new RemoteConfig(node.getRepository().getConfig(),
735 configName);
736 } catch (URISyntaxException e2) {
737 // TODO Exception handling
738 rconfig = null;
741 boolean fetchExists = rconfig != null
742 && !rconfig.getURIs().isEmpty();
743 boolean pushExists = rconfig != null
744 && !rconfig.getPushURIs().isEmpty();
746 if (!fetchExists) {
747 MenuItem configureUrlFetch = new MenuItem(men, SWT.PUSH);
748 configureUrlFetch
749 .setText(UIText.RepositoriesView_CreateFetch_menu);
751 configureUrlFetch.addSelectionListener(new SelectionAdapter() {
753 @Override
754 public void widgetSelected(SelectionEvent e) {
756 WizardDialog dlg = new WizardDialog(getSite()
757 .getShell(), new ConfigureRemoteWizard(node
758 .getRepository(), configName, false));
759 if (dlg.open() == Window.OK)
760 scheduleRefresh();
767 if (!pushExists) {
768 MenuItem configureUrlPush = new MenuItem(men, SWT.PUSH);
770 configureUrlPush
771 .setText(UIText.RepositoriesView_CreatePush_menu);
773 configureUrlPush.addSelectionListener(new SelectionAdapter() {
775 @Override
776 public void widgetSelected(SelectionEvent e) {
778 WizardDialog dlg = new WizardDialog(getSite()
779 .getShell(), new ConfigureRemoteWizard(node
780 .getRepository(), configName, true));
781 if (dlg.open() == Window.OK)
782 scheduleRefresh();
789 if (!fetchExists || !pushExists)
790 // add a separator dynamically
791 new MenuItem(men, SWT.SEPARATOR);
793 MenuItem removeRemote = new MenuItem(men, SWT.PUSH);
794 removeRemote.setText(UIText.RepositoriesView_RemoveRemoteMenu);
795 removeRemote.addSelectionListener(new SelectionAdapter() {
797 @Override
798 public void widgetSelected(SelectionEvent e) {
800 boolean ok = MessageDialog
801 .openConfirm(
802 getSite().getShell(),
803 UIText.RepositoriesView_ConfirmDeleteRemoteHeader,
805 .bind(
806 UIText.RepositoriesView_ConfirmDeleteRemoteMessage,
807 configName));
808 if (ok) {
809 RepositoryConfig config = node.getRepository()
810 .getConfig();
811 config.unsetSection(REMOTE, configName);
812 try {
813 config.save();
814 scheduleRefresh();
815 } catch (IOException e1) {
816 Activator.handleError(
817 UIText.RepositoriesView_ErrorHeader, e1,
818 true);
826 new MenuItem(men, SWT.SEPARATOR);
828 MenuItem openPropsView = new MenuItem(men, SWT.PUSH);
829 openPropsView.setText(UIText.RepositoriesView_OpenPropertiesMenu);
830 openPropsView.addSelectionListener(new SelectionAdapter() {
832 @Override
833 public void widgetSelected(SelectionEvent e) {
834 try {
835 PlatformUI.getWorkbench().getActiveWorkbenchWindow()
836 .getActivePage().showView(
837 IPageLayout.ID_PROP_SHEET);
838 } catch (PartInitException e1) {
839 // just ignore
846 if (node.getType() == RepositoryTreeNodeType.FETCH) {
848 final String configName = (String) node.getParent().getObject();
850 MenuItem configureUrlFetch = new MenuItem(men, SWT.PUSH);
851 configureUrlFetch
852 .setText(UIText.RepositoriesView_ConfigureFetchMenu);
854 configureUrlFetch.addSelectionListener(new SelectionAdapter() {
856 @Override
857 public void widgetSelected(SelectionEvent e) {
859 WizardDialog dlg = new WizardDialog(getSite().getShell(),
860 new ConfigureRemoteWizard(node.getRepository(),
861 configName, false));
862 if (dlg.open() == Window.OK)
863 scheduleRefresh();
869 MenuItem deleteFetch = new MenuItem(men, SWT.PUSH);
870 deleteFetch.setText(UIText.RepositoriesView_RemoveFetch_menu);
871 deleteFetch.addSelectionListener(new SelectionAdapter() {
873 @Override
874 public void widgetSelected(SelectionEvent e) {
875 RepositoryConfig config = node.getRepository().getConfig();
876 config.unset("remote", configName, "url"); //$NON-NLS-1$ //$NON-NLS-2$
877 config.unset("remote", configName, "fetch"); //$NON-NLS-1$//$NON-NLS-2$
878 try {
879 config.save();
880 scheduleRefresh();
881 } catch (IOException e1) {
882 MessageDialog.openError(getSite().getShell(),
883 UIText.RepositoriesView_ErrorHeader, e1
884 .getMessage());
892 if (node.getType() == RepositoryTreeNodeType.PUSH) {
894 final String configName = (String) node.getParent().getObject();
896 MenuItem configureUrlPush = new MenuItem(men, SWT.PUSH);
898 configureUrlPush.setText(UIText.RepositoriesView_ConfigurePushMenu);
900 configureUrlPush.addSelectionListener(new SelectionAdapter() {
902 @Override
903 public void widgetSelected(SelectionEvent e) {
905 WizardDialog dlg = new WizardDialog(getSite().getShell(),
906 new ConfigureRemoteWizard(node.getRepository(),
907 configName, true));
908 if (dlg.open() == Window.OK)
909 scheduleRefresh();
914 MenuItem deleteFetch = new MenuItem(men, SWT.PUSH);
915 deleteFetch.setText(UIText.RepositoriesView_RemovePush_menu);
916 deleteFetch.addSelectionListener(new SelectionAdapter() {
918 @Override
919 public void widgetSelected(SelectionEvent e) {
920 RepositoryConfig config = node.getRepository().getConfig();
921 config.unset("remote", configName, "pushurl"); //$NON-NLS-1$ //$NON-NLS-2$
922 config.unset("remote", configName, "push"); //$NON-NLS-1$ //$NON-NLS-2$
923 try {
924 config.save();
925 scheduleRefresh();
926 } catch (IOException e1) {
927 MessageDialog.openError(getSite().getShell(),
928 UIText.RepositoriesView_ErrorHeader, e1
929 .getMessage());
936 if (node.getType() == RepositoryTreeNodeType.FILE) {
938 final File file = (File) node.getObject();
940 MenuItem openInTextEditor = new MenuItem(men, SWT.PUSH);
941 openInTextEditor
942 .setText(UIText.RepositoriesView_OpenInTextEditor_menu);
943 openInTextEditor.addSelectionListener(new SelectionAdapter() {
945 @Override
946 public void widgetSelected(SelectionEvent e) {
947 openFile(file);
952 new MenuItem(men, SWT.SEPARATOR);
953 createCopyPathItem(men, file.getPath());
956 if (!isBare && node.getType() == RepositoryTreeNodeType.WORKINGDIR) {
957 String path = node.getRepository().getWorkDir().getAbsolutePath();
958 createImportProjectItem(men, node.getRepository(), path);
959 new MenuItem(men, SWT.SEPARATOR);
960 createCopyPathItem(men, path);
963 if (node.getType() == RepositoryTreeNodeType.FOLDER) {
964 String path = ((File) node.getObject()).getPath();
965 createImportProjectItem(men, node.getRepository(), path);
966 new MenuItem(men, SWT.SEPARATOR);
967 createCopyPathItem(men, path);
972 private boolean isBare(Repository repository) {
973 return repository.getConfig().getBoolean("core", "bare", false); //$NON-NLS-1$ //$NON-NLS-2$
976 private boolean isRefCheckedOut(Repository repository, String refName) {
977 String branchName;
978 String compareString;
980 try {
981 branchName = repository.getFullBranch();
982 if (branchName == null)
983 return false;
984 if (refName.startsWith(Constants.R_HEADS)) {
985 // local branch: HEAD would be on the branch
986 compareString = refName;
987 } else if (refName.startsWith(Constants.R_TAGS)) {
988 // tag: HEAD would be on the commit id to which the tag is
989 // pointing
990 compareString = repository.mapTag(refName).getObjId().getName();
991 } else if (refName.startsWith(Constants.R_REMOTES)) {
992 // remote branch: HEAD would be on the commit id to which
993 // the branch is pointing
994 compareString = repository.mapCommit(refName).getCommitId()
995 .getName();
996 } else {
997 // some other symbolic reference
998 return false;
1000 } catch (IOException e1) {
1001 return false;
1004 return compareString.equals(branchName);
1007 private void createCopyPathItem(Menu men, final String path) {
1009 MenuItem copyPath;
1010 copyPath = new MenuItem(men, SWT.PUSH);
1011 copyPath.setText(UIText.RepositoriesView_CopyPathToClipboardMenu);
1012 copyPath.addSelectionListener(new SelectionAdapter() {
1014 @Override
1015 public void widgetSelected(SelectionEvent e) {
1016 Clipboard clipboard = new Clipboard(null);
1017 TextTransfer textTransfer = TextTransfer.getInstance();
1018 Transfer[] transfers = new Transfer[] { textTransfer };
1019 Object[] data = new Object[] { path };
1020 clipboard.setContents(data, transfers);
1021 clipboard.dispose();
1028 private void createCreateBranchItem(Menu men, final RepositoryTreeNode node) {
1029 final Ref ref;
1030 if (node.getType() == RepositoryTreeNodeType.REF)
1031 ref = (Ref) node.getObject();
1032 else
1033 ref = null;
1035 MenuItem createLocal = new MenuItem(men, SWT.PUSH);
1036 createLocal.setText(UIText.RepositoriesView_NewBranchMenu);
1038 createLocal.addSelectionListener(new SelectionAdapter() {
1040 @Override
1041 public void widgetSelected(SelectionEvent e) {
1043 Wizard wiz = new Wizard() {
1045 @Override
1046 public void addPages() {
1047 addPage(new CreateBranchPage(node.getRepository(), ref));
1048 setWindowTitle(UIText.RepositoriesView_NewBranchTitle);
1051 @Override
1052 public boolean performFinish() {
1054 try {
1055 getContainer().run(false, true,
1056 new IRunnableWithProgress() {
1058 public void run(IProgressMonitor monitor)
1059 throws InvocationTargetException,
1060 InterruptedException {
1061 CreateBranchPage cp = (CreateBranchPage) getPages()[0];
1062 try {
1063 cp.createBranch(monitor);
1064 } catch (CoreException ce) {
1065 throw new InvocationTargetException(
1066 ce);
1067 } catch (IOException ioe) {
1068 throw new InvocationTargetException(
1069 ioe);
1074 } catch (InvocationTargetException ite) {
1075 Activator
1076 .handleError(
1077 UIText.RepositoriesView_BranchCreationFailureMessage,
1078 ite.getCause(), true);
1079 return false;
1080 } catch (InterruptedException ie) {
1081 // ignore here
1083 return true;
1086 if (new WizardDialog(getSite().getShell(), wiz).open() == Window.OK)
1087 scheduleRefresh();
1093 private void createDeleteBranchItem(Menu men, final RepositoryTreeNode node) {
1095 final Ref ref = (Ref) node.getObject();
1097 MenuItem deleteBranch = new MenuItem(men, SWT.PUSH);
1098 deleteBranch.setText(UIText.RepositoriesView_DeleteBranchMenu);
1100 deleteBranch.setEnabled(!isRefCheckedOut(node.getRepository(), ref
1101 .getName()));
1103 deleteBranch.addSelectionListener(new SelectionAdapter() {
1105 @Override
1106 public void widgetSelected(SelectionEvent e) {
1108 if (!MessageDialog
1109 .openConfirm(
1110 getSite().getShell(),
1111 UIText.RepositoriesView_ConfirmDeleteTitle,
1113 .bind(
1114 UIText.RepositoriesView_ConfirmBranchDeletionMessage,
1115 ref.getName())))
1116 return;
1118 try {
1119 new ProgressMonitorDialog(getSite().getShell()).run(false,
1120 false, new IRunnableWithProgress() {
1122 public void run(IProgressMonitor monitor)
1123 throws InvocationTargetException,
1124 InterruptedException {
1126 try {
1127 RefUpdate op = node.getRepository()
1128 .updateRef(ref.getName());
1129 op.setRefLogMessage("branch deleted", //$NON-NLS-1$
1130 false);
1131 // we set the force update in order
1132 // to avoid having this rejected
1133 // due to minor issues
1134 op.setForceUpdate(true);
1135 op.delete();
1136 scheduleRefresh();
1137 } catch (IOException ioe) {
1138 throw new InvocationTargetException(ioe);
1143 } catch (InvocationTargetException e1) {
1144 Activator
1145 .handleError(
1146 UIText.RepositoriesView_BranchDeletionFailureMessage,
1147 e1.getCause(), true);
1148 e1.printStackTrace();
1149 } catch (InterruptedException e1) {
1150 // ignore
1158 private void openFile(File file) {
1159 IFileStore store = EFS.getLocalFileSystem().getStore(
1160 new Path(file.getAbsolutePath()));
1161 try {
1162 // TODO do we need a read-only editor here?
1163 IDE.openEditor(getSite().getPage(),
1164 new FileStoreEditorInput(store),
1165 EditorsUI.DEFAULT_TEXT_EDITOR_ID);
1166 } catch (PartInitException e) {
1167 Activator.handleError(UIText.RepositoriesView_Error_WindowTitle, e,
1168 true);
1172 private void checkoutBranch(final RepositoryTreeNode node,
1173 final String refName) {
1174 // for the sake of UI responsiveness, let's start a job
1175 Job job = new Job(NLS.bind(UIText.RepositoriesView_CheckingOutMessage,
1176 refName)) {
1178 @Override
1179 protected IStatus run(IProgressMonitor monitor) {
1181 Repository repo = node.getRepository();
1183 final BranchOperation op = new BranchOperation(repo, refName);
1184 IWorkspaceRunnable wsr = new IWorkspaceRunnable() {
1186 public void run(IProgressMonitor myMonitor)
1187 throws CoreException {
1188 op.execute(myMonitor);
1192 try {
1193 ResourcesPlugin.getWorkspace().run(wsr,
1194 ResourcesPlugin.getWorkspace().getRoot(),
1195 IWorkspace.AVOID_UPDATE, monitor);
1196 scheduleRefresh();
1197 } catch (CoreException e1) {
1198 return new Status(IStatus.ERROR, Activator.getPluginId(),
1199 e1.getMessage(), e1);
1202 return Status.OK_STATUS;
1206 job.setUser(true);
1207 job.schedule();
1210 private void createImportProjectItem(Menu men, final Repository repo,
1211 final String path) {
1213 MenuItem startWizard;
1214 startWizard = new MenuItem(men, SWT.PUSH);
1215 startWizard.setText(UIText.RepositoriesView_ImportProjectsMenu);
1216 startWizard.addSelectionListener(new SelectionAdapter() {
1218 @Override
1219 public void widgetSelected(SelectionEvent e) {
1220 WizardDialog dlg = new WizardDialog(getSite().getShell(),
1221 new GitCreateProjectViaWizardWizard(repo, path));
1222 if (dlg.open() == Window.OK)
1223 scheduleRefresh();
1229 // we could start the ImportWizard here,
1230 // unfortunately, this fails within a wizard
1231 // startWizard = new MenuItem(men, SWT.PUSH);
1232 // startWizard.setText("Start the Import wizard...");
1233 // startWizard.addSelectionListener(new SelectionAdapter() {
1235 // @Override
1236 // public void widgetSelected(SelectionEvent e) {
1238 // IHandlerService handlerService = (IHandlerService) getSite()
1239 // .getWorkbenchWindow().getWorkbench().getService(
1240 // IHandlerService.class);
1242 // try {
1243 // handlerService.executeCommand("org.eclipse.ui.file.import", //$NON-NLS-1$
1244 // null);
1245 // } catch (ExecutionException e1) {
1246 // Activator.handleError(e1.getMessage(), e1, true);
1247 // } catch (NotDefinedException e1) {
1248 // Activator.handleError(e1.getMessage(), e1, true);
1249 // } catch (NotEnabledException e1) {
1250 // Activator.handleError(e1.getMessage(), e1, true);
1251 // } catch (NotHandledException e1) {
1252 // Activator.handleError(e1.getMessage(), e1, true);
1253 // }
1254 // }
1256 // });
1259 private void addActionsToToolbar() {
1261 IToolBarManager manager = getViewSite().getActionBars()
1262 .getToolBarManager();
1264 refreshAction = new Action(UIText.RepositoriesView_Refresh_Button) {
1266 @Override
1267 public void run() {
1268 scheduleRefresh();
1271 refreshAction.setImageDescriptor(UIIcons.ELCL16_REFRESH);
1272 manager.add(refreshAction);
1274 linkWithSelectionAction = new Action(
1275 UIText.RepositoriesView_LinkWithSelection_action,
1276 IAction.AS_CHECK_BOX) {
1278 @Override
1279 public void run() {
1280 IEclipsePreferences prefs = getPrefs();
1281 prefs.putBoolean(PREFS_SYNCED, isChecked());
1282 try {
1283 prefs.flush();
1284 } catch (BackingStoreException e) {
1285 // ignore here
1287 if (isChecked()) {
1288 ISelectionService srv = (ISelectionService) getSite()
1289 .getService(ISelectionService.class);
1290 reactOnSelection(srv.getSelection());
1297 linkWithSelectionAction
1298 .setToolTipText(UIText.RepositoriesView_LinkWithSelection_action);
1299 linkWithSelectionAction.setImageDescriptor(UIIcons.ELCL16_SYNCED);
1300 linkWithSelectionAction.setChecked(getPrefs().getBoolean(PREFS_SYNCED,
1301 false));
1303 manager.add(linkWithSelectionAction);
1305 manager.add(new Separator());
1307 IAction collapseAllAction = new Action(
1308 UIText.RepositoriesView_CollapseAllMenu) {
1310 @Override
1311 public void run() {
1312 tv.collapseAll();
1315 collapseAllAction.setImageDescriptor(UIIcons.COLLAPSEALL);
1316 manager.add(collapseAllAction);
1318 manager.add(new Separator());
1320 importAction = new Action(UIText.RepositoriesView_Import_Button) {
1322 @Override
1323 public void run() {
1324 WizardDialog dlg = new WizardDialog(getSite().getShell(),
1325 new GitCloneWizard());
1326 if (dlg.open() == Window.OK)
1327 scheduleRefresh();
1330 importAction.setToolTipText(UIText.RepositoriesView_Clone_Tooltip);
1331 importAction.setImageDescriptor(UIIcons.CLONEGIT);
1333 manager.add(importAction);
1335 addAction = new Action(UIText.RepositoriesView_Add_Button) {
1337 @Override
1338 public void run() {
1339 RepositorySearchDialog sd = new RepositorySearchDialog(
1340 getSite().getShell(), getDirs());
1341 if (sd.open() == Window.OK) {
1342 Set<String> dirs = new HashSet<String>();
1343 dirs.addAll(getDirs());
1344 if (dirs.addAll(sd.getDirectories()))
1345 saveDirs(dirs);
1346 scheduleRefresh();
1351 addAction.setToolTipText(UIText.RepositoriesView_AddRepository_Tooltip);
1352 addAction.setImageDescriptor(UIIcons.NEW_REPOSITORY);
1354 manager.add(addAction);
1356 // copy and paste are global actions; we just implement them
1357 // and register them with the global action handler
1358 // we enable/disable them upon tree selection changes
1360 copyAction = new Action("") { //$NON-NLS-1$
1362 @Override
1363 public void run() {
1364 // for REPO, WORKINGDIR, FILE, FOLDER: copy directory
1365 IStructuredSelection sel = (IStructuredSelection) tv
1366 .getSelection();
1367 if (sel.size() == 1) {
1368 RepositoryTreeNode node = (RepositoryTreeNode) sel
1369 .getFirstElement();
1370 String dir = null;
1371 if (node.getType() == RepositoryTreeNodeType.REPO) {
1372 dir = node.getRepository().getDirectory().getPath();
1373 } else if (node.getType() == RepositoryTreeNodeType.FILE
1374 || node.getType() == RepositoryTreeNodeType.FOLDER) {
1375 dir = ((File) node.getObject()).getPath();
1376 } else if (node.getType() == RepositoryTreeNodeType.WORKINGDIR) {
1377 if (!isBare(node.getRepository()))
1378 dir = node.getRepository().getWorkDir().getPath();
1380 if (dir != null) {
1381 Clipboard clip = null;
1382 try {
1383 clip = new Clipboard(getSite().getShell()
1384 .getDisplay());
1385 clip
1386 .setContents(new Object[] { dir },
1387 new Transfer[] { TextTransfer
1388 .getInstance() });
1389 } finally {
1390 if (clip != null)
1391 // we must dispose ourselves
1392 clip.dispose();
1399 copyAction.setEnabled(false);
1401 getViewSite().getActionBars().setGlobalActionHandler(
1402 ActionFactory.COPY.getId(), copyAction);
1404 pasteAction = new Action("") { //$NON-NLS-1$
1406 @Override
1407 public void run() {
1408 // we check if the pasted content is a directory
1409 // repository location and try to add this
1410 String errorMessage = null;
1412 Clipboard clip = null;
1413 try {
1414 clip = new Clipboard(getSite().getShell().getDisplay());
1415 String content = (String) clip.getContents(TextTransfer
1416 .getInstance());
1417 if (content == null) {
1418 errorMessage = UIText.RepositoriesView_NothingToPasteMessage;
1419 return;
1422 File file = new File(content);
1423 if (!file.exists() || !file.isDirectory()) {
1424 errorMessage = UIText.RepositoriesView_ClipboardContentNotDirectoryMessage;
1425 return;
1428 if (!RepositoryCache.FileKey.isGitRepository(file)) {
1429 errorMessage = NLS
1430 .bind(
1431 UIText.RepositoriesView_ClipboardContentNoGitRepoMessage,
1432 content);
1433 return;
1436 if (addDir(file))
1437 scheduleRefresh();
1438 else
1439 errorMessage = NLS.bind(
1440 UIText.RepositoriesView_PasteRepoAlreadyThere,
1441 content);
1442 } finally {
1443 if (clip != null)
1444 // we must dispose ourselves
1445 clip.dispose();
1446 if (errorMessage != null)
1447 // TODO String ext
1448 MessageDialog.openWarning(getSite().getShell(),
1449 UIText.RepositoriesView_PasteFailureTitle,
1450 errorMessage);
1456 getViewSite().getActionBars().setGlobalActionHandler(
1457 ActionFactory.PASTE.getId(), pasteAction);
1462 * @return the preferences
1464 protected static IEclipsePreferences getPrefs() {
1465 return new InstanceScope().getNode(Activator.getPluginId());
1468 @Override
1469 public void dispose() {
1470 // make sure to cancel the refresh job
1471 if (this.scheduledJob != null) {
1472 this.scheduledJob.cancel();
1473 this.scheduledJob = null;
1475 super.dispose();
1479 * Schedules a refreh
1481 public void scheduleRefresh() {
1483 Job job = new Job("Refreshing Git Repositories view") { //$NON-NLS-1$
1485 @Override
1486 protected IStatus run(IProgressMonitor monitor) {
1488 final List<RepositoryTreeNode<Repository>> input;
1489 try {
1490 input = getRepositoriesFromDirs(monitor);
1491 } catch (InterruptedException e) {
1492 return new Status(IStatus.ERROR, Activator.getPluginId(), e
1493 .getMessage(), e);
1496 boolean needsNewInput = tv.getInput() == null;
1497 List oldInput = (List) tv.getInput();
1498 if (!needsNewInput)
1499 needsNewInput = oldInput.size() != input.size();
1501 if (!needsNewInput) {
1502 for (int i = 0; i < input.size(); i++) {
1503 needsNewInput = !input.get(i).equals(oldInput.get(i));
1504 if (needsNewInput)
1505 break;
1509 final boolean updateInput = needsNewInput;
1511 Display.getDefault().syncExec(new Runnable() {
1513 public void run() {
1514 // keep expansion state and selection so that we can
1515 // restore the tree
1516 // after update
1517 Object[] expanded = tv.getExpandedElements();
1518 IStructuredSelection sel = (IStructuredSelection) tv
1519 .getSelection();
1520 if (updateInput)
1521 tv.setInput(input);
1522 else
1523 tv.refresh();
1524 tv.setExpandedElements(expanded);
1526 Object selected = sel.getFirstElement();
1527 if (selected != null)
1528 tv.reveal(selected);
1530 IViewPart part = PlatformUI.getWorkbench()
1531 .getActiveWorkbenchWindow().getActivePage()
1532 .findView(IPageLayout.ID_PROP_SHEET);
1533 if (part != null) {
1534 PropertySheet sheet = (PropertySheet) part;
1535 PropertySheetPage page = (PropertySheetPage) sheet
1536 .getCurrentPage();
1537 page.refresh();
1542 return new Status(IStatus.OK, Activator.getPluginId(), ""); //$NON-NLS-1$
1547 job.setSystem(true);
1549 IWorkbenchSiteProgressService service = (IWorkbenchSiteProgressService) getSite()
1550 .getService(IWorkbenchSiteProgressService.class);
1552 service.schedule(job);
1554 scheduledJob = job;
1559 * Adds a directory to the list if it is not already there
1561 * @param file
1562 * @return see {@link Collection#add(Object)}
1564 public static boolean addDir(File file) {
1566 String dirString;
1567 try {
1568 dirString = file.getCanonicalPath();
1569 } catch (IOException e) {
1570 dirString = file.getAbsolutePath();
1573 List<String> dirStrings = getDirs();
1574 if (dirStrings.contains(dirString)) {
1575 return false;
1576 } else {
1577 Set<String> dirs = new HashSet<String>();
1578 dirs.addAll(dirStrings);
1579 dirs.add(dirString);
1580 saveDirs(dirs);
1581 return true;
1586 * Converts the directories as configured for this view into a list of
1587 * {@link Repository} objects suitable for the tree content provider
1588 * <p>
1589 * TODO move to some utility class
1591 * @param monitor
1592 * @return a list of nodes
1593 * @throws InterruptedException
1595 public static List<RepositoryTreeNode<Repository>> getRepositoriesFromDirs(
1596 IProgressMonitor monitor) throws InterruptedException {
1598 List<String> gitDirStrings = getDirs();
1599 List<RepositoryTreeNode<Repository>> input = new ArrayList<RepositoryTreeNode<Repository>>();
1601 for (String dirString : gitDirStrings) {
1602 if (monitor != null && monitor.isCanceled()) {
1603 throw new InterruptedException(
1604 UIText.RepositoriesView_ActionCanceled_Message);
1606 try {
1607 File dir = new File(dirString);
1608 if (dir.exists() && dir.isDirectory()) {
1609 Repository repo = new Repository(dir);
1610 RepositoryTreeNode<Repository> node = new RepositoryTreeNode<Repository>(
1611 null, RepositoryTreeNodeType.REPO, repo, repo);
1612 input.add(node);
1614 } catch (IOException e) {
1615 IStatus error = new Status(IStatus.ERROR, Activator
1616 .getPluginId(), e.getMessage(), e);
1617 Activator.getDefault().getLog().log(error);
1620 Collections.sort(input);
1621 return input;
1624 private static void saveDirs(Set<String> gitDirStrings) {
1625 StringBuilder sb = new StringBuilder();
1626 for (String gitDirString : gitDirStrings) {
1627 sb.append(gitDirString);
1628 sb.append(File.pathSeparatorChar);
1631 IEclipsePreferences prefs = getPrefs();
1632 prefs.put(PREFS_DIRECTORIES, sb.toString());
1633 try {
1634 prefs.flush();
1635 } catch (BackingStoreException e) {
1636 IStatus error = new Status(IStatus.ERROR, Activator.getPluginId(),
1637 e.getMessage(), e);
1638 Activator.getDefault().getLog().log(error);
1642 @Override
1643 public void setFocus() {
1644 tv.getTree().setFocus();
1647 @SuppressWarnings("boxing")
1648 private boolean confirmProjectDeletion(List<IProject> projectsToDelete) {
1649 boolean confirmed;
1650 confirmed = MessageDialog
1651 .openConfirm(
1652 getSite().getShell(),
1653 UIText.RepositoriesView_ConfirmProjectDeletion_WindowTitle,
1655 .bind(
1656 UIText.RepositoriesView_ConfirmProjectDeletion_Question,
1657 projectsToDelete.size()));
1658 return confirmed;
1661 public void addSelectionChangedListener(ISelectionChangedListener listener) {
1662 selectionListeners.add(listener);
1665 public ISelection getSelection() {
1666 return currentSelection;
1669 public void removeSelectionChangedListener(
1670 ISelectionChangedListener listener) {
1671 selectionListeners.remove(listener);
1675 public void setSelection(ISelection selection) {
1676 currentSelection = selection;
1677 for (ISelectionChangedListener listener : selectionListeners) {
1678 listener.selectionChanged(new SelectionChangedEvent(
1679 RepositoriesView.this, selection));
1684 * Opens the tree and marks the folder to which a project is pointing
1686 * @param resource
1687 * TODO exceptions?
1689 @SuppressWarnings("unchecked")
1690 public void showResource(final IResource resource) {
1691 IProject project = resource.getProject();
1692 RepositoryMapping mapping = RepositoryMapping.getMapping(project);
1693 if (mapping == null)
1694 return;
1696 if (addDir(mapping.getRepository().getDirectory())) {
1697 scheduleRefresh();
1700 boolean doSetSelection = false;
1702 if (this.scheduledJob != null) {
1703 int state = this.scheduledJob.getState();
1704 if (state == Job.WAITING || state == Job.RUNNING) {
1705 this.scheduledJob.addJobChangeListener(new JobChangeAdapter() {
1707 @Override
1708 public void done(IJobChangeEvent event) {
1709 showResource(resource);
1712 } else {
1713 doSetSelection = true;
1717 if (doSetSelection) {
1718 RepositoriesViewContentProvider cp = (RepositoriesViewContentProvider) tv
1719 .getContentProvider();
1720 RepositoryTreeNode currentNode = null;
1721 Object[] repos = cp.getElements(tv.getInput());
1722 for (Object repo : repos) {
1723 RepositoryTreeNode node = (RepositoryTreeNode) repo;
1724 // TODO equals implementation of Repository?
1725 if (mapping.getRepository().getDirectory().equals(
1726 ((Repository) node.getObject()).getDirectory())) {
1727 for (Object child : cp.getChildren(node)) {
1728 RepositoryTreeNode childNode = (RepositoryTreeNode) child;
1729 if (childNode.getType() == RepositoryTreeNodeType.WORKINGDIR) {
1730 currentNode = childNode;
1731 break;
1734 break;
1738 IPath relPath = new Path(mapping.getRepoRelativePath(resource));
1740 for (String segment : relPath.segments()) {
1741 for (Object child : cp.getChildren(currentNode)) {
1742 RepositoryTreeNode<File> childNode = (RepositoryTreeNode<File>) child;
1743 if (childNode.getObject().getName().equals(segment)) {
1744 currentNode = childNode;
1745 break;
1750 final RepositoryTreeNode selNode = currentNode;
1752 Display.getDefault().asyncExec(new Runnable() {
1754 public void run() {
1755 tv.setSelection(new StructuredSelection(selNode), true);
1763 public boolean show(ShowInContext context) {
1764 ISelection selection = context.getSelection();
1765 if (selection instanceof IStructuredSelection) {
1766 IStructuredSelection ss = (IStructuredSelection) selection;
1767 if (ss.size() == 1) {
1768 Object element = ss.getFirstElement();
1769 if (element instanceof IAdaptable) {
1770 IResource resource = (IResource) ((IAdaptable) element)
1771 .getAdapter(IResource.class);
1772 if (resource != null) {
1773 showResource(resource);
1774 return true;
1779 return false;
1782 private void removeRepository(final IProgressMonitor monitor,
1783 final Repository... repository) {
1784 final List<IProject> projectsToDelete = new ArrayList<IProject>();
1786 monitor
1787 .setTaskName(UIText.RepositoriesView_DeleteRepoDeterminProjectsMessage);
1789 for (Repository repo : repository) {
1790 File workDir = repo.getWorkDir();
1791 final IPath wdPath = new Path(workDir.getAbsolutePath());
1792 for (IProject prj : ResourcesPlugin.getWorkspace().getRoot()
1793 .getProjects()) {
1794 if (monitor.isCanceled())
1795 return;
1796 if (wdPath.isPrefixOf(prj.getLocation())) {
1797 projectsToDelete.add(prj);
1802 if (!projectsToDelete.isEmpty()) {
1803 boolean confirmed;
1804 confirmed = confirmProjectDeletion(projectsToDelete);
1805 if (!confirmed) {
1806 return;
1810 if (monitor.isCanceled())
1811 return;
1813 IWorkspaceRunnable wsr = new IWorkspaceRunnable() {
1815 public void run(IProgressMonitor actMonitor) throws CoreException {
1817 for (IProject prj : projectsToDelete) {
1818 prj.delete(false, false, actMonitor);
1820 for (Repository repo : repository)
1821 removeDir(repo.getDirectory());
1822 scheduleRefresh();
1826 try {
1827 ResourcesPlugin.getWorkspace().run(wsr,
1828 ResourcesPlugin.getWorkspace().getRoot(),
1829 IWorkspace.AVOID_UPDATE, monitor);
1830 } catch (CoreException e1) {
1831 Activator.logError(e1.getMessage(), e1);