Project

General

Profile

Download (33.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
    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
                String defaultSourceStr = (defaultSource == null) ? "" : "Default Source Reference: " + defaultSource.getTitleCache();
352
                if (defaultSourceStr.length()> 100){
353
                	defaultSourceStr = defaultSourceStr.substring(0, 98) + "...";
354
                }
355
                statusLabelSourceReference.setText(defaultSourceStr);
356
                button2.setBackground(EditorUtil.getColor(Resources.COLOR_CONTROL_SELECTED));
357
            }
358

    
359
        });
360

    
361
        parent.pack();
362
        return searchText;
363
    }
364

    
365
    /**
366
     * @param parent
367
     */
368
    private void createToolbar(Composite parent) {
369
        ToolBar toolBar = new ToolBar(parent, SWT.BORDER);
370
      //  toolItem = new ToolItem(toolBar, SWT.DROP_DOWN | SWT.BORDER);
371

    
372
        toolItem = new ToolItem(toolBar, SWT.PUSH| SWT.BORDER);
373

    
374

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

    
386
                int open = dialog.open();
387
                if(open == 0){
388
                    reload();
389
                }
390
            }
391
        });
392
        toolItem2 = new ToolItem(toolBar, SWT.PUSH | SWT.BORDER);
393

    
394

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

    
405
            }
406
        });
407

    
408
        toolBar.pack();
409
    }
410

    
411

    
412

    
413
    private void createStatusBar(Composite composite) {
414
        GridData gridData = new GridData();
415
        gridData.horizontalSpan = 1;
416
        gridData.grabExcessHorizontalSpace = true;
417
        gridData.horizontalAlignment = GridData.FILL;
418

    
419
        statusLabel = new Label(composite, SWT.LEFT);
420
        statusLabel.setText(ELEMENT_COUNT + (countNodes != null ? countNodes : UNKNOWN));
421
        statusLabel.setLayoutData(gridData);
422

    
423
        statusLabelSourceReference = new Label(composite, SWT.RIGHT);
424
        statusLabelSourceReference.setLayoutData(gridData);
425
        if (defaultSource != null){
426
            statusLabelSourceReference.setText("Default Source Reference: " + defaultSource.getAbbrevTitle() != null? defaultSource.getAbbrevTitle() : defaultSource.getAbbrevTitleCache());
427

    
428
        }
429
    }
430

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

    
443

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

    
487
            }
488
        }
489
	}
490

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

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

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

    
567
        viewerColumn.setEditingSupport(new DistributionEditingSupportE4(viewer, this, colNumber));
568
        column.setResizable(true);
569
        column.setMoveable(true);
570
        return viewerColumn;
571
      }
572

    
573

    
574

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

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

    
612

    
613
    @PreDestroy
614
    public void dispose() {
615
    	if(conversation!=null){
616
    		conversation.unregisterForDataStoreChanges(this);
617
    		conversation.close();
618
    	}
619
    	conversation = null;
620
    	if(checklistEditorInput!=null){
621
    	    checklistEditorInput.dispose();
622
    	}
623

    
624
    }
625

    
626
    /** {@inheritDoc} */
627
    @Focus
628
    public void setFocus() {
629
    	if(viewer!=null && viewer.getControl()!=null && !viewer.getControl().isDisposed()) {
630
            viewer.getControl().setFocus();
631
        }
632
    }
633

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

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

    
666
    public void refresh() {
667
        viewer.refresh();
668
    }
669

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

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

    
696
    	//check which terms are deleted and which are new.
697
    	TableColumn[] columns = viewer.getTable().getColumns() ;
698
    	int index = 0;
699

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

    
715
            }
716
            if (delete){
717
               // viewer.getTable().remove(areaPosition.get(oldTerm.getUuid()));
718
                areaPosition.remove(oldTerm.getUuid());
719

    
720
            }
721
        }
722
    	updateColumnIndex();
723
      }
724

    
725

    
726
    	for (DefinedTermBase term:newTerms){
727
    	    boolean isNew = true;
728

    
729
    	    Integer position = areaPosition.get(term.getUuid());
730
    	    Representation rep = term.getPreferredRepresentation(CdmStore.getDefaultLanguage());
731

    
732
    	    String termLable = rep.getAbbreviatedLabel();
733
    	    if (termLable == null){
734
    	        termLable = rep.getLabel();
735
    	    }
736
            if (PreferencesUtil.isShowIdInVocabularyInChecklistEditor()){
737
                if (term.getIdInVocabulary() != null){
738
                    termLable = term.getIdInVocabulary();
739
                }
740
            }
741

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

    
750

    
751
    	}
752

    
753
        viewer.setLabelProvider(labelProvider);
754

    
755
        table.setRedraw(true);
756
    	viewer.refresh();
757
    }
758

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

    
774
    }
775

    
776

    
777

    
778

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

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

    
809
    public void doSave(IProgressMonitor monitor) {
810
        try {
811
          //  monitor.beginTask(Messages.ChecklistEditor_SAVE_EDITOR, 1);
812
//            if (!conversation.isBound()) {
813
//                conversation.bind();
814
//            }
815

    
816
            this.checklistEditorInput.merge();
817

    
818
            //conversation.commit(true);
819
            setDirty(false);
820
  //          monitor.worked(1);
821
        } finally {
822
   //         monitor.done();
823
        }
824

    
825
    }
826

    
827
    public void init(ChecklistEditorInput input) {
828
        checklistEditorInput = input;
829
        thisPart.setLabel(DISTRIBUTION_EDITOR+": " + checklistEditorInput.getName());
830
        conversation = checklistEditorInput.getConversation();
831
        conversation.registerForDataStoreChanges(this);
832

    
833
        //propagate selection
834
        selectionChangedListener = (event -> selService.setSelection(
835
               DistributionEditorHelper.getDistributionForColumn(event, areaPosition)));
836

    
837
        viewer.addSelectionChangedListener(selectionChangedListener);
838

    
839

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

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

    
860
            if (element instanceof Taxon){
861
                checklistEditorInput.addTaxonToSave((Taxon)element);
862
            }
863
            setDirty(true);
864
        }
865
    }
866

    
867
    /* (non-Javadoc)
868
     * @see eu.etaxonomy.taxeditor.model.IDirtyMarkableSelectionProvider#forceDirty()
869
     */
870
    @Override
871
    public void forceDirty() {
872
        changed(null);
873
    }
874

    
875
    public void setDirty(boolean dirty) {
876
        this.dirty.setDirty(dirty);
877
    }
878

    
879
    /*
880
     * (non-Javadoc)
881
     *
882
     * @see org.eclipse.ui.forms.editor.FormEditor#isDirty()
883
     */
884
    public boolean isDirty() {
885
        return dirty.isDirty();
886
    }
887

    
888

    
889
    /**
890
     * @return the labelProvider
891
     */
892
    public ChecklistLabelProvider getLabelProvider() {
893
        return labelProvider;
894
    }
895

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

    
903
    }
904

    
905
    /* (non-Javadoc)
906
     * @see eu.etaxonomy.cdm.api.conversation.IConversationEnabled#getConversationHolder()
907
     */
908
    @Override
909
    public ConversationHolder getConversationHolder() {
910
        return conversation;
911
    }
912

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

    
922

    
923
}
(2-2/5)