Project

General

Profile

Download (32.2 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2007 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

    
10
package eu.etaxonomy.taxeditor.editor.view.checklist.e4;
11

    
12

    
13
import java.util.ArrayList;
14
import java.util.Arrays;
15
import java.util.Collection;
16
import java.util.Collections;
17
import java.util.HashMap;
18
import java.util.List;
19
import java.util.Map;
20
import java.util.SortedSet;
21
import java.util.UUID;
22

    
23
import javax.annotation.PostConstruct;
24
import javax.annotation.PreDestroy;
25
import javax.inject.Inject;
26

    
27
import org.apache.log4j.Logger;
28
import org.eclipse.core.runtime.IProgressMonitor;
29
import org.eclipse.e4.ui.di.Focus;
30
import org.eclipse.e4.ui.di.Persist;
31
import org.eclipse.e4.ui.model.application.ui.MDirtyable;
32
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
33
import org.eclipse.e4.ui.workbench.modeling.ESelectionService;
34
import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy;
35
import org.eclipse.jface.viewers.FocusCellOwnerDrawHighlighter;
36
import org.eclipse.jface.viewers.ISelectionChangedListener;
37
import org.eclipse.jface.viewers.StructuredViewer;
38
import org.eclipse.jface.viewers.TableViewer;
39
import org.eclipse.jface.viewers.TableViewerColumn;
40
import org.eclipse.jface.viewers.TableViewerEditor;
41
import org.eclipse.jface.viewers.TableViewerFocusCellManager;
42
import org.eclipse.jface.wizard.WizardDialog;
43
import org.eclipse.swt.SWT;
44
import org.eclipse.swt.events.ModifyListener;
45
import org.eclipse.swt.events.SelectionAdapter;
46
import org.eclipse.swt.events.SelectionEvent;
47
import org.eclipse.swt.layout.GridData;
48
import org.eclipse.swt.layout.GridLayout;
49
import org.eclipse.swt.widgets.Button;
50
import org.eclipse.swt.widgets.Composite;
51
import org.eclipse.swt.widgets.Display;
52
import org.eclipse.swt.widgets.Label;
53
import org.eclipse.swt.widgets.Table;
54
import org.eclipse.swt.widgets.TableColumn;
55
import org.eclipse.swt.widgets.Text;
56
import org.eclipse.swt.widgets.ToolBar;
57
import org.eclipse.swt.widgets.ToolItem;
58
import org.eclipse.ui.progress.IWorkbenchSiteProgressService;
59

    
60
import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
61
import eu.etaxonomy.cdm.api.conversation.IConversationEnabled;
62
import eu.etaxonomy.cdm.api.service.ITaxonNodeService;
63
import eu.etaxonomy.cdm.model.common.DefinedTermBase;
64
import eu.etaxonomy.cdm.model.common.Representation;
65
import eu.etaxonomy.cdm.model.reference.Reference;
66
import eu.etaxonomy.cdm.model.taxon.Classification;
67
import eu.etaxonomy.cdm.model.taxon.Taxon;
68
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
69
import eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap;
70
import eu.etaxonomy.taxeditor.editor.EditorUtil;
71
import eu.etaxonomy.taxeditor.editor.IDistributionEditor;
72
import eu.etaxonomy.taxeditor.editor.internal.TaxeditorEditorPlugin;
73
import eu.etaxonomy.taxeditor.editor.l10n.Messages;
74
import eu.etaxonomy.taxeditor.editor.view.checklist.ChecklistContentProvider;
75
import eu.etaxonomy.taxeditor.editor.view.checklist.ChecklistEditorComparator;
76
import eu.etaxonomy.taxeditor.editor.view.checklist.ChecklistEditorInput;
77
import eu.etaxonomy.taxeditor.editor.view.checklist.ChecklistLabelProvider;
78
import eu.etaxonomy.taxeditor.editor.view.checklist.filter.ChecklistEditorFilter;
79
import eu.etaxonomy.taxeditor.editor.view.checklist.listener.ChecklistFocusListener;
80
import eu.etaxonomy.taxeditor.editor.view.checklist.listener.ChecklistModifyListener;
81
import eu.etaxonomy.taxeditor.model.AbstractUtility;
82
import eu.etaxonomy.taxeditor.model.IDirtyMarkable;
83
import eu.etaxonomy.taxeditor.model.IPartContentHasDetails;
84
import eu.etaxonomy.taxeditor.model.IPartContentHasSupplementalData;
85
import eu.etaxonomy.taxeditor.preference.PreferencesUtil;
86
import eu.etaxonomy.taxeditor.preference.Resources;
87
import eu.etaxonomy.taxeditor.preference.wizard.AvailableDistributionWizard;
88
import eu.etaxonomy.taxeditor.store.CdmStore;
89
import eu.etaxonomy.taxeditor.store.StoreUtil;
90
import eu.etaxonomy.taxeditor.ui.dialog.selection.ReferenceSelectionDialog;
91
import eu.etaxonomy.taxeditor.ui.element.CdmFormFactory;
92
import eu.etaxonomy.taxeditor.ui.selection.EntitySelectionElement;
93
import eu.etaxonomy.taxeditor.workbench.part.IE4SavablePart;
94

    
95
/**
96
 *
97
 * @author k.luther
98
 *
99
 */
100
public class ChecklistEditorE4 implements  IConversationEnabled,
101
       IDirtyMarkable, IPartContentHasDetails, IE4SavablePart, IDistributionEditor, IPartContentHasSupplementalData{
102

    
103
    private static final String DISTRIBUTION_EDITOR = "Distribution Editor";
104
	private static final String LOADING_TAXA = Messages.ChecklistEditor_LOAD_TAXA;
105
    private static final String UNKNOWN = Messages.ChecklistEditor_UNKNOWN;
106
    private static final String ELEMENT_COUNT = Messages.ChecklistEditor_ELEMENT_COUNT;
107
    public static final String TYPE_FILTER_TEXT = "type filter text"; //$NON-NLS-1$
108

    
109
    private static final Logger logger = Logger.getLogger(ChecklistEditorE4.class);
110

    
111
    /**
112
     * Constant
113
     * <code>ID="eu.etaxonomy.taxeditor.store.datasource"{trunked}</code>
114
     */
115
    public static String ID = "eu.etaxonomy.taxeditor.editor.view.checklist.ChecklistEditor"; //$NON-NLS-1$
116

    
117
    private TableViewer viewer;
118

    
119
    private ITaxonNodeService taxonNodeService;
120

    
121
    private ChecklistEditorComparator comparator;
122

    
123
    private ChecklistEditorInput checklistEditorInput;
124

    
125
    private ConversationHolder conversation;
126

    
127
    private Integer countNodes;
128

    
129
    private List<TaxonNode> selectedTaxonNodes;
130

    
131
    @Inject
132
    private MPart thisPart;
133

    
134
    @Inject
135
    private MDirtyable dirty;
136

    
137
    @Inject
138
    private ESelectionService selService;
139

    
140
    private ISelectionChangedListener selectionChangedListener;
141

    
142
    private ChecklistEditorFilter filter;
143

    
144
    private Label statusLabel;
145

    
146
    private ChecklistLabelProvider labelProvider;
147

    
148
    private Map<UUID, Integer> areaPosition= new HashMap();
149

    
150
    private ToolItem toolItem;
151
    private ToolItem toolItem2;
152
	private ChecklistDropdownSelectionListenerE4 dropListener;
153
	private Text searchText;
154
	private EntitySelectionElement<Reference> defaultReferenceSelection;
155

    
156
	private Reference defaultSource = null;
157

    
158
	public Reference getDefaultSource() {
159
        return defaultSource;
160
    }
161
    public Map<UUID, Integer> getAreaPosition() {
162
        return areaPosition;
163
    }
164
    /**
165
     * @return the selectedTaxonNodes
166
     */
167
    public List<TaxonNode> getSelectedTaxonNodes() {
168
        return selectedTaxonNodes;
169
    }
170

    
171
    /**
172
     * @param selectedTaxonNodes
173
     *            the selectedTaxonNodes to set
174
     */
175
    public void setSelectedTaxonNodes(List<TaxonNode> selectedTaxonNodes) {
176
        this.selectedTaxonNodes = selectedTaxonNodes;
177
    }
178

    
179
    @Inject
180
    public ChecklistEditorE4() {
181
    }
182

    
183
    /** {@inheritDoc} */
184
    @PostConstruct
185
    public void createPartControl(Composite parent) {
186
    	if (!CdmStore.isActive()){
187
            return;
188
        }
189
        taxonNodeService = CdmStore.getService(ITaxonNodeService.class);
190
        filter = new ChecklistEditorFilter();
191
        createTopComposite(parent);
192
      // createToolbar(parent);
193
        viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
194

    
195
        //the focuzsCellManager should return the distribution!!!
196
        TableViewerFocusCellManager focusCellManager = new TableViewerFocusCellManager(viewer, new FocusCellOwnerDrawHighlighter (viewer));
197
        TableViewerEditor.create(viewer, focusCellManager, new ColumnViewerEditorActivationStrategy(viewer), TableViewerEditor.DEFAULT);
198

    
199

    
200
//        viewer.addSelectionChangedListener(new ISelectionChangedListener() {
201
//        	  @Override
202
//        	  public void selectionChanged(SelectionChangedEvent event) {
203
//        	    IStructuredSelection selection = viewer.getStructuredSelection();
204
//        	    Object firstElement = selection.getFirstElement();
205
//        	    // do something with it
206
//        	  }
207
//
208
//
209
//        	});
210

    
211

    
212

    
213
        labelProvider = new ChecklistLabelProvider(this);
214
       // SortedSet<DefinedTermBase> termSet = labelProvider.getNamedAreas(true);
215
//        terms = new HashMap();
216
//        for (DefinedTermBase term : termSet){
217
//                terms.put(term.getUuid(), term);
218
//        }
219
//        if (terms == null){
220
//			MessagingUtils.informationDialog(Messages.ChecklistEditor_NO_AREAS, Messages.ChecklistEditor_NO_AREAS_MESSAGE);
221
//			this.dispose();
222
//			return;
223
//		}
224

    
225

    
226
        viewer.addFilter(filter);
227
        createTable();
228

    
229
        viewer.setContentProvider(new ChecklistContentProvider());
230
        viewer.setLabelProvider(this.labelProvider);
231
//        selectionChangedListener = (event -> selService.setSelection(event.getSelection()));
232
//        viewer.addSelectionChangedListener(selectionChangedListener);
233

    
234
        comparator = new ChecklistEditorComparator();
235
        viewer.setComparator(comparator);
236
        final ModifyListener modifyListener = new ChecklistModifyListener(viewer, filter, searchText);
237

    
238
        searchText.addFocusListener(new ChecklistFocusListener(searchText, modifyListener));
239
        searchText.addModifyListener(modifyListener);
240
        createGridDataForViewerLayout();
241
        createStatusBar(parent);
242

    
243
    }
244

    
245
    /**
246
     * @param parent
247
     */
248
    private void createTopComposite(Composite parent) {
249
        GridLayout gridLayout = new GridLayout(3, false);
250
        gridLayout.marginWidth = 0;
251
        gridLayout.marginHeight = 0;
252
        parent.setLayout(gridLayout);
253

    
254
       searchText = createSearchBar(parent);
255
      // createSetDefaultReferenceButton(parent);
256

    
257
       // getSite().setSelectionProvider(viewer);
258

    
259
    }
260

    
261

    
262
    /**
263
     * @param parent
264
     * @return
265
     */
266
    private void createSetDefaultReferenceButton(Composite parent) {
267
        CdmFormFactory cdmFormFactory = new CdmFormFactory(Display.getCurrent());
268
        defaultReferenceSelection = cdmFormFactory.createSelectionElement(Reference.class,
269
                        null, "Default Source Reference", null,
270
                        EntitySelectionElement.DELETABLE, SWT.NULL);
271

    
272

    
273

    
274

    
275

    
276
        return;
277
    }
278
    private void createGridDataForViewerLayout() {
279
		GridData gridData = new GridData();
280
		gridData.verticalAlignment = GridData.FILL;
281
        gridData.horizontalSpan = 3;
282
        gridData.grabExcessHorizontalSpace = true;
283
        gridData.grabExcessVerticalSpace = true;
284
        gridData.horizontalAlignment = GridData.FILL;
285
        viewer.getControl().setLayoutData(gridData);
286
	}
287

    
288
    /**
289
     * @param parent
290
     * @return
291
     */
292
    private Text createSearchBar(Composite parent) {
293

    
294

    
295

    
296
//        FillLayout fillLayout = new FillLayout();
297
//
298
//        fillLayout.type = SWT.VERTICAL;
299
//        parent.setLayoutData(fillLayout);
300
//        Label searchLabel = new Label(parent, SWT.NONE);
301
//        searchLabel.setText(Messages.ChecklistEditor_SEARCH);
302
//        GridData gridDataLabel = new GridData();
303
//        gridDataLabel.horizontalSpan =1;
304
//        searchLabel.setLayoutData(gridDataLabel);
305
        final Text searchText = new Text(parent, SWT.BORDER | SWT.SEARCH | SWT.ICON_SEARCH | SWT.CANCEL);
306
        GridData gridData = new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL);
307

    
308
        searchText.setLayoutData(gridData);
309
        searchText.setForeground(EditorUtil.getColor(Resources.SEARCH_VIEW_FOREGROUND));
310
        searchText.setText(TYPE_FILTER_TEXT);
311
        searchText.setToolTipText(Messages.ChecklistEditor_SEARCH_TOOLTIP);
312

    
313

    
314
      //  Composite buttons = new Composite(parent, SWT.NONE);
315
        //buttons.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL ));
316
        Button button1 = new Button(parent, SWT.PUSH );
317
        GridData gridData2 = new GridData();
318
        gridData2.horizontalSpan = 1;
319
        button1.setLayoutData(gridData2);
320

    
321

    
322
        button1.setText(Messages.ChecklistEditor_DIST_STATUS);
323
        button1.setToolTipText(Messages.ChecklistEditor_DIST_STATUS_TOOLTIP);
324
        button1.addSelectionListener(new SelectionAdapter() {
325
            @Override
326
            public void widgetSelected(SelectionEvent event) {
327
                AvailableDistributionWizard availableDistributionWizard = new AvailableDistributionWizard();
328
                WizardDialog dialog = new WizardDialog(StoreUtil.getShell(),
329
                        availableDistributionWizard);
330

    
331
                int open = dialog.open();
332
                if(open == 0){
333
                    reload();
334
                }
335
            }
336
        });
337

    
338
        Button button2 = new Button(parent, SWT.PUSH );
339
        GridData gridData3 = new GridData();
340
        gridData2.horizontalSpan = 1;
341
        button2.setLayoutData(gridData3);
342

    
343

    
344
        button2.setText(Messages.ChecklistEditor_DEFAULT_SOURCE);
345
        button2.setToolTipText(Messages.ChecklistEditor_DEFAULT_SOURCE_TOOLTIP);
346
        button2.addSelectionListener(new SelectionAdapter() {
347

    
348
            @Override
349
            public void widgetSelected(SelectionEvent event) {
350
                defaultSource = ReferenceSelectionDialog.select(AbstractUtility.getShell(), null);
351

    
352
            }
353

    
354
        });
355

    
356
        parent.pack();
357
        return searchText;
358
    }
359

    
360
    /**
361
     * @param parent
362
     */
363
    private void createToolbar(Composite parent) {
364
        ToolBar toolBar = new ToolBar(parent, SWT.BORDER);
365
      //  toolItem = new ToolItem(toolBar, SWT.DROP_DOWN | SWT.BORDER);
366

    
367
        toolItem = new ToolItem(toolBar, SWT.PUSH| SWT.BORDER);
368

    
369

    
370
        toolItem.setText(Messages.ChecklistEditor_DIST_STATUS);
371
        toolItem.setToolTipText(Messages.ChecklistEditor_DIST_STATUS_TOOLTIP);
372
        //createToolbarItems();
373
      //  toolItem.addSelectionListener(dropListener);
374
        toolItem.addSelectionListener(new SelectionAdapter() {
375
            @Override
376
            public void widgetSelected(SelectionEvent event) {
377
                AvailableDistributionWizard availableDistributionWizard = new AvailableDistributionWizard();
378
                WizardDialog dialog = new WizardDialog(StoreUtil.getShell(),
379
                        availableDistributionWizard);
380

    
381
                int open = dialog.open();
382
                if(open == 0){
383
                    reload();
384
                }
385
            }
386
        });
387
        toolItem2 = new ToolItem(toolBar, SWT.PUSH | SWT.BORDER);
388

    
389

    
390
        toolItem2.setText(Messages.ChecklistEditor_DEFAULT_SOURCE);
391
        toolItem2.setToolTipText(Messages.ChecklistEditor_DEFAULT_SOURCE_TOOLTIP);
392
        //createToolbarItems();
393
      //  toolItem.addSelectionListener(dropListener);
394
        toolItem2.addSelectionListener(new SelectionAdapter() {
395
            @Override
396
            public void widgetSelected(SelectionEvent event) {
397
                defaultSource = ReferenceSelectionDialog.select(AbstractUtility.getShell(), null);
398
            }
399
        });
400

    
401
        toolBar.pack();
402
    }
403

    
404

    
405

    
406
    private void createStatusBar(Composite composite) {
407
        GridData gridData = new GridData();
408
        gridData.horizontalSpan = 3;
409
        gridData.grabExcessHorizontalSpace = true;
410
        gridData.horizontalAlignment = GridData.FILL;
411

    
412
        statusLabel = new Label(composite, SWT.LEFT);
413
        statusLabel.setText(ELEMENT_COUNT + (countNodes != null ? countNodes : UNKNOWN));
414
        statusLabel.setLayoutData(gridData);
415
    }
416

    
417
    private void createTable() {
418
        Table table = viewer.getTable();//new Table(parent, viewer.getTable().getStyle());
419
        List<String> titles = new ArrayList<String>();
420
        List<Integer> bounds = new ArrayList<Integer>();
421
        if (PreferencesUtil.isShowRankInChecklistEditor()){
422
            Collections.addAll(titles, Messages.ChecklistEditor_TAXON,  Messages.ChecklistEditor_RANK);
423
            Collections.addAll(bounds, 300, 200);
424
        } else{
425
            Collections.addAll(titles, Messages.ChecklistEditor_TAXON);
426
            Collections.addAll(bounds, 300);
427
        }
428

    
429

    
430
      //  Map<Integer, Boolean> restoreValuesForColumnWidth =
431
        restoreValuesForColumnWidth(titles, bounds);
432
        createInitalDistributionColumns(table, titles, bounds);
433
        table.setSortDirection(SWT.DOWN);
434
        table.setHeaderVisible(true);
435
        table.setLinesVisible(true);
436
	}
437
    /**
438
     * This method creates initially the distribution columns for a table. It should only be called for creation.<br>
439
     *<p>
440
     *
441
     *<b>Notice:</b> If you want to add additional columns later please use <b>addTableViewerColumn()</b>
442
     *
443
     * @param table
444
     * @param titles
445
     * @param bounds
446
     * @param restoreValuesForColumnWidth
447
     */
448
	private void createInitalDistributionColumns(Table table,
449
			List<String> titles, List<Integer> bounds) {
450
		for (int columnIndex = 0; columnIndex < titles.size(); columnIndex++) {
451
            TableViewerColumn column = new TableViewerColumn(viewer, SWT.NONE);
452
            column.getColumn().setText(titles.get(columnIndex));
453
            column.getColumn().setWidth(bounds.get(columnIndex));
454
            column.getColumn().setResizable(true);
455
            column.getColumn().setMoveable(true);
456
            column.getColumn().addSelectionListener(getSelectionAdapter(column.getColumn(), columnIndex));
457
            if (columnIndex == 0) {
458
                table.setSortColumn(column.getColumn());
459
            }
460
            if (columnIndex == 1 && PreferencesUtil.isShowRankInChecklistEditor()) {
461
            	/** uncommented it for now because no rank editing is wanted **/
462
//                column.setEditingSupport(new RankEditingSupport(viewer, this));
463
            }
464
            if ((columnIndex == 1 && !PreferencesUtil.isShowRankInChecklistEditor()) || columnIndex >= 2 ) {
465
                //read PrefrenceStore to setWidth according to last saved state
466
//                if(restoreValuesForColumnWidth.get(columnIndex)){
467
                    column.getColumn().setWidth(50);
468
//                }else{
469
//                    column.getColumn().setWidth(0);
470
//                }
471
                column.setEditingSupport(new DistributionEditingSupportE4(viewer, this, columnIndex));
472

    
473
            }
474
        }
475
	}
476

    
477
    /**
478
     * This methods loads the last opened distribution columns for the table viewer from the prefrence store.<br>
479
     *<p>
480
     * <b>Notice:</b> It adds also the TitleCache to the titles list for the header of each column.<p>
481
     *
482
     * @param titles
483
     * @param bounds
484
     * @return Map<Integer, Boolean>
485
     */
486
	private void restoreValuesForColumnWidth(List<String> titles,
487
			List<Integer> bounds) {
488
//		Map<Integer, Boolean> restoreColumnWidth = new HashMap<Integer, Boolean>();
489
		if (labelProvider.getNamedAreas(true) != null) {
490
		    int columnIndex;
491
		    if (PreferencesUtil.isShowRankInChecklistEditor()){
492
		        columnIndex = 2;
493
		    } else{
494
		        columnIndex = 1;
495
		    }
496
            for (DefinedTermBase<DefinedTermBase> term : getLabelProvider().getNamedAreas(false)) {
497
                if(term != null){
498
                   // restoreColumnWidth.put(columnIndex, PreferencesUtil.getPreferenceStore().getBoolean(term.getUuid().toString()));
499
                    areaPosition.put(term.getUuid(), columnIndex);
500
                    Representation rep = term.getPreferredRepresentation(CdmStore.getDefaultLanguage());
501
                    String label = rep.getAbbreviatedLabel() != null ? rep.getAbbreviatedLabel(): rep.getLabel();
502
                    if (label == null){
503
                        term.getTitleCache();
504
                    }
505
                    if (PreferencesUtil.isShowIdInVocabularyInChecklistEditor()){
506
                        if (term.getIdInVocabulary() != null){
507
                            titles.add(term.getIdInVocabulary());
508
                        } else{
509
                            titles.add(label);
510
                        }
511
                    }else if (PreferencesUtil.isShowSymbol1InChecklistEditor()){
512
                        if (term.getSymbol() != null){
513
                            titles.add(term.getSymbol());
514
                        } else{
515
                            titles.add(label);
516
                        }
517
                    }else if (PreferencesUtil.isShowSymbol2InChecklistEditor()){
518
                        if (term.getSymbol2() != null){
519
                            titles.add(term.getSymbol2());
520
                        } else{
521
                            titles.add(label);
522
                        }
523
                    }else{
524
                        titles.add(label);
525
                    }
526
                    bounds.add(200);
527
                    columnIndex++;
528
                }
529
            }
530
        }
531
//		return restoreColumnWidth;
532
	}
533

    
534
    /**
535
     * This method adds new DistributionColumns to an existing table.
536
     *
537
     * @param title
538
     * @param bound
539
     * @param colNumber
540
     * @return
541
     */
542
    private TableViewerColumn addTableViewerColumn(String title, int bound, final int colNumber, DefinedTermBase term) {
543

    
544
        final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.FULL_SELECTION);
545
        final TableColumn column = viewerColumn.getColumn();
546
        column.setText(title);
547
        String[] UuidAndLable = new String[2];
548
        UuidAndLable[0] = term.getUuid().toString();
549
        UuidAndLable[1] = title;
550
        column.setData(UuidAndLable);
551
        column.setWidth(200);
552

    
553
        viewerColumn.setEditingSupport(new DistributionEditingSupportE4(viewer, this, colNumber));
554
        column.setResizable(true);
555
        column.setMoveable(true);
556
        return viewerColumn;
557
      }
558

    
559

    
560

    
561
    /**
562
     *
563
     * pull data from database and set input for view
564
     *
565
     */
566
    private void loadDataInput() {
567
        Classification classification = checklistEditorInput.getClassification();
568
        TaxonNode taxonNode = checklistEditorInput.getTaxonNode();
569
        if (classification != null && taxonNode == null) {
570
            countNodes = taxonNodeService.countAllNodesForClassification(classification);
571
//            statusLabel.setText(ELEMENT_COUNT + (countNodes != null ? countNodes : UNKNOWN));
572
            // This should not kill the view nor the editor if something goes
573
            // wrong
574
            // TODO: don't load the whole taxonNode Object but rather a small
575
            // and simple Solution
576
            // FIXME: May be don't open classification which are greater than
577
            // 3000 Taxa
578
            selectedTaxonNodes = taxonNodeService.listAllNodesForClassification(classification, 0, countNodes);
579
            countNodes = selectedTaxonNodes.size();
580
            statusLabel.setText(ELEMENT_COUNT + (countNodes != null ? countNodes : UNKNOWN));
581
            viewer.setInput(checklistEditorInput.getTaxa());
582
//            Job checkListJob = new ChecklistJob(LOADING_TAXA, selectedTaxonNodes);
583
//            checkListJob.schedule(Job.LONG);
584

    
585
        }
586
        if (taxonNode != null) {
587
        	boolean includeUnpublished = true;
588
            selectedTaxonNodes = taxonNodeService.loadChildNodesOfTaxonNode(taxonNode, NODE_INIT_STRATEGY, true, includeUnpublished, null);
589
            countNodes = selectedTaxonNodes.size();
590
            viewer.setInput(checklistEditorInput.getTaxa());
591
            statusLabel.setText(ELEMENT_COUNT + (countNodes != null ? countNodes : UNKNOWN));
592
//            Job checkListJob = new ChecklistJob(LOADING_TAXA, selectedTaxonNodes);
593
//            checkListJob.schedule(Job.LONG);
594
//          getService().schedule(new ChecklistJob(LOADING_TAXA, selectedTaxonNodes), Job.LONG);
595
        }
596
    }
597

    
598

    
599
    @PreDestroy
600
    public void dispose() {
601
    	if(conversation!=null){
602
    		conversation.unregisterForDataStoreChanges(this);
603
    		conversation.close();
604
    	}
605
    	conversation = null;
606
    	if(checklistEditorInput!=null){
607
    	    checklistEditorInput.dispose();
608
    	}
609

    
610
    }
611

    
612
    /** {@inheritDoc} */
613
    @Focus
614
    public void setFocus() {
615
    	if(viewer!=null && viewer.getControl()!=null && !viewer.getControl().isDisposed()) {
616
            viewer.getControl().setFocus();
617
        }
618
    }
619

    
620
    //FIXME E4 migrate
621
//    /*
622
//     * (non-Javadoc)
623
//     *
624
//     * @see org.eclipse.ui.part.WorkbenchPart#showBusy(boolean)
625
//     */
626
//    /** {@inheritDoc} */
627
//    @Override
628
//    public void showBusy(boolean busy) {
629
//        super.showBusy(busy);
630
//        // viewer.getTable().setEnabled(!busy);
631
//        if (busy) {
632
//            partNameCache = getPartName();
633
//            setPartName(String.format(Messages.ChecklistEditor_LOAD_CNT_TAXA, countNodes));
634
//        } else {
635
//            if (partNameCache != null) {
636
//                setPartName(partNameCache);
637
//            }
638
//        }
639
//    }
640

    
641
    /**
642
     * <p>
643
     * Getter for the field <code>viewer</code>.
644
     * </p>
645
     *
646
     * @return a {@link org.eclipse.jface.viewers.StructuredViewer} object.
647
     */
648
    public StructuredViewer getViewer() {
649
        return viewer;
650
    }
651

    
652
    public void refresh() {
653
        viewer.refresh();
654
    }
655

    
656
    /**
657
     * This method should only be called for adding new Distribution columns and reloading the table.<br>
658
     * It will hide the old distribution column and load the newly added columns.<br>
659
     * <p>
660
     * <b>Notice:</b> for data update please use <b>refresh()</b>
661
     *
662
     */
663
    @SuppressWarnings({ "unchecked", "rawtypes" })
664
	public void reload(){
665
    	//create new Items for Dropdown menue
666
    	Table table = viewer.getTable();
667
    	table.setRedraw(false);
668
    	Collection<DefinedTermBase> oldTerms = labelProvider.getNamedAreas(false);
669

    
670
//    	if (PreferencesUtil.isShowIdInVocabularyInChecklistEditor()){
671
//
672
//    	} else{
673
//    	    terms = (SortedSet<DefinedTermBase>) labelProvider.getTermsOrderedByLabels(labelProvider.getNamedAreas(), CdmStore.getDefaultLanguage());
674
//    	}
675
    	SortedSet<DefinedTermBase> newTerms = labelProvider.getNamedAreas(true);
676
    	//terms = newTerms;
677
//    	toolItem.removeSelectionListener(dropListener);
678
////    	hideDistributionColumns(oldTerms);
679
//    	createToolbarItems();
680
//    	toolItem.addSelectionListener(dropListener);
681

    
682
    	//check which terms are deleted and which are new.
683
    	TableColumn[] columns = viewer.getTable().getColumns() ;
684
    	int index = 0;
685

    
686
      for (TableColumn column: columns){
687
          if ((!PreferencesUtil.isShowRankInChecklistEditor() && index > 0) || (index > 1)) {
688
                column.dispose();
689
            }
690
          index++;
691
      }
692
      if (oldTerms != null){
693
    	for (DefinedTermBase oldTerm:oldTerms){
694
            boolean delete = true;
695
            for (DefinedTermBase term: newTerms){
696
                   if(oldTerm.getUuid().equals(term.getUuid())){
697
                       delete = false;
698
                       break;
699
                   }
700

    
701
            }
702
            if (delete){
703
               // viewer.getTable().remove(areaPosition.get(oldTerm.getUuid()));
704
                areaPosition.remove(oldTerm.getUuid());
705

    
706
            }
707
        }
708
    	updateColumnIndex();
709
      }
710

    
711

    
712
    	for (DefinedTermBase term:newTerms){
713
    	    boolean isNew = true;
714

    
715
    	    Integer position = areaPosition.get(term.getUuid());
716
    	    Representation rep = term.getPreferredRepresentation(CdmStore.getDefaultLanguage());
717

    
718
    	    String termLable = rep.getAbbreviatedLabel();
719
    	    if (termLable == null){
720
    	        termLable = rep.getLabel();
721
    	    }
722
            if (PreferencesUtil.isShowIdInVocabularyInChecklistEditor()){
723
                if (term.getIdInVocabulary() != null){
724
                    termLable = term.getIdInVocabulary();
725
                }
726
            }
727

    
728
            if (position == null){
729
                int count = viewer.getTable().getColumnCount();
730
                TableViewerColumn column= addTableViewerColumn(termLable, 200, count, term);
731
                areaPosition.put(term.getUuid(), Integer.valueOf(count));
732
            }else{
733
                TableViewerColumn column= addTableViewerColumn(termLable, 200, position, term);
734
            }
735

    
736

    
737
    	}
738

    
739
        viewer.setLabelProvider(labelProvider);
740

    
741
        table.setRedraw(true);
742
    	viewer.refresh();
743
    }
744

    
745
	/**
746
     *
747
     */
748
    private void updateColumnIndex() {
749
        int columnIndex;
750
        if (PreferencesUtil.isShowRankInChecklistEditor()){
751
            columnIndex = 2;
752
        } else{
753
            columnIndex = 1;
754
        }
755
        for (UUID uuid:areaPosition.keySet()){
756
            areaPosition.put(uuid, columnIndex);
757
            columnIndex++;
758
        }
759

    
760
    }
761

    
762

    
763

    
764

    
765
    /**
766
     * <p>
767
     * Getter for the field <code>service</code>.
768
     * </p>
769
     *
770
     * @return the service
771
     */
772
    public IWorkbenchSiteProgressService getService() {
773
        return TaxeditorEditorPlugin.getDefault().getWorkbench().getService(IWorkbenchSiteProgressService.class);
774
    }
775

    
776
    private SelectionAdapter getSelectionAdapter(final TableColumn column, final int index) {
777
        SelectionAdapter selectionAdapter = new SelectionAdapter() {
778
            @Override
779
            public void widgetSelected(SelectionEvent e) {
780
                comparator.setColumn(index);
781
                int dir = viewer.getTable().getSortDirection();
782
                if (viewer.getTable().getSortColumn() == column) {
783
                    dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
784
                } else {
785
                    dir = SWT.DOWN;
786
                }
787
                viewer.getTable().setSortDirection(dir);
788
                viewer.getTable().setSortColumn(column);
789
                viewer.refresh();
790
            }
791
        };
792
        return selectionAdapter;
793
    }
794

    
795
    public void doSave(IProgressMonitor monitor) {
796
        try {
797
          //  monitor.beginTask(Messages.ChecklistEditor_SAVE_EDITOR, 1);
798
//            if (!conversation.isBound()) {
799
//                conversation.bind();
800
//            }
801

    
802
            this.checklistEditorInput.merge();
803

    
804
            //conversation.commit(true);
805
            setDirty(false);
806
  //          monitor.worked(1);
807
        } finally {
808
   //         monitor.done();
809
        }
810

    
811
    }
812

    
813
    public void init(ChecklistEditorInput input) {
814
        checklistEditorInput = input;
815
        thisPart.setLabel(DISTRIBUTION_EDITOR+": " + checklistEditorInput.getName());
816
        conversation = checklistEditorInput.getConversation();
817
        conversation.registerForDataStoreChanges(this);
818

    
819
        //propagate selection
820
        selectionChangedListener = (event -> selService.setSelection(
821
               DistributionEditorHelper.getDistributionForColumn(event, areaPosition)));
822

    
823
        viewer.addSelectionChangedListener(selectionChangedListener);
824

    
825

    
826
        loadDataInput();
827
    }
828
    private static final List<String> NODE_INIT_STRATEGY = Arrays.asList(new String[] { "descriptions", //$NON-NLS-1$
829
            "descriptions.*", "description.state", "feature", "feature.*", "childNodes", "childNodes.taxon", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
830
            "childNodes.taxon.name", "taxonNodes", "taxonNodes.*", "taxonNodes.taxon.*", "taxon.*", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
831
            "taxon.descriptions", "taxon.sec", "taxon.name.*", "terms", "name.*", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
832
            "name.rank.representations", "name.status.type.representations", "stateData.$" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
833

    
834
    /*
835
     * (non-Javadoc)
836
     *
837
     * @see
838
     * eu.etaxonomy.taxeditor.model.IDirtyMarkableSelectionProvider#changed(
839
     * java.lang.Object)
840
     */
841
    @Override
842
    public void changed(Object element) {
843
        if (element != null) {
844
            viewer.update(element, null);
845

    
846
            if (element instanceof Taxon){
847
                checklistEditorInput.addTaxonToSave((Taxon)element);
848
            }
849
            setDirty(true);
850
        }
851
    }
852

    
853
    /* (non-Javadoc)
854
     * @see eu.etaxonomy.taxeditor.model.IDirtyMarkableSelectionProvider#forceDirty()
855
     */
856
    @Override
857
    public void forceDirty() {
858
        changed(null);
859
    }
860

    
861
    public void setDirty(boolean dirty) {
862
        this.dirty.setDirty(dirty);
863
    }
864

    
865
    /*
866
     * (non-Javadoc)
867
     *
868
     * @see org.eclipse.ui.forms.editor.FormEditor#isDirty()
869
     */
870
    public boolean isDirty() {
871
        return dirty.isDirty();
872
    }
873

    
874

    
875
    /**
876
     * @return the labelProvider
877
     */
878
    public ChecklistLabelProvider getLabelProvider() {
879
        return labelProvider;
880
    }
881

    
882
    /* (non-Javadoc)
883
     * @see eu.etaxonomy.cdm.persistence.hibernate.ICdmPostDataChangeObserver#update(eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap)
884
     */
885
    @Override
886
    public void update(CdmDataChangeMap arg0) {
887
        // TODO Auto-generated method stub
888

    
889
    }
890

    
891
    /* (non-Javadoc)
892
     * @see eu.etaxonomy.cdm.api.conversation.IConversationEnabled#getConversationHolder()
893
     */
894
    @Override
895
    public ConversationHolder getConversationHolder() {
896
        return conversation;
897
    }
898

    
899
    /* (non-Javadoc)
900
     * @see eu.etaxonomy.taxeditor.workbench.part.IE4SavablePart#save(org.eclipse.core.runtime.IProgressMonitor)
901
     */
902
    @Override
903
    @Persist
904
    public void save(IProgressMonitor monitor) {
905
        doSave(monitor);
906
    }
907

    
908

    
909
}
(2-2/5)