1cc0c6be3a1ad1c8bc09502e19186d5b9bab5dfa
[taxeditor.git] / eu.etaxonomy.taxeditor.editor / src / main / java / eu / etaxonomy / taxeditor / editor / view / derivate / DerivateView.java
1 package eu.etaxonomy.taxeditor.editor.view.derivate;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.Collection;
6 import java.util.HashMap;
7 import java.util.HashSet;
8 import java.util.List;
9 import java.util.Map;
10 import java.util.Set;
11 import java.util.UUID;
12
13 import org.eclipse.core.runtime.IProgressMonitor;
14 import org.eclipse.jface.action.MenuManager;
15 import org.eclipse.jface.util.LocalSelectionTransfer;
16 import org.eclipse.jface.viewers.AbstractTreeViewer;
17 import org.eclipse.jface.viewers.ISelection;
18 import org.eclipse.jface.viewers.IStructuredSelection;
19 import org.eclipse.jface.viewers.StructuredSelection;
20 import org.eclipse.jface.viewers.TreeNode;
21 import org.eclipse.jface.viewers.TreeSelection;
22 import org.eclipse.jface.viewers.TreeViewer;
23 import org.eclipse.swt.SWT;
24 import org.eclipse.swt.dnd.DND;
25 import org.eclipse.swt.dnd.Transfer;
26 import org.eclipse.swt.layout.GridData;
27 import org.eclipse.swt.layout.GridLayout;
28 import org.eclipse.swt.widgets.Composite;
29 import org.eclipse.swt.widgets.Control;
30 import org.eclipse.swt.widgets.Menu;
31 import org.eclipse.swt.widgets.Tree;
32 import org.eclipse.ui.IEditorInput;
33 import org.eclipse.ui.IEditorPart;
34 import org.eclipse.ui.IEditorSite;
35 import org.eclipse.ui.IMemento;
36 import org.eclipse.ui.ISelectionListener;
37 import org.eclipse.ui.ISelectionService;
38 import org.eclipse.ui.IWorkbenchPart;
39 import org.eclipse.ui.PartInitException;
40 import org.eclipse.ui.part.EditorPart;
41
42 import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
43 import eu.etaxonomy.cdm.api.conversation.IConversationEnabled;
44 import eu.etaxonomy.cdm.api.service.IOccurrenceService;
45 import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
46 import eu.etaxonomy.cdm.model.common.CdmBase;
47 import eu.etaxonomy.cdm.model.molecular.SingleRead;
48 import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
49 import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
50 import eu.etaxonomy.cdm.model.taxon.Taxon;
51 import eu.etaxonomy.cdm.model.taxon.TaxonNode;
52 import eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap;
53 import eu.etaxonomy.taxeditor.editor.EditorUtil;
54 import eu.etaxonomy.taxeditor.editor.Messages;
55 import eu.etaxonomy.taxeditor.editor.MultiPageTaxonEditor;
56 import eu.etaxonomy.taxeditor.editor.view.derivate.searchFilter.DerivateSearchCompositeController;
57 import eu.etaxonomy.taxeditor.model.IContextListener;
58 import eu.etaxonomy.taxeditor.model.IDirtyMarkable;
59 import eu.etaxonomy.taxeditor.model.IPartContentHasDetails;
60 import eu.etaxonomy.taxeditor.model.IPartContentHasFactualData;
61 import eu.etaxonomy.taxeditor.model.IPartContentHasMedia;
62 import eu.etaxonomy.taxeditor.model.IPartContentHasSupplementalData;
63 import eu.etaxonomy.taxeditor.operation.IPostOperationEnabled;
64 import eu.etaxonomy.taxeditor.session.ICdmEntitySession;
65 import eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled;
66 import eu.etaxonomy.taxeditor.store.CdmStore;
67 import eu.etaxonomy.taxeditor.view.derivateSearch.DerivateContentProvider;
68 import eu.etaxonomy.taxeditor.view.derivateSearch.DerivateLabelProvider;
69
70 /**
71 * Displays the derivate hierarchy of the specimen specified in the editor input.
72 *
73 */
74 public class DerivateView extends EditorPart implements IPartContentHasFactualData, IConversationEnabled,
75 ICdmEntitySessionEnabled, IDirtyMarkable, IPostOperationEnabled, IPartContentHasDetails, IPartContentHasSupplementalData, IPartContentHasMedia,
76 IContextListener, ISelectionListener {
77 public static final String ID = "eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView"; //$NON-NLS-1$
78
79 public static final String YOU_NEED_TO_SAVE_BEFORE_PERFORMING_THIS_ACTION = Messages.DerivateView_YOU_NEED_TO_SAVE;
80 public static final String VIEW_HAS_UNSAVED_CHANGES = Messages.DerivateView_UNSAVED_CHANGES;
81
82 private static final List<String> SPECIMEN_INIT_STRATEGY = Arrays.asList(new String[] {
83 "descriptions",
84 "annotations",
85 "markers",
86 "credits",
87 "extensions",
88 "rights",
89 "sources",
90 "derivationEvents.derivatives.annotations",
91 "derivationEvents.derivatives.markers",
92 "derivationEvents.derivatives.credits",
93 "derivationEvents.derivatives.extensions",
94 "derivationEvents.derivatives.rights",
95 "derivationEvents.derivatives.sources"
96 });
97
98 private ConversationHolder conversation;
99
100 private TreeViewer viewer;
101
102 private boolean isDirty;
103
104 private final int dndOperations = DND.DROP_MOVE;
105
106 private DerivateLabelProvider labelProvider;
107
108 private DerivateContentProvider contentProvider;
109
110 private DerivateSearchCompositeController derivateSearchCompositeController;
111
112 /**
113 * A map with keys being the derivative entities belonging to the {@link UUID}s passed to the constructor
114 * and values being the root elements of the hierarchy (may be the same objects as the derivative entities)
115 */
116 private Map<SpecimenOrObservationBase<?>, SpecimenOrObservationBase<?>> derivateToRootEntityMap;
117
118 /**
119 * The set of root elements
120 */
121 private Set<SpecimenOrObservationBase<?>> rootElements;
122
123 private ICdmEntitySession cdmEntitySession;
124
125 /**
126 * <code>true</code> if this view is listening to selection changes
127 */
128 private boolean listenToSelectionChange;
129
130 private Taxon selectedTaxon;
131
132 private ISelectionService selectionService;
133
134 /**
135 * Default constructor
136 */
137 public DerivateView() {
138 }
139
140
141 /**
142 * {@inheritDoc}
143 */
144 @Override
145 public void init(IEditorSite site, IEditorInput input) throws PartInitException {
146 this.setSite(site);
147 this.setInput(input);
148 this.derivateToRootEntityMap = new HashMap<SpecimenOrObservationBase<?>, SpecimenOrObservationBase<?>>();
149 this.rootElements = new HashSet<SpecimenOrObservationBase<?>>();
150
151 if (CdmStore.isActive() && conversation == null) {
152 conversation = CdmStore.createConversation();
153 }
154 if (CdmStore.isActive()) {
155 cdmEntitySession = CdmStore.getCurrentSessionManager().newSession(this, true);
156 }
157 //listen to context changes
158 CdmStore.getContextManager().addContextListener(this);
159 }
160
161 @Override
162 public void createPartControl(Composite parent) {
163
164 parent.setLayout(new GridLayout());
165
166 //---search and filter---
167 derivateSearchCompositeController = new DerivateSearchCompositeController(parent, this);
168 GridData gridDataSearchBar = new GridData();
169 gridDataSearchBar.horizontalAlignment = GridData.FILL;
170 gridDataSearchBar.grabExcessHorizontalSpace = true;
171 derivateSearchCompositeController.setLayoutData(gridDataSearchBar);
172 derivateSearchCompositeController.setEnabled(CdmStore.isActive());
173
174 //---tree viewer---
175 viewer = new TreeViewer(new Tree(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION));
176 GridData gridDataTree = new GridData();
177 gridDataTree.horizontalAlignment = GridData.FILL;
178 gridDataTree.verticalAlignment = GridData.FILL;
179 gridDataTree.grabExcessVerticalSpace = true;
180 gridDataTree.grabExcessHorizontalSpace = true;
181 viewer.getTree().setLayoutData(gridDataTree);
182 contentProvider = new DerivateContentProvider();
183 viewer.setContentProvider(contentProvider);
184 labelProvider = new DerivateLabelProvider();
185 labelProvider.setConversation(conversation);
186 viewer.setLabelProvider(labelProvider);
187 viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
188 viewer.getTree().setEnabled(CdmStore.isActive());
189 // Propagate selection from viewer
190 getSite().setSelectionProvider(viewer);
191
192 //listen to selection changes
193 selectionService = getSite().getWorkbenchWindow().getSelectionService();
194 selectionService.addSelectionListener(this);
195
196 //create context menu
197 MenuManager menuManager = new MenuManager();
198 getSite().registerContextMenu(menuManager, viewer);
199 Control control = viewer.getControl();
200 Menu menu = menuManager.createContextMenu(control);
201 control.setMenu(menu);
202
203 //init tree
204 updateRootEntities();
205 // reset status bar
206 getEditorSite().getActionBars().getStatusLineManager().setMessage("");
207
208 //add drag'n'drop support
209 Transfer[] transfers = new Transfer[] {LocalSelectionTransfer.getTransfer(),};
210 viewer.addDragSupport(dndOperations, transfers, new DerivateDragListener(this));
211 viewer.addDropSupport(dndOperations, transfers, new DerivateDropListener(this));
212 }
213
214 public void updateRootEntities() {
215 updateRootEntities((Collection)null);
216 }
217
218 public void updateRootEntities(Collection<UUID> derivativeUuids) {
219 if(conversation!=null){
220 if (!conversation.isBound()) {
221 conversation.bind();
222 }
223 /*
224 * If the active session is not the session of the Derivate Editor then we will
225 * save it, bind temporarily to our session and rebind to the original session.
226 * This happens e.g. if a selection change happens in the taxon editor and
227 * "Link with editor" is enabled. The selection change event and thus the
228 * loading in updateRootEntities() happens in the session of the taxon
229 * editor.
230 */
231 ICdmEntitySession previousCdmEntitySession = CdmStore.getCurrentSessionManager().getActiveSession();
232 if(cdmEntitySession != null) {
233 cdmEntitySession.bind();
234 }
235
236 List<SpecimenOrObservationBase> derivates = null;
237 if(derivativeUuids!=null){
238 this.derivateToRootEntityMap = new HashMap<SpecimenOrObservationBase<?>, SpecimenOrObservationBase<?>>();
239 this.rootElements = new HashSet<SpecimenOrObservationBase<?>>();
240 derivates = CdmStore.getService(IOccurrenceService.class).load(new ArrayList(derivativeUuids), SPECIMEN_INIT_STRATEGY);
241 }
242 updateRootEntities(derivates);
243 previousCdmEntitySession.bind();
244 }
245 }
246
247
248 public void updateRootEntities(List<SpecimenOrObservationBase> derivates) {
249
250 if(derivates!=null){
251 this.derivateToRootEntityMap = new HashMap<SpecimenOrObservationBase<?>, SpecimenOrObservationBase<?>>();
252 this.rootElements = new HashSet<SpecimenOrObservationBase<?>>();
253 for (SpecimenOrObservationBase derivate : derivates) {
254
255 if(derivate instanceof FieldUnit){
256 derivateToRootEntityMap.put(derivate, derivate);
257 }
258 else {
259 SpecimenOrObservationBase<?> topMostDerivate = EditorUtil.getTopMostDerivate(derivate);
260 if(topMostDerivate!=null){
261 derivateToRootEntityMap.put(derivate, topMostDerivate);
262 }
263 else{
264 derivateToRootEntityMap.put(derivate, derivate);
265 }
266 }
267 }
268 for (SpecimenOrObservationBase<?> specimen : derivateToRootEntityMap.values()) {
269 rootElements.add(specimen);
270 }
271 }
272 labelProvider.initCache(rootElements);
273 viewer.setInput(rootElements);
274
275 getEditorSite().getActionBars().getStatusLineManager().setMessage(rootElements.size() +" derivative hierarchies found");
276
277 }
278
279 @Override
280 public void doSave(IProgressMonitor monitor) {
281 String taskName = Messages.DerivateView_SAVING_HIERARCHY;
282 monitor.beginTask(taskName, 3);
283 if (!conversation.isBound()) {
284 conversation.bind();
285 }
286 monitor.worked(1);
287
288 // commit the conversation and start a new transaction immediately
289 conversation.commit(true);
290
291 if(CdmStore.getCurrentSessionManager().isRemoting()) {
292 CdmStore.getService(IOccurrenceService.class).merge(new ArrayList<SpecimenOrObservationBase>(rootElements), true);
293 }
294 monitor.worked(1);
295
296 this.setDirty(false);
297 monitor.worked(1);
298 monitor.done();
299 firePropertyChange(PROP_DIRTY);
300 refreshTree();
301 }
302
303 @Override
304 public void doSaveAs() {
305 }
306
307 @Override
308 public String getTitleToolTip() {
309 return Messages.DerivateView_DERIVATIVE_EDITOR;
310 }
311
312 @Override
313 public boolean isDirty() {
314 return isDirty;
315 }
316
317 /**
318 * @param isDirty the isDirty to set
319 */
320 public void setDirty(boolean isDirty) {
321 this.isDirty = isDirty;
322 }
323
324 @Override
325 public boolean isSaveAsAllowed() {
326 return false;
327 }
328
329 @Override
330 public void setFocus() {
331 viewer.getControl().setFocus();
332 //make sure to bind again if maybe in another view the conversation was unbound
333 if(conversation!=null && !conversation.isBound()){
334 conversation.bind();
335 }
336 if(cdmEntitySession != null) {
337 cdmEntitySession.bind();
338 }
339 }
340
341 @Override
342 public void update(CdmDataChangeMap changeEvents) {
343 }
344
345 @Override
346 public ConversationHolder getConversationHolder() {
347 return conversation;
348 }
349
350 @Override
351 public void changed(Object element) {
352 setDirty(true);
353 firePropertyChange(IEditorPart.PROP_DIRTY);
354 viewer.update(new TreeNode(element), null);
355 }
356
357 @Override
358 public void forceDirty() {
359 changed(null);
360 }
361
362 @Override
363 public Map<Object, List<String>> getPropertyPathsMap() {
364 List<String> specimenPropertyPaths = Arrays.asList(new String[] {
365 "descriptions",
366 "derivationEvents.derivates",
367 "annotations",
368 "markers",
369 "credits",
370 "extensions",
371 "rights",
372 "sources"
373 });
374 Map<Object, List<String>> specimenPropertyPathMap =
375 new HashMap<Object, List<String>>();
376 specimenPropertyPathMap.put(SpecimenOrObservationBase.class,specimenPropertyPaths);
377 return specimenPropertyPathMap;
378 }
379
380 /**
381 * Refreshes the derivate hierarchy tree and expands the tree
382 * to show and select the given object.
383 *
384 * @param expandTo the object to which the tree should be expanded
385 */
386 public void refreshTree(Object expandTo){
387 refreshTree();
388 TreeSelection selection = (TreeSelection) viewer.getSelection();
389 viewer.expandToLevel(selection.getFirstElement(), 1);
390 viewer.setSelection(new StructuredSelection(new TreeNode(expandTo)));
391 }
392
393 /**
394 * Refreshes the derivate hierarchy tree
395 */
396 public void refreshTree(){
397 viewer.refresh();
398 }
399
400 //FIXME:Remoting hack to make this work for remoting
401 //This should actually be resolved using remoting post operations
402 public void remove(Object obj) {
403 rootElements.remove(obj);
404 viewer.setInput(rootElements);
405 }
406
407 /**
408 * @return a set of {@link SingleRead}s that have multiple parents
409 */
410 public Set<SingleRead> getMultiLinkSingleReads() {
411 return DerivateLabelProvider.getMultiLinkSingleReads();
412 }
413
414 public Object getSelectionInput() {
415 return selectedTaxon;
416 }
417
418 public DerivateLabelProvider getLabelProvider() {
419 return labelProvider;
420 }
421
422 @Override
423 public boolean postOperation(CdmBase objectAffectedByOperation) {
424 refreshTree();
425 if(objectAffectedByOperation!=null){
426 changed(objectAffectedByOperation);
427 }
428 return true;
429 }
430
431 @Override
432 public boolean onComplete() {
433 return true;
434 }
435
436
437 @Override
438 public boolean canAttachMedia() {
439 return true;
440 }
441
442 public void addFieldUnit(FieldUnit fieldUnit) {
443 rootElements.add(fieldUnit);
444 derivateToRootEntityMap.put(fieldUnit, fieldUnit);
445 }
446
447 @Override
448 public ICdmEntitySession getCdmEntitySession() {
449 return cdmEntitySession;
450 }
451
452 @Override
453 public void dispose() {
454 super.dispose();
455 if(conversation!=null){
456 conversation.close();
457 }
458 if(cdmEntitySession != null) {
459 cdmEntitySession.dispose();
460 }
461 }
462
463 @Override
464 public void selectionChanged(IWorkbenchPart part, ISelection selection) {
465 if(viewer.getTree().isDisposed()){
466 return;
467 }
468 if(listenToSelectionChange){
469 if(part instanceof MultiPageTaxonEditor){
470 selectedTaxon = ((MultiPageTaxonEditor) part).getTaxon();
471 }
472 else if(selection instanceof IStructuredSelection){
473 Object selectedElement = ((IStructuredSelection) selection).getFirstElement();
474 if(selectedElement instanceof CdmBase){
475 if(((CdmBase) selectedElement).isInstanceOf(TaxonNode.class)){
476 selectedTaxon = HibernateProxyHelper.deproxy(selectedElement, TaxonNode.class).getTaxon();
477 }
478 else if(((CdmBase) selectedElement).isInstanceOf(Taxon.class)){
479 selectedTaxon = HibernateProxyHelper.deproxy(selectedElement, Taxon.class);
480 }
481 }
482 }
483 if(selectedTaxon!=null){
484 Collection<SpecimenOrObservationBase> fieldUnits = CdmStore.getService(IOccurrenceService.class).listFieldUnitsByAssociatedTaxon(selectedTaxon, null, null);
485 Collection<UUID> uuids = new HashSet<UUID>();
486 for (SpecimenOrObservationBase specimenOrObservationBase : fieldUnits) {
487 uuids.add(specimenOrObservationBase.getUuid());
488 }
489 updateRootEntities(uuids);
490 setPartName("Derivative Editor: " + selectedTaxon.getName());
491 }
492 }
493 }
494
495 public TreeViewer getViewer() {
496 return viewer;
497 }
498
499 /**
500 * {@inheritDoc}
501 */
502 @Override
503 public List<SpecimenOrObservationBase<?>> getRootEntities() {
504 return new ArrayList<SpecimenOrObservationBase<?>>(rootElements);
505 }
506
507 public void toggleListenToSelectionChange() {
508 listenToSelectionChange = !listenToSelectionChange;
509 derivateSearchCompositeController.setEnabled(!listenToSelectionChange);
510 if(!listenToSelectionChange){
511 selectedTaxon = null;
512 setPartName("Derivative Editor");
513 }
514 else if(selectedTaxon==null){
515 setPartName("Derivative Editor [no taxon selected]");
516 }
517 }
518
519 public boolean isListenToSelectionChange(){
520 return listenToSelectionChange;
521 }
522
523 /**
524 * {@inheritDoc}
525 */
526 @Override
527 public void contextAboutToStop(IMemento memento, IProgressMonitor monitor) {
528 }
529
530 /**
531 * {@inheritDoc}
532 */
533 @Override
534 public void contextStop(IMemento memento, IProgressMonitor monitor) {
535 derivateSearchCompositeController.setEnabled(false);
536 viewer.getTree().setEnabled(false);
537 viewer.setInput(null);
538 }
539
540 /**
541 * {@inheritDoc}
542 */
543 @Override
544 public void contextStart(IMemento memento, IProgressMonitor monitor) {
545 derivateSearchCompositeController.setEnabled(!listenToSelectionChange);
546 viewer.getTree().setEnabled(true);
547 refreshTree();
548 }
549
550 /**
551 * {@inheritDoc}
552 */
553 @Override
554 public void contextRefresh(IProgressMonitor monitor) {
555 }
556
557 /**
558 * {@inheritDoc}
559 */
560 @Override
561 public void workbenchShutdown(IMemento memento, IProgressMonitor monitor) {
562 }
563
564 }