Project

General

Profile

Download (36.8 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.grid.GridRegion;
60
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
61
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
62
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
63
import org.eclipse.nebula.widgets.nattable.grid.data.FixedSummaryRowHeaderLayer;
64
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
65
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
66
import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultRowHeaderDataLayer;
67
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
68
import org.eclipse.nebula.widgets.nattable.hideshow.ColumnHideShowLayer;
69
import org.eclipse.nebula.widgets.nattable.hideshow.RowHideShowLayer;
70
import org.eclipse.nebula.widgets.nattable.layer.CompositeLayer;
71
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
72
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
73
import org.eclipse.nebula.widgets.nattable.layer.ILayerListener;
74
import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator;
75
import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell;
76
import org.eclipse.nebula.widgets.nattable.layer.event.ILayerEvent;
77
import org.eclipse.nebula.widgets.nattable.persistence.PersistenceHelper;
78
import org.eclipse.nebula.widgets.nattable.persistence.command.DisplayPersistenceDialogCommand;
79
import org.eclipse.nebula.widgets.nattable.persistence.command.DisplayPersistenceDialogCommandHandler;
80
import org.eclipse.nebula.widgets.nattable.persistence.command.IStateChangedListener;
81
import org.eclipse.nebula.widgets.nattable.persistence.command.StateChangeEvent;
82
import org.eclipse.nebula.widgets.nattable.persistence.gui.PersistenceDialog;
83
import org.eclipse.nebula.widgets.nattable.reorder.ColumnReorderLayer;
84
import org.eclipse.nebula.widgets.nattable.reorder.RowReorderLayer;
85
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
86
import org.eclipse.nebula.widgets.nattable.selection.event.CellSelectionEvent;
87
import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer;
88
import org.eclipse.nebula.widgets.nattable.sort.config.SingleClickSortConfiguration;
89
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
90
import org.eclipse.nebula.widgets.nattable.summaryrow.FixedSummaryRowLayer;
91
import org.eclipse.nebula.widgets.nattable.summaryrow.SummaryRowLayer;
92
import org.eclipse.nebula.widgets.nattable.ui.menu.AbstractHeaderMenuConfiguration;
93
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuBuilder;
94
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
95
import org.eclipse.swt.SWT;
96
import org.eclipse.swt.events.SelectionAdapter;
97
import org.eclipse.swt.events.SelectionEvent;
98
import org.eclipse.swt.layout.GridData;
99
import org.eclipse.swt.layout.GridLayout;
100
import org.eclipse.swt.widgets.Button;
101
import org.eclipse.swt.widgets.Composite;
102
import org.eclipse.swt.widgets.Label;
103

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

    
137
/**
138
 * @author pplitzner
139
 * @since Nov 26, 2017
140
 *
141
 */
142
public class CharacterMatrix implements IE4SavablePart, IPartContentHasDetails, IConversationEnabled, IDirtyMarkable,
143
ICdmEntitySessionEnabled{
144

    
145
    private static final List<String> WS_PROPERTY_PATH = Arrays.asList(new String[] {
146
            "descriptions", //$NON-NLS-1$
147
            "descriptions.descriptionElements", //$NON-NLS-1$
148
            "descriptions.descriptionElements.inDescription", //$NON-NLS-1$
149
            "descriptions.descriptionElements.inDescription.descriptionElements", //$NON-NLS-1$
150
            "descriptions.descriptionElements.feature", //$NON-NLS-1$
151
    });
152

    
153
    private static final String CHARACTER_MATRIX_STATE_PROPERTIES = "characterMatrixState.properties";
154

    
155
    private static final int LEADING_COLUMN_COUNT = 4;
156
    private static final String TAXON_COLUMN = "taxon_column";
157
    private static final String COLLECTOR_COLUMN = "collector_column";
158
    private static final String IDENTIFIER_COLUMN = "identifier_column";
159
    private static final String COUNTRY_COLUMN = "country_column";
160

    
161
    private WorkingSet workingSet;
162

    
163
    private Composite parent;
164

    
165
    private ConversationHolder conversation;
166

    
167
    private ICdmEntitySession cdmEntitySession;
168

    
169
    @Inject
170
    private ESelectionService selService;
171

    
172
    @Inject
173
    private MDirtyable dirty;
174

    
175
    @Inject
176
    private MPart thisPart;
177

    
178
    private NatTable natTable;
179

    
180
    private Map<Integer, Feature> indexToFeatureMap = new HashMap<>();
181

    
182
    private LinkedMap<String, String> propertyToLabelMap = new LinkedMap<>();
183

    
184
    private Properties natTableState;
185

    
186
    private EventList<RowWrapper> descriptions;
187

    
188
    private Collection<SpecimenOrObservationBase> specimenCache = null;
189

    
190
    @PostConstruct
191
    public void create(Composite parent) {
192
        if(CdmStore.isActive() && conversation==null){
193
            conversation = CdmStore.createConversation();
194
        }
195
        if(cdmEntitySession == null){
196
            cdmEntitySession = CdmStore.getCurrentSessionManager().newSession(this, true);
197
        }
198
        else{
199
            return;
200
        }
201
        parent.setLayout(new GridLayout());
202
        this.parent = parent;
203
    }
204

    
205

    
206
    public void init(UUID workingSetUuid) {
207
        this.workingSet = CdmStore.getService(IWorkingSetService.class).load(workingSetUuid, WS_PROPERTY_PATH);
208
        thisPart.setLabel(workingSet.getLabel());
209

    
210
        Composite toolbarComposite = new Composite(parent, SWT.NONE);
211
        toolbarComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
212
        toolbarComposite.setLayout(new GridLayout(4, false));
213

    
214
        //get features/columns stored in working set
215
        FeatureTree tree = workingSet.getDescriptiveSystem();
216
        List<Feature> features = new ArrayList<>(tree.getDistinctFeatures());
217
        Collections.sort(features);
218

    
219
        descriptions = GlazedLists.eventList(getDescriptions(workingSet));
220
        SortedList<RowWrapper> sortedList = new SortedList<>(descriptions, null);
221

    
222
        ConfigRegistry configRegistry = new ConfigRegistry();
223

    
224
        /**
225
         * data provider
226
         */
227
        SpecimenColumnPropertyAccessor columnPropertyAccessor = new SpecimenColumnPropertyAccessor(this);
228
        IDataProvider bodyDataProvider = new ListDataProvider<RowWrapper>(sortedList, columnPropertyAccessor);
229

    
230
        /**
231
         * BODY layer
232
         *
233
         *
234

    
235
        CompositeLayer
236
         - (top) SummaryRowLayer
237
         - (bottom) ViewportLayer
238

    
239
             ^
240
        ViewportLayer
241

    
242
             ^
243
        SelectionLayer
244

    
245
             ^
246
        RowHideShowLayer
247

    
248
             ^
249
        ColumnHideShowLayer
250

    
251
             ^
252
        ColumnReorderLayer
253

    
254
             ^
255
        RowReorderLayer
256

    
257
             ^
258
        DataLayer
259

    
260
         *
261

    
262
         */
263
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
264

    
265
        //register labels for columns
266
        ColumnOverrideLabelAccumulator bodyColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
267
        bodyDataLayer.setConfigLabelAccumulator(bodyColumnLabelAccumulator);
268
        propertyToLabelMap.put(TAXON_COLUMN, "Taxon");
269
        bodyColumnLabelAccumulator.registerColumnOverrides(0, TAXON_COLUMN);
270
        propertyToLabelMap.put(COLLECTOR_COLUMN, "Collector + No");
271
        bodyColumnLabelAccumulator.registerColumnOverrides(1, COLLECTOR_COLUMN);
272
        propertyToLabelMap.put(IDENTIFIER_COLUMN, "Identifier");
273
        bodyColumnLabelAccumulator.registerColumnOverrides(2, IDENTIFIER_COLUMN);
274
        propertyToLabelMap.put(COUNTRY_COLUMN, "Country");
275
        bodyColumnLabelAccumulator.registerColumnOverrides(3, COUNTRY_COLUMN);
276
        for(int i=0;i<features.size();i++){
277
            Feature feature = features.get(i);
278
            initLabels(bodyColumnLabelAccumulator, i, feature);
279
        }
280

    
281
        GlazedListsEventLayer<RowWrapper> eventLayer = new GlazedListsEventLayer<>(bodyDataLayer, sortedList);
282

    
283
        RowReorderLayer rowReorderLayer = new RowReorderLayer(eventLayer);
284
        ColumnReorderLayer columnReorderLayer = new ColumnReorderLayer(rowReorderLayer);
285
        ColumnHideShowLayer columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
286
        RowHideShowLayer rowHideShowLayer = new RowHideShowLayer(columnHideShowLayer);
287
        SelectionLayer selectionLayer = new SelectionLayer(rowHideShowLayer);
288
        ViewportLayer viewportLayer = new ViewportLayer(selectionLayer);
289

    
290

    
291
        // create a standalone FixedSummaryRowLayer
292
        // since the summary row should be fixed at the top of the body
293
        // region the horizontal dependency of the FixedSummaryRowLayer
294
        // is the ViewportLayer
295
        FixedSummaryRowLayer summaryRowLayer =
296
                new FixedSummaryRowLayer(bodyDataLayer, viewportLayer, configRegistry, false);
297
        //regoster labels with summary prefix for summary layer
298
        ColumnOverrideLabelAccumulator summaryColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
299
        summaryRowLayer.setConfigLabelAccumulator(summaryColumnLabelAccumulator);
300
        for(int i=0;i<features.size();i++){
301
            Feature feature = features.get(i);
302
            summaryColumnLabelAccumulator.registerColumnOverrides(
303
                    i+LEADING_COLUMN_COUNT,
304
                    SummaryRowLayer.DEFAULT_SUMMARY_COLUMN_CONFIG_LABEL_PREFIX+MatrixUtility.getProperty(feature));
305
        }
306
        // because the horizontal dependency is the ViewportLayer
307
        // we need to set the composite dependency to false
308
        summaryRowLayer.setHorizontalCompositeDependency(false);
309

    
310
        CompositeLayer composite = new CompositeLayer(1, 2);
311
        composite.setChildLayer("SUMMARY", summaryRowLayer, 0, 0);
312
        composite.setChildLayer(GridRegion.BODY, viewportLayer, 0, 1);
313

    
314

    
315

    
316

    
317
        /**
318
         * column header layer
319
         */
320
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
321
                propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
322
        DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
323
        ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, viewportLayer, selectionLayer);
324

    
325
        // add the SortHeaderLayer to the column header layer stack
326
        // as we use GlazedLists, we use the GlazedListsSortModel which
327
        // delegates the sorting to the SortedList
328
        final SortHeaderLayer<SpecimenDescription> sortHeaderLayer = new SortHeaderLayer<>(
329
                columnHeaderLayer,
330
                new GlazedListsSortModel<>(
331
                        sortedList,
332
                        columnPropertyAccessor,
333
                        configRegistry,
334
                        columnHeaderDataLayer));
335

    
336

    
337
        /**
338
         * row header layer
339
         */
340
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
341
        DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
342
        FixedSummaryRowHeaderLayer fixedSummaryRowHeaderLayer = new FixedSummaryRowHeaderLayer(rowHeaderDataLayer,
343
                composite, selectionLayer);
344
        fixedSummaryRowHeaderLayer.setSummaryRowLabel("\u2211");
345

    
346

    
347
        /**
348
         * corner layer
349
         */
350
        ILayer cornerLayer = new CornerLayer(
351
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
352
                fixedSummaryRowHeaderLayer, sortHeaderLayer);
353

    
354

    
355
        /**
356
         * GRID layer (composition of all other layers)
357
         */
358
        GridLayer gridLayer = new GridLayer(composite, sortHeaderLayer, fixedSummaryRowHeaderLayer, cornerLayer);
359

    
360

    
361

    
362
        natTable = new NatTable(parent, gridLayer, false);
363

    
364

    
365
        /**
366
         * CONFIGURATION
367
         */
368
        natTable.setConfigRegistry(configRegistry);
369

    
370

    
371
        //add default configuration because autoconfigure is set to false in constructor
372
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
373

    
374
        //FIXME: this is for DEBUG ONLY
375
        //        natTable.addConfiguration(new DebugMenuConfiguration(natTable));
376

    
377
        // override the default sort configuration and change the mouse bindings
378
        // to sort on a single click
379
        natTable.addConfiguration(new SingleClickSortConfiguration());
380

    
381

    
382
        // add the header menu configuration for adding the column header menu
383
        // with hide/show actions
384
        natTable.addConfiguration(new AbstractHeaderMenuConfiguration(natTable) {
385

    
386
            @Override
387
            protected PopupMenuBuilder createColumnHeaderMenu(NatTable natTable) {
388
                return super.createColumnHeaderMenu(natTable)
389
                        .withHideColumnMenuItem()
390
                        .withShowAllColumnsMenuItem();
391
            }
392

    
393
            @Override
394
            protected PopupMenuBuilder createRowHeaderMenu(NatTable natTable) {
395
                return super.createRowHeaderMenu(natTable)
396
                        .withHideRowMenuItem()
397
                        .withShowAllRowsMenuItem();
398
            }
399

    
400
            @Override
401
            protected PopupMenuBuilder createCornerMenu(NatTable natTable) {
402
                return super.createCornerMenu(natTable)
403
                        .withShowAllColumnsMenuItem()
404
                        .withShowAllRowsMenuItem();
405
            }
406
        });
407

    
408
        // add custom configuration for data conversion and add column labels to viewport layer
409
        viewportLayer.addConfiguration(new AbstractRegistryConfiguration() {
410
            @Override
411
            public void configureRegistry(IConfigRegistry configRegistry) {
412
                //add display converter for string representation
413
                configRegistry.registerConfigAttribute(
414
                        CellConfigAttributes.DISPLAY_CONVERTER,
415
                        new SupplementalInfoDisplayConverter(),
416
                        DisplayMode.NORMAL,
417
                        TAXON_COLUMN);
418
                configRegistry.registerConfigAttribute(
419
                        CellConfigAttributes.DISPLAY_CONVERTER,
420
                        new SupplementalInfoDisplayConverter(),
421
                        DisplayMode.NORMAL,
422
                        COLLECTOR_COLUMN);
423
                configRegistry.registerConfigAttribute(
424
                        CellConfigAttributes.DISPLAY_CONVERTER,
425
                        new SupplementalInfoDisplayConverter(),
426
                        DisplayMode.NORMAL,
427
                        IDENTIFIER_COLUMN);
428
                configRegistry.registerConfigAttribute(
429
                        CellConfigAttributes.DISPLAY_CONVERTER,
430
                        new SupplementalInfoDisplayConverter(),
431
                        DisplayMode.NORMAL,
432
                        COUNTRY_COLUMN);
433
                features.forEach(feature->registerColumnConfiguration(feature, configRegistry));
434
            }
435

    
436
        });
437

    
438
        //register aggregation configuration for each feature
439
        features.forEach(feature->summaryRowLayer.addConfiguration(new AggregationConfiguration(bodyDataProvider, feature)));
440

    
441
        // add the ExportCommandHandler to the ViewportLayer in order to make
442
        // exporting work
443
        viewportLayer.registerCommandHandler(new ExportCommandHandler(viewportLayer));
444

    
445
        //propagate single cell selection
446
        natTable.addLayerListener(new ILayerListener() {
447
            @Override
448
            public void handleLayerEvent(ILayerEvent event) {
449
                if(event instanceof CellSelectionEvent){
450
                    CellSelectionEvent cellSelectionEvent = (CellSelectionEvent)event;
451
                    Collection<ILayerCell> selectedCells = cellSelectionEvent.getSelectionLayer().getSelectedCells();
452
                    StructuredSelection selection = new StructuredSelection();
453
                    if(selectedCells.size()==1){
454
                        ILayerCell cell = selectedCells.iterator().next();
455
                        Object dataValue = cell.getDataValue();
456
                        if(dataValue!=null){
457
                            selection = new StructuredSelection(dataValue);
458
                        }
459
                    }
460
                    selService.setSelection(selection);
461
                }
462
            }
463
        });
464

    
465
        natTable.configure();
466

    
467
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
468

    
469
        /**
470
         * Info label
471
         */
472
        Label wsLabel = new Label(toolbarComposite, SWT.NONE);
473
        wsLabel.setText(workingSet.getLabel());
474
        wsLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
475

    
476
        /**
477
         * Table state persistence
478
         */
479
        natTableState = new Properties();
480
        //load persisted state
481
        File statePropertiesFile = getStatePropertiesFile();
482
        FileInputStream inputStream;
483
        try {
484
            inputStream = new FileInputStream(statePropertiesFile);
485
            natTableState.load(inputStream);
486
        } catch (IOException e) {
487
            MessagingUtils.info("No initial state properties file found for character matrix");
488
        }
489

    
490
        DisplayPersistenceDialogCommandHandler handler =
491
                new DisplayPersistenceDialogCommandHandler(natTableState, natTable);
492
        gridLayer.registerCommandHandler(handler);
493
        // create a combobox for showing the available view states
494
        ComboViewer comboStates= new ComboViewer(toolbarComposite, SWT.DROP_DOWN) ;
495
        Collection<String> availableStates = PersistenceHelper.getAvailableStates(natTableState);
496
        comboStates.setLabelProvider(new LabelProvider(){
497
            @Override
498
            public String getText(Object element) {
499
                if(element instanceof String && ((String) element).isEmpty()){
500
                    return "-default-";
501
                }
502
                return super.getText(element);
503
            }
504
        });
505
        comboStates.setContentProvider(new ArrayContentProvider());
506
        comboStates.addSelectionChangedListener(e->
507
        {
508
            int index = comboStates.getCombo().getSelectionIndex();
509
            if (index >= 0) {
510
                String selected = comboStates.getCombo().getItem(index);
511
                // load the state
512
                natTable.loadState(selected, natTableState);
513
                natTableState.setProperty(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY, selected);
514
            }
515
        });
516
        comboStates.setInput(availableStates);
517
        if(comboStates.getCombo().getItemCount()>0){
518
            comboStates.getCombo().select(0);
519
        }
520

    
521
        // add listener to update the combo on view state management changes
522
        handler.addStateChangeListener(new IStateChangedListener() {
523
            @Override
524
            public void handleStateChange(StateChangeEvent event) {
525
                comboStates.setInput(PersistenceHelper.getAvailableStates(natTableState));
526
                selectStateItem(comboStates, event.getViewConfigName());
527
            }
528
        });
529

    
530
        // add button to show dialog
531
        Button btnManageState = new Button(toolbarComposite, SWT.PUSH);
532
        btnManageState.setImage(ImageResources.getImage(ImageResources.SETTINGS));
533
        btnManageState.addSelectionListener(new SelectionAdapter() {
534
            @Override
535
            public void widgetSelected(SelectionEvent e) {
536
                natTable.doCommand(new DisplayPersistenceDialogCommand(natTable));
537
                selectStateItem(comboStates, natTableState.get(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY).toString());
538
            }
539
        });
540

    
541
        /**
542
         * excel export
543
         */
544
        Button btnExcelExport = new Button(toolbarComposite, SWT.PUSH);
545
        btnExcelExport.setToolTipText("Export to Excel");
546
        btnExcelExport.setImage(ImageResources.getImage(ImageResources.EXPORT));
547
        btnExcelExport.addSelectionListener(new SelectionAdapter() {
548
            @Override
549
            public void widgetSelected(SelectionEvent e) {
550
                natTable.doCommand(
551
                        new ExportCommand(
552
                                natTable.getConfigRegistry(),
553
                                natTable.getShell()));
554
            }
555
        });
556

    
557
        /**
558
         * Add description button
559
         */
560
        Button btnAddDescription = new Button(parent, SWT.PUSH);
561
        btnAddDescription.setImage(ImageResources.getImage(ImageResources.ADD_ICON));
562
        btnAddDescription.addSelectionListener(new SelectionAdapter() {
563
            @Override
564
            public void widgetSelected(SelectionEvent e) {
565
                SpecimenSelectionDialog dialog = new SpecimenSelectionDialog(natTable.getShell(), CharacterMatrix.this);
566
                if(dialog.open()==Window.OK){
567
                    Collection<SpecimenOrObservationBase> specimens = dialog.getSpecimen();
568
                    boolean hasAdded = false;
569
                    for (SpecimenOrObservationBase specimen : specimens) {
570
                        SpecimenDescription description = getDescriptionForWorkingSet(specimen);
571
                        if(!workingSet.getDescriptions().contains(description)){
572
                            CharacterMatrix.this.descriptions.add(new RowWrapper(description));
573
                            workingSet.addDescription(description);
574
                            hasAdded = true;
575
                        }
576
                    }
577
                    if(hasAdded){
578
                        setDirty();
579
                    }
580
                }
581
            }
582
        });
583
        parent.layout();
584
    }
585

    
586
    private void selectStateItem(ComboViewer comboStates, String stateName){
587
        String[] items = comboStates.getCombo().getItems();
588
        for(int i=0;i<items.length;i++){
589
            if(items[i].equals(stateName)){
590
                comboStates.getCombo().select(i);
591
                break;
592
            }
593
        }
594
    }
595

    
596
    private SpecimenDescription getDescriptionForWorkingSet(SpecimenOrObservationBase specimen){
597
        Set<Feature> wsFeatures = workingSet.getDescriptiveSystem().getDistinctFeatures();
598
        List<DescriptionElementBase> matchingDescriptionElements = new ArrayList<>();
599

    
600
        for (SpecimenDescription specimenDescription : (Set<SpecimenDescription>) specimen.getDescriptions()) {
601
            Set<Feature> specimenDescriptionFeatures = new HashSet<>();
602
            //gather specimen description features and check for match with WS features
603
            for (DescriptionElementBase specimenDescriptionElement : specimenDescription.getElements()) {
604
                Feature feature = specimenDescriptionElement.getFeature();
605
                specimenDescriptionFeatures.add(feature);
606
                if(wsFeatures.contains(feature)){
607
                    matchingDescriptionElements.add(specimenDescriptionElement);
608
                }
609
            }
610
            //if description with the exact same features is found return the description
611
            if(specimenDescriptionFeatures.equals(wsFeatures)){
612
                return specimenDescription;
613
            }
614
        }
615
        //Create new specimen description if no match was found
616
        setDirty();
617
        SpecimenDescription newDesription = SpecimenDescription.NewInstance(specimen);
618
        newDesription.setTitleCache("WorkingSet "+workingSet.getLabel()+": "+newDesription.generateTitle(), true);
619

    
620
        //check for equals description element (same feature and same values)
621
        Map<Feature, List<DescriptionElementBase>> featureToElementMap = new HashMap<>();
622
        for(DescriptionElementBase element:matchingDescriptionElements){
623
            List<DescriptionElementBase> list = featureToElementMap.get(element.getFeature());
624
            if(list==null){
625
                list = new ArrayList<>();
626
            }
627
            list.add(element);
628
            featureToElementMap.put(element.getFeature(), list);
629
        }
630
        Set<DescriptionElementBase> descriptionElementsToClone = new HashSet<>();
631
        for(Feature feature:featureToElementMap.keySet()){
632
            List<DescriptionElementBase> elements = featureToElementMap.get(feature);
633
            //no duplicate description elements found for this feature
634
            if(elements.size()==1){
635
                descriptionElementsToClone.add(elements.get(0));
636
            }
637
            //duplicates found -> check if all are equal
638
            else{
639
                DescriptionElementBase match = null;
640
                for (DescriptionElementBase descriptionElementBase : elements) {
641
                    if(match==null){
642
                        match = descriptionElementBase;
643
                    }
644
                    else if(!new DescriptionElementCompareWrapper(match).equals(new DescriptionElementCompareWrapper(descriptionElementBase))){
645
                        match = null;
646
                        MessagingUtils.informationDialog("Multiple data found",
647
                                String.format("Multiple description elements with different values "
648
                                        + "found for feature '%s'.\nData will not be copied to new specimen description.", feature.getLabel()));
649
                        break;
650
                    }
651
                }
652
                if(match!=null){
653
                    descriptionElementsToClone.add(match);
654
                }
655
            }
656
        }
657
        //clone matching descriptionElements
658
        for (DescriptionElementBase descriptionElementBase : descriptionElementsToClone) {
659
            DescriptionElementBase clone;
660
            try {
661
                clone = descriptionElementBase.clone(newDesription);
662
                clone.getSources().forEach(source -> source.setOriginalNameString(DescriptionHelper.getLabel(descriptionElementBase)));
663
            } catch (CloneNotSupportedException e) {
664
                MessagingUtils.error(CharacterMatrix.class, e);
665
            }
666
        }
667
        return newDesription;
668

    
669
    }
670

    
671
    private void initLabels(final ColumnOverrideLabelAccumulator columnLabelAccumulator,
672
            int index, Feature feature) {
673

    
674
        columnLabelAccumulator.registerColumnOverrides(index+LEADING_COLUMN_COUNT, MatrixUtility.getProperty(feature));
675
        indexToFeatureMap.put(index+LEADING_COLUMN_COUNT, feature);
676

    
677
        String featureLabel = feature.getLabel();
678
        String property = featureLabel;
679
        //show unit for quantitative data
680
        if(feature.isSupportsQuantitativeData()){
681
            Set<MeasurementUnit> recommendedMeasurementUnits = feature.getRecommendedMeasurementUnits();
682
            if(recommendedMeasurementUnits.size()!=1){
683
                MessagingUtils.warningDialog("Column initialization problem", CharacterMatrix.class,
684
                        String.format("Only one unit is allowed for quantitative data: %s", feature.getLabel()));
685
                return;
686
            }
687
            MeasurementUnit unit = recommendedMeasurementUnits.iterator().next();
688
            featureLabel += " ["+unit.getLabel()+"]";
689
        }
690
        propertyToLabelMap.put(property, featureLabel);
691
    }
692

    
693
    private void registerColumnConfiguration(Feature feature, IConfigRegistry configRegistry) {
694
        //make cell editable
695
        configRegistry.registerConfigAttribute(
696
                EditConfigAttributes.CELL_EDITABLE_RULE,
697
                IEditableRule.ALWAYS_EDITABLE,
698
                DisplayMode.EDIT,
699
                MatrixUtility.getProperty(feature)
700
                );
701
        if(feature.isSupportsQuantitativeData()){
702
            //add display converter for string representation
703
            configRegistry.registerConfigAttribute(
704
                    CellConfigAttributes.DISPLAY_CONVERTER,
705
                    new QuantitativeDataDisplayConverter(),
706
                    DisplayMode.NORMAL,
707
                    MatrixUtility.getProperty(feature));
708
            //register quantitative editor
709
            configRegistry.registerConfigAttribute(
710
                    EditConfigAttributes.CELL_EDITOR,
711
                    new QuantitativeDataCellEditor(feature.getRecommendedStatisticalMeasures(), this),
712
                    DisplayMode.EDIT,
713
                    MatrixUtility.getProperty(feature));
714
        }
715
        else if(feature.isSupportsCategoricalData()){
716
            //add display converter for string representation
717
            configRegistry.registerConfigAttribute(
718
                    CellConfigAttributes.DISPLAY_CONVERTER,
719
                    new CategoricalDataDisplayConverter(),
720
                    DisplayMode.NORMAL,
721
                    MatrixUtility.getProperty(feature));
722

    
723
            //add combo box cell editor
724
            CategoricalDataCellEditor comboBoxCellEditor = new CategoricalDataCellEditor(new IComboBoxDataProvider() {
725

    
726
                @Override
727
                public List<?> getValues(int columnIndex, int rowIndex) {
728
                    List<State> states = new ArrayList<>();
729
                    Feature feature = indexToFeatureMap.get(columnIndex);
730
                    if(feature.isSupportsCategoricalData()){
731
                        Set<TermVocabulary<State>> stateVocs = feature.getSupportedCategoricalEnumerations();
732
                        for (TermVocabulary<State> voc : stateVocs) {
733
                            states.addAll(voc.getTerms());
734
                        }
735
                    }
736
                    return states;
737
                }
738
            }, 5, this);
739
            //register editor
740
            configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR,
741
                    comboBoxCellEditor,
742
                    DisplayMode.EDIT,
743
                    MatrixUtility.getProperty(feature));
744

    
745
        }
746

    
747
    }
748

    
749
    private List<RowWrapper> getDescriptions(WorkingSet workingSet) {
750
        List<RowWrapper> rowWrappers = new ArrayList<>();
751
        Set<DescriptionBase> wsDescriptions = workingSet.getDescriptions();
752
        for (DescriptionBase descriptionBase : wsDescriptions) {
753
            if(descriptionBase instanceof SpecimenDescription){
754
                rowWrappers.add(new RowWrapper((SpecimenDescription) descriptionBase));
755
            }
756
        }
757
        return rowWrappers;
758
    }
759

    
760
    public Map<Integer, Feature> getIndexToFeatureMap() {
761
        return indexToFeatureMap;
762
    }
763

    
764
    public LinkedMap<String, String> getPropertyToLabelMap() {
765
        return propertyToLabelMap;
766
    }
767

    
768
    public void setDirty() {
769
        this.dirty.setDirty(true);
770
    }
771

    
772
    public NatTable getNatTable() {
773
        return natTable;
774
    }
775

    
776
    public WorkingSet getWorkingSet() {
777
        return workingSet;
778
    }
779

    
780
    public Collection<SpecimenOrObservationBase> getSpecimenCache() {
781
        return specimenCache;
782
    }
783

    
784
    public void setSpecimenCache(Collection<SpecimenOrObservationBase> specimenCache) {
785
        this.specimenCache = specimenCache;
786
    }
787

    
788
    @Persist
789
    @Override
790
    public void save(IProgressMonitor monitor) {
791
        CdmStore.getService(IWorkingSetService.class).merge(workingSet, true);
792
        conversation.commit();
793
        dirty.setDirty(false);
794
    }
795

    
796
    @Focus
797
    public void setFocus(){
798
        if(conversation!=null){
799
            conversation.bind();
800
        }
801
        if(cdmEntitySession != null) {
802
            cdmEntitySession.bind();
803
        }
804
    }
805

    
806
    @PreDestroy
807
    public void dispose(){
808
        if (conversation != null) {
809
            conversation.close();
810
            conversation = null;
811
        }
812
        if(cdmEntitySession != null) {
813
            cdmEntitySession.dispose();
814
            cdmEntitySession = null;
815
        }
816
        dirty.setDirty(false);
817
        if(natTableState!=null){
818
            try (FileOutputStream tableStateStream =
819
                    new FileOutputStream(getStatePropertiesFile())) {
820
                natTableState.store(tableStateStream, null);
821
            } catch (IOException ioe) {
822
                ioe.printStackTrace();
823
            }
824
        }
825
    }
826

    
827
    private File getStatePropertiesFile() {
828
        return new File(WorkbenchUtility.getBaseLocation(), CHARACTER_MATRIX_STATE_PROPERTIES);
829
    }
830

    
831
    /**
832
     * {@inheritDoc}
833
     */
834
    @Override
835
    public void update(CdmDataChangeMap arg0) {
836
    }
837

    
838
    /**
839
     * {@inheritDoc}
840
     */
841
    @Override
842
    public ConversationHolder getConversationHolder() {
843
        return conversation;
844
    }
845

    
846
    /**
847
     * {@inheritDoc}
848
     */
849
    @Override
850
    public void changed(Object element) {
851
        setDirty();
852
        natTable.refresh();
853
    }
854

    
855
    /**
856
     * {@inheritDoc}
857
     */
858
    @Override
859
    public void forceDirty() {
860
        setDirty();
861
    }
862

    
863

    
864
    /**
865
     * {@inheritDoc}
866
     */
867
    @Override
868
    public ICdmEntitySession getCdmEntitySession() {
869
        return cdmEntitySession;
870
    }
871

    
872

    
873
    /**
874
     * {@inheritDoc}
875
     */
876
    @Override
877
    public Collection<WorkingSet> getRootEntities() {
878
        return Collections.singleton(this.workingSet);
879
    }
880

    
881

    
882
    /**
883
     * {@inheritDoc}
884
     */
885
    @Override
886
    public Map<Object, List<String>> getPropertyPathsMap() {
887
        Map<Object, List<String>> propertyMap = new HashMap<>();
888
        propertyMap.put(SpecimenOrObservationBase.class,WS_PROPERTY_PATH);
889
        return propertyMap;
890
    }
891

    
892
}
(2-2/9)