KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 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.IOException JavaDoc;
14 import java.lang.reflect.InvocationTargetException JavaDoc;
15 import com.ibm.icu.text.MessageFormat;
16 import java.util.ArrayList JavaDoc;
17 import java.util.Iterator JavaDoc;
18 import java.util.List JavaDoc;
19 import java.util.regex.Pattern JavaDoc;
20 import java.util.regex.PatternSyntaxException JavaDoc;
21
22 import org.eclipse.core.filebuffers.FileBuffers;
23 import org.eclipse.core.filebuffers.ITextFileBuffer;
24 import org.eclipse.core.filebuffers.ITextFileBufferManager;
25 import org.eclipse.core.filebuffers.LocationKind;
26
27 import org.eclipse.core.runtime.Assert;
28 import org.eclipse.core.runtime.CoreException;
29 import org.eclipse.core.runtime.IProgressMonitor;
30 import org.eclipse.core.runtime.OperationCanceledException;
31 import org.eclipse.core.runtime.SubProgressMonitor;
32 import org.eclipse.core.runtime.jobs.ISchedulingRule;
33
34 import org.eclipse.core.resources.IFile;
35 import org.eclipse.core.resources.IResource;
36 import org.eclipse.core.resources.IResourceRuleFactory;
37 import org.eclipse.core.resources.IWorkspace;
38 import org.eclipse.core.resources.IWorkspaceDescription;
39 import org.eclipse.core.resources.IncrementalProjectBuilder;
40 import org.eclipse.core.resources.ResourcesPlugin;
41
42 import org.eclipse.swt.SWT;
43 import org.eclipse.swt.events.SelectionAdapter;
44 import org.eclipse.swt.events.SelectionEvent;
45 import org.eclipse.swt.layout.GridData;
46 import org.eclipse.swt.layout.GridLayout;
47 import org.eclipse.swt.widgets.Button;
48 import org.eclipse.swt.widgets.Combo;
49 import org.eclipse.swt.widgets.Composite;
50 import org.eclipse.swt.widgets.Control;
51 import org.eclipse.swt.widgets.Label;
52 import org.eclipse.swt.widgets.Shell;
53 import org.eclipse.swt.widgets.Text;
54
55 import org.eclipse.jface.contentassist.SubjectControlContentAssistant;
56 import org.eclipse.jface.dialogs.IDialogConstants;
57 import org.eclipse.jface.dialogs.IDialogSettings;
58 import org.eclipse.jface.dialogs.MessageDialog;
59 import org.eclipse.jface.operation.IRunnableWithProgress;
60 import org.eclipse.jface.resource.JFaceColors;
61 import org.eclipse.jface.viewers.ISelection;
62 import org.eclipse.jface.viewers.IStructuredSelection;
63 import org.eclipse.jface.viewers.StructuredSelection;
64
65 import org.eclipse.jface.text.BadLocationException;
66 import org.eclipse.jface.text.DefaultInformationControl;
67 import org.eclipse.jface.text.IDocument;
68 import org.eclipse.jface.text.IInformationControl;
69 import org.eclipse.jface.text.IInformationControlCreator;
70 import org.eclipse.jface.text.Position;
71 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
72 import org.eclipse.jface.text.contentassist.IContentAssistant;
73
74 import org.eclipse.ui.IEditorDescriptor;
75 import org.eclipse.ui.IEditorPart;
76 import org.eclipse.ui.IEditorReference;
77 import org.eclipse.ui.IReusableEditor;
78 import org.eclipse.ui.IWorkbenchPage;
79 import org.eclipse.ui.PartInitException;
80 import org.eclipse.ui.PlatformUI;
81 import org.eclipse.ui.actions.GlobalBuildAction;
82 import org.eclipse.ui.contentassist.ContentAssistHandler;
83 import org.eclipse.ui.ide.IDE;
84 import org.eclipse.ui.part.FileEditorInput;
85 import org.eclipse.ui.texteditor.ITextEditor;
86
87 import org.eclipse.search.ui.NewSearchUI;
88 import org.eclipse.search.ui.text.Match;
89
90 import org.eclipse.search.internal.core.text.PatternConstructor;
91 import org.eclipse.search.internal.ui.ISearchHelpContextIds;
92 import org.eclipse.search.internal.ui.Messages;
93 import org.eclipse.search.internal.ui.SearchMessages;
94 import org.eclipse.search.internal.ui.SearchPlugin;
95 import org.eclipse.search.internal.ui.util.ExceptionHandler;
96 import org.eclipse.search.internal.ui.util.ExtendedDialogWindow;
97
98 import org.eclipse.search2.internal.ui.InternalSearchUI;
99 import org.eclipse.search2.internal.ui.text.PositionTracker;
100
101 class ReplaceDialog2 extends ExtendedDialogWindow {
102         
103     private abstract static class ReplaceOperation implements IRunnableWithProgress {
104
105         public void run(IProgressMonitor monitor) throws InvocationTargetException JavaDoc {
106             try {
107                 doReplace(monitor);
108             } catch (BadLocationException e) {
109                 throw new InvocationTargetException JavaDoc(e);
110             } catch (CoreException e) {
111                 throw new InvocationTargetException JavaDoc(e);
112             } catch (IOException JavaDoc e) {
113                 throw new InvocationTargetException JavaDoc(e);
114             }
115         }
116         
117         protected abstract void doReplace(IProgressMonitor pm) throws BadLocationException, CoreException, IOException JavaDoc;
118     }
119     
120     private static final String JavaDoc SETTINGS_GROUP= "ReplaceDialog2"; //$NON-NLS-1$
121
private static final String JavaDoc SETTINGS_REPLACE_WITH= "replace_with"; //$NON-NLS-1$
122

123     // various widget related constants
124
private static final int REPLACE= IDialogConstants.CLIENT_ID + 1;
125     private static final int REPLACE_ALL_IN_FILE= IDialogConstants.CLIENT_ID + 2;
126     private static final int REPLACE_ALL= IDialogConstants.CLIENT_ID + 3;
127     private static final int SKIP= IDialogConstants.CLIENT_ID + 4;
128     private static final int SKIP_FILE= IDialogConstants.CLIENT_ID + 5;
129     private static final int SKIP_ALL= IDialogConstants.CLIENT_ID + 6;
130     
131     // Widgets
132
private Combo fTextField;
133     private Button fReplaceWithRegex;
134     private Button fReplaceButton;
135     private Button fReplaceAllInFileButton;
136     private Button fReplaceAllButton;
137     private Button fSkipButton;
138     private Button fSkipFileButton;
139
140     
141     private List JavaDoc fMarkers;
142     private boolean fSkipReadonly= false;
143     
144     // reuse editors stuff
145
private IReusableEditor fEditor;
146     private FileSearchPage fPage;
147     private ContentAssistHandler fReplaceContentAssistHandler;
148     private Label fStatusLabel;
149
150     private boolean fSaved= false;
151
152     protected ReplaceDialog2(Shell parentShell, IFile[] entries, FileSearchPage page) {
153         super(parentShell);
154         Assert.isNotNull(entries);
155         Assert.isNotNull(page.getInput());
156         fPage= page;
157         fMarkers= new ArrayList JavaDoc();
158         initializeMarkers(entries);
159     }
160     
161     /* (non-Javadoc)
162      * @see org.eclipse.jface.dialogs.Dialog#getDialogBoundsSettings()
163      */

164     protected IDialogSettings getDialogBoundsSettings() {
165         return SearchPlugin.getDefault().getDialogSettingsSection("DialogBounds_ReplaceDialog2"); //$NON-NLS-1$
166
}
167         
168     private FileSearchQuery getQuery() {
169         return (FileSearchQuery) fPage.getInput().getQuery();
170     }
171         
172     private void initializeMarkers(IFile[] entries) {
173         for (int j= 0; j < entries.length; j++) {
174             IFile entry = entries[j];
175             Match[] matches= fPage.getDisplayedMatches(entry);
176             for (int i= 0; i < matches.length; i++) {
177                 fMarkers.add(matches[i]);
178             }
179         }
180     }
181     
182     // widget related stuff -----------------------------------------------------------
183
public void create() {
184         super.create();
185         Shell shell= getShell();
186         shell.setText(getDialogTitle());
187         gotoCurrentMarker();
188         enableButtons();
189         
190         if (!canReplace()) {
191             statusMessage(true, MessageFormat.format(SearchMessages.ReplaceDialog2_nomatches_error, new String JavaDoc[] { getQuery().getSearchString() }));
192         }
193         
194     }
195         
196     public int open() {
197         boolean wasAutobuild = false;
198         try {
199             wasAutobuild= disableAutobuild();
200         } catch (CoreException e) {
201             ExceptionHandler.handle(e, getShell(), getDialogTitle(), SearchMessages.ReplaceDialog2_error_disableAutobuild);
202         }
203         try {
204             return super.open();
205         } finally {
206             if (wasAutobuild)
207                 try {
208                     restoreAutobuild();
209                 } catch (CoreException e1) {
210                     ExceptionHandler.handle(e1, getShell(), getDialogTitle(), SearchMessages.ReplaceDialog2_error_restoreAutobuild);
211                     return CANCEL;
212                 }
213         }
214     }
215
216     private void restoreAutobuild() throws CoreException {
217         // this is only called if autobuild was on before.
218
IWorkspace workspace= ResourcesPlugin.getWorkspace();
219         IWorkspaceDescription description = workspace.getDescription();
220         description.setAutoBuilding(true);
221         workspace.setDescription(description);
222
223         if (fSaved) {
224             new GlobalBuildAction(fPage.getSite().getWorkbenchWindow(), IncrementalProjectBuilder.INCREMENTAL_BUILD).run();
225         }
226     }
227
228     private boolean disableAutobuild() throws CoreException {
229         IWorkspace workspace = ResourcesPlugin.getWorkspace();
230         boolean autobuild = workspace.isAutoBuilding();
231         if (autobuild) {
232             IWorkspaceDescription description = workspace.getDescription();
233             description.setAutoBuilding(false);
234             workspace.setDescription(description);
235         }
236         return autobuild;
237     }
238
239     protected Control createPageArea(Composite parent) {
240         initializeDialogUnits(parent);
241         PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, ISearchHelpContextIds.REPLACE_DIALOG);
242         Composite result= new Composite(parent, SWT.NULL);
243         GridLayout layout= new GridLayout();
244         result.setLayout(layout);
245         layout.numColumns= 2;
246         
247         layout.marginHeight = 0;
248         layout.marginWidth = 0;
249         
250         initializeDialogUnits(result);
251         
252         FileSearchQuery query= getQuery();
253         
254         Label label= new Label(result, SWT.NONE);
255         label.setText(SearchMessages.ReplaceDialog_replace_label);
256         Text clabel= new Text(result, SWT.BORDER | SWT.READ_ONLY);
257         clabel.setText(query.getSearchString());
258         GridData gd= new GridData(GridData.FILL_HORIZONTAL);
259         gd.widthHint= convertWidthInCharsToPixels(50);
260         clabel.setLayoutData(gd);
261         
262         
263         label= new Label(result, SWT.NONE);
264         label.setText(SearchMessages.ReplaceDialog_with_label);
265         fTextField= new Combo(result, SWT.DROP_DOWN);
266         gd= new GridData(GridData.FILL_HORIZONTAL);
267         gd.widthHint= convertWidthInCharsToPixels(50);
268         fTextField.setLayoutData(gd);
269         fTextField.setFocus();
270         
271         IDialogSettings settings= SearchPlugin.getDefault().getDialogSettings().getSection(SETTINGS_GROUP);
272         if (settings != null) {
273             String JavaDoc[] previousReplaceWith= settings.getArray(SETTINGS_REPLACE_WITH);
274             if (previousReplaceWith != null) {
275                 fTextField.setItems(previousReplaceWith);
276                 fTextField.select(0);
277             }
278         }
279         
280         new Label(result, SWT.NONE);
281         fReplaceWithRegex= new Button(result, SWT.CHECK);
282         fReplaceWithRegex.setText(SearchMessages.ReplaceDialog_isRegex_label);
283         fReplaceWithRegex.addSelectionListener(new SelectionAdapter() {
284             public void widgetSelected(SelectionEvent e) {
285                 setContentAssistsEnablement(fReplaceWithRegex.getSelection());
286             }
287         });
288         if (query.isRegexSearch()) {
289             fReplaceWithRegex.setSelection(true);
290         } else {
291             fReplaceWithRegex.setSelection(false);
292             fReplaceWithRegex.setEnabled(false);
293         }
294     
295         
296         fStatusLabel= new Label(result, SWT.NULL);
297         gd= new GridData(GridData.FILL_HORIZONTAL);
298         gd.verticalAlignment= SWT.BOTTOM;
299         gd.horizontalSpan= 2;
300         fStatusLabel.setLayoutData(gd);
301
302         setContentAssistsEnablement(fReplaceWithRegex.getSelection());
303         
304         applyDialogFont(result);
305         return result;
306     }
307     
308     protected Control createButtonBar(Composite parent) {
309         Composite composite= new Composite(parent, SWT.NONE);
310         GridLayout layout= new GridLayout();
311         layout.numColumns= 0; // createActionButton increments
312
layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
313         layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
314         layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
315         layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
316         
317         composite.setLayout(layout);
318         composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
319     
320         fReplaceButton= createActionButton(composite, REPLACE, SearchMessages.ReplaceDialog_replace, true);
321         fReplaceAllInFileButton= createActionButton(composite, REPLACE_ALL_IN_FILE, SearchMessages.ReplaceDialog_replaceAllInFile, false);
322
323         Label filler= new Label(composite, SWT.NONE);
324         filler.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
325         
326         fReplaceAllButton= createActionButton(composite, REPLACE_ALL, SearchMessages.ReplaceDialog_replaceAll, false);
327         fSkipButton= createActionButton(composite, SKIP, SearchMessages.ReplaceDialog_skip, false);
328         fSkipFileButton= createActionButton(composite, SKIP_FILE, SearchMessages.ReplaceDialog_skipFile, false);
329
330         filler= new Label(composite, SWT.NONE);
331         filler.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
332         super.createButtonsForButtonBar(composite); // cancel button
333

334         layout.numColumns= 4; // createActionButton increments
335

336         return composite;
337     }
338         
339     private void enableButtons() {
340         fSkipButton.setEnabled(hasNextMarker());
341         fSkipFileButton.setEnabled(hasNextFile());
342         fReplaceButton.setEnabled(canReplace());
343         fReplaceAllInFileButton.setEnabled(canReplace());
344         fReplaceAllButton.setEnabled(canReplace());
345     }
346     
347     protected void buttonPressed(int buttonId) {
348         if (buttonId == IDialogConstants.CANCEL_ID) {
349             super.buttonPressed(buttonId);
350             return;
351         }
352         
353         
354         final String JavaDoc replaceText= fTextField.getText();
355         statusMessage(false, ""); //$NON-NLS-1$
356
try {
357             switch (buttonId) {
358                 case SKIP :
359                     skip();
360                     break;
361                 case SKIP_FILE :
362                     skipFile();
363                     break;
364                 case REPLACE :
365                     run(new ReplaceOperation() {
366                         protected void doReplace(IProgressMonitor pm) throws BadLocationException, CoreException {
367                             replace(pm, replaceText);
368                         }
369                     }, (IResource) getCurrentMarker().getElement());
370                     gotoCurrentMarker();
371                     break;
372                 case REPLACE_ALL_IN_FILE :
373                     run(new ReplaceOperation() {
374                         protected void doReplace(IProgressMonitor pm) throws BadLocationException, CoreException {
375                             replaceInFile(pm, replaceText);
376                         }
377                     }, (IResource) getCurrentMarker().getElement());
378                     gotoCurrentMarker();
379                     break;
380                 case REPLACE_ALL :
381                     run(new ReplaceOperation() {
382                         protected void doReplace(IProgressMonitor pm) throws BadLocationException, CoreException {
383                             replaceAll(pm, replaceText);
384                         }
385                     }, ResourcesPlugin.getWorkspace().getRoot());
386                     gotoCurrentMarker();
387                     break;
388                 default : {
389                 }
390             }
391         } catch (InvocationTargetException JavaDoc e) {
392             Throwable JavaDoc targetException= e.getTargetException();
393             if (targetException instanceof PatternSyntaxException JavaDoc) {
394                 String JavaDoc format= SearchMessages.ReplaceDialog2_regexError_format;
395                 String JavaDoc message= MessageFormat.format(format, new Object JavaDoc[] { targetException.getLocalizedMessage() });
396                 statusMessage(true, message);
397             } else {
398                 String JavaDoc message= Messages.format(SearchMessages.ReplaceDialog_error_unable_to_replace, ((IFile)getCurrentMarker().getElement()).getName());
399                 ExceptionHandler.handle(e, getParentShell(), getDialogTitle(), message);
400             }
401         } catch (InterruptedException JavaDoc e) {
402             // means operation canceled
403
} finally {
404             if (!canReplace())
405                 close();
406             else {
407                 enableButtons();
408             }
409         }
410     }
411     
412     private void run(ReplaceOperation operation, IResource resource) throws InvocationTargetException JavaDoc, InterruptedException JavaDoc {
413         IResourceRuleFactory ruleFactory = ResourcesPlugin.getWorkspace().getRuleFactory();
414         ISchedulingRule rule= ruleFactory.modifyRule(resource);
415         
416         PlatformUI.getWorkbench().getProgressService().runInUI(this, operation, rule);
417     }
418     
419     private Match getCurrentMarker() {
420         return (Match)fMarkers.get(0);
421     }
422     
423     private void replace(IProgressMonitor pm, String JavaDoc replacementText) throws BadLocationException, CoreException {
424         Match marker= getCurrentMarker();
425         pm.beginTask(SearchMessages.ReplaceDialog_task_replace, 10);
426         replaceInFile(pm, (IFile) marker.getElement(), replacementText, new Match[]{marker});
427     }
428     
429     private void replaceInFile(IProgressMonitor pm, String JavaDoc replacementText) throws BadLocationException, CoreException {
430         Match firstMarker= getCurrentMarker();
431         Match[] markers= collectMarkers((IFile)firstMarker.getElement());
432         pm.beginTask(Messages.format(SearchMessages.ReplaceDialog_task_replaceInFile, ((IFile)firstMarker.getElement()).getFullPath().toOSString()), 4);
433         replaceInFile(pm, (IFile) firstMarker.getElement(), replacementText, markers);
434     }
435     
436     private void replaceAll(IProgressMonitor pm, String JavaDoc replacementText) throws BadLocationException, CoreException {
437         int resourceCount= countResources();
438         pm.beginTask(SearchMessages.ReplaceDialog_task_replace_replaceAll, resourceCount);
439         try {
440             while (fMarkers.size() > 0) {
441                 replaceInFile(new SubProgressMonitor(pm, 1, 0), replacementText);
442             }
443         } finally {
444             pm.done();
445         }
446     }
447     
448     private void replaceInFile(final IProgressMonitor pm, final IFile file, final String JavaDoc replacementText, final Match[] markers) throws BadLocationException, CoreException {
449         if (pm.isCanceled())
450             throw new OperationCanceledException();
451         doReplaceInFile(pm, file, replacementText, markers);
452     }
453     
454     private void doReplaceInFile(IProgressMonitor pm, IFile file, String JavaDoc replacementText, final Match[] markers) throws BadLocationException, CoreException {
455         Pattern JavaDoc pattern= null;
456         FileSearchQuery query= getQuery();
457         if (query.isRegexSearch()) {
458             pattern= createReplacePattern(query);
459         }
460         try {
461             if (file.isReadOnly()) {
462                 if (fSkipReadonly) {
463                     skipFile();
464                     return;
465                 }
466                 int rc= askForSkip(file);
467                 switch (rc) {
468                     case CANCEL :
469                         throw new OperationCanceledException();
470                     case SKIP_FILE :
471                         skipFile();
472                         return;
473                     case SKIP_ALL :
474                         fSkipReadonly= true;
475                         skipFile();
476                         return;
477                 }
478             }
479             ITextFileBufferManager bm= FileBuffers.getTextFileBufferManager();
480             try {
481                 bm.connect(file.getFullPath(), LocationKind.IFILE, new SubProgressMonitor(pm, 1));
482                 ITextFileBuffer fb= bm.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE);
483                 boolean wasDirty= fb.isDirty();
484                 IDocument doc= fb.getDocument();
485                 for (int i= 0; i < markers.length; i++) {
486                     PositionTracker tracker= InternalSearchUI.getInstance().getPositionTracker();
487                     Match match= markers[i];
488                     int offset= match.getOffset();
489                     int length= match.getLength();
490                     Position currentPosition= tracker.getCurrentPosition(match);
491                     if (currentPosition != null) {
492                         offset= currentPosition.offset;
493                         length= currentPosition.length;
494                     }
495                     String JavaDoc originalText= doc.get(offset, length);
496                     String JavaDoc replacementString= computeReplacementString(pattern, originalText, replacementText);
497                     doc.replace(offset, length, replacementString);
498                     fMarkers.remove(match);
499                     fPage.getInput().removeMatch(match);
500                 }
501                 if (!wasDirty) {
502                     fb.commit(new SubProgressMonitor(pm, 1), true);
503                     fSaved= true;
504                 }
505             } finally {
506                 bm.disconnect(file.getFullPath(), LocationKind.IFILE, new SubProgressMonitor(pm, 1));
507             }
508         } finally {
509             pm.done();
510         }
511     }
512     
513     private Pattern JavaDoc createReplacePattern(FileSearchQuery query) {
514         return PatternConstructor.createPattern(query.getSearchString(), true, true, query.isCaseSensitive(), false);
515     }
516
517     private String JavaDoc computeReplacementString(Pattern JavaDoc pattern, String JavaDoc originalText, String JavaDoc replacementText) {
518         if (pattern != null) {
519             try {
520                 return pattern.matcher(originalText).replaceFirst(replacementText);
521             } catch (IndexOutOfBoundsException JavaDoc ex) {
522                 throw new PatternSyntaxException JavaDoc(ex.getLocalizedMessage(), replacementText, -1);
523             }
524         }
525         return replacementText;
526     }
527
528     private int askForSkip(final IFile file) {
529         
530         String JavaDoc message= Messages.format(SearchMessages.ReadOnlyDialog_message, file.getFullPath().toOSString());
531         String JavaDoc[] buttonLabels= null;
532         boolean showSkip= countResources() > 1;
533         if (showSkip) {
534             String JavaDoc skipLabel= SearchMessages.ReadOnlyDialog_skipFile;
535             String JavaDoc skipAllLabel= SearchMessages.ReadOnlyDialog_skipAll;
536             buttonLabels= new String JavaDoc[]{skipLabel, skipAllLabel, IDialogConstants.CANCEL_LABEL};
537         } else {
538             buttonLabels= new String JavaDoc[]{IDialogConstants.CANCEL_LABEL};
539             
540         }
541         
542         MessageDialog msd= new MessageDialog(getShell(), getShell().getText(), null, message, MessageDialog.ERROR, buttonLabels, 0);
543         int rc= msd.open();
544         switch (rc) {
545             case 0 :
546                 return showSkip ? SKIP_FILE : CANCEL;
547             case 1 :
548                 return SKIP_ALL;
549             default :
550                 return CANCEL;
551         }
552     }
553         
554     private String JavaDoc getDialogTitle() {
555         return SearchMessages.ReplaceDialog_dialog_title;
556     }
557     
558     private void skip() {
559         fMarkers.remove(0);
560         Assert.isTrue(fMarkers.size() > 0);
561         gotoCurrentMarker();
562     }
563     
564     private void skipFile() {
565         Match currentMarker= getCurrentMarker();
566         if (currentMarker == null)
567             return;
568         IResource currentFile= (IResource) currentMarker.getElement();
569         while (fMarkers.size() > 0 && getCurrentMarker().getElement().equals(currentFile))
570             fMarkers.remove(0);
571         gotoCurrentMarker();
572     }
573     
574     private void gotoCurrentMarker() {
575         if (fMarkers.size() > 0) {
576             Match marker= getCurrentMarker();
577             Control focusControl= getShell().getDisplay().getFocusControl();
578             try {
579                 selectEntry(marker);
580                 ITextEditor editor= null;
581                 if (NewSearchUI.reuseEditor())
582                     editor= openEditorReuse(marker);
583                 else
584                     editor= openEditorNoReuse(marker);
585                 Position p= InternalSearchUI.getInstance().getPositionTracker().getCurrentPosition(marker);
586                 if (p != null)
587                     editor.selectAndReveal(p.getOffset(), p.getLength());
588                 else
589                 editor.selectAndReveal(marker.getOffset(), marker.getLength());
590                 if (focusControl != null && !focusControl.isDisposed())
591                     focusControl.setFocus();
592             } catch (PartInitException e) {
593                 String JavaDoc message= Messages.format(SearchMessages.ReplaceDialog_error_unable_to_open_text_editor, ((IFile)marker.getElement()).getName());
594                 MessageDialog.openError(getParentShell(), getDialogTitle(), message);
595             }
596         }
597     }
598     
599     private void selectEntry(Match marker) {
600         ISelection sel= fPage.getViewer().getSelection();
601         if (!(sel instanceof IStructuredSelection))
602             return;
603         IStructuredSelection ss= (IStructuredSelection) sel;
604         IFile file= (IFile) marker.getElement();
605         if (ss.size() == 1 && file.equals(ss.getFirstElement()))
606             return;
607         fPage.getViewer().setSelection(new StructuredSelection(marker.getElement()));
608     }
609
610     // opening editors ------------------------------------------
611
private ITextEditor openEditorNoReuse(Match marker) throws PartInitException {
612         IFile file= (IFile) marker.getElement();
613         IWorkbenchPage activePage= SearchPlugin.getActivePage();
614         if (activePage == null)
615             return null;
616         ITextEditor textEditor= showOpenTextEditor(activePage, file);
617         if (textEditor != null)
618             return textEditor;
619         return openNewTextEditor(file, activePage);
620     }
621     
622     private ITextEditor openNewTextEditor(IFile file, IWorkbenchPage activePage) throws PartInitException {
623         IEditorDescriptor desc= IDE.getDefaultEditor(file);
624         if (desc != null) {
625             String JavaDoc editorID= desc.getId();
626             IEditorPart editor;
627             if (desc.isInternal()) {
628                 editor= activePage.openEditor(new FileEditorInput(file), editorID);
629                 if (editor instanceof ITextEditor) {
630                     if (editor instanceof IReusableEditor)
631                         fEditor= (IReusableEditor) editor;
632                     return (ITextEditor)editor;
633                 }
634                 activePage.closeEditor(editor, false);
635             }
636         }
637         IEditorPart editor= activePage.openEditor(new FileEditorInput(file), "org.eclipse.ui.DefaultTextEditor"); //$NON-NLS-1$
638
return (ITextEditor)editor;
639     }
640
641     private ITextEditor openEditorReuse(Match marker) throws PartInitException {
642         IWorkbenchPage page= SearchPlugin.getActivePage();
643         IFile file= (IFile) marker.getElement();
644         if (page == null)
645             return null;
646
647         ITextEditor textEditor= showOpenTextEditor(page, file);
648         if (textEditor != null)
649             return textEditor;
650
651         String JavaDoc editorId= null;
652         IEditorDescriptor desc= IDE.getDefaultEditor(file);
653         if (desc != null && desc.isInternal())
654             editorId= desc.getId();
655
656         boolean isOpen= isEditorOpen(page, fEditor);
657
658         boolean canBeReused= isOpen && !fEditor.isDirty() && !isPinned(fEditor);
659         boolean showsSameInputType= fEditor != null && (editorId == null || fEditor.getSite().getId().equals(editorId));
660
661         if (canBeReused) {
662             if (showsSameInputType) {
663                 fEditor.setInput(new FileEditorInput(file));
664                 page.bringToTop(fEditor);
665                 return (ITextEditor) fEditor;
666             }
667             page.closeEditor(fEditor, false);
668             fEditor= null;
669         }
670         return openNewTextEditor(file, page);
671     }
672
673     private boolean isEditorOpen(IWorkbenchPage page, IEditorPart editor) {
674         if (editor != null) {
675             IEditorReference[] parts= page.getEditorReferences();
676             int i= 0;
677             for (int j = 0; j < parts.length; j++) {
678                 if (editor == parts[i++].getEditor(false))
679                     return true;
680             }
681         }
682         return false;
683     }
684
685     private ITextEditor showOpenTextEditor(IWorkbenchPage page, IFile file) {
686         IEditorPart editor= page.findEditor(new FileEditorInput(file));
687         if (editor instanceof ITextEditor) {
688             page.bringToTop(editor);
689             return (ITextEditor) editor;
690         }
691         return null;
692     }
693
694     private boolean isPinned(IEditorPart editor) {
695         if (editor == null)
696             return false;
697         
698         IEditorReference[] editorRefs= editor.getEditorSite().getPage().getEditorReferences();
699         int i= 0;
700         while (i < editorRefs.length) {
701             if (editor.equals(editorRefs[i].getEditor(false)))
702                 return editorRefs[i].isPinned();
703             i++;
704         }
705         return false;
706     }
707     
708     // resource related -------------------------------------------------------------
709
/**
710      * @return the number of resources referred to in fMarkers
711      */

712     private int countResources() {
713         IResource r= null;
714         int count= 0;
715         for (Iterator JavaDoc elements= fMarkers.iterator(); elements.hasNext(); ) {
716             Match element= (Match)elements.next();
717             if (!element.getElement().equals(r)) {
718                 count++;
719                 r= (IResource) element.getElement();
720             }
721         }
722         return count;
723     }
724     
725     private Match[] collectMarkers(IFile resource) {
726         List JavaDoc matching= new ArrayList JavaDoc();
727         for (int i= 0; i < fMarkers.size(); i++) {
728             Match marker= (Match)fMarkers.get(i);
729             if (!resource.equals(marker.getElement()))
730                 break;
731             matching.add(marker);
732         }
733         Match[] markers= new Match[matching.size()];
734         return (Match[])matching.toArray(markers);
735     }
736     
737     
738     // some queries -------------------------------------------------------------
739
private boolean hasNextMarker() {
740         return fMarkers.size() > 1;
741     }
742     
743     private boolean hasNextFile() {
744         if (!hasNextMarker())
745             return false;
746         IResource currentFile= (IResource) getCurrentMarker().getElement();
747         for (int i= 0; i < fMarkers.size(); i++) {
748             if (!((Match)fMarkers.get(i)).getElement().equals(currentFile))
749                 return true;
750         }
751         return false;
752     }
753     
754     private boolean canReplace() {
755         return fMarkers.size() > 0;
756     }
757     
758     public static SubjectControlContentAssistant createContentAssistant(boolean isFind) {
759         final SubjectControlContentAssistant contentAssistant= new SubjectControlContentAssistant();
760         
761         contentAssistant.setRestoreCompletionProposalSize(SearchPlugin.getDefault().getDialogSettings());
762         
763         IContentAssistProcessor processor= new RegExContentAssistProcessor(isFind);
764         contentAssistant.setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE);
765         
766         contentAssistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
767         contentAssistant.setInformationControlCreator(new IInformationControlCreator() {
768             /*
769              * @see org.eclipse.jface.text.IInformationControlCreator#createInformationControl(org.eclipse.swt.widgets.Shell)
770              */

771             public IInformationControl createInformationControl(Shell parent) {
772                 return new DefaultInformationControl(parent);
773             }});
774         
775         return contentAssistant;
776     }
777     
778     private void setContentAssistsEnablement(boolean enable) {
779         if (enable) {
780             if (fReplaceContentAssistHandler == null) {
781                 fReplaceContentAssistHandler= ContentAssistHandler.createHandlerForCombo(fTextField, createContentAssistant(false));
782             }
783             fReplaceContentAssistHandler.setEnabled(true);
784             
785         } else {
786             if (fReplaceContentAssistHandler == null)
787                 return;
788             fReplaceContentAssistHandler.setEnabled(false);
789         }
790     }
791
792     private void statusMessage(boolean error, String JavaDoc message) {
793         fStatusLabel.setText(message);
794     
795         if (error)
796             fStatusLabel.setForeground(JFaceColors.getErrorText(fStatusLabel.getDisplay()));
797         else
798             fStatusLabel.setForeground(null);
799     
800         if (error)
801             getShell().getDisplay().beep();
802     }
803     
804     
805     /* (non-Javadoc)
806      * @see org.eclipse.jface.dialogs.Dialog#close()
807      */

808     public boolean close() {
809         String JavaDoc[] items= fTextField.getItems();
810         ArrayList JavaDoc history= new ArrayList JavaDoc();
811         history.add(fTextField.getText());
812         int historySize= Math.min(items.length, 6);
813         for (int i= 0; i < historySize; i++) {
814             String JavaDoc curr= items[i];
815             if (!history.contains(curr)) {
816                 history.add(curr);
817             }
818         }
819         IDialogSettings settings= SearchPlugin.getDefault().getDialogSettings().addNewSection(SETTINGS_GROUP);
820         settings.put(SETTINGS_REPLACE_WITH, (String JavaDoc[]) history.toArray(new String JavaDoc[history.size()]));
821         return super.close();
822     }
823
824
825 }
826
Popular Tags