Project

General

Profile

Download (30.4 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2018 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.view.checklist.e4;
10

    
11
import java.util.ArrayList;
12
import java.util.Arrays;
13
import java.util.HashMap;
14
import java.util.HashSet;
15
import java.util.Iterator;
16
import java.util.List;
17
import java.util.Map;
18
import java.util.Set;
19
import java.util.SortedSet;
20
import java.util.TreeSet;
21
import java.util.UUID;
22

    
23
import org.apache.commons.collections4.map.LinkedMap;
24
import org.apache.logging.log4j.LogManager;
25
import org.apache.logging.log4j.Logger;
26
import org.eclipse.jface.layout.GridDataFactory;
27
import org.eclipse.jface.layout.GridLayoutFactory;
28
import org.eclipse.jface.wizard.WizardDialog;
29
import org.eclipse.nebula.widgets.nattable.NatTable;
30
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
31
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
32
import org.eclipse.nebula.widgets.nattable.coordinate.PositionCoordinate;
33
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
34
import org.eclipse.nebula.widgets.nattable.data.IRowDataProvider;
35
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
36
import org.eclipse.nebula.widgets.nattable.extension.e4.selection.E4SelectionListener;
37
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.filterrow.DefaultGlazedListsFilterStrategy;
38
import org.eclipse.nebula.widgets.nattable.filterrow.FilterRowHeaderComposite;
39
import org.eclipse.nebula.widgets.nattable.freeze.CompositeFreezeLayer;
40
import org.eclipse.nebula.widgets.nattable.freeze.FreezeHelper;
41
import org.eclipse.nebula.widgets.nattable.freeze.FreezeLayer;
42
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
43
import org.eclipse.nebula.widgets.nattable.grid.command.ClientAreaResizeCommand;
44
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
45
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
46
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
47
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
48
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
49
import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultColumnHeaderDataLayer;
50
import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultRowHeaderDataLayer;
51
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
52
import org.eclipse.nebula.widgets.nattable.grid.layer.RowHeaderLayer;
53
import org.eclipse.nebula.widgets.nattable.layer.AbstractLayer;
54
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
55
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
56
import org.eclipse.nebula.widgets.nattable.layer.config.DefaultColumnHeaderStyleConfiguration;
57
import org.eclipse.nebula.widgets.nattable.painter.cell.TextPainter;
58
import org.eclipse.nebula.widgets.nattable.painter.cell.decorator.BeveledBorderDecorator;
59
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
60
import org.eclipse.nebula.widgets.nattable.sort.config.SingleClickSortConfiguration;
61
import org.eclipse.nebula.widgets.nattable.util.GUIHelper;
62
import org.eclipse.swt.SWT;
63
import org.eclipse.swt.events.SelectionAdapter;
64
import org.eclipse.swt.events.SelectionEvent;
65
import org.eclipse.swt.layout.GridData;
66
import org.eclipse.swt.layout.GridLayout;
67
import org.eclipse.swt.widgets.Button;
68
import org.eclipse.swt.widgets.Composite;
69
import org.eclipse.swt.widgets.Label;
70
import org.eclipse.swt.widgets.Text;
71

    
72
import ca.odell.glazedlists.BasicEventList;
73
import ca.odell.glazedlists.EventList;
74
import eu.etaxonomy.cdm.api.service.IVocabularyService;
75
import eu.etaxonomy.cdm.api.service.dto.TaxonDescriptionDTO;
76
import eu.etaxonomy.cdm.api.service.dto.TaxonDistributionDTO;
77
import eu.etaxonomy.cdm.compare.term.OrderedTermComparator;
78
import eu.etaxonomy.cdm.compare.term.TermIdInVocabularyComparator;
79
import eu.etaxonomy.cdm.compare.term.TermLanguageComparator;
80
import eu.etaxonomy.cdm.compare.term.TermSymbol1Comparator;
81
import eu.etaxonomy.cdm.compare.term.TermSymbol2Comparator;
82
import eu.etaxonomy.cdm.model.common.Language;
83
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
84
import eu.etaxonomy.cdm.model.description.Distribution;
85
import eu.etaxonomy.cdm.model.description.TaxonDescription;
86
import eu.etaxonomy.cdm.model.location.NamedArea;
87
import eu.etaxonomy.cdm.model.metadata.PreferencePredicate;
88
import eu.etaxonomy.cdm.model.metadata.TermOrder;
89
import eu.etaxonomy.cdm.model.reference.Reference;
90
import eu.etaxonomy.cdm.model.term.DefinedTermBase;
91
import eu.etaxonomy.cdm.model.term.OrderedTermBase;
92
import eu.etaxonomy.cdm.model.term.Representation;
93
import eu.etaxonomy.cdm.model.term.TermType;
94
import eu.etaxonomy.cdm.model.term.TermVocabulary;
95
import eu.etaxonomy.taxeditor.editor.IDistributionEditor;
96
import eu.etaxonomy.taxeditor.editor.l10n.Messages;
97
import eu.etaxonomy.taxeditor.model.AbstractUtility;
98
import eu.etaxonomy.taxeditor.model.ImageResources;
99
import eu.etaxonomy.taxeditor.preference.PreferencesUtil;
100
import eu.etaxonomy.taxeditor.preference.Resources;
101
import eu.etaxonomy.taxeditor.preference.wizard.AvailableDistributionWizard;
102
import eu.etaxonomy.taxeditor.store.CdmStore;
103
import eu.etaxonomy.taxeditor.ui.dialog.selection.ReferenceSelectionDialog;
104

    
105
/**
106
 * @author k.luther
107
 * @since 27.11.2018
108
 */
109
public class DistributionEditor extends Composite implements IDistributionEditor{
110

    
111
    @SuppressWarnings("unused")
112
    private static final Logger logger = LogManager.getLogger();
113

    
114
    private static final String DISTRIBUTION_EDITOR = "Distribution Editor"; //$NON-NLS-1$
115
    private static final String LOADING_TAXA = Messages.ChecklistEditor_LOAD_TAXA;
116
    private static final String UNKNOWN = Messages.ChecklistEditor_UNKNOWN;
117
    private static final String ELEMENT_COUNT = Messages.ChecklistEditor_ELEMENT_COUNT;
118
    public static final String TYPE_FILTER_TEXT = "type filter text"; //$NON-NLS-1$
119

    
120
    static final String TAXON_COLUMN = "taxon_column"; //$NON-NLS-1$
121
    static final String RANK_COLUMN = "collector_column";//$NON-NLS-1$
122
    static final String SYNONYM_COLUMN = "synonym_column";//$NON-NLS-1$
123

    
124

    
125
    private NatTable natTable;
126
    private Label statusLabel;
127
    private Label statusLabelSourceReference;
128
    private Reference defaultSource;
129

    
130
    private Map<Integer, NamedArea> areaToColumnIndexMap= new HashMap<>();
131
    private int firstDataColumnIndex;
132

    
133
    private ListDataProvider<TaxonDistributionDTO> bodyDataProvider;
134
    private LinkedMap<String, String> propertyToLabelMap = new LinkedMap<>();
135

    
136
    private boolean isShowRank = false;
137
    private Text searchText;
138

    
139
    private Button button3;
140
    private Button button2;
141

    
142
    protected EventList<TaxonDistributionDTO> taxonList;
143
    private String actualNameCache;
144
    protected Map<UUID,Map<NamedArea,Set<DescriptionElementBase>>> taxonDistributionMap = new HashMap<>();
145

    
146
    protected List<TaxonDistributionDTO> descriptionsToSave = new ArrayList<>();
147

    
148
    protected SortedSet<NamedArea> areas;
149
    protected DistributionEditorPart part;
150
    private BodyLayerStack<TaxonDistributionDTO> bodyLayerStack;
151
    private FreezeLayer freezeLayer;
152
    private ConfigRegistry configRegistry;
153
    private AbstractLayer topMostLayer;
154

    
155
    private SelectionLayer selectionLayer;
156

    
157
    public DistributionEditor(Composite parent, DistributionEditorPart part) {
158
        super(parent, SWT.NULL);
159
        isShowRank = PreferencesUtil.getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
160
        this.part = part;
161
        this.setLayout(new GridLayout());
162
        GridLayoutFactory.fillDefaults().applyTo(parent);
163

    
164
        Composite topComposite = new Composite(parent, SWT.NONE);
165
        createTopComposite(topComposite);
166

    
167
        natTable = new NatTable(parent, false);
168
        parent.pack();
169

    
170
        Composite bottomComposite = new Composite(parent, SWT.NONE);
171
        GridLayoutFactory.fillDefaults().applyTo(bottomComposite);
172
        createStatusBar(bottomComposite);
173
    }
174

    
175
    public boolean isShowRank() {
176
        return isShowRank;
177
    }
178

    
179
    public void setShowRank(boolean isShowRank) {
180
        this.isShowRank = isShowRank;
181
    }
182

    
183
    public int getFirstDataColumnIndex() {
184
        return firstDataColumnIndex;
185
    }
186

    
187
    public void setFirstDataColumnIndex(int firstDataColumnIndex) {
188
        this.firstDataColumnIndex = firstDataColumnIndex;
189
    }
190

    
191
    @Override
192
    public String getActualNameCache() {
193
        return actualNameCache;
194
    }
195

    
196
    public void setActualNameCache(String actualNameCache) {
197
        this.actualNameCache = actualNameCache;
198
    }
199

    
200
    public LinkedMap<String, String> getPropertyToLabelMap() {
201
        return propertyToLabelMap;
202
    }
203

    
204
    public void setPropertyToLabelMap(LinkedMap<String, String> propertyToLabelMap) {
205
        this.propertyToLabelMap = propertyToLabelMap;
206
    }
207

    
208
    public Map<Integer, NamedArea> getAreaToColumnIndexMap() {
209
        return areaToColumnIndexMap;
210
    }
211

    
212
    public void setAreaToColumnIndexMap(Map<Integer, NamedArea> areaToColumnIndexMap) {
213
        this.areaToColumnIndexMap = areaToColumnIndexMap;
214
    }
215

    
216
    public List<TaxonDistributionDTO> getDescriptionsToSave() {
217
        return descriptionsToSave;
218
    }
219

    
220
    public void setDescriptionsToSave(List<TaxonDistributionDTO> descriptionsToSave) {
221
        this.descriptionsToSave = descriptionsToSave;
222
    }
223

    
224
    private void createStatusBar(Composite composite) {
225
        GridData gridData = new GridData();
226
        gridData.horizontalSpan = 2;
227
        gridData.grabExcessHorizontalSpace = true;
228
        gridData.horizontalAlignment = GridData.FILL;
229
        GridLayout gridLayout = new GridLayout();
230
        gridLayout.numColumns = 3;
231
        composite.setLayoutData(gridData);
232
        composite.setLayout(gridLayout);
233

    
234

    
235
        gridData = new GridData();
236
        gridData.horizontalSpan = 1;
237
        gridData.grabExcessHorizontalSpace = true;
238
        gridData.horizontalAlignment = GridData.FILL;
239

    
240
        statusLabel = new Label(composite, SWT.LEFT);
241
        statusLabel.setText(ELEMENT_COUNT + (taxonList != null ? taxonList.size() : UNKNOWN));
242
        statusLabel.setLayoutData(gridData);
243

    
244
        statusLabelSourceReference = new Label(composite, SWT.RIGHT);
245

    
246
        statusLabelSourceReference.setLayoutData(gridData);
247

    
248
        if (defaultSource != null){
249
            statusLabelSourceReference.setText(Messages.DistributionEditor_defaultSource + (defaultSource.getAbbrevTitle() != null? defaultSource.getAbbrevTitle() : defaultSource.getAbbrevTitleCache()));
250
        }
251

    
252
        button3 = new Button(composite, SWT.PUSH );
253
        button3.setEnabled(false);
254
        GridData gridData3 = new GridData();
255
        gridData3.horizontalAlignment = SWT.RIGHT;
256
        button3.setLayoutData(gridData3);
257
        //button3.setText(Messages.ChecklistEditor_REMOVE_DEFAULT_SOURCE);
258
        button3.setImage(ImageResources.getImage(ImageResources.TRASH_ICON));
259
        button3.setToolTipText(Messages.ChecklistEditor_REMOVE_DEFAULT_SOURCE_TOOLTIP);
260
        button3.addSelectionListener(new SelectionAdapter() {
261

    
262
            @Override
263
            public void widgetSelected(SelectionEvent event) {
264
                defaultSource = null;
265

    
266
                String defaultSourceStr = (defaultSource == null) ? "" : Messages.DistributionEditor_defaultSource + defaultSource.getTitleCache(); //$NON-NLS-1$
267
                if (defaultSourceStr.length()> 100){
268
                    defaultSourceStr = defaultSourceStr.substring(0, 98) + "..."; //$NON-NLS-1$
269
                }
270
                statusLabelSourceReference.setText(defaultSourceStr);
271

    
272
                button3.setBackground(AbstractUtility.getColor(Resources.COLOR_CONTROL_SELECTED));
273
                button3.setEnabled(false);
274
                button2.setText(Messages.ChecklistEditor_DEFAULT_SOURCE);
275
            }
276

    
277
        });
278
    }
279

    
280
    private void applyStyles(){
281
        CdmModernNatTableThemeConfiguration configuration = new CdmModernNatTableThemeConfiguration();
282

    
283
//        configuration.summaryRowHAlign = HorizontalAlignmentEnum.CENTER;
284
        // NOTE: Getting the colors and fonts from the GUIHelper ensures that
285
        // they are disposed properly (required by SWT)
286
        configuration.cHeaderBgColor = GUIHelper.getColor(211, 211, 211);
287
        configuration.rHeaderBgColor = GUIHelper.getColor(211, 211, 211);
288
        natTable.addConfiguration(configuration);
289
    }
290

    
291
    private void configureNatTable(ConfigRegistry configRegistry,
292
            AbstractLayer topMostLayer) {
293
        /**
294
         * CONFIGURATION
295
         */
296
        natTable.setConfigRegistry(configRegistry);
297

    
298
        //add default configuration because autoconfigure is set to false in constructor
299
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
300

    
301

    
302
        natTable.addConfiguration(new DefaultColumnHeaderStyleConfiguration() {
303
            {
304
                TextPainter painter = new TextPainter();
305
                painter.setCalculateByTextLength(true);
306
                painter.setWrapText(false);
307

    
308
                cellPainter = new BeveledBorderDecorator(painter);
309

    
310
            }
311
        });
312
//        applyStyles();
313
        // override the default sort configuration and change the mouse bindings
314
        // to sort on a single click
315

    
316
        natTable.addConfiguration(new SingleClickSortConfiguration());
317
        natTable.addConfiguration(new FilterRowConfiguration(this));
318

    
319
        // add the header menu configuration for adding the column header menu
320
        // with hide/show actions
321
        natTable.addConfiguration(new DistributionEditorHeaderMenuConfiguration(natTable));
322

    
323
        // add custom configuration for data conversion and add column labels to viewport layer
324
        topMostLayer.addConfiguration(new DistributionCellEditorDataConversionConfiguration(this));
325

    
326
        applyStyles();
327
        natTable.configure();
328
    }
329

    
330
    public void createTable(){
331
        /**
332
         * layers
333
         */
334
        createLayers();
335

    
336
        /**
337
         * configuration
338
         */
339
        configureNatTable( configRegistry, topMostLayer);
340

    
341
        /**
342
         * handlers and listeners
343
         */
344
        registerHandlersAndListeners(topMostLayer);
345
        FreezeHelper.freeze(freezeLayer, bodyLayerStack.getViewPortLayer(),
346
                new PositionCoordinate(bodyLayerStack.getViewPortLayer(), 0, 0),
347
                new PositionCoordinate(bodyLayerStack.getViewPortLayer(), 0, -1));
348
        //grab all space
349
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
350

    
351
        this.layout();
352
        natTable.doCommand(new ClientAreaResizeCommand(natTable));
353
      //  boolean ok = natTable.doCommand(new ClientAreaResizeCommand(natTable));
354
    }
355

    
356
    private void createLayers() {
357

    
358
        DistributionColumnAccessor columnPropertyAccessor = new DistributionColumnAccessor(this);
359
        DistributionEditorConfigLabelAccumulator labelAccumulator = new DistributionEditorConfigLabelAccumulator(this);
360

    
361
//        bodyLayerStack = new BodyLayerStack<>(taxonList, columnPropertyAccessor, new TaxonDistributionDtoComparator(), labelAccumulator);
362
        bodyLayerStack = new BodyLayerStack<>(taxonList, columnPropertyAccessor, null, labelAccumulator);
363
        bodyDataProvider = bodyLayerStack.getBodyDataProvider();
364

    
365
        propertyToLabelMap.put(TAXON_COLUMN, Messages.ChecklistEditor_TAXON);
366
        if (isShowRank){
367
            propertyToLabelMap.put(RANK_COLUMN, Messages.ChecklistEditor_RANK);
368
            propertyToLabelMap.put(SYNONYM_COLUMN, Messages.ChecklistEditor_SYNONYMS);
369
        }else{
370
            propertyToLabelMap.put(SYNONYM_COLUMN, Messages.ChecklistEditor_SYNONYMS);
371
        }
372
        configRegistry = new ConfigRegistry();
373

    
374
        initLabels();
375
        this.selectionLayer = bodyLayerStack.getSelectionLayer();
376

    
377
        freezeLayer = new FreezeLayer(selectionLayer);
378
        final CompositeFreezeLayer compositeFreezeLayer = new CompositeFreezeLayer(
379
                freezeLayer,  bodyLayerStack.getViewPortLayer(), selectionLayer);
380

    
381
        // as the selection mouse bindings are registered for the region label
382
        // GridRegion.BODY
383
        // we need to set that region label to the viewport so the selection via mouse
384
        // is working correctly
385
        compositeFreezeLayer.setRegionName(GridRegion.BODY);
386

    
387
        IDataProvider columnHeaderDataProvider =
388
                new DefaultColumnHeaderDataProvider(propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
389
        DataLayer columnHeaderDataLayer = new DefaultColumnHeaderDataLayer(columnHeaderDataProvider);
390
        ILayer columnHeaderLayer = new ColumnHeaderLayer(
391
            columnHeaderDataLayer,
392
            compositeFreezeLayer,
393
            selectionLayer);
394

    
395
        FilterRowHeaderComposite<TaxonDistributionDTO> filterRowHeaderLayer =
396
                new FilterRowHeaderComposite<>(
397
                        new DefaultGlazedListsFilterStrategy<>(
398
                                bodyLayerStack.getFilterList(),
399
                                columnPropertyAccessor,
400
                                configRegistry),
401
                        columnHeaderLayer,
402
                        columnHeaderDataLayer.getDataProvider(),
403
                        configRegistry);
404

    
405
     // build the row header layer stack
406
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
407
        DataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
408
        ILayer rowHeaderLayer = new RowHeaderLayer(
409
            rowHeaderDataLayer,
410
            compositeFreezeLayer,
411
            selectionLayer);
412

    
413
        IDataProvider cornerDataProvider =
414
                new DefaultCornerDataProvider(
415
                    columnHeaderDataProvider,
416
                    rowHeaderDataProvider);
417
        DataLayer cornerDataLayer = new DataLayer(cornerDataProvider);
418
        ILayer cornerLayer = new CornerLayer(
419
            cornerDataLayer,
420
            rowHeaderLayer,
421
            filterRowHeaderLayer);
422

    
423
        GridLayer gridLayer = new GridLayer(
424
                compositeFreezeLayer,
425
                filterRowHeaderLayer,
426
                rowHeaderLayer,
427
                cornerLayer);
428

    
429
        natTable.setLayer(gridLayer);
430
        topMostLayer = compositeFreezeLayer;
431
    }
432

    
433
    private Text createSearchBar(Composite parent) {
434

    
435
        Button button1 = new Button(parent, SWT.PUSH );
436
        GridData gridData2 = new GridData();
437
        gridData2.horizontalSpan = 1;
438
        gridData2.horizontalAlignment = SWT.RIGHT;
439

    
440
        button1.setLayoutData(gridData2);
441

    
442
        button1.setText(Messages.ChecklistEditor_DIST_STATUS);
443
        button1.setToolTipText(Messages.ChecklistEditor_DIST_STATUS_TOOLTIP);
444
        button1.addSelectionListener(new SelectionAdapter() {
445
            @Override
446
            public void widgetSelected(SelectionEvent event) {
447
                AvailableDistributionWizard availableDistributionWizard = new AvailableDistributionWizard();
448
                WizardDialog dialog = new WizardDialog(AbstractUtility.getShell(),
449
                        availableDistributionWizard);
450

    
451
                int open = dialog.open();
452
                if(open == 0){
453
                    reload();
454
                }
455
            }
456
        });
457

    
458
        button2 = new Button(parent, SWT.PUSH );
459
        GridData gridData3 = new GridData();
460
        gridData3.horizontalAlignment = SWT.RIGHT;
461

    
462
        button2.setLayoutData(gridData3);
463

    
464
        button2.setText(Messages.ChecklistEditor_DEFAULT_SOURCE);
465
        button2.setToolTipText(Messages.ChecklistEditor_DEFAULT_SOURCE_TOOLTIP);
466
        button2.addSelectionListener(new SelectionAdapter() {
467

    
468
            @Override
469
            public void widgetSelected(SelectionEvent event) {
470
                defaultSource = ReferenceSelectionDialog.select(AbstractUtility.getShell(), null);
471

    
472
                String defaultSourceStr = (defaultSource == null) ? "" : Messages.DistributionEditor_defaultSource + defaultSource.getTitleCache(); //$NON-NLS-1$
473
                if (defaultSourceStr.length()> 100){
474
                    defaultSourceStr = defaultSourceStr.substring(0, 98) + "..."; //$NON-NLS-1$
475
                }
476
                statusLabelSourceReference.setText(defaultSourceStr);
477

    
478
                button2.setBackground(AbstractUtility.getColor(Resources.COLOR_CONTROL_SELECTED));
479
//                EventUtility.postEvent(WorkbenchEventConstants.REFRESH_DETAILS, true);
480
                button3.setEnabled(true);
481
                button2.setText(Messages.ChecklistEditor_SWITCH_DEFAULT_SOURCE);
482
            }
483
        });
484

    
485
        parent.pack();
486
        return searchText;
487
    }
488
    /**
489
    * This method should only be called for adding new Distribution columns and reloading the table.<br>
490
    * It will hide the old distribution column and load the newly added columns.<br>
491
    * <p>
492
    * <b>Notice:</b> for data update please use <b>refresh()</b>
493
    *
494
    */
495
   public void reload(){
496
       this.areaToColumnIndexMap.clear();
497
       this.areas.clear();
498
       this.propertyToLabelMap.clear();
499
       createTable();
500
       natTable.redraw();
501
    }
502

    
503
    private void createTopComposite(Composite parent) {
504
        GridLayout gridLayout = new GridLayout(3, false);
505
        gridLayout.marginWidth = 0;
506
        gridLayout.marginHeight = 0;
507
        GridData gridData2 = new GridData();
508
        gridData2.horizontalSpan = 1;
509
        gridData2.horizontalAlignment = SWT.RIGHT;
510
        gridData2.horizontalIndent = 3;
511
        parent.setLayoutData(gridData2);
512
        parent.setLayout(gridLayout);
513
        searchText = createSearchBar(parent);
514

    
515

    
516
    }
517
    public void loadDistributions(List<TaxonDistributionDTO> taxonList) {
518
        if (this.taxonList == null){
519
            this.taxonList = new BasicEventList<>();
520
        }
521
       taxonList.stream().forEach(wrapper->DistributionEditor.this.taxonList.add(wrapper));
522
       statusLabel.setText(ELEMENT_COUNT + taxonList.size());
523
       createTaxonDistributionMap();
524
    }
525

    
526
    protected void createTaxonDistributionMap() {
527
        Iterator<TaxonDistributionDTO> iterator = this.taxonList.iterator();
528
        while (iterator.hasNext()){
529
            TaxonDistributionDTO dto = iterator.next();
530
            TaxonDescriptionDTO descriptionDto = dto.getDescriptionsWrapper();
531
            for (TaxonDescription desc: descriptionDto.getDescriptions()){
532
                if(this.part.getCdmEntitySession()!=null){
533
                    this.part.getCdmEntitySession().load(desc, true);
534
                }
535
                for (DescriptionElementBase descElement: desc.getElements()){
536
                    if (descElement instanceof Distribution){
537
                        Map<NamedArea, Set<DescriptionElementBase>> distributionsMap = taxonDistributionMap.get(dto.getTaxonUuid());
538

    
539
                        if (distributionsMap == null){
540
                            distributionsMap = new HashMap<>();
541
                            taxonDistributionMap.put(dto.getTaxonUuid(), distributionsMap);
542
                        }
543
                        Set<DescriptionElementBase> distributions = distributionsMap.get(((Distribution) descElement).getArea());
544
                        if (distributions == null){
545
                            distributions = new HashSet<>();
546
                            distributionsMap.put(((Distribution)descElement).getArea(), distributions);
547
                        }
548
                        distributions.add(descElement);
549
                    }
550
                }
551
            }
552
        }
553
    }
554

    
555
    private void initLabels() {
556

    
557
        int index = 2;
558
        if (isShowRank){
559
            index++;
560
        }
561

    
562
        loadNamedAreas();
563
        if (areas == null){
564
            areas = new TreeSet<>();
565
        }
566
        for (DefinedTermBase<?> area: areas) {
567
            this.areaToColumnIndexMap.put(index++, (NamedArea)area);
568
            String areaLabel;
569
            //TODO: adapt to preference
570
            Representation rep = area.getPreferredRepresentation(CdmStore.getDefaultLanguage());
571
            String label = rep.getLabel();
572
            if (label == null){
573
                label = area.getTitleCache();
574
            }
575
            if (PreferencesUtil.isShowIdInVocabularyInChecklistEditor()){
576
                if (area.getIdInVocabulary() != null){
577
                    areaLabel = area.getIdInVocabulary();
578
                } else{
579
                    areaLabel = label;
580
                }
581
            }else if (PreferencesUtil.isShowSymbol1InChecklistEditor()){
582
                if (area.getSymbol() != null){
583
                    areaLabel = area.getSymbol();
584
                } else{
585
                    areaLabel = label;
586
                }
587
            }else if (PreferencesUtil.isShowSymbol2InChecklistEditor()){
588
                if (area.getSymbol2() != null){
589
                    areaLabel = area.getSymbol2();
590
                } else{
591
                    areaLabel = label;
592
                }
593
            }else{
594
                areaLabel = label;
595
            }
596

    
597
            //String areaLabel = area.getLabel();
598
            String property = area.getUuid().toString();
599
            propertyToLabelMap.put(property, areaLabel);
600
        }
601
    }
602

    
603
    private SortedSet<NamedArea> loadNamedAreas() {
604
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
605

    
606
        String valuesAreas = PreferencesUtil.getStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), true);
607
        String values = PreferencesUtil.getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey());
608
        Set<UUID> uuidList = new HashSet<UUID>();
609
        String[] split;
610
        List<String> listValue;
611
        List<NamedArea> termlist = new ArrayList<>();
612
        if (values != null && values != "") { //$NON-NLS-1$
613
            split = values.split(";"); //$NON-NLS-1$
614
            listValue = Arrays.asList(split);
615

    
616
            UUID uuid;
617
            for(String s : listValue){
618
                uuid = UUID.fromString(s);
619
                uuidList.add(uuid);
620
            }
621
        }
622

    
623
        List<TermVocabulary<NamedArea>> vocs = new ArrayList<>();
624
        IVocabularyService service =  CdmStore.getService(IVocabularyService.class);
625
        if (uuidList.isEmpty()){
626
            List<TermVocabulary<NamedArea>> vocList = CdmStore.getService(IVocabularyService.class).findByTermType(TermType.NamedArea, null);
627
            vocs.addAll(vocList);
628
        }else{
629
            vocs= (List)service.find(uuidList);
630
        }
631
        for (TermVocabulary<NamedArea> voc: vocs){
632
            termlist.addAll((List)service.getTerms(voc, null, null, null, null).getRecords());
633
        }
634
        List<NamedArea> filteredList = new ArrayList<>();
635
        if (valuesAreas != null && valuesAreas != "") {
636
            split = valuesAreas.split(";"); //$NON-NLS-1$
637
            listValue = Arrays.asList(split);
638

    
639
            for (NamedArea area: termlist){
640
                if (listValue.contains(area.getUuid().toString())) {
641
                    filteredList.add(area);
642
                }
643
            }
644
        }else{
645
            filteredList.addAll(termlist);
646
        }
647

    
648
        TermOrder sortOrder = PreferencesUtil.getSortNamedAreasInDistributionEditor();
649
        if (sortOrder.equals(TermOrder.Natural)){
650
            areas =  getTermsOrderedByVocabularyOrder(filteredList);
651
        } else if (sortOrder.equals(TermOrder.IdInVoc)){
652
            areas = getTermsOrderedByIdInVocabulary(filteredList);
653
        }else{
654
            areas =  getTermsOrderedByLabels(filteredList, CdmStore.getDefaultLanguage());
655
        }
656

    
657
        return null;
658
    }
659

    
660
    public <T extends DefinedTermBase<T>> SortedSet<T> getTermsOrderedByLabels(List<T> listTerm,Language language){
661
        TermLanguageComparator<T> comp = new TermLanguageComparator<>(Language.DEFAULT(), language);
662
        SortedSet<T> result = new TreeSet<>(comp);
663
        if(listTerm != null){
664
            result.addAll(listTerm);
665
        }
666

    
667
        return result;
668
    }
669

    
670
    public <T extends DefinedTermBase<T>> SortedSet<T> getTermsOrderedByIdInVocabulary(List<T> namedAreas) {
671
        TermIdInVocabularyComparator<T> comp = new TermIdInVocabularyComparator<>();
672

    
673
        SortedSet<T> result = new TreeSet<>(comp);
674
        if(namedAreas != null){
675
            result.addAll(namedAreas);
676
        }
677
        return result;
678
    }
679

    
680
    public <T extends DefinedTermBase<T>> SortedSet<T> getTermsOrderedBySymbol(List<T> namedAreas) {
681
        TermSymbol1Comparator<T> comp = new TermSymbol1Comparator<>();
682

    
683
        SortedSet<T> result = new TreeSet<>(comp);
684
        if(namedAreas != null){
685
            result.addAll(namedAreas);
686
        }
687
        return result;
688
    }
689

    
690
    public <T extends DefinedTermBase<T>> SortedSet<T> getTermsOrderedBySymbol2(List<T> namedAreas) {
691
        TermSymbol2Comparator<T> comp = new TermSymbol2Comparator<>();
692

    
693
        SortedSet<T> result = new TreeSet<>(comp);
694
        if(namedAreas != null){
695
            result.addAll(namedAreas);
696
        }
697
        return result;
698
    }
699

    
700
    public <T extends DefinedTermBase<T>> SortedSet<T> getTermsOrderedByVocabularyOrder(List<T> listAreas){
701
        OrderedTermComparator<T> comp = new OrderedTermComparator<>();
702
        boolean allOrderedTerms = true;
703
        List<TermVocabulary<T>> alreadyOrderIndexNull = new ArrayList<>();
704
        for (T term: listAreas){
705
            if (!(term instanceof OrderedTermBase)){
706
                allOrderedTerms = false;
707
                break;
708
            }else if (((OrderedTermBase<?>)term).getOrderIndex() == 0){
709
                if(alreadyOrderIndexNull.contains(term.getVocabulary())) {
710
                    allOrderedTerms = false;
711
                    break;
712
                }else{
713
                    alreadyOrderIndexNull.add(term.getVocabulary());
714
                }
715
            }
716
        }
717
        if (allOrderedTerms){
718
            SortedSet<T> result = new TreeSet<>(comp);
719
            result.addAll(listAreas);
720
            return result;
721
        }else{
722
            return getTermsOrderedByLabels(listAreas, PreferencesUtil.getGlobalLanguage());
723
        }
724
    }
725

    
726
    private void registerHandlersAndListeners(AbstractLayer topMostLayer) {
727
        //selection listener
728
        E4SelectionListener<?> selectionListener = new DistributionCellSelectionListener(part.getSelectionService(),
729
                selectionLayer, bodyDataProvider, part);
730
        selectionLayer.addLayerListener(selectionListener);
731
        selectionListener.setFullySelectedRowsOnly(false);
732

    
733
        //register handler for view configuration menu
734
      //  natTable.registerCommandHandler(toolbar.getDisplayPersistenceDialogCommandHandler());
735
    }
736

    
737
    public IRowDataProvider<TaxonDistributionDTO> getBodyDataProvider() {
738
        return bodyDataProvider;
739
    }
740

    
741
    public void setDirty() {
742
        part.setDirty();
743
    }
744

    
745
    @Override
746
    public Reference getDefaultSource(){
747
        return defaultSource;
748
    }
749

    
750
//    /**
751
//     * @param result
752
//     */
753
//    public void reloadDistributions() {
754
//       loadDistributions(taxonList);
755
//
756
//    }
757
}
(6-6/19)