Project

General

Profile

Download (28.5 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.DefinedTermBase;
79
import eu.etaxonomy.cdm.model.common.Language;
80
import eu.etaxonomy.cdm.model.common.OrderedTermBase;
81
import eu.etaxonomy.cdm.model.common.OrderedTermComparator;
82
import eu.etaxonomy.cdm.model.common.Representation;
83
import eu.etaxonomy.cdm.model.common.TermIdInVocabularyComparator;
84
import eu.etaxonomy.cdm.model.common.TermLanguageComparator;
85
import eu.etaxonomy.cdm.model.common.TermType;
86
import eu.etaxonomy.cdm.model.common.TermVocabulary;
87
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
88
import eu.etaxonomy.cdm.model.description.Distribution;
89
import eu.etaxonomy.cdm.model.description.TaxonDescription;
90
import eu.etaxonomy.cdm.model.location.NamedArea;
91
import eu.etaxonomy.cdm.model.metadata.PreferencePredicate;
92
import eu.etaxonomy.cdm.model.reference.Reference;
93
import eu.etaxonomy.taxeditor.editor.EditorUtil;
94
import eu.etaxonomy.taxeditor.editor.l10n.Messages;
95
import eu.etaxonomy.taxeditor.model.AbstractUtility;
96
import eu.etaxonomy.taxeditor.preference.EditorPreferencePredicate;
97
import eu.etaxonomy.taxeditor.preference.PreferencesUtil;
98
import eu.etaxonomy.taxeditor.preference.Resources;
99
import eu.etaxonomy.taxeditor.preference.TermOrder;
100
import eu.etaxonomy.taxeditor.preference.wizard.AvailableDistributionWizard;
101
import eu.etaxonomy.taxeditor.store.CdmStore;
102
import eu.etaxonomy.taxeditor.store.StoreUtil;
103
import eu.etaxonomy.taxeditor.ui.dialog.selection.ReferenceSelectionDialog;
104

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

    
112

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

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

    
122
    private static final Logger logger = Logger.getLogger(DistributionEditor.class);
123
    @Inject
124
    private EMenuService menuService;
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 Integer countNodes;
138
    private Text searchText;
139

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

    
143
    List<TaxonDistributionDTO> descriptionsToSave = new ArrayList<>();
144

    
145

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

    
153
    private SelectionLayer selectionLayer;
154

    
155

    
156

    
157
 //  private FixedSummaryRowLayer summaryRowLayer;
158

    
159

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

    
171
        Composite topComposite = new Composite(parent, SWT.NONE);
172
        createTopComposite(topComposite);
173

    
174

    
175

    
176
        natTable = new NatTable(parent, false);
177
        parent.pack();
178

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

    
184
    public boolean isShowRank() {
185
        return isShowRank;
186
    }
187

    
188
    public void setShowRank(boolean isShowRank) {
189
        this.isShowRank = isShowRank;
190
    }
191

    
192
    public int getFirstDataColumnIndex() {
193
        return firstDataColumnIndex;
194
    }
195

    
196
    public void setFirstDataColumnIndex(int firstDataColumnIndex) {
197
        this.firstDataColumnIndex = firstDataColumnIndex;
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

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

    
217

    
218
    public List<TaxonDistributionDTO> getDescriptionsToSave() {
219
        return descriptionsToSave;
220
    }
221

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

    
226

    
227

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

    
238

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

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

    
248
        statusLabelSourceReference = new Label(composite, SWT.RIGHT);
249

    
250
        statusLabelSourceReference.setLayoutData(gridData);
251

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

    
255
        }
256
    }
257

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

    
267
    }
268

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

    
276
        applyStyles();
277

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

    
281

    
282

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

    
286
        natTable.addConfiguration(new SingleClickSortConfiguration());
287
        natTable.addConfiguration(new FilterRowConfiguration(this));
288

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

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

    
296
        natTable.configure();
297
    }
298

    
299
    public void createTable(){
300
        /**
301
         * layers
302
         */
303

    
304
        createLayers();
305

    
306
        /**
307
         * configuration
308
         */
309
        configureNatTable( configRegistry, topMostLayer);
310

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

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

    
325
    }
326

    
327

    
328
    private void createLayers() {
329

    
330
        DistributionColumnAccessor columnPropertyAccessor = new DistributionColumnAccessor(this);
331

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

    
335
        bodyDataProvider = bodyLayerStack.getBodyDataProvider();
336

    
337

    
338

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

    
345
        initLabels();
346
        this.selectionLayer = bodyLayerStack.getSelectionLayer();
347

    
348

    
349

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

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

    
360

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

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

    
379

    
380

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

    
389

    
390

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

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

    
407
        natTable.setLayer(gridLayer);
408

    
409
        topMostLayer = compositeFreezeLayer;
410

    
411

    
412
    }
413

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

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

    
425
        button1.setLayoutData(gridData2);
426

    
427

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

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

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

    
449

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

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

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

    
464
                button2.setBackground(EditorUtil.getColor(Resources.COLOR_CONTROL_SELECTED));
465
            }
466

    
467
        });
468

    
469
        Button button3 = new Button(parent, SWT.PUSH );
470

    
471
        button3.setLayoutData(gridData3);
472
        button3.setText(Messages.ChecklistEditor_REMOVE_DEFAULT_SOURCE);
473
        button2.setToolTipText(Messages.ChecklistEditor_REMOVE_DEFAULT_SOURCE_TOOLTIP);
474
        button3.addSelectionListener(new SelectionAdapter() {
475

    
476
            @Override
477
            public void widgetSelected(SelectionEvent event) {
478
                defaultSource = null;
479

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

    
486
                button3.setBackground(EditorUtil.getColor(Resources.COLOR_CONTROL_SELECTED));
487
            }
488

    
489
        });
490

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

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

    
525

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

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

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

    
560
                       }
561
                   }
562
               }
563
           }
564
    }
565

    
566

    
567

    
568

    
569

    
570
    private void initLabels() {
571

    
572
        int index = 1;
573
        if (isShowRank){
574
            index++;
575
        }
576

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

    
612

    
613
            //String areaLabel = area.getLabel();
614
            String property = areaLabel;
615
            propertyToLabelMap.put(property, areaLabel);
616
        }
617

    
618
    }
619

    
620
    private SortedSet<DefinedTermBase> loadNamedAreas() {
621
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
622

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

    
633

    
634
            UUID uuid;
635
            for(String s : listValue){
636
                uuid = UUID.fromString(s);
637
                uuidList.add(uuid);
638

    
639
            }
640
        }
641

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

    
661
        }
662
        String sortOrder = PreferencesUtil.getSortNamedAreasInDistributionEditor();
663
        if (sortOrder.equals(TermOrder.Natural.getKey())){
664
            areas =  getTermsOrderedByVocabularyOrder(filteredList);
665
        } else if (sortOrder.equals(TermOrder.IdInVoc.getKey())){
666
            areas = getTermsOrderedByIdInVocabulary(filteredList);
667
        }else{
668
            areas =  getTermsOrderedByLabels(filteredList, CdmStore.getDefaultLanguage());
669
        }
670

    
671
        return null;
672
    }
673

    
674
    public SortedSet<DefinedTermBase> getTermsOrderedByLabels(List<DefinedTermBase> listTerm,Language language){
675
        TermLanguageComparator<?> comp = new TermLanguageComparator<>();
676
        comp.setCompareLanguage(language);
677
        SortedSet<DefinedTermBase> result = new TreeSet(comp);
678
        if(listTerm != null){
679
            result.addAll(listTerm);
680
        }
681

    
682
        return result;
683
    }
684

    
685
    public SortedSet<DefinedTermBase> getTermsOrderedByIdInVocabulary(List<DefinedTermBase> namedAreas) {
686
        TermIdInVocabularyComparator<?> comp = new TermIdInVocabularyComparator<>();
687

    
688
        SortedSet<DefinedTermBase> result = new TreeSet(comp);
689
        if(namedAreas != null){
690
            result.addAll(namedAreas);
691
        }
692
        return result;
693
    }
694

    
695
    public SortedSet<DefinedTermBase> getTermsOrderedByVocabularyOrder(List<DefinedTermBase> listAreas){
696
        HashMap<TermVocabulary<DefinedTermBase>, List<DefinedTermBase>> vocs = new HashMap<>();
697
        OrderedTermComparator<?> comp = new OrderedTermComparator<>();
698
        boolean allOrderedTerms = true;
699
        List<TermVocabulary> alreadyOrderIndexNull = new ArrayList<>();
700
        for (DefinedTermBase term: listAreas){
701
            if (!(term instanceof OrderedTermBase)){
702
                allOrderedTerms = false;
703
                break;
704
            }else if (((OrderedTermBase)term).getOrderIndex() == 0){
705
                if(alreadyOrderIndexNull.contains(term.getVocabulary())) {
706
                    allOrderedTerms = false;
707
                    break;
708
                }else{
709
                    alreadyOrderIndexNull.add(term.getVocabulary());
710
                }
711

    
712

    
713
            }
714
        }
715
        if (allOrderedTerms){
716
            SortedSet<DefinedTermBase> result = new TreeSet(comp.reversed());
717
            result.addAll(listAreas);
718
            return result;
719
        }else{
720
            return getTermsOrderedByLabels(listAreas, PreferencesUtil.getGlobalLanguage());
721
        }
722

    
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
    /**
738
     * @return
739
     */
740
    public IRowDataProvider<TaxonDistributionDTO> getBodyDataProvider() {
741
        return bodyDataProvider;
742
    }
743

    
744
    public void setDirty() {
745
        part.setDirty();
746
    }
747

    
748
    public Reference getDefaultSource(){
749
        return defaultSource;
750
    }
751

    
752
//    /**
753
//     * @param result
754
//     */
755
//    public void reloadDistributions() {
756
//       loadDistributions(taxonList);
757
//
758
//    }
759

    
760

    
761

    
762
}
(8-8/20)