Project

General

Profile

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

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

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

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

    
125
import ca.odell.glazedlists.EventList;
126
import ca.odell.glazedlists.GlazedLists;
127
import ca.odell.glazedlists.SortedList;
128
import ca.odell.glazedlists.TreeList;
129
import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
130
import eu.etaxonomy.cdm.api.conversation.IConversationEnabled;
131
import eu.etaxonomy.cdm.api.service.IWorkingSetService;
132
import eu.etaxonomy.cdm.model.common.TermVocabulary;
133
import eu.etaxonomy.cdm.model.description.DescriptionBase;
134
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
135
import eu.etaxonomy.cdm.model.description.Feature;
136
import eu.etaxonomy.cdm.model.description.FeatureTree;
137
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
138
import eu.etaxonomy.cdm.model.description.SpecimenDescription;
139
import eu.etaxonomy.cdm.model.description.State;
140
import eu.etaxonomy.cdm.model.description.WorkingSet;
141
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
142
import eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap;
143
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.categorical.CategoricalDataCellEditor;
144
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.categorical.CategoricalDataDisplayConverter;
145
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.quantitative.QuantitativeDataCellEditor;
146
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.quantitative.QuantitativeDataDisplayConverter;
147
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.supplementalInfo.SupplementalInfoDisplayConverter;
148
import eu.etaxonomy.taxeditor.model.ColorResources;
149
import eu.etaxonomy.taxeditor.model.DescriptionHelper;
150
import eu.etaxonomy.taxeditor.model.IDirtyMarkable;
151
import eu.etaxonomy.taxeditor.model.IPartContentHasDetails;
152
import eu.etaxonomy.taxeditor.model.ImageResources;
153
import eu.etaxonomy.taxeditor.model.MessagingUtils;
154
import eu.etaxonomy.taxeditor.preference.Resources;
155
import eu.etaxonomy.taxeditor.session.ICdmEntitySession;
156
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled;
157
import eu.etaxonomy.taxeditor.store.CdmStore;
158
import eu.etaxonomy.taxeditor.workbench.WorkbenchUtility;
159
import eu.etaxonomy.taxeditor.workbench.part.IE4SavablePart;
160

    
161
/**
162
 * @author pplitzner
163
 * @since Nov 26, 2017
164
 *
165
 */
166
public class CharacterMatrix implements IE4SavablePart, IPartContentHasDetails, IConversationEnabled, IDirtyMarkable,
167
ICdmEntitySessionEnabled{
168

    
169
    private static final List<String> WS_PROPERTY_PATH = Arrays.asList(new String[] {
170
            "descriptions", //$NON-NLS-1$
171
            "descriptions.descriptionElements", //$NON-NLS-1$
172
            "descriptions.descriptionElements.inDescription", //$NON-NLS-1$
173
            "descriptions.descriptionElements.inDescription.descriptionElements", //$NON-NLS-1$
174
            "descriptions.descriptionElements.feature", //$NON-NLS-1$
175
    });
176

    
177
    private static final String CHARACTER_MATRIX_STATE_PROPERTIES = "characterMatrixState.properties";
178

    
179
    private static final int LEADING_COLUMN_COUNT = 4;
180
    private static final String TAXON_COLUMN = "taxon_column";
181
    private static final String COLLECTOR_COLUMN = "collector_column";
182
    private static final String IDENTIFIER_COLUMN = "identifier_column";
183
    private static final String COUNTRY_COLUMN = "country_column";
184

    
185
    private WorkingSet workingSet;
186

    
187
    private ConversationHolder conversation;
188

    
189
    private ICdmEntitySession cdmEntitySession;
190

    
191
    @Inject
192
    private ESelectionService selService;
193

    
194
    @Inject
195
    private MDirtyable dirty;
196

    
197
    @Inject
198
    private MPart thisPart;
199

    
200
    private NatTable natTable;
201

    
202
    private Map<Integer, Feature> indexToFeatureMap = new HashMap<>();
203

    
204
    private LinkedMap<String, String> propertyToLabelMap = new LinkedMap<>();
205

    
206
    private Properties natTableState;
207

    
208
    private EventList<Object> descriptions;
209

    
210
    private Collection<SpecimenOrObservationBase> specimenCache = null;
211

    
212
    private ListDataProvider<Object> bodyDataProvider;
213

    
214
    private Label wsLabel;
215

    
216
    private Composite parent;
217

    
218
    private List<Feature> features;
219

    
220
    private DisplayPersistenceDialogCommandHandler displayPersistenceDialogCommandHandler;
221

    
222
    @PostConstruct
223
    public void create(Composite parent) {
224
        if(CdmStore.isActive() && conversation==null){
225
            conversation = CdmStore.createConversation();
226
        }
227
        if(cdmEntitySession == null){
228
            cdmEntitySession = CdmStore.getCurrentSessionManager().newSession(this, true);
229
        }
230
        else{
231
            return;
232
        }
233
        this.parent = parent;
234
        parent.setLayout(new GridLayout());
235

    
236
        Composite toolbarComposite = new Composite(parent, SWT.NONE);
237
        toolbarComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
238
        toolbarComposite.setLayout(new GridLayout(8, false));
239
        natTable = new NatTable(parent, false);
240

    
241
        wsLabel = new Label(toolbarComposite, SWT.NONE);
242

    
243
        Button btnToggleTree = new Button(toolbarComposite, SWT.PUSH);
244
        Button btnToggleFlat = new Button(toolbarComposite, SWT.PUSH);
245
        Button btnCollapseAll = new Button(toolbarComposite, SWT.PUSH);
246
        Button btnExpandAll = new Button(toolbarComposite, SWT.PUSH);
247
        ComboViewer comboStates = new ComboViewer(toolbarComposite, SWT.DROP_DOWN);
248
        Button btnManageState = new Button(toolbarComposite, SWT.PUSH);
249
        Button btnExcelExport = new Button(toolbarComposite, SWT.PUSH);
250

    
251
        /**
252
         * Toogle tree button
253
         */
254
        btnToggleTree.setImage(ImageResources.getImage(ImageResources.HIERARCHICAL));
255
        btnToggleTree.setToolTipText("Show taxon hierarchy");
256
        btnToggleTree.setSelection(true);
257
        btnToggleTree.setEnabled(false);
258
        btnToggleTree.addSelectionListener(new SelectionAdapter() {
259
            @Override
260
            public void widgetSelected(SelectionEvent e) {
261
                toggleTreeFlat(true, btnToggleFlat, btnToggleTree, btnCollapseAll, btnExpandAll);
262
            }
263
        });
264

    
265
        /**
266
         * Toogle flat button
267
         */
268
        btnToggleFlat.setImage(ImageResources.getImage(ImageResources.FLAT));
269
        btnToggleFlat.setToolTipText("Show flat list");
270
        btnToggleFlat.addSelectionListener(new SelectionAdapter() {
271
            @Override
272
            public void widgetSelected(SelectionEvent e) {
273
                toggleTreeFlat(false, btnToggleFlat, btnToggleTree, btnCollapseAll, btnExpandAll);
274
            }
275
        });
276

    
277
        /**
278
         *
279
         * Collapse button
280
         */
281
        btnCollapseAll.setImage(ImageResources.getImage(ImageResources.COLLAPSE_ALL));
282
        btnCollapseAll.setToolTipText("Collapse all");
283
        btnCollapseAll.addSelectionListener(new SelectionAdapter() {
284
            @Override
285
            public void widgetSelected(SelectionEvent e) {
286
                natTable.doCommand(new TreeCollapseAllCommand());
287
            }
288
        });
289

    
290
        /**
291
         * Expand button
292
         */
293
        btnExpandAll.setImage(ImageResources.getImage(ImageResources.EXPAND_ALL));
294
        btnExpandAll.setToolTipText("Expand all");
295
        btnExpandAll.addSelectionListener(new SelectionAdapter() {
296
            @Override
297
            public void widgetSelected(SelectionEvent e) {
298
                natTable.doCommand(new TreeExpandAllCommand());
299
            }
300
        });
301

    
302
        /**
303
         * Table state persistence
304
         */
305
        natTableState = new Properties();
306
        //load persisted state
307
        File statePropertiesFile = getStatePropertiesFile();
308
        FileInputStream inputStream;
309
        try {
310
            inputStream = new FileInputStream(statePropertiesFile);
311
            natTableState.load(inputStream);
312
        } catch (IOException e) {
313
            MessagingUtils.info("No initial state properties file found for character matrix");
314
        }
315

    
316
        // create a combobox for showing the available view states
317
        Collection<String> availableStates = PersistenceHelper.getAvailableStates(natTableState);
318
        comboStates.setLabelProvider(new LabelProvider(){
319
            @Override
320
            public String getText(Object element) {
321
                if(element instanceof String && ((String) element).isEmpty()){
322
                    return "-default-";
323
                }
324
                return super.getText(element);
325
            }
326
        });
327
        comboStates.setContentProvider(new ArrayContentProvider());
328
        comboStates.addSelectionChangedListener(e->
329
        {
330
            int index = comboStates.getCombo().getSelectionIndex();
331
            if (index >= 0) {
332
                String selected = comboStates.getCombo().getItem(index);
333
                // load the state
334
                natTable.loadState(selected, natTableState);
335
                natTableState.setProperty(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY, selected);
336
            }
337
        });
338
        comboStates.setInput(availableStates);
339
        if(comboStates.getCombo().getItemCount()>0){
340
            comboStates.getCombo().select(0);
341
        }
342

    
343
        displayPersistenceDialogCommandHandler = new DisplayPersistenceDialogCommandHandler(natTableState, natTable);
344
        // add listener to update the combo on view state management changes
345
        displayPersistenceDialogCommandHandler.addStateChangeListener(new IStateChangedListener() {
346
            @Override
347
            public void handleStateChange(StateChangeEvent event) {
348
                comboStates.setInput(PersistenceHelper.getAvailableStates(natTableState));
349
                selectStateItem(comboStates, event.getViewConfigName());
350
            }
351
        });
352

    
353
        // add button to show dialog
354
        btnManageState.setImage(ImageResources.getImage(ImageResources.SETTINGS));
355
        btnManageState.setToolTipText("View configuration");
356
        btnManageState.addSelectionListener(new SelectionAdapter() {
357
            @Override
358
            public void widgetSelected(SelectionEvent e) {
359
                natTable.doCommand(new DisplayPersistenceDialogCommand(natTable));
360
                selectStateItem(comboStates, natTableState.get(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY).toString());
361
            }
362
        });
363

    
364
        /**
365
         * excel export
366
         */
367
        btnExcelExport.setToolTipText("Export to Excel");
368
        btnExcelExport.setImage(ImageResources.getImage(ImageResources.EXPORT));
369
        btnExcelExport.addSelectionListener(new SelectionAdapter() {
370
            @Override
371
            public void widgetSelected(SelectionEvent e) {
372
                natTable.doCommand(
373
                        new ExportCommand(
374
                                natTable.getConfigRegistry(),
375
                                natTable.getShell()));
376
            }
377
        });
378

    
379
        Composite buttonPanel = new Composite(parent, SWT.NONE);
380

    
381
        buttonPanel.setLayout(new RowLayout());
382
        GridDataFactory.fillDefaults().grab(true, false).applyTo(buttonPanel);
383

    
384
        /**
385
         * Add description button
386
         */
387
        Button btnAddDescription = new Button(buttonPanel, SWT.PUSH);
388
        btnAddDescription.setImage(ImageResources.getImage(ImageResources.ADD_ICON));
389
        btnAddDescription.addSelectionListener(new SelectionAdapter() {
390
            @Override
391
            public void widgetSelected(SelectionEvent e) {
392
                SpecimenSelectionDialog dialog = new SpecimenSelectionDialog(natTable.getShell(), CharacterMatrix.this);
393
                if(dialog.open()==Window.OK){
394
                    Collection<SpecimenOrObservationBase> specimens = dialog.getSpecimen();
395
                    boolean hasAdded = false;
396
                    for (SpecimenOrObservationBase specimen : specimens) {
397
                        SpecimenDescription description = getDescriptionForWorkingSet(specimen);
398
                        if(!workingSet.getDescriptions().contains(description)){
399
                            CharacterMatrix.this.descriptions.add(new RowWrapper(description));
400
                            workingSet.addDescription(description);
401
                            hasAdded = true;
402
                        }
403
                    }
404
                    if(hasAdded){
405
                        setDirty();
406
                    }
407
                }
408
            }
409
        });
410

    
411
        applyStyles();
412
    }
413

    
414
    private void applyStyles(){
415
        // NOTE: Getting the colors and fonts from the GUIHelper ensures that
416
        // they are disposed properly (required by SWT)
417
        DefaultNatTableStyleConfiguration natTableConfiguration = new DefaultNatTableStyleConfiguration();
418
        natTableConfiguration.bgColor = GUIHelper.getColor(249, 172, 7);
419
        natTableConfiguration.fgColor = GUIHelper.getColor(30, 76, 19);
420
        natTableConfiguration.hAlign = HorizontalAlignmentEnum.LEFT;
421
        natTableConfiguration.vAlign = VerticalAlignmentEnum.TOP;
422

    
423
        // Setup even odd row colors - row colors override the NatTable default
424
        // colors
425
        DefaultRowStyleConfiguration rowStyleConfiguration = new DefaultRowStyleConfiguration();
426
        rowStyleConfiguration.oddRowBgColor = ColorResources.getColor(Resources.COLOR_LIST_ODD);
427
        rowStyleConfiguration.evenRowBgColor = ColorResources.getColor(Resources.COLOR_LIST_EVEN);
428

    
429
        // Setup selection styling
430
        DefaultSelectionStyleConfiguration selectionStyle = new DefaultSelectionStyleConfiguration();
431
//        selectionStyle.selectionFont = GUIHelper.getFont(new FontData("Verdana", 8, SWT.NORMAL));
432
//        selectionStyle.selectionBgColor = GUIHelper.getColor(217, 232, 251);
433
//        selectionStyle.selectionFgColor = GUIHelper.COLOR_BLACK;
434
        selectionStyle.anchorBorderStyle = new BorderStyle(1, GUIHelper.COLOR_DARK_GRAY, LineStyleEnum.SOLID);
435
//        selectionStyle.anchorBgColor = GUIHelper.getColor(65, 113, 43);
436
        selectionStyle.selectedHeaderBgColor = GUIHelper.getColor(156, 209, 103);
437

    
438
        // Add all style configurations to NatTable
439
        natTable.addConfiguration(natTableConfiguration);
440
        natTable.addConfiguration(rowStyleConfiguration);
441
        natTable.addConfiguration(selectionStyle);
442

    
443
        // Column/Row header style and custom painters
444
        DefaultRowHeaderStyleConfiguration rowHeaderConfig = new DefaultRowHeaderStyleConfiguration();
445
        Color rowColumnColor = GUIHelper.getColor(230, 255, 255);
446
        rowHeaderConfig.bgColor = rowColumnColor;
447
        natTable.addConfiguration(rowHeaderConfig);
448
        DefaultColumnHeaderStyleConfiguration columnHeaderStyle = new DefaultColumnHeaderStyleConfiguration();
449
        columnHeaderStyle.bgColor = rowColumnColor;
450
        columnHeaderStyle.font = GUIHelper.getFont(new FontData("Verdana", 8, SWT.BOLD));
451
        natTable.addConfiguration(columnHeaderStyle);
452

    
453
    }
454

    
455
    private void toggleTreeFlat(boolean isTree, Button btnToggleFlat, Button btnToggleTree, Button btnCollapseAll, Button btnExpandAll) {
456
        init(workingSet.getUuid(), isTree);
457
        btnToggleFlat.setEnabled(isTree);
458
        btnToggleTree.setEnabled(!isTree);
459
        btnCollapseAll.setEnabled(isTree);
460
        btnExpandAll.setEnabled(isTree);
461
        natTable.doCommand(new ClientAreaResizeCommand(natTable));
462
    }
463

    
464
    public void init(UUID workingSetUuid, boolean treeView) {
465
        if(workingSet==null){
466
            this.workingSet = CdmStore.getService(IWorkingSetService.class).load(workingSetUuid, WS_PROPERTY_PATH);
467
            if(workingSet.getDescriptiveSystem()==null){
468
                MessagingUtils.informationDialog("Editor could not be opened", "The working set has no feature tree selected.");
469
                return;
470
            }
471
            thisPart.setLabel(workingSet.getLabel());
472

    
473
            //get features/columns stored in working set
474
            FeatureTree tree = workingSet.getDescriptiveSystem();
475
            features = new ArrayList<>(tree.getDistinctFeatures());
476
            Collections.sort(features);
477

    
478
            descriptions = GlazedLists.eventList(getDescriptions(workingSet));
479
        }
480
        // use the SortedList constructor with 'null' for the Comparator
481
        // because the Comparator will be set by configuration
482
        SortedList<Object> sortedList = new SortedList<>(descriptions, new MatrixRowComparator());
483
        // wrap the SortedList with the TreeList
484
        TreeList<Object> treeList = new TreeList(sortedList, new DescriptionTreeFormat(workingSet.getMaxRank()), TreeList.NODES_START_EXPANDED);
485
        /**
486
         * data provider
487
         */
488
        SpecimenColumnPropertyAccessor columnPropertyAccessor = new SpecimenColumnPropertyAccessor(this);
489
        bodyDataProvider = treeView?new ListDataProvider<>(treeList, columnPropertyAccessor):new ListDataProvider<>(sortedList, columnPropertyAccessor);
490

    
491
        ConfigRegistry configRegistry = new ConfigRegistry();
492

    
493

    
494
        /**
495
         * BODY layer
496
         *
497
         *
498

    
499
        CompositeLayer
500
         - (top) SummaryRowLayer
501
         - (bottom) ViewportLayer
502

    
503
             ^
504
        ViewportLayer
505

    
506
             ^
507
        TreeLayer (default visible)
508

    
509
             ^
510
        SelectionLayer
511

    
512
             ^
513
        RowHideShowLayer
514

    
515
             ^
516
        ColumnHideShowLayer
517

    
518
             ^
519
        ColumnReorderLayer
520

    
521
             ^
522
        RowReorderLayer
523

    
524
             ^
525
        DataLayer
526

    
527
         *
528

    
529
         */
530
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
531

    
532
        //register labels for columns
533
        ColumnOverrideLabelAccumulator bodyColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
534
        bodyDataLayer.setConfigLabelAccumulator(bodyColumnLabelAccumulator);
535
        propertyToLabelMap.put(TAXON_COLUMN, "Taxon");
536
        bodyColumnLabelAccumulator.registerColumnOverrides(0, TAXON_COLUMN);
537
        propertyToLabelMap.put(COLLECTOR_COLUMN, "Collector + No");
538
        bodyColumnLabelAccumulator.registerColumnOverrides(1, COLLECTOR_COLUMN);
539
        propertyToLabelMap.put(IDENTIFIER_COLUMN, "Identifier");
540
        bodyColumnLabelAccumulator.registerColumnOverrides(2, IDENTIFIER_COLUMN);
541
        propertyToLabelMap.put(COUNTRY_COLUMN, "Country");
542
        bodyColumnLabelAccumulator.registerColumnOverrides(3, COUNTRY_COLUMN);
543
        for(int i=0;i<features.size();i++){
544
            Feature feature = features.get(i);
545
            initLabels(bodyColumnLabelAccumulator, i, feature);
546
        }
547

    
548
        // layer for event handling of GlazedLists and PropertyChanges
549
        GlazedListsEventLayer eventLayer = new GlazedListsEventLayer<>(bodyDataLayer, treeList);
550
        GlazedListTreeData treeData = new GlazedListTreeData<>(treeList);
551
        ITreeRowModel treeRowModel = new GlazedListTreeRowModel<>(treeData);
552

    
553
        ColumnReorderLayer columnReorderLayer;
554
        ColumnHideShowLayer columnHideShowLayer;
555
        SelectionLayer selectionLayer;
556
        TreeLayer treeLayer;
557
        ViewportLayer viewportLayer;
558
        if(treeView){
559
            columnReorderLayer = new ColumnReorderLayer(eventLayer);
560
            columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
561
            selectionLayer = new SelectionLayer(columnHideShowLayer);
562
            treeLayer = new TreeLayer(selectionLayer, treeRowModel);
563
            viewportLayer = treeView?new ViewportLayer(treeLayer):new ViewportLayer(selectionLayer);
564
        }
565
        else{
566
            RowReorderLayer rowReorderLayer = new RowReorderLayer(eventLayer);
567
            columnReorderLayer = new ColumnReorderLayer(rowReorderLayer);
568
            columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
569
            RowHideShowLayer rowHideShowLayer = new RowHideShowLayer(columnHideShowLayer);
570
            selectionLayer = new SelectionLayer(rowHideShowLayer);
571
            treeLayer = new TreeLayer(selectionLayer, treeRowModel);
572
            viewportLayer = treeView?new ViewportLayer(treeLayer):new ViewportLayer(selectionLayer);
573
        }
574

    
575
        // create a standalone FixedSummaryRowLayer
576
        // since the summary row should be fixed at the top of the body
577
        // region the horizontal dependency of the FixedSummaryRowLayer
578
        // is the ViewportLayer
579
        FixedSummaryRowLayer summaryRowLayer =
580
                new FixedSummaryRowLayer(bodyDataLayer, viewportLayer, configRegistry, false);
581
        //register labels with summary prefix for summary layer
582
        ColumnOverrideLabelAccumulator summaryColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
583
        summaryRowLayer.setConfigLabelAccumulator(summaryColumnLabelAccumulator);
584
        for(int i=0;i<features.size();i++){
585
            Feature feature = features.get(i);
586
            summaryColumnLabelAccumulator.registerColumnOverrides(
587
                    i+LEADING_COLUMN_COUNT,
588
                    SummaryRowLayer.DEFAULT_SUMMARY_COLUMN_CONFIG_LABEL_PREFIX+MatrixUtility.getProperty(feature));
589
        }
590
        // because the horizontal dependency is the ViewportLayer
591
        // we need to set the composite dependency to false
592
        summaryRowLayer.setHorizontalCompositeDependency(false);
593

    
594
        CompositeLayer composite = new CompositeLayer(1, 2);
595
        composite.setChildLayer("SUMMARY", summaryRowLayer, 0, 0);
596
        composite.setChildLayer(GridRegion.BODY, viewportLayer, 0, 1);
597

    
598

    
599
        /**
600
         * column header layer
601
         */
602
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
603
                propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
604
        DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
605
        ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, viewportLayer, selectionLayer);
606

    
607
        // add the SortHeaderLayer to the column header layer stack
608
        // as we use GlazedLists, we use the GlazedListsSortModel which
609
        // delegates the sorting to the SortedList
610
        final SortHeaderLayer<SpecimenDescription> sortHeaderLayer = new SortHeaderLayer<>(
611
                columnHeaderLayer,
612
                new GlazedListsSortModel<>(
613
                        sortedList,
614
                        columnPropertyAccessor,
615
                        configRegistry,
616
                        columnHeaderDataLayer));
617

    
618

    
619
        /**
620
         * row header layer
621
         */
622
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
623
        DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
624
        FixedSummaryRowHeaderLayer fixedSummaryRowHeaderLayer = new FixedSummaryRowHeaderLayer(rowHeaderDataLayer,
625
                composite, selectionLayer);
626
        fixedSummaryRowHeaderLayer.setSummaryRowLabel("\u2211");
627

    
628

    
629
        /**
630
         * corner layer
631
         */
632
        ILayer cornerLayer = new CornerLayer(
633
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
634
                fixedSummaryRowHeaderLayer, sortHeaderLayer);
635

    
636

    
637
        /**
638
         * GRID layer (composition of all other layers)
639
         */
640
        GridLayer gridLayer = new GridLayer(composite, sortHeaderLayer, fixedSummaryRowHeaderLayer, cornerLayer);
641

    
642
        natTable.setLayer(gridLayer);
643

    
644
        /**
645
         * CONFIGURATION
646
         */
647
        natTable.setConfigRegistry(configRegistry);
648

    
649
        //add default configuration because autoconfigure is set to false in constructor
650
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
651

    
652
        //FIXME: this is for DEBUG ONLY
653
        //        natTable.addConfiguration(new DebugMenuConfiguration(natTable));
654

    
655
        // override the default sort configuration and change the mouse bindings
656
        // to sort on a single click
657
        if(!treeView){
658
            natTable.addConfiguration(new SingleClickSortConfiguration());
659
        }
660

    
661
        // add the header menu configuration for adding the column header menu
662
        // with hide/show actions
663
        natTable.addConfiguration(new AbstractHeaderMenuConfiguration(natTable) {
664

    
665
            @Override
666
            protected PopupMenuBuilder createColumnHeaderMenu(NatTable natTable) {
667
                return super.createColumnHeaderMenu(natTable)
668
                        .withHideColumnMenuItem()
669
                        .withShowAllColumnsMenuItem();
670
            }
671

    
672
        });
673

    
674
        Style cellStyle = new Style();
675
        cellStyle.setAttributeValue(CellStyleAttributes.HORIZONTAL_ALIGNMENT, HorizontalAlignmentEnum.LEFT);
676

    
677
        // add custom configuration for data conversion and add column labels to viewport layer
678
        viewportLayer.addConfiguration(new AbstractRegistryConfiguration() {
679
            @Override
680
            public void configureRegistry(IConfigRegistry configRegistry) {
681
                //add display converter for string representation
682
                configRegistry.registerConfigAttribute(
683
                        CellConfigAttributes.DISPLAY_CONVERTER,
684
                        new SupplementalInfoDisplayConverter(),
685
                        DisplayMode.NORMAL,
686
                        TAXON_COLUMN);
687
                configRegistry.registerConfigAttribute(
688
                        CellConfigAttributes.CELL_STYLE,
689
                        cellStyle,
690
                        DisplayMode.NORMAL,
691
                        TAXON_COLUMN);
692
                configRegistry.registerConfigAttribute(
693
                        CellConfigAttributes.DISPLAY_CONVERTER,
694
                        new SupplementalInfoDisplayConverter(),
695
                        DisplayMode.NORMAL,
696
                        COLLECTOR_COLUMN);
697
                configRegistry.registerConfigAttribute(
698
                        CellConfigAttributes.CELL_STYLE,
699
                        cellStyle,
700
                        DisplayMode.NORMAL,
701
                        COLLECTOR_COLUMN);
702
                configRegistry.registerConfigAttribute(
703
                        CellConfigAttributes.DISPLAY_CONVERTER,
704
                        new SupplementalInfoDisplayConverter(),
705
                        DisplayMode.NORMAL,
706
                        IDENTIFIER_COLUMN);
707
                configRegistry.registerConfigAttribute(
708
                        CellConfigAttributes.CELL_STYLE,
709
                        cellStyle,
710
                        DisplayMode.NORMAL,
711
                        IDENTIFIER_COLUMN);
712
                configRegistry.registerConfigAttribute(
713
                        CellConfigAttributes.DISPLAY_CONVERTER,
714
                        new SupplementalInfoDisplayConverter(),
715
                        DisplayMode.NORMAL,
716
                        COUNTRY_COLUMN);
717
                configRegistry.registerConfigAttribute(
718
                        CellConfigAttributes.CELL_STYLE,
719
                        cellStyle,
720
                        DisplayMode.NORMAL,
721
                        COUNTRY_COLUMN);
722
                features.forEach(feature->registerColumnConfiguration(feature, configRegistry));
723
            }
724

    
725
        });
726

    
727
        //register aggregation configuration for each feature
728
        features.forEach(feature->summaryRowLayer.addConfiguration(new AggregationConfiguration(bodyDataProvider, feature)));
729

    
730
        // add the ExportCommandHandler to the ViewportLayer in order to make
731
        // exporting work
732
        viewportLayer.registerCommandHandler(new ExportCommandHandler(viewportLayer));
733

    
734
        //propagate single cell selection
735
        natTable.addLayerListener(new ILayerListener() {
736
            @Override
737
            public void handleLayerEvent(ILayerEvent event) {
738
                if(event instanceof CellSelectionEvent){
739
                    CellSelectionEvent cellSelectionEvent = (CellSelectionEvent)event;
740
                    int columnPosition = cellSelectionEvent.getColumnPosition();
741
                    if(columnPosition>LEADING_COLUMN_COUNT){
742
                        Collection<ILayerCell> selectedCells = cellSelectionEvent.getSelectionLayer().getSelectedCells();
743
                        StructuredSelection selection = new StructuredSelection();
744
                        if(selectedCells.size()==1){
745
                            ILayerCell cell = selectedCells.iterator().next();
746
                            Object dataValue = cell.getDataValue();
747
                            if(dataValue!=null){
748
                                selection = new StructuredSelection(dataValue);
749
                            }
750
                        }
751
                        selService.setSelection(selection);
752
                    }
753
                }
754
            }
755
        });
756

    
757
        //register handler for view configuration menu
758
        natTable.registerCommandHandler(displayPersistenceDialogCommandHandler);
759

    
760
        natTable.configure();
761

    
762
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
763

    
764
        wsLabel.setText(workingSet.getLabel());
765
        wsLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
766
        wsLabel.getParent().layout();
767

    
768
        parent.layout();
769
    }
770

    
771
    private void selectStateItem(ComboViewer comboStates, String stateName){
772
        String[] items = comboStates.getCombo().getItems();
773
        for(int i=0;i<items.length;i++){
774
            if(items[i].equals(stateName)){
775
                comboStates.getCombo().select(i);
776
                break;
777
            }
778
        }
779
    }
780

    
781
    private SpecimenDescription getDescriptionForWorkingSet(SpecimenOrObservationBase specimen){
782
        Set<Feature> wsFeatures = workingSet.getDescriptiveSystem().getDistinctFeatures();
783
        List<DescriptionElementBase> matchingDescriptionElements = new ArrayList<>();
784

    
785
        for (SpecimenDescription specimenDescription : (Set<SpecimenDescription>) specimen.getDescriptions()) {
786
            Set<Feature> specimenDescriptionFeatures = new HashSet<>();
787
            //gather specimen description features and check for match with WS features
788
            for (DescriptionElementBase specimenDescriptionElement : specimenDescription.getElements()) {
789
                Feature feature = specimenDescriptionElement.getFeature();
790
                specimenDescriptionFeatures.add(feature);
791
                if(wsFeatures.contains(feature)){
792
                    matchingDescriptionElements.add(specimenDescriptionElement);
793
                }
794
            }
795
            //if description with the exact same features is found return the description
796
            if(specimenDescriptionFeatures.equals(wsFeatures)){
797
                return specimenDescription;
798
            }
799
        }
800
        //Create new specimen description if no match was found
801
        setDirty();
802
        SpecimenDescription newDesription = SpecimenDescription.NewInstance(specimen);
803
        newDesription.setTitleCache("WorkingSet "+workingSet.getLabel()+": "+newDesription.generateTitle(), true);
804

    
805
        //check for equals description element (same feature and same values)
806
        Map<Feature, List<DescriptionElementBase>> featureToElementMap = new HashMap<>();
807
        for(DescriptionElementBase element:matchingDescriptionElements){
808
            List<DescriptionElementBase> list = featureToElementMap.get(element.getFeature());
809
            if(list==null){
810
                list = new ArrayList<>();
811
            }
812
            list.add(element);
813
            featureToElementMap.put(element.getFeature(), list);
814
        }
815
        Set<DescriptionElementBase> descriptionElementsToClone = new HashSet<>();
816
        for(Feature feature:featureToElementMap.keySet()){
817
            List<DescriptionElementBase> elements = featureToElementMap.get(feature);
818
            //no duplicate description elements found for this feature
819
            if(elements.size()==1){
820
                descriptionElementsToClone.add(elements.get(0));
821
            }
822
            //duplicates found -> check if all are equal
823
            else{
824
                DescriptionElementBase match = null;
825
                for (DescriptionElementBase descriptionElementBase : elements) {
826
                    if(match==null){
827
                        match = descriptionElementBase;
828
                    }
829
                    else if(!new DescriptionElementCompareWrapper(match).equals(new DescriptionElementCompareWrapper(descriptionElementBase))){
830
                        match = null;
831
                        MessagingUtils.informationDialog("Multiple data found",
832
                                String.format("Multiple description elements with different values "
833
                                        + "found for feature '%s'.\nData will not be copied to new specimen description.", feature.getLabel()));
834
                        break;
835
                    }
836
                }
837
                if(match!=null){
838
                    descriptionElementsToClone.add(match);
839
                }
840
            }
841
        }
842
        //clone matching descriptionElements
843
        for (DescriptionElementBase descriptionElementBase : descriptionElementsToClone) {
844
            DescriptionElementBase clone;
845
            try {
846
                clone = descriptionElementBase.clone(newDesription);
847
                clone.getSources().forEach(source -> source.setOriginalNameString(DescriptionHelper.getLabel(descriptionElementBase)));
848
            } catch (CloneNotSupportedException e) {
849
                MessagingUtils.error(CharacterMatrix.class, e);
850
            }
851
        }
852
        return newDesription;
853

    
854
    }
855

    
856
    private void initLabels(final ColumnOverrideLabelAccumulator columnLabelAccumulator,
857
            int index, Feature feature) {
858

    
859
        columnLabelAccumulator.registerColumnOverrides(index+LEADING_COLUMN_COUNT, MatrixUtility.getProperty(feature));
860
        indexToFeatureMap.put(index+LEADING_COLUMN_COUNT, feature);
861

    
862
        String featureLabel = feature.getLabel();
863
        String property = featureLabel;
864
        //show unit for quantitative data
865
        if(feature.isSupportsQuantitativeData()){
866
            Set<MeasurementUnit> recommendedMeasurementUnits = feature.getRecommendedMeasurementUnits();
867
            if(recommendedMeasurementUnits.size()!=1){
868
                MessagingUtils.warningDialog("Column initialization problem", CharacterMatrix.class,
869
                        String.format("Only one unit is allowed for quantitative data: %s", feature.getLabel()));
870
                return;
871
            }
872
            MeasurementUnit unit = recommendedMeasurementUnits.iterator().next();
873
            featureLabel += " ["+unit.getLabel()+"]";
874
        }
875
        propertyToLabelMap.put(property, featureLabel);
876
    }
877

    
878
    private void registerColumnConfiguration(Feature feature, IConfigRegistry configRegistry) {
879
        //make cell editable
880
        configRegistry.registerConfigAttribute(
881
                EditConfigAttributes.CELL_EDITABLE_RULE,
882
                IEditableRule.ALWAYS_EDITABLE,
883
                DisplayMode.EDIT,
884
                MatrixUtility.getProperty(feature)
885
                );
886
        if(feature.isSupportsQuantitativeData()){
887
            //add display converter for string representation
888
            configRegistry.registerConfigAttribute(
889
                    CellConfigAttributes.DISPLAY_CONVERTER,
890
                    new QuantitativeDataDisplayConverter(),
891
                    DisplayMode.NORMAL,
892
                    MatrixUtility.getProperty(feature));
893
            //register quantitative editor
894
            configRegistry.registerConfigAttribute(
895
                    EditConfigAttributes.CELL_EDITOR,
896
                    new QuantitativeDataCellEditor(feature, this),
897
                    DisplayMode.EDIT,
898
                    MatrixUtility.getProperty(feature));
899
        }
900
        else if(feature.isSupportsCategoricalData()){
901
            //add display converter for string representation
902
            configRegistry.registerConfigAttribute(
903
                    CellConfigAttributes.DISPLAY_CONVERTER,
904
                    new CategoricalDataDisplayConverter(),
905
                    DisplayMode.NORMAL,
906
                    MatrixUtility.getProperty(feature));
907

    
908
            //add combo box cell editor
909
            CategoricalDataCellEditor comboBoxCellEditor = new CategoricalDataCellEditor(new IComboBoxDataProvider() {
910

    
911
                @Override
912
                public List<?> getValues(int columnIndex, int rowIndex) {
913
                    List<State> states = new ArrayList<>();
914
                    Feature feature = indexToFeatureMap.get(columnIndex);
915
                    if(feature.isSupportsCategoricalData()){
916
                        Set<TermVocabulary<State>> stateVocs = feature.getSupportedCategoricalEnumerations();
917
                        for (TermVocabulary<State> voc : stateVocs) {
918
                            states.addAll(voc.getTerms());
919
                        }
920
                    }
921
                    return states;
922
                }
923
            }, 5, this, feature);
924
            //register editor
925
            configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR,
926
                    comboBoxCellEditor,
927
                    DisplayMode.EDIT,
928
                    MatrixUtility.getProperty(feature));
929

    
930
        }
931

    
932
    }
933

    
934
    private List<RowWrapper> getDescriptions(WorkingSet workingSet) {
935
        List<RowWrapper> rowWrappers = new ArrayList<>();
936
        Set<DescriptionBase> wsDescriptions = workingSet.getDescriptions();
937
        for (DescriptionBase descriptionBase : wsDescriptions) {
938
            if(descriptionBase instanceof SpecimenDescription){
939
                rowWrappers.add(new RowWrapper((SpecimenDescription) descriptionBase));
940
            }
941
        }
942
        return rowWrappers;
943
    }
944

    
945
    public Map<Integer, Feature> getIndexToFeatureMap() {
946
        return indexToFeatureMap;
947
    }
948

    
949
    public LinkedMap<String, String> getPropertyToLabelMap() {
950
        return propertyToLabelMap;
951
    }
952

    
953
    public void setDirty() {
954
        this.dirty.setDirty(true);
955
    }
956

    
957
    public NatTable getNatTable() {
958
        return natTable;
959
    }
960

    
961
    public WorkingSet getWorkingSet() {
962
        return workingSet;
963
    }
964

    
965
    public Collection<SpecimenOrObservationBase> getSpecimenCache() {
966
        return specimenCache;
967
    }
968

    
969
    public void setSpecimenCache(Collection<SpecimenOrObservationBase> specimenCache) {
970
        this.specimenCache = specimenCache;
971
    }
972

    
973
    /**
974
     * @return the bodyDataProvider
975
     */
976
    public ListDataProvider<Object> getBodyDataProvider() {
977
        return bodyDataProvider;
978
    }
979

    
980
    @Persist
981
    @Override
982
    public void save(IProgressMonitor monitor) {
983
        CdmStore.getService(IWorkingSetService.class).merge(workingSet, true);
984
        conversation.commit();
985
        dirty.setDirty(false);
986
    }
987

    
988
    @Focus
989
    public void setFocus(){
990
        if(conversation!=null){
991
            conversation.bind();
992
        }
993
        if(cdmEntitySession != null) {
994
            cdmEntitySession.bind();
995
        }
996
    }
997

    
998
    @PreDestroy
999
    public void dispose(){
1000
        if (conversation != null) {
1001
            conversation.close();
1002
            conversation = null;
1003
        }
1004
        if(cdmEntitySession != null) {
1005
            cdmEntitySession.dispose();
1006
            cdmEntitySession = null;
1007
        }
1008
        dirty.setDirty(false);
1009
        if(natTableState!=null){
1010
            try (FileOutputStream tableStateStream =
1011
                    new FileOutputStream(getStatePropertiesFile())) {
1012
                natTableState.store(tableStateStream, null);
1013
            } catch (IOException ioe) {
1014
                ioe.printStackTrace();
1015
            }
1016
        }
1017
    }
1018

    
1019
    private File getStatePropertiesFile() {
1020
        return new File(WorkbenchUtility.getBaseLocation(), CHARACTER_MATRIX_STATE_PROPERTIES);
1021
    }
1022

    
1023
    /**
1024
     * {@inheritDoc}
1025
     */
1026
    @Override
1027
    public void update(CdmDataChangeMap arg0) {
1028
    }
1029

    
1030
    /**
1031
     * {@inheritDoc}
1032
     */
1033
    @Override
1034
    public ConversationHolder getConversationHolder() {
1035
        return conversation;
1036
    }
1037

    
1038
    /**
1039
     * {@inheritDoc}
1040
     */
1041
    @Override
1042
    public void changed(Object element) {
1043
        setDirty();
1044
        natTable.refresh();
1045
    }
1046

    
1047
    /**
1048
     * {@inheritDoc}
1049
     */
1050
    @Override
1051
    public void forceDirty() {
1052
        setDirty();
1053
    }
1054

    
1055

    
1056
    /**
1057
     * {@inheritDoc}
1058
     */
1059
    @Override
1060
    public ICdmEntitySession getCdmEntitySession() {
1061
        return cdmEntitySession;
1062
    }
1063

    
1064

    
1065
    /**
1066
     * {@inheritDoc}
1067
     */
1068
    @Override
1069
    public Collection<WorkingSet> getRootEntities() {
1070
        return Collections.singleton(this.workingSet);
1071
    }
1072

    
1073

    
1074
    /**
1075
     * {@inheritDoc}
1076
     */
1077
    @Override
1078
    public Map<Object, List<String>> getPropertyPathsMap() {
1079
        Map<Object, List<String>> propertyMap = new HashMap<>();
1080
        propertyMap.put(SpecimenOrObservationBase.class,WS_PROPERTY_PATH);
1081
        return propertyMap;
1082
    }
1083

    
1084
}
(2-2/11)