Project

General

Profile

Download (46.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.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.HeaderMenuConfiguration;
111
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuBuilder;
112
import org.eclipse.nebula.widgets.nattable.util.GUIHelper;
113
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
114
import org.eclipse.swt.SWT;
115
import org.eclipse.swt.events.SelectionAdapter;
116
import org.eclipse.swt.events.SelectionEvent;
117
import org.eclipse.swt.graphics.Color;
118
import org.eclipse.swt.graphics.FontData;
119
import org.eclipse.swt.layout.GridData;
120
import org.eclipse.swt.layout.GridLayout;
121
import org.eclipse.swt.layout.RowLayout;
122
import org.eclipse.swt.widgets.Button;
123
import org.eclipse.swt.widgets.Composite;
124
import org.eclipse.swt.widgets.Label;
125

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

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

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

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

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

    
186
    private WorkingSet workingSet;
187

    
188
    private ConversationHolder conversation;
189

    
190
    private ICdmEntitySession cdmEntitySession;
191

    
192
    @Inject
193
    private ESelectionService selService;
194

    
195
    @Inject
196
    private MDirtyable dirty;
197

    
198
    @Inject
199
    private MPart thisPart;
200

    
201
    private NatTable natTable;
202

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

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

    
207
    private Properties natTableState;
208

    
209
    private EventList<Object> descriptions;
210

    
211
    private Collection<SpecimenOrObservationBase> specimenCache = null;
212

    
213
    private ListDataProvider<Object> bodyDataProvider;
214

    
215
    private Label wsLabel;
216

    
217
    private Composite parent;
218

    
219
    private List<Feature> features;
220

    
221
    private DisplayPersistenceDialogCommandHandler displayPersistenceDialogCommandHandler;
222

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
412
        applyStyles();
413
    }
414

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

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

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

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

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

    
454
        // Add popup menu - build your own popup menu using the PopupMenuBuilder
455
        natTable.addConfiguration(new HeaderMenuConfiguration(natTable));
456
    }
457

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

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

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

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

    
494
        ConfigRegistry configRegistry = new ConfigRegistry();
495

    
496

    
497
        /**
498
         * BODY layer
499
         *
500
         *
501

    
502
        CompositeLayer
503
         - (top) SummaryRowLayer
504
         - (bottom) ViewportLayer
505

    
506
             ^
507
        ViewportLayer
508

    
509
             ^
510
        TreeLayer (default visible)
511

    
512
             ^
513
        SelectionLayer
514

    
515
             ^
516
        RowHideShowLayer
517

    
518
             ^
519
        ColumnHideShowLayer
520

    
521
             ^
522
        ColumnReorderLayer
523

    
524
             ^
525
        RowReorderLayer
526

    
527
             ^
528
        DataLayer
529

    
530
         *
531

    
532
         */
533
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
534

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

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

    
556
        RowReorderLayer rowReorderLayer = new RowReorderLayer(eventLayer);
557
        ColumnReorderLayer columnReorderLayer = new ColumnReorderLayer(rowReorderLayer);
558
        ColumnHideShowLayer columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
559
        RowHideShowLayer rowHideShowLayer = new RowHideShowLayer(columnHideShowLayer);
560
        SelectionLayer selectionLayer = new SelectionLayer(rowHideShowLayer);
561
        TreeLayer treeLayer = new TreeLayer(selectionLayer, treeRowModel);
562
        ViewportLayer viewportLayer = treeView?new ViewportLayer(treeLayer):new ViewportLayer(selectionLayer);
563

    
564
        // create a standalone FixedSummaryRowLayer
565
        // since the summary row should be fixed at the top of the body
566
        // region the horizontal dependency of the FixedSummaryRowLayer
567
        // is the ViewportLayer
568
        FixedSummaryRowLayer summaryRowLayer =
569
                new FixedSummaryRowLayer(bodyDataLayer, viewportLayer, configRegistry, false);
570
        //register labels with summary prefix for summary layer
571
        ColumnOverrideLabelAccumulator summaryColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
572
        summaryRowLayer.setConfigLabelAccumulator(summaryColumnLabelAccumulator);
573
        for(int i=0;i<features.size();i++){
574
            Feature feature = features.get(i);
575
            summaryColumnLabelAccumulator.registerColumnOverrides(
576
                    i+LEADING_COLUMN_COUNT,
577
                    SummaryRowLayer.DEFAULT_SUMMARY_COLUMN_CONFIG_LABEL_PREFIX+MatrixUtility.getProperty(feature));
578
        }
579
        // because the horizontal dependency is the ViewportLayer
580
        // we need to set the composite dependency to false
581
        summaryRowLayer.setHorizontalCompositeDependency(false);
582

    
583
        CompositeLayer composite = new CompositeLayer(1, 2);
584
        composite.setChildLayer("SUMMARY", summaryRowLayer, 0, 0);
585
        composite.setChildLayer(GridRegion.BODY, viewportLayer, 0, 1);
586

    
587

    
588
        /**
589
         * column header layer
590
         */
591
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
592
                propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
593
        DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
594
        ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, viewportLayer, selectionLayer);
595

    
596
        // add the SortHeaderLayer to the column header layer stack
597
        // as we use GlazedLists, we use the GlazedListsSortModel which
598
        // delegates the sorting to the SortedList
599
        final SortHeaderLayer<SpecimenDescription> sortHeaderLayer = new SortHeaderLayer<>(
600
                columnHeaderLayer,
601
                new GlazedListsSortModel<>(
602
                        sortedList,
603
                        columnPropertyAccessor,
604
                        configRegistry,
605
                        columnHeaderDataLayer));
606

    
607

    
608
        /**
609
         * row header layer
610
         */
611
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
612
        DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
613
        FixedSummaryRowHeaderLayer fixedSummaryRowHeaderLayer = new FixedSummaryRowHeaderLayer(rowHeaderDataLayer,
614
                composite, selectionLayer);
615
        fixedSummaryRowHeaderLayer.setSummaryRowLabel("\u2211");
616

    
617

    
618
        /**
619
         * corner layer
620
         */
621
        ILayer cornerLayer = new CornerLayer(
622
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
623
                fixedSummaryRowHeaderLayer, sortHeaderLayer);
624

    
625

    
626
        /**
627
         * GRID layer (composition of all other layers)
628
         */
629
        GridLayer gridLayer = new GridLayer(composite, sortHeaderLayer, fixedSummaryRowHeaderLayer, cornerLayer);
630

    
631
        natTable.setLayer(gridLayer);
632

    
633
        /**
634
         * CONFIGURATION
635
         */
636
        natTable.setConfigRegistry(configRegistry);
637

    
638
        //add default configuration because autoconfigure is set to false in constructor
639
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
640

    
641
        //FIXME: this is for DEBUG ONLY
642
        //        natTable.addConfiguration(new DebugMenuConfiguration(natTable));
643

    
644
        // override the default sort configuration and change the mouse bindings
645
        // to sort on a single click
646
        //currently removed sorting because of using the TreeConfiguration
647
        natTable.addConfiguration(new SingleClickSortConfiguration());
648

    
649
        // add the header menu configuration for adding the column header menu
650
        // with hide/show actions
651
        natTable.addConfiguration(new AbstractHeaderMenuConfiguration(natTable) {
652

    
653
            @Override
654
            protected PopupMenuBuilder createColumnHeaderMenu(NatTable natTable) {
655
                return super.createColumnHeaderMenu(natTable)
656
                        .withHideColumnMenuItem()
657
                        .withShowAllColumnsMenuItem();
658
            }
659

    
660
            @Override
661
            protected PopupMenuBuilder createRowHeaderMenu(NatTable natTable) {
662
                return super.createRowHeaderMenu(natTable)
663
                        .withHideRowMenuItem()
664
                        .withShowAllRowsMenuItem();
665
            }
666

    
667
            @Override
668
            protected PopupMenuBuilder createCornerMenu(NatTable natTable) {
669
                return super.createCornerMenu(natTable)
670
                        .withShowAllColumnsMenuItem()
671
                        .withShowAllRowsMenuItem();
672
            }
673
        });
674

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

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

    
726
        });
727

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

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

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

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

    
761
        natTable.configure();
762

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

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

    
769
        parent.layout();
770
    }
771

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

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

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

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

    
855
    }
856

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

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

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

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

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

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

    
931
        }
932

    
933
    }
934

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1056

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

    
1065

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

    
1074

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

    
1085
}
(2-2/11)