Project

General

Profile

Download (32.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.StructuredSelection;
40
import org.eclipse.jface.window.Window;
41
import org.eclipse.nebula.widgets.nattable.NatTable;
42
import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration;
43
import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes;
44
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
45
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
46
import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
47
import org.eclipse.nebula.widgets.nattable.config.IEditableRule;
48
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
49
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
50
import org.eclipse.nebula.widgets.nattable.edit.EditConfigAttributes;
51
import org.eclipse.nebula.widgets.nattable.edit.editor.IComboBoxDataProvider;
52
import org.eclipse.nebula.widgets.nattable.export.command.ExportCommand;
53
import org.eclipse.nebula.widgets.nattable.export.command.ExportCommandHandler;
54
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsEventLayer;
55
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsSortModel;
56
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
57
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
58
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
59
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
60
import org.eclipse.nebula.widgets.nattable.grid.data.FixedSummaryRowHeaderLayer;
61
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
62
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
63
import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultRowHeaderDataLayer;
64
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
65
import org.eclipse.nebula.widgets.nattable.hideshow.ColumnHideShowLayer;
66
import org.eclipse.nebula.widgets.nattable.hideshow.RowHideShowLayer;
67
import org.eclipse.nebula.widgets.nattable.layer.CompositeLayer;
68
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
69
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
70
import org.eclipse.nebula.widgets.nattable.layer.ILayerListener;
71
import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator;
72
import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell;
73
import org.eclipse.nebula.widgets.nattable.layer.event.ILayerEvent;
74
import org.eclipse.nebula.widgets.nattable.persistence.PersistenceHelper;
75
import org.eclipse.nebula.widgets.nattable.persistence.command.DisplayPersistenceDialogCommand;
76
import org.eclipse.nebula.widgets.nattable.persistence.command.DisplayPersistenceDialogCommandHandler;
77
import org.eclipse.nebula.widgets.nattable.persistence.command.IStateChangedListener;
78
import org.eclipse.nebula.widgets.nattable.persistence.command.StateChangeEvent;
79
import org.eclipse.nebula.widgets.nattable.persistence.gui.PersistenceDialog;
80
import org.eclipse.nebula.widgets.nattable.reorder.ColumnReorderLayer;
81
import org.eclipse.nebula.widgets.nattable.reorder.RowReorderLayer;
82
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
83
import org.eclipse.nebula.widgets.nattable.selection.event.CellSelectionEvent;
84
import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer;
85
import org.eclipse.nebula.widgets.nattable.sort.config.SingleClickSortConfiguration;
86
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
87
import org.eclipse.nebula.widgets.nattable.summaryrow.FixedSummaryRowLayer;
88
import org.eclipse.nebula.widgets.nattable.summaryrow.SummaryRowLayer;
89
import org.eclipse.nebula.widgets.nattable.ui.menu.AbstractHeaderMenuConfiguration;
90
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuBuilder;
91
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
92
import org.eclipse.swt.SWT;
93
import org.eclipse.swt.events.SelectionAdapter;
94
import org.eclipse.swt.events.SelectionEvent;
95
import org.eclipse.swt.layout.GridData;
96
import org.eclipse.swt.layout.GridLayout;
97
import org.eclipse.swt.widgets.Button;
98
import org.eclipse.swt.widgets.Combo;
99
import org.eclipse.swt.widgets.Composite;
100

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

    
133
/**
134
 * @author pplitzner
135
 * @since Nov 26, 2017
136
 *
137
 */
138
public class CharacterMatrix implements IE4SavablePart, IPartContentHasDetails, IConversationEnabled, IDirtyMarkable,
139
        ICdmEntitySessionEnabled{
140

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

    
149
    private static final String CHARACTER_MATRIX_STATE_PROPERTIES = "characterMatrixState.properties";
150

    
151
    private static final int LEADING_COLUMN_COUNT = 4;
152
    private static final String TAXON_COLUMN = "taxon_column";
153
    private static final String COLLECTOR_COLUMN = "collector_column";
154
    private static final String IDENTIFIER_COLUMN = "identifier_column";
155
    private static final String COUNTRY_COLUMN = "country_column";
156

    
157
    private WorkingSet workingSet;
158

    
159
    private Composite parent;
160

    
161
    private ConversationHolder conversation;
162

    
163
    private ICdmEntitySession cdmEntitySession;
164

    
165
    @Inject
166
    private ESelectionService selService;
167

    
168
    @Inject
169
    private MDirtyable dirty;
170

    
171
    @Inject
172
    private MPart thisPart;
173

    
174
    private NatTable natTable;
175

    
176
    private Map<Integer, Feature> indexToFeatureMap = new HashMap<>();
177

    
178
    private LinkedMap<String, String> propertyToLabelMap = new LinkedMap<>();
179

    
180
    private Properties natTableState;
181

    
182
    private EventList<RowWrapper> descriptions;
183

    
184
    @PostConstruct
185
    public void create(Composite parent) {
186
        if(CdmStore.isActive() && conversation==null){
187
            conversation = CdmStore.createConversation();
188
        }
189
        if(cdmEntitySession == null){
190
            cdmEntitySession = CdmStore.getCurrentSessionManager().newSession(this, true);
191
        }
192
        else{
193
            return;
194
        }
195
        parent.setLayout(new GridLayout());
196
        this.parent = parent;
197
    }
198

    
199

    
200
    public void init(UUID workingSetUuid) {
201
        this.workingSet = CdmStore.getService(IWorkingSetService.class).load(workingSetUuid, WS_PROPERTY_PATH);
202
        thisPart.setLabel(workingSet.getLabel());
203

    
204
        Composite toolbarComposite = new Composite(parent, SWT.NONE);
205
        toolbarComposite.setLayout(new GridLayout(3, false));
206
        toolbarComposite.setLayoutData(new GridData(SWT.TRAIL, SWT.CENTER, true, false));
207

    
208
        //get features/columns stored in working set
209
        FeatureTree tree = workingSet.getDescriptiveSystem();
210
        List<Feature> features = new ArrayList<>(tree.getDistinctFeatures());
211
        Collections.sort(features);
212

    
213
        descriptions = GlazedLists.eventList(getDescriptions(workingSet));
214
        SortedList<RowWrapper> sortedList = new SortedList<>(descriptions, null);
215

    
216
        ConfigRegistry configRegistry = new ConfigRegistry();
217

    
218
        /**
219
         * data provider
220
         */
221
        SpecimenColumnPropertyAccessor columnPropertyAccessor = new SpecimenColumnPropertyAccessor(this);
222
        IDataProvider bodyDataProvider = new ListDataProvider<RowWrapper>(sortedList, columnPropertyAccessor);
223

    
224
        /**
225
         * BODY layer
226
         *
227
         *
228

    
229
        CompositeLayer
230
         - (top) SummaryRowLayer
231
         - (bottom) ViewportLayer
232

    
233
             ^
234
        ViewportLayer
235

    
236
             ^
237
        SelectionLayer
238

    
239
             ^
240
        RowHideShowLayer
241

    
242
             ^
243
        ColumnHideShowLayer
244

    
245
             ^
246
        ColumnReorderLayer
247

    
248
             ^
249
        RowReorderLayer
250

    
251
             ^
252
        DataLayer
253

    
254
             *
255

    
256
         */
257
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
258

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

    
275
        GlazedListsEventLayer<RowWrapper> eventLayer = new GlazedListsEventLayer<>(bodyDataLayer, sortedList);
276

    
277
        RowReorderLayer rowReorderLayer = new RowReorderLayer(eventLayer);
278
        ColumnReorderLayer columnReorderLayer = new ColumnReorderLayer(rowReorderLayer);
279
        ColumnHideShowLayer columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
280
        RowHideShowLayer rowHideShowLayer = new RowHideShowLayer(columnHideShowLayer);
281
        SelectionLayer selectionLayer = new SelectionLayer(rowHideShowLayer);
282
        ViewportLayer viewportLayer = new ViewportLayer(selectionLayer);
283

    
284

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

    
304
        CompositeLayer composite = new CompositeLayer(1, 2);
305
        composite.setChildLayer("SUMMARY", summaryRowLayer, 0, 0);
306
        composite.setChildLayer(GridRegion.BODY, viewportLayer, 0, 1);
307

    
308

    
309

    
310

    
311
        /**
312
         * column header layer
313
         */
314
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
315
                propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
316
        DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
317
        ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, viewportLayer, selectionLayer);
318

    
319
        // add the SortHeaderLayer to the column header layer stack
320
        // as we use GlazedLists, we use the GlazedListsSortModel which
321
        // delegates the sorting to the SortedList
322
        final SortHeaderLayer<SpecimenDescription> sortHeaderLayer = new SortHeaderLayer<>(
323
                columnHeaderLayer,
324
                        new GlazedListsSortModel<>(
325
                                sortedList,
326
                                columnPropertyAccessor,
327
                                configRegistry,
328
                                columnHeaderDataLayer));
329

    
330

    
331
        /**
332
         * row header layer
333
         */
334
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
335
        DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
336
        FixedSummaryRowHeaderLayer fixedSummaryRowHeaderLayer = new FixedSummaryRowHeaderLayer(rowHeaderDataLayer,
337
                composite, selectionLayer);
338
        fixedSummaryRowHeaderLayer.setSummaryRowLabel("\u2211");
339

    
340

    
341
        /**
342
         * corner layer
343
         */
344
        ILayer cornerLayer = new CornerLayer(
345
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
346
                fixedSummaryRowHeaderLayer, sortHeaderLayer);
347

    
348

    
349
        /**
350
         * GRID layer (composition of all other layers)
351
         */
352
        GridLayer gridLayer = new GridLayer(composite, sortHeaderLayer, fixedSummaryRowHeaderLayer, cornerLayer);
353

    
354

    
355

    
356
        natTable = new NatTable(parent, gridLayer, false);
357

    
358

    
359
        /**
360
         * CONFIGURATION
361
         */
362
        natTable.setConfigRegistry(configRegistry);
363

    
364

    
365
        //add default configuration because autoconfigure is set to false in constructor
366
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
367

    
368
        //FIXME: this is for DEBUG ONLY
369
//        natTable.addConfiguration(new DebugMenuConfiguration(natTable));
370

    
371
        // override the default sort configuration and change the mouse bindings
372
        // to sort on a single click
373
        natTable.addConfiguration(new SingleClickSortConfiguration());
374

    
375

    
376
        // add the header menu configuration for adding the column header menu
377
        // with hide/show actions
378
        natTable.addConfiguration(new AbstractHeaderMenuConfiguration(natTable) {
379

    
380
            @Override
381
            protected PopupMenuBuilder createColumnHeaderMenu(NatTable natTable) {
382
                return super.createColumnHeaderMenu(natTable)
383
                        .withHideColumnMenuItem()
384
                        .withShowAllColumnsMenuItem();
385
            }
386

    
387
            @Override
388
            protected PopupMenuBuilder createRowHeaderMenu(NatTable natTable) {
389
                return super.createRowHeaderMenu(natTable)
390
                        .withHideRowMenuItem()
391
                        .withShowAllRowsMenuItem();
392
            }
393

    
394
            @Override
395
            protected PopupMenuBuilder createCornerMenu(NatTable natTable) {
396
                return super.createCornerMenu(natTable)
397
                        .withShowAllColumnsMenuItem()
398
                        .withShowAllRowsMenuItem();
399
            }
400
        });
401

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

    
430
        });
431

    
432
        //register aggregation configuration for each feature
433
        features.forEach(feature->summaryRowLayer.addConfiguration(new AggregationConfiguration(bodyDataProvider, feature)));
434

    
435
        // add the ExportCommandHandler to the ViewportLayer in order to make
436
        // exporting work
437
        viewportLayer.registerCommandHandler(new ExportCommandHandler(viewportLayer));
438

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

    
459
        natTable.configure();
460

    
461
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
462

    
463
        /**
464
         * Table state persistence
465
         */
466
        natTableState = new Properties();
467
        //load persisted state
468
        File statePropertiesFile = getStatePropertiesFile();
469
        FileInputStream inputStream;
470
        try {
471
            inputStream = new FileInputStream(statePropertiesFile);
472
            natTableState.load(inputStream);
473
        } catch (IOException e) {
474
            MessagingUtils.info("No initial state properties file found for character matrix");
475
        }
476

    
477
        DisplayPersistenceDialogCommandHandler handler =
478
                new DisplayPersistenceDialogCommandHandler(natTableState, natTable);
479
        gridLayer.registerCommandHandler(handler);
480
        // create a combobox for showing the available view states
481
        Combo comboStates = new Combo(toolbarComposite, SWT.DROP_DOWN);
482
        Collection<String> availableStates = PersistenceHelper.getAvailableStates(natTableState);
483
        comboStates.setItems(availableStates.toArray(new String[] {}));
484

    
485
        comboStates.addSelectionListener(new SelectionAdapter() {
486
            @Override
487
            public void widgetSelected(SelectionEvent e) {
488
                int index = comboStates.getSelectionIndex();
489
                if (index >= 0) {
490
                    String selected = comboStates.getItem(index);
491
                    // load the state
492
                    natTable.loadState(selected, natTableState);
493
                    natTableState.setProperty(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY, selected);
494
                }
495
            }
496
        });
497

    
498
        // add listener to update the combo on view state management changes
499
        handler.addStateChangeListener(new IStateChangedListener() {
500
            @Override
501
            public void handleStateChange(StateChangeEvent event) {
502
                comboStates.setItems(PersistenceHelper.getAvailableStates(natTableState)
503
                        .toArray(new String[] {}));
504
                selectStateItem(comboStates, event.getViewConfigName());
505
            }
506
        });
507

    
508
        // add button to show dialog
509
        Button btnManageState = new Button(toolbarComposite, SWT.PUSH);
510
        btnManageState.setImage(ImageResources.getImage(ImageResources.SETTINGS));
511
        btnManageState.addSelectionListener(new SelectionAdapter() {
512
            @Override
513
            public void widgetSelected(SelectionEvent e) {
514
                natTable.doCommand(new DisplayPersistenceDialogCommand(natTable));
515
                selectStateItem(comboStates, natTableState.get(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY).toString());
516
            }
517
        });
518

    
519
        /**
520
         * excel export
521
         */
522
        Button btnExcelExport = new Button(toolbarComposite, SWT.PUSH);
523
        btnExcelExport.setToolTipText("Export to Excel");
524
        btnExcelExport.setImage(ImageResources.getImage(ImageResources.EXPORT));
525
        btnExcelExport.addSelectionListener(new SelectionAdapter() {
526
            @Override
527
            public void widgetSelected(SelectionEvent e) {
528
                natTable.doCommand(
529
                        new ExportCommand(
530
                                natTable.getConfigRegistry(),
531
                                natTable.getShell()));
532
            }
533
        });
534

    
535
        /**
536
         * Add description button
537
         */
538
        Button btnAddDescription = new Button(parent, SWT.PUSH);
539
        btnAddDescription.setImage(ImageResources.getImage(ImageResources.ADD_ICON));
540
        btnAddDescription.addSelectionListener(new SelectionAdapter() {
541
            @Override
542
            public void widgetSelected(SelectionEvent e) {
543
                SpecimenSelectionDialog dialog = new SpecimenSelectionDialog(natTable.getShell(), workingSet);
544
                if(dialog.open()==Window.OK){
545
                    Collection<SpecimenOrObservationBase> specimens = dialog.getSpecimen();
546
                    boolean hasAdded = false;
547
                    for (SpecimenOrObservationBase specimen : specimens) {
548
                        SpecimenDescription description = getDescriptionForWorkingSet(specimen);
549
                        if(!workingSet.getDescriptions().contains(description)){
550
                            CharacterMatrix.this.descriptions.add(new RowWrapper(description));
551
                            workingSet.addDescription(description);
552
                            hasAdded = true;
553
                        }
554
                    }
555
                    if(hasAdded){
556
                        setDirty();
557
                    }
558
                }
559
            }
560
        });
561
        parent.layout();
562
    }
563

    
564
    private void selectStateItem(Combo comboStates, String stateName){
565
        String[] items = comboStates.getItems();
566
        for(int i=0;i<items.length;i++){
567
            if(items[i].equals(stateName)){
568
                comboStates.select(i);
569
                break;
570
            }
571
        }
572
    }
573

    
574
    private SpecimenDescription getDescriptionForWorkingSet(SpecimenOrObservationBase specimen){
575
        Set<SpecimenDescription> descriptions = specimen.getDescriptions();
576
        if(descriptions!=null){
577
            Set<Feature> features = workingSet.getDescriptiveSystem().getDistinctFeatures();
578
            for (SpecimenDescription specimenDescription : descriptions) {
579
                Set<Feature> specimenDescriptionFeatures = new HashSet<>();
580
                for (DescriptionElementBase descriptionElementBase : specimenDescription.getElements()) {
581
                    specimenDescriptionFeatures.add(descriptionElementBase.getFeature());
582
                }
583
                if(specimenDescriptionFeatures.containsAll(features)){
584
                    return specimenDescription;
585
                }
586
            }
587
        }
588
        //Create new specimen description if no match was found
589
        setDirty();
590
        SpecimenDescription newDesription = SpecimenDescription.NewInstance(specimen);
591
        newDesription.setTitleCache("WorkingSet "+workingSet.getLabel()+" "+newDesription.generateTitle(), true);
592
        return newDesription;
593

    
594
    }
595

    
596
    private void initLabels(final ColumnOverrideLabelAccumulator columnLabelAccumulator,
597
            int index, Feature feature) {
598

    
599
        columnLabelAccumulator.registerColumnOverrides(index+LEADING_COLUMN_COUNT, MatrixUtility.getProperty(feature));
600
        indexToFeatureMap.put(index+LEADING_COLUMN_COUNT, feature);
601

    
602
        String featureLabel = feature.getLabel();
603
        String property = featureLabel;
604
        //show unit for quantitative data
605
        if(feature.isSupportsQuantitativeData()){
606
            Set<MeasurementUnit> recommendedMeasurementUnits = feature.getRecommendedMeasurementUnits();
607
            if(recommendedMeasurementUnits.size()!=1){
608
                MessagingUtils.warningDialog("Column initialization problem", CharacterMatrix.class,
609
                        String.format("Only one unit is allowed for quantitative data: %s", feature.getLabel()));
610
                return;
611
            }
612
            MeasurementUnit unit = recommendedMeasurementUnits.iterator().next();
613
            featureLabel += " ["+unit.getLabel()+"]";
614
        }
615
        propertyToLabelMap.put(property, featureLabel);
616
    }
617

    
618
    private void registerColumnConfiguration(Feature feature, IConfigRegistry configRegistry) {
619
        //make cell editable
620
        configRegistry.registerConfigAttribute(
621
                EditConfigAttributes.CELL_EDITABLE_RULE,
622
                IEditableRule.ALWAYS_EDITABLE,
623
                DisplayMode.EDIT,
624
                MatrixUtility.getProperty(feature)
625
                );
626
        if(feature.isSupportsQuantitativeData()){
627
            //add display converter for string representation
628
            configRegistry.registerConfigAttribute(
629
                    CellConfigAttributes.DISPLAY_CONVERTER,
630
                    new QuantitativeDataDisplayConverter(),
631
                    DisplayMode.NORMAL,
632
                    MatrixUtility.getProperty(feature));
633
            //register quantitative editor
634
            configRegistry.registerConfigAttribute(
635
                    EditConfigAttributes.CELL_EDITOR,
636
                    new QuantitativeDataCellEditor(feature.getRecommendedStatisticalMeasures(), this),
637
                    DisplayMode.EDIT,
638
                    MatrixUtility.getProperty(feature));
639
        }
640
        else if(feature.isSupportsCategoricalData()){
641
            //add display converter for string representation
642
            configRegistry.registerConfigAttribute(
643
                    CellConfigAttributes.DISPLAY_CONVERTER,
644
                    new CategoricalDataDisplayConverter(),
645
                    DisplayMode.NORMAL,
646
                    MatrixUtility.getProperty(feature));
647

    
648
            //add combo box cell editor
649
            CategoricalDataCellEditor comboBoxCellEditor = new CategoricalDataCellEditor(new IComboBoxDataProvider() {
650

    
651
                @Override
652
                public List<?> getValues(int columnIndex, int rowIndex) {
653
                    List<State> states = new ArrayList<>();
654
                    Feature feature = indexToFeatureMap.get(columnIndex);
655
                    if(feature.isSupportsCategoricalData()){
656
                        Set<TermVocabulary<State>> stateVocs = feature.getSupportedCategoricalEnumerations();
657
                        for (TermVocabulary<State> voc : stateVocs) {
658
                            states.addAll(voc.getTerms());
659
                        }
660
                    }
661
                    return states;
662
                }
663
            }, 5, this);
664
            //register editor
665
            configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR,
666
                    comboBoxCellEditor,
667
                    DisplayMode.EDIT,
668
                    MatrixUtility.getProperty(feature));
669

    
670
        }
671

    
672
    }
673

    
674
    private List<RowWrapper> getDescriptions(WorkingSet workingSet) {
675
        List<RowWrapper> rowWrappers = new ArrayList<>();
676
        Set<DescriptionBase> wsDescriptions = workingSet.getDescriptions();
677
        for (DescriptionBase descriptionBase : wsDescriptions) {
678
            if(descriptionBase instanceof SpecimenDescription){
679
                rowWrappers.add(new RowWrapper((SpecimenDescription) descriptionBase));
680
            }
681
        }
682
        return rowWrappers;
683
    }
684

    
685
    public Map<Integer, Feature> getIndexToFeatureMap() {
686
        return indexToFeatureMap;
687
    }
688

    
689
    public LinkedMap<String, String> getPropertyToLabelMap() {
690
        return propertyToLabelMap;
691
    }
692

    
693
    public void setDirty() {
694
        this.dirty.setDirty(true);
695
    }
696

    
697
    public NatTable getNatTable() {
698
        return natTable;
699
    }
700

    
701
    @Persist
702
    @Override
703
    public void save(IProgressMonitor monitor) {
704
        CdmStore.getService(IWorkingSetService.class).merge(workingSet, true);
705
        conversation.commit();
706
        dirty.setDirty(false);
707
    }
708

    
709
    @Focus
710
    public void setFocus(){
711
        if(conversation!=null){
712
            conversation.bind();
713
        }
714
        if(cdmEntitySession != null) {
715
            cdmEntitySession.bind();
716
        }
717
    }
718

    
719
    @PreDestroy
720
    public void dispose(){
721
        if (conversation != null) {
722
            conversation.close();
723
            conversation = null;
724
        }
725
        if(cdmEntitySession != null) {
726
            cdmEntitySession.dispose();
727
            cdmEntitySession = null;
728
        }
729
        dirty.setDirty(false);
730
        if(natTableState!=null){
731
            try (FileOutputStream tableStateStream =
732
                    new FileOutputStream(getStatePropertiesFile())) {
733
                natTableState.store(tableStateStream, null);
734
            } catch (IOException ioe) {
735
                ioe.printStackTrace();
736
            }
737
        }
738
    }
739

    
740
    private File getStatePropertiesFile() {
741
        return new File(WorkbenchUtility.getBaseLocation(), CHARACTER_MATRIX_STATE_PROPERTIES);
742
    }
743

    
744
    /**
745
     * {@inheritDoc}
746
     */
747
    @Override
748
    public void update(CdmDataChangeMap arg0) {
749
    }
750

    
751
    /**
752
     * {@inheritDoc}
753
     */
754
    @Override
755
    public ConversationHolder getConversationHolder() {
756
        return conversation;
757
    }
758

    
759
    /**
760
     * {@inheritDoc}
761
     */
762
    @Override
763
    public void changed(Object element) {
764
        setDirty();
765
        natTable.refresh();
766
    }
767

    
768
    /**
769
     * {@inheritDoc}
770
     */
771
    @Override
772
    public void forceDirty() {
773
        setDirty();
774
    }
775

    
776

    
777
    /**
778
     * {@inheritDoc}
779
     */
780
    @Override
781
    public ICdmEntitySession getCdmEntitySession() {
782
        return cdmEntitySession;
783
    }
784

    
785

    
786
    /**
787
     * {@inheritDoc}
788
     */
789
    @Override
790
    public Collection<WorkingSet> getRootEntities() {
791
        return Collections.singleton(this.workingSet);
792
    }
793

    
794

    
795
    /**
796
     * {@inheritDoc}
797
     */
798
    @Override
799
    public Map<Object, List<String>> getPropertyPathsMap() {
800
        Map<Object, List<String>> propertyMap = new HashMap<>();
801
        propertyMap.put(SpecimenOrObservationBase.class,WS_PROPERTY_PATH);
802
        return propertyMap;
803
    }
804

    
805
}
(2-2/7)