Project

General

Profile

Download (15.5 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
package eu.etaxonomy.taxeditor.ui.dialog.selection;
10

    
11
import java.text.Collator;
12
import java.util.ArrayList;
13
import java.util.Collections;
14
import java.util.Comparator;
15
import java.util.HashSet;
16
import java.util.Iterator;
17
import java.util.List;
18
import java.util.Set;
19
import java.util.UUID;
20

    
21
import org.apache.commons.lang3.StringUtils;
22
import org.eclipse.core.runtime.IProgressMonitor;
23
import org.eclipse.core.runtime.IStatus;
24
import org.eclipse.core.runtime.jobs.Job;
25
import org.eclipse.jface.dialogs.IDialogConstants;
26
import org.eclipse.jface.dialogs.IDialogSettings;
27
import org.eclipse.jface.viewers.ILabelProvider;
28
import org.eclipse.jface.viewers.LabelProvider;
29
import org.eclipse.jface.viewers.StructuredSelection;
30
import org.eclipse.jface.window.Window;
31
import org.eclipse.jface.wizard.WizardDialog;
32
import org.eclipse.swt.SWT;
33
import org.eclipse.swt.events.SelectionAdapter;
34
import org.eclipse.swt.events.SelectionEvent;
35
import org.eclipse.swt.events.SelectionListener;
36
import org.eclipse.swt.graphics.Cursor;
37
import org.eclipse.swt.layout.GridData;
38
import org.eclipse.swt.layout.GridLayout;
39
import org.eclipse.swt.widgets.Button;
40
import org.eclipse.swt.widgets.Composite;
41
import org.eclipse.swt.widgets.Control;
42
import org.eclipse.swt.widgets.Shell;
43
import org.eclipse.swt.widgets.Text;
44

    
45
import eu.etaxonomy.cdm.api.service.dto.EntityDTOBase;
46
import eu.etaxonomy.cdm.api.service.dto.IdentifiedEntityDTO;
47
import eu.etaxonomy.cdm.model.common.CdmBase;
48
import eu.etaxonomy.cdm.model.common.ICdmBase;
49
import eu.etaxonomy.cdm.model.common.IIdentifiableEntity;
50
import eu.etaxonomy.cdm.model.metadata.PreferencePredicate;
51
import eu.etaxonomy.cdm.persistence.dto.UuidAndTitleCache;
52
import eu.etaxonomy.taxeditor.l10n.Messages;
53
import eu.etaxonomy.taxeditor.model.MessagingUtils;
54
import eu.etaxonomy.taxeditor.newWizard.AbstractNewEntityWizard;
55
import eu.etaxonomy.taxeditor.preference.PreferencesUtil;
56
import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
57

    
58
/**
59
 * Abstract AbstractFilteredCdmResourceSelectionDialog class.
60
 *
61
 * @author n.hoffmann
62
 * @created 04.06.2009
63
 */
64
public abstract class AbstractFilteredCdmResourceSelectionDialog<T extends ICdmBase>
65
        extends SearchDialog<T> {
66

    
67
    protected List<UuidAndTitleCache<T>> model;
68
	private final Set<T> transientCdmObjects = new HashSet<>();
69
	private final String settings;
70
	protected final Integer limitOfInitialElements = null;
71

    
72
	protected Set<UUID> cdmBaseToBeFiltered;
73

    
74
	protected Job searchJob;
75

    
76
	protected AbstractFilteredCdmResourceSelectionDialog(Shell shell,
77
	        String title, boolean multi, String settings, Set<T> objectsToBeFiltered) {
78
	    super(shell, title);
79

    
80
	    setMessage(Messages.SearchDialog_patternLabel);
81
        this.settings = settings;
82
        if (objectsToBeFiltered != null){
83
            this.cdmBaseToBeFiltered = new HashSet<>();
84
            objectsToBeFiltered.forEach(filter->this.cdmBaseToBeFiltered.add(filter.getUuid()));
85
        }
86
        Cursor cursor = null;
87
        if (shell != null){
88
        	cursor = shell.getCursor();
89
        	shell.setCursor(shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT));
90
        }
91
        
92
        init();
93
        if (shell != null){   
94
        	shell.setCursor(cursor);
95
        }
96
        setListLabelProvider(createListLabelProvider());
97

    
98
	}
99

    
100
	protected AbstractFilteredCdmResourceSelectionDialog(Shell shell,
101
	        String title, boolean multi, String settings) {
102
        this(shell, title, multi, settings, (Set<T>)null);
103
	}
104

    
105
	protected AbstractFilteredCdmResourceSelectionDialog(Shell shell,
106
	        String title, boolean multi, String settings, T objectToBeFiltered) {
107
	    this(shell, title, multi, settings, objectToBeFiltered!=null?Collections.singleton(objectToBeFiltered):null);
108
	}
109

    
110
	/**
111
	 * By default, we are returning the standard list label provider
112
	 *
113
	 * Override in subclasses if you want different behavior
114
	 *
115
	 * @return
116
	 */
117
	protected ILabelProvider createDetailsLabelProvider() {
118
		return createListLabelProvider();
119
	}
120

    
121
	protected ILabelProvider createListLabelProvider() {
122
		return new FilteredCdmResourceLabelProvider();
123
	}
124

    
125
	/**
126
	 * Override in subclasses.
127
	 * Will run before initModel()
128
	 */
129
	protected void init() {}
130

    
131
	/**
132
	 * <p>getSelectionFromDialog</p>
133
	 *
134
	 * @param dialog a {@link eu.etaxonomy.taxeditor.ui.dialog.selection.AbstractFilteredCdmResourceSelectionDialog} object.
135
	 * @param <TYPE> a TYPE object.
136
	 * @return a TYPE object.
137
	 */
138
	protected static <TYPE extends CdmBase> TYPE getSelectionFromDialog(AbstractFilteredCdmResourceSelectionDialog<TYPE> dialog) {
139
	    UuidAndTitleCache<?> result = getUuidAndTitleCacheSelectionFromDialog(dialog);
140
	    if (result != null){
141
	        return dialog.getCdmObjectByUuid(result.getUuid());
142
	    } else {
143
            return null;
144
        }
145
	}
146

    
147
	/**
148
     * getSelectionFromDialog
149
     */
150
    protected static <S extends ICdmBase> UuidAndTitleCache<S> getUuidAndTitleCacheSelectionFromDialog(
151
            AbstractFilteredCdmResourceSelectionDialog<S> dialog) {
152
        if (dialog == null){
153
            return null;
154
        }
155
        int result = dialog.open();
156

    
157
        if (result == Window.CANCEL) {
158
            return null;
159
        }
160

    
161
        UuidAndTitleCache<S> uuid = dialog.getSelectedUuidAndTitleCache();
162

    
163
        return uuid;
164
    }
165

    
166
	/**
167
	 * Check if object was created during the life of this dialog. If not,
168
	 * retrieve it from the CdmStore.
169
	 */
170
	protected T getCdmObjectByUuid(UUID cdmUuid) {
171
		for (T cdmObject : transientCdmObjects) {
172
			if (cdmObject.getUuid().equals(cdmUuid)) {
173
				return cdmObject;
174
			}
175
		}
176
		return getPersistentObject(cdmUuid);
177
	}
178

    
179
	/**
180
	 * <p>getPersistentObject</p>
181
	 *
182
	 * @param uuid a {@link java.util.UUID} object.
183
	 * @return a T object.
184
	 */
185
	abstract protected T getPersistentObject(UUID uuid);
186

    
187
	/**
188
	 * <p>isObjectTransient</p>
189
	 *
190
	 * @param cdmObject a T object.
191
	 * @return a boolean.
192
	 */
193
	protected boolean isObjectTransient(T cdmObject) {
194
		return (getPersistentObject(cdmObject.getUuid()) == null);
195
	}
196

    
197
	/**
198
	 * <p>getTitle</p>
199
	 *
200
	 * @param cdmObject a T object.
201
	 * @return a {@link java.lang.String} object.
202
	 */
203
	protected String getTitle(T cdmObject) {
204
		if(cdmObject == null){
205
			return "";
206
		}
207

    
208
		if (cdmObject instanceof IIdentifiableEntity) {
209
			return ((IIdentifiableEntity) cdmObject).getTitleCache();
210
		}
211

    
212
		throw new IllegalArgumentException("Generic method only" +
213
				" supports cdmObject of type IIdentifiableEntity." +
214
				" Please implement specific method in subclass.");
215
	}
216

    
217
	/**
218
	 * Set the filter input to the Agent's title cache
219
	 *
220
	 * @param cdmObject a T object.
221
	 */
222
	protected void setPattern(T cdmObject) {
223
		String pattern = getTitle(cdmObject);
224
		getSearchField().setText(pattern);
225
		
226
	}
227

    
228
	@Override
229
    protected void fillContentProvider(IProgressMonitor progressMonitor)
230
		 {
231
		try {
232
		    if (model == null){
233
		        model = new ArrayList<UuidAndTitleCache<T>>();
234
		    }
235
			if(model != null){
236
			    if (progressMonitor != null){
237
			        progressMonitor.beginTask("Looking for entities", model.size());
238
			    }
239
			    sort();
240

    
241
			    contentProvider.reset();
242
				Iterator<UuidAndTitleCache<T>> iterator = model.iterator();
243
				UuidAndTitleCache<T> element;
244
				while(iterator.hasNext()){
245
				    element = iterator.next();
246

    
247
				    if (cdmBaseToBeFiltered == null || !cdmBaseToBeFiltered.contains(element.getUuid())){
248
				        contentProvider.add(element);
249
				    }
250
				    if (progressMonitor != null){
251
    					if (progressMonitor.isCanceled()) {
252
    						return;
253
    					}
254
    					progressMonitor.worked(1);
255
				    }
256
				}
257
				this.refresh();
258
			}else{
259

    
260
				MessagingUtils.warn(getClass(), "Model for Filtered Selection is null:" + this.getClass().getSimpleName());
261
			}
262
		}
263
		finally {
264
		    if (progressMonitor != null) {
265
                progressMonitor.done();
266
            }
267
		}
268
	}
269

    
270
    protected void sort() {
271
        Collections.sort(model, getItemsComparator());
272
    }
273

    
274
	protected IDialogSettings getDialogSettings() {
275
		IDialogSettings settings = TaxeditorStorePlugin.getDefault().getDialogSettings().getSection(getSettings());
276

    
277
		if (settings == null) {
278
			settings = TaxeditorStorePlugin.getDefault().getDialogSettings().addNewSection(getSettings());
279
		}
280
		return settings;
281
	}
282

    
283
	@Override
284
    protected Comparator<UuidAndTitleCache<T>> getItemsComparator() {
285
		return new Comparator<UuidAndTitleCache<T>>() {
286
			@Override
287
			public int compare(UuidAndTitleCache<T> entity1,
288
					UuidAndTitleCache<T> entity2) {
289
				Collator collator = Collator.getInstance();
290
				if (entity1 == entity2){
291
				    return 0;
292
				}else if (entity1 == null){
293
				    return -1;
294
				}else if (entity2 == null){
295
				    return 1;
296
				}else if (entity1.getUuid().equals(entity2.getUuid())){
297
                    return 0;
298
                }else if (entity1.getTitleCache() == null && entity2.getTitleCache() != null){
299
				    return -1;
300
				}else if (entity2.getTitleCache() == null){
301
				    return 1;
302
				}
303
				int result = collator.compare(entity1.getTitleCache(), entity2.getTitleCache());
304
				if (result == 0){
305
				    result = entity1.getUuid().compareTo(entity2.getUuid());
306
				}
307
				return result;
308
			}
309
		};
310
	}
311

    
312
	/**
313
	 * getSelectedUuidAndTitleCache
314
	 */
315
	protected UuidAndTitleCache<T> getSelectedUuidAndTitleCache() {
316
		Object result = getResult();
317
		if (result instanceof UuidAndTitleCache){
318
		    return (UuidAndTitleCache<T>) result;
319
		}
320
		return null;
321
	}
322

    
323
    private Object getResult() {
324
        StructuredSelection selection = getCurrentSelection();
325
        if (selection == null){
326
            return null;
327
        }
328
        return selection.getFirstElement();
329
    }
330

    
331
    /**
332
	 * <p>Getter for the field <code>settings</code>.</p>
333
	 *
334
	 * @return a {@link java.lang.String} object.
335
	 */
336
	public String getSettings()  {
337
		if(settings == null){
338
			throw new IllegalStateException("No SETTINGS set.");
339
		}
340
		return settings;
341
	}
342

    
343
	/**
344
	 * <p>getNewWizardLinkText</p>
345
	 *
346
	 * @return a {@link java.lang.String} object.
347
	 */
348
	protected abstract String[] getNewWizardText();
349

    
350
	/**
351
	 * <p>getNewEntityWizard</p>
352
	 * @param parameter
353
	 * @return a {@link eu.etaxonomy.taxeditor.newWizard.AbstractNewEntityWizard} object.
354
	 */
355
	protected abstract AbstractNewEntityWizard<T> getNewEntityWizard(String parameter);
356

    
357
	public class FilteredCdmResourceLabelProvider extends LabelProvider {
358
		@Override
359
		public String getText(Object element) {
360
			if (element == null) {
361
				return null;
362
			}
363
			UuidAndTitleCache<?> uuidAndTitleCache = (UuidAndTitleCache<?>) element;
364
			String titleCache = uuidAndTitleCache.getTitleCache();
365
			if(PreferencesUtil.getBooleanValue(PreferencePredicate.ShowIdInSelectionDialog.getKey())){
366
			    titleCache += " ["+uuidAndTitleCache.getId()+"]";
367
			}
368
			if (element instanceof EntityDTOBase){
369
			    titleCache += "(" + ((IdentifiedEntityDTO)element).getIdentifier().getTypeLabel() +": " + ((IdentifiedEntityDTO)element).getIdentifier().getIdentifier() + ")";
370
			}
371

    
372
            return titleCache;
373
		}
374
	}
375

    
376
//	@Override
377
//    protected Control createExtendedContentArea(Composite parent) {
378
//		String newWizardLinkText = getNewWizardLinkText();
379
////        if(newWizardLinkText != null){
380
////            newButton1 = this.createButton(this.getShell(), new_id, newWizardLinkText, false);
381
////
382
////            newButton1.addSelectionListener(getNewWizardLinkSelectionListener());
383
////			return newButton1;
384
////		}
385
//		return null;
386
//	}
387

    
388
	@Override
389
    protected void createButtonsForButtonBar(Composite parent) {
390
	    String[] newButtonText = getNewWizardText();
391

    
392
	    if (newButtonText!= null){
393
	        this.newButton1 = createButton(parent, this.new_id, newButtonText[0], false);
394
	        newButton1.addSelectionListener(getNewWizardButtonSelectionListener());
395

    
396
	        if (newButtonText.length > 1){
397
	            newButton2 = createButton(parent, this.new_id2, newButtonText[1], false);
398
	            newButton2.addSelectionListener(getNewWizardButtonSelectionListener());
399
	        }
400
	    }
401
	    Button space = createButton(parent, this.space_id, " ", false);
402
	    space.setEnabled(false);
403
	    space.setVisible(false);
404
	    GridData gridData = new GridData();
405
        gridData.grabExcessHorizontalSpace = false;
406
        gridData.widthHint = 3;
407
	    space.setLayoutData(gridData);
408
	    GridLayout gridLayout = new GridLayout();
409
	    gridLayout.makeColumnsEqualWidth= false;
410
	    if (newButtonText != null){
411
	    	gridLayout.numColumns=newButtonText.length+2;
412
	    }else{
413
	    	gridLayout.numColumns=2;
414
	    }
415
	    parent.setLayout(gridLayout);
416

    
417
        super.createButtonsForButtonBar(parent);
418
        super.getButton(IDialogConstants.OK_ID).setEnabled(false);
419
    }
420

    
421
	protected SelectionListener getNewWizardButtonSelectionListener(){
422
		return new SelectionAdapter() {
423

    
424
			@Override
425
			public void widgetSelected(SelectionEvent e) {
426
			    Object source = e.getSource();
427
			    String text = null;
428
			    if (source instanceof Button){
429
			        Button sourceButton = (Button) source;
430
			        text = sourceButton.getText();
431
			    }
432
			    AbstractNewEntityWizard<?> wizard = getNewEntityWizard(text);
433
			    if(wizard != null){
434
			        if (wizard.getEntity() == null){
435
			            wizard.init(null, null);
436
			        }
437
			        if(wizard.getEntity() != null) {
438
			            WizardDialog dialog = new WizardDialog(getShell(), wizard);
439
			            int status = dialog.open();
440

    
441
			            if (status == IStatus.OK) {
442

    
443
			                T entity = (T) wizard.getEntity();
444
			                refresh();
445
			                setPattern(entity);
446

    
447
//			                if (getConversationHolder() != null){
448
//			                    getConversationHolder().bind();
449
//			                }
450
			            }
451
			            //FIXME : Need to make sure this is a stable fix (ticket 3822)
452
//			            if (getConversationHolder() != null){
453
//			                getConversationHolder().commit();
454
//			            }
455
			        }
456
			    }
457
			}
458
		};
459
	}
460

    
461
	/**
462
	 * Don't want to add for example a taxon or synonym to itself
463
	 * so filter the list to remove the taxon in question
464
	 * (<code>cdmBaseToBeFiltered</code>)
465
	 * so it is not available in the filtered list.
466
	 */
467
	private void filterExcludedObjects() {
468
		if (model != null && cdmBaseToBeFiltered != null) {
469

    
470
			UuidAndTitleCache<?> uuidAndTitleCacheToRemove = null;
471

    
472
			for (UuidAndTitleCache<?> uuidAndTitleCache : model){
473
				if (cdmBaseToBeFiltered != null && cdmBaseToBeFiltered.contains(uuidAndTitleCache.getUuid())) {
474
					uuidAndTitleCacheToRemove = uuidAndTitleCache;
475
				}
476
			}
477
			model.remove(uuidAndTitleCacheToRemove);
478
		}
479
	}
480

    
481
	@Override
482
	void createFilterButton(Composite searchAndFilter){
483
	    //as default no filter button available
484
	}
485

    
486
    @Override
487
    protected void search() {
488
        Control control =getSearchField();
489
        String pattern = null;
490
        if (control != null){
491
            pattern = ((Text)control).getText();
492
            if (pattern.equals("*") || pattern.equals("?")){
493
                callService(null);
494
            }else if (StringUtils.isNotBlank(pattern)){
495
//                callService(CdmUtils.replaceNonWordCharacters(pattern, "."));
496
                callService(pattern);
497
            }
498
            fillContentProvider(null);
499
        }
500

    
501
//        if (pattern.equals("?")){
502
//            model = CdmStore.getService(INameService.class).getUuidAndTitleCache(null, null);
503
//        }else if (pattern != null){
504
//            model = CdmStore.getService(INameService.class).getUuidAndTitleCache(limitOfInitialElements, pattern);
505
//        }
506
    }
507

    
508
    protected abstract void callService(String pattern);
509

    
510
}
(2-2/46)