Project

General

Profile

Download (33.6 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.IDirtyMarkable;
127
import eu.etaxonomy.taxeditor.model.IPartContentHasDetails;
128
import eu.etaxonomy.taxeditor.model.ImageResources;
129
import eu.etaxonomy.taxeditor.model.MessagingUtils;
130
import eu.etaxonomy.taxeditor.session.ICdmEntitySession;
131
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled;
132
import eu.etaxonomy.taxeditor.store.CdmStore;
133
import eu.etaxonomy.taxeditor.workbench.WorkbenchUtility;
134
import eu.etaxonomy.taxeditor.workbench.part.IE4SavablePart;
135

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

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

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

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

    
160
    private WorkingSet workingSet;
161

    
162
    private Composite parent;
163

    
164
    private ConversationHolder conversation;
165

    
166
    private ICdmEntitySession cdmEntitySession;
167

    
168
    @Inject
169
    private ESelectionService selService;
170

    
171
    @Inject
172
    private MDirtyable dirty;
173

    
174
    @Inject
175
    private MPart thisPart;
176

    
177
    private NatTable natTable;
178

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

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

    
183
    private Properties natTableState;
184

    
185
    private EventList<RowWrapper> descriptions;
186

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

    
202

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

    
207
        Composite toolbarComposite = new Composite(parent, SWT.NONE);
208
        toolbarComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
209
        toolbarComposite.setLayout(new GridLayout(4, false));
210

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

    
216
        descriptions = GlazedLists.eventList(getDescriptions(workingSet));
217
        SortedList<RowWrapper> sortedList = new SortedList<>(descriptions, null);
218

    
219
        ConfigRegistry configRegistry = new ConfigRegistry();
220

    
221
        /**
222
         * data provider
223
         */
224
        SpecimenColumnPropertyAccessor columnPropertyAccessor = new SpecimenColumnPropertyAccessor(this);
225
        IDataProvider bodyDataProvider = new ListDataProvider<RowWrapper>(sortedList, columnPropertyAccessor);
226

    
227
        /**
228
         * BODY layer
229
         *
230
         *
231

    
232
        CompositeLayer
233
         - (top) SummaryRowLayer
234
         - (bottom) ViewportLayer
235

    
236
             ^
237
        ViewportLayer
238

    
239
             ^
240
        SelectionLayer
241

    
242
             ^
243
        RowHideShowLayer
244

    
245
             ^
246
        ColumnHideShowLayer
247

    
248
             ^
249
        ColumnReorderLayer
250

    
251
             ^
252
        RowReorderLayer
253

    
254
             ^
255
        DataLayer
256

    
257
             *
258

    
259
         */
260
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
261

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

    
278
        GlazedListsEventLayer<RowWrapper> eventLayer = new GlazedListsEventLayer<>(bodyDataLayer, sortedList);
279

    
280
        RowReorderLayer rowReorderLayer = new RowReorderLayer(eventLayer);
281
        ColumnReorderLayer columnReorderLayer = new ColumnReorderLayer(rowReorderLayer);
282
        ColumnHideShowLayer columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
283
        RowHideShowLayer rowHideShowLayer = new RowHideShowLayer(columnHideShowLayer);
284
        SelectionLayer selectionLayer = new SelectionLayer(rowHideShowLayer);
285
        ViewportLayer viewportLayer = new ViewportLayer(selectionLayer);
286

    
287

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

    
307
        CompositeLayer composite = new CompositeLayer(1, 2);
308
        composite.setChildLayer("SUMMARY", summaryRowLayer, 0, 0);
309
        composite.setChildLayer(GridRegion.BODY, viewportLayer, 0, 1);
310

    
311

    
312

    
313

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

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

    
333

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

    
343

    
344
        /**
345
         * corner layer
346
         */
347
        ILayer cornerLayer = new CornerLayer(
348
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
349
                fixedSummaryRowHeaderLayer, sortHeaderLayer);
350

    
351

    
352
        /**
353
         * GRID layer (composition of all other layers)
354
         */
355
        GridLayer gridLayer = new GridLayer(composite, sortHeaderLayer, fixedSummaryRowHeaderLayer, cornerLayer);
356

    
357

    
358

    
359
        natTable = new NatTable(parent, gridLayer, false);
360

    
361

    
362
        /**
363
         * CONFIGURATION
364
         */
365
        natTable.setConfigRegistry(configRegistry);
366

    
367

    
368
        //add default configuration because autoconfigure is set to false in constructor
369
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
370

    
371
        //FIXME: this is for DEBUG ONLY
372
//        natTable.addConfiguration(new DebugMenuConfiguration(natTable));
373

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

    
378

    
379
        // add the header menu configuration for adding the column header menu
380
        // with hide/show actions
381
        natTable.addConfiguration(new AbstractHeaderMenuConfiguration(natTable) {
382

    
383
            @Override
384
            protected PopupMenuBuilder createColumnHeaderMenu(NatTable natTable) {
385
                return super.createColumnHeaderMenu(natTable)
386
                        .withHideColumnMenuItem()
387
                        .withShowAllColumnsMenuItem();
388
            }
389

    
390
            @Override
391
            protected PopupMenuBuilder createRowHeaderMenu(NatTable natTable) {
392
                return super.createRowHeaderMenu(natTable)
393
                        .withHideRowMenuItem()
394
                        .withShowAllRowsMenuItem();
395
            }
396

    
397
            @Override
398
            protected PopupMenuBuilder createCornerMenu(NatTable natTable) {
399
                return super.createCornerMenu(natTable)
400
                        .withShowAllColumnsMenuItem()
401
                        .withShowAllRowsMenuItem();
402
            }
403
        });
404

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

    
433
        });
434

    
435
        //register aggregation configuration for each feature
436
        features.forEach(feature->summaryRowLayer.addConfiguration(new AggregationConfiguration(bodyDataProvider, feature)));
437

    
438
        // add the ExportCommandHandler to the ViewportLayer in order to make
439
        // exporting work
440
        viewportLayer.registerCommandHandler(new ExportCommandHandler(viewportLayer));
441

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

    
462
        natTable.configure();
463

    
464
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
465

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

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

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

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

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

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

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

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

    
593
    private SpecimenDescription getDescriptionForWorkingSet(SpecimenOrObservationBase specimen){
594
        Set<SpecimenDescription> descriptions = specimen.getDescriptions();
595
        if(descriptions!=null){
596
            Set<Feature> features = workingSet.getDescriptiveSystem().getDistinctFeatures();
597
            for (SpecimenDescription specimenDescription : descriptions) {
598
                Set<Feature> specimenDescriptionFeatures = new HashSet<>();
599
                for (DescriptionElementBase descriptionElementBase : specimenDescription.getElements()) {
600
                    specimenDescriptionFeatures.add(descriptionElementBase.getFeature());
601
                }
602
                if(specimenDescriptionFeatures.containsAll(features)){
603
                    return specimenDescription;
604
                }
605
            }
606
        }
607
        //Create new specimen description if no match was found
608
        setDirty();
609
        SpecimenDescription newDesription = SpecimenDescription.NewInstance(specimen);
610
        newDesription.setTitleCache("WorkingSet "+workingSet.getLabel()+" "+newDesription.generateTitle(), true);
611
        return newDesription;
612

    
613
    }
614

    
615
    private void initLabels(final ColumnOverrideLabelAccumulator columnLabelAccumulator,
616
            int index, Feature feature) {
617

    
618
        columnLabelAccumulator.registerColumnOverrides(index+LEADING_COLUMN_COUNT, MatrixUtility.getProperty(feature));
619
        indexToFeatureMap.put(index+LEADING_COLUMN_COUNT, feature);
620

    
621
        String featureLabel = feature.getLabel();
622
        String property = featureLabel;
623
        //show unit for quantitative data
624
        if(feature.isSupportsQuantitativeData()){
625
            Set<MeasurementUnit> recommendedMeasurementUnits = feature.getRecommendedMeasurementUnits();
626
            if(recommendedMeasurementUnits.size()!=1){
627
                MessagingUtils.warningDialog("Column initialization problem", CharacterMatrix.class,
628
                        String.format("Only one unit is allowed for quantitative data: %s", feature.getLabel()));
629
                return;
630
            }
631
            MeasurementUnit unit = recommendedMeasurementUnits.iterator().next();
632
            featureLabel += " ["+unit.getLabel()+"]";
633
        }
634
        propertyToLabelMap.put(property, featureLabel);
635
    }
636

    
637
    private void registerColumnConfiguration(Feature feature, IConfigRegistry configRegistry) {
638
        //make cell editable
639
        configRegistry.registerConfigAttribute(
640
                EditConfigAttributes.CELL_EDITABLE_RULE,
641
                IEditableRule.ALWAYS_EDITABLE,
642
                DisplayMode.EDIT,
643
                MatrixUtility.getProperty(feature)
644
                );
645
        if(feature.isSupportsQuantitativeData()){
646
            //add display converter for string representation
647
            configRegistry.registerConfigAttribute(
648
                    CellConfigAttributes.DISPLAY_CONVERTER,
649
                    new QuantitativeDataDisplayConverter(),
650
                    DisplayMode.NORMAL,
651
                    MatrixUtility.getProperty(feature));
652
            //register quantitative editor
653
            configRegistry.registerConfigAttribute(
654
                    EditConfigAttributes.CELL_EDITOR,
655
                    new QuantitativeDataCellEditor(feature.getRecommendedStatisticalMeasures(), this),
656
                    DisplayMode.EDIT,
657
                    MatrixUtility.getProperty(feature));
658
        }
659
        else if(feature.isSupportsCategoricalData()){
660
            //add display converter for string representation
661
            configRegistry.registerConfigAttribute(
662
                    CellConfigAttributes.DISPLAY_CONVERTER,
663
                    new CategoricalDataDisplayConverter(),
664
                    DisplayMode.NORMAL,
665
                    MatrixUtility.getProperty(feature));
666

    
667
            //add combo box cell editor
668
            CategoricalDataCellEditor comboBoxCellEditor = new CategoricalDataCellEditor(new IComboBoxDataProvider() {
669

    
670
                @Override
671
                public List<?> getValues(int columnIndex, int rowIndex) {
672
                    List<State> states = new ArrayList<>();
673
                    Feature feature = indexToFeatureMap.get(columnIndex);
674
                    if(feature.isSupportsCategoricalData()){
675
                        Set<TermVocabulary<State>> stateVocs = feature.getSupportedCategoricalEnumerations();
676
                        for (TermVocabulary<State> voc : stateVocs) {
677
                            states.addAll(voc.getTerms());
678
                        }
679
                    }
680
                    return states;
681
                }
682
            }, 5, this);
683
            //register editor
684
            configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR,
685
                    comboBoxCellEditor,
686
                    DisplayMode.EDIT,
687
                    MatrixUtility.getProperty(feature));
688

    
689
        }
690

    
691
    }
692

    
693
    private List<RowWrapper> getDescriptions(WorkingSet workingSet) {
694
        List<RowWrapper> rowWrappers = new ArrayList<>();
695
        Set<DescriptionBase> wsDescriptions = workingSet.getDescriptions();
696
        for (DescriptionBase descriptionBase : wsDescriptions) {
697
            if(descriptionBase instanceof SpecimenDescription){
698
                rowWrappers.add(new RowWrapper((SpecimenDescription) descriptionBase));
699
            }
700
        }
701
        return rowWrappers;
702
    }
703

    
704
    public Map<Integer, Feature> getIndexToFeatureMap() {
705
        return indexToFeatureMap;
706
    }
707

    
708
    public LinkedMap<String, String> getPropertyToLabelMap() {
709
        return propertyToLabelMap;
710
    }
711

    
712
    public void setDirty() {
713
        this.dirty.setDirty(true);
714
    }
715

    
716
    public NatTable getNatTable() {
717
        return natTable;
718
    }
719

    
720
    @Persist
721
    @Override
722
    public void save(IProgressMonitor monitor) {
723
        CdmStore.getService(IWorkingSetService.class).merge(workingSet, true);
724
        conversation.commit();
725
        dirty.setDirty(false);
726
    }
727

    
728
    @Focus
729
    public void setFocus(){
730
        if(conversation!=null){
731
            conversation.bind();
732
        }
733
        if(cdmEntitySession != null) {
734
            cdmEntitySession.bind();
735
        }
736
    }
737

    
738
    @PreDestroy
739
    public void dispose(){
740
        if (conversation != null) {
741
            conversation.close();
742
            conversation = null;
743
        }
744
        if(cdmEntitySession != null) {
745
            cdmEntitySession.dispose();
746
            cdmEntitySession = null;
747
        }
748
        dirty.setDirty(false);
749
        if(natTableState!=null){
750
            try (FileOutputStream tableStateStream =
751
                    new FileOutputStream(getStatePropertiesFile())) {
752
                natTableState.store(tableStateStream, null);
753
            } catch (IOException ioe) {
754
                ioe.printStackTrace();
755
            }
756
        }
757
    }
758

    
759
    private File getStatePropertiesFile() {
760
        return new File(WorkbenchUtility.getBaseLocation(), CHARACTER_MATRIX_STATE_PROPERTIES);
761
    }
762

    
763
    /**
764
     * {@inheritDoc}
765
     */
766
    @Override
767
    public void update(CdmDataChangeMap arg0) {
768
    }
769

    
770
    /**
771
     * {@inheritDoc}
772
     */
773
    @Override
774
    public ConversationHolder getConversationHolder() {
775
        return conversation;
776
    }
777

    
778
    /**
779
     * {@inheritDoc}
780
     */
781
    @Override
782
    public void changed(Object element) {
783
        setDirty();
784
        natTable.refresh();
785
    }
786

    
787
    /**
788
     * {@inheritDoc}
789
     */
790
    @Override
791
    public void forceDirty() {
792
        setDirty();
793
    }
794

    
795

    
796
    /**
797
     * {@inheritDoc}
798
     */
799
    @Override
800
    public ICdmEntitySession getCdmEntitySession() {
801
        return cdmEntitySession;
802
    }
803

    
804

    
805
    /**
806
     * {@inheritDoc}
807
     */
808
    @Override
809
    public Collection<WorkingSet> getRootEntities() {
810
        return Collections.singleton(this.workingSet);
811
    }
812

    
813

    
814
    /**
815
     * {@inheritDoc}
816
     */
817
    @Override
818
    public Map<Object, List<String>> getPropertyPathsMap() {
819
        Map<Object, List<String>> propertyMap = new HashMap<>();
820
        propertyMap.put(SpecimenOrObservationBase.class,WS_PROPERTY_PATH);
821
        return propertyMap;
822
    }
823

    
824
}
(2-2/8)