Project

General

Profile

Download (33 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
    private Label statusLabelSourceReference;
146

    
147
    private ChecklistLabelProvider labelProvider;
148

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

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

    
157
	private Reference defaultSource = null;
158

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

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

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

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

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

    
200

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

    
212

    
213

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

    
226

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

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

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

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

    
244
    }
245

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

    
255
       searchText = createSearchBar(parent);
256

    
257

    
258
    }
259

    
260

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

    
271

    
272

    
273

    
274

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

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

    
293

    
294

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

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

    
312

    
313
      //  Composite buttons = new Composite(parent, SWT.NONE);
314
        //buttons.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL ));
315
        Button button1 = new Button(parent, SWT.PUSH );
316
        GridData gridData2 = new GridData();
317
        gridData2.horizontalSpan = 1;
318
        gridData2.horizontalAlignment = SWT.RIGHT;
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
                statusLabelSourceReference.setText(defaultSource == null ? "" : "Default Source Reference: " + defaultSource.getAbbrevTitleCache());
352
                button2.setBackground(EditorUtil.getColor(Resources.COLOR_CONTROL_SELECTED));
353
            }
354

    
355
        });
356

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

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

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

    
370

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

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

    
390

    
391
        toolItem2.setText(Messages.ChecklistEditor_DEFAULT_SOURCE);
392
        toolItem2.setToolTipText(Messages.ChecklistEditor_DEFAULT_SOURCE_TOOLTIP);
393
        //createToolbarItems();
394
      //  toolItem.addSelectionListener(dropListener);
395
        toolItem2.addSelectionListener(new SelectionAdapter() {
396
            @Override
397
            public void widgetSelected(SelectionEvent event) {
398
                defaultSource = ReferenceSelectionDialog.select(AbstractUtility.getShell(), null);
399
                statusLabelSourceReference.setText("Default Source Reference: " + defaultSource.getAbbrevTitle() != null? defaultSource.getAbbrevTitle() : defaultSource.getAbbrevTitleCache());
400

    
401
            }
402
        });
403

    
404
        toolBar.pack();
405
    }
406

    
407

    
408

    
409
    private void createStatusBar(Composite composite) {
410
        GridData gridData = new GridData();
411
        gridData.horizontalSpan = 1;
412
        gridData.grabExcessHorizontalSpace = true;
413
        gridData.horizontalAlignment = GridData.FILL;
414

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

    
419
        statusLabelSourceReference = new Label(composite, SWT.RIGHT);
420
        statusLabelSourceReference.setLayoutData(gridData);
421
        if (defaultSource != null){
422
            statusLabelSourceReference.setText("Default Source Reference: " + defaultSource.getAbbrevTitle() != null? defaultSource.getAbbrevTitle() : defaultSource.getAbbrevTitleCache());
423

    
424
        }
425
    }
426

    
427
    private void createTable() {
428
        Table table = viewer.getTable();//new Table(parent, viewer.getTable().getStyle());
429
        List<String> titles = new ArrayList<String>();
430
        List<Integer> bounds = new ArrayList<Integer>();
431
        if (PreferencesUtil.isShowRankInChecklistEditor()){
432
            Collections.addAll(titles, Messages.ChecklistEditor_TAXON,  Messages.ChecklistEditor_RANK);
433
            Collections.addAll(bounds, 300, 200);
434
        } else{
435
            Collections.addAll(titles, Messages.ChecklistEditor_TAXON);
436
            Collections.addAll(bounds, 300);
437
        }
438

    
439

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

    
483
            }
484
        }
485
	}
486

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

    
544
    /**
545
     * This method adds new DistributionColumns to an existing table.
546
     *
547
     * @param title
548
     * @param bound
549
     * @param colNumber
550
     * @return
551
     */
552
    private TableViewerColumn addTableViewerColumn(String title, int bound, final int colNumber, DefinedTermBase term) {
553

    
554
        final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.FULL_SELECTION);
555
        final TableColumn column = viewerColumn.getColumn();
556
        column.setText(title);
557
        String[] UuidAndLable = new String[2];
558
        UuidAndLable[0] = term.getUuid().toString();
559
        UuidAndLable[1] = title;
560
        column.setData(UuidAndLable);
561
        column.setWidth(200);
562

    
563
        viewerColumn.setEditingSupport(new DistributionEditingSupportE4(viewer, this, colNumber));
564
        column.setResizable(true);
565
        column.setMoveable(true);
566
        return viewerColumn;
567
      }
568

    
569

    
570

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

    
595
        }
596
        if (taxonNode != null) {
597
        	boolean includeUnpublished = true;
598
            selectedTaxonNodes = taxonNodeService.loadChildNodesOfTaxonNode(taxonNode, NODE_INIT_STRATEGY, true, includeUnpublished, null);
599
            countNodes = selectedTaxonNodes.size();
600
            viewer.setInput(checklistEditorInput.getTaxa());
601
            statusLabel.setText(ELEMENT_COUNT + (countNodes != null ? countNodes : UNKNOWN));
602
//            Job checkListJob = new ChecklistJob(LOADING_TAXA, selectedTaxonNodes);
603
//            checkListJob.schedule(Job.LONG);
604
//          getService().schedule(new ChecklistJob(LOADING_TAXA, selectedTaxonNodes), Job.LONG);
605
        }
606
    }
607

    
608

    
609
    @PreDestroy
610
    public void dispose() {
611
    	if(conversation!=null){
612
    		conversation.unregisterForDataStoreChanges(this);
613
    		conversation.close();
614
    	}
615
    	conversation = null;
616
    	if(checklistEditorInput!=null){
617
    	    checklistEditorInput.dispose();
618
    	}
619

    
620
    }
621

    
622
    /** {@inheritDoc} */
623
    @Focus
624
    public void setFocus() {
625
    	if(viewer!=null && viewer.getControl()!=null && !viewer.getControl().isDisposed()) {
626
            viewer.getControl().setFocus();
627
        }
628
    }
629

    
630
    //FIXME E4 migrate
631
//    /*
632
//     * (non-Javadoc)
633
//     *
634
//     * @see org.eclipse.ui.part.WorkbenchPart#showBusy(boolean)
635
//     */
636
//    /** {@inheritDoc} */
637
//    @Override
638
//    public void showBusy(boolean busy) {
639
//        super.showBusy(busy);
640
//        // viewer.getTable().setEnabled(!busy);
641
//        if (busy) {
642
//            partNameCache = getPartName();
643
//            setPartName(String.format(Messages.ChecklistEditor_LOAD_CNT_TAXA, countNodes));
644
//        } else {
645
//            if (partNameCache != null) {
646
//                setPartName(partNameCache);
647
//            }
648
//        }
649
//    }
650

    
651
    /**
652
     * <p>
653
     * Getter for the field <code>viewer</code>.
654
     * </p>
655
     *
656
     * @return a {@link org.eclipse.jface.viewers.StructuredViewer} object.
657
     */
658
    public StructuredViewer getViewer() {
659
        return viewer;
660
    }
661

    
662
    public void refresh() {
663
        viewer.refresh();
664
    }
665

    
666
    /**
667
     * This method should only be called for adding new Distribution columns and reloading the table.<br>
668
     * It will hide the old distribution column and load the newly added columns.<br>
669
     * <p>
670
     * <b>Notice:</b> for data update please use <b>refresh()</b>
671
     *
672
     */
673
    @SuppressWarnings({ "unchecked", "rawtypes" })
674
	public void reload(){
675
    	//create new Items for Dropdown menue
676
    	Table table = viewer.getTable();
677
    	table.setRedraw(false);
678
    	Collection<DefinedTermBase> oldTerms = labelProvider.getNamedAreas(false);
679

    
680
//    	if (PreferencesUtil.isShowIdInVocabularyInChecklistEditor()){
681
//
682
//    	} else{
683
//    	    terms = (SortedSet<DefinedTermBase>) labelProvider.getTermsOrderedByLabels(labelProvider.getNamedAreas(), CdmStore.getDefaultLanguage());
684
//    	}
685
    	SortedSet<DefinedTermBase> newTerms = labelProvider.getNamedAreas(true);
686
    	//terms = newTerms;
687
//    	toolItem.removeSelectionListener(dropListener);
688
////    	hideDistributionColumns(oldTerms);
689
//    	createToolbarItems();
690
//    	toolItem.addSelectionListener(dropListener);
691

    
692
    	//check which terms are deleted and which are new.
693
    	TableColumn[] columns = viewer.getTable().getColumns() ;
694
    	int index = 0;
695

    
696
      for (TableColumn column: columns){
697
          if ((!PreferencesUtil.isShowRankInChecklistEditor() && index > 0) || (index > 1)) {
698
                column.dispose();
699
            }
700
          index++;
701
      }
702
      if (oldTerms != null){
703
    	for (DefinedTermBase oldTerm:oldTerms){
704
            boolean delete = true;
705
            for (DefinedTermBase term: newTerms){
706
                   if(oldTerm.getUuid().equals(term.getUuid())){
707
                       delete = false;
708
                       break;
709
                   }
710

    
711
            }
712
            if (delete){
713
               // viewer.getTable().remove(areaPosition.get(oldTerm.getUuid()));
714
                areaPosition.remove(oldTerm.getUuid());
715

    
716
            }
717
        }
718
    	updateColumnIndex();
719
      }
720

    
721

    
722
    	for (DefinedTermBase term:newTerms){
723
    	    boolean isNew = true;
724

    
725
    	    Integer position = areaPosition.get(term.getUuid());
726
    	    Representation rep = term.getPreferredRepresentation(CdmStore.getDefaultLanguage());
727

    
728
    	    String termLable = rep.getAbbreviatedLabel();
729
    	    if (termLable == null){
730
    	        termLable = rep.getLabel();
731
    	    }
732
            if (PreferencesUtil.isShowIdInVocabularyInChecklistEditor()){
733
                if (term.getIdInVocabulary() != null){
734
                    termLable = term.getIdInVocabulary();
735
                }
736
            }
737

    
738
            if (position == null){
739
                int count = viewer.getTable().getColumnCount();
740
                TableViewerColumn column= addTableViewerColumn(termLable, 200, count, term);
741
                areaPosition.put(term.getUuid(), Integer.valueOf(count));
742
            }else{
743
                TableViewerColumn column= addTableViewerColumn(termLable, 200, position, term);
744
            }
745

    
746

    
747
    	}
748

    
749
        viewer.setLabelProvider(labelProvider);
750

    
751
        table.setRedraw(true);
752
    	viewer.refresh();
753
    }
754

    
755
	/**
756
     *
757
     */
758
    private void updateColumnIndex() {
759
        int columnIndex;
760
        if (PreferencesUtil.isShowRankInChecklistEditor()){
761
            columnIndex = 2;
762
        } else{
763
            columnIndex = 1;
764
        }
765
        for (UUID uuid:areaPosition.keySet()){
766
            areaPosition.put(uuid, columnIndex);
767
            columnIndex++;
768
        }
769

    
770
    }
771

    
772

    
773

    
774

    
775
    /**
776
     * <p>
777
     * Getter for the field <code>service</code>.
778
     * </p>
779
     *
780
     * @return the service
781
     */
782
    public IWorkbenchSiteProgressService getService() {
783
        return TaxeditorEditorPlugin.getDefault().getWorkbench().getService(IWorkbenchSiteProgressService.class);
784
    }
785

    
786
    private SelectionAdapter getSelectionAdapter(final TableColumn column, final int index) {
787
        SelectionAdapter selectionAdapter = new SelectionAdapter() {
788
            @Override
789
            public void widgetSelected(SelectionEvent e) {
790
                comparator.setColumn(index);
791
                int dir = viewer.getTable().getSortDirection();
792
                if (viewer.getTable().getSortColumn() == column) {
793
                    dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
794
                } else {
795
                    dir = SWT.DOWN;
796
                }
797
                viewer.getTable().setSortDirection(dir);
798
                viewer.getTable().setSortColumn(column);
799
                viewer.refresh();
800
            }
801
        };
802
        return selectionAdapter;
803
    }
804

    
805
    public void doSave(IProgressMonitor monitor) {
806
        try {
807
          //  monitor.beginTask(Messages.ChecklistEditor_SAVE_EDITOR, 1);
808
//            if (!conversation.isBound()) {
809
//                conversation.bind();
810
//            }
811

    
812
            this.checklistEditorInput.merge();
813

    
814
            //conversation.commit(true);
815
            setDirty(false);
816
  //          monitor.worked(1);
817
        } finally {
818
   //         monitor.done();
819
        }
820

    
821
    }
822

    
823
    public void init(ChecklistEditorInput input) {
824
        checklistEditorInput = input;
825
        thisPart.setLabel(DISTRIBUTION_EDITOR+": " + checklistEditorInput.getName());
826
        conversation = checklistEditorInput.getConversation();
827
        conversation.registerForDataStoreChanges(this);
828

    
829
        //propagate selection
830
        selectionChangedListener = (event -> selService.setSelection(
831
               DistributionEditorHelper.getDistributionForColumn(event, areaPosition)));
832

    
833
        viewer.addSelectionChangedListener(selectionChangedListener);
834

    
835

    
836
        loadDataInput();
837
    }
838
    private static final List<String> NODE_INIT_STRATEGY = Arrays.asList(new String[] { "descriptions", //$NON-NLS-1$
839
            "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$
840
            "childNodes.taxon.name", "taxonNodes", "taxonNodes.*", "taxonNodes.taxon.*", "taxon.*", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
841
            "taxon.descriptions", "taxon.sec", "taxon.name.*", "terms", "name.*", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
842
            "name.rank.representations", "name.status.type.representations", "stateData.$" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
843

    
844
    /*
845
     * (non-Javadoc)
846
     *
847
     * @see
848
     * eu.etaxonomy.taxeditor.model.IDirtyMarkableSelectionProvider#changed(
849
     * java.lang.Object)
850
     */
851
    @Override
852
    public void changed(Object element) {
853
        if (element != null) {
854
            viewer.update(element, null);
855

    
856
            if (element instanceof Taxon){
857
                checklistEditorInput.addTaxonToSave((Taxon)element);
858
            }
859
            setDirty(true);
860
        }
861
    }
862

    
863
    /* (non-Javadoc)
864
     * @see eu.etaxonomy.taxeditor.model.IDirtyMarkableSelectionProvider#forceDirty()
865
     */
866
    @Override
867
    public void forceDirty() {
868
        changed(null);
869
    }
870

    
871
    public void setDirty(boolean dirty) {
872
        this.dirty.setDirty(dirty);
873
    }
874

    
875
    /*
876
     * (non-Javadoc)
877
     *
878
     * @see org.eclipse.ui.forms.editor.FormEditor#isDirty()
879
     */
880
    public boolean isDirty() {
881
        return dirty.isDirty();
882
    }
883

    
884

    
885
    /**
886
     * @return the labelProvider
887
     */
888
    public ChecklistLabelProvider getLabelProvider() {
889
        return labelProvider;
890
    }
891

    
892
    /* (non-Javadoc)
893
     * @see eu.etaxonomy.cdm.persistence.hibernate.ICdmPostDataChangeObserver#update(eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap)
894
     */
895
    @Override
896
    public void update(CdmDataChangeMap arg0) {
897
        // TODO Auto-generated method stub
898

    
899
    }
900

    
901
    /* (non-Javadoc)
902
     * @see eu.etaxonomy.cdm.api.conversation.IConversationEnabled#getConversationHolder()
903
     */
904
    @Override
905
    public ConversationHolder getConversationHolder() {
906
        return conversation;
907
    }
908

    
909
    /* (non-Javadoc)
910
     * @see eu.etaxonomy.taxeditor.workbench.part.IE4SavablePart#save(org.eclipse.core.runtime.IProgressMonitor)
911
     */
912
    @Override
913
    @Persist
914
    public void save(IProgressMonitor monitor) {
915
        doSave(monitor);
916
    }
917

    
918

    
919
}
(2-2/5)