3 * Copyright (C) 2007 EDIT
4 * European Distributed Institute of Taxonomy
5 * http://www.e-taxonomy.eu
7 * The contents of this file are subject to the Mozilla Public License Version 1.1
8 * See LICENSE.TXT at the top of this package for the full license terms.
11 package eu
.etaxonomy
.taxeditor
.model
;
13 import java
.lang
.reflect
.InvocationTargetException
;
14 import java
.util
.ArrayList
;
15 import java
.util
.Collection
;
16 import java
.util
.LinkedHashMap
;
17 import java
.util
.List
;
18 import java
.util
.TreeSet
;
20 import org
.eclipse
.core
.commands
.ExecutionException
;
21 import org
.eclipse
.core
.commands
.NotEnabledException
;
22 import org
.eclipse
.core
.commands
.NotHandledException
;
23 import org
.eclipse
.core
.commands
.common
.NotDefinedException
;
24 import org
.eclipse
.core
.commands
.operations
.AbstractOperation
;
25 import org
.eclipse
.core
.commands
.operations
.IOperationHistory
;
26 import org
.eclipse
.core
.runtime
.IAdaptable
;
27 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
28 import org
.eclipse
.core
.runtime
.IStatus
;
29 import org
.eclipse
.core
.runtime
.NullProgressMonitor
;
30 import org
.eclipse
.core
.runtime
.OperationCanceledException
;
31 import org
.eclipse
.core
.runtime
.Status
;
32 import org
.eclipse
.core
.runtime
.SubProgressMonitor
;
33 import org
.eclipse
.core
.runtime
.jobs
.ISchedulingRule
;
34 import org
.eclipse
.jface
.action
.IStatusLineManager
;
35 import org
.eclipse
.jface
.operation
.IRunnableWithProgress
;
36 import org
.eclipse
.jface
.resource
.ColorRegistry
;
37 import org
.eclipse
.jface
.resource
.FontRegistry
;
38 import org
.eclipse
.jface
.window
.ApplicationWindow
;
39 import org
.eclipse
.swt
.graphics
.Color
;
40 import org
.eclipse
.swt
.graphics
.Font
;
41 import org
.eclipse
.swt
.widgets
.Display
;
42 import org
.eclipse
.swt
.widgets
.Shell
;
43 import org
.eclipse
.ui
.IEditorPart
;
44 import org
.eclipse
.ui
.IViewPart
;
45 import org
.eclipse
.ui
.IViewReference
;
46 import org
.eclipse
.ui
.IWorkbench
;
47 import org
.eclipse
.ui
.IWorkbenchPage
;
48 import org
.eclipse
.ui
.IWorkbenchPart
;
49 import org
.eclipse
.ui
.PartInitException
;
50 import org
.eclipse
.ui
.PlatformUI
;
51 import org
.eclipse
.ui
.handlers
.IHandlerService
;
52 import org
.eclipse
.ui
.ide
.undo
.WorkspaceUndoUtil
;
53 import org
.eclipse
.ui
.part
.EditorPart
;
54 import org
.eclipse
.ui
.progress
.IProgressService
;
55 import org
.eclipse
.ui
.progress
.IWorkbenchSiteProgressService
;
56 import org
.eclipse
.ui
.themes
.ITheme
;
57 import org
.eclipse
.ui
.themes
.IThemeManager
;
59 import eu
.etaxonomy
.cdm
.model
.common
.IEnumTerm
;
60 import eu
.etaxonomy
.taxeditor
.operation
.AbstractPostOperation
;
61 import eu
.etaxonomy
.taxeditor
.operation
.IPostOperationEnabled
;
62 import eu
.etaxonomy
.taxeditor
.operation
.RemotingCdmHandler
;
63 import eu
.etaxonomy
.taxeditor
.store
.internal
.TaxeditorStorePlugin
;
64 import eu
.etaxonomy
.taxeditor
.view
.AbstractCdmDataViewer
;
65 import eu
.etaxonomy
.taxeditor
.view
.detail
.DetailsViewPart
;
66 import eu
.etaxonomy
.taxeditor
.view
.supplementaldata
.SupplementalDataViewPart
;
70 * Abstract AbstractUtility class.
77 public abstract class AbstractUtility
{
79 /** Constant <code>statusLineManager</code> */
80 protected static IStatusLineManager statusLineManager
;
90 public static boolean closeAll() {
91 return getActivePage().closeAllEditors(true);
95 * Close the given editor.
98 * The <tt>MultipageTaxonEditor</tt> to close.
99 * @return <tt>true</tt> on success
101 public static boolean close(EditorPart editor
) {
102 return getActivePage().closeEditor(editor
, true);
110 * @return a {@link org.eclipse.swt.widgets.Shell} object.
112 public static Shell
getShell() {
114 return TaxeditorStorePlugin
.getDefault().getWorkbench()
115 .getActiveWorkbenchWindow().getShell();
123 * @return a {@link org.eclipse.ui.IWorkbenchPage} object.
125 public static IWorkbenchPage
getActivePage() {
127 return TaxeditorStorePlugin
.getDefault().getWorkbench()
128 .getActiveWorkbenchWindow().getActivePage();
136 * @return a {@link org.eclipse.ui.IWorkbenchPart} object.
138 public static IWorkbenchPart
getActivePart() {
139 return getActivePage() != null ?
getActivePage().getActivePart() : null;
142 public static IWorkbench
getWorkbench() {
143 return TaxeditorStorePlugin
.getDefault().getWorkbench();
151 * @return a {@link org.eclipse.jface.window.ApplicationWindow} object.
153 public static ApplicationWindow
getWorkbenchWindow() {
154 if (getWorkbench().getWorkbenchWindowCount() > 1) {
155 throw new IllegalStateException("More than one workbench window");
157 return (ApplicationWindow
) getWorkbench().getWorkbenchWindows()[0];
166 * a {@link java.lang.String} object.
167 * @return a {@link org.eclipse.ui.IViewPart} object.
169 public static IViewPart
showView(String id
) {
171 return PlatformUI
.getWorkbench().getActiveWorkbenchWindow()
173 .showView(id
, null, IWorkbenchPage
.VIEW_VISIBLE
);
174 } catch (PartInitException e
) {
175 MessagingUtils
.messageDialog("Error opening view", AbstractUtility
.class, "Could not open view: " + id
, e
);
186 * a {@link org.eclipse.ui.IViewPart} object.
188 public static void hideView(IViewPart view
) {
189 PlatformUI
.getWorkbench().getActiveWorkbenchWindow().getActivePage()
199 * a {@link java.lang.String} object.
202 * @return a {@link org.eclipse.ui.IViewPart} object.
204 public static IViewPart
getView(String id
, boolean restore
) {
205 IViewReference
[] references
= PlatformUI
.getWorkbench()
206 .getActiveWorkbenchWindow().getActivePage().getViewReferences();
207 for (IViewReference reference
: references
) {
208 if (reference
.getId().equals(id
)) {
209 return reference
.getView(restore
);
221 * a {@link java.lang.Class} object.
222 * @return a {@link java.lang.Object} object.
224 public static Object
getService(Class api
) {
225 return TaxeditorStorePlugin
.getDefault().getWorkbench().getService(api
);
233 * @return a {@link org.eclipse.ui.themes.ITheme} object.
235 public static ITheme
getCurrentTheme() {
236 IThemeManager themeManager
= TaxeditorStorePlugin
.getDefault()
237 .getWorkbench().getThemeManager();
238 return themeManager
.getCurrentTheme();
242 * Fonts registered to the plugin may be obtained with the Eclipse themeing
243 * functionality. Thus fonts are chooseable by the user via
244 * Preferences->General->Appearance->Colors and Fonts
246 * @return the FontRegistry for the current theme
248 public static FontRegistry
getFontRegistry() {
249 return getCurrentTheme().getFontRegistry();
257 * @param symbolicName
258 * a {@link java.lang.String} object.
259 * @return a {@link org.eclipse.swt.graphics.Font} object.
261 public static Font
getFont(String symbolicName
) {
262 return getFontRegistry().get(symbolicName
);
266 * Color registered to the plugin may be obtained with the Eclipse themeing
267 * functionality. Thus colors are editable by the user via
268 * Preferences->General->Appearance->Colors and Fonts
270 * @return the ColorRegistry for the current theme
272 public static ColorRegistry
getColorRegistry() {
273 return getCurrentTheme().getColorRegistry();
281 * @param symbolicName
282 * a {@link java.lang.String} object.
283 * @return a {@link org.eclipse.swt.graphics.Color} object.
285 public static Color
getColor(String symbolicName
) {
286 return getColorRegistry().get(symbolicName
);
296 * {@link eu.etaxonomy.taxeditor.operation.AbstractPostTaxonOperation}
298 * @return a {@link org.eclipse.core.runtime.IStatus} object.
300 public static IStatus
executeOperation(final AbstractPostOperation operation
) {
301 if (getOperationHistory() == null) {
302 throw new IllegalArgumentException(
303 "There is no operation history for this context");
306 final IAdaptable uiInfoAdapter
= WorkspaceUndoUtil
307 .getUIInfoAdapter(getShell());
309 IRunnableWithProgress runnable
= new IRunnableWithProgress() {
312 public void run(IProgressMonitor monitor
)
313 throws InvocationTargetException
, InterruptedException
{
314 String operationlabel
= operation
.getLabel();
315 monitor
.beginTask(operationlabel
, 100);
316 IStatus status
= Status
.CANCEL_STATUS
;
318 operation
.addContext(IOperationHistory
.GLOBAL_UNDO_CONTEXT
);
319 status
= getOperationHistory().execute(operation
, monitor
,
321 } catch (ExecutionException e
) {
323 MessagingUtils
.operationDialog(this, e
, TaxeditorStorePlugin
.PLUGIN_ID
, operationlabel
, null);
329 String statusString
= status
.equals(Status
.OK_STATUS
) ?
"completed"
331 setStatusLine(operationlabel
+ " " + statusString
+ ".");
337 runInUI(runnable
, null);
338 } catch (Exception e
) {
339 MessagingUtils
.messageDialog("Error executing operation", AbstractUtility
.class, "An error occured while executing " + operation
.getLabel(), e
);
342 IPostOperationEnabled postOperationEnabled
= operation
343 .getPostOperationEnabled();
344 if (postOperationEnabled
!= null) {
345 postOperationEnabled
.onComplete();
347 return Status
.OK_STATUS
;
350 public static IStatus
executeOperation(final AbstractOperation operation
, final RemotingCdmHandler handler
) {
351 if (getOperationHistory() == null) {
352 throw new IllegalArgumentException(
353 "There is no operation history for this context");
356 final IAdaptable uiInfoAdapter
= WorkspaceUndoUtil
357 .getUIInfoAdapter(getShell());
359 IRunnableWithProgress runnable
= new IRunnableWithProgress() {
362 public void run(IProgressMonitor monitor
)
363 throws InvocationTargetException
, InterruptedException
{
364 String operationlabel
= operation
.getLabel();
365 monitor
.beginTask(operationlabel
, 100);
366 IStatus status
= Status
.CANCEL_STATUS
;
368 operation
.addContext(IOperationHistory
.GLOBAL_UNDO_CONTEXT
);
369 status
= getOperationHistory().execute(operation
, monitor
,
371 if(handler
!= null) {
372 handler
.postOperation(status
);
374 } catch (ExecutionException e
) {
375 MessagingUtils
.operationDialog(this, e
, TaxeditorStorePlugin
.PLUGIN_ID
, operationlabel
, null);
380 String statusString
= status
.equals(Status
.OK_STATUS
) ?
"completed"
382 setStatusLine(operationlabel
+ " " + statusString
+ ".");
388 runInUI(runnable
, null);
389 } catch (Exception e
) {
390 MessagingUtils
.messageDialog("Error executing operation", AbstractUtility
.class, "An error occured while executing " + operation
.getLabel(), e
);
393 return Status
.OK_STATUS
;
397 * getOperationHistory
400 * @return a {@link org.eclipse.core.commands.operations.IOperationHistory}
403 public static IOperationHistory
getOperationHistory() {
404 return getWorkbench().getOperationSupport().getOperationHistory();
413 * a {@link java.lang.String} object.
415 public static void setStatusLine(final String message
) {
416 Display
.getDefault().asyncExec(new Runnable() {
420 statusLineManager
.setMessage(message
);
432 * @return a {@link org.eclipse.core.runtime.IProgressMonitor} object.
434 public static IProgressMonitor
getMonitor() {
435 statusLineManager
.setCancelEnabled(false);
436 return statusLineManager
.getProgressMonitor();
440 * Starts either the given {@link IProgressMonitor} if it's not
441 * <code>null</code> or a new {@link NullProgressMonitor}.
443 * @param progressMonitor
444 * The {@link IProgressMonitor} or <code>null</code> if no
445 * progress should be reported.
447 * The name of the main task.
449 * The number of steps this task is subdivided into.
450 * @return The {@link IProgressMonitor}.
452 public static IProgressMonitor
startMainMonitor(
453 IProgressMonitor progressMonitor
, String taskName
, int steps
) {
454 IProgressMonitor newMonitor
= progressMonitor
;
455 if (newMonitor
== null) {
456 newMonitor
= new NullProgressMonitor();
458 newMonitor
.beginTask(taskName
== null ?
"" : taskName
, steps
);
459 newMonitor
.subTask(" ");
464 * Creates a {@link SubProgressMonitor} if the given
465 * {@link IProgressMonitor} is not <code>null</code> and not a
466 * {@link NullProgressMonitor}.
468 * @param progressMonitor
469 * The parent {@link IProgressMonitor} of the
470 * {@link SubProgressMonitor} to be created.
472 * The number of steps this subtask is subdivided into. Must be a
473 * positive number and must not be
474 * {@link IProgressMonitor#UNKNOWN}.
475 * @return The {@link IProgressMonitor}.
477 public static IProgressMonitor
getSubProgressMonitor(
478 IProgressMonitor progressMonitor
, int ticks
) {
479 if (progressMonitor
== null) {
480 return new NullProgressMonitor();
482 if (progressMonitor
instanceof NullProgressMonitor
) {
483 return progressMonitor
;
486 return new SubProgressMonitor(progressMonitor
, ticks
);
490 * Checks whether the user canceled this operation. If not canceled, the
491 * given number of steps are declared as done.
494 * a {@link org.eclipse.core.runtime.IProgressMonitor} object.
498 public static void workedChecked(IProgressMonitor newMonitor
, int steps
) {
499 // In case the progress monitor was canceled throw an exception.
500 if (newMonitor
.isCanceled()) {
501 throw new OperationCanceledException();
503 // Otherwise declare this step as done.
504 newMonitor
.worked(steps
);
508 * Present a progress dialog to the user. This dialog will block the UI
511 * an implementation of {@link IRunnableWithProgress}
512 * @throws java.lang.InterruptedException
514 * @throws java.lang.reflect.InvocationTargetException
517 public static void busyCursorWhile(IRunnableWithProgress runnable
)
518 throws InvocationTargetException
, InterruptedException
{
519 getProgressService().busyCursorWhile(runnable
);
527 * @see {@link IProgressService#runInUI(org.eclipse.jface.operation.IRunnableContext, IRunnableWithProgress, ISchedulingRule)}
529 * a {@link org.eclipse.jface.operation.IRunnableWithProgress}
532 * a {@link org.eclipse.core.runtime.jobs.ISchedulingRule}
534 * @throws java.lang.reflect.InvocationTargetException
536 * @throws java.lang.InterruptedException
539 public static void runInUI(IRunnableWithProgress runnable
,
540 ISchedulingRule rule
) throws InvocationTargetException
,
541 InterruptedException
{
542 getProgressService().runInUI(getWorkbenchWindow(), runnable
, rule
);
555 * a {@link org.eclipse.jface.operation.IRunnableWithProgress}
557 * @throws java.lang.reflect.InvocationTargetException
559 * @throws java.lang.InterruptedException
562 public static void run(boolean fork
, boolean cancelable
,
563 IRunnableWithProgress runnable
) throws InvocationTargetException
,
564 InterruptedException
{
565 getProgressService().run(fork
, cancelable
, runnable
);
573 * @return a {@link org.eclipse.ui.progress.IProgressService} object.
575 public static IProgressService
getProgressService() {
576 IWorkbench workbench
= PlatformUI
.getWorkbench();
577 return workbench
.getProgressService();
582 * getProgressService2
585 * @return a {@link org.eclipse.ui.progress.IWorkbenchSiteProgressService}
588 public static IWorkbenchSiteProgressService
getProgressService2() {
589 return (IWorkbenchSiteProgressService
) getService(IWorkbenchSiteProgressService
.class);
597 * @return a {@link java.lang.String} object.
599 public static String
getPluginId() {
600 return "eu.taxeditor";
608 * @return a {@link org.eclipse.ui.IEditorPart} object.
610 public static IEditorPart
getActiveEditor() {
611 return getActivePage() != null ?
getActivePage().getActiveEditor()
620 * @return a {@link eu.etaxonomy.taxeditor.view.detail.DetailsViewPart}
623 public static DetailsViewPart
getDetailsView() {
624 return (DetailsViewPart
) getView(DetailsViewPart
.ID
, false);
629 * refreshDetailsViewer
632 public static void refreshDetailsViewer() {
633 if (getDetailsView() != null) {
634 ((AbstractCdmDataViewer
) getDetailsView().getViewer()).refresh();
640 * reflowDetailsViewer
643 public static void reflowDetailsViewer() {
644 if (getDetailsView() != null) {
645 ((AbstractCdmDataViewer
) getDetailsView().getViewer()).reflow();
649 public static SupplementalDataViewPart
getSupplementalDataView() {
650 return (SupplementalDataViewPart
) getView(SupplementalDataViewPart
.ID
,
654 public static void reflowSupplementalViewer() {
655 if (getSupplementalDataView() != null) {
656 ((AbstractCdmDataViewer
) getSupplementalDataView().getViewer())
663 * Orders a Collection of {@link IEnumTerm}s according to the term
666 * The returned map will be be ordered primarily by root elements,
667 * secondarily by the child elements and their children resp., both ascending alphabetically. <br>
669 * A {@link Collection} of {@link IEnumTerm}s for which the term
670 * hierarchy should be created
671 * @return a map which holds the terms as keys and their string
672 * representation via {@link IEnumTerm#getMessage()} as values
674 public static <T
extends IEnumTerm
<T
>> LinkedHashMap
<T
, String
> orderTerms(Collection
<T
> terms
) {
675 TreeSet
<TermNode
<T
>> parentElements
= new TreeSet
<TermNode
<T
>>();
676 parentElements
.addAll(getTermHierarchy(terms
));
678 // create list according to the type hierarchy (root elements alphabetically with recursive children also alphabetically)
679 LinkedHashMap
<T
, String
> result
= new LinkedHashMap
<T
, String
>();
680 parseTermTree(parentElements
, result
, -1);
684 private static<T
extends IEnumTerm
<T
>> void parseTermTree(Collection
<TermNode
<T
>> children
, LinkedHashMap
<T
, String
> result
, int depth
){
686 for(TermNode
<T
> node
:children
){
687 String indentString
= "";
688 for(int i
=0;i
<depth
;i
++){
692 indentString
+= "- ";
694 result
.put(node
.term
, indentString
+ node
.term
.getMessage());
695 parseTermTree(node
.children
, result
, depth
);
699 private static<T
extends IEnumTerm
<T
>> void addToParents(List
<TermNode
<T
>> parents
, Collection
<T
> terms
){
700 List
<TermNode
<T
>> hasChildrenList
= new ArrayList
<TermNode
<T
>>();
702 // only terms with parents
703 if(term
.getKindOf()!=null){
704 TermNode
<T
> parentNode
= new TermNode
<T
>(term
.getKindOf());
705 TermNode
<T
> childNode
= new TermNode
<T
>(term
);
706 if(parents
.contains(parentNode
)){
707 // parent found in parent list -> add this term to parent's child list
708 parents
.get(parents
.indexOf(parentNode
)).addChild(childNode
);
709 if(!term
.getGeneralizationOf().isEmpty()){
710 // has more children -> add to list which will be the parent for the next recursion
711 hasChildrenList
.add(childNode
);
716 if(!hasChildrenList
.isEmpty()){
717 addToParents(hasChildrenList
, terms
);
721 private static<T
extends IEnumTerm
<T
>> List
<TermNode
<T
>> getTermHierarchy(Collection
<T
> terms
){
722 List
<TermNode
<T
>> parents
= new ArrayList
<TermNode
<T
>>();
725 T parentTerm
= term
.getKindOf();
726 if(parentTerm
==null){
728 parents
.add(new TermNode
<T
>(term
));
731 addToParents(parents
, terms
);
735 @SuppressWarnings("unchecked")
737 * Recursively iterates over all term parents until no more parent is found i.e. the root node
738 * @param term The term for which the parent should be found
739 * @return the root terms of the term hierarchy
741 private static<T
extends IEnumTerm
<T
>> T
getParentFor(T term
){
742 // PP: cast should be safe. Why is Eclipse complaining??
743 T parent
= term
.getKindOf();
748 return getParentFor(term
.getKindOf());
752 private static class TermNode
<T
extends IEnumTerm
<T
>> implements Comparable
<TermNode
<T
>>{
753 private final T term
;
754 private final TreeSet
<TermNode
<T
>> children
;
760 public TermNode(T term
) {
763 this.children
= new TreeSet
<TermNode
<T
>>();
766 public void addChild(TermNode
<T
> child
){
767 this.children
.add(child
);
771 * @return the children
773 public TreeSet
<TermNode
<T
>> getChildren() {
785 * @see java.lang.Object#hashCode()
788 public int hashCode() {
789 final int prime
= 31;
791 result
= prime
* result
+ ((term
== null) ?
0 : term
.hashCode());
796 * @see java.lang.Object#equals(java.lang.Object)
799 public boolean equals(Object obj
) {
806 if (getClass() != obj
.getClass()) {
809 TermNode other
= (TermNode
) obj
;
811 if (other
.term
!= null) {
814 } else if (!term
.equals(other
.term
)) {
821 * @see java.lang.Comparable#compareTo(java.lang.Object)
824 public int compareTo(TermNode
<T
> that
) {
825 return this.term
.getMessage().compareTo(that
.term
.getMessage());
830 public static void executeCommand(String commandId
, Object source
, String pluginId
) {
831 IHandlerService handlerService
= (IHandlerService
) AbstractUtility
.getService(IHandlerService
.class);
832 Exception exception
= null;
834 handlerService
.executeCommand(commandId
, null);
835 } catch (ExecutionException e
) {
837 } catch (NotDefinedException e
) {
839 } catch (NotEnabledException e
) {
841 } catch (NotHandledException e
) {
844 if(exception
!= null) {
845 MessagingUtils
.errorDialog("Error executing command",
847 "Could not execute command with id " + commandId
,