Project

General

Profile

Download (41.9 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2017 EDIT
3
 * European Distributed Institute of Taxonomy
4
 * http://www.e-taxonomy.eu
5
 *
6
 * The contents of this file are subject to the Mozilla Public License Version 1.1
7
 * See LICENSE.TXT at the top of this package for the full license terms.
8
 */
9
package eu.etaxonomy.taxeditor.editor.workingSet.matrix;
10

    
11
import java.io.File;
12
import java.io.FileInputStream;
13
import java.io.FileOutputStream;
14
import java.io.IOException;
15
import java.util.ArrayList;
16
import java.util.Arrays;
17
import java.util.Collection;
18
import java.util.Collections;
19
import java.util.Comparator;
20
import java.util.HashMap;
21
import java.util.HashSet;
22
import java.util.List;
23
import java.util.Map;
24
import java.util.Properties;
25
import java.util.Set;
26
import java.util.UUID;
27

    
28
import javax.annotation.PostConstruct;
29
import javax.annotation.PreDestroy;
30
import javax.inject.Inject;
31

    
32
import org.apache.commons.collections4.map.LinkedMap;
33
import org.eclipse.core.runtime.IProgressMonitor;
34
import org.eclipse.e4.ui.di.Focus;
35
import org.eclipse.e4.ui.di.Persist;
36
import org.eclipse.e4.ui.model.application.ui.MDirtyable;
37
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
38
import org.eclipse.e4.ui.workbench.modeling.ESelectionService;
39
import org.eclipse.jface.layout.GridDataFactory;
40
import org.eclipse.jface.viewers.ArrayContentProvider;
41
import org.eclipse.jface.viewers.ComboViewer;
42
import org.eclipse.jface.viewers.LabelProvider;
43
import org.eclipse.jface.viewers.StructuredSelection;
44
import org.eclipse.jface.window.Window;
45
import org.eclipse.nebula.widgets.nattable.NatTable;
46
import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration;
47
import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes;
48
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
49
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
50
import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
51
import org.eclipse.nebula.widgets.nattable.config.IEditableRule;
52
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
53
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
54
import org.eclipse.nebula.widgets.nattable.edit.EditConfigAttributes;
55
import org.eclipse.nebula.widgets.nattable.edit.editor.IComboBoxDataProvider;
56
import org.eclipse.nebula.widgets.nattable.export.command.ExportCommand;
57
import org.eclipse.nebula.widgets.nattable.export.command.ExportCommandHandler;
58
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsEventLayer;
59
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsSortModel;
60
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeData;
61
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeRowModel;
62
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
63
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
64
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
65
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
66
import org.eclipse.nebula.widgets.nattable.grid.data.FixedSummaryRowHeaderLayer;
67
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
68
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
69
import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultRowHeaderDataLayer;
70
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
71
import org.eclipse.nebula.widgets.nattable.hideshow.ColumnHideShowLayer;
72
import org.eclipse.nebula.widgets.nattable.hideshow.RowHideShowLayer;
73
import org.eclipse.nebula.widgets.nattable.layer.CompositeLayer;
74
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
75
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
76
import org.eclipse.nebula.widgets.nattable.layer.ILayerListener;
77
import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator;
78
import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell;
79
import org.eclipse.nebula.widgets.nattable.layer.event.ILayerEvent;
80
import org.eclipse.nebula.widgets.nattable.persistence.PersistenceHelper;
81
import org.eclipse.nebula.widgets.nattable.persistence.command.DisplayPersistenceDialogCommand;
82
import org.eclipse.nebula.widgets.nattable.persistence.command.DisplayPersistenceDialogCommandHandler;
83
import org.eclipse.nebula.widgets.nattable.persistence.command.IStateChangedListener;
84
import org.eclipse.nebula.widgets.nattable.persistence.command.StateChangeEvent;
85
import org.eclipse.nebula.widgets.nattable.persistence.gui.PersistenceDialog;
86
import org.eclipse.nebula.widgets.nattable.reorder.ColumnReorderLayer;
87
import org.eclipse.nebula.widgets.nattable.reorder.RowReorderLayer;
88
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
89
import org.eclipse.nebula.widgets.nattable.selection.event.CellSelectionEvent;
90
import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer;
91
import org.eclipse.nebula.widgets.nattable.sort.config.SingleClickSortConfiguration;
92
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
93
import org.eclipse.nebula.widgets.nattable.summaryrow.FixedSummaryRowLayer;
94
import org.eclipse.nebula.widgets.nattable.summaryrow.SummaryRowLayer;
95
import org.eclipse.nebula.widgets.nattable.tree.ITreeRowModel;
96
import org.eclipse.nebula.widgets.nattable.tree.TreeLayer;
97
import org.eclipse.nebula.widgets.nattable.ui.menu.AbstractHeaderMenuConfiguration;
98
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuBuilder;
99
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
100
import org.eclipse.swt.SWT;
101
import org.eclipse.swt.events.SelectionAdapter;
102
import org.eclipse.swt.events.SelectionEvent;
103
import org.eclipse.swt.layout.GridData;
104
import org.eclipse.swt.layout.GridLayout;
105
import org.eclipse.swt.widgets.Button;
106
import org.eclipse.swt.widgets.Composite;
107
import org.eclipse.swt.widgets.Label;
108

    
109
import ca.odell.glazedlists.EventList;
110
import ca.odell.glazedlists.GlazedLists;
111
import ca.odell.glazedlists.SortedList;
112
import ca.odell.glazedlists.TreeList;
113
import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
114
import eu.etaxonomy.cdm.api.conversation.IConversationEnabled;
115
import eu.etaxonomy.cdm.api.service.IWorkingSetService;
116
import eu.etaxonomy.cdm.model.common.TermVocabulary;
117
import eu.etaxonomy.cdm.model.description.DescriptionBase;
118
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
119
import eu.etaxonomy.cdm.model.description.Feature;
120
import eu.etaxonomy.cdm.model.description.FeatureTree;
121
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
122
import eu.etaxonomy.cdm.model.description.SpecimenDescription;
123
import eu.etaxonomy.cdm.model.description.State;
124
import eu.etaxonomy.cdm.model.description.WorkingSet;
125
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
126
import eu.etaxonomy.cdm.model.taxon.Taxon;
127
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
128
import eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap;
129
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.categorical.CategoricalDataCellEditor;
130
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.categorical.CategoricalDataDisplayConverter;
131
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.quantitative.QuantitativeDataCellEditor;
132
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.quantitative.QuantitativeDataDisplayConverter;
133
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.supplementalInfo.SupplementalInfoDisplayConverter;
134
import eu.etaxonomy.taxeditor.model.DescriptionHelper;
135
import eu.etaxonomy.taxeditor.model.IDirtyMarkable;
136
import eu.etaxonomy.taxeditor.model.IPartContentHasDetails;
137
import eu.etaxonomy.taxeditor.model.ImageResources;
138
import eu.etaxonomy.taxeditor.model.MessagingUtils;
139
import eu.etaxonomy.taxeditor.session.ICdmEntitySession;
140
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled;
141
import eu.etaxonomy.taxeditor.store.CdmStore;
142
import eu.etaxonomy.taxeditor.workbench.WorkbenchUtility;
143
import eu.etaxonomy.taxeditor.workbench.part.IE4SavablePart;
144

    
145
/**
146
 * @author pplitzner
147
 * @since Nov 26, 2017
148
 *
149
 */
150
public class CharacterMatrix implements IE4SavablePart, IPartContentHasDetails, IConversationEnabled, IDirtyMarkable,
151
ICdmEntitySessionEnabled{
152

    
153
    private static final List<String> WS_PROPERTY_PATH = Arrays.asList(new String[] {
154
            "descriptions", //$NON-NLS-1$
155
            "descriptions.descriptionElements", //$NON-NLS-1$
156
            "descriptions.descriptionElements.inDescription", //$NON-NLS-1$
157
            "descriptions.descriptionElements.inDescription.descriptionElements", //$NON-NLS-1$
158
            "descriptions.descriptionElements.feature", //$NON-NLS-1$
159
    });
160

    
161
    private static final String CHARACTER_MATRIX_STATE_PROPERTIES = "characterMatrixState.properties";
162

    
163
    private static final int LEADING_COLUMN_COUNT = 4;
164
    private static final String TAXON_COLUMN = "taxon_column";
165
    private static final String COLLECTOR_COLUMN = "collector_column";
166
    private static final String IDENTIFIER_COLUMN = "identifier_column";
167
    private static final String COUNTRY_COLUMN = "country_column";
168

    
169
    private WorkingSet workingSet;
170

    
171
    private Composite parent;
172

    
173
    private ConversationHolder conversation;
174

    
175
    private ICdmEntitySession cdmEntitySession;
176

    
177
    @Inject
178
    private ESelectionService selService;
179

    
180
    @Inject
181
    private MDirtyable dirty;
182

    
183
    @Inject
184
    private MPart thisPart;
185

    
186
    private NatTable natTable;
187

    
188
    private Map<Integer, Feature> indexToFeatureMap = new HashMap<>();
189

    
190
    private LinkedMap<String, String> propertyToLabelMap = new LinkedMap<>();
191

    
192
    private Properties natTableState;
193

    
194
    private EventList<Object> descriptions;
195

    
196
    private Collection<SpecimenOrObservationBase> specimenCache = null;
197

    
198
    @PostConstruct
199
    public void create(Composite parent) {
200
        if(CdmStore.isActive() && conversation==null){
201
            conversation = CdmStore.createConversation();
202
        }
203
        if(cdmEntitySession == null){
204
            cdmEntitySession = CdmStore.getCurrentSessionManager().newSession(this, true);
205
        }
206
        else{
207
            return;
208
        }
209
        parent.setLayout(new GridLayout());
210
        this.parent = parent;
211
    }
212

    
213

    
214
    public void init(UUID workingSetUuid) {
215
        this.workingSet = CdmStore.getService(IWorkingSetService.class).load(workingSetUuid, WS_PROPERTY_PATH);
216
        thisPart.setLabel(workingSet.getLabel());
217

    
218
        Composite toolbarComposite = new Composite(parent, SWT.NONE);
219
        toolbarComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
220
        toolbarComposite.setLayout(new GridLayout(4, false));
221

    
222
        //get features/columns stored in working set
223
        FeatureTree tree = workingSet.getDescriptiveSystem();
224
        List<Feature> features = new ArrayList<>(tree.getDistinctFeatures());
225
        Collections.sort(features);
226

    
227
        descriptions = GlazedLists.eventList(getDescriptions(workingSet));
228
        // use the SortedList constructor with 'null' for the Comparator
229
        // because the Comparator will be set by configuration
230
        SortedList<Object> sortedList = new SortedList<>(descriptions, null);
231
        // wrap the SortedList with the TreeList
232
        TreeList treeList = new TreeList(sortedList, new DescriptionTreeFormat(), TreeList.NODES_START_EXPANDED);
233

    
234
        ConfigRegistry configRegistry = new ConfigRegistry();
235

    
236
        /**
237
         * data provider
238
         */
239
        SpecimenColumnPropertyAccessor columnPropertyAccessor = new SpecimenColumnPropertyAccessor(this);
240
        IDataProvider bodyDataProvider = new ListDataProvider<Object>(treeList, columnPropertyAccessor);
241

    
242
        /**
243
         * BODY layer
244
         *
245
         *
246

    
247
        CompositeLayer
248
         - (top) SummaryRowLayer
249
         - (bottom) ViewportLayer
250

    
251
             ^
252
        ViewportLayer
253

    
254
             ^
255
        SelectionLayer
256

    
257
             ^
258
        RowHideShowLayer
259

    
260
             ^
261
        ColumnHideShowLayer
262

    
263
             ^
264
        ColumnReorderLayer
265

    
266
             ^
267
        RowReorderLayer
268

    
269
             ^
270
        DataLayer
271

    
272
         *
273

    
274
         */
275
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
276

    
277
        //register labels for columns
278
        ColumnOverrideLabelAccumulator bodyColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
279
        bodyDataLayer.setConfigLabelAccumulator(bodyColumnLabelAccumulator);
280
        propertyToLabelMap.put(TAXON_COLUMN, "Taxon");
281
        bodyColumnLabelAccumulator.registerColumnOverrides(0, TAXON_COLUMN);
282
        propertyToLabelMap.put(COLLECTOR_COLUMN, "Collector + No");
283
        bodyColumnLabelAccumulator.registerColumnOverrides(1, COLLECTOR_COLUMN);
284
        propertyToLabelMap.put(IDENTIFIER_COLUMN, "Identifier");
285
        bodyColumnLabelAccumulator.registerColumnOverrides(2, IDENTIFIER_COLUMN);
286
        propertyToLabelMap.put(COUNTRY_COLUMN, "Country");
287
        bodyColumnLabelAccumulator.registerColumnOverrides(3, COUNTRY_COLUMN);
288
        for(int i=0;i<features.size();i++){
289
            Feature feature = features.get(i);
290
            initLabels(bodyColumnLabelAccumulator, i, feature);
291
        }
292

    
293
        // layer for event handling of GlazedLists and PropertyChanges
294
        GlazedListsEventLayer eventLayer = new GlazedListsEventLayer<>(bodyDataLayer, treeList);
295
        GlazedListTreeData treeData = new GlazedListTreeData<>(treeList);
296
        ITreeRowModel treeRowModel = new GlazedListTreeRowModel<>(treeData);
297

    
298
        RowReorderLayer rowReorderLayer = new RowReorderLayer(eventLayer);
299
        ColumnReorderLayer columnReorderLayer = new ColumnReorderLayer(rowReorderLayer);
300
        ColumnHideShowLayer columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
301
        RowHideShowLayer rowHideShowLayer = new RowHideShowLayer(columnHideShowLayer);
302
        SelectionLayer selectionLayer = new SelectionLayer(rowHideShowLayer);
303
        TreeLayer treeLayer = new TreeLayer(selectionLayer, treeRowModel);
304
        ViewportLayer viewportLayer = new ViewportLayer(treeLayer);
305

    
306

    
307

    
308
        // create a standalone FixedSummaryRowLayer
309
        // since the summary row should be fixed at the top of the body
310
        // region the horizontal dependency of the FixedSummaryRowLayer
311
        // is the ViewportLayer
312
        FixedSummaryRowLayer summaryRowLayer =
313
                new FixedSummaryRowLayer(bodyDataLayer, viewportLayer, configRegistry, false);
314
        //regoster labels with summary prefix for summary layer
315
        ColumnOverrideLabelAccumulator summaryColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
316
        summaryRowLayer.setConfigLabelAccumulator(summaryColumnLabelAccumulator);
317
        for(int i=0;i<features.size();i++){
318
            Feature feature = features.get(i);
319
            summaryColumnLabelAccumulator.registerColumnOverrides(
320
                    i+LEADING_COLUMN_COUNT,
321
                    SummaryRowLayer.DEFAULT_SUMMARY_COLUMN_CONFIG_LABEL_PREFIX+MatrixUtility.getProperty(feature));
322
        }
323
        // because the horizontal dependency is the ViewportLayer
324
        // we need to set the composite dependency to false
325
        summaryRowLayer.setHorizontalCompositeDependency(false);
326

    
327
        CompositeLayer composite = new CompositeLayer(1, 2);
328
        composite.setChildLayer("SUMMARY", summaryRowLayer, 0, 0);
329
        composite.setChildLayer(GridRegion.BODY, viewportLayer, 0, 1);
330

    
331

    
332

    
333

    
334
        /**
335
         * column header layer
336
         */
337
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
338
                propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
339
        DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
340
        ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, viewportLayer, selectionLayer);
341

    
342
        // add the SortHeaderLayer to the column header layer stack
343
        // as we use GlazedLists, we use the GlazedListsSortModel which
344
        // delegates the sorting to the SortedList
345
        final SortHeaderLayer<SpecimenDescription> sortHeaderLayer = new SortHeaderLayer<>(
346
                columnHeaderLayer,
347
                new GlazedListsSortModel<>(
348
                        sortedList,
349
                        columnPropertyAccessor,
350
                        configRegistry,
351
                        columnHeaderDataLayer));
352

    
353

    
354
        /**
355
         * row header layer
356
         */
357
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
358
        DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
359
        FixedSummaryRowHeaderLayer fixedSummaryRowHeaderLayer = new FixedSummaryRowHeaderLayer(rowHeaderDataLayer,
360
                composite, selectionLayer);
361
        fixedSummaryRowHeaderLayer.setSummaryRowLabel("\u2211");
362

    
363

    
364
        /**
365
         * corner layer
366
         */
367
        ILayer cornerLayer = new CornerLayer(
368
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
369
                fixedSummaryRowHeaderLayer, sortHeaderLayer);
370

    
371

    
372
        /**
373
         * GRID layer (composition of all other layers)
374
         */
375
        GridLayer gridLayer = new GridLayer(composite, sortHeaderLayer, fixedSummaryRowHeaderLayer, cornerLayer);
376

    
377

    
378

    
379
        natTable = new NatTable(parent, gridLayer, false);
380

    
381

    
382
        /**
383
         * CONFIGURATION
384
         */
385
        natTable.setConfigRegistry(configRegistry);
386

    
387

    
388
        //add default configuration because autoconfigure is set to false in constructor
389
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
390

    
391
        //FIXME: this is for DEBUG ONLY
392
        //        natTable.addConfiguration(new DebugMenuConfiguration(natTable));
393

    
394
        // override the default sort configuration and change the mouse bindings
395
        // to sort on a single click
396
        natTable.addConfiguration(new SingleClickSortConfiguration());
397

    
398

    
399
        // add the header menu configuration for adding the column header menu
400
        // with hide/show actions
401
        natTable.addConfiguration(new AbstractHeaderMenuConfiguration(natTable) {
402

    
403
            @Override
404
            protected PopupMenuBuilder createColumnHeaderMenu(NatTable natTable) {
405
                return super.createColumnHeaderMenu(natTable)
406
                        .withHideColumnMenuItem()
407
                        .withShowAllColumnsMenuItem();
408
            }
409

    
410
            @Override
411
            protected PopupMenuBuilder createRowHeaderMenu(NatTable natTable) {
412
                return super.createRowHeaderMenu(natTable)
413
                        .withHideRowMenuItem()
414
                        .withShowAllRowsMenuItem();
415
            }
416

    
417
            @Override
418
            protected PopupMenuBuilder createCornerMenu(NatTable natTable) {
419
                return super.createCornerMenu(natTable)
420
                        .withShowAllColumnsMenuItem()
421
                        .withShowAllRowsMenuItem();
422
            }
423
        });
424

    
425
        // add custom configuration for data conversion and add column labels to viewport layer
426
        viewportLayer.addConfiguration(new AbstractRegistryConfiguration() {
427
            @Override
428
            public void configureRegistry(IConfigRegistry configRegistry) {
429
                //add display converter for string representation
430
                configRegistry.registerConfigAttribute(
431
                        CellConfigAttributes.DISPLAY_CONVERTER,
432
                        new SupplementalInfoDisplayConverter(),
433
                        DisplayMode.NORMAL,
434
                        TAXON_COLUMN);
435
                configRegistry.registerConfigAttribute(
436
                        CellConfigAttributes.DISPLAY_CONVERTER,
437
                        new SupplementalInfoDisplayConverter(),
438
                        DisplayMode.NORMAL,
439
                        COLLECTOR_COLUMN);
440
                configRegistry.registerConfigAttribute(
441
                        CellConfigAttributes.DISPLAY_CONVERTER,
442
                        new SupplementalInfoDisplayConverter(),
443
                        DisplayMode.NORMAL,
444
                        IDENTIFIER_COLUMN);
445
                configRegistry.registerConfigAttribute(
446
                        CellConfigAttributes.DISPLAY_CONVERTER,
447
                        new SupplementalInfoDisplayConverter(),
448
                        DisplayMode.NORMAL,
449
                        COUNTRY_COLUMN);
450
                features.forEach(feature->registerColumnConfiguration(feature, configRegistry));
451
            }
452

    
453
        });
454

    
455
        //register aggregation configuration for each feature
456
        features.forEach(feature->summaryRowLayer.addConfiguration(new AggregationConfiguration(bodyDataProvider, feature)));
457

    
458
        // add the ExportCommandHandler to the ViewportLayer in order to make
459
        // exporting work
460
        viewportLayer.registerCommandHandler(new ExportCommandHandler(viewportLayer));
461

    
462
        //propagate single cell selection
463
        natTable.addLayerListener(new ILayerListener() {
464
            @Override
465
            public void handleLayerEvent(ILayerEvent event) {
466
                if(event instanceof CellSelectionEvent){
467
                    CellSelectionEvent cellSelectionEvent = (CellSelectionEvent)event;
468
                    Collection<ILayerCell> selectedCells = cellSelectionEvent.getSelectionLayer().getSelectedCells();
469
                    StructuredSelection selection = new StructuredSelection();
470
                    if(selectedCells.size()==1){
471
                        ILayerCell cell = selectedCells.iterator().next();
472
                        Object dataValue = cell.getDataValue();
473
                        if(dataValue!=null){
474
                            selection = new StructuredSelection(dataValue);
475
                        }
476
                    }
477
                    selService.setSelection(selection);
478
                }
479
            }
480
        });
481

    
482
        natTable.configure();
483

    
484
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
485

    
486
        /**
487
         * Info label
488
         */
489
        Label wsLabel = new Label(toolbarComposite, SWT.NONE);
490
        wsLabel.setText(workingSet.getLabel());
491
        wsLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
492

    
493
        /**
494
         * Table state persistence
495
         */
496
        natTableState = new Properties();
497
        //load persisted state
498
        File statePropertiesFile = getStatePropertiesFile();
499
        FileInputStream inputStream;
500
        try {
501
            inputStream = new FileInputStream(statePropertiesFile);
502
            natTableState.load(inputStream);
503
        } catch (IOException e) {
504
            MessagingUtils.info("No initial state properties file found for character matrix");
505
        }
506

    
507
        DisplayPersistenceDialogCommandHandler handler =
508
                new DisplayPersistenceDialogCommandHandler(natTableState, natTable);
509
        gridLayer.registerCommandHandler(handler);
510
        // create a combobox for showing the available view states
511
        ComboViewer comboStates= new ComboViewer(toolbarComposite, SWT.DROP_DOWN) ;
512
        Collection<String> availableStates = PersistenceHelper.getAvailableStates(natTableState);
513
        comboStates.setLabelProvider(new LabelProvider(){
514
            @Override
515
            public String getText(Object element) {
516
                if(element instanceof String && ((String) element).isEmpty()){
517
                    return "-default-";
518
                }
519
                return super.getText(element);
520
            }
521
        });
522
        comboStates.setContentProvider(new ArrayContentProvider());
523
        comboStates.addSelectionChangedListener(e->
524
        {
525
            int index = comboStates.getCombo().getSelectionIndex();
526
            if (index >= 0) {
527
                String selected = comboStates.getCombo().getItem(index);
528
                // load the state
529
                natTable.loadState(selected, natTableState);
530
                natTableState.setProperty(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY, selected);
531
            }
532
        });
533
        comboStates.setInput(availableStates);
534
        if(comboStates.getCombo().getItemCount()>0){
535
            comboStates.getCombo().select(0);
536
        }
537

    
538
        // add listener to update the combo on view state management changes
539
        handler.addStateChangeListener(new IStateChangedListener() {
540
            @Override
541
            public void handleStateChange(StateChangeEvent event) {
542
                comboStates.setInput(PersistenceHelper.getAvailableStates(natTableState));
543
                selectStateItem(comboStates, event.getViewConfigName());
544
            }
545
        });
546

    
547
        // add button to show dialog
548
        Button btnManageState = new Button(toolbarComposite, SWT.PUSH);
549
        btnManageState.setImage(ImageResources.getImage(ImageResources.SETTINGS));
550
        btnManageState.addSelectionListener(new SelectionAdapter() {
551
            @Override
552
            public void widgetSelected(SelectionEvent e) {
553
                natTable.doCommand(new DisplayPersistenceDialogCommand(natTable));
554
                selectStateItem(comboStates, natTableState.get(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY).toString());
555
            }
556
        });
557

    
558
        /**
559
         * excel export
560
         */
561
        Button btnExcelExport = new Button(toolbarComposite, SWT.PUSH);
562
        btnExcelExport.setToolTipText("Export to Excel");
563
        btnExcelExport.setImage(ImageResources.getImage(ImageResources.EXPORT));
564
        btnExcelExport.addSelectionListener(new SelectionAdapter() {
565
            @Override
566
            public void widgetSelected(SelectionEvent e) {
567
                natTable.doCommand(
568
                        new ExportCommand(
569
                                natTable.getConfigRegistry(),
570
                                natTable.getShell()));
571
            }
572
        });
573

    
574
        /**
575
         * Add description button
576
         */
577
        Button btnAddDescription = new Button(parent, SWT.PUSH);
578
        btnAddDescription.setImage(ImageResources.getImage(ImageResources.ADD_ICON));
579
        btnAddDescription.addSelectionListener(new SelectionAdapter() {
580
            @Override
581
            public void widgetSelected(SelectionEvent e) {
582
                SpecimenSelectionDialog dialog = new SpecimenSelectionDialog(natTable.getShell(), CharacterMatrix.this);
583
                if(dialog.open()==Window.OK){
584
                    Collection<SpecimenOrObservationBase> specimens = dialog.getSpecimen();
585
                    boolean hasAdded = false;
586
                    for (SpecimenOrObservationBase specimen : specimens) {
587
                        SpecimenDescription description = getDescriptionForWorkingSet(specimen);
588
                        if(!workingSet.getDescriptions().contains(description)){
589
                            CharacterMatrix.this.descriptions.add(new RowWrapper(description));
590
                            workingSet.addDescription(description);
591
                            hasAdded = true;
592
                        }
593
                    }
594
                    if(hasAdded){
595
                        setDirty();
596
                    }
597
                }
598
            }
599
        });
600
        parent.layout();
601
    }
602

    
603
    private void selectStateItem(ComboViewer comboStates, String stateName){
604
        String[] items = comboStates.getCombo().getItems();
605
        for(int i=0;i<items.length;i++){
606
            if(items[i].equals(stateName)){
607
                comboStates.getCombo().select(i);
608
                break;
609
            }
610
        }
611
    }
612

    
613
    private SpecimenDescription getDescriptionForWorkingSet(SpecimenOrObservationBase specimen){
614
        Set<Feature> wsFeatures = workingSet.getDescriptiveSystem().getDistinctFeatures();
615
        List<DescriptionElementBase> matchingDescriptionElements = new ArrayList<>();
616

    
617
        for (SpecimenDescription specimenDescription : (Set<SpecimenDescription>) specimen.getDescriptions()) {
618
            Set<Feature> specimenDescriptionFeatures = new HashSet<>();
619
            //gather specimen description features and check for match with WS features
620
            for (DescriptionElementBase specimenDescriptionElement : specimenDescription.getElements()) {
621
                Feature feature = specimenDescriptionElement.getFeature();
622
                specimenDescriptionFeatures.add(feature);
623
                if(wsFeatures.contains(feature)){
624
                    matchingDescriptionElements.add(specimenDescriptionElement);
625
                }
626
            }
627
            //if description with the exact same features is found return the description
628
            if(specimenDescriptionFeatures.equals(wsFeatures)){
629
                return specimenDescription;
630
            }
631
        }
632
        //Create new specimen description if no match was found
633
        setDirty();
634
        SpecimenDescription newDesription = SpecimenDescription.NewInstance(specimen);
635
        newDesription.setTitleCache("WorkingSet "+workingSet.getLabel()+": "+newDesription.generateTitle(), true);
636

    
637
        //check for equals description element (same feature and same values)
638
        Map<Feature, List<DescriptionElementBase>> featureToElementMap = new HashMap<>();
639
        for(DescriptionElementBase element:matchingDescriptionElements){
640
            List<DescriptionElementBase> list = featureToElementMap.get(element.getFeature());
641
            if(list==null){
642
                list = new ArrayList<>();
643
            }
644
            list.add(element);
645
            featureToElementMap.put(element.getFeature(), list);
646
        }
647
        Set<DescriptionElementBase> descriptionElementsToClone = new HashSet<>();
648
        for(Feature feature:featureToElementMap.keySet()){
649
            List<DescriptionElementBase> elements = featureToElementMap.get(feature);
650
            //no duplicate description elements found for this feature
651
            if(elements.size()==1){
652
                descriptionElementsToClone.add(elements.get(0));
653
            }
654
            //duplicates found -> check if all are equal
655
            else{
656
                DescriptionElementBase match = null;
657
                for (DescriptionElementBase descriptionElementBase : elements) {
658
                    if(match==null){
659
                        match = descriptionElementBase;
660
                    }
661
                    else if(!new DescriptionElementCompareWrapper(match).equals(new DescriptionElementCompareWrapper(descriptionElementBase))){
662
                        match = null;
663
                        MessagingUtils.informationDialog("Multiple data found",
664
                                String.format("Multiple description elements with different values "
665
                                        + "found for feature '%s'.\nData will not be copied to new specimen description.", feature.getLabel()));
666
                        break;
667
                    }
668
                }
669
                if(match!=null){
670
                    descriptionElementsToClone.add(match);
671
                }
672
            }
673
        }
674
        //clone matching descriptionElements
675
        for (DescriptionElementBase descriptionElementBase : descriptionElementsToClone) {
676
            DescriptionElementBase clone;
677
            try {
678
                clone = descriptionElementBase.clone(newDesription);
679
                clone.getSources().forEach(source -> source.setOriginalNameString(DescriptionHelper.getLabel(descriptionElementBase)));
680
            } catch (CloneNotSupportedException e) {
681
                MessagingUtils.error(CharacterMatrix.class, e);
682
            }
683
        }
684
        return newDesription;
685

    
686
    }
687

    
688
    private void initLabels(final ColumnOverrideLabelAccumulator columnLabelAccumulator,
689
            int index, Feature feature) {
690

    
691
        columnLabelAccumulator.registerColumnOverrides(index+LEADING_COLUMN_COUNT, MatrixUtility.getProperty(feature));
692
        indexToFeatureMap.put(index+LEADING_COLUMN_COUNT, feature);
693

    
694
        String featureLabel = feature.getLabel();
695
        String property = featureLabel;
696
        //show unit for quantitative data
697
        if(feature.isSupportsQuantitativeData()){
698
            Set<MeasurementUnit> recommendedMeasurementUnits = feature.getRecommendedMeasurementUnits();
699
            if(recommendedMeasurementUnits.size()!=1){
700
                MessagingUtils.warningDialog("Column initialization problem", CharacterMatrix.class,
701
                        String.format("Only one unit is allowed for quantitative data: %s", feature.getLabel()));
702
                return;
703
            }
704
            MeasurementUnit unit = recommendedMeasurementUnits.iterator().next();
705
            featureLabel += " ["+unit.getLabel()+"]";
706
        }
707
        propertyToLabelMap.put(property, featureLabel);
708
    }
709

    
710
    private void registerColumnConfiguration(Feature feature, IConfigRegistry configRegistry) {
711
        //make cell editable
712
        configRegistry.registerConfigAttribute(
713
                EditConfigAttributes.CELL_EDITABLE_RULE,
714
                IEditableRule.ALWAYS_EDITABLE,
715
                DisplayMode.EDIT,
716
                MatrixUtility.getProperty(feature)
717
                );
718
        if(feature.isSupportsQuantitativeData()){
719
            //add display converter for string representation
720
            configRegistry.registerConfigAttribute(
721
                    CellConfigAttributes.DISPLAY_CONVERTER,
722
                    new QuantitativeDataDisplayConverter(),
723
                    DisplayMode.NORMAL,
724
                    MatrixUtility.getProperty(feature));
725
            //register quantitative editor
726
            configRegistry.registerConfigAttribute(
727
                    EditConfigAttributes.CELL_EDITOR,
728
                    new QuantitativeDataCellEditor(feature.getRecommendedStatisticalMeasures(), this),
729
                    DisplayMode.EDIT,
730
                    MatrixUtility.getProperty(feature));
731
        }
732
        else if(feature.isSupportsCategoricalData()){
733
            //add display converter for string representation
734
            configRegistry.registerConfigAttribute(
735
                    CellConfigAttributes.DISPLAY_CONVERTER,
736
                    new CategoricalDataDisplayConverter(),
737
                    DisplayMode.NORMAL,
738
                    MatrixUtility.getProperty(feature));
739

    
740
            //add combo box cell editor
741
            CategoricalDataCellEditor comboBoxCellEditor = new CategoricalDataCellEditor(new IComboBoxDataProvider() {
742

    
743
                @Override
744
                public List<?> getValues(int columnIndex, int rowIndex) {
745
                    List<State> states = new ArrayList<>();
746
                    Feature feature = indexToFeatureMap.get(columnIndex);
747
                    if(feature.isSupportsCategoricalData()){
748
                        Set<TermVocabulary<State>> stateVocs = feature.getSupportedCategoricalEnumerations();
749
                        for (TermVocabulary<State> voc : stateVocs) {
750
                            states.addAll(voc.getTerms());
751
                        }
752
                    }
753
                    return states;
754
                }
755
            }, 5, this);
756
            //register editor
757
            configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR,
758
                    comboBoxCellEditor,
759
                    DisplayMode.EDIT,
760
                    MatrixUtility.getProperty(feature));
761

    
762
        }
763

    
764
    }
765

    
766
    private List<RowWrapper> getDescriptions(WorkingSet workingSet) {
767
        List<RowWrapper> rowWrappers = new ArrayList<>();
768
        Set<DescriptionBase> wsDescriptions = workingSet.getDescriptions();
769
        for (DescriptionBase descriptionBase : wsDescriptions) {
770
            if(descriptionBase instanceof SpecimenDescription){
771
                rowWrappers.add(new RowWrapper((SpecimenDescription) descriptionBase));
772
            }
773
        }
774
        return rowWrappers;
775
    }
776

    
777
    public Map<Integer, Feature> getIndexToFeatureMap() {
778
        return indexToFeatureMap;
779
    }
780

    
781
    public LinkedMap<String, String> getPropertyToLabelMap() {
782
        return propertyToLabelMap;
783
    }
784

    
785
    public void setDirty() {
786
        this.dirty.setDirty(true);
787
    }
788

    
789
    public NatTable getNatTable() {
790
        return natTable;
791
    }
792

    
793
    public WorkingSet getWorkingSet() {
794
        return workingSet;
795
    }
796

    
797
    public Collection<SpecimenOrObservationBase> getSpecimenCache() {
798
        return specimenCache;
799
    }
800

    
801
    public void setSpecimenCache(Collection<SpecimenOrObservationBase> specimenCache) {
802
        this.specimenCache = specimenCache;
803
    }
804

    
805
    @Persist
806
    @Override
807
    public void save(IProgressMonitor monitor) {
808
        CdmStore.getService(IWorkingSetService.class).merge(workingSet, true);
809
        conversation.commit();
810
        dirty.setDirty(false);
811
    }
812

    
813
    @Focus
814
    public void setFocus(){
815
        if(conversation!=null){
816
            conversation.bind();
817
        }
818
        if(cdmEntitySession != null) {
819
            cdmEntitySession.bind();
820
        }
821
    }
822

    
823
    @PreDestroy
824
    public void dispose(){
825
        if (conversation != null) {
826
            conversation.close();
827
            conversation = null;
828
        }
829
        if(cdmEntitySession != null) {
830
            cdmEntitySession.dispose();
831
            cdmEntitySession = null;
832
        }
833
        dirty.setDirty(false);
834
        if(natTableState!=null){
835
            try (FileOutputStream tableStateStream =
836
                    new FileOutputStream(getStatePropertiesFile())) {
837
                natTableState.store(tableStateStream, null);
838
            } catch (IOException ioe) {
839
                ioe.printStackTrace();
840
            }
841
        }
842
    }
843

    
844
    private File getStatePropertiesFile() {
845
        return new File(WorkbenchUtility.getBaseLocation(), CHARACTER_MATRIX_STATE_PROPERTIES);
846
    }
847

    
848
    /**
849
     * {@inheritDoc}
850
     */
851
    @Override
852
    public void update(CdmDataChangeMap arg0) {
853
    }
854

    
855
    /**
856
     * {@inheritDoc}
857
     */
858
    @Override
859
    public ConversationHolder getConversationHolder() {
860
        return conversation;
861
    }
862

    
863
    /**
864
     * {@inheritDoc}
865
     */
866
    @Override
867
    public void changed(Object element) {
868
        setDirty();
869
        natTable.refresh();
870
    }
871

    
872
    /**
873
     * {@inheritDoc}
874
     */
875
    @Override
876
    public void forceDirty() {
877
        setDirty();
878
    }
879

    
880

    
881
    /**
882
     * {@inheritDoc}
883
     */
884
    @Override
885
    public ICdmEntitySession getCdmEntitySession() {
886
        return cdmEntitySession;
887
    }
888

    
889

    
890
    /**
891
     * {@inheritDoc}
892
     */
893
    @Override
894
    public Collection<WorkingSet> getRootEntities() {
895
        return Collections.singleton(this.workingSet);
896
    }
897

    
898

    
899
    /**
900
     * {@inheritDoc}
901
     */
902
    @Override
903
    public Map<Object, List<String>> getPropertyPathsMap() {
904
        Map<Object, List<String>> propertyMap = new HashMap<>();
905
        propertyMap.put(SpecimenOrObservationBase.class,WS_PROPERTY_PATH);
906
        return propertyMap;
907
    }
908

    
909
    /*
910
    * Using a String directly as the tree item has the possible disadvantage of
911
    * haven non-unique items in the tree within subtrees.
912
    */
913
    private class DescriptionTreeFormat implements TreeList.Format<Object> {
914

    
915
        private Map parentMapping = new HashMap<>();
916

    
917
        /**
918
         * Populate path with a list describing the path from a root node to
919
         * this element. Upon returning, the list must have size >= 1, where the
920
         * provided element identical to the list's last element. This
921
         * implementation will use the first object found for a last name as
922
         * root node by storing it within a map. If there is already an object
923
         * stored for the lastname of the given element, it will be used as root
924
         * for the path.
925
         */
926
        @Override
927
        public void getPath(List path, Object element) {
928
            if(element instanceof RowWrapper){
929
                //TODO: check for multiple taxon nodes in multiple classifications
930
                Taxon taxon = (Taxon) ((RowWrapper) element).getAssociatedTaxa().iterator().next();
931
                Set<TaxonNode> taxonNodes = taxon.getTaxonNodes();
932
                if(taxonNodes!=null){
933
                    TaxonNode node = taxonNodes.iterator().next();
934
                    addPathRecursive(path, node);
935
//                    Object rowWrapperParentNode = parentMapping.get(node);
936
//                    if(rowWrapperParentNode!=null){
937
//                        path.add(rowWrapperParentNode);
938
//                    }
939
//                    else{
940
//                        TaxonNode parentNode = HibernateProxyHelper.deproxy(node.getParent(), TaxonNode.class);
941
//                        while(parentNode!=null){
942
//                            path.add(parentNode);
943
//                            parentMapping.put(node, parentNode);
944
//                            if(parentNode instanceof TaxonNode){
945
//                                if(parentMapping.get(parentNode)!=null){
946
//                                    path.add(parentMapping).get(parentNode);
947
//                                }
948
//                                else{
949
//                                    parentNode = HibernateProxyHelper.deproxy(parentNode.getParent(), TaxonNode.class);
950
//                                }
951
//                            }
952
//                        }
953
//                    }
954
                }
955
            }
956
            path.add(element);
957
        }
958

    
959
        private void addPathRecursive(List path, TaxonNode node){
960
            if(node.getParent()!=null){
961
                addPathRecursive(path, node.getParent());
962
                path.add(node);
963
            }
964
        }
965

    
966
        /**
967
         * Simply always return true.
968
         *
969
         * @return true if this element can have child elements, or
970
         *         false if it is always a leaf node.
971
         */
972
        @Override
973
        public boolean allowsChildren(Object element) {
974
            return true;
975
        }
976

    
977
        /**
978
         * Returns the comparator used to order path elements of the specified
979
         * depth. If enforcing order at this level is not intended, this method
980
         * should return null. We do a simple sorting of the last
981
         * names of the persons to show so the tree nodes are sorted in
982
         * alphabetical order.
983
         */
984
        @Override
985
        public Comparator<Object> getComparator(int depth) {
986
            return new Comparator<Object>() {
987

    
988
                @Override
989
                public int compare(Object o1, Object o2) {
990
//                    if(o1 instanceof RowWrapper && o2 instanceof RowWrapper){
991
//                        return ((RowWrapper) o1).getSpecimenDescription().getId()-(((RowWrapper) o2).getSpecimenDescription().getId());
992
//                    }
993
//                    else
994
                        if(o1 instanceof TaxonNode && o2 instanceof TaxonNode){
995
                        return ((TaxonNode) o1).getTaxon().getName().getNameCache().compareTo(((TaxonNode) o2).getTaxon().getName().getNameCache());
996
                    }
997
                    return 0;
998
                }
999

    
1000
            };
1001
        }
1002
    }
1003

    
1004

    
1005
}
(2-2/9)