95d3b939215a3751ee4284f09775142d35c8c6fe
[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
206 //add drag'n'drop support
207 Transfer[] transfers = new Transfer[] {LocalSelectionTransfer.getTransfer(),};
208 viewer.addDragSupport(dndOperations, transfers, new DerivateDragListener(this));
209 viewer.addDropSupport(dndOperations, transfers, new DerivateDropListener(this));
210 }
211
212 public void updateRootEntities() {
213 updateRootEntities(null);
214 }
215
216 public void updateRootEntities(Collection<UUID> derivativeUuids) {
217 if(conversation!=null){
218 if (!conversation.isBound()) {
219 conversation.bind();
220 }
221 /*
222 * If the active session is not the session of the Derivate Editor then we will
223 * save it, bind temporarily to our session and rebind to the original session.
224 * This happens e.g. if a selection change happens in the taxon editor and
225 * "Link with editor" is enabled. The selection change event and thus the
226 * loading in updateRootEntities() happens in the session of the taxon
227 * editor.
228 */
229 ICdmEntitySession previousCdmEntitySession = CdmStore.getCurrentSessionManager().getActiveSession();
230 if(cdmEntitySession != null) {
231 cdmEntitySession.bind();
232 }
233
234 if(derivativeUuids!=null){
235 this.derivateToRootEntityMap = new HashMap<SpecimenOrObservationBase<?>, SpecimenOrObservationBase<?>>();
236 this.rootElements = new HashSet<SpecimenOrObservationBase<?>>();
237 for (UUID uuid : derivativeUuids) {
238 SpecimenOrObservationBase<?> derivate = CdmStore.getService(IOccurrenceService.class).load(uuid, SPECIMEN_INIT_STRATEGY);
239 if(derivate instanceof FieldUnit){
240 derivateToRootEntityMap.put(derivate, derivate);
241 }
242 else {
243 SpecimenOrObservationBase<?> topMostDerivate = EditorUtil.getTopMostDerivate(derivate);
244 if(topMostDerivate!=null){
245 derivateToRootEntityMap.put(derivate, topMostDerivate);
246 }
247 else{
248 derivateToRootEntityMap.put(derivate, derivate);
249 }
250 }
251 }
252 for (SpecimenOrObservationBase<?> specimen : derivateToRootEntityMap.values()) {
253 rootElements.add(specimen);
254 }
255 }
256 viewer.setInput(rootElements);
257 refreshTree(false);
258 previousCdmEntitySession.bind();
259 }
260 }
261
262 @Override
263 public void doSave(IProgressMonitor monitor) {
264 String taskName = Messages.DerivateView_SAVING_HIERARCHY;
265 monitor.beginTask(taskName, 3);
266 if (!conversation.isBound()) {
267 conversation.bind();
268 }
269 monitor.worked(1);
270
271 // commit the conversation and start a new transaction immediately
272 conversation.commit(true);
273
274 if(CdmStore.getCurrentSessionManager().isRemoting()) {
275 CdmStore.getService(IOccurrenceService.class).merge(new ArrayList<SpecimenOrObservationBase>(rootElements), true);
276 }
277 monitor.worked(1);
278
279 this.setDirty(false);
280 monitor.worked(1);
281 monitor.done();
282 firePropertyChange(PROP_DIRTY);
283 refreshTree();
284 }
285
286 @Override
287 public void doSaveAs() {
288 }
289
290 @Override
291 public String getTitleToolTip() {
292 return Messages.DerivateView_DERIVATIVE_EDITOR;
293 }
294
295 @Override
296 public boolean isDirty() {
297 return isDirty;
298 }
299
300 /**
301 * @param isDirty the isDirty to set
302 */
303 public void setDirty(boolean isDirty) {
304 this.isDirty = isDirty;
305 }
306
307 @Override
308 public boolean isSaveAsAllowed() {
309 return false;
310 }
311
312 @Override
313 public void setFocus() {
314 viewer.getControl().setFocus();
315 //make sure to bind again if maybe in another view the conversation was unbound
316 if(conversation!=null && !conversation.isBound()){
317 conversation.bind();
318 }
319 if(cdmEntitySession != null) {
320 cdmEntitySession.bind();
321 }
322 }
323
324 @Override
325 public void update(CdmDataChangeMap changeEvents) {
326 }
327
328 @Override
329 public ConversationHolder getConversationHolder() {
330 return conversation;
331 }
332
333 @Override
334 public void changed(Object element) {
335 setDirty(true);
336 firePropertyChange(IEditorPart.PROP_DIRTY);
337 viewer.refresh();
338 }
339
340 @Override
341 public void forceDirty() {
342 changed(null);
343 }
344
345 @Override
346 public Map<Object, List<String>> getPropertyPathsMap() {
347 List<String> specimenPropertyPaths = Arrays.asList(new String[] {
348 "descriptions",
349 "derivationEvents.derivates",
350 "annotations",
351 "markers",
352 "credits",
353 "extensions",
354 "rights",
355 "sources"
356 });
357 Map<Object, List<String>> specimenPropertyPathMap =
358 new HashMap<Object, List<String>>();
359 specimenPropertyPathMap.put(SpecimenOrObservationBase.class,specimenPropertyPaths);
360 return specimenPropertyPathMap;
361 }
362
363 /**
364 * Refreshes the derivate hierarchy tree and expands the tree
365 * to show and select the given object.
366 *
367 * @param expandTo the object to which the tree should be expanded
368 */
369 public void refreshTree(Object expandTo){
370 refreshTree();
371 TreeSelection selection = (TreeSelection) viewer.getSelection();
372 viewer.expandToLevel(selection.getFirstElement(), 1);
373 viewer.setSelection(new StructuredSelection(new TreeNode(expandTo)));
374 }
375
376 /**
377 * Refreshes the derivate hierarchy tree
378 */
379 public void refreshTree(){
380 refreshTree(true);
381 }
382
383 /**
384 * Refreshes the derivate hierarchy tree
385 * @param refreshViewer if <code>true</code> then also the
386 * viewer will be refreshed. This was implemented due to
387 * performance reasons. If passing <code>false</code>
388 * does what was expected use <code>false</code> preferably.
389 */
390 public void refreshTree(boolean refreshViewer){
391 //refresh typedesignations
392 labelProvider.refresh();
393 if(refreshViewer){
394 viewer.refresh();
395 }
396 }
397
398 //FIXME:Remoting hack to make this work for remoting
399 //This should actually be resolved using remoting post operations
400 public void remove(Object obj) {
401 rootElements.remove(obj);
402 viewer.setInput(rootElements);
403 }
404
405 /**
406 * @return a set of {@link SingleRead}s that have multiple parents
407 */
408 public Set<SingleRead> getMultiLinkSingleReads() {
409 return DerivateLabelProvider.getMultiLinkSingleReads();
410 }
411
412 public Object getSelectionInput() {
413 return selectedTaxon;
414 }
415
416 public DerivateLabelProvider getLabelProvider() {
417 return labelProvider;
418 }
419
420 @Override
421 public boolean postOperation(CdmBase objectAffectedByOperation) {
422 refreshTree();
423 if(objectAffectedByOperation!=null){
424 changed(objectAffectedByOperation);
425 }
426 return true;
427 }
428
429 @Override
430 public boolean onComplete() {
431 return true;
432 }
433
434
435 @Override
436 public boolean canAttachMedia() {
437 return true;
438 }
439
440 public void addFieldUnit(FieldUnit fieldUnit) {
441 rootElements.add(fieldUnit);
442 derivateToRootEntityMap.put(fieldUnit, fieldUnit);
443 }
444
445 @Override
446 public ICdmEntitySession getCdmEntitySession() {
447 return cdmEntitySession;
448 }
449
450 @Override
451 public void dispose() {
452 super.dispose();
453 if(conversation!=null){
454 conversation.close();
455 }
456 if(cdmEntitySession != null) {
457 cdmEntitySession.dispose();
458 }
459 }
460
461 @Override
462 public void selectionChanged(IWorkbenchPart part, ISelection selection) {
463 if(viewer.getTree().isDisposed()){
464 return;
465 }
466 if(listenToSelectionChange){
467 if(part instanceof MultiPageTaxonEditor){
468 selectedTaxon = ((MultiPageTaxonEditor) part).getTaxon();
469 }
470 else if(selection instanceof IStructuredSelection){
471 Object selectedElement = ((IStructuredSelection) selection).getFirstElement();
472 if(selectedElement instanceof CdmBase){
473 if(((CdmBase) selectedElement).isInstanceOf(TaxonNode.class)){
474 selectedTaxon = HibernateProxyHelper.deproxy(selectedElement, TaxonNode.class).getTaxon();
475 }
476 else if(((CdmBase) selectedElement).isInstanceOf(Taxon.class)){
477 selectedTaxon = HibernateProxyHelper.deproxy(selectedElement, Taxon.class);
478 }
479 }
480 }
481 Collection<SpecimenOrObservationBase> fieldUnits = CdmStore.getService(IOccurrenceService.class).listFieldUnitsByAssociatedTaxon(selectedTaxon, null, null);
482 Collection<UUID> uuids = new HashSet<UUID>();
483 for (SpecimenOrObservationBase specimenOrObservationBase : fieldUnits) {
484 uuids.add(specimenOrObservationBase.getUuid());
485 }
486 updateRootEntities(uuids);
487 setPartName("Derivative Editor: " + selectedTaxon.getName());
488 }
489 }
490
491 public TreeViewer getViewer() {
492 return viewer;
493 }
494
495 /**
496 * {@inheritDoc}
497 */
498 @Override
499 public List<SpecimenOrObservationBase<?>> getRootEntities() {
500 return new ArrayList<SpecimenOrObservationBase<?>>(rootElements);
501 }
502
503 public void toggleListenToSelectionChange() {
504 listenToSelectionChange = !listenToSelectionChange;
505 derivateSearchCompositeController.setEnabled(!listenToSelectionChange);
506 if(!listenToSelectionChange){
507 selectedTaxon = null;
508 setPartName("Derivative Editor");
509 }
510 else if(selectedTaxon==null){
511 setPartName("Derivative Editor [no taxon selected]");
512 }
513 }
514
515 public boolean isListenToSelectionChange(){
516 return listenToSelectionChange;
517 }
518
519 /**
520 * {@inheritDoc}
521 */
522 @Override
523 public void contextAboutToStop(IMemento memento, IProgressMonitor monitor) {
524 }
525
526 /**
527 * {@inheritDoc}
528 */
529 @Override
530 public void contextStop(IMemento memento, IProgressMonitor monitor) {
531 derivateSearchCompositeController.setEnabled(false);
532 viewer.getTree().setEnabled(false);
533 viewer.setInput(null);
534 }
535
536 /**
537 * {@inheritDoc}
538 */
539 @Override
540 public void contextStart(IMemento memento, IProgressMonitor monitor) {
541 derivateSearchCompositeController.setEnabled(!listenToSelectionChange);
542 viewer.getTree().setEnabled(true);
543 refreshTree();
544 }
545
546 /**
547 * {@inheritDoc}
548 */
549 @Override
550 public void contextRefresh(IProgressMonitor monitor) {
551 }
552
553 /**
554 * {@inheritDoc}
555 */
556 @Override
557 public void workbenchShutdown(IMemento memento, IProgressMonitor monitor) {
558 }
559
560 }