Project

General

Profile

Download (38 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.HashMap;
20
import java.util.HashSet;
21
import java.util.List;
22
import java.util.Map;
23
import java.util.Properties;
24
import java.util.Set;
25
import java.util.UUID;
26

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

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

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

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

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

    
158
    private static final String CHARACTER_MATRIX_STATE_PROPERTIES = "characterMatrixState.properties";
159

    
160
    private static final int LEADING_COLUMN_COUNT = 4;
161
    private static final String TAXON_COLUMN = "taxon_column";
162
    private static final String COLLECTOR_COLUMN = "collector_column";
163
    private static final String IDENTIFIER_COLUMN = "identifier_column";
164
    private static final String COUNTRY_COLUMN = "country_column";
165

    
166
    private WorkingSet workingSet;
167

    
168
    private Composite parent;
169

    
170
    private ConversationHolder conversation;
171

    
172
    private ICdmEntitySession cdmEntitySession;
173

    
174
    @Inject
175
    private ESelectionService selService;
176

    
177
    @Inject
178
    private MDirtyable dirty;
179

    
180
    @Inject
181
    private MPart thisPart;
182

    
183
    private NatTable natTable;
184

    
185
    private Map<Integer, Feature> indexToFeatureMap = new HashMap<>();
186

    
187
    private LinkedMap<String, String> propertyToLabelMap = new LinkedMap<>();
188

    
189
    private Properties natTableState;
190

    
191
    private EventList<Object> descriptions;
192

    
193
    private Collection<SpecimenOrObservationBase> specimenCache = null;
194

    
195
    private ListDataProvider<Object> bodyDataProvider;
196

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

    
212

    
213
    public void init(UUID workingSetUuid) {
214
        this.workingSet = CdmStore.getService(IWorkingSetService.class).load(workingSetUuid, WS_PROPERTY_PATH);
215
        if(workingSet.getDescriptiveSystem()==null){
216
            MessagingUtils.informationDialog("Editor could not be opened", "The working set has no feature tree selected.");
217
            return;
218
        }
219
        thisPart.setLabel(workingSet.getLabel());
220

    
221
        Composite toolbarComposite = new Composite(parent, SWT.NONE);
222
        toolbarComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
223
        toolbarComposite.setLayout(new GridLayout(4, false));
224

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

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

    
237
        ConfigRegistry configRegistry = new ConfigRegistry();
238

    
239
        /**
240
         * data provider
241
         */
242
        SpecimenColumnPropertyAccessor columnPropertyAccessor = new SpecimenColumnPropertyAccessor(this);
243
        bodyDataProvider = new ListDataProvider<Object>(treeList, columnPropertyAccessor);
244

    
245
        /**
246
         * BODY layer
247
         *
248
         *
249

    
250
        CompositeLayer
251
         - (top) SummaryRowLayer
252
         - (bottom) ViewportLayer
253

    
254
             ^
255
        ViewportLayer
256

    
257
             ^
258
        SelectionLayer
259

    
260
             ^
261
        RowHideShowLayer
262

    
263
             ^
264
        ColumnHideShowLayer
265

    
266
             ^
267
        ColumnReorderLayer
268

    
269
             ^
270
        RowReorderLayer
271

    
272
             ^
273
        DataLayer
274

    
275
         *
276

    
277
         */
278
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
279

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

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

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

    
309

    
310

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

    
330
        CompositeLayer composite = new CompositeLayer(1, 2);
331
        composite.setChildLayer("SUMMARY", summaryRowLayer, 0, 0);
332
        composite.setChildLayer(GridRegion.BODY, viewportLayer, 0, 1);
333

    
334

    
335

    
336

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

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

    
356

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

    
366

    
367
        /**
368
         * corner layer
369
         */
370
        ILayer cornerLayer = new CornerLayer(
371
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
372
                fixedSummaryRowHeaderLayer, sortHeaderLayer);
373

    
374

    
375
        /**
376
         * GRID layer (composition of all other layers)
377
         */
378
        GridLayer gridLayer = new GridLayer(composite, sortHeaderLayer, fixedSummaryRowHeaderLayer, cornerLayer);
379

    
380

    
381

    
382
        natTable = new NatTable(parent, gridLayer, false);
383

    
384

    
385
        /**
386
         * CONFIGURATION
387
         */
388
        natTable.setConfigRegistry(configRegistry);
389

    
390

    
391
        //add default configuration because autoconfigure is set to false in constructor
392
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
393

    
394
        //FIXME: this is for DEBUG ONLY
395
        //        natTable.addConfiguration(new DebugMenuConfiguration(natTable));
396

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

    
401

    
402
        // add the header menu configuration for adding the column header menu
403
        // with hide/show actions
404
        natTable.addConfiguration(new AbstractHeaderMenuConfiguration(natTable) {
405

    
406
            @Override
407
            protected PopupMenuBuilder createColumnHeaderMenu(NatTable natTable) {
408
                return super.createColumnHeaderMenu(natTable)
409
                        .withHideColumnMenuItem()
410
                        .withShowAllColumnsMenuItem();
411
            }
412

    
413
            @Override
414
            protected PopupMenuBuilder createRowHeaderMenu(NatTable natTable) {
415
                return super.createRowHeaderMenu(natTable)
416
                        .withHideRowMenuItem()
417
                        .withShowAllRowsMenuItem();
418
            }
419

    
420
            @Override
421
            protected PopupMenuBuilder createCornerMenu(NatTable natTable) {
422
                return super.createCornerMenu(natTable)
423
                        .withShowAllColumnsMenuItem()
424
                        .withShowAllRowsMenuItem();
425
            }
426
        });
427

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

    
456
        });
457

    
458
        //register aggregation configuration for each feature
459
        features.forEach(feature->summaryRowLayer.addConfiguration(new AggregationConfiguration(bodyDataProvider, feature)));
460

    
461
        // add the ExportCommandHandler to the ViewportLayer in order to make
462
        // exporting work
463
        viewportLayer.registerCommandHandler(new ExportCommandHandler(viewportLayer));
464

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

    
485
        natTable.configure();
486

    
487
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
488

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

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

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

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

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

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

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

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

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

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

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

    
689
    }
690

    
691
    private void initLabels(final ColumnOverrideLabelAccumulator columnLabelAccumulator,
692
            int index, Feature feature) {
693

    
694
        columnLabelAccumulator.registerColumnOverrides(index+LEADING_COLUMN_COUNT, MatrixUtility.getProperty(feature));
695
        indexToFeatureMap.put(index+LEADING_COLUMN_COUNT, feature);
696

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

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

    
743
            //add combo box cell editor
744
            CategoricalDataCellEditor comboBoxCellEditor = new CategoricalDataCellEditor(new IComboBoxDataProvider() {
745

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

    
765
        }
766

    
767
    }
768

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

    
780
    public Map<Integer, Feature> getIndexToFeatureMap() {
781
        return indexToFeatureMap;
782
    }
783

    
784
    public LinkedMap<String, String> getPropertyToLabelMap() {
785
        return propertyToLabelMap;
786
    }
787

    
788
    public void setDirty() {
789
        this.dirty.setDirty(true);
790
    }
791

    
792
    public NatTable getNatTable() {
793
        return natTable;
794
    }
795

    
796
    public WorkingSet getWorkingSet() {
797
        return workingSet;
798
    }
799

    
800
    public Collection<SpecimenOrObservationBase> getSpecimenCache() {
801
        return specimenCache;
802
    }
803

    
804
    public void setSpecimenCache(Collection<SpecimenOrObservationBase> specimenCache) {
805
        this.specimenCache = specimenCache;
806
    }
807

    
808
    /**
809
     * @return the bodyDataProvider
810
     */
811
    public ListDataProvider<Object> getBodyDataProvider() {
812
        return bodyDataProvider;
813
    }
814

    
815
    @Persist
816
    @Override
817
    public void save(IProgressMonitor monitor) {
818
        CdmStore.getService(IWorkingSetService.class).merge(workingSet, true);
819
        conversation.commit();
820
        dirty.setDirty(false);
821
    }
822

    
823
    @Focus
824
    public void setFocus(){
825
        if(conversation!=null){
826
            conversation.bind();
827
        }
828
        if(cdmEntitySession != null) {
829
            cdmEntitySession.bind();
830
        }
831
    }
832

    
833
    @PreDestroy
834
    public void dispose(){
835
        if (conversation != null) {
836
            conversation.close();
837
            conversation = null;
838
        }
839
        if(cdmEntitySession != null) {
840
            cdmEntitySession.dispose();
841
            cdmEntitySession = null;
842
        }
843
        dirty.setDirty(false);
844
        if(natTableState!=null){
845
            try (FileOutputStream tableStateStream =
846
                    new FileOutputStream(getStatePropertiesFile())) {
847
                natTableState.store(tableStateStream, null);
848
            } catch (IOException ioe) {
849
                ioe.printStackTrace();
850
            }
851
        }
852
    }
853

    
854
    private File getStatePropertiesFile() {
855
        return new File(WorkbenchUtility.getBaseLocation(), CHARACTER_MATRIX_STATE_PROPERTIES);
856
    }
857

    
858
    /**
859
     * {@inheritDoc}
860
     */
861
    @Override
862
    public void update(CdmDataChangeMap arg0) {
863
    }
864

    
865
    /**
866
     * {@inheritDoc}
867
     */
868
    @Override
869
    public ConversationHolder getConversationHolder() {
870
        return conversation;
871
    }
872

    
873
    /**
874
     * {@inheritDoc}
875
     */
876
    @Override
877
    public void changed(Object element) {
878
        setDirty();
879
        natTable.refresh();
880
    }
881

    
882
    /**
883
     * {@inheritDoc}
884
     */
885
    @Override
886
    public void forceDirty() {
887
        setDirty();
888
    }
889

    
890

    
891
    /**
892
     * {@inheritDoc}
893
     */
894
    @Override
895
    public ICdmEntitySession getCdmEntitySession() {
896
        return cdmEntitySession;
897
    }
898

    
899

    
900
    /**
901
     * {@inheritDoc}
902
     */
903
    @Override
904
    public Collection<WorkingSet> getRootEntities() {
905
        return Collections.singleton(this.workingSet);
906
    }
907

    
908

    
909
    /**
910
     * {@inheritDoc}
911
     */
912
    @Override
913
    public Map<Object, List<String>> getPropertyPathsMap() {
914
        Map<Object, List<String>> propertyMap = new HashMap<>();
915
        propertyMap.put(SpecimenOrObservationBase.class,WS_PROPERTY_PATH);
916
        return propertyMap;
917
    }
918

    
919
}
(2-2/10)