Project

General

Profile

Download (29.4 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
import java.util.ArrayList;
13
import java.util.Arrays;
14
import java.util.Collection;
15
import java.util.Collections;
16
import java.util.HashMap;
17
import java.util.List;
18
import java.util.Map;
19
import java.util.SortedSet;
20
import java.util.UUID;
21

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

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

    
59
import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
60
import eu.etaxonomy.cdm.api.conversation.IConversationEnabled;
61
import eu.etaxonomy.cdm.api.service.ITaxonNodeService;
62
import eu.etaxonomy.cdm.model.common.DefinedTermBase;
63
import eu.etaxonomy.cdm.model.taxon.Classification;
64
import eu.etaxonomy.cdm.model.taxon.Taxon;
65
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
66
import eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap;
67
import eu.etaxonomy.taxeditor.editor.EditorUtil;
68
import eu.etaxonomy.taxeditor.editor.IDistributionEditor;
69
import eu.etaxonomy.taxeditor.editor.internal.TaxeditorEditorPlugin;
70
import eu.etaxonomy.taxeditor.editor.l10n.Messages;
71
import eu.etaxonomy.taxeditor.editor.view.checklist.ChecklistContentProvider;
72
import eu.etaxonomy.taxeditor.editor.view.checklist.ChecklistEditorComparator;
73
import eu.etaxonomy.taxeditor.editor.view.checklist.ChecklistEditorInput;
74
import eu.etaxonomy.taxeditor.editor.view.checklist.ChecklistLabelProvider;
75
import eu.etaxonomy.taxeditor.editor.view.checklist.filter.ChecklistEditorFilter;
76
import eu.etaxonomy.taxeditor.editor.view.checklist.listener.ChecklistFocusListener;
77
import eu.etaxonomy.taxeditor.editor.view.checklist.listener.ChecklistModifyListener;
78
import eu.etaxonomy.taxeditor.model.IDirtyMarkable;
79
import eu.etaxonomy.taxeditor.model.IPartContentHasDetails;
80
import eu.etaxonomy.taxeditor.preference.PreferencesUtil;
81
import eu.etaxonomy.taxeditor.preference.Resources;
82
import eu.etaxonomy.taxeditor.preference.wizard.AvailableDistributionWizard;
83
import eu.etaxonomy.taxeditor.store.CdmStore;
84
import eu.etaxonomy.taxeditor.store.StoreUtil;
85
import eu.etaxonomy.taxeditor.workbench.part.IE4SavablePart;
86

    
87
/**
88
 *
89
 * @author k.luther
90
 *
91
 */
92
public class ChecklistEditorE4 implements  IConversationEnabled,
93
       IDirtyMarkable, IPartContentHasDetails, IE4SavablePart, IDistributionEditor{
94

    
95
    private static final String DISTRIBUTION_EDITOR = "Distribution Editor";
96
	private static final String LOADING_TAXA = Messages.ChecklistEditor_LOAD_TAXA;
97
    private static final String UNKNOWN = Messages.ChecklistEditor_UNKNOWN;
98
    private static final String ELEMENT_COUNT = Messages.ChecklistEditor_ELEMENT_COUNT;
99
    public static final String TYPE_FILTER_TEXT = "type filter text"; //$NON-NLS-1$
100

    
101
    private static final Logger logger = Logger.getLogger(ChecklistEditorE4.class);
102

    
103
    /**
104
     * Constant
105
     * <code>ID="eu.etaxonomy.taxeditor.store.datasource"{trunked}</code>
106
     */
107
    public static String ID = "eu.etaxonomy.taxeditor.editor.view.checklist.ChecklistEditor"; //$NON-NLS-1$
108

    
109
    private TableViewer viewer;
110

    
111
    private ITaxonNodeService taxonNodeService;
112

    
113
    private ChecklistEditorComparator comparator;
114

    
115
    private ChecklistEditorInput checklistEditorInput;
116

    
117
    private ConversationHolder conversation;
118

    
119
    private Integer countNodes;
120

    
121
    private List<TaxonNode> selectedTaxonNodes;
122

    
123
    @Inject
124
    private MPart thisPart;
125

    
126
    @Inject
127
    private MDirtyable dirty;
128

    
129
    @Inject
130
    private ESelectionService selService;
131

    
132
    private ISelectionChangedListener selectionChangedListener;
133

    
134
    private ChecklistEditorFilter filter;
135

    
136
    private Label statusLabel;
137

    
138
    private ChecklistLabelProvider labelProvider;
139
//TODO: maybe it is better to use a hashMap for better handling of adding and removing terms??
140
    private Map<UUID, Integer> areaPosition= new HashMap();
141

    
142
    private ToolItem toolItem;
143
	private ChecklistDropdownSelectionListenerE4 dropListener;
144
	private Text searchText;
145

    
146
	public Map<UUID, Integer> getAreaPosition() {
147
        return areaPosition;
148
    }
149
    /**
150
     * @return the selectedTaxonNodes
151
     */
152
    public List<TaxonNode> getSelectedTaxonNodes() {
153
        return selectedTaxonNodes;
154
    }
155

    
156
    /**
157
     * @param selectedTaxonNodes
158
     *            the selectedTaxonNodes to set
159
     */
160
    public void setSelectedTaxonNodes(List<TaxonNode> selectedTaxonNodes) {
161
        this.selectedTaxonNodes = selectedTaxonNodes;
162
    }
163

    
164
    @Inject
165
    public ChecklistEditorE4() {
166
    }
167

    
168
    /** {@inheritDoc} */
169
    @PostConstruct
170
    public void createPartControl(Composite parent) {
171
    	if (!CdmStore.isActive()){
172
            return;
173
        }
174
        taxonNodeService = CdmStore.getService(ITaxonNodeService.class);
175
        filter = new ChecklistEditorFilter();
176
        createTopComposite(parent);
177
        viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
178

    
179
        //the focuzsCellManager should return the distribution!!!
180
        TableViewerFocusCellManager focusCellManager = new TableViewerFocusCellManager(viewer, new FocusCellOwnerDrawHighlighter (viewer));
181
        TableViewerEditor.create(viewer, focusCellManager, new ColumnViewerEditorActivationStrategy(viewer), TableViewerEditor.KEYBOARD_ACTIVATION);
182

    
183

    
184
//        viewer.addSelectionChangedListener(new ISelectionChangedListener() {
185
//        	  @Override
186
//        	  public void selectionChanged(SelectionChangedEvent event) {
187
//        	    IStructuredSelection selection = viewer.getStructuredSelection();
188
//        	    Object firstElement = selection.getFirstElement();
189
//        	    // do something with it
190
//        	  }
191
//
192
//
193
//        	});
194

    
195

    
196

    
197
        labelProvider = new ChecklistLabelProvider(this.viewer);
198
       // SortedSet<DefinedTermBase> termSet = labelProvider.getNamedAreas(true);
199
//        terms = new HashMap();
200
//        for (DefinedTermBase term : termSet){
201
//                terms.put(term.getUuid(), term);
202
//        }
203
//        if (terms == null){
204
//			MessagingUtils.informationDialog(Messages.ChecklistEditor_NO_AREAS, Messages.ChecklistEditor_NO_AREAS_MESSAGE);
205
//			this.dispose();
206
//			return;
207
//		}
208

    
209

    
210
        viewer.addFilter(filter);
211
        createTable();
212

    
213
        viewer.setContentProvider(new ChecklistContentProvider());
214
        viewer.setLabelProvider(this.labelProvider);
215
        comparator = new ChecklistEditorComparator();
216
        viewer.setComparator(comparator);
217
        final ModifyListener modifyListener = new ChecklistModifyListener(viewer, filter, searchText);
218

    
219
        searchText.addFocusListener(new ChecklistFocusListener(searchText, modifyListener));
220
        searchText.addModifyListener(modifyListener);
221
        createGridDataForViewerLayout();
222
        createStatusBar(parent);
223
        createToolbar(parent);
224
    }
225

    
226
    /**
227
     * @param parent
228
     */
229
    private void createTopComposite(Composite parent) {
230
        GridLayout gridLayout = new GridLayout(3, false);
231
        gridLayout.marginWidth = 0;
232
        gridLayout.marginHeight = 0;
233
        parent.setLayout(gridLayout);
234

    
235
       searchText = createSearchBar(parent);
236

    
237

    
238
       // getSite().setSelectionProvider(viewer);
239

    
240

    
241

    
242

    
243

    
244
    }
245

    
246
	private void createGridDataForViewerLayout() {
247
		GridData gridData = new GridData();
248
		gridData.verticalAlignment = GridData.FILL;
249
        gridData.horizontalSpan = 3;
250
        gridData.grabExcessHorizontalSpace = true;
251
        gridData.grabExcessVerticalSpace = true;
252
        gridData.horizontalAlignment = GridData.FILL;
253
        viewer.getControl().setLayoutData(gridData);
254
	}
255

    
256
    /**
257
     * @param parent
258
     * @return
259
     */
260
    private Text createSearchBar(Composite parent) {
261
        Label searchLabel = new Label(parent, SWT.NONE);
262
        searchLabel.setText(Messages.ChecklistEditor_SEARCH);
263
        final Text searchText = new Text(parent, SWT.BORDER | SWT.SEARCH | SWT.ICON_SEARCH | SWT.CANCEL);
264
        searchText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
265
        searchText.setForeground(EditorUtil.getColor(Resources.SEARCH_VIEW_FOREGROUND));
266
        searchText.setText(TYPE_FILTER_TEXT);
267
        return searchText;
268
    }
269

    
270
    /**
271
     * @param parent
272
     */
273
    private void createToolbar(Composite parent) {
274
        ToolBar toolBar = new ToolBar(parent, SWT.NONE);
275
      //  toolItem = new ToolItem(toolBar, SWT.DROP_DOWN | SWT.BORDER);
276
        toolItem = new ToolItem(toolBar, SWT.BUTTON1);
277

    
278
        toolItem.setText(Messages.ChecklistEditor_DIST_STATUS);
279
        toolItem.setToolTipText(Messages.ChecklistEditor_DIST_STATUS_TOOLTIP);
280
        //createToolbarItems();
281
      //  toolItem.addSelectionListener(dropListener);
282
        toolItem.addSelectionListener(new SelectionAdapter() {
283
            @Override
284
            public void widgetSelected(SelectionEvent event) {
285
                AvailableDistributionWizard availableDistributionWizard = new AvailableDistributionWizard();
286
                WizardDialog dialog = new WizardDialog(StoreUtil.getShell(),
287
                        availableDistributionWizard);
288

    
289
                int open = dialog.open();
290
                if(open == 0){
291
                    reload();
292
                }
293
            }
294
        });
295
        toolBar.pack();
296
    }
297

    
298
	private void createToolbarItems() {
299
	    SortedSet<DefinedTermBase> termsList = getLabelProvider().getNamedAreas(false);
300
		dropListener = new ChecklistDropdownSelectionListenerE4(toolItem, this, termsList);
301

    
302
        for (DefinedTermBase<DefinedTermBase> term : termsList) {
303
            if(term!=null){
304
                dropListener.add(term);
305
            }
306
        }
307
	}
308

    
309
    private void createStatusBar(Composite composite) {
310
        GridData gridData = new GridData();
311
        gridData.horizontalSpan = 3;
312
        gridData.grabExcessHorizontalSpace = true;
313
        gridData.horizontalAlignment = GridData.FILL;
314

    
315
        statusLabel = new Label(composite, SWT.LEFT);
316
        statusLabel.setText(ELEMENT_COUNT + (countNodes != null ? countNodes : UNKNOWN));
317
        statusLabel.setLayoutData(gridData);
318
    }
319

    
320
    private void createTable() {
321
        Table table = viewer.getTable();//new Table(parent, viewer.getTable().getStyle());
322
        List<String> titles = new ArrayList<String>();
323
        List<Integer> bounds = new ArrayList<Integer>();
324
        if (PreferencesUtil.isShowRankInChecklistEditor()){
325
            Collections.addAll(titles, Messages.ChecklistEditor_TAXON,  Messages.ChecklistEditor_RANK);
326
            Collections.addAll(bounds, 300, 200);
327
        } else{
328
            Collections.addAll(titles, Messages.ChecklistEditor_TAXON);
329
            Collections.addAll(bounds, 300);
330
        }
331

    
332

    
333
      //  Map<Integer, Boolean> restoreValuesForColumnWidth =
334
        restoreValuesForColumnWidth(titles, bounds);
335
        createInitalDistributionColumns(table, titles, bounds);
336
        table.setSortDirection(SWT.DOWN);
337
        table.setHeaderVisible(true);
338
        table.setLinesVisible(true);
339
	}
340
    /**
341
     * This method creates initially the distribution columns for a table. It should only be called for creation.<br>
342
     *<p>
343
     *
344
     *<b>Notice:</b> If you want to add additional columns later please use <b>addTableViewerColumn()</b>
345
     *
346
     * @param table
347
     * @param titles
348
     * @param bounds
349
     * @param restoreValuesForColumnWidth
350
     */
351
	private void createInitalDistributionColumns(Table table,
352
			List<String> titles, List<Integer> bounds) {
353
		for (int columnIndex = 0; columnIndex < titles.size(); columnIndex++) {
354
            TableViewerColumn column = new TableViewerColumn(viewer, SWT.NONE);
355
            column.getColumn().setText(titles.get(columnIndex));
356
            column.getColumn().setWidth(bounds.get(columnIndex));
357
            column.getColumn().setResizable(true);
358
            column.getColumn().setMoveable(true);
359
            column.getColumn().addSelectionListener(getSelectionAdapter(column.getColumn(), columnIndex));
360
            if (columnIndex == 0) {
361
                table.setSortColumn(column.getColumn());
362
            }
363
            if (columnIndex == 1 && PreferencesUtil.isShowRankInChecklistEditor()) {
364
            	/** uncommented it for now because no rank editing is wanted **/
365
//                column.setEditingSupport(new RankEditingSupport(viewer, this));
366
            }
367
            if ((columnIndex == 1 && !PreferencesUtil.isShowRankInChecklistEditor()) || columnIndex >= 2 ) {
368
                //read PrefrenceStore to setWidth according to last saved state
369
//                if(restoreValuesForColumnWidth.get(columnIndex)){
370
                    column.getColumn().setWidth(50);
371
//                }else{
372
//                    column.getColumn().setWidth(0);
373
//                }
374
                column.setEditingSupport(new DistributionEditingSupportE4(viewer, this, columnIndex));
375

    
376
            }
377
        }
378
	}
379

    
380
    /**
381
     * This methods loads the last opened distribution columns for the table viewer from the prefrence store.<br>
382
     *<p>
383
     * <b>Notice:</b> It adds also the TitleCache to the titles list for the header of each column.<p>
384
     *
385
     * @param titles
386
     * @param bounds
387
     * @return Map<Integer, Boolean>
388
     */
389
	private void restoreValuesForColumnWidth(List<String> titles,
390
			List<Integer> bounds) {
391
//		Map<Integer, Boolean> restoreColumnWidth = new HashMap<Integer, Boolean>();
392
		if (labelProvider.getNamedAreas(true) != null) {
393
		    int columnIndex;
394
		    if (PreferencesUtil.isShowRankInChecklistEditor()){
395
		        columnIndex = 2;
396
		    } else{
397
		        columnIndex = 1;
398
		    }
399
            for (DefinedTermBase<DefinedTermBase> term : getLabelProvider().getNamedAreas(false)) {
400
                if(term != null){
401
                   // restoreColumnWidth.put(columnIndex, PreferencesUtil.getPreferenceStore().getBoolean(term.getUuid().toString()));
402
                    areaPosition.put(term.getUuid(), columnIndex);
403
                    if (PreferencesUtil.isShowIdInVocabularyInChecklistEditor()){
404
                        if (term.getIdInVocabulary() != null){
405
                            titles.add(term.getIdInVocabulary());
406
                        } else{
407
                            titles.add(term.getTitleCache());
408
                        }
409
                    }else{
410
                        titles.add(term.getTitleCache());
411
                    }
412
                    bounds.add(200);
413
                    columnIndex++;
414
                }
415
            }
416
        }
417
//		return restoreColumnWidth;
418
	}
419

    
420
    /**
421
     * This method adds new DistributionColumns to an existing table.
422
     *
423
     * @param title
424
     * @param bound
425
     * @param colNumber
426
     * @return
427
     */
428
    private TableViewerColumn addTableViewerColumn(String title, int bound, final int colNumber, DefinedTermBase term) {
429

    
430
        final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.FULL_SELECTION);
431
        final TableColumn column = viewerColumn.getColumn();
432
        column.setText(title);
433
        String[] UuidAndLable = new String[2];
434
        UuidAndLable[0] = term.getUuid().toString();
435
        UuidAndLable[1] = title;
436
        column.setData(UuidAndLable);
437
        column.setWidth(200);
438

    
439
        viewerColumn.setEditingSupport(new DistributionEditingSupportE4(viewer, this, colNumber));
440
        column.setResizable(true);
441
        column.setMoveable(true);
442
        return viewerColumn;
443
      }
444

    
445

    
446

    
447
    /**
448
     *
449
     * pull data from database and set input for view
450
     *
451
     */
452
    private void loadDataInput() {
453
        Classification classification = checklistEditorInput.getClassification();
454
        TaxonNode taxonNode = checklistEditorInput.getTaxonNode();
455
        if (classification != null && taxonNode == null) {
456
            countNodes = taxonNodeService.countAllNodesForClassification(classification);
457
//            statusLabel.setText(ELEMENT_COUNT + (countNodes != null ? countNodes : UNKNOWN));
458
            // This should not kill the view nor the editor if something goes
459
            // wrong
460
            // TODO: don't load the whole taxonNode Object but rather a small
461
            // and simple Solution
462
            // FIXME: May be don't open classification which are greater than
463
            // 3000 Taxa
464
            selectedTaxonNodes = taxonNodeService.listAllNodesForClassification(classification, 0, countNodes);
465
            countNodes = selectedTaxonNodes.size();
466
            statusLabel.setText(ELEMENT_COUNT + (countNodes != null ? countNodes : UNKNOWN));
467
            viewer.setInput(checklistEditorInput.getTaxa());
468
//            Job checkListJob = new ChecklistJob(LOADING_TAXA, selectedTaxonNodes);
469
//            checkListJob.schedule(Job.LONG);
470

    
471
        }
472
        if (taxonNode != null) {
473
        	boolean includeUnpublished = true;
474
            selectedTaxonNodes = taxonNodeService.loadChildNodesOfTaxonNode(taxonNode, NODE_INIT_STRATEGY, true, includeUnpublished, null);
475
            countNodes = selectedTaxonNodes.size();
476
            viewer.setInput(checklistEditorInput.getTaxa());
477
            statusLabel.setText(ELEMENT_COUNT + (countNodes != null ? countNodes : UNKNOWN));
478
//            Job checkListJob = new ChecklistJob(LOADING_TAXA, selectedTaxonNodes);
479
//            checkListJob.schedule(Job.LONG);
480
//          getService().schedule(new ChecklistJob(LOADING_TAXA, selectedTaxonNodes), Job.LONG);
481
        }
482
    }
483

    
484

    
485
    @PreDestroy
486
    public void dispose() {
487
    	if(conversation!=null){
488
    		conversation.unregisterForDataStoreChanges(this);
489
    		conversation.close();
490
    	}
491
    	conversation = null;
492
    	if(checklistEditorInput!=null){
493
    	    checklistEditorInput.dispose();
494
    	}
495

    
496
    }
497

    
498
    /** {@inheritDoc} */
499
    @Focus
500
    public void setFocus() {
501
    	if(viewer!=null && viewer.getControl()!=null && !viewer.getControl().isDisposed()) {
502
            viewer.getControl().setFocus();
503
        }
504
    }
505

    
506
    //FIXME E4 migrate
507
//    /*
508
//     * (non-Javadoc)
509
//     *
510
//     * @see org.eclipse.ui.part.WorkbenchPart#showBusy(boolean)
511
//     */
512
//    /** {@inheritDoc} */
513
//    @Override
514
//    public void showBusy(boolean busy) {
515
//        super.showBusy(busy);
516
//        // viewer.getTable().setEnabled(!busy);
517
//        if (busy) {
518
//            partNameCache = getPartName();
519
//            setPartName(String.format(Messages.ChecklistEditor_LOAD_CNT_TAXA, countNodes));
520
//        } else {
521
//            if (partNameCache != null) {
522
//                setPartName(partNameCache);
523
//            }
524
//        }
525
//    }
526

    
527
    /**
528
     * <p>
529
     * Getter for the field <code>viewer</code>.
530
     * </p>
531
     *
532
     * @return a {@link org.eclipse.jface.viewers.StructuredViewer} object.
533
     */
534
    public StructuredViewer getViewer() {
535
        return viewer;
536
    }
537

    
538
    public void refresh() {
539
        viewer.refresh();
540
    }
541

    
542
    /**
543
     * This method should only be called for adding new Distribution columns and reloading the table.<br>
544
     * It will hide the old distribution column and load the newly added columns.<br>
545
     * <p>
546
     * <b>Notice:</b> for data update please use <b>refresh()</b>
547
     *
548
     */
549
    @SuppressWarnings({ "unchecked", "rawtypes" })
550
	public void reload(){
551
    	//create new Items for Dropdown menue
552
    	Table table = viewer.getTable();
553
    	table.setRedraw(false);
554
    	Collection<DefinedTermBase> oldTerms = labelProvider.getNamedAreas(false);
555

    
556
//    	if (PreferencesUtil.isShowIdInVocabularyInChecklistEditor()){
557
//
558
//    	} else{
559
//    	    terms = (SortedSet<DefinedTermBase>) labelProvider.getTermsOrderedByLabels(labelProvider.getNamedAreas(), CdmStore.getDefaultLanguage());
560
//    	}
561
    	SortedSet<DefinedTermBase> newTerms = labelProvider.getNamedAreas(true);
562
    	//terms = newTerms;
563
//    	toolItem.removeSelectionListener(dropListener);
564
////    	hideDistributionColumns(oldTerms);
565
//    	createToolbarItems();
566
//    	toolItem.addSelectionListener(dropListener);
567

    
568
    	//check which terms are deleted and which are new.
569
    	TableColumn[] columns = viewer.getTable().getColumns() ;
570
    	int index = 0;
571

    
572
      for (TableColumn column: columns){
573
          if ((!PreferencesUtil.isShowRankInChecklistEditor() && index > 0) || (index > 1)) {
574
                column.dispose();
575
            }
576
          index++;
577
      }
578
      if (oldTerms != null){
579
    	for (DefinedTermBase oldTerm:oldTerms){
580
            boolean delete = true;
581
            for (DefinedTermBase term: newTerms){
582
                   if(oldTerm.getUuid().equals(term.getUuid())){
583
                       delete = false;
584
                       break;
585
                   }
586

    
587
            }
588
            if (delete){
589
               // viewer.getTable().remove(areaPosition.get(oldTerm.getUuid()));
590
                areaPosition.remove(oldTerm.getUuid());
591

    
592
            }
593
        }
594
    	updateColumnIndex();
595
      }
596

    
597

    
598
    	for (DefinedTermBase term:newTerms){
599
    	    boolean isNew = true;
600

    
601
    	    Integer position = areaPosition.get(term.getUuid());
602

    
603
    	    String termLable = term.getTitleCache();;
604
            if (PreferencesUtil.isShowIdInVocabularyInChecklistEditor()){
605
                if (term.getIdInVocabulary() != null){
606
                    termLable = term.getIdInVocabulary();
607
                }
608
            }
609

    
610
            if (position == null){
611
                int count = viewer.getTable().getColumnCount();
612
                TableViewerColumn column= addTableViewerColumn(termLable, 200, count, term);
613
                areaPosition.put(term.getUuid(), Integer.valueOf(count));
614
            }else{
615
                TableViewerColumn column= addTableViewerColumn(termLable, 200, position, term);
616
            }
617

    
618
           // acitivateNewColumnInDropDownMenu(term);
619
    	}
620

    
621

    
622

    
623
//    	for(DefinedTermBase term:terms.values()){
624
//    		int count = viewer.getTable().getColumnCount();
625
//
626
//    		//add new terms
627
//    		for (TableColumn column: columns){
628
//    		    if (terms.){
629
//    		        break;
630
//    		    }
631
//    		}
632
//
633
////    		String termLable = term.getTitleCache();;
634
////    		if (PreferencesUtil.isShowIdInVocabularyInChecklistEditor()){
635
////    			if (term.getIdInVocabulary() != null){
636
////    				termLable = term.getIdInVocabulary();
637
////    	        }
638
////    		}
639
////    		addTableViewerColumn(termLable, 200, count);
640
////    		acitivateNewColumnInDropDownMenu(term);
641
    //	}
642

    
643
        viewer.setLabelProvider(labelProvider);
644
//        getService().schedule(new ChecklistJob(LOADING_TAXA, selectedTaxonNodes), Job.LONG);
645
        table.setRedraw(true);
646
    	viewer.refresh();
647
    }
648

    
649
	/**
650
     *
651
     */
652
    private void updateColumnIndex() {
653
        int columnIndex;
654
        if (PreferencesUtil.isShowRankInChecklistEditor()){
655
            columnIndex = 2;
656
        } else{
657
            columnIndex = 1;
658
        }
659
        for (UUID uuid:areaPosition.keySet()){
660
            areaPosition.put(uuid, columnIndex);
661
            columnIndex++;
662
        }
663

    
664
    }
665
    private void acitivateNewColumnInDropDownMenu(DefinedTermBase term) {
666
		Menu menu = dropListener.getMenu();
667
		MenuItem[] items = menu.getItems();
668
		for(MenuItem item: items){
669
			if(item.getText().equalsIgnoreCase(term.getTitleCache())){
670
				item.setSelection(true);
671
				PreferencesUtil.getPreferenceStore().setValue(term.getUuid().toString(), true);
672
			}
673
		}
674
	}
675

    
676
	private void hideDistributionColumns(Collection<DefinedTermBase> oldTerms) {
677
		TableColumn[] columns = viewer.getTable().getColumns();
678
    	for(int i=4; i<columns.length; i++){
679
    		//remove all columns
680
    		columns[i].dispose();
681
    		Menu menu = dropListener.getMenu();
682
    		int itemCount = menu.getItemCount();
683
    		MenuItem item = menu.getItem(i-3);
684
    		item.setSelection(false);
685
    	}
686
    	if(oldTerms != null){
687
    		for(DefinedTermBase term : oldTerms){
688
    			PreferencesUtil.getPreferenceStore().setValue(term.getUuid().toString(), false);
689
    		}
690
    	}
691
	}
692

    
693
    /**
694
     * <p>
695
     * Getter for the field <code>service</code>.
696
     * </p>
697
     *
698
     * @return the service
699
     */
700
    public IWorkbenchSiteProgressService getService() {
701
        return TaxeditorEditorPlugin.getDefault().getWorkbench().getService(IWorkbenchSiteProgressService.class);
702
    }
703

    
704
    private SelectionAdapter getSelectionAdapter(final TableColumn column, final int index) {
705
        SelectionAdapter selectionAdapter = new SelectionAdapter() {
706
            @Override
707
            public void widgetSelected(SelectionEvent e) {
708
                comparator.setColumn(index);
709
                int dir = viewer.getTable().getSortDirection();
710
                if (viewer.getTable().getSortColumn() == column) {
711
                    dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
712
                } else {
713
                    dir = SWT.DOWN;
714
                }
715
                viewer.getTable().setSortDirection(dir);
716
                viewer.getTable().setSortColumn(column);
717
                viewer.refresh();
718
            }
719
        };
720
        return selectionAdapter;
721
    }
722

    
723
    public void doSave(IProgressMonitor monitor) {
724
        try {
725
            monitor.beginTask(Messages.ChecklistEditor_SAVE_EDITOR, 1);
726
            if (!conversation.isBound()) {
727
                conversation.bind();
728
            }
729

    
730
            this.checklistEditorInput.merge();
731

    
732
            conversation.commit(true);
733
            setDirty(false);
734
            monitor.worked(1);
735
        } finally {
736
            monitor.done();
737
        }
738

    
739
    }
740

    
741
    public void init(ChecklistEditorInput input) {
742
        checklistEditorInput = input;
743
        thisPart.setLabel(DISTRIBUTION_EDITOR+": " + checklistEditorInput.getName());
744
        conversation = checklistEditorInput.getConversation();
745
        conversation.registerForDataStoreChanges(this);
746

    
747
        //propagate selection
748
        selectionChangedListener = (event -> selService.setSelection(
749
               DistributionEditorHelper.getDistributionForColumn(event, areaPosition)));
750

    
751
        viewer.addSelectionChangedListener(selectionChangedListener);
752

    
753

    
754
        loadDataInput();
755
    }
756
    private static final List<String> NODE_INIT_STRATEGY = Arrays.asList(new String[] { "descriptions", //$NON-NLS-1$
757
            "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$
758
            "childNodes.taxon.name", "taxonNodes", "taxonNodes.*", "taxonNodes.taxon.*", "taxon.*", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
759
            "taxon.descriptions", "taxon.sec", "taxon.name.*", "terms", "name.*", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
760
            "name.rank.representations", "name.status.type.representations", "stateData.$" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
761

    
762
    /*
763
     * (non-Javadoc)
764
     *
765
     * @see
766
     * eu.etaxonomy.taxeditor.model.IDirtyMarkableSelectionProvider#changed(
767
     * java.lang.Object)
768
     */
769
    @Override
770
    public void changed(Object element) {
771
        if (element != null) {
772
            viewer.update(element, null);
773
            if (element instanceof Taxon){
774
                checklistEditorInput.addTaxonToSave((Taxon)element);
775
            }
776
            setDirty(true);
777
        }
778
    }
779

    
780
    /* (non-Javadoc)
781
     * @see eu.etaxonomy.taxeditor.model.IDirtyMarkableSelectionProvider#forceDirty()
782
     */
783
    @Override
784
    public void forceDirty() {
785
        changed(null);
786
    }
787

    
788
    public void setDirty(boolean dirty) {
789
        this.dirty.setDirty(dirty);
790
    }
791

    
792
    /*
793
     * (non-Javadoc)
794
     *
795
     * @see org.eclipse.ui.forms.editor.FormEditor#isDirty()
796
     */
797
    public boolean isDirty() {
798
        return dirty.isDirty();
799
    }
800

    
801

    
802
    /**
803
     * @return the labelProvider
804
     */
805
    public ChecklistLabelProvider getLabelProvider() {
806
        return labelProvider;
807
    }
808

    
809
    /* (non-Javadoc)
810
     * @see eu.etaxonomy.cdm.persistence.hibernate.ICdmPostDataChangeObserver#update(eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap)
811
     */
812
    @Override
813
    public void update(CdmDataChangeMap arg0) {
814
        // TODO Auto-generated method stub
815

    
816
    }
817

    
818
    /* (non-Javadoc)
819
     * @see eu.etaxonomy.cdm.api.conversation.IConversationEnabled#getConversationHolder()
820
     */
821
    @Override
822
    public ConversationHolder getConversationHolder() {
823
        return conversation;
824
    }
825

    
826
    /* (non-Javadoc)
827
     * @see eu.etaxonomy.taxeditor.workbench.part.IE4SavablePart#save(org.eclipse.core.runtime.IProgressMonitor)
828
     */
829
    @Override
830
    @Persist
831
    public void save(IProgressMonitor monitor) {
832
        doSave(monitor);
833
    }
834

    
835

    
836
}
(2-2/4)