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 handler
.postOperation(status
);
372 } catch (ExecutionException e
) {
373 MessagingUtils
.operationDialog(this, e
, TaxeditorStorePlugin
.PLUGIN_ID
, operationlabel
, null);
378 String statusString
= status
.equals(Status
.OK_STATUS
) ?
"completed"
380 setStatusLine(operationlabel
+ " " + statusString
+ ".");
386 runInUI(runnable
, null);
387 } catch (Exception e
) {
388 MessagingUtils
.messageDialog("Error executing operation", AbstractUtility
.class, "An error occured while executing " + operation
.getLabel(), e
);
391 return Status
.OK_STATUS
;
395 * getOperationHistory
398 * @return a {@link org.eclipse.core.commands.operations.IOperationHistory}
401 public static IOperationHistory
getOperationHistory() {
402 return getWorkbench().getOperationSupport().getOperationHistory();
411 * a {@link java.lang.String} object.
413 public static void setStatusLine(final String message
) {
414 Display
.getDefault().asyncExec(new Runnable() {
418 statusLineManager
.setMessage(message
);
430 * @return a {@link org.eclipse.core.runtime.IProgressMonitor} object.
432 public static IProgressMonitor
getMonitor() {
433 statusLineManager
.setCancelEnabled(false);
434 return statusLineManager
.getProgressMonitor();
438 * Starts either the given {@link IProgressMonitor} if it's not
439 * <code>null</code> or a new {@link NullProgressMonitor}.
441 * @param progressMonitor
442 * The {@link IProgressMonitor} or <code>null</code> if no
443 * progress should be reported.
445 * The name of the main task.
447 * The number of steps this task is subdivided into.
448 * @return The {@link IProgressMonitor}.
450 public static IProgressMonitor
startMainMonitor(
451 IProgressMonitor progressMonitor
, String taskName
, int steps
) {
452 IProgressMonitor newMonitor
= progressMonitor
;
453 if (newMonitor
== null) {
454 newMonitor
= new NullProgressMonitor();
456 newMonitor
.beginTask(taskName
== null ?
"" : taskName
, steps
);
457 newMonitor
.subTask(" ");
462 * Creates a {@link SubProgressMonitor} if the given
463 * {@link IProgressMonitor} is not <code>null</code> and not a
464 * {@link NullProgressMonitor}.
466 * @param progressMonitor
467 * The parent {@link IProgressMonitor} of the
468 * {@link SubProgressMonitor} to be created.
470 * The number of steps this subtask is subdivided into. Must be a
471 * positive number and must not be
472 * {@link IProgressMonitor#UNKNOWN}.
473 * @return The {@link IProgressMonitor}.
475 public static IProgressMonitor
getSubProgressMonitor(
476 IProgressMonitor progressMonitor
, int ticks
) {
477 if (progressMonitor
== null) {
478 return new NullProgressMonitor();
480 if (progressMonitor
instanceof NullProgressMonitor
) {
481 return progressMonitor
;
484 return new SubProgressMonitor(progressMonitor
, ticks
);
488 * Checks whether the user canceled this operation. If not canceled, the
489 * given number of steps are declared as done.
492 * a {@link org.eclipse.core.runtime.IProgressMonitor} object.
496 public static void workedChecked(IProgressMonitor newMonitor
, int steps
) {
497 // In case the progress monitor was canceled throw an exception.
498 if (newMonitor
.isCanceled()) {
499 throw new OperationCanceledException();
501 // Otherwise declare this step as done.
502 newMonitor
.worked(steps
);
506 * Present a progress dialog to the user. This dialog will block the UI
509 * an implementation of {@link IRunnableWithProgress}
510 * @throws java.lang.InterruptedException
512 * @throws java.lang.reflect.InvocationTargetException
515 public static void busyCursorWhile(IRunnableWithProgress runnable
)
516 throws InvocationTargetException
, InterruptedException
{
517 getProgressService().busyCursorWhile(runnable
);
525 * @see {@link IProgressService#runInUI(org.eclipse.jface.operation.IRunnableContext, IRunnableWithProgress, ISchedulingRule)}
527 * a {@link org.eclipse.jface.operation.IRunnableWithProgress}
530 * a {@link org.eclipse.core.runtime.jobs.ISchedulingRule}
532 * @throws java.lang.reflect.InvocationTargetException
534 * @throws java.lang.InterruptedException
537 public static void runInUI(IRunnableWithProgress runnable
,
538 ISchedulingRule rule
) throws InvocationTargetException
,
539 InterruptedException
{
540 getProgressService().runInUI(getWorkbenchWindow(), runnable
, rule
);
553 * a {@link org.eclipse.jface.operation.IRunnableWithProgress}
555 * @throws java.lang.reflect.InvocationTargetException
557 * @throws java.lang.InterruptedException
560 public static void run(boolean fork
, boolean cancelable
,
561 IRunnableWithProgress runnable
) throws InvocationTargetException
,
562 InterruptedException
{
563 getProgressService().run(fork
, cancelable
, runnable
);
571 * @return a {@link org.eclipse.ui.progress.IProgressService} object.
573 public static IProgressService
getProgressService() {
574 IWorkbench workbench
= PlatformUI
.getWorkbench();
575 return workbench
.getProgressService();
580 * getProgressService2
583 * @return a {@link org.eclipse.ui.progress.IWorkbenchSiteProgressService}
586 public static IWorkbenchSiteProgressService
getProgressService2() {
587 return (IWorkbenchSiteProgressService
) getService(IWorkbenchSiteProgressService
.class);
595 * @return a {@link java.lang.String} object.
597 public static String
getPluginId() {
598 return "eu.taxeditor";
606 * @return a {@link org.eclipse.ui.IEditorPart} object.
608 public static IEditorPart
getActiveEditor() {
609 return getActivePage() != null ?
getActivePage().getActiveEditor()
618 * @return a {@link eu.etaxonomy.taxeditor.view.detail.DetailsViewPart}
621 public static DetailsViewPart
getDetailsView() {
622 return (DetailsViewPart
) getView(DetailsViewPart
.ID
, false);
627 * refreshDetailsViewer
630 public static void refreshDetailsViewer() {
631 if (getDetailsView() != null) {
632 ((AbstractCdmDataViewer
) getDetailsView().getViewer()).refresh();
638 * reflowDetailsViewer
641 public static void reflowDetailsViewer() {
642 if (getDetailsView() != null) {
643 ((AbstractCdmDataViewer
) getDetailsView().getViewer()).reflow();
647 public static SupplementalDataViewPart
getSupplementalDataView() {
648 return (SupplementalDataViewPart
) getView(SupplementalDataViewPart
.ID
,
652 public static void reflowSupplementalViewer() {
653 if (getSupplementalDataView() != null) {
654 ((AbstractCdmDataViewer
) getSupplementalDataView().getViewer())
661 * Orders a Collection of {@link IEnumTerm}s according to the term
664 * The returned map will be be ordered primarily by root elements,
665 * secondarily by the child elements and their children resp., both ascending alphabetically. <br>
667 * A {@link Collection} of {@link IEnumTerm}s for which the term
668 * hierarchy should be created
669 * @return a map which holds the terms as keys and their string
670 * representation via {@link IEnumTerm#getMessage()} as values
672 public static <T
extends IEnumTerm
<T
>> LinkedHashMap
<T
, String
> orderTerms(Collection
<T
> terms
) {
673 TreeSet
<TermNode
<T
>> parentElements
= new TreeSet
<TermNode
<T
>>();
674 parentElements
.addAll(getTermHierarchy(terms
));
676 // create list according to the type hierarchy (root elements alphabetically with recursive children also alphabetically)
677 LinkedHashMap
<T
, String
> result
= new LinkedHashMap
<T
, String
>();
678 parseTermTree(parentElements
, result
, -1);
682 private static<T
extends IEnumTerm
<T
>> void parseTermTree(Collection
<TermNode
<T
>> children
, LinkedHashMap
<T
, String
> result
, int depth
){
684 for(TermNode
<T
> node
:children
){
685 String indentString
= "";
686 for(int i
=0;i
<depth
;i
++){
690 indentString
+= "- ";
692 result
.put(node
.term
, indentString
+ node
.term
.getMessage());
693 parseTermTree(node
.children
, result
, depth
);
697 private static<T
extends IEnumTerm
<T
>> void addToParents(List
<TermNode
<T
>> parents
, Collection
<T
> terms
){
698 List
<TermNode
<T
>> hasChildrenList
= new ArrayList
<TermNode
<T
>>();
700 // only terms with parents
701 if(term
.getKindOf()!=null){
702 TermNode
<T
> parentNode
= new TermNode
<T
>(term
.getKindOf());
703 TermNode
<T
> childNode
= new TermNode
<T
>(term
);
704 if(parents
.contains(parentNode
)){
705 // parent found in parent list -> add this term to parent's child list
706 parents
.get(parents
.indexOf(parentNode
)).addChild(childNode
);
707 if(!term
.getGeneralizationOf().isEmpty()){
708 // has more children -> add to list which will be the parent for the next recursion
709 hasChildrenList
.add(childNode
);
714 if(!hasChildrenList
.isEmpty()){
715 addToParents(hasChildrenList
, terms
);
719 private static<T
extends IEnumTerm
<T
>> List
<TermNode
<T
>> getTermHierarchy(Collection
<T
> terms
){
720 List
<TermNode
<T
>> parents
= new ArrayList
<TermNode
<T
>>();
723 T parentTerm
= term
.getKindOf();
724 if(parentTerm
==null){
726 parents
.add(new TermNode
<T
>(term
));
729 addToParents(parents
, terms
);
733 @SuppressWarnings("unchecked")
735 * Recursively iterates over all term parents until no more parent is found i.e. the root node
736 * @param term The term for which the parent should be found
737 * @return the root terms of the term hierarchy
739 private static<T
extends IEnumTerm
<T
>> T
getParentFor(T term
){
740 // PP: cast should be safe. Why is Eclipse complaining??
741 T parent
= term
.getKindOf();
746 return getParentFor(term
.getKindOf());
750 private static class TermNode
<T
extends IEnumTerm
<T
>> implements Comparable
<TermNode
<T
>>{
751 private final T term
;
752 private final TreeSet
<TermNode
<T
>> children
;
758 public TermNode(T term
) {
761 this.children
= new TreeSet
<TermNode
<T
>>();
764 public void addChild(TermNode
<T
> child
){
765 this.children
.add(child
);
769 * @return the children
771 public TreeSet
<TermNode
<T
>> getChildren() {
783 * @see java.lang.Object#hashCode()
786 public int hashCode() {
787 final int prime
= 31;
789 result
= prime
* result
+ ((term
== null) ?
0 : term
.hashCode());
794 * @see java.lang.Object#equals(java.lang.Object)
797 public boolean equals(Object obj
) {
804 if (getClass() != obj
.getClass()) {
807 TermNode other
= (TermNode
) obj
;
809 if (other
.term
!= null) {
812 } else if (!term
.equals(other
.term
)) {
819 * @see java.lang.Comparable#compareTo(java.lang.Object)
822 public int compareTo(TermNode
<T
> that
) {
823 return this.term
.getMessage().compareTo(that
.term
.getMessage());
828 public static void executeCommand(String commandId
, Object source
, String pluginId
) {
829 IHandlerService handlerService
= (IHandlerService
) AbstractUtility
.getService(IHandlerService
.class);
830 Exception exception
= null;
832 handlerService
.executeCommand(commandId
, null);
833 } catch (ExecutionException e
) {
835 } catch (NotDefinedException e
) {
837 } catch (NotEnabledException e
) {
839 } catch (NotHandledException e
) {
842 if(exception
!= null) {
843 MessagingUtils
.errorDialog("Error executing command",
845 "Could not execute command with id " + commandId
,