KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > search > internal > ui > text > TextSearchPage


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.search.internal.ui.text;
12
13 import java.io.BufferedReader JavaDoc;
14 import java.io.IOException JavaDoc;
15 import java.io.StringReader JavaDoc;
16 import java.util.ArrayList JavaDoc;
17 import java.util.HashSet JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.List JavaDoc;
20 import java.util.regex.Pattern JavaDoc;
21 import java.util.regex.PatternSyntaxException JavaDoc;
22
23 import org.eclipse.core.runtime.Assert;
24 import org.eclipse.core.runtime.CoreException;
25 import org.eclipse.core.runtime.IAdaptable;
26 import org.eclipse.core.runtime.IStatus;
27
28 import org.eclipse.core.resources.IFile;
29 import org.eclipse.core.resources.IResource;
30 import org.eclipse.core.resources.IWorkspaceRoot;
31 import org.eclipse.core.resources.ResourcesPlugin;
32
33 import org.eclipse.swt.SWT;
34 import org.eclipse.swt.custom.CLabel;
35 import org.eclipse.swt.events.ModifyEvent;
36 import org.eclipse.swt.events.ModifyListener;
37 import org.eclipse.swt.events.SelectionAdapter;
38 import org.eclipse.swt.events.SelectionEvent;
39 import org.eclipse.swt.layout.GridData;
40 import org.eclipse.swt.layout.GridLayout;
41 import org.eclipse.swt.widgets.Button;
42 import org.eclipse.swt.widgets.Combo;
43 import org.eclipse.swt.widgets.Composite;
44 import org.eclipse.swt.widgets.Display;
45 import org.eclipse.swt.widgets.Label;
46
47 import org.eclipse.jface.dialogs.Dialog;
48 import org.eclipse.jface.dialogs.DialogPage;
49 import org.eclipse.jface.dialogs.ErrorDialog;
50 import org.eclipse.jface.dialogs.IDialogSettings;
51 import org.eclipse.jface.resource.JFaceColors;
52 import org.eclipse.jface.viewers.ISelection;
53 import org.eclipse.jface.viewers.IStructuredSelection;
54
55 import org.eclipse.jface.text.ITextSelection;
56
57 import org.eclipse.ui.IEditorPart;
58 import org.eclipse.ui.IEditorRegistry;
59 import org.eclipse.ui.IFileEditorInput;
60 import org.eclipse.ui.IWorkingSet;
61 import org.eclipse.ui.IWorkingSetManager;
62 import org.eclipse.ui.PlatformUI;
63 import org.eclipse.ui.contentassist.ContentAssistHandler;
64
65 import org.eclipse.search.ui.IReplacePage;
66 import org.eclipse.search.ui.ISearchPage;
67 import org.eclipse.search.ui.ISearchPageContainer;
68 import org.eclipse.search.ui.ISearchQuery;
69 import org.eclipse.search.ui.ISearchResultPage;
70 import org.eclipse.search.ui.ISearchResultViewPart;
71 import org.eclipse.search.ui.NewSearchUI;
72 import org.eclipse.search.ui.text.FileTextSearchScope;
73 import org.eclipse.search.ui.text.TextSearchQueryProvider;
74 import org.eclipse.search.ui.text.TextSearchQueryProvider.TextSearchInput;
75
76 import org.eclipse.search.internal.ui.ISearchHelpContextIds;
77 import org.eclipse.search.internal.ui.SearchMessages;
78 import org.eclipse.search.internal.ui.SearchPlugin;
79 import org.eclipse.search.internal.ui.util.FileTypeEditor;
80 import org.eclipse.search.internal.ui.util.SWTUtil;
81
82
83 public class TextSearchPage extends DialogPage implements ISearchPage, IReplacePage {
84
85     private static final int HISTORY_SIZE= 12;
86     public static final String JavaDoc EXTENSION_POINT_ID= "org.eclipse.search.internal.ui.text.TextSearchPage"; //$NON-NLS-1$
87

88     // Dialog store id constants
89
private static final String JavaDoc PAGE_NAME= "TextSearchPage"; //$NON-NLS-1$
90
private static final String JavaDoc STORE_CASE_SENSITIVE= "CASE_SENSITIVE"; //$NON-NLS-1$
91
private static final String JavaDoc STORE_IS_REG_EX_SEARCH= "REG_EX_SEARCH"; //$NON-NLS-1$
92
private static final String JavaDoc STORE_SEARCH_DERIVED = "SEARCH_DERIVED"; //$NON-NLS-1$
93
private static final String JavaDoc STORE_HISTORY= "HISTORY"; //$NON-NLS-1$
94
private static final String JavaDoc STORE_HISTORY_SIZE= "HISTORY_SIZE"; //$NON-NLS-1$
95

96     private List JavaDoc fPreviousSearchPatterns= new ArrayList JavaDoc(20);
97
98     private boolean fFirstTime= true;
99     private boolean fIsCaseSensitive;
100     private boolean fIsRegExSearch;
101     private boolean fSearchDerived;
102     
103     private Combo fPattern;
104     private Button fIsCaseSensitiveCheckbox;
105     private Combo fExtensions;
106     private Button fIsRegExCheckbox;
107     private CLabel fStatusLabel;
108     private Button fSearchDerivedCheckbox;
109
110     private ISearchPageContainer fContainer;
111     private FileTypeEditor fFileTypeEditor;
112
113     private ContentAssistHandler fReplaceContentAssistHandler;
114     
115     private static class SearchPatternData {
116         public final boolean isCaseSensitive;
117         public final boolean isRegExSearch;
118         public final String JavaDoc textPattern;
119         public final String JavaDoc[] fileNamePatterns;
120         public final int scope;
121         public final IWorkingSet[] workingSets;
122         
123         public SearchPatternData(String JavaDoc textPattern, boolean isCaseSensitive, boolean isRegExSearch, String JavaDoc[] fileNamePatterns, int scope, IWorkingSet[] workingSets) {
124             Assert.isNotNull(fileNamePatterns);
125             this.isCaseSensitive= isCaseSensitive;
126             this.isRegExSearch= isRegExSearch;
127             this.textPattern= textPattern;
128             this.fileNamePatterns= fileNamePatterns;
129             this.scope= scope;
130             this.workingSets= workingSets; // can be null
131
}
132         
133         public void store(IDialogSettings settings) {
134             settings.put("ignoreCase", !isCaseSensitive); //$NON-NLS-1$
135
settings.put("isRegExSearch", isRegExSearch); //$NON-NLS-1$
136
settings.put("textPattern", textPattern); //$NON-NLS-1$
137
settings.put("fileNamePatterns", fileNamePatterns); //$NON-NLS-1$
138
settings.put("scope", scope); //$NON-NLS-1$
139
if (workingSets != null) {
140                 String JavaDoc[] wsIds= new String JavaDoc[workingSets.length];
141                 for (int i= 0; i < workingSets.length; i++) {
142                     wsIds[i]= workingSets[i].getLabel();
143                 }
144                 settings.put("workingSets", wsIds); //$NON-NLS-1$
145
} else {
146                 settings.put("workingSets", new String JavaDoc[0]); //$NON-NLS-1$
147
}
148
149         }
150         
151         public static SearchPatternData create(IDialogSettings settings) {
152             String JavaDoc textPattern= settings.get("textPattern"); //$NON-NLS-1$
153
String JavaDoc[] wsIds= settings.getArray("workingSets"); //$NON-NLS-1$
154
IWorkingSet[] workingSets= null;
155             if (wsIds != null && wsIds.length > 0) {
156                 IWorkingSetManager workingSetManager= PlatformUI.getWorkbench().getWorkingSetManager();
157                 workingSets= new IWorkingSet[wsIds.length];
158                 for (int i= 0; workingSets != null && i < wsIds.length; i++) {
159                     workingSets[i]= workingSetManager.getWorkingSet(wsIds[i]);
160                     if (workingSets[i] == null) {
161                         workingSets= null;
162                     }
163                 }
164             }
165             String JavaDoc[] fileNamePatterns= settings.getArray("fileNamePatterns"); //$NON-NLS-1$
166
if (fileNamePatterns == null) {
167                 fileNamePatterns= new String JavaDoc[0];
168             }
169             try {
170                 int scope= settings.getInt("scope"); //$NON-NLS-1$
171
boolean isRegExSearch= settings.getBoolean("isRegExSearch"); //$NON-NLS-1$
172
boolean ignoreCase= settings.getBoolean("ignoreCase"); //$NON-NLS-1$
173

174                 return new SearchPatternData(textPattern, !ignoreCase, isRegExSearch, fileNamePatterns, scope, workingSets);
175             } catch (NumberFormatException JavaDoc e) {
176                 return null;
177             }
178         }
179
180         public String JavaDoc getPattern() {
181             return textPattern;
182         }
183
184         public boolean isCaseSensitive() {
185             return isCaseSensitive;
186         }
187
188         public boolean isRegExSearch() {
189             return isRegExSearch;
190         }
191
192         public boolean isStringMatcherPattern() {
193             return !isRegExSearch;
194         }
195     }
196     
197     private static class TextSearchPageInput extends TextSearchInput {
198         
199         private final String JavaDoc fSearchText;
200         private final boolean fIsCaseSensitive;
201         private final boolean fIsRegEx;
202         private final FileTextSearchScope fScope;
203
204         public TextSearchPageInput(String JavaDoc searchText, boolean isCaseSensitive, boolean isRegEx, FileTextSearchScope scope) {
205             fSearchText= searchText;
206             fIsCaseSensitive= isCaseSensitive;
207             fIsRegEx= isRegEx;
208             fScope= scope;
209         }
210
211         public String JavaDoc getSearchText() {
212             return fSearchText;
213         }
214
215         public boolean isCaseSensitiveSearch() {
216             return fIsCaseSensitive;
217         }
218
219         public boolean isRegExSearch() {
220             return fIsRegEx;
221         }
222
223         public FileTextSearchScope getScope() {
224             return fScope;
225         }
226     }
227     
228     //---- Action Handling ------------------------------------------------
229

230     private ISearchQuery newQuery() throws CoreException {
231         SearchPatternData data= getPatternData();
232         TextSearchPageInput input= new TextSearchPageInput(data.textPattern, data.isCaseSensitive, data.isRegExSearch, createTextSearchScope());
233         return TextSearchQueryProvider.getPreferred().createQuery(input);
234     }
235     
236     public boolean performAction() {
237         try {
238             NewSearchUI.runQueryInBackground(newQuery());
239         } catch (CoreException e) {
240             ErrorDialog.openError(getShell(), SearchMessages.TextSearchPage_replace_searchproblems_title, SearchMessages.TextSearchPage_replace_searchproblems_message, e.getStatus());
241             return false;
242         }
243         return true;
244     }
245     
246     /* (non-Javadoc)
247      * @see org.eclipse.search.ui.IReplacePage#performReplace()
248      */

249     public boolean performReplace() {
250         try {
251             IStatus status= NewSearchUI.runQueryInForeground(getContainer().getRunnableContext(), newQuery());
252             if (status.matches(IStatus.CANCEL)) {
253                 return false;
254             }
255             if (!status.isOK()) {
256                 ErrorDialog.openError(getShell(), SearchMessages.TextSearchPage_replace_searchproblems_title, SearchMessages.TextSearchPage_replace_runproblem_message, status);
257             }
258             
259             
260             Display.getCurrent().asyncExec(new Runnable JavaDoc() {
261                 public void run() {
262                     ISearchResultViewPart view= NewSearchUI.activateSearchResultView();
263                     if (view != null) {
264                         ISearchResultPage page= view.getActivePage();
265                         if (page instanceof FileSearchPage) {
266                             FileSearchPage filePage= (FileSearchPage) page;
267                             Object JavaDoc[] elements= filePage.getInput().getElements();
268                             IFile[] files= new IFile[elements.length];
269                             System.arraycopy(elements, 0, files, 0, files.length);
270                             new ReplaceAction2(filePage, files).run();
271                         }
272                     }
273                 }
274             });
275             return true;
276         } catch (CoreException e) {
277             ErrorDialog.openError(getShell(), SearchMessages.TextSearchPage_replace_searchproblems_title, SearchMessages.TextSearchPage_replace_querycreationproblem_message, e.getStatus());
278             return false;
279         }
280     }
281
282     private String JavaDoc getPattern() {
283         return fPattern.getText();
284     }
285     
286     public FileTextSearchScope createTextSearchScope() {
287         // Setup search scope
288
switch (getContainer().getSelectedScope()) {
289             case ISearchPageContainer.WORKSPACE_SCOPE:
290                 return FileTextSearchScope.newWorkspaceScope(getExtensions(), fSearchDerived);
291             case ISearchPageContainer.SELECTION_SCOPE:
292                 return getSelectedResourcesScope();
293             case ISearchPageContainer.SELECTED_PROJECTS_SCOPE:
294                 return getEnclosingProjectScope();
295             case ISearchPageContainer.WORKING_SET_SCOPE:
296                 IWorkingSet[] workingSets= getContainer().getSelectedWorkingSets();
297                 return FileTextSearchScope.newSearchScope(workingSets, getExtensions(), fSearchDerived);
298             default:
299                 // unknown scope
300
return FileTextSearchScope.newWorkspaceScope(getExtensions(), fSearchDerived);
301         }
302     }
303     
304     private FileTextSearchScope getSelectedResourcesScope() {
305         HashSet JavaDoc resources= new HashSet JavaDoc();
306         ISelection sel= getContainer().getSelection();
307         if (sel instanceof IStructuredSelection && !sel.isEmpty()) {
308             Iterator JavaDoc iter= ((IStructuredSelection) sel).iterator();
309             while (iter.hasNext()) {
310                 Object JavaDoc curr= iter.next();
311                 if (curr instanceof IWorkingSet) {
312                     IWorkingSet workingSet= (IWorkingSet) curr;
313                     if (workingSet.isAggregateWorkingSet() && workingSet.isEmpty()) {
314                         return FileTextSearchScope.newWorkspaceScope(getExtensions(), fSearchDerived);
315                     }
316                     IAdaptable[] elements= workingSet.getElements();
317                     for (int i= 0; i < elements.length; i++) {
318                         IResource resource= (IResource)elements[i].getAdapter(IResource.class);
319                         if (resource != null && resource.isAccessible()) {
320                             resources.add(resource);
321                         }
322                     }
323                 } else if (curr instanceof IAdaptable) {
324                     IResource resource= (IResource) ((IAdaptable)curr).getAdapter(IResource.class);
325                     if (resource != null && resource.isAccessible()) {
326                         resources.add(resource);
327                     }
328                 }
329             }
330         }
331         IResource[] arr= (IResource[]) resources.toArray(new IResource[resources.size()]);
332         return FileTextSearchScope.newSearchScope(arr, getExtensions(), fSearchDerived);
333     }
334
335     private FileTextSearchScope getEnclosingProjectScope() {
336         String JavaDoc[] enclosingProjectName= getContainer().getSelectedProjectNames();
337         if (enclosingProjectName == null) {
338             return FileTextSearchScope.newWorkspaceScope(getExtensions(), fSearchDerived);
339         }
340         
341         IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
342         IResource[] res= new IResource[enclosingProjectName.length];
343         for (int i= 0; i < res.length; i++) {
344             res[i]= root.getProject(enclosingProjectName[i]);
345         }
346         
347         return FileTextSearchScope.newSearchScope(res, getExtensions(), fSearchDerived);
348     }
349
350     
351     private SearchPatternData findInPrevious(String JavaDoc pattern) {
352         for (Iterator JavaDoc iter= fPreviousSearchPatterns.iterator(); iter.hasNext();) {
353             SearchPatternData element= (SearchPatternData) iter.next();
354             if (pattern.equals(element.textPattern)) {
355                 return element;
356             }
357         }
358         return null;
359     }
360
361     /**
362      * Return search pattern data and update previous searches.
363      * An existing entry will be updated.
364      * @return the search pattern data
365      */

366     private SearchPatternData getPatternData() {
367         SearchPatternData match= findInPrevious(fPattern.getText());
368         if (match != null) {
369             fPreviousSearchPatterns.remove(match);
370         }
371         match= new SearchPatternData(
372                     getPattern(),
373                     isCaseSensitive(),
374                     fIsRegExCheckbox.getSelection(),
375                     getExtensions(),
376                     getContainer().getSelectedScope(),
377                     getContainer().getSelectedWorkingSets());
378         fPreviousSearchPatterns.add(0, match);
379         return match;
380     }
381
382     private String JavaDoc[] getPreviousExtensions() {
383         List JavaDoc extensions= new ArrayList JavaDoc(fPreviousSearchPatterns.size());
384         int size= fPreviousSearchPatterns.size();
385         for (int i= 0; i < size; i++) {
386             SearchPatternData data= (SearchPatternData) fPreviousSearchPatterns.get(i);
387             String JavaDoc text= FileTypeEditor.typesToString(data.fileNamePatterns);
388             if (!extensions.contains(text))
389                 extensions.add(text);
390         }
391         return (String JavaDoc[]) extensions.toArray(new String JavaDoc[extensions.size()]);
392     }
393
394     private String JavaDoc[] getPreviousSearchPatterns() {
395         int size= fPreviousSearchPatterns.size();
396         String JavaDoc [] patterns= new String JavaDoc[size];
397         for (int i= 0; i < size; i++)
398             patterns[i]= ((SearchPatternData) fPreviousSearchPatterns.get(i)).textPattern;
399         return patterns;
400     }
401         
402     private String JavaDoc[] getExtensions() {
403         return fFileTypeEditor.getFileTypes();
404     }
405
406     private boolean isCaseSensitive() {
407         return fIsCaseSensitiveCheckbox.getSelection();
408     }
409
410     /*
411      * Implements method from IDialogPage
412      */

413     public void setVisible(boolean visible) {
414         if (visible && fPattern != null) {
415             if (fFirstTime) {
416                 fFirstTime= false;
417                 // Set item and text here to prevent page from resizing
418
fPattern.setItems(getPreviousSearchPatterns());
419                 fExtensions.setItems(getPreviousExtensions());
420 // if (fExtensions.getItemCount() == 0) {
421
// loadFilePatternDefaults();
422
// }
423
if (!initializePatternControl()) {
424                     fPattern.select(0);
425                     fExtensions.setText("*"); //$NON-NLS-1$
426
handleWidgetSelected();
427                 }
428             }
429             fPattern.setFocus();
430         }
431         updateOKStatus();
432         super.setVisible(visible);
433     }
434     
435     final void updateOKStatus() {
436         boolean regexStatus= validateRegex();
437         boolean hasFilePattern= fExtensions.getText().length() > 0;
438         getContainer().setPerformActionEnabled(regexStatus && hasFilePattern);
439     }
440
441     //---- Widget creation ------------------------------------------------
442

443     public void createControl(Composite parent) {
444         initializeDialogUnits(parent);
445         readConfiguration();
446         
447         Composite result= new Composite(parent, SWT.NONE);
448         result.setFont(parent.getFont());
449         GridLayout layout= new GridLayout(2, false);
450         result.setLayout(layout);
451         
452         addTextPatternControls(result);
453         
454         Label separator= new Label(result, SWT.NONE);
455         separator.setVisible(false);
456         GridData data= new GridData(GridData.FILL, GridData.FILL, false, false, 2, 1);
457         data.heightHint= convertHeightInCharsToPixels(1) / 3;
458         separator.setLayoutData(data);
459         
460         addFileNameControls(result);
461
462         setControl(result);
463         Dialog.applyDialogFont(result);
464         PlatformUI.getWorkbench().getHelpSystem().setHelp(result, ISearchHelpContextIds.TEXT_SEARCH_PAGE);
465 }
466     
467     private boolean validateRegex() {
468         if (fIsRegExCheckbox.getSelection()) {
469             try {
470                 Pattern.compile(fPattern.getText());
471             } catch (PatternSyntaxException JavaDoc e) {
472                 String JavaDoc locMessage= e.getLocalizedMessage();
473                 int i= 0;
474                 while (i < locMessage.length() && "\n\r".indexOf(locMessage.charAt(i)) == -1) { //$NON-NLS-1$
475
i++;
476                 }
477                 statusMessage(true, locMessage.substring(0, i)); // only take first line
478
return false;
479             }
480             statusMessage(false, ""); //$NON-NLS-1$
481
} else {
482             statusMessage(false, SearchMessages.SearchPage_containingText_hint);
483         }
484         return true;
485     }
486
487     private void addTextPatternControls(Composite group) {
488         // grid layout with 2 columns
489

490         // Info text
491
Label label= new Label(group, SWT.LEAD);
492         label.setText(SearchMessages.SearchPage_containingText_text);
493         label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
494         label.setFont(group.getFont());
495
496         // Pattern combo
497
fPattern= new Combo(group, SWT.SINGLE | SWT.BORDER);
498         // Not done here to prevent page from resizing
499
// fPattern.setItems(getPreviousSearchPatterns());
500
fPattern.addSelectionListener(new SelectionAdapter() {
501             public void widgetSelected(SelectionEvent e) {
502                 handleWidgetSelected();
503                 updateOKStatus();
504             }
505         });
506         // add some listeners for regex syntax checking
507
fPattern.addModifyListener(new ModifyListener() {
508             public void modifyText(ModifyEvent e) {
509                 updateOKStatus();
510             }
511         });
512         fPattern.setFont(group.getFont());
513         GridData data= new GridData(GridData.FILL, GridData.FILL, true, false, 1, 1);
514         data.widthHint= convertWidthInCharsToPixels(50);
515         fPattern.setLayoutData(data);
516         
517         fIsCaseSensitiveCheckbox= new Button(group, SWT.CHECK);
518         fIsCaseSensitiveCheckbox.setText(SearchMessages.SearchPage_caseSensitive);
519         fIsCaseSensitiveCheckbox.setSelection(fIsCaseSensitive);
520         fIsCaseSensitiveCheckbox.addSelectionListener(new SelectionAdapter() {
521             public void widgetSelected(SelectionEvent e) {
522                 fIsCaseSensitive= fIsCaseSensitiveCheckbox.getSelection();
523             }
524         });
525         fIsCaseSensitiveCheckbox.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
526         fIsCaseSensitiveCheckbox.setFont(group.getFont());
527
528         // Text line which explains the special characters
529
fStatusLabel= new CLabel(group, SWT.LEAD);
530         fStatusLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
531         fStatusLabel.setFont(group.getFont());
532         fStatusLabel.setAlignment(SWT.LEFT);
533         fStatusLabel.setText(SearchMessages.SearchPage_containingText_hint);
534
535         // RegEx checkbox
536
fIsRegExCheckbox= new Button(group, SWT.CHECK);
537         fIsRegExCheckbox.setText(SearchMessages.SearchPage_regularExpression);
538         fIsRegExCheckbox.setSelection(fIsRegExSearch);
539         setContentAssistsEnablement(fIsRegExSearch);
540         fIsRegExCheckbox.addSelectionListener(new SelectionAdapter() {
541             public void widgetSelected(SelectionEvent e) {
542                 fIsRegExSearch= fIsRegExCheckbox.getSelection();
543                 updateOKStatus();
544
545                 writeConfiguration();
546                 setContentAssistsEnablement(fIsRegExSearch);
547             }
548         });
549         fIsRegExCheckbox.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
550         fIsRegExCheckbox.setFont(group.getFont());
551     }
552
553     private void handleWidgetSelected() {
554         int selectionIndex= fPattern.getSelectionIndex();
555         if (selectionIndex < 0 || selectionIndex >= fPreviousSearchPatterns.size())
556             return;
557         
558         SearchPatternData patternData= (SearchPatternData) fPreviousSearchPatterns.get(selectionIndex);
559         if (!fPattern.getText().equals(patternData.textPattern))
560             return;
561         fIsCaseSensitiveCheckbox.setSelection(patternData.isCaseSensitive);
562         fIsRegExCheckbox.setSelection(patternData.isRegExSearch);
563         fPattern.setText(patternData.textPattern);
564         fFileTypeEditor.setFileTypes(patternData.fileNamePatterns);
565         if (patternData.workingSets != null)
566             getContainer().setSelectedWorkingSets(patternData.workingSets);
567         else
568             getContainer().setSelectedScope(patternData.scope);
569     }
570
571     private boolean initializePatternControl() {
572         ISelection selection= getSelection();
573         if (selection instanceof ITextSelection && !selection.isEmpty()) {
574             String JavaDoc text= ((ITextSelection) selection).getText();
575             if (text != null) {
576                 fPattern.setText(insertEscapeChars(text));
577                 
578                 if (getPreviousExtensions().length > 0) {
579                     fExtensions.setText(getPreviousExtensions()[0]);
580                 } else {
581                     String JavaDoc extension= getExtensionFromEditor();
582                     if (extension != null)
583                         fExtensions.setText(extension);
584                     else
585                         fExtensions.setText("*"); //$NON-NLS-1$
586
}
587                 return true;
588             }
589         }
590         return false;
591     }
592     
593 // private void loadFilePatternDefaults() {
594
// SearchMatchInformationProviderRegistry registry= SearchPlugin.getDefault().getSearchMatchInformationProviderRegistry();
595
// String[] defaults= registry.getDefaultFilePatterns();
596
// fExtensions.setItems(defaults);
597
// fExtensions.setText(defaults[0]);
598
// }
599

600     private String JavaDoc insertEscapeChars(String JavaDoc text) {
601         if (text == null || text.equals("")) //$NON-NLS-1$
602
return ""; //$NON-NLS-1$
603
StringBuffer JavaDoc sbIn= new StringBuffer JavaDoc(text);
604         BufferedReader JavaDoc reader= new BufferedReader JavaDoc(new StringReader JavaDoc(text));
605         int lengthOfFirstLine= 0;
606         try {
607             lengthOfFirstLine= reader.readLine().length();
608         } catch (IOException JavaDoc ex) {
609             return ""; //$NON-NLS-1$
610
}
611         StringBuffer JavaDoc sbOut= new StringBuffer JavaDoc(lengthOfFirstLine + 5);
612         int i= 0;
613         while (i < lengthOfFirstLine) {
614             char ch= sbIn.charAt(i);
615             if (ch == '*' || ch == '?' || ch == '\\')
616                 sbOut.append("\\"); //$NON-NLS-1$
617
sbOut.append(ch);
618             i++;
619         }
620         return sbOut.toString();
621     }
622
623     private String JavaDoc getExtensionFromEditor() {
624         IEditorPart ep= SearchPlugin.getActivePage().getActiveEditor();
625         if (ep != null) {
626             Object JavaDoc elem= ep.getEditorInput();
627             if (elem instanceof IFileEditorInput) {
628                 String JavaDoc extension= ((IFileEditorInput)elem).getFile().getFileExtension();
629                 if (extension == null)
630                     return ((IFileEditorInput)elem).getFile().getName();
631                 return "*." + extension; //$NON-NLS-1$
632
}
633         }
634         return null;
635     }
636
637     private void addFileNameControls(Composite group) {
638         // grid layout with 2 columns
639

640         // Line with label, combo and button
641
Label label= new Label(group, SWT.LEAD);
642         label.setText(SearchMessages.SearchPage_fileNamePatterns_text);
643         label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
644         label.setFont(group.getFont());
645         
646         fExtensions= new Combo(group, SWT.SINGLE | SWT.BORDER);
647         fExtensions.addModifyListener(new ModifyListener() {
648             public void modifyText(ModifyEvent e) {
649                 updateOKStatus();
650             }
651         });
652         GridData data= new GridData(GridData.FILL, GridData.FILL, true, false, 1, 1);
653         data.widthHint= convertWidthInCharsToPixels(50);
654         fExtensions.setLayoutData(data);
655         fExtensions.setFont(group.getFont());
656         
657         Button button= new Button(group, SWT.PUSH);
658         button.setText(SearchMessages.SearchPage_browse);
659         GridData gridData= new GridData(SWT.BEGINNING, SWT.CENTER, false, false, 1, 1);
660         gridData.widthHint= SWTUtil.getButtonWidthHint(button);
661         button.setLayoutData(gridData);
662         button.setFont(group.getFont());
663         
664         IEditorRegistry editorRegistry= SearchPlugin.getDefault().getWorkbench().getEditorRegistry();
665         fFileTypeEditor= new FileTypeEditor(editorRegistry, fExtensions, button);
666         
667         // Text line which explains the special characters
668
Label description= new Label(group, SWT.LEAD);
669         description.setText(SearchMessages.SearchPage_fileNamePatterns_hint);
670         description.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
671         description.setFont(group.getFont());
672         
673         fSearchDerivedCheckbox= new Button(group, SWT.CHECK);
674         fSearchDerivedCheckbox.setText(SearchMessages.TextSearchPage_searchDerived_label);
675         
676         fSearchDerivedCheckbox.setSelection(fSearchDerived);
677         fSearchDerivedCheckbox.addSelectionListener(new SelectionAdapter() {
678             public void widgetSelected(SelectionEvent e) {
679                 fSearchDerived= fSearchDerivedCheckbox.getSelection();
680                 writeConfiguration();
681             }
682         });
683         fSearchDerivedCheckbox.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
684         fSearchDerivedCheckbox.setFont(group.getFont());
685     }
686
687     /**
688      * Sets the search page's container.
689      * @param container the container to set
690      */

691     public void setContainer(ISearchPageContainer container) {
692         fContainer= container;
693     }
694     
695     private ISearchPageContainer getContainer() {
696         return fContainer;
697     }
698     
699     private ISelection getSelection() {
700         return fContainer.getSelection();
701     }
702         
703
704     //--------------- Configuration handling --------------
705

706     /* (non-Javadoc)
707      * @see org.eclipse.jface.dialogs.DialogPage#dispose()
708      */

709     public void dispose() {
710         writeConfiguration();
711         super.dispose();
712     }
713     
714     /**
715      * Returns the page settings for this Text search page.
716      *
717      * @return the page settings to be used
718      */

719     private IDialogSettings getDialogSettings() {
720         return SearchPlugin.getDefault().getDialogSettingsSection(PAGE_NAME);
721     }
722         
723     
724     /**
725      * Initializes itself from the stored page settings.
726      */

727     private void readConfiguration() {
728         IDialogSettings s= getDialogSettings();
729         fIsCaseSensitive= s.getBoolean(STORE_CASE_SENSITIVE);
730         fIsRegExSearch= s.getBoolean(STORE_IS_REG_EX_SEARCH);
731         fSearchDerived= s.getBoolean(STORE_SEARCH_DERIVED);
732         
733         try {
734             int historySize= s.getInt(STORE_HISTORY_SIZE);
735             for (int i= 0; i < historySize; i++) {
736                 IDialogSettings histSettings= s.getSection(STORE_HISTORY + i);
737                 if (histSettings != null) {
738                     SearchPatternData data= SearchPatternData.create(histSettings);
739                     if (data != null) {
740                         fPreviousSearchPatterns.add(data);
741                     }
742                 }
743             }
744         } catch (NumberFormatException JavaDoc e) {
745             // ignore
746
}
747     }
748     
749     /**
750      * Stores it current configuration in the dialog store.
751      */

752     private void writeConfiguration() {
753         IDialogSettings s= getDialogSettings();
754         s.put(STORE_CASE_SENSITIVE, fIsCaseSensitive);
755         s.put(STORE_IS_REG_EX_SEARCH, fIsRegExSearch);
756         s.put(STORE_SEARCH_DERIVED, fSearchDerived);
757         
758         int historySize= Math.min(fPreviousSearchPatterns.size(), HISTORY_SIZE);
759         s.put(STORE_HISTORY_SIZE, historySize);
760         for (int i= 0; i < historySize; i++) {
761             IDialogSettings histSettings= s.addNewSection(STORE_HISTORY + i);
762             SearchPatternData data= ((SearchPatternData) fPreviousSearchPatterns.get(i));
763             data.store(histSettings);
764         }
765     }
766     
767     private void setContentAssistsEnablement(boolean enable) {
768         if (enable) {
769             if (fReplaceContentAssistHandler == null) {
770                 fReplaceContentAssistHandler= ContentAssistHandler.createHandlerForCombo(fPattern, ReplaceDialog2.createContentAssistant(true));
771             }
772             fReplaceContentAssistHandler.setEnabled(true);
773         } else {
774             if (fReplaceContentAssistHandler == null)
775                 return;
776             fReplaceContentAssistHandler.setEnabled(false);
777         }
778     }
779
780     private void statusMessage(boolean error, String JavaDoc message) {
781         fStatusLabel.setText(message);
782         if (error)
783             fStatusLabel.setForeground(JFaceColors.getErrorText(fStatusLabel.getDisplay()));
784         else
785             fStatusLabel.setForeground(null);
786     }
787
788 }
789
Popular Tags