Project

General

Profile

Download (28.9 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 javax.inject.Inject;
24

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

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

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

    
114

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

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

    
124
    private static final Logger logger = Logger.getLogger(DistributionEditor.class);
125
    @Inject
126
    private EMenuService menuService;
127
    private NatTable natTable;
128
    private Label statusLabel;
129
    private Label statusLabelSourceReference;
130
    private Reference defaultSource;
131

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

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

    
138
    private boolean isShowRank = false;
139
    private Integer countNodes;
140
    private Text searchText;
141

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

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

    
147

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

    
155
    private SelectionLayer selectionLayer;
156

    
157

    
158

    
159
 //  private FixedSummaryRowLayer summaryRowLayer;
160

    
161

    
162
    /**
163
     * @param parent
164
     * @param style
165
     */
166
    public DistributionEditor(Composite parent, DistributionEditorPart part) {
167
        super(parent, SWT.NULL);
168
        isShowRank = PreferencesUtil.getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
169
        this.part = part;
170
        this.setLayout(new GridLayout());
171
        GridLayoutFactory.fillDefaults().applyTo(parent);
172

    
173
        Composite topComposite = new Composite(parent, SWT.NONE);
174
        createTopComposite(topComposite);
175

    
176

    
177

    
178
        natTable = new NatTable(parent, false);
179
        parent.pack();
180

    
181
        Composite bottomComposite = new Composite(parent, SWT.NONE);
182
        GridLayoutFactory.fillDefaults().applyTo(bottomComposite);
183
        createStatusBar(bottomComposite);
184
    }
185

    
186
    public boolean isShowRank() {
187
        return isShowRank;
188
    }
189

    
190
    public void setShowRank(boolean isShowRank) {
191
        this.isShowRank = isShowRank;
192
    }
193

    
194
    public int getFirstDataColumnIndex() {
195
        return firstDataColumnIndex;
196
    }
197

    
198
    public void setFirstDataColumnIndex(int firstDataColumnIndex) {
199
        this.firstDataColumnIndex = firstDataColumnIndex;
200
    }
201

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

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

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

    
214

    
215
    public void setAreaToColumnIndexMap(Map<Integer, NamedArea> areaToColumnIndexMap) {
216
        this.areaToColumnIndexMap = areaToColumnIndexMap;
217
    }
218

    
219

    
220
    public List<TaxonDistributionDTO> getDescriptionsToSave() {
221
        return descriptionsToSave;
222
    }
223

    
224
    public void setDescriptionsToSave(List<TaxonDistributionDTO> descriptionsToSave) {
225
        this.descriptionsToSave = descriptionsToSave;
226
    }
227

    
228

    
229

    
230
    private void createStatusBar(Composite composite) {
231
        GridData gridData = new GridData();
232
        gridData.horizontalSpan = 2;
233
        gridData.grabExcessHorizontalSpace = true;
234
        gridData.horizontalAlignment = GridData.FILL;
235
        GridLayout gridLayout = new GridLayout();
236
        gridLayout.numColumns = 2;
237
        composite.setLayoutData(gridData);
238
        composite.setLayout(gridLayout);
239

    
240

    
241
        gridData = new GridData();
242
        gridData.horizontalSpan = 1;
243
        gridData.grabExcessHorizontalSpace = true;
244
        gridData.horizontalAlignment = GridData.FILL;
245

    
246
        statusLabel = new Label(composite, SWT.LEFT);
247
        statusLabel.setText(ELEMENT_COUNT + (taxonList != null ? taxonList.size() : UNKNOWN));
248
        statusLabel.setLayoutData(gridData);
249

    
250
        statusLabelSourceReference = new Label(composite, SWT.RIGHT);
251

    
252
        statusLabelSourceReference.setLayoutData(gridData);
253

    
254
        if (defaultSource != null){
255
            statusLabelSourceReference.setText(Messages.DistributionEditor_defaultSource + defaultSource.getAbbrevTitle() != null? defaultSource.getAbbrevTitle() : defaultSource.getAbbrevTitleCache());
256

    
257
        }
258
    }
259

    
260
    private void applyStyles(){
261
        ModernNatTableThemeConfiguration configuration = new ModernNatTableThemeConfiguration();
262
        configuration.summaryRowHAlign = HorizontalAlignmentEnum.CENTER;
263
        // NOTE: Getting the colors and fonts from the GUIHelper ensures that
264
        // they are disposed properly (required by SWT)
265
        configuration.cHeaderBgColor = GUIHelper.getColor(211, 211, 211);
266
        configuration.rHeaderBgColor = GUIHelper.getColor(211, 211, 211);
267
        natTable.addConfiguration(configuration);
268

    
269
    }
270

    
271
    private void configureNatTable(ConfigRegistry configRegistry,
272
            AbstractLayer topMostLayer) {
273
        /**
274
         * CONFIGURATION
275
         */
276
        natTable.setConfigRegistry(configRegistry);
277

    
278
        applyStyles();
279

    
280
        //add default configuration because autoconfigure is set to false in constructor
281
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
282

    
283

    
284

    
285
        // override the default sort configuration and change the mouse bindings
286
        // to sort on a single click
287

    
288
        natTable.addConfiguration(new SingleClickSortConfiguration());
289
        natTable.addConfiguration(new FilterRowConfiguration(this));
290

    
291
        // add the header menu configuration for adding the column header menu
292
        // with hide/show actions
293
        natTable.addConfiguration(new DistributionEditorHeaderMenuConfiguration(natTable));
294

    
295
        // add custom configuration for data conversion and add column labels to viewport layer
296
        topMostLayer.addConfiguration(new DistributionCellEditorDataConversionConfiguration(this));
297

    
298
        natTable.configure();
299
    }
300

    
301
    public void createTable(){
302
        /**
303
         * layers
304
         */
305

    
306
        createLayers();
307

    
308
        /**
309
         * configuration
310
         */
311
        configureNatTable( configRegistry, topMostLayer);
312

    
313
        /**
314
         * handlers and listeners
315
         */
316
        registerHandlersAndListeners(topMostLayer);
317
        FreezeHelper.freeze(freezeLayer, bodyLayerStack.getViewPortLayer(),
318
                new PositionCoordinate(bodyLayerStack.getViewPortLayer(), 0, 0),
319
                new PositionCoordinate(bodyLayerStack.getViewPortLayer(), 0, -1));
320
        //grab all space
321
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
322

    
323
        this.layout();
324
        natTable.doCommand(new ClientAreaResizeCommand(natTable));
325
      //  boolean ok = natTable.doCommand(new ClientAreaResizeCommand(natTable));
326

    
327
    }
328

    
329

    
330
    private void createLayers() {
331

    
332
        DistributionColumnAccessor columnPropertyAccessor = new DistributionColumnAccessor(this);
333

    
334
        DistributionEditorConfigLabelAccumulator labelAccumulator = new DistributionEditorConfigLabelAccumulator(this);
335
        bodyLayerStack = new BodyLayerStack<>(taxonList, columnPropertyAccessor, new TaxonDistributionDtoComparator(), labelAccumulator);
336

    
337
        bodyDataProvider = bodyLayerStack.getBodyDataProvider();
338

    
339

    
340

    
341
        propertyToLabelMap.put(TAXON_COLUMN, Messages.ChecklistEditor_TAXON);
342
        if (isShowRank){
343
            propertyToLabelMap.put(RANK_COLUMN, Messages.ChecklistEditor_RANK);
344
        }
345
        configRegistry = new ConfigRegistry();
346

    
347
        initLabels();
348
        this.selectionLayer = bodyLayerStack.getSelectionLayer();
349

    
350

    
351

    
352
        freezeLayer = new FreezeLayer(selectionLayer);
353
        final CompositeFreezeLayer compositeFreezeLayer = new CompositeFreezeLayer(
354
                freezeLayer,  bodyLayerStack.getViewPortLayer(), selectionLayer);
355

    
356
        // as the selection mouse bindings are registered for the region label
357
        // GridRegion.BODY
358
        // we need to set that region label to the viewport so the selection via mouse
359
        // is working correctly
360
        compositeFreezeLayer.setRegionName(GridRegion.BODY);
361

    
362

    
363
        IDataProvider columnHeaderDataProvider =
364
                new DefaultColumnHeaderDataProvider(propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
365
        DataLayer columnHeaderDataLayer = new DefaultColumnHeaderDataLayer(columnHeaderDataProvider);
366
        ILayer columnHeaderLayer = new ColumnHeaderLayer(
367
            columnHeaderDataLayer,
368
            compositeFreezeLayer,
369
            selectionLayer);
370

    
371
        FilterRowHeaderComposite<TaxonDistributionDTO> filterRowHeaderLayer =
372
                new FilterRowHeaderComposite<>(
373
                        new DefaultGlazedListsFilterStrategy<>(
374
                                bodyLayerStack.getFilterList(),
375
                                columnPropertyAccessor,
376
                                configRegistry),
377
                        columnHeaderLayer,
378
                        columnHeaderDataLayer.getDataProvider(),
379
                        configRegistry);
380

    
381

    
382

    
383
     // build the row header layer stack
384
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
385
        DataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
386
        ILayer rowHeaderLayer = new RowHeaderLayer(
387
            rowHeaderDataLayer,
388
            compositeFreezeLayer,
389
            selectionLayer);
390

    
391

    
392

    
393
        IDataProvider cornerDataProvider =
394
                new DefaultCornerDataProvider(
395
                    columnHeaderDataProvider,
396
                    rowHeaderDataProvider);
397
        DataLayer cornerDataLayer = new DataLayer(cornerDataProvider);
398
        ILayer cornerLayer = new CornerLayer(
399
            cornerDataLayer,
400
            rowHeaderLayer,
401
            filterRowHeaderLayer);
402

    
403
        GridLayer gridLayer = new GridLayer(
404
                compositeFreezeLayer,
405
                filterRowHeaderLayer,
406
                rowHeaderLayer,
407
                cornerLayer);
408

    
409
        natTable.setLayer(gridLayer);
410

    
411
        topMostLayer = compositeFreezeLayer;
412

    
413

    
414
    }
415

    
416
    /**
417
     * @param parent
418
     * @return
419
     */
420
    private Text createSearchBar(Composite parent) {
421

    
422
        Button button1 = new Button(parent, SWT.PUSH );
423
        GridData gridData2 = new GridData();
424
        gridData2.horizontalSpan = 1;
425
        gridData2.horizontalAlignment = SWT.RIGHT;
426

    
427
        button1.setLayoutData(gridData2);
428

    
429

    
430
        button1.setText(Messages.ChecklistEditor_DIST_STATUS);
431
        button1.setToolTipText(Messages.ChecklistEditor_DIST_STATUS_TOOLTIP);
432
        button1.addSelectionListener(new SelectionAdapter() {
433
            @Override
434
            public void widgetSelected(SelectionEvent event) {
435
                AvailableDistributionWizard availableDistributionWizard = new AvailableDistributionWizard();
436
                WizardDialog dialog = new WizardDialog(StoreUtil.getShell(),
437
                        availableDistributionWizard);
438

    
439
                int open = dialog.open();
440
                if(open == 0){
441
                    reload();
442
                }
443
            }
444
        });
445

    
446
        Button button2 = new Button(parent, SWT.PUSH );
447
        GridData gridData3 = new GridData();
448
        gridData2.horizontalSpan = 1;
449
        button2.setLayoutData(gridData3);
450

    
451

    
452
        button2.setText(Messages.ChecklistEditor_DEFAULT_SOURCE);
453
        button2.setToolTipText(Messages.ChecklistEditor_DEFAULT_SOURCE_TOOLTIP);
454
        button2.addSelectionListener(new SelectionAdapter() {
455

    
456
            @Override
457
            public void widgetSelected(SelectionEvent event) {
458
                defaultSource = ReferenceSelectionDialog.select(AbstractUtility.getShell(), null);
459

    
460
                String defaultSourceStr = (defaultSource == null) ? "" : Messages.DistributionEditor_defaultSource + defaultSource.getTitleCache(); //$NON-NLS-1$
461
                if (defaultSourceStr.length()> 100){
462
                    defaultSourceStr = defaultSourceStr.substring(0, 98) + "..."; //$NON-NLS-1$
463
                }
464
                statusLabelSourceReference.setText(defaultSourceStr);
465

    
466
                button2.setBackground(EditorUtil.getColor(Resources.COLOR_CONTROL_SELECTED));
467
                EventUtility.postEvent(WorkbenchEventConstants.REFRESH_DETAILS, true);
468
            }
469

    
470
        });
471

    
472
        Button button3 = new Button(parent, SWT.PUSH );
473

    
474
        button3.setLayoutData(gridData3);
475
        button3.setText(Messages.ChecklistEditor_REMOVE_DEFAULT_SOURCE);
476
        button2.setToolTipText(Messages.ChecklistEditor_REMOVE_DEFAULT_SOURCE_TOOLTIP);
477
        button3.addSelectionListener(new SelectionAdapter() {
478

    
479
            @Override
480
            public void widgetSelected(SelectionEvent event) {
481
                defaultSource = null;
482

    
483
                String defaultSourceStr = (defaultSource == null) ? "" : Messages.DistributionEditor_defaultSource + defaultSource.getTitleCache(); //$NON-NLS-1$
484
                if (defaultSourceStr.length()> 100){
485
                    defaultSourceStr = defaultSourceStr.substring(0, 98) + "..."; //$NON-NLS-1$
486
                }
487
                statusLabelSourceReference.setText(defaultSourceStr);
488

    
489
                button3.setBackground(EditorUtil.getColor(Resources.COLOR_CONTROL_SELECTED));
490
            }
491

    
492
        });
493

    
494
        parent.pack();
495
        return searchText;
496
    }
497
    /**
498
    * This method should only be called for adding new Distribution columns and reloading the table.<br>
499
    * It will hide the old distribution column and load the newly added columns.<br>
500
    * <p>
501
    * <b>Notice:</b> for data update please use <b>refresh()</b>
502
    *
503
    */
504
   @SuppressWarnings({ "unchecked", "rawtypes" })
505
   public void reload(){
506
       this.areaToColumnIndexMap.clear();
507
       this.areas.clear();
508
       this.propertyToLabelMap.clear();
509
       createTable();
510
       natTable.redraw();
511
    }
512

    
513
    /**
514
     * @param parent
515
     */
516
    private void createTopComposite(Composite parent) {
517
        GridLayout gridLayout = new GridLayout(3, false);
518
        gridLayout.marginWidth = 0;
519
        gridLayout.marginHeight = 0;
520
        GridData gridData2 = new GridData();
521
        gridData2.horizontalSpan = 1;
522
        gridData2.horizontalAlignment = SWT.RIGHT;
523
        gridData2.horizontalIndent = 3;
524
        parent.setLayoutData(gridData2);
525
        parent.setLayout(gridLayout);
526
        searchText = createSearchBar(parent);
527

    
528

    
529
    }
530
    public void loadDistributions(List<TaxonDistributionDTO> taxonList) {
531
        if (this.taxonList == null){
532
            this.taxonList = new BasicEventList<>();
533
        }
534
       taxonList.stream().forEach(wrapper->DistributionEditor.this.taxonList.add(wrapper));
535
       statusLabel.setText(ELEMENT_COUNT + (taxonList != null ? taxonList.size() : UNKNOWN));
536
       createTaxonDistributionMap();
537
    }
538

    
539
    protected void createTaxonDistributionMap() {
540
        Iterator<TaxonDistributionDTO> iterator = this.taxonList.iterator();
541
           while (iterator.hasNext()){
542
               TaxonDistributionDTO dto = iterator.next();
543
               TaxonDescriptionDTO descriptionDto = dto.getDescriptionsWrapper();
544
               for (TaxonDescription desc: descriptionDto.getDescriptions()){
545
                   if(this.part.getCdmEntitySession()!=null){
546
                       this.part.getCdmEntitySession().load(desc, true);
547
                   }
548
                   for (DescriptionElementBase descElement: desc.getElements()){
549
                       if (descElement instanceof Distribution){
550
                           Map<NamedArea, Set<DescriptionElementBase>> distributionsMap = taxonDistributionMap.get(dto.getTaxonUuid());
551

    
552
                           if (distributionsMap == null){
553
                               distributionsMap = new HashMap();
554
                               taxonDistributionMap.put(dto.getTaxonUuid(), distributionsMap);
555
                           }
556
                           Set<DescriptionElementBase> distributions = distributionsMap.get(((Distribution) descElement).getArea());
557
                           if (distributions == null){
558
                               distributions = new HashSet();
559
                               distributionsMap.put(((Distribution)descElement).getArea(), distributions);
560
                           }
561
                           distributions.add(descElement);
562

    
563
                       }
564
                   }
565
               }
566
           }
567
    }
568

    
569

    
570

    
571

    
572

    
573
    private void initLabels() {
574

    
575
        int index = 1;
576
        if (isShowRank){
577
            index++;
578
        }
579

    
580
        loadNamedAreas();
581
        if (areas == null){
582
            areas = new TreeSet<>();
583
        }
584
        for (DefinedTermBase area: areas) {
585
            this.areaToColumnIndexMap.put(index++, (NamedArea)area);
586
            String areaLabel;
587
            //TODO: adapt to preference
588
            Representation rep = area.getPreferredRepresentation(CdmStore.getDefaultLanguage());
589
            String label = rep.getLabel();
590
            if (label == null){
591
                label = area.getTitleCache();
592
            }
593
            if (PreferencesUtil.isShowIdInVocabularyInChecklistEditor()){
594
                if (area.getIdInVocabulary() != null){
595
                    areaLabel = area.getIdInVocabulary();
596
                } else{
597
                    areaLabel = label;
598
                }
599
            }else if (PreferencesUtil.isShowSymbol1InChecklistEditor()){
600
                if (area.getSymbol() != null){
601
                    areaLabel = area.getSymbol();
602
                } else{
603
                    areaLabel = label;
604
                }
605
            }else if (PreferencesUtil.isShowSymbol2InChecklistEditor()){
606
                if (area.getSymbol2() != null){
607
                    areaLabel = area.getSymbol2();
608
                } else{
609
                    areaLabel = label;
610
                }
611
            }else{
612
                areaLabel = label;
613
            }
614

    
615

    
616
            //String areaLabel = area.getLabel();
617
            String property = area.getUuid().toString();
618
            propertyToLabelMap.put(property, areaLabel);
619
        }
620

    
621
    }
622

    
623
    private SortedSet<DefinedTermBase> loadNamedAreas() {
624
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
625

    
626
        String valuesAreas = PreferencesUtil.getStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), true);
627
        String values = PreferencesUtil.getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey());
628
        Set<UUID> uuidList = new HashSet<UUID>();
629
        String[] split;
630
        List<String> listValue;
631
        List<DefinedTermBase> termlist = new ArrayList<DefinedTermBase>();
632
        if (values != null && values != "") { //$NON-NLS-1$
633
            split = values.split(";"); //$NON-NLS-1$
634
            listValue = Arrays.asList(split);
635

    
636

    
637
            UUID uuid;
638
            for(String s : listValue){
639
                uuid = UUID.fromString(s);
640
                uuidList.add(uuid);
641

    
642
            }
643
        }
644

    
645
        List<TermVocabulary> vocs = new ArrayList<>();
646
        IVocabularyService service =  CdmStore.getService(IVocabularyService.class);
647
        if (uuidList.isEmpty()){
648
            List<TermVocabulary<DefinedTermBase>> vocList = CdmStore.getService(IVocabularyService.class).findByTermType(TermType.NamedArea, null);
649
            vocs.addAll(vocList);
650
        }else{
651
            vocs= service.find(uuidList);
652
        }
653
        for (TermVocabulary voc: vocs){
654
            termlist.addAll(service.getTerms(voc, null, null, null, null).getRecords());
655
        }
656
        List<DefinedTermBase> filteredList = new ArrayList();
657
        if (valuesAreas != null && valuesAreas != "") {
658
            split = valuesAreas.split(";"); //$NON-NLS-1$
659
            listValue = Arrays.asList(split);
660

    
661
            for (DefinedTermBase area: termlist){
662
                if (listValue.contains(area.getUuid().toString())) {
663
                    filteredList.add(area);
664
                }
665

    
666
            }
667
        }else{
668
            filteredList.addAll(termlist);
669
        }
670

    
671

    
672
        TermOrder sortOrder = PreferencesUtil.getSortNamedAreasInDistributionEditor();
673
        if (sortOrder.equals(TermOrder.Natural)){
674
            areas =  getTermsOrderedByVocabularyOrder(filteredList);
675
        } else if (sortOrder.equals(TermOrder.IdInVoc)){
676
            areas = getTermsOrderedByIdInVocabulary(filteredList);
677
        }else{
678
            areas =  getTermsOrderedByLabels(filteredList, CdmStore.getDefaultLanguage());
679
        }
680

    
681
        return null;
682
    }
683

    
684
    public SortedSet<DefinedTermBase> getTermsOrderedByLabels(List<DefinedTermBase> listTerm,Language language){
685
        TermLanguageComparator<?> comp = new TermLanguageComparator<>();
686
        comp.setCompareLanguage(language);
687
        SortedSet<DefinedTermBase> result = new TreeSet(comp);
688
        if(listTerm != null){
689
            result.addAll(listTerm);
690
        }
691

    
692
        return result;
693
    }
694

    
695
    public SortedSet<DefinedTermBase> getTermsOrderedByIdInVocabulary(List<DefinedTermBase> namedAreas) {
696
        TermIdInVocabularyComparator<?> comp = new TermIdInVocabularyComparator<>();
697

    
698
        SortedSet<DefinedTermBase> result = new TreeSet(comp);
699
        if(namedAreas != null){
700
            result.addAll(namedAreas);
701
        }
702
        return result;
703
    }
704

    
705
    public SortedSet<DefinedTermBase> getTermsOrderedByVocabularyOrder(List<DefinedTermBase> listAreas){
706
        HashMap<TermVocabulary<DefinedTermBase>, List<DefinedTermBase>> vocs = new HashMap<>();
707
        OrderedTermComparator<?> comp = new OrderedTermComparator<>();
708
        boolean allOrderedTerms = true;
709
        List<TermVocabulary> alreadyOrderIndexNull = new ArrayList<>();
710
        for (DefinedTermBase term: listAreas){
711
            if (!(term instanceof OrderedTermBase)){
712
                allOrderedTerms = false;
713
                break;
714
            }else if (((OrderedTermBase)term).getOrderIndex() == 0){
715
                if(alreadyOrderIndexNull.contains(term.getVocabulary())) {
716
                    allOrderedTerms = false;
717
                    break;
718
                }else{
719
                    alreadyOrderIndexNull.add(term.getVocabulary());
720
                }
721

    
722

    
723
            }
724
        }
725
        if (allOrderedTerms){
726
            SortedSet<DefinedTermBase> result = new TreeSet(comp.reversed());
727
            result.addAll(listAreas);
728
            return result;
729
        }else{
730
            return getTermsOrderedByLabels(listAreas, PreferencesUtil.getGlobalLanguage());
731
        }
732

    
733

    
734
    }
735

    
736
    private void registerHandlersAndListeners(AbstractLayer topMostLayer) {
737
        //selection listener
738
        E4SelectionListener selectionListener = new DistributionCellSelectionListener(part.getSelectionService(),
739
                selectionLayer, bodyDataProvider, part);
740
        selectionLayer.addLayerListener(selectionListener);
741
        selectionListener.setFullySelectedRowsOnly(false);
742

    
743
        //register handler for view configuration menu
744
      //  natTable.registerCommandHandler(toolbar.getDisplayPersistenceDialogCommandHandler());
745
    }
746

    
747
    /**
748
     * @return
749
     */
750
    public IRowDataProvider<TaxonDistributionDTO> getBodyDataProvider() {
751
        return bodyDataProvider;
752
    }
753

    
754
    public void setDirty() {
755
        part.setDirty();
756
    }
757

    
758
    @Override
759
    public Reference getDefaultSource(){
760
        return defaultSource;
761
    }
762

    
763
//    /**
764
//     * @param result
765
//     */
766
//    public void reloadDistributions() {
767
//       loadDistributions(taxonList);
768
//
769
//    }
770

    
771

    
772

    
773
}
(5-5/18)