KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > refactoring > nls > search > NLSSearchPage


1 /*******************************************************************************
2  * Copyright (c) 2000, 2005 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.jdt.internal.ui.refactoring.nls.search;
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
18 import org.eclipse.search.ui.ISearchPage;
19 import org.eclipse.search.ui.ISearchPageContainer;
20 import org.eclipse.search.ui.NewSearchUI;
21
22 import org.eclipse.core.resources.IFile;
23 import org.eclipse.core.resources.IProject;
24 import org.eclipse.core.resources.IResource;
25 import org.eclipse.core.runtime.IAdaptable;
26 import org.eclipse.core.runtime.IPath;
27 import org.eclipse.core.runtime.IStatus;
28 import org.eclipse.core.runtime.Path;
29
30 import org.eclipse.swt.SWT;
31 import org.eclipse.swt.events.ModifyEvent;
32 import org.eclipse.swt.events.ModifyListener;
33 import org.eclipse.swt.events.SelectionAdapter;
34 import org.eclipse.swt.events.SelectionEvent;
35 import org.eclipse.swt.layout.GridData;
36 import org.eclipse.swt.layout.GridLayout;
37 import org.eclipse.swt.widgets.Button;
38 import org.eclipse.swt.widgets.Combo;
39 import org.eclipse.swt.widgets.Composite;
40 import org.eclipse.swt.widgets.Control;
41 import org.eclipse.swt.widgets.Label;
42 import org.eclipse.swt.widgets.Shell;
43 import org.eclipse.swt.widgets.Text;
44
45 import org.eclipse.jface.dialogs.Dialog;
46 import org.eclipse.jface.dialogs.DialogPage;
47 import org.eclipse.jface.dialogs.IDialogConstants;
48 import org.eclipse.jface.dialogs.ProgressMonitorDialog;
49 import org.eclipse.jface.text.ITextSelection;
50 import org.eclipse.jface.viewers.ILabelProvider;
51 import org.eclipse.jface.viewers.ISelection;
52 import org.eclipse.jface.viewers.IStructuredSelection;
53 import org.eclipse.jface.viewers.ITreeContentProvider;
54 import org.eclipse.jface.window.Window;
55
56 import org.eclipse.ui.IEditorInput;
57 import org.eclipse.ui.IEditorPart;
58 import org.eclipse.ui.IWorkbenchPage;
59 import org.eclipse.ui.IWorkbenchWindow;
60 import org.eclipse.ui.IWorkingSet;
61 import org.eclipse.ui.dialogs.ElementListSelectionDialog;
62 import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
63 import org.eclipse.ui.dialogs.ISelectionStatusValidator;
64 import org.eclipse.ui.dialogs.SelectionDialog;
65 import org.eclipse.ui.PlatformUI;
66 import org.eclipse.ui.model.IWorkbenchAdapter;
67
68 import org.eclipse.jdt.core.IClassFile;
69 import org.eclipse.jdt.core.ICodeAssist;
70 import org.eclipse.jdt.core.ICompilationUnit;
71 import org.eclipse.jdt.core.IField;
72 import org.eclipse.jdt.core.IImportDeclaration;
73 import org.eclipse.jdt.core.IJavaElement;
74 import org.eclipse.jdt.core.IMethod;
75 import org.eclipse.jdt.core.IType;
76 import org.eclipse.jdt.core.JavaCore;
77 import org.eclipse.jdt.core.JavaModelException;
78 import org.eclipse.jdt.core.search.IJavaSearchConstants;
79 import org.eclipse.jdt.core.search.IJavaSearchScope;
80 import org.eclipse.jdt.core.search.SearchEngine;
81
82 import org.eclipse.jdt.ui.IJavaElementSearchConstants;
83 import org.eclipse.jdt.ui.IWorkingCopyManager;
84 import org.eclipse.jdt.ui.JavaElementLabelProvider;
85 import org.eclipse.jdt.ui.JavaElementSorter;
86 import org.eclipse.jdt.ui.JavaUI;
87 import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
88
89 import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
90 import org.eclipse.jdt.internal.corext.util.Messages;
91
92 import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
93 import org.eclipse.jdt.internal.ui.JavaPlugin;
94 import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
95 import org.eclipse.jdt.internal.ui.filters.EmptyInnerPackageFilter;
96 import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
97 import org.eclipse.jdt.internal.ui.search.JavaSearchScopeFactory;
98 import org.eclipse.jdt.internal.ui.search.PatternStrings;
99 import org.eclipse.jdt.internal.ui.search.SearchUtil;
100 import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
101 import org.eclipse.jdt.internal.ui.util.RowLayouter;
102 import org.eclipse.jdt.internal.ui.util.SWTUtil;
103 import org.eclipse.jdt.internal.ui.viewsupport.LibraryFilter;
104
105 public class NLSSearchPage extends DialogPage implements ISearchPage, IJavaSearchConstants {
106
107     public static final String JavaDoc EXTENSION_POINT_ID= "org.eclipse.jdt.ui.nls.NLSSearchPage"; //$NON-NLS-1$
108
private static final String JavaDoc RESOURCE_BUNDLE_FIELD= "RESOURCE_BUNDLE"; //$NON-NLS-1$
109
private static final String JavaDoc BUNDLE_NAME_FIELD= "BUNDLE_NAME"; //$NON-NLS-1$
110

111     private static java.util.List JavaDoc fgPreviousSearchPatterns= new ArrayList JavaDoc(20);
112
113     private Combo fWrapperClassCombo;
114     private Text fPropertyFileText;
115     private boolean fFirstTime= true;
116     private ISearchPageContainer fContainer;
117
118     private IJavaElement fWrapperClass;
119
120     private static class SearchPatternData {
121
122         String JavaDoc propertyFileName;
123         IFile propertyFile;
124         String JavaDoc wrapperClassName;
125         IJavaElement wrapperClass;
126         int scope;
127         IWorkingSet[] workingSets;
128
129         public SearchPatternData(String JavaDoc wrapperClassName, IJavaElement wrapperClass, String JavaDoc p) {
130             this(wrapperClassName, wrapperClass, p, ISearchPageContainer.WORKSPACE_SCOPE, null);
131         }
132
133         public SearchPatternData(String JavaDoc wrapperClassName, IJavaElement wrapperClass, String JavaDoc p, int scope , IWorkingSet[] workingSets) {
134             if (wrapperClassName == null)
135                 this.wrapperClassName= ""; //$NON-NLS-1$
136
else
137                 this.wrapperClassName= wrapperClassName;
138             this.wrapperClass= wrapperClass;
139             this.scope= scope;
140             this.workingSets= workingSets;
141             propertyFileName= p;
142             if (p != null && p.length() > 0) {
143                 IPath path= new Path(propertyFileName);
144                 if (path.segmentCount() >= 2)
145                     propertyFile= JavaPlugin.getWorkspace().getRoot().getFile(path);
146             }
147         }
148     }
149
150     //---- Action Handling ------------------------------------------------
151

152     public boolean performAction() {
153         return performNewSearch();
154     }
155
156     private boolean performNewSearch() {
157         SearchPatternData data= getPatternData();
158         if (data.wrapperClass == null || data.propertyFile == null)
159             return false;
160         
161         // Setup search scope
162
IJavaSearchScope scope= null;
163         String JavaDoc scopeDescription= ""; //$NON-NLS-1$
164

165         boolean includeJRE= true;
166         
167         switch (getContainer().getSelectedScope()) {
168             case ISearchPageContainer.WORKSPACE_SCOPE :
169                 scopeDescription= NLSSearchMessages.WorkspaceScope;
170                 scope= SearchEngine.createWorkspaceScope();
171                 break;
172             case ISearchPageContainer.SELECTION_SCOPE :
173                 scopeDescription= NLSSearchMessages.SelectionScope;
174                 scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(getSelection(), includeJRE);
175                 break;
176             case ISearchPageContainer.SELECTED_PROJECTS_SCOPE :
177                 scope= JavaSearchScopeFactory.getInstance().createJavaProjectSearchScope(getSelection(), includeJRE);
178                 IProject[] projects= JavaSearchScopeFactory.getInstance().getProjects(scope);
179                 if (projects.length > 1)
180                     scopeDescription= Messages.format(NLSSearchMessages.EnclosingProjectsScope, projects[0].getName());
181                 else if (projects.length == 1)
182                     scopeDescription= Messages.format(NLSSearchMessages.EnclosingProjectScope, projects[0].getName());
183                 else
184                     scopeDescription= Messages.format(NLSSearchMessages.EnclosingProjectScope, ""); //$NON-NLS-1$
185
break;
186             case ISearchPageContainer.WORKING_SET_SCOPE :
187                 IWorkingSet[] workingSets= getContainer().getSelectedWorkingSets();
188                 // should not happen - just to be sure
189
if (workingSets == null || workingSets.length < 1)
190                     return false;
191                 scopeDescription= Messages.format(NLSSearchMessages.WorkingSetScope, new String JavaDoc[] { SearchUtil.toString(workingSets)});
192                 scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(getContainer().getSelectedWorkingSets(), includeJRE);
193                 SearchUtil.updateLRUWorkingSets(getContainer().getSelectedWorkingSets());
194         }
195         
196         NLSSearchQuery query= new NLSSearchQuery(data.wrapperClass, data.propertyFile, scope, scopeDescription);
197         NewSearchUI.activateSearchResultView();
198         NewSearchUI.runQueryInBackground(query); // NLSSearchQuery can be run in background
199
return true;
200     }
201
202     private String JavaDoc[] getPreviousSearchPatterns() {
203         // Search results are not persistent
204
int patternCount= fgPreviousSearchPatterns.size();
205         String JavaDoc[] patterns= new String JavaDoc[patternCount];
206         for (int i= 0; i < patternCount; i++)
207             patterns[i]= ((SearchPatternData) fgPreviousSearchPatterns.get(patternCount - 1 - i)).wrapperClassName;
208         return patterns;
209     }
210
211     private String JavaDoc getWrapperClassName() {
212         return fWrapperClassCombo.getText();
213     }
214     /**
215      * Return search pattern data and update previous searches.
216      * An existing entry will be updated.
217      */

218     private SearchPatternData getPatternData() {
219         String JavaDoc pattern= getWrapperClassName();
220         SearchPatternData match= null;
221         int i= 0;
222         int size= fgPreviousSearchPatterns.size();
223
224         if (fWrapperClass == null) {
225             SelectionDialog dialog= createWrapperClassSelectionDialog();
226             if (dialog == null)
227                 fWrapperClass= null;
228             else if (dialog.open() == IDialogConstants.OK_ID) {
229                 Object JavaDoc[] types= dialog.getResult();
230                 if (types != null && types.length > 0) {
231                     fWrapperClass= (IType) types[0];
232                     fWrapperClassCombo.setText(PatternStrings.getSignature(fWrapperClass));
233                     pattern= getWrapperClassName();
234                 }
235             }
236         }
237
238         while (match == null && i < size) {
239             match= (SearchPatternData) fgPreviousSearchPatterns.get(i);
240             i++;
241             if (!pattern.equals(match.wrapperClassName))
242                 match= null;
243         }
244         if (match == null) {
245             match= new SearchPatternData(pattern, fWrapperClass, fPropertyFileText.getText());
246             fgPreviousSearchPatterns.add(match);
247         } else {
248             match.wrapperClass= fWrapperClass;
249             match.propertyFileName= fPropertyFileText.getText();
250             match.scope= getContainer().getSelectedScope();
251             match.workingSets= getContainer().getSelectedWorkingSets();
252             match.propertyFile= null;
253             if (match.propertyFileName != null) {
254                 IPath path= new Path(match.propertyFileName);
255                 if (path.segmentCount() >= 2)
256                     match.propertyFile= JavaPlugin.getWorkspace().getRoot().getFile(path);
257             }
258         }
259         return match;
260     }
261     /*
262      * Implements method from IDialogPage
263      */

264     public void setVisible(boolean visible) {
265         if (visible && fWrapperClassCombo != null) {
266             if (fFirstTime) {
267                 JavaPlugin.getDefault().getImageRegistry();
268                 fFirstTime= false;
269                 // Set item and text here to prevent page from resizing
270
fWrapperClassCombo.setItems(getPreviousSearchPatterns());
271                 initSelections();
272             }
273             fWrapperClassCombo.setFocus();
274             getContainer().setPerformActionEnabled(getWrapperClassName().length() > 0 && fPropertyFileText.getText().length() > 0);
275         }
276         super.setVisible(visible);
277     }
278
279     public boolean isValid() {
280         return true;
281     }
282
283     //---- Widget creation ------------------------------------------------
284
/**
285      * Creates the page's content.
286      */

287     public void createControl(Composite parent) {
288         GridData gd;
289         Composite result= new Composite(parent, SWT.NONE);
290         GridLayout layout= new GridLayout();
291         layout.numColumns= 2;
292         layout.makeColumnsEqualWidth= true;
293         layout.horizontalSpacing= 10;
294         result.setLayout(layout);
295         result.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
296
297         RowLayouter layouter= new RowLayouter(layout.numColumns);
298         gd= new GridData();
299         gd.horizontalAlignment= GridData.FILL;
300         layouter.setDefaultGridData(gd, 0);
301         layouter.setDefaultGridData(gd, 1);
302         layouter.setDefaultSpan();
303
304         layouter.perform(createWrapperClassControl(result));
305         layouter.perform(createPropertyFileControl(result));
306
307         setControl(result);
308
309         Dialog.applyDialogFont(result);
310         PlatformUI.getWorkbench().getHelpSystem().setHelp(result, IJavaHelpContextIds.NLS_SEARCH_PAGE);
311     }
312     /**
313      * Creates the control for the wrapper class
314      */

315     private Control createWrapperClassControl(Composite parent) {
316         Composite result= new Composite(parent, SWT.NONE);
317         result.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
318         GridLayout layout= new GridLayout();
319         layout.numColumns= 2;
320         result.setLayout(layout);
321
322         Label label= new Label(result, SWT.NORMAL);
323         label.setText(NLSSearchMessages.NLSSearchPage_wrapperClassGroup_text);
324         GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
325         gd.horizontalSpan= 2;
326         label.setLayoutData(gd);
327         
328         // Wrapper class combo
329
fWrapperClassCombo= new Combo(result, SWT.SINGLE | SWT.BORDER);
330         fWrapperClassCombo.addSelectionListener(new SelectionAdapter() {
331             public void widgetSelected(SelectionEvent e) {
332                 if (fWrapperClassCombo.getSelectionIndex() < 0)
333                     return;
334                 int index= fgPreviousSearchPatterns.size() - 1 - fWrapperClassCombo.getSelectionIndex();
335                 SearchPatternData values= (SearchPatternData) fgPreviousSearchPatterns.get(index);
336                 fWrapperClass= values.wrapperClass;
337                 fWrapperClassCombo.setText(values.wrapperClassName);
338                 fPropertyFileText.setText(values.propertyFileName);
339                 if (values.workingSets != null)
340                     getContainer().setSelectedWorkingSets(values.workingSets);
341                 else
342                     getContainer().setSelectedScope(values.scope);
343             }
344         });
345         fWrapperClassCombo.addModifyListener(new ModifyListener() {
346             public void modifyText(ModifyEvent e) {
347                 if (fWrapperClass != null && !PatternStrings.getSignature(fWrapperClass).equals(fWrapperClassCombo.getText()))
348                     fWrapperClass= null;
349                 getContainer().setPerformActionEnabled(fWrapperClassCombo.getText().length() > 0 && fPropertyFileText.getText().length() > 0);
350             }
351         });
352         gd= new GridData(GridData.FILL_HORIZONTAL);
353         gd.widthHint= convertWidthInCharsToPixels(30);
354         fWrapperClassCombo.setLayoutData(gd);
355
356         // browse button
357
Button browseButton= new Button(result, SWT.PUSH);
358         browseButton.setText(NLSSearchMessages.NLSSearchPage_wrapperClassBrowseButton_text);
359         browseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
360         SWTUtil.setButtonDimensionHint(browseButton);
361         browseButton.addSelectionListener(new SelectionAdapter() {
362             public void widgetSelected(SelectionEvent e) {
363                 handleBrowseWrapperClassButtonPressed();
364             }
365         });
366
367         return result;
368     }
369     /**
370      * Creates the control for the property file
371      */

372     private Control createPropertyFileControl(Composite parent) {
373         Composite result= new Composite(parent, SWT.NONE);
374         result.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
375         GridLayout layout= new GridLayout();
376         layout.numColumns= 2;
377         result.setLayout(layout);
378         
379         Label label= new Label(result, SWT.NORMAL);
380         label.setText(NLSSearchMessages.NLSSearchPage_propertyFileGroup_text);
381         GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
382         gd.horizontalSpan= 2;
383         label.setLayoutData(gd);
384
385         fPropertyFileText= new Text(result, SWT.SINGLE | SWT.BORDER);
386         fPropertyFileText.addModifyListener(new ModifyListener() {
387             public void modifyText(ModifyEvent e) {
388                 getContainer().setPerformActionEnabled(fWrapperClassCombo.getText().length() > 0 && fPropertyFileText.getText().length() > 0);
389             }
390         });
391         gd= new GridData(GridData.FILL_HORIZONTAL);
392         gd.widthHint= convertWidthInCharsToPixels(30);
393         fPropertyFileText.setLayoutData(gd);
394
395         // browse button
396
Button browseButton= new Button(result, SWT.PUSH);
397         browseButton.setText(NLSSearchMessages.NLSSearchPage_propertyFileBrowseButton_text);
398         browseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
399         SWTUtil.setButtonDimensionHint(browseButton);
400         browseButton.addSelectionListener(new SelectionAdapter() {
401             public void widgetSelected(SelectionEvent e) {
402                 handleBrowsePropertiesButtonPressed();
403             }
404         });
405
406         return result;
407     }
408
409     private void initSelections() {
410         fWrapperClass= null;
411         ISelection selection= getSelection();
412         SearchPatternData values= null;
413         values= tryIfPropertyFileSelected(selection);
414         if (values == null)
415             values= tryTypedTextSelection(selection);
416         if (values == null)
417             values= trySelection(selection);
418         if (values == null)
419             values= trySimpleTextSelection(selection);
420         if (values == null)
421             values= getDefaultInitValues();
422         fPropertyFileText.setText(values.propertyFileName);
423         fWrapperClass= values.wrapperClass;
424         if (fWrapperClass != null)
425             fWrapperClassCombo.setText(PatternStrings.getSignature(fWrapperClass));
426         else
427             fWrapperClassCombo.setText(values.wrapperClassName); //$NON-NLS-1$
428
}
429
430     private SearchPatternData tryTypedTextSelection(ISelection selection) {
431         if (selection instanceof ITextSelection) {
432             IEditorPart e= getEditorPart();
433             if (e != null) {
434                 ITextSelection ts= (ITextSelection) selection;
435                 ICodeAssist assist= getCodeAssist(e);
436                 if (assist != null) {
437                     IJavaElement[] elements= null;
438                     try {
439                         elements= assist.codeSelect(ts.getOffset(), ts.getLength());
440                     } catch (JavaModelException ex) {
441                         ExceptionHandler.handle(ex, NLSSearchMessages.Search_Error_createJavaElement_title, NLSSearchMessages.Search_Error_createJavaElement_message);
442                     }
443                     if (elements != null && elements.length > 0) {
444                         if (elements.length == 1)
445                             fWrapperClass= elements[0];
446                         else
447                             fWrapperClass= chooseFromList(elements);
448                         if (fWrapperClass != null)
449                             return determineInitValuesFrom(fWrapperClass);
450                     }
451                 }
452             }
453         }
454         return null;
455     }
456
457     private ICodeAssist getCodeAssist(IEditorPart editorPart) {
458         IEditorInput input= editorPart.getEditorInput();
459         if (input instanceof IClassFileEditorInput)
460             return ((IClassFileEditorInput) input).getClassFile();
461         IWorkingCopyManager manager= JavaUI.getWorkingCopyManager();
462         return manager.getWorkingCopy(input);
463     }
464
465     private SearchPatternData trySelection(ISelection selection) {
466         SearchPatternData result= null;
467         if (selection == null)
468             return result;
469         Object JavaDoc o= null;
470         if (selection instanceof IStructuredSelection)
471             o= ((IStructuredSelection) selection).getFirstElement();
472         if (o instanceof IJavaElement) {
473             fWrapperClass= (IJavaElement) o;
474             result= determineInitValuesFrom(fWrapperClass);
475         } if (o instanceof IAdaptable) {
476             IWorkbenchAdapter element= (IWorkbenchAdapter) ((IAdaptable) o).getAdapter(IWorkbenchAdapter.class);
477             if (element != null)
478                 result= new SearchPatternData(element.getLabel(o), null, ""); //$NON-NLS-1$
479
}
480         return result;
481     }
482
483     private SearchPatternData determineInitValuesFrom(IJavaElement element) {
484         if (element == null)
485             return null;
486         int searchFor= UNKNOWN;
487         String JavaDoc pattern= null;
488         IType mainType= null;
489         switch (element.getElementType()) {
490             case IJavaElement.PACKAGE_FRAGMENT :
491                 searchFor= PACKAGE;
492                 pattern= element.getElementName();
493                 break;
494             case IJavaElement.PACKAGE_FRAGMENT_ROOT :
495                 searchFor= PACKAGE;
496                 pattern= element.getElementName();
497                 break;
498             case IJavaElement.PACKAGE_DECLARATION :
499                 searchFor= PACKAGE;
500                 pattern= element.getElementName();
501                 break;
502             case IJavaElement.IMPORT_DECLARATION :
503                 pattern= element.getElementName();
504                 IImportDeclaration declaration= (IImportDeclaration) element;
505                 if (declaration.isOnDemand()) {
506                     searchFor= PACKAGE;
507                     int index= pattern.lastIndexOf('.');
508                     pattern= pattern.substring(0, index);
509                 } else {
510                     searchFor= TYPE;
511                 }
512                 break;
513             case IJavaElement.TYPE :
514                 searchFor= TYPE;
515                 mainType= (IType) element;
516                 pattern= JavaModelUtil.getFullyQualifiedName(mainType);
517                 break;
518             case IJavaElement.COMPILATION_UNIT :
519                 ICompilationUnit cu= (ICompilationUnit) element;
520                 String JavaDoc mainTypeName= element.getElementName().substring(0, element.getElementName().indexOf(".")); //$NON-NLS-1$
521
mainType= cu.getType(mainTypeName);
522                 mainTypeName= JavaModelUtil.getTypeQualifiedName(mainType);
523                 try {
524                     mainType= JavaModelUtil.findTypeInCompilationUnit(cu, mainTypeName);
525                     if (mainType == null) {
526                         // fetch type which is declared first in the file
527
IType[] types= cu.getTypes();
528                         if (types.length > 0)
529                             mainType= types[0];
530                         else
531                             break;
532                     }
533                 } catch (JavaModelException ex) {
534                     ExceptionHandler.handle(ex, NLSSearchMessages.Search_Error_javaElementAccess_title, NLSSearchMessages.Search_Error_javaElementAccess_message);
535                     break;
536                 }
537                 searchFor= TYPE;
538                 element= mainType;
539                 pattern= JavaModelUtil.getFullyQualifiedName(mainType);
540                 break;
541             case IJavaElement.CLASS_FILE :
542                 IClassFile cf= (IClassFile) element;
543                 try {
544                     mainType= cf.getType();
545                 } catch (JavaModelException ex) {
546                     ExceptionHandler.handle(ex, NLSSearchMessages.Search_Error_javaElementAccess_title, NLSSearchMessages.Search_Error_javaElementAccess_message);
547                     break;
548                 }
549                 if (mainType == null)
550                     break;
551                 searchFor= TYPE;
552                 pattern= JavaModelUtil.getFullyQualifiedName(mainType);
553                 break;
554             case IJavaElement.FIELD :
555                 searchFor= FIELD;
556                 IType type= ((IField) element).getDeclaringType();
557                 StringBuffer JavaDoc buffer= new StringBuffer JavaDoc();
558                 buffer.append(JavaModelUtil.getFullyQualifiedName(type));
559                 buffer.append('.');
560                 buffer.append(element.getElementName());
561                 pattern= buffer.toString();
562                 break;
563             case IJavaElement.METHOD :
564                 searchFor= METHOD;
565                 try {
566                     IMethod method= (IMethod) element;
567                     if (method.isConstructor())
568                         searchFor= CONSTRUCTOR;
569                 } catch (JavaModelException ex) {
570                     ExceptionHandler.handle(ex, NLSSearchMessages.Search_Error_javaElementAccess_title, NLSSearchMessages.Search_Error_javaElementAccess_message);
571                     break;
572                 }
573                 pattern= PatternStrings.getMethodSignature((IMethod) element);
574                 break;
575         }
576         if (searchFor == TYPE && pattern != null) {
577             String JavaDoc propertyFilePathStr= null; //$NON-NLS-1$
578
// make suggestions for properties file: look for string constants according to conventions
579
if (mainType != null) {
580                 propertyFilePathStr= getPropertyFilePathStr(mainType, RESOURCE_BUNDLE_FIELD);
581                 if (propertyFilePathStr == null)
582                     propertyFilePathStr= getPropertyFilePathStr(mainType, BUNDLE_NAME_FIELD);
583             }
584             if (propertyFilePathStr == null) {
585                 //fallback:
586
IPath path= element.getPath().removeFileExtension().addFileExtension("properties"); //$NON-NLS-1$
587
propertyFilePathStr= path.toString();
588             }
589             return new SearchPatternData(pattern, element, propertyFilePathStr); //$NON-NLS-1$
590
}
591
592         return null;
593     }
594
595     private String JavaDoc getPropertyFilePathStr(IType mainType, String JavaDoc fieldName) {
596         IField bundle= mainType.getField(fieldName);
597         if (bundle.exists()) {
598             try {
599                 Object JavaDoc constant= bundle.getConstant();
600                 if (constant instanceof String JavaDoc) {
601                     String JavaDoc string= (String JavaDoc) constant;
602                     return mainType.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT).getPath().toString()
603                         + IPath.SEPARATOR + string.substring(1, string.length() - 1).replace('.', IPath.SEPARATOR)
604                         + ".properties"; //$NON-NLS-1$
605
}
606             } catch (JavaModelException e) {
607                 return null; //failed
608
}
609         }
610         return null;
611     }
612
613     private SearchPatternData trySimpleTextSelection(ISelection selection) {
614         SearchPatternData result= null;
615         if (selection instanceof ITextSelection) {
616             BufferedReader JavaDoc reader= new BufferedReader JavaDoc(new StringReader JavaDoc(((ITextSelection) selection).getText()));
617             String JavaDoc text;
618             try {
619                 text= reader.readLine();
620                 if (text == null)
621                     text= ""; //$NON-NLS-1$
622
} catch (IOException JavaDoc ex) {
623                 text= ""; //$NON-NLS-1$
624
}
625             result= new SearchPatternData(text, null, ""); //$NON-NLS-1$
626
}
627         return result;
628     }
629
630     private SearchPatternData tryIfPropertyFileSelected(ISelection selection) {
631         if (selection instanceof IStructuredSelection) {
632             Object JavaDoc o= ((IStructuredSelection) selection).getFirstElement();
633             if (o instanceof IFile && ((IFile) o).getFileExtension().equalsIgnoreCase("properties")) { //$NON-NLS-1$
634
IPath propertyFullPath= ((IFile)o).getFullPath();
635                 String JavaDoc typePathStr= null;
636
637                 // try to be smarter and find a corresponding CU
638
IPath cuPath= propertyFullPath.removeFileExtension().addFileExtension("java"); //$NON-NLS-1$
639
IFile cuFile= (IFile)JavaPlugin.getWorkspace().getRoot().findMember(cuPath);
640                 if (cuFile == null) { //try with uppercase first char
641
String JavaDoc filename= cuPath.removeFileExtension().lastSegment();
642                     if (filename != null && filename.length() > 0) {
643                         filename= Character.toUpperCase(filename.charAt(0)) + filename.substring(1);
644                         IPath dirPath= propertyFullPath.removeLastSegments(1).addTrailingSeparator();
645                         cuPath= dirPath.append(filename).addFileExtension("java"); //$NON-NLS-1$
646
cuFile= (IFile)JavaPlugin.getWorkspace().getRoot().findMember(cuPath);
647                     }
648                 }
649                 IType type= null;
650                 if (cuFile != null && cuFile.exists()) {
651                     IJavaElement cu= JavaCore.create(cuFile);
652                     if (cu != null && cu.exists() && cu.getElementType() == IJavaElement.COMPILATION_UNIT)
653                         type= ((ICompilationUnit)cu).findPrimaryType();
654                         if (type != null)
655                             typePathStr= JavaModelUtil.getFullyQualifiedName(type);
656                         else {
657                             IPath propertyFile= propertyFullPath.removeFirstSegments(propertyFullPath.segmentCount() - 1);
658                             typePathStr= propertyFile.removeFileExtension().toString();
659                         }
660                 }
661                 return new SearchPatternData(typePathStr, type, propertyFullPath.toString());
662             }
663         }
664         return null;
665     }
666
667     private SearchPatternData getDefaultInitValues() {
668         return new SearchPatternData("", null, ""); //$NON-NLS-2$ //$NON-NLS-1$
669
}
670
671     private IJavaElement chooseFromList(IJavaElement[] openChoices) {
672         int flags= JavaElementLabelProvider.SHOW_DEFAULT | JavaElementLabelProvider.SHOW_QUALIFIED;
673         ILabelProvider labelProvider= new JavaElementLabelProvider(flags);
674         ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider);
675         dialog.setIgnoreCase(true);
676         dialog.setMultipleSelection(false);
677         dialog.setTitle(NLSSearchMessages.SearchElementSelectionDialog_title);
678         dialog.setMessage(NLSSearchMessages.SearchElementSelectionDialog_message);
679         dialog.setElements(openChoices);
680         if (dialog.open() == Window.OK)
681             return (IJavaElement)dialog.getFirstResult();
682         return null;
683     }
684
685     /*
686      * Implements method from ISearchPage
687      */

688     public void setContainer(ISearchPageContainer container) {
689         fContainer= container;
690     }
691
692     /**
693      * Returns the search page's container.
694      */

695     private ISearchPageContainer getContainer() {
696         return fContainer;
697     }
698
699     /**
700      * Returns the current active selection.
701      */

702     private ISelection getSelection() {
703         return fContainer.getSelection();
704     }
705
706     /**
707      * Returns the current active editor part.
708      */

709     private IEditorPart getEditorPart() {
710         IWorkbenchWindow window= JavaPlugin.getActiveWorkbenchWindow();
711         if (window != null) {
712             IWorkbenchPage page= window.getActivePage();
713             if (page != null)
714                 return page.getActiveEditor();
715         }
716         return null;
717     }
718
719     protected void handleBrowseWrapperClassButtonPressed() {
720         SelectionDialog dialog= createWrapperClassSelectionDialog();
721         if (dialog == null || dialog.open() == IDialogConstants.CANCEL_ID)
722             return;
723
724         Object JavaDoc[] types= dialog.getResult();
725         if (types != null && types.length > 0) {
726             fWrapperClass= (IType) types[0];
727             fWrapperClassCombo.setText(PatternStrings.getSignature(fWrapperClass));
728         }
729     }
730
731     protected void handleBrowsePropertiesButtonPressed() {
732         ElementTreeSelectionDialog dialog= createWorkspaceFileSelectionDialog(NLSSearchMessages.NLSSearchPage_propertiesFileSelectionDialog_title, NLSSearchMessages.NLSSearchPage_propertiesFileSelectionDialog_message);
733         dialog.setSorter(new JavaElementSorter());
734         dialog.setInitialSelections(new String JavaDoc[] { fPropertyFileText.getText()});
735         if (dialog.open() == Window.OK) {
736             Object JavaDoc[] resources= dialog.getResult();
737             if (resources.length == 1)
738                 fPropertyFileText.setText(((IResource) resources[0]).getFullPath().toString());
739         }
740     }
741     /**
742      * Creates and returns a dialog to choose an existing workspace file.
743      */

744     protected ElementTreeSelectionDialog createWorkspaceFileSelectionDialog(String JavaDoc title, String JavaDoc message) {
745         int labelFlags= JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_OVERLAY_ICONS | JavaElementLabelProvider.SHOW_SMALL_ICONS;
746         ITreeContentProvider contentProvider= new StandardJavaElementContentProvider();
747         ILabelProvider labelProvider= new JavaElementLabelProvider(labelFlags);
748         ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, contentProvider);
749         dialog.setAllowMultiple(false);
750         dialog.setDoubleClickSelects(true);
751         dialog.setValidator(new ISelectionStatusValidator() {
752             public IStatus validate(Object JavaDoc[] selection) {
753                 // only single selection
754
if (selection.length == 1 && (selection[0] instanceof IFile) && (((IFile) selection[0]).getFileExtension().equalsIgnoreCase("properties"))) //$NON-NLS-1$
755
return new StatusInfo();
756                 else
757                     return new StatusInfo(IStatus.ERROR, "");//$NON-NLS-1$
758
}
759         });
760         dialog.addFilter(new EmptyInnerPackageFilter());
761         dialog.addFilter(new LibraryFilter());
762         dialog.setTitle(title);
763         dialog.setMessage(message);
764         dialog.setStatusLineAboveButtons(true);
765         dialog.setInput(JavaCore.create(JavaPlugin.getWorkspace().getRoot()));
766         return dialog;
767     }
768     /**
769      * Creates and returns a dialog to choose an existing type.
770      */

771     protected SelectionDialog createWrapperClassSelectionDialog() {
772         Shell shell= getControl().getShell();
773         SelectionDialog dialog= null;
774         try {
775             String JavaDoc filter= getWrapperClassName();
776             int lastDot= filter.lastIndexOf('.');
777             if (lastDot > -1 && lastDot != filter.length() - 1)
778                 filter= filter.substring(lastDot + 1);
779             dialog= JavaUI.createTypeDialog(shell, new ProgressMonitorDialog(shell), SearchEngine.createWorkspaceScope(), IJavaElementSearchConstants.CONSIDER_TYPES, false, filter);
780             if (fWrapperClass != null)
781                 dialog.setInitialSelections(new Object JavaDoc[] {fWrapperClass});
782         } catch (JavaModelException e) {
783             ExceptionHandler.handle(e, NLSSearchMessages.NLSSearchPage_Error_createTypeDialog_title, NLSSearchMessages.NLSSearchPage_Error_createTypeDialog_message);
784             return null;
785         }
786
787         dialog.setTitle(NLSSearchMessages.NLSSearchPage_wrapperClassDialog_title);
788         dialog.setInitialSelections(new Object JavaDoc[] { getUnqualifiedType(getWrapperClassName())});
789         dialog.setMessage(NLSSearchMessages.NLSSearchPage_wrapperClassDialog_message);
790         return dialog;
791     }
792
793     public static String JavaDoc getUnqualifiedType(String JavaDoc typeName) {
794         if (typeName == null)
795             return null;
796         int lastDotIndex= typeName.lastIndexOf('.');
797         if (lastDotIndex < 0)
798             return typeName;
799         if (lastDotIndex > typeName.length() - 1)
800             return ""; //$NON-NLS-1$
801
return typeName.substring(lastDotIndex + 1);
802     }
803 }
804
Popular Tags