Project

General

Profile

Download (29.6 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.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.store.StoreUtil;
104
import eu.etaxonomy.taxeditor.ui.dialog.selection.ReferenceSelectionDialog;
105

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

    
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
    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
    Button button3;
143

    
144
    EventList<TaxonDistributionDTO> taxonList;
145
    String actualNameCache = null;
146
    Map<UUID,Map<NamedArea,Set<DescriptionElementBase>>> taxonDistributionMap = new HashMap<>();
147

    
148
    List<TaxonDistributionDTO> descriptionsToSave = new ArrayList<>();
149

    
150

    
151
    SortedSet<DefinedTermBase> areas;
152
    DistributionEditorPart part;
153
    BodyLayerStack<TaxonDistributionDTO> bodyLayerStack;
154
    private FreezeLayer freezeLayer;
155
    private ConfigRegistry configRegistry;
156
    private AbstractLayer topMostLayer;
157

    
158
    private SelectionLayer selectionLayer;
159

    
160

    
161

    
162
 //  private FixedSummaryRowLayer summaryRowLayer;
163

    
164

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

    
176
        Composite topComposite = new Composite(parent, SWT.NONE);
177
        createTopComposite(topComposite);
178

    
179

    
180

    
181
        natTable = new NatTable(parent, false);
182
        parent.pack();
183

    
184
        Composite bottomComposite = new Composite(parent, SWT.NONE);
185
        GridLayoutFactory.fillDefaults().applyTo(bottomComposite);
186
        createStatusBar(bottomComposite);
187
    }
188

    
189
    public boolean isShowRank() {
190
        return isShowRank;
191
    }
192

    
193
    public void setShowRank(boolean isShowRank) {
194
        this.isShowRank = isShowRank;
195
    }
196

    
197
    public int getFirstDataColumnIndex() {
198
        return firstDataColumnIndex;
199
    }
200

    
201
    public void setFirstDataColumnIndex(int firstDataColumnIndex) {
202
        this.firstDataColumnIndex = firstDataColumnIndex;
203
    }
204

    
205
    @Override
206
    public String getActualNameCache() {
207
        return actualNameCache;
208
    }
209

    
210
    public void setActualNameCache(String actualNameCache) {
211
        this.actualNameCache = actualNameCache;
212
    }
213

    
214
    public LinkedMap<String, String> getPropertyToLabelMap() {
215
        return propertyToLabelMap;
216
    }
217

    
218
    public void setPropertyToLabelMap(LinkedMap<String, String> propertyToLabelMap) {
219
        this.propertyToLabelMap = propertyToLabelMap;
220
    }
221

    
222
    public Map<Integer, NamedArea> getAreaToColumnIndexMap() {
223
        return areaToColumnIndexMap;
224
    }
225

    
226

    
227
    public void setAreaToColumnIndexMap(Map<Integer, NamedArea> areaToColumnIndexMap) {
228
        this.areaToColumnIndexMap = areaToColumnIndexMap;
229
    }
230

    
231

    
232
    public List<TaxonDistributionDTO> getDescriptionsToSave() {
233
        return descriptionsToSave;
234
    }
235

    
236
    public void setDescriptionsToSave(List<TaxonDistributionDTO> descriptionsToSave) {
237
        this.descriptionsToSave = descriptionsToSave;
238
    }
239

    
240

    
241

    
242
    private void createStatusBar(Composite composite) {
243
        GridData gridData = new GridData();
244
        gridData.horizontalSpan = 2;
245
        gridData.grabExcessHorizontalSpace = true;
246
        gridData.horizontalAlignment = GridData.FILL;
247
        GridLayout gridLayout = new GridLayout();
248
        gridLayout.numColumns = 3;
249
        composite.setLayoutData(gridData);
250
        composite.setLayout(gridLayout);
251

    
252

    
253
        gridData = new GridData();
254
        gridData.horizontalSpan = 1;
255
        gridData.grabExcessHorizontalSpace = true;
256
        gridData.horizontalAlignment = GridData.FILL;
257

    
258
        statusLabel = new Label(composite, SWT.LEFT);
259
        statusLabel.setText(ELEMENT_COUNT + (taxonList != null ? taxonList.size() : UNKNOWN));
260
        statusLabel.setLayoutData(gridData);
261

    
262
        statusLabelSourceReference = new Label(composite, SWT.RIGHT);
263

    
264
        statusLabelSourceReference.setLayoutData(gridData);
265

    
266
        if (defaultSource != null){
267
            statusLabelSourceReference.setText(Messages.DistributionEditor_defaultSource + defaultSource.getAbbrevTitle() != null? defaultSource.getAbbrevTitle() : defaultSource.getAbbrevTitleCache());
268

    
269
        }
270

    
271
        button3 = new Button(composite, SWT.PUSH );
272
        button3.setEnabled(false);
273
        GridData gridData3 = new GridData();
274
        gridData3.horizontalAlignment = SWT.RIGHT;
275
        button3.setLayoutData(gridData3);
276
        //button3.setText(Messages.ChecklistEditor_REMOVE_DEFAULT_SOURCE);
277
        button3.setImage(ImageResources.getImage(ImageResources.TRASH_ICON));
278
        button3.setToolTipText(Messages.ChecklistEditor_REMOVE_DEFAULT_SOURCE_TOOLTIP);
279
        button3.addSelectionListener(new SelectionAdapter() {
280

    
281
            @Override
282
            public void widgetSelected(SelectionEvent event) {
283
                defaultSource = null;
284

    
285
                String defaultSourceStr = (defaultSource == null) ? "" : Messages.DistributionEditor_defaultSource + defaultSource.getTitleCache(); //$NON-NLS-1$
286
                if (defaultSourceStr.length()> 100){
287
                    defaultSourceStr = defaultSourceStr.substring(0, 98) + "..."; //$NON-NLS-1$
288
                }
289
                statusLabelSourceReference.setText(defaultSourceStr);
290

    
291
                button3.setBackground(EditorUtil.getColor(Resources.COLOR_CONTROL_SELECTED));
292
                button3.setEnabled(false);
293
            }
294

    
295
        });
296

    
297
    }
298

    
299
    private void applyStyles(){
300
        ModernNatTableThemeConfiguration configuration = new ModernNatTableThemeConfiguration();
301
        configuration.summaryRowHAlign = HorizontalAlignmentEnum.CENTER;
302
        // NOTE: Getting the colors and fonts from the GUIHelper ensures that
303
        // they are disposed properly (required by SWT)
304
        configuration.cHeaderBgColor = GUIHelper.getColor(211, 211, 211);
305
        configuration.rHeaderBgColor = GUIHelper.getColor(211, 211, 211);
306
        natTable.addConfiguration(configuration);
307

    
308
    }
309

    
310
    private void configureNatTable(ConfigRegistry configRegistry,
311
            AbstractLayer topMostLayer) {
312
        /**
313
         * CONFIGURATION
314
         */
315
        natTable.setConfigRegistry(configRegistry);
316

    
317
        applyStyles();
318

    
319
        //add default configuration because autoconfigure is set to false in constructor
320
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
321

    
322

    
323

    
324
        // override the default sort configuration and change the mouse bindings
325
        // to sort on a single click
326

    
327
        natTable.addConfiguration(new SingleClickSortConfiguration());
328
        natTable.addConfiguration(new FilterRowConfiguration(this));
329

    
330
        // add the header menu configuration for adding the column header menu
331
        // with hide/show actions
332
        natTable.addConfiguration(new DistributionEditorHeaderMenuConfiguration(natTable));
333

    
334
        // add custom configuration for data conversion and add column labels to viewport layer
335
        topMostLayer.addConfiguration(new DistributionCellEditorDataConversionConfiguration(this));
336

    
337
        natTable.configure();
338
    }
339

    
340
    public void createTable(){
341
        /**
342
         * layers
343
         */
344

    
345
        createLayers();
346

    
347
        /**
348
         * configuration
349
         */
350
        configureNatTable( configRegistry, topMostLayer);
351

    
352
        /**
353
         * handlers and listeners
354
         */
355
        registerHandlersAndListeners(topMostLayer);
356
        FreezeHelper.freeze(freezeLayer, bodyLayerStack.getViewPortLayer(),
357
                new PositionCoordinate(bodyLayerStack.getViewPortLayer(), 0, 0),
358
                new PositionCoordinate(bodyLayerStack.getViewPortLayer(), 0, -1));
359
        //grab all space
360
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
361

    
362
        this.layout();
363
        natTable.doCommand(new ClientAreaResizeCommand(natTable));
364
      //  boolean ok = natTable.doCommand(new ClientAreaResizeCommand(natTable));
365

    
366
    }
367

    
368

    
369
    private void createLayers() {
370

    
371
        DistributionColumnAccessor columnPropertyAccessor = new DistributionColumnAccessor(this);
372

    
373
        DistributionEditorConfigLabelAccumulator labelAccumulator = new DistributionEditorConfigLabelAccumulator(this);
374
        bodyLayerStack = new BodyLayerStack<>(taxonList, columnPropertyAccessor, new TaxonDistributionDtoComparator(), labelAccumulator);
375

    
376
        bodyDataProvider = bodyLayerStack.getBodyDataProvider();
377

    
378

    
379

    
380
        propertyToLabelMap.put(TAXON_COLUMN, Messages.ChecklistEditor_TAXON);
381
        if (isShowRank){
382
            propertyToLabelMap.put(RANK_COLUMN, Messages.ChecklistEditor_RANK);
383
            propertyToLabelMap.put(SYNONYM_COLUMN, Messages.ChecklistEditor_SYNONYMS);
384
        }else{
385
            propertyToLabelMap.put(SYNONYM_COLUMN, Messages.ChecklistEditor_SYNONYMS);
386
        }
387
        configRegistry = new ConfigRegistry();
388

    
389
        initLabels();
390
        this.selectionLayer = bodyLayerStack.getSelectionLayer();
391

    
392

    
393

    
394
        freezeLayer = new FreezeLayer(selectionLayer);
395
        final CompositeFreezeLayer compositeFreezeLayer = new CompositeFreezeLayer(
396
                freezeLayer,  bodyLayerStack.getViewPortLayer(), selectionLayer);
397

    
398
        // as the selection mouse bindings are registered for the region label
399
        // GridRegion.BODY
400
        // we need to set that region label to the viewport so the selection via mouse
401
        // is working correctly
402
        compositeFreezeLayer.setRegionName(GridRegion.BODY);
403

    
404

    
405
        IDataProvider columnHeaderDataProvider =
406
                new DefaultColumnHeaderDataProvider(propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
407
        DataLayer columnHeaderDataLayer = new DefaultColumnHeaderDataLayer(columnHeaderDataProvider);
408
        ILayer columnHeaderLayer = new ColumnHeaderLayer(
409
            columnHeaderDataLayer,
410
            compositeFreezeLayer,
411
            selectionLayer);
412

    
413
        FilterRowHeaderComposite<TaxonDistributionDTO> filterRowHeaderLayer =
414
                new FilterRowHeaderComposite<>(
415
                        new DefaultGlazedListsFilterStrategy<>(
416
                                bodyLayerStack.getFilterList(),
417
                                columnPropertyAccessor,
418
                                configRegistry),
419
                        columnHeaderLayer,
420
                        columnHeaderDataLayer.getDataProvider(),
421
                        configRegistry);
422

    
423

    
424

    
425
     // build the row header layer stack
426
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
427
        DataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
428
        ILayer rowHeaderLayer = new RowHeaderLayer(
429
            rowHeaderDataLayer,
430
            compositeFreezeLayer,
431
            selectionLayer);
432

    
433

    
434

    
435
        IDataProvider cornerDataProvider =
436
                new DefaultCornerDataProvider(
437
                    columnHeaderDataProvider,
438
                    rowHeaderDataProvider);
439
        DataLayer cornerDataLayer = new DataLayer(cornerDataProvider);
440
        ILayer cornerLayer = new CornerLayer(
441
            cornerDataLayer,
442
            rowHeaderLayer,
443
            filterRowHeaderLayer);
444

    
445
        GridLayer gridLayer = new GridLayer(
446
                compositeFreezeLayer,
447
                filterRowHeaderLayer,
448
                rowHeaderLayer,
449
                cornerLayer);
450

    
451
        natTable.setLayer(gridLayer);
452

    
453
        topMostLayer = compositeFreezeLayer;
454

    
455

    
456
    }
457

    
458
    /**
459
     * @param parent
460
     * @return
461
     */
462
    private Text createSearchBar(Composite parent) {
463

    
464
        Button button1 = new Button(parent, SWT.PUSH );
465
        GridData gridData2 = new GridData();
466
        gridData2.horizontalSpan = 1;
467
        gridData2.horizontalAlignment = SWT.RIGHT;
468

    
469
        button1.setLayoutData(gridData2);
470

    
471

    
472
        button1.setText(Messages.ChecklistEditor_DIST_STATUS);
473
        button1.setToolTipText(Messages.ChecklistEditor_DIST_STATUS_TOOLTIP);
474
        button1.addSelectionListener(new SelectionAdapter() {
475
            @Override
476
            public void widgetSelected(SelectionEvent event) {
477
                AvailableDistributionWizard availableDistributionWizard = new AvailableDistributionWizard();
478
                WizardDialog dialog = new WizardDialog(StoreUtil.getShell(),
479
                        availableDistributionWizard);
480

    
481
                int open = dialog.open();
482
                if(open == 0){
483
                    reload();
484
                }
485
            }
486
        });
487

    
488
        Button button2 = new Button(parent, SWT.PUSH );
489
        GridData gridData3 = new GridData();
490
        gridData3.horizontalAlignment = SWT.RIGHT;
491

    
492
        button2.setLayoutData(gridData3);
493

    
494
        button2.setText(Messages.ChecklistEditor_DEFAULT_SOURCE);
495
        button2.setToolTipText(Messages.ChecklistEditor_DEFAULT_SOURCE_TOOLTIP);
496
        button2.addSelectionListener(new SelectionAdapter() {
497

    
498
            @Override
499
            public void widgetSelected(SelectionEvent event) {
500
                defaultSource = ReferenceSelectionDialog.select(AbstractUtility.getShell(), null);
501

    
502
                String defaultSourceStr = (defaultSource == null) ? "" : Messages.DistributionEditor_defaultSource + defaultSource.getTitleCache(); //$NON-NLS-1$
503
                if (defaultSourceStr.length()> 100){
504
                    defaultSourceStr = defaultSourceStr.substring(0, 98) + "..."; //$NON-NLS-1$
505
                }
506
                statusLabelSourceReference.setText(defaultSourceStr);
507

    
508
                button2.setBackground(EditorUtil.getColor(Resources.COLOR_CONTROL_SELECTED));
509
//                EventUtility.postEvent(WorkbenchEventConstants.REFRESH_DETAILS, true);
510
                button3.setEnabled(true);
511
            }
512

    
513
        });
514

    
515

    
516

    
517

    
518

    
519
        parent.pack();
520
        return searchText;
521
    }
522
    /**
523
    * This method should only be called for adding new Distribution columns and reloading the table.<br>
524
    * It will hide the old distribution column and load the newly added columns.<br>
525
    * <p>
526
    * <b>Notice:</b> for data update please use <b>refresh()</b>
527
    *
528
    */
529
   @SuppressWarnings({ "unchecked", "rawtypes" })
530
   public void reload(){
531
       this.areaToColumnIndexMap.clear();
532
       this.areas.clear();
533
       this.propertyToLabelMap.clear();
534
       createTable();
535
       natTable.redraw();
536
    }
537

    
538
    /**
539
     * @param parent
540
     */
541
    private void createTopComposite(Composite parent) {
542
        GridLayout gridLayout = new GridLayout(3, false);
543
        gridLayout.marginWidth = 0;
544
        gridLayout.marginHeight = 0;
545
        GridData gridData2 = new GridData();
546
        gridData2.horizontalSpan = 1;
547
        gridData2.horizontalAlignment = SWT.RIGHT;
548
        gridData2.horizontalIndent = 3;
549
        parent.setLayoutData(gridData2);
550
        parent.setLayout(gridLayout);
551
        searchText = createSearchBar(parent);
552

    
553

    
554
    }
555
    public void loadDistributions(List<TaxonDistributionDTO> taxonList) {
556
        if (this.taxonList == null){
557
            this.taxonList = new BasicEventList<>();
558
        }
559
       taxonList.stream().forEach(wrapper->DistributionEditor.this.taxonList.add(wrapper));
560
       statusLabel.setText(ELEMENT_COUNT + (taxonList != null ? taxonList.size() : UNKNOWN));
561
       createTaxonDistributionMap();
562
    }
563

    
564
    protected void createTaxonDistributionMap() {
565
        Iterator<TaxonDistributionDTO> iterator = this.taxonList.iterator();
566
           while (iterator.hasNext()){
567
               TaxonDistributionDTO dto = iterator.next();
568
               TaxonDescriptionDTO descriptionDto = dto.getDescriptionsWrapper();
569
               for (TaxonDescription desc: descriptionDto.getDescriptions()){
570
                   if(this.part.getCdmEntitySession()!=null){
571
                       this.part.getCdmEntitySession().load(desc, true);
572
                   }
573
                   for (DescriptionElementBase descElement: desc.getElements()){
574
                       if (descElement instanceof Distribution){
575
                           Map<NamedArea, Set<DescriptionElementBase>> distributionsMap = taxonDistributionMap.get(dto.getTaxonUuid());
576

    
577
                           if (distributionsMap == null){
578
                               distributionsMap = new HashMap();
579
                               taxonDistributionMap.put(dto.getTaxonUuid(), distributionsMap);
580
                           }
581
                           Set<DescriptionElementBase> distributions = distributionsMap.get(((Distribution) descElement).getArea());
582
                           if (distributions == null){
583
                               distributions = new HashSet();
584
                               distributionsMap.put(((Distribution)descElement).getArea(), distributions);
585
                           }
586
                           distributions.add(descElement);
587

    
588
                       }
589
                   }
590
               }
591
           }
592
    }
593

    
594

    
595

    
596

    
597

    
598
    private void initLabels() {
599

    
600
        int index = 2;
601
        if (isShowRank){
602
            index++;
603
        }
604

    
605
        loadNamedAreas();
606
        if (areas == null){
607
            areas = new TreeSet<>();
608
        }
609
        for (DefinedTermBase area: areas) {
610
            this.areaToColumnIndexMap.put(index++, (NamedArea)area);
611
            String areaLabel;
612
            //TODO: adapt to preference
613
            Representation rep = area.getPreferredRepresentation(CdmStore.getDefaultLanguage());
614
            String label = rep.getLabel();
615
            if (label == null){
616
                label = area.getTitleCache();
617
            }
618
            if (PreferencesUtil.isShowIdInVocabularyInChecklistEditor()){
619
                if (area.getIdInVocabulary() != null){
620
                    areaLabel = area.getIdInVocabulary();
621
                } else{
622
                    areaLabel = label;
623
                }
624
            }else if (PreferencesUtil.isShowSymbol1InChecklistEditor()){
625
                if (area.getSymbol() != null){
626
                    areaLabel = area.getSymbol();
627
                } else{
628
                    areaLabel = label;
629
                }
630
            }else if (PreferencesUtil.isShowSymbol2InChecklistEditor()){
631
                if (area.getSymbol2() != null){
632
                    areaLabel = area.getSymbol2();
633
                } else{
634
                    areaLabel = label;
635
                }
636
            }else{
637
                areaLabel = label;
638
            }
639

    
640

    
641
            //String areaLabel = area.getLabel();
642
            String property = area.getUuid().toString();
643
            propertyToLabelMap.put(property, areaLabel);
644
        }
645

    
646
    }
647

    
648
    private SortedSet<DefinedTermBase> loadNamedAreas() {
649
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
650

    
651
        String valuesAreas = PreferencesUtil.getStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), true);
652
        String values = PreferencesUtil.getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey());
653
        Set<UUID> uuidList = new HashSet<UUID>();
654
        String[] split;
655
        List<String> listValue;
656
        List<DefinedTermBase> termlist = new ArrayList<DefinedTermBase>();
657
        if (values != null && values != "") { //$NON-NLS-1$
658
            split = values.split(";"); //$NON-NLS-1$
659
            listValue = Arrays.asList(split);
660

    
661

    
662
            UUID uuid;
663
            for(String s : listValue){
664
                uuid = UUID.fromString(s);
665
                uuidList.add(uuid);
666

    
667
            }
668
        }
669

    
670
        List<TermVocabulary> vocs = new ArrayList<>();
671
        IVocabularyService service =  CdmStore.getService(IVocabularyService.class);
672
        if (uuidList.isEmpty()){
673
            List<TermVocabulary<DefinedTermBase>> vocList = CdmStore.getService(IVocabularyService.class).findByTermType(TermType.NamedArea, null);
674
            vocs.addAll(vocList);
675
        }else{
676
            vocs= service.find(uuidList);
677
        }
678
        for (TermVocabulary voc: vocs){
679
            termlist.addAll(service.getTerms(voc, null, null, null, null).getRecords());
680
        }
681
        List<DefinedTermBase> filteredList = new ArrayList();
682
        if (valuesAreas != null && valuesAreas != "") {
683
            split = valuesAreas.split(";"); //$NON-NLS-1$
684
            listValue = Arrays.asList(split);
685

    
686
            for (DefinedTermBase area: termlist){
687
                if (listValue.contains(area.getUuid().toString())) {
688
                    filteredList.add(area);
689
                }
690

    
691
            }
692
        }else{
693
            filteredList.addAll(termlist);
694
        }
695

    
696

    
697
        TermOrder sortOrder = PreferencesUtil.getSortNamedAreasInDistributionEditor();
698
        if (sortOrder.equals(TermOrder.Natural)){
699
            areas =  getTermsOrderedByVocabularyOrder(filteredList);
700
        } else if (sortOrder.equals(TermOrder.IdInVoc)){
701
            areas = getTermsOrderedByIdInVocabulary(filteredList);
702
        }else{
703
            areas =  getTermsOrderedByLabels(filteredList, CdmStore.getDefaultLanguage());
704
        }
705

    
706
        return null;
707
    }
708

    
709
    public SortedSet<DefinedTermBase> getTermsOrderedByLabels(List<DefinedTermBase> listTerm,Language language){
710
        TermLanguageComparator<?> comp = new TermLanguageComparator<>();
711
        comp.setCompareLanguage(language);
712
        SortedSet<DefinedTermBase> result = new TreeSet(comp);
713
        if(listTerm != null){
714
            result.addAll(listTerm);
715
        }
716

    
717
        return result;
718
    }
719

    
720
    public SortedSet<DefinedTermBase> getTermsOrderedByIdInVocabulary(List<DefinedTermBase> namedAreas) {
721
        TermIdInVocabularyComparator<?> comp = new TermIdInVocabularyComparator<>();
722

    
723
        SortedSet<DefinedTermBase> result = new TreeSet(comp);
724
        if(namedAreas != null){
725
            result.addAll(namedAreas);
726
        }
727
        return result;
728
    }
729

    
730
    public SortedSet<DefinedTermBase> getTermsOrderedByVocabularyOrder(List<DefinedTermBase> listAreas){
731
        HashMap<TermVocabulary<DefinedTermBase>, List<DefinedTermBase>> vocs = new HashMap<>();
732
        OrderedTermComparator<?> comp = new OrderedTermComparator<>();
733
        boolean allOrderedTerms = true;
734
        List<TermVocabulary> alreadyOrderIndexNull = new ArrayList<>();
735
        for (DefinedTermBase term: listAreas){
736
            if (!(term instanceof OrderedTermBase)){
737
                allOrderedTerms = false;
738
                break;
739
            }else if (((OrderedTermBase)term).getOrderIndex() == 0){
740
                if(alreadyOrderIndexNull.contains(term.getVocabulary())) {
741
                    allOrderedTerms = false;
742
                    break;
743
                }else{
744
                    alreadyOrderIndexNull.add(term.getVocabulary());
745
                }
746

    
747

    
748
            }
749
        }
750
        if (allOrderedTerms){
751
            SortedSet<DefinedTermBase> result = new TreeSet(comp.reversed());
752
            result.addAll(listAreas);
753
            return result;
754
        }else{
755
            return getTermsOrderedByLabels(listAreas, PreferencesUtil.getGlobalLanguage());
756
        }
757

    
758

    
759
    }
760

    
761
    private void registerHandlersAndListeners(AbstractLayer topMostLayer) {
762
        //selection listener
763
        E4SelectionListener selectionListener = new DistributionCellSelectionListener(part.getSelectionService(),
764
                selectionLayer, bodyDataProvider, part);
765
        selectionLayer.addLayerListener(selectionListener);
766
        selectionListener.setFullySelectedRowsOnly(false);
767

    
768
        //register handler for view configuration menu
769
      //  natTable.registerCommandHandler(toolbar.getDisplayPersistenceDialogCommandHandler());
770
    }
771

    
772
    /**
773
     * @return
774
     */
775
    public IRowDataProvider<TaxonDistributionDTO> getBodyDataProvider() {
776
        return bodyDataProvider;
777
    }
778

    
779
    public void setDirty() {
780
        part.setDirty();
781
    }
782

    
783
    @Override
784
    public Reference getDefaultSource(){
785
        return defaultSource;
786
    }
787

    
788
//    /**
789
//     * @param result
790
//     */
791
//    public void reloadDistributions() {
792
//       loadDistributions(taxonList);
793
//
794
//    }
795

    
796

    
797

    
798
}
(5-5/18)