Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 4af679f816e31ff075368059a583c5e20aa0cccb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
/*******************************************************************************
 * Copyright (c) 2000, 2016 IBM Corporation and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     Michael Fraenkel (fraenkel@us.ibm.com) - contributed a fix for:
 *       o Search dialog not respecting activity enablement
 *         (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=45729)
 *     Marco Descher <marco@descher.at> - Open Search dialog with previous page instead of using the current selection to detect the page - http://bugs.eclipse.org/33710
 *******************************************************************************/
package org.eclipse.search.internal.ui;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Shell;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.core.runtime.SafeRunner;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;

import org.eclipse.jface.action.LegacyActionTools;
import org.eclipse.jface.dialogs.DialogSettings;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.IPageChangeProvider;
import org.eclipse.jface.dialogs.IPageChangedListener;
import org.eclipse.jface.dialogs.PageChangedEvent;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.SafeRunnable;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.window.Window;

import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.activities.WorkbenchActivityHelper;
import org.eclipse.ui.dialogs.ListSelectionDialog;
import org.eclipse.ui.part.MultiPageEditorPart;

import org.eclipse.search.internal.ui.util.ExceptionHandler;
import org.eclipse.search.internal.ui.util.ExtendedDialogWindow;
import org.eclipse.search.ui.IReplacePage;
import org.eclipse.search.ui.ISearchPage;
import org.eclipse.search.ui.ISearchPageContainer;
import org.eclipse.search.ui.ISearchPageScoreComputer;


public class SearchDialog extends ExtendedDialogWindow implements ISearchPageContainer, IPageChangeProvider {

	// Dialog store id constants
	private static final String DIALOG_NAME= "SearchDialog"; //$NON-NLS-1$
	private static final String STORE_PREVIOUS_PAGE= "PREVIOUS_PAGE"; //$NON-NLS-1$
	private static final String STORE_IS_OPEN_PREVIOUS_PAGE= "IS_OPEN_PREVIOUS_PAGE"; //$NON-NLS-1$


	private class TabFolderLayout extends Layout {
		@Override
		protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) {
			if (wHint != SWT.DEFAULT && hHint != SWT.DEFAULT)
				return new Point(wHint, hHint);

			int x= 0;
			int y= 0;
			Control[] children= composite.getChildren();
			for (Control element : children) {
				Point size= element.computeSize(SWT.DEFAULT, SWT.DEFAULT, flushCache);
				x= Math.max(x, size.x);
				y= Math.max(y, size.y);
			}

			Point minSize= getMinSize();
			x= Math.max(x, minSize.x);
			y= Math.max(y, minSize.y);

			if (wHint != SWT.DEFAULT)
				x= wHint;
			if (hHint != SWT.DEFAULT)
				y= hHint;
			return new Point(x, y);
		}
		@Override
		protected void layout(Composite composite, boolean flushCache) {
			Rectangle rect= composite.getClientArea();

			Control[] children= composite.getChildren();
			for (Control element : children) {
				element.setBounds(rect);
			}
		}
	}


	private static final int SEARCH_ID= IDialogConstants.CLIENT_ID + 1;
	private static final int REPLACE_ID= SEARCH_ID + 1;
	private static final int CUSTOMIZE_ID= REPLACE_ID + 1;

	private ISearchPage fCurrentPage;
	private String fInitialPageId;
	private int fCurrentIndex;

	private List<SearchPageDescriptor> fDescriptors;
	private Point fMinSize;
	private ScopePart[] fScopeParts;
	private boolean fLastEnableState;
	private Button fCustomizeButton;
	private Button fReplaceButton;
	private ListenerList<IPageChangedListener> fPageChangeListeners;

	private final IWorkbenchWindow fWorkbenchWindow;
	private final ISelection fCurrentSelection;
	private final String[] fCurrentEnclosingProject;

	private final IDialogSettings fDialogSettings= DialogSettings.getOrCreateSection(SearchPlugin.getDefault().getDialogSettings(), DIALOG_NAME);


	public SearchDialog(IWorkbenchWindow window, String pageId) {
		super(window.getShell());
		fWorkbenchWindow= window;
		fCurrentSelection= window.getSelectionService().getSelection();
		fCurrentEnclosingProject= evaluateEnclosingProject(fCurrentSelection, getActiveEditor());

		fDescriptors= filterByActivities(SearchPlugin.getDefault().getEnabledSearchPageDescriptors(pageId));
		fInitialPageId= pageId;

		if (fInitialPageId == null && fDialogSettings.getBoolean(STORE_IS_OPEN_PREVIOUS_PAGE)) {
			fInitialPageId= fDialogSettings.get(STORE_PREVIOUS_PAGE);
		}

		fPageChangeListeners= null;
		setUseEmbeddedProgressMonitorPart(false);
	}

	public static String evaluateEnclosingProject(IAdaptable adaptable) {
		IProject project= adaptable.getAdapter(IProject.class);
		if (project == null) {
			IResource resource= adaptable.getAdapter(IResource.class);
			if (resource != null) {
				project= resource.getProject();
			}
		}
		if (project != null && project.isAccessible()) {
			return project.getName();
		}
		return null;
	}

	public static String[] evaluateEnclosingProject(ISelection selection, IEditorPart activeEditor) {
		// always use the editor if active
		if (activeEditor != null) {
			String name= evaluateEnclosingProject(activeEditor.getEditorInput());
			if (name != null) {
				return new String[] { name };
			}
		} else if (selection instanceof IStructuredSelection) {
			HashSet<String> res= new HashSet<>();
			for (Iterator<?> iter= ((IStructuredSelection) selection).iterator(); iter.hasNext();) {
				Object curr= iter.next();
				if (curr instanceof IWorkingSet) {
					IWorkingSet workingSet= (IWorkingSet) curr;
					if (workingSet.isAggregateWorkingSet() && workingSet.isEmpty()) {
						IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
						for (IProject proj : projects) {
							if (proj.isOpen()) {
								res.add(proj.getName());
							}
						}
					} else {
						IAdaptable[] elements= workingSet.getElements();
						for (IAdaptable element : elements) {
							String name= evaluateEnclosingProject(element);
							if (name != null) {
								res.add(name);
							}
						}
					}
				} else if (curr instanceof IAdaptable) {
					String name= evaluateEnclosingProject((IAdaptable) curr);
					if (name != null) {
						res.add(name);
					}
				}
			}
			if (!res.isEmpty()) {
				return res.toArray(new String[res.size()]);
			}
		}
		return new String[0];
	}

	@Override
	protected IDialogSettings getDialogBoundsSettings() {
		return SearchPlugin.getDefault().getDialogSettingsSection("DialogBounds_SearchDialog"); //$NON-NLS-1$
	}

	@Override
	protected Point getInitialSize() {
		Point requiredSize= getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
		Point lastSize= super.getInitialSize();
		if (requiredSize.x > lastSize.x || requiredSize.y > lastSize.y) {
			return requiredSize;
		}
		return lastSize;
	}

	@Override
	protected void configureShell(Shell shell) {
		super.configureShell(shell);
		shell.setText(SearchMessages.SearchDialog_title);
		PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, ISearchHelpContextIds.SEARCH_DIALOG);
	}

	public IWorkbenchWindow getWorkbenchWindow() {
		return fWorkbenchWindow;
	}

	@Override
	public ISelection getSelection() {
		return fCurrentSelection;
	}

	public IEditorPart getActiveEditor() {
		IWorkbenchPage activePage= fWorkbenchWindow.getActivePage();
		if (activePage == null)
			return null;

		IWorkbenchPart activePart= activePage.getActivePart();
		if (activePart == null)
			return null;

		IEditorPart activeEditor= activePage.getActiveEditor();
		if (activeEditor == activePart || isOldSearchView(activePart))
			return activeEditor;

		return null;
	}

	/**
	 * Tells whether the given part is the old ('classic') search view.
	 *
	 * @param part the part to test
	 * @return <code>true</code> if the given part is the old search view
	 * @deprecated old ('classic') search is deprecated
	 * @since 3.7
	 */
	@Deprecated
	private static boolean isOldSearchView(IWorkbenchPart part) {
		return org.eclipse.search.ui.SearchUI.SEARCH_RESULT_VIEW_ID.equals(part.getSite().getId());
	}

	//---- Page Handling -------------------------------------------------------

	/*
	 * Overrides method from Window
	 */
	@Override
	public void create() {
		super.create();
		if (fCurrentPage != null) {
			fCurrentPage.setVisible(true);
		}
	}

	private void handleCustomizePressed() {
		List<SearchPageDescriptor> input= SearchPlugin.getDefault().getSearchPageDescriptors();
		input= filterByActivities(input);

		final ArrayList<Image> createdImages= new ArrayList<>(input.size());
		ILabelProvider labelProvider= new LabelProvider() {
			@Override
			public String getText(Object element) {
				if (element instanceof SearchPageDescriptor)
					return LegacyActionTools.removeMnemonics(((SearchPageDescriptor)element).getLabel());
				return null;
			}
			@Override
			public Image getImage(Object element) {
				if (element instanceof SearchPageDescriptor) {
					ImageDescriptor imageDesc= ((SearchPageDescriptor)element).getImage();
					if (imageDesc == null)
						return null;
					Image image= imageDesc.createImage();
					if (image != null)
						createdImages.add(image);
					return image;
				}
				return null;
			}
		};

		String message= SearchMessages.SearchPageSelectionDialog_message;

		ListSelectionDialog dialog= new ListSelectionDialog(getShell(), input, new ArrayContentProvider(), labelProvider, message) {
			Button fLastUsedPageButton;

			@Override
			public void create() {
				super.create();
				final CheckboxTableViewer viewer= getViewer();
				final Button okButton= this.getOkButton();
				viewer.addCheckStateListener(event -> okButton.setEnabled(viewer.getCheckedElements().length > 0));
				SelectionListener listener = new SelectionAdapter() {
					@Override
					public void widgetSelected(SelectionEvent e) {
						okButton.setEnabled(viewer.getCheckedElements().length > 0);
					}
				};
				this.getButton(IDialogConstants.SELECT_ALL_ID).addSelectionListener(listener);
				this.getButton(IDialogConstants.DESELECT_ALL_ID).addSelectionListener(listener);
			}

			@Override
			protected Control createDialogArea(Composite parent) {
				Composite control= (Composite)super.createDialogArea(parent);
				fLastUsedPageButton= new Button(control, SWT.CHECK);
				fLastUsedPageButton.setText(SearchMessages.SearchPageSelectionDialog_rememberLastUsedPage_message);
				fLastUsedPageButton.setSelection(fDialogSettings.getBoolean(STORE_IS_OPEN_PREVIOUS_PAGE));
				return control;
			}

			@Override
			protected void okPressed() {
				fDialogSettings.put(STORE_IS_OPEN_PREVIOUS_PAGE, fLastUsedPageButton.getSelection());
				super.okPressed();
			}
		};
		dialog.setTitle(SearchMessages.SearchPageSelectionDialog_title);
		dialog.setInitialSelections(SearchPlugin.getDefault().getEnabledSearchPageDescriptors(fInitialPageId).toArray());
		if (dialog.open() == Window.OK) {
			SearchPageDescriptor.setEnabled(dialog.getResult());
			Display display= getShell().getDisplay();
			close();
			if (display != null && !display.isDisposed()) {
				display.asyncExec(
						() -> new OpenSearchDialogAction().run());
			}
		}
		destroyImages(createdImages);
	}

	private List<SearchPageDescriptor> filterByActivities(List<SearchPageDescriptor> input) {
		ArrayList<SearchPageDescriptor> filteredList= new ArrayList<>(input.size());
		for (SearchPageDescriptor descriptor : input) {
			if (!WorkbenchActivityHelper.filterItem(descriptor))
			    filteredList.add(descriptor);

		}
		return filteredList;
	}

	private void destroyImages(List<Image> images) {
		Iterator<Image> iter= images.iterator();
		while (iter.hasNext()) {
			Image image= iter.next();
			if (image != null && !image.isDisposed())
				image.dispose();
		}
	}

	@Override
	protected Control createPageArea(Composite parent) {
		int numPages= fDescriptors.size();
		fScopeParts= new ScopePart[numPages];

		if (numPages == 0) {
			Label label= new Label(parent, SWT.CENTER | SWT.WRAP);
			label.setText(SearchMessages.SearchDialog_noSearchExtension);
			return label;
		}

		fCurrentIndex= getPreferredPageIndex();

		Composite composite= new Composite(parent, SWT.NONE);
		composite.setFont(parent.getFont());

		GridLayout layout = new GridLayout();
		layout.marginHeight = 0;
		layout.marginWidth = 0;
		composite.setLayout(layout);
		composite.setLayoutData(new GridData(GridData.FILL_BOTH));

		CTabFolder folder = new CTabFolder(composite, SWT.BORDER);

		folder.setLayout(new TabFolderLayout());
		folder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		folder.setFont(composite.getFont());

		for (int i= 0; i < numPages; i++) {
			SearchPageDescriptor descriptor= getDescriptorAt(i);
			if (WorkbenchActivityHelper.filterItem(descriptor))
			    continue;

			final CTabItem item = new CTabItem(folder, SWT.NONE);
			item.setData("descriptor", descriptor); //$NON-NLS-1$
			item.setText(descriptor.getLabel());
			item.addDisposeListener(e -> {
				item.setData("descriptor", null); //$NON-NLS-1$
				if (item.getImage() != null)
					item.getImage().dispose();
			});
			ImageDescriptor imageDesc= descriptor.getImage();
			if (imageDesc != null)
				item.setImage(imageDesc.createImage());

			if (i == fCurrentIndex) {
				Control pageControl= createPageControl(folder, descriptor);
				pageControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
				item.setControl(pageControl);
				fCurrentPage= descriptor.getPage();
				fDialogSettings.put(STORE_PREVIOUS_PAGE, descriptor.getId());
			}
		}

		folder.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent event) {
				turnToPage(event);
			}
		});

		folder.setSelection(fCurrentIndex);

		return composite;
	}

	@Override
	protected Control createButtonBar(Composite parent) {
		Composite composite= new Composite(parent, SWT.NONE);
		GridLayout layout= new GridLayout();
		layout.numColumns= 0;   // create
		layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
		layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
		layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
		layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);

		composite.setLayout(layout);
		composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		// create help control if needed
        if (isHelpAvailable()) {
        	createHelpControl(composite);
        }
		fCustomizeButton= createButton(composite, CUSTOMIZE_ID, SearchMessages.SearchDialog_customize, true);

		Label filler= new Label(composite, SWT.NONE);
		filler.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
		layout.numColumns++;

		fReplaceButton= createActionButton(composite, REPLACE_ID, SearchMessages.SearchDialog_replaceAction, true);
		fReplaceButton.setVisible(fCurrentPage instanceof IReplacePage);
		Button searchButton= createActionButton(composite, SEARCH_ID, SearchMessages.SearchDialog_searchAction, true);
		searchButton.setEnabled(fDescriptors.size() > 0);
		super.createButtonsForButtonBar(composite);  // cancel button

		return composite;
	}

	@Override
	protected boolean performAction(int actionID) {
		switch (actionID) {
			case CUSTOMIZE_ID:
				handleCustomizePressed();
				return false;
			case CANCEL:
				return true;
			case SEARCH_ID:
				if (fCurrentPage != null) {
					return fCurrentPage.performAction();
				}
				return true;
			case REPLACE_ID:
				boolean isAutoBuilding= SearchPlugin.setAutoBuilding(false);
				try {
					fCustomizeButton.setEnabled(false);

					// safe cast, replace button is only visible when the current page is
					// a replace page.
					return ((IReplacePage)fCurrentPage).performReplace();
				} finally {
					fCustomizeButton.setEnabled(true);
					SearchPlugin.setAutoBuilding(isAutoBuilding);
				}
			default:
				return false;
		}
	}

	private SearchPageDescriptor getDescriptorAt(int index) {
		return fDescriptors.get(index);
	}

	private Point getMinSize() {
		if (fMinSize != null)
			return fMinSize;

		int x= 0;
		int y= 0;
		int length= fDescriptors.size();
		for (int i= 0; i < length; i++) {
			Point size= getDescriptorAt(i).getPreferredSize();
			if (size.x != SWT.DEFAULT)
				x= Math.max(x, size.x);
			if (size.y != SWT.DEFAULT)
				y= Math.max(y, size.y);
		}

		fMinSize= new Point(x, y);
		return fMinSize;
	}

	private void turnToPage(SelectionEvent event) {
		final CTabItem item = (CTabItem) event.item;
		CTabFolder folder = item.getParent();

		SearchPageDescriptor descriptor= (SearchPageDescriptor) item.getData("descriptor"); //$NON-NLS-1$


		if (item.getControl() == null) {
			item.setControl(createPageControl(folder, descriptor));
		}

		Control oldControl= folder.getItem(fCurrentIndex).getControl();
		Point oldSize= oldControl.getSize();
		Control newControl= item.getControl();
		Point newSize= newControl.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
		resizeDialogIfNeeded(oldSize, newSize);

		ISearchPage oldPage= fCurrentPage;
		if (oldPage != null) {
			oldPage.setVisible(false);
		}

		fCurrentPage= descriptor.getPage();
		fDialogSettings.put(STORE_PREVIOUS_PAGE, descriptor.getId());
		fCurrentIndex= folder.getSelectionIndex();

		setPerformActionEnabled(fCurrentPage != null);
		if (fCurrentPage != null) {
			fCurrentPage.setVisible(true);
			Control pageControl= fCurrentPage.getControl();
			if (pageControl instanceof Composite)
				((Composite)pageControl).layout(false, true);
		}
		fReplaceButton.setVisible(fCurrentPage instanceof IReplacePage);
		notifyPageChanged();
	}

	private int getPreferredPageIndex() {
		Object element= null;
		ISelection selection= getSelection();
		if (selection instanceof IStructuredSelection)
			element= ((IStructuredSelection) selection).getFirstElement();

		if (element == null)
			element= getActiveEditorInput();

		int result= 0;
		int level= ISearchPageScoreComputer.LOWEST;
		int size= fDescriptors.size();
		for (int i= 0; i < size; i++) {
			SearchPageDescriptor descriptor= fDescriptors.get(i);
			if (fInitialPageId != null && fInitialPageId.equals(descriptor.getId()))
				return i;

			int newLevel= descriptor.computeScore(element);
			if (newLevel > level) {
				level= newLevel;
				result= i;
			}
		}
		return result;
	}

	/*
	 * Implements method from ISearchPageContainer
	 */
	@Override
	public IRunnableContext getRunnableContext() {
		return this;
	}

	/*
	 * Implements method from ISearchPageContainer
	 */
	@Override
	public int getSelectedScope() {
		if (fScopeParts[fCurrentIndex] == null)
			// safe code - should not happen
			return ISearchPageContainer.WORKSPACE_SCOPE;

		return fScopeParts[fCurrentIndex].getSelectedScope();
	}

	/*
	 * Implements method from ISearchPageContainer
	 */
	@Override
	public IWorkingSet[] getSelectedWorkingSets() {
		if (fScopeParts[fCurrentIndex] == null)
			// safe code - should not happen
			return null;

		return fScopeParts[fCurrentIndex].getSelectedWorkingSets();
	}

	public String[] getEnclosingProjectNames() {
		return fCurrentEnclosingProject;
	}


	@Override
	public String[] getSelectedProjectNames() {
		if (getSelectedScope() == SELECTED_PROJECTS_SCOPE) {
			return getEnclosingProjectNames();
		}
		return null;
	}

	/*
	 * Implements method from ISearchPageContainer
	 */
	@Override
	public void setSelectedScope(int scope) {
		if (fScopeParts[fCurrentIndex] != null)
			fScopeParts[fCurrentIndex].setSelectedScope(scope);
	}

	/*
	 * @see org.eclipse.search.ui.ISearchPageContainer#allowsActiveEditorAsScope(boolean)
	 * @since 3.7
	 */
	@Override
	public void setActiveEditorCanProvideScopeSelection(boolean state) {
		if (fScopeParts[fCurrentIndex] != null)
			fScopeParts[fCurrentIndex].setActiveEditorCanProvideScopeSelection(state);
	}

	@Override
	public IEditorInput getActiveEditorInput() {
		IEditorPart editor= getActiveEditor();
		if (editor == null)
			return null;

		// Handle multi-page editors
		if (editor instanceof MultiPageEditorPart) {
			Object page= ((MultiPageEditorPart)editor).getSelectedPage();
			if (page instanceof IEditorPart)
				editor= (IEditorPart)page;
			else
				return null;
		}

		return editor.getEditorInput();
	}

	/*
	 * Implements method from ISearchPageContainer
	 */
	@Override
	public boolean hasValidScope() {
		return getSelectedScope() != WORKING_SET_SCOPE || getSelectedWorkingSets() != null;
	}

	/*
	 * Implements method from ISearchPageContainer
	 */
	@Override
	public void setSelectedWorkingSets(IWorkingSet[] workingSets) {
		if (fScopeParts[fCurrentIndex] != null)
			fScopeParts[fCurrentIndex].setSelectedWorkingSets(workingSets);
	}

	/*
	 * Overrides method from ExtendedDialogWindow
	 */
	@Override
	public void setPerformActionEnabled(boolean state) {
		fLastEnableState= state;
		super.setPerformActionEnabled(state && hasValidScope());
	}

	/**
	 * Notify that the scope selection has changed
	 * <p>
	 * Note: This is a special method to be called only from the ScopePart
	 * </p>
	 */
	public void notifyScopeSelectionChanged() {
		setPerformActionEnabled(fLastEnableState);
	}

	private Control createPageControl(Composite parent, final SearchPageDescriptor descriptor) {

		// Page wrapper
		final Composite pageWrapper= new Composite(parent, SWT.NONE);
		GridLayout layout= new GridLayout();
		layout.marginWidth= 0;
		layout.marginHeight= 0;
		pageWrapper.setLayout(layout);

		applyDialogFont(pageWrapper);

		BusyIndicator.showWhile(getShell().getDisplay(), () -> SafeRunner.run(new ISafeRunnable() {
			@Override
			public void run() throws Exception {
				// create page and control
				ISearchPage page= descriptor.createObject(SearchDialog.this);
				if (page != null) {
					page.createControl(pageWrapper);
				}
			}
			@Override
			public void handleException(Throwable ex) {
				if (ex instanceof CoreException) {
					ExceptionHandler.handle((CoreException) ex, getShell(), SearchMessages.Search_Error_createSearchPage_title, Messages.format(SearchMessages.Search_Error_createSearchPage_message, descriptor.getLabel()));
				} else {
					ExceptionHandler.displayMessageDialog(ex, getShell(), SearchMessages.Search_Error_createSearchPage_title, Messages.format(SearchMessages.Search_Error_createSearchPage_message, descriptor.getLabel()));
				}
			}
		}));

		ISearchPage page= descriptor.getPage();
		if (page == null || page.getControl() == null) {
			Composite container= new Composite(parent, SWT.NONE);
			Label label= new Label(container, SWT.WRAP);
			label.setText(Messages.format(SearchMessages.SearchDialog_error_pageCreationFailed, descriptor.getLabel()));
			container.setLayout(new GridLayout());
			label.setLayoutData(new GridData());
			return container;
		}

		page.getControl().setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));

		// Search scope
		boolean showScope= descriptor.showScopeSection();
		if (showScope) {
			Composite c= new Composite(pageWrapper, SWT.NONE);
			c.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
			c.setLayout(new GridLayout());

			int index= fDescriptors.indexOf(descriptor);
			fScopeParts[index]= new ScopePart(this, descriptor.canSearchInProjects());
			Control part= fScopeParts[index].createPart(c);
			applyDialogFont(part);
			part.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
			fScopeParts[index].setVisible(true);
		}

		return pageWrapper;
	}

	private void resizeDialogIfNeeded(Point oldSize, Point newSize) {
		if (oldSize == null || newSize == null)
			return;
			Shell shell= getShell();
		Point shellSize= shell.getSize();
		if (mustResize(oldSize, newSize)) {
			if (newSize.x > oldSize.x)
				shellSize.x+= (newSize.x-oldSize.x);
			if (newSize.y > oldSize.y)
				shellSize.y+= (newSize.y-oldSize.y);
			shell.setSize(shellSize);
					shell.layout(true);
		}
	}

	private boolean mustResize(Point currentSize, Point newSize) {
		return currentSize.x < newSize.x || currentSize.y < newSize.y;
	}

	@Override
	public boolean close() {
		for (int i= 0; i < fDescriptors.size(); i++) {
			SearchPageDescriptor desc= fDescriptors.get(i);
			desc.dispose();
		}
		return super.close();
	}

	@Override
	public Object getSelectedPage() {
		return fCurrentPage;
	}

	@Override
	public void addPageChangedListener(IPageChangedListener listener) {
		if (fPageChangeListeners == null) {
			fPageChangeListeners= new ListenerList<>();
		}
		fPageChangeListeners.add(listener);
	}

	@Override
	public void removePageChangedListener(IPageChangedListener listener) {
		fPageChangeListeners.remove(listener);
	}

	private void notifyPageChanged() {
		if (fPageChangeListeners != null && !fPageChangeListeners.isEmpty()) {
			// Fires the page change event
			final PageChangedEvent event= new PageChangedEvent(this, getSelectedPage());
			for (IPageChangedListener l : fPageChangeListeners) {
				SafeRunner.run(new SafeRunnable() {
					@Override
					public void run() {
						l.pageChanged(event);
					}
				});
			}
		}
	}
}

Back to the top