KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*******************************************************************************
2  * Copyright (c) 2000, 2004 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Common Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/cpl-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 java.util.ArrayList JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.List JavaDoc;
18
19 import org.eclipse.core.resources.IFile;
20 import org.eclipse.core.resources.IMarker;
21 import org.eclipse.core.resources.IResource;
22 import org.eclipse.core.runtime.CoreException;
23 import org.eclipse.core.runtime.IProgressMonitor;
24 import org.eclipse.core.runtime.OperationCanceledException;
25 import org.eclipse.core.runtime.SubProgressMonitor;
26
27 import org.eclipse.swt.SWT;
28 import org.eclipse.swt.graphics.Point;
29 import org.eclipse.swt.layout.GridData;
30 import org.eclipse.swt.layout.GridLayout;
31 import org.eclipse.swt.widgets.Button;
32 import org.eclipse.swt.widgets.Composite;
33 import org.eclipse.swt.widgets.Control;
34 import org.eclipse.swt.widgets.Label;
35 import org.eclipse.swt.widgets.Shell;
36 import org.eclipse.swt.widgets.Table;
37 import org.eclipse.swt.widgets.Text;
38
39 import org.eclipse.core.filebuffers.FileBuffers;
40 import org.eclipse.core.filebuffers.ITextFileBuffer;
41 import org.eclipse.core.filebuffers.ITextFileBufferManager;
42
43 import org.eclipse.jface.dialogs.IDialogConstants;
44 import org.eclipse.jface.dialogs.MessageDialog;
45 import org.eclipse.jface.util.Assert;
46 import org.eclipse.jface.viewers.ISelection;
47 import org.eclipse.jface.viewers.IStructuredSelection;
48 import org.eclipse.jface.viewers.StructuredSelection;
49
50 import org.eclipse.jface.text.BadLocationException;
51 import org.eclipse.jface.text.IDocument;
52 import org.eclipse.jface.text.Position;
53
54 import org.eclipse.ui.IEditorDescriptor;
55 import org.eclipse.ui.IEditorPart;
56 import org.eclipse.ui.IEditorReference;
57 import org.eclipse.ui.IReusableEditor;
58 import org.eclipse.ui.IWorkbenchPage;
59 import org.eclipse.ui.PartInitException;
60 import org.eclipse.ui.actions.WorkspaceModifyOperation;
61 import org.eclipse.ui.ide.IDE;
62 import org.eclipse.ui.part.FileEditorInput;
63 import org.eclipse.ui.texteditor.ITextEditor;
64 import org.eclipse.ui.texteditor.MarkerUtilities;
65
66 import org.eclipse.search.ui.SearchUI;
67
68 import org.eclipse.search.internal.ui.SearchMessages;
69 import org.eclipse.search.internal.ui.SearchPlugin;
70 import org.eclipse.search.internal.ui.SearchResultView;
71 import org.eclipse.search.internal.ui.SearchResultViewEntry;
72 import org.eclipse.search.internal.ui.SearchResultViewer;
73 import org.eclipse.search.internal.ui.util.ExtendedDialogWindow;
74
75 class ReplaceDialog extends ExtendedDialogWindow {
76         
77     /**
78      * A class wrapping a resource marker, adding a position.
79      */

80     private static class ReplaceMarker {
81         private Position fPosition;
82         private IMarker fMarker;
83         
84         ReplaceMarker(IMarker marker) {
85             fMarker= marker;
86         }
87         
88         public IFile getFile() {
89             return (IFile)fMarker.getResource();
90         }
91         
92         public void deletePosition(IDocument doc) {
93             if (fPosition != null) {
94                 MarkerUtilities.setCharStart(fMarker, fPosition.getOffset());
95                 MarkerUtilities.setCharEnd(fMarker, fPosition.getOffset()+fPosition.getLength());
96                 doc.removePosition(fPosition);
97                 fPosition= null;
98             }
99         }
100         
101         public void delete() throws CoreException {
102             fMarker.delete();
103         }
104         
105         public void createPosition(IDocument doc) throws BadLocationException {
106             if (fPosition == null) {
107                 int charStart= MarkerUtilities.getCharStart(fMarker);
108                 fPosition= new Position(charStart, MarkerUtilities.getCharEnd(fMarker)-charStart);
109                 doc.addPosition(fPosition);
110             }
111         }
112         
113         public int getLength() {
114             if (fPosition != null)
115                 return fPosition.getLength();
116             return MarkerUtilities.getCharEnd(fMarker)-MarkerUtilities.getCharStart(fMarker);
117         }
118         
119         public int getOffset() {
120             if (fPosition != null)
121                 return fPosition.getOffset();
122             return MarkerUtilities.getCharStart(fMarker);
123         }
124     }
125     
126     private abstract static class ReplaceOperation extends WorkspaceModifyOperation {
127         public void execute(IProgressMonitor monitor) throws InvocationTargetException JavaDoc {
128             try {
129                 doReplace(monitor);
130             } catch (BadLocationException e) {
131                 throw new InvocationTargetException JavaDoc(e);
132             } catch (CoreException e) {
133                 throw new InvocationTargetException JavaDoc(e);
134             } catch (IOException JavaDoc e) {
135                 throw new InvocationTargetException JavaDoc(e);
136             }
137         }
138         
139         protected abstract void doReplace(IProgressMonitor pm) throws BadLocationException, CoreException, IOException JavaDoc;
140     }
141         
142     // various widget related constants
143
private static final int REPLACE= IDialogConstants.CLIENT_ID + 1;
144     private static final int REPLACE_ALL_IN_FILE= IDialogConstants.CLIENT_ID + 2;
145     private static final int REPLACE_ALL= IDialogConstants.CLIENT_ID + 3;
146     private static final int SKIP= IDialogConstants.CLIENT_ID + 4;
147     private static final int SKIP_FILE= IDialogConstants.CLIENT_ID + 5;
148     private static final int SKIP_ALL= IDialogConstants.CLIENT_ID + 6;
149     
150     // Widgets
151
private Text fTextField;
152     private Button fReplaceButton;
153     private Button fReplaceAllInFileButton;
154     private Button fReplaceAllButton;
155     private Button fSkipButton;
156     private Button fSkipFileButton;
157     
158     private List JavaDoc fMarkers;
159     private TextSearchOperation fOperation;
160     private boolean fSkipReadonly= false;
161     
162     // reuse editors stuff
163
private IReusableEditor fEditor;
164     
165     protected ReplaceDialog(Shell parentShell, List JavaDoc entries, TextSearchOperation operation) {
166         super(parentShell);
167         Assert.isNotNull(entries);
168         Assert.isNotNull(operation);
169         fMarkers= new ArrayList JavaDoc();
170         initializeMarkers(entries);
171         fOperation= operation;
172     }
173     
174     private void initializeMarkers(List JavaDoc entries) {
175         for (Iterator JavaDoc elements= entries.iterator(); elements.hasNext(); ) {
176             SearchResultViewEntry element= (SearchResultViewEntry)elements.next();
177             List JavaDoc markerList= element.getMarkers();
178             for (Iterator JavaDoc markers= markerList.iterator(); markers.hasNext(); ) {
179                 IMarker marker= (IMarker)markers.next();
180                 int charStart= MarkerUtilities.getCharStart(marker);
181                 if (charStart >= 0 && MarkerUtilities.getCharEnd(marker) > charStart)
182                     fMarkers.add(new ReplaceMarker(marker));
183             }
184         }
185     }
186     
187     // widget related stuff -----------------------------------------------------------
188
public void create() {
189         super.create();
190         Shell shell= getShell();
191         shell.setText(getDialogTitle());
192         gotoCurrentMarker();
193         enableButtons();
194     }
195         
196     protected Control createPageArea(Composite parent) {
197         Composite result= new Composite(parent, SWT.NULL);
198         GridLayout layout= new GridLayout();
199         result.setLayout(layout);
200         layout.numColumns= 2;
201         
202         layout.marginHeight =
203             convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
204         layout.marginWidth =
205             convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
206         layout.verticalSpacing =
207             convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
208         layout.horizontalSpacing =
209             convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
210         
211         initializeDialogUnits(result);
212         
213         Label label= new Label(result, SWT.NONE);
214         label.setText(SearchMessages.getString("ReplaceDialog.replace_label")); //$NON-NLS-1$
215
Text clabel= new Text(result, SWT.BORDER);
216         clabel.setEnabled(false);
217         clabel.setText(fOperation.getPattern());
218         GridData gd= new GridData(GridData.FILL_HORIZONTAL);
219         gd.widthHint= convertWidthInCharsToPixels(50);
220         clabel.setLayoutData(gd);
221         
222         
223         label= new Label(result, SWT.NONE);
224         label.setText(SearchMessages.getString("ReplaceDialog.with_label")); //$NON-NLS-1$
225
fTextField= new Text(result, SWT.BORDER);
226         gd= new GridData(GridData.FILL_HORIZONTAL);
227         gd.widthHint= convertWidthInCharsToPixels(50);
228         fTextField.setLayoutData(gd);
229         fTextField.setFocus();
230         
231         
232         new Label(result, SWT.NONE);
233         Button replaceWithRegex= new Button(result, SWT.CHECK);
234         replaceWithRegex.setText(SearchMessages.getString("ReplaceDialog.isRegex.label")); //$NON-NLS-1$
235
replaceWithRegex.setEnabled(false);
236         replaceWithRegex.setSelection(false);
237         
238         applyDialogFont(result);
239         return result;
240     }
241     
242     protected void createButtonsForButtonBar(Composite parent) {
243         fReplaceButton= createButton(parent, REPLACE, SearchMessages.getString("ReplaceDialog.replace"), true); //$NON-NLS-1$
244
fReplaceAllInFileButton= createButton(parent, REPLACE_ALL_IN_FILE, SearchMessages.getString("ReplaceDialog.replaceAllInFile"), false); //$NON-NLS-1$
245

246         Label filler= new Label(parent, SWT.NONE);
247         filler.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
248         
249         fReplaceAllButton= createButton(parent, REPLACE_ALL, SearchMessages.getString("ReplaceDialog.replaceAll"), false); //$NON-NLS-1$
250
fSkipButton= createButton(parent, SKIP, SearchMessages.getString("ReplaceDialog.skip"), false); //$NON-NLS-1$
251
fSkipFileButton= createButton(parent, SKIP_FILE, SearchMessages.getString("ReplaceDialog.skipFile"), false); //$NON-NLS-1$
252

253         filler= new Label(parent, SWT.NONE);
254         filler.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
255         super.createButtonsForButtonBar(parent);
256         ((GridLayout)parent.getLayout()).numColumns= 4;
257     }
258     
259     protected Point getInitialLocation(Point initialSize) {
260         SearchResultView view= (SearchResultView)SearchPlugin.getSearchResultView();
261         if (view == null)
262             return super.getInitialLocation(initialSize);
263         Point result= new Point(0, 0);
264         Control control= view.getViewer().getControl();
265         Point size= control.getSize();
266         Point location= control.toDisplay(control.getLocation());
267         result.x= Math.max(0, location.x + size.x - initialSize.x);
268         result.y= Math.max(0, location.y + size.y - initialSize.y);
269         return result;
270     }
271     
272     private void enableButtons() {
273         fSkipButton.setEnabled(hasNextMarker());
274         fSkipFileButton.setEnabled(hasNextFile());
275         fReplaceButton.setEnabled(canReplace());
276         fReplaceAllInFileButton.setEnabled(canReplace());
277         fReplaceAllButton.setEnabled(canReplace());
278     }
279     
280     protected void buttonPressed(int buttonId) {
281         final String JavaDoc replaceText= fTextField.getText();
282         try {
283             switch (buttonId) {
284                 case SKIP :
285                     skip();
286                     break;
287                 case SKIP_FILE :
288                     skipFile();
289                     break;
290                 case REPLACE :
291                     run(false, true, new ReplaceOperation() {
292                     protected void doReplace(IProgressMonitor pm) throws BadLocationException, CoreException {
293                         replace(pm, replaceText);
294                     }
295                 });
296                     gotoCurrentMarker();
297                     break;
298                 case REPLACE_ALL_IN_FILE :
299                     run(false, true, new ReplaceOperation() {
300                     protected void doReplace(IProgressMonitor pm) throws BadLocationException, CoreException {
301                         replaceInFile(pm, replaceText);
302                         
303                     }
304                 });
305                     gotoCurrentMarker();
306                     break;
307                 case REPLACE_ALL :
308                     run(false, true, new ReplaceOperation() {
309                     protected void doReplace(IProgressMonitor pm) throws BadLocationException, CoreException {
310                         replaceAll(pm, replaceText);
311                     }
312                 });
313                     gotoCurrentMarker();
314                     break;
315                 default :
316                     {
317                     super.buttonPressed(buttonId);
318                     return;
319                 }
320             }
321         } catch (InvocationTargetException JavaDoc e) {
322             SearchPlugin.log(e);
323             String JavaDoc message= SearchMessages.getFormattedString("ReplaceDialog.error.unable_to_replace", getCurrentMarker().getFile().getName()); //$NON-NLS-1$
324
MessageDialog.openError(getParentShell(), getDialogTitle(), message);
325         } catch (InterruptedException JavaDoc e) {
326             // means operation canceled
327
}
328         if (!hasNextMarker() && !hasNextFile() && !canReplace())
329             close();
330         else {
331             enableButtons();
332         }
333     }
334     
335     private ReplaceMarker getCurrentMarker() {
336         return (ReplaceMarker)fMarkers.get(0);
337     }
338     
339     private void replace(IProgressMonitor pm, String JavaDoc replacementText) throws BadLocationException, CoreException {
340         ReplaceMarker marker= getCurrentMarker();
341         pm.beginTask(SearchMessages.getString("ReplaceDialog.task.replace"), 10); //$NON-NLS-1$
342
replaceInFile(pm, marker.getFile(), replacementText, new ReplaceMarker[]{marker});
343     }
344     
345     private void replaceInFile(IProgressMonitor pm, String JavaDoc replacementText) throws BadLocationException, CoreException {
346         ReplaceMarker firstMarker= getCurrentMarker();
347         ReplaceMarker[] markers= collectMarkers(firstMarker.getFile());
348         pm.beginTask(SearchMessages.getFormattedString("ReplaceDialog.task.replaceInFile", firstMarker.getFile().getFullPath().toOSString()), 4); //$NON-NLS-1$
349
replaceInFile(pm, firstMarker.getFile(), replacementText, markers);
350     }
351     
352     private void replaceAll(IProgressMonitor pm, String JavaDoc replacementText) throws BadLocationException, CoreException {
353         int resourceCount= countResources();
354         pm.beginTask(SearchMessages.getString("ReplaceDialog.task.replace.replaceAll"), resourceCount); //$NON-NLS-1$
355
while (fMarkers.size() > 0) {
356             replaceInFile(new SubProgressMonitor(pm, 1, 0), replacementText);
357         }
358         pm.done();
359     }
360     
361     private void replaceInFile(final IProgressMonitor pm, final IFile file, final String JavaDoc replacementText, final ReplaceMarker[] markers) throws BadLocationException, CoreException {
362         if (pm.isCanceled())
363             throw new OperationCanceledException();
364         doReplaceInFile(pm, file, replacementText, markers);
365     }
366     
367     private void doReplaceInFile(IProgressMonitor pm, IFile file, String JavaDoc replacementText, final ReplaceMarker[] markers) throws BadLocationException, CoreException {
368         try {
369             if (file.isReadOnly()) {
370                 file.getWorkspace().validateEdit(new IFile[]{file}, null);
371             }
372             if (file.isReadOnly()) {
373                 if (fSkipReadonly) {
374                     skipFile();
375                     return;
376                 }
377                 int rc= askForSkip(file);
378                 switch (rc) {
379                     case CANCEL :
380                         throw new OperationCanceledException();
381                     case SKIP_FILE :
382                         skipFile();
383                         return;
384                     case SKIP_ALL :
385                         fSkipReadonly= true;
386                         skipFile();
387                         return;
388                 }
389             }
390             ITextFileBufferManager bm= FileBuffers.getTextFileBufferManager();
391             try {
392                 bm.connect(file.getFullPath(), new SubProgressMonitor(pm, 1));
393                 ITextFileBuffer fb= bm.getTextFileBuffer(file.getFullPath());
394                 boolean wasDirty= fb.isDirty();
395                 IDocument doc= fb.getDocument();
396                 try {
397                     createPositionsInFile(file, doc);
398                     for (int i= 0; i < markers.length; i++) {
399                         doc.replace(markers[i].getOffset(), markers[i].getLength(), replacementText);
400                         fMarkers.remove(0);
401                         markers[i].delete();
402                     }
403                 } finally {
404                     removePositonsInFile(file, doc);
405                 }
406                 if (!wasDirty)
407                     fb.commit(new SubProgressMonitor(pm, 1), true);
408             } finally {
409                 bm.disconnect(file.getFullPath(), new SubProgressMonitor(pm, 1));
410             }
411         } finally {
412             pm.done();
413         }
414     }
415     
416     private void removePositonsInFile(IFile file, IDocument doc) {
417         for (Iterator JavaDoc markers= fMarkers.iterator(); markers.hasNext(); ) {
418             ReplaceMarker marker= (ReplaceMarker)markers.next();
419             if (!marker.getFile().equals(file))
420                 return;
421             marker.deletePosition(doc);
422         }
423     }
424     
425     private void createPositionsInFile(IFile file, IDocument doc) throws BadLocationException {
426         for (Iterator JavaDoc markers= fMarkers.iterator(); markers.hasNext(); ) {
427             ReplaceMarker marker= (ReplaceMarker)markers.next();
428             if (!marker.getFile().equals(file))
429                 return;
430             marker.createPosition(doc);
431         }
432     }
433     
434     private int askForSkip(final IFile file) {
435         
436         String JavaDoc message= SearchMessages.getFormattedString("ReadOnlyDialog.message", file.getFullPath().toOSString()); //$NON-NLS-1$
437
String JavaDoc[] buttonLabels= null;
438         boolean showSkip= countResources() > 1;
439         if (showSkip) {
440             String JavaDoc skipLabel= SearchMessages.getString("ReadOnlyDialog.skipFile"); //$NON-NLS-1$
441
String JavaDoc skipAllLabel= SearchMessages.getString("ReadOnlyDialog.skipAll"); //$NON-NLS-1$
442
buttonLabels= new String JavaDoc[]{skipLabel, skipAllLabel, IDialogConstants.CANCEL_LABEL};
443         } else {
444             buttonLabels= new String JavaDoc[]{IDialogConstants.CANCEL_LABEL};
445             
446         }
447         
448         MessageDialog msd= new MessageDialog(getShell(), getShell().getText(), null, message, MessageDialog.ERROR, buttonLabels, 0);
449         int rc= msd.open();
450         switch (rc) {
451             case 0 :
452                 return showSkip ? SKIP_FILE : CANCEL;
453             case 1 :
454                 return SKIP_ALL;
455             default :
456                 return CANCEL;
457         }
458     }
459         
460     private String JavaDoc getDialogTitle() {
461         return SearchMessages.getString("ReplaceDialog.dialog.title"); //$NON-NLS-1$
462
}
463     
464     private void skip() {
465         fMarkers.remove(0);
466         Assert.isTrue(fMarkers.size() > 0);
467         gotoCurrentMarker();
468     }
469     
470     private void skipFile() {
471         ReplaceMarker currentMarker= getCurrentMarker();
472         if (currentMarker == null)
473             return;
474         IResource currentFile= currentMarker.getFile();
475         while (fMarkers.size() > 0 && getCurrentMarker().getFile().equals(currentFile))
476             fMarkers.remove(0);
477         gotoCurrentMarker();
478     }
479     
480     private void gotoCurrentMarker() {
481         if (fMarkers.size() > 0) {
482             ReplaceMarker marker= getCurrentMarker();
483             Control focusControl= getShell().getDisplay().getFocusControl();
484             try {
485                 selectEntry(marker);
486                 ITextEditor editor= null;
487                 if (SearchUI.reuseEditor())
488                     editor= openEditorReuse(marker);
489                 else
490                     editor= openEditorNoReuse(marker);
491                 editor.selectAndReveal(marker.getOffset(), marker.getLength());
492                 if (focusControl != null && !focusControl.isDisposed())
493                     focusControl.setFocus();
494             } catch (PartInitException e) {
495                 String JavaDoc message= SearchMessages.getFormattedString("ReplaceDialog.error.unable_to_open_text_editor", marker.getFile().getName()); //$NON-NLS-1$
496
MessageDialog.openError(getParentShell(), getDialogTitle(), message);
497             }
498         }
499     }
500     
501     private void selectEntry(ReplaceMarker marker) {
502         SearchResultView view= (SearchResultView) SearchPlugin.getSearchResultView();
503         if (view == null)
504             return;
505         SearchResultViewer viewer= view.getViewer();
506         if (viewer == null)
507             return;
508         ISelection sel= viewer.getSelection();
509         if (!(sel instanceof IStructuredSelection))
510             return;
511         IStructuredSelection ss= (IStructuredSelection) sel;
512         IFile file= marker.getFile();
513         if (ss.size() == 1 && file.equals(ss.getFirstElement()))
514             return;
515         Table table= viewer.getTable();
516         if (table == null || table.isDisposed())
517             return;
518         int selectionIndex= table.getSelectionIndex();
519         if (selectionIndex < 0)
520             selectionIndex= 0;
521         for (int i= 0; i < table.getItemCount(); i++) {
522             int currentTableIndex= (selectionIndex+i) % table.getItemCount();
523             SearchResultViewEntry entry= (SearchResultViewEntry) viewer.getElementAt(currentTableIndex);
524             if (file.equals(entry.getGroupByKey())) {
525                 viewer.setSelection(new StructuredSelection(entry));
526                 return;
527             }
528         }
529     }
530
531     // opening editors ------------------------------------------
532
private ITextEditor openEditorNoReuse(ReplaceMarker marker) throws PartInitException {
533         IFile file= marker.getFile();
534         IWorkbenchPage activePage= SearchPlugin.getActivePage();
535         if (activePage == null)
536             return null;
537         ITextEditor textEditor= showOpenTextEditor(activePage, file);
538         if (textEditor != null)
539             return textEditor;
540         return openNewTextEditor(file, activePage);
541     }
542     
543     private ITextEditor openNewTextEditor(IFile file, IWorkbenchPage activePage) throws PartInitException {
544         IEditorDescriptor desc= IDE.getDefaultEditor(file);
545         if (desc != null) {
546             String JavaDoc editorID= desc.getId();
547             IEditorPart editor;
548             if (desc.isInternal()) {
549                 editor= activePage.openEditor(new FileEditorInput(file), editorID);
550                 if (editor instanceof ITextEditor) {
551                     if (editor instanceof IReusableEditor)
552                         fEditor= (IReusableEditor) editor;
553                     return (ITextEditor)editor;
554                 } else
555                     activePage.closeEditor(editor, false);
556             }
557         }
558         IEditorPart editor= activePage.openEditor(new FileEditorInput(file), "org.eclipse.ui.DefaultTextEditor"); //$NON-NLS-1$
559
return (ITextEditor)editor;
560     }
561
562     private ITextEditor openEditorReuse(ReplaceMarker marker) throws PartInitException {
563         IWorkbenchPage page= SearchPlugin.getActivePage();
564         IFile file= marker.getFile();
565         if (page == null)
566             return null;
567
568         ITextEditor textEditor= showOpenTextEditor(page, file);
569         if (textEditor != null)
570             return textEditor;
571
572         String JavaDoc editorId= null;
573         IEditorDescriptor desc= IDE.getDefaultEditor(file);
574         if (desc != null && desc.isInternal())
575             editorId= desc.getId();
576
577         boolean isOpen= isEditorOpen(page, fEditor);
578
579         boolean canBeReused= isOpen && !fEditor.isDirty() && !isPinned(fEditor);
580         boolean showsSameInputType= fEditor != null && (editorId == null || fEditor.getSite().getId().equals(editorId));
581
582         if (canBeReused) {
583             if (showsSameInputType) {
584                 fEditor.setInput(new FileEditorInput(file));
585                 page.bringToTop(fEditor);
586                 return (ITextEditor) fEditor;
587             } else {
588                 page.closeEditor(fEditor, false);
589                 fEditor= null;
590             }
591         }
592         return openNewTextEditor(file, page);
593     }
594
595     private boolean isEditorOpen(IWorkbenchPage page, IEditorPart editor) {
596         if (editor != null) {
597             IEditorReference[] parts= page.getEditorReferences();
598             int i= 0;
599             for (int j = 0; j < parts.length; j++) {
600                 if (editor == parts[i++].getEditor(false))
601                     return true;
602             }
603         }
604         return false;
605     }
606
607     private ITextEditor showOpenTextEditor(IWorkbenchPage page, IFile file) {
608         IEditorPart editor= page.findEditor(new FileEditorInput(file));
609         if (editor instanceof ITextEditor) {
610             page.bringToTop(editor);
611             return (ITextEditor) editor;
612         }
613         return null;
614     }
615
616     private boolean isPinned(IEditorPart editor) {
617         if (editor == null)
618             return false;
619         
620         IEditorReference[] editorRefs= editor.getEditorSite().getPage().getEditorReferences();
621         int i= 0;
622         while (i < editorRefs.length) {
623             if (editor.equals(editorRefs[i].getEditor(false)))
624                 return editorRefs[i].isPinned();
625             i++;
626         }
627         return false;
628     }
629     
630     // resource related -------------------------------------------------------------
631
/**
632      * @return the number of resources referred to in fMarkers
633      */

634     private int countResources() {
635         IResource r= null;
636         int count= 0;
637         for (Iterator JavaDoc elements= fMarkers.iterator(); elements.hasNext(); ) {
638             ReplaceMarker element= (ReplaceMarker)elements.next();
639             if (!element.getFile().equals(r)) {
640                 count++;
641                 r= element.getFile();
642             }
643         }
644         return count;
645     }
646     
647     private ReplaceMarker[] collectMarkers(IResource resource) {
648         List JavaDoc matching= new ArrayList JavaDoc();
649         for (int i= 0; i < fMarkers.size(); i++) {
650             ReplaceMarker marker= (ReplaceMarker)fMarkers.get(i);
651             if (!marker.getFile().equals(resource))
652                 break;
653             matching.add(marker);
654         }
655         ReplaceMarker[] markers= new ReplaceMarker[matching.size()];
656         return (ReplaceMarker[])matching.toArray(markers);
657     }
658     
659     
660     // some queries -------------------------------------------------------------
661
private boolean hasNextMarker() {
662         return fMarkers.size() > 1;
663     }
664     
665     private boolean hasNextFile() {
666         if (!hasNextMarker())
667             return false;
668         IResource currentFile= getCurrentMarker().getFile();
669         for (int i= 0; i < fMarkers.size(); i++) {
670             if (!((ReplaceMarker)fMarkers.get(i)).getFile().equals(currentFile))
671                 return true;
672         }
673         return false;
674     }
675     
676     private boolean canReplace() {
677         return fMarkers.size() > 0;
678     }
679 }
680
Popular Tags