KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > bluej > editor > moe > Finder


1 // Copyright (c) 2000, 2005 BlueJ Group, Deakin University
2
//
3
// This software is made available under the terms of the "MIT License"
4
// A copy of this license is included with this source distribution
5
// in "license.txt" and is also available at:
6
// http://www.opensource.org/licenses/mit-license.html
7
// Any queries should be directed to Michael Kolling mik@bluej.org
8

9 package bluej.editor.moe;
10
11 import java.awt.*;
12 import java.awt.event.*;
13
14 import javax.swing.*;
15 import javax.swing.event.*;
16
17 import bluej.Config;
18 import bluej.utility.EscapeDialog;
19
20 /**
21  * The Finder class implements the find and replace functionality of the Moe editor.
22  * It provides both the user interface dialogue and the high level implementation
23  * of the find and replace functionality.
24  *
25  * @author Michael Kolling
26  * @author Bruce Quig
27  * @version $Id: Finder.java,v 1.20 2005/05/02 03:23:32 davmac Exp $
28  */

29
30 public class Finder extends EscapeDialog
31     implements ActionListener, DocumentListener
32 {
33     static final String JavaDoc title = Config.getString("editor.find.title");
34     static final String JavaDoc findLabel = Config.getString("editor.find.find.label");
35     static final String JavaDoc replaceLabel = Config.getString("editor.find.replace.label");
36
37     // -------- CONSTANTS --------
38

39     // search direction for the finder
40
static final String JavaDoc UP = "up";
41     static final String JavaDoc DOWN = "down";
42   
43     // -------- INSTANCE VARIABLES --------
44

45     private boolean searchFound; // true if last find was successfull
46
private boolean replacing;
47
48     private JButton findButton;
49     private JButton replaceButton;
50     private JButton replaceAllButton;
51     private JButton cancelButton;
52     private JTextField searchField;
53     private JTextField replaceField;
54     private JCheckBox wholeWord;
55     private JCheckBox ignoreCase;
56     private ButtonGroup directionButtons;
57
58     private MoeEditor editor;
59
60     // ------------- METHODS --------------
61

62     public Finder()
63     {
64         super((Frame)null, title, true);
65         searchFound = true;
66         makeDialog();
67     }
68
69     /**
70      * Ask the user for input of search details via a dialogue.
71      *
72      */

73     public void show(MoeEditor currentEditor, String JavaDoc selection, boolean replace)
74     {
75         editor = currentEditor;
76         replacing = replace;
77         getRootPane().setDefaultButton(findButton);
78
79         if(selection != null && selection.length() > 0) {
80             setSearchString(selection);
81             replaceButton.setEnabled(true);
82         }
83         else
84             replaceButton.setEnabled(false);
85
86         if(!replacing)
87             replaceField.setText("");
88
89         searchField.selectAll();
90         searchField.requestFocus();
91
92         setVisible(true);
93     }
94
95     /**
96      * search for the next instance of a text string
97      */

98     private void find()
99     {
100         searchFound = editor.findString(getSearchString(), getSearchBack(),
101                                         getIgnoreCase(), getWholeWord(), !searchFound);
102         replaceButton.setEnabled(searchFound);
103         if(searchFound && replacing)
104             getRootPane().setDefaultButton(replaceButton);
105     }
106
107     /**
108      * replaces selected text with the contents of the replaceField and return
109      * next instance of the searchString.
110      */

111     private void replace()
112     {
113         String JavaDoc replaceText = smartFormat(editor.getSelectedText(), replaceField.getText());
114         editor.insertText(replaceText, getSearchBack());
115         find();
116     }
117
118     /**
119      * Replace all instances of the search String with a replacement.
120      * -check for valid search criteria
121      * - TODO: get initial cursor pos
122      * -start at beginning
123      * -do initial find
124      * -replace until not found, no wrapping!
125      * -print out number of replacements (?)
126      * -TODO: return cursor/caret to original place
127      */

128     private void replaceAll()
129     {
130         String JavaDoc searchString = getSearchString();
131         String JavaDoc replaceString = replaceField.getText();
132
133         int count = 0;
134         if(getSearchBack()) {
135             while(editor.doFindBackward(searchString, getIgnoreCase(), getWholeWord(), false)) {
136                 editor.insertText(smartFormat(editor.getSelectedText(), replaceString), true);
137                 count++;
138             }
139         }
140         else {
141             while(editor.doFind(searchString, getIgnoreCase(), getWholeWord(), false)) {
142                 editor.insertText(smartFormat(editor.getSelectedText(), replaceString), false);
143                 count++;
144             }
145         }
146         if(count > 0)
147             //editor.writeMessage("Replaced " + count + " instances of " + searchString);
148
editor.writeMessage(Config.getString("editor.replaceAll.replaced") +
149                  count + Config.getString("editor.replaceAll.intancesOf") +
150                  searchString);
151         else
152             //editor.writeMessage("String " + searchString + " not found. Nothing replaced.");
153
editor.writeMessage(Config.getString("editor.replaceAll.string") +
154                     searchString + Config.getString("editor.replaceAll.notFoundNothingReplaced"));
155     }
156
157     /**
158      * Replace the text currently selected in the editor with
159      */

160     private String JavaDoc smartFormat(String JavaDoc original, String JavaDoc replacement)
161     {
162         if(original == null || replacement == null)
163             return replacement;
164
165         // only do smart stuff if search and replace strings were entered in lowercase.
166
// check here. if not lowercase, just return.
167

168         String JavaDoc search = getSearchString();
169         if( !isLowerCase(replacement) || !isLowerCase(search))
170             return replacement;
171
172         if(isUpperCase(original))
173             return replacement.toUpperCase();
174         if(isTitleCase(original))
175             return Character.toTitleCase(replacement.charAt(0)) +
176                 replacement.substring(1);
177         else
178             return replacement;
179     }
180        
181     /**
182      * True if the string is in lower case.
183      */

184     public boolean isLowerCase(String JavaDoc s)
185     {
186         for(int i=0; i<s.length(); i++) {
187             if(! Character.isLowerCase(s.charAt(i)))
188                 return false;
189         }
190         return true;
191     }
192
193     /**
194      * True if the string is in Upper case.
195      */

196     public boolean isUpperCase(String JavaDoc s)
197     {
198         for(int i=0; i<s.length(); i++) {
199             if(! Character.isUpperCase(s.charAt(i)))
200                 return false;
201         }
202         return true;
203     }
204
205     /**
206      * True if the string is in title case.
207      */

208     public boolean isTitleCase(String JavaDoc s)
209     {
210         if(s.length() < 2)
211             return false;
212         return Character.isUpperCase(s.charAt(0)) &&
213             Character.isLowerCase(s.charAt(1));
214     }
215
216     /**
217      * set the search string
218      */

219     public void setSearchString(String JavaDoc s)
220     {
221         searchField.setText(s);
222     }
223      
224     /**
225      * return the last search string
226      */

227     public String JavaDoc getSearchString()
228     {
229         return searchField.getText();
230     }
231
232     /**
233      * return true if the current search direction is backward
234      */

235     private boolean getSearchBack()
236     {
237         return directionButtons.getSelection().getActionCommand() == UP;
238     }
239
240     /**
241      * return true if "Ignore case" search is selected
242      */

243     public boolean getIgnoreCase()
244     {
245         return ignoreCase.isSelected();
246     }
247
248     /**
249      * return true if "whole word" search is selected
250      */

251     public boolean getWholeWord()
252     {
253         return wholeWord.isSelected();
254     }
255
256     /**
257      * set last search found
258      */

259     public void setSearchFound(boolean found)
260     {
261         searchFound = found;
262     }
263
264     /**
265      * return info whether the last search was successful
266      */

267     public boolean getSearchFound()
268     {
269         return searchFound;
270     }
271
272     // === Actionlistener interface ===
273
/**
274      * A button was pressed. Find out which one and do the appropriate
275      * thing.
276      */

277     public void actionPerformed(ActionEvent evt)
278     {
279         Object JavaDoc src = evt.getSource();
280         if(src == findButton)
281             find();
282         else if(src == replaceButton)
283             replace();
284         else if(src == replaceAllButton)
285             replaceAll();
286         else if(src == cancelButton)
287             setVisible(false);
288     }
289
290     // === Documentlistener interface ===
291
/**
292      * The search text was changed.
293      */

294     public void changedUpdate(DocumentEvent evt) { }
295
296     public void insertUpdate(DocumentEvent evt)
297     {
298         findButton.setEnabled(true);
299         replaceAllButton.setEnabled(true);
300     }
301
302     public void removeUpdate(DocumentEvent evt)
303     {
304         if(getSearchString().length() == 0) {
305             findButton.setEnabled(false);
306             replaceAllButton.setEnabled(false);
307         }
308     }
309
310     private void makeDialog()
311     {
312         addWindowListener(new WindowAdapter() {
313                 public void windowClosing(WindowEvent E) {
314                     setVisible(false);
315                 }
316             });
317         
318         // add search and replace text fields with labels
319

320         JPanel textPanel = new JPanel();
321         textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.Y_AXIS));
322         textPanel.setBorder(BorderFactory.createEmptyBorder(10,20,20,20));
323         {
324             JPanel findPanel = new JPanel(new BorderLayout());
325             findPanel.add(new JLabel(findLabel), BorderLayout.WEST);
326             searchField = new JTextField(16);
327             searchField.getDocument().addDocumentListener(this);
328             findPanel.add(searchField, BorderLayout.CENTER);
329             textPanel.add(findPanel);
330
331             textPanel.add(Box.createVerticalStrut(6));
332
333             JPanel replacePanel = new JPanel(new BorderLayout());
334             replacePanel.add(new JLabel(replaceLabel), BorderLayout.WEST);
335             replaceField = new JTextField(16);
336             replacePanel.add(replaceField, BorderLayout.CENTER);
337             textPanel.add(replacePanel);
338
339             textPanel.add(Box.createVerticalStrut(6));
340
341             Box togglesBox = new Box(BoxLayout.X_AXIS);
342             {
343                 Box optionBox = new Box(BoxLayout.Y_AXIS);
344                 {
345                     ignoreCase = new JCheckBox(Config.getString("editor.find.ignoreCase"), true);
346                     optionBox.add(ignoreCase);
347                     optionBox.add(Box.createVerticalStrut(6));
348                     wholeWord = new JCheckBox(Config.getString("editor.find.wholeWord"));
349                     optionBox.add(wholeWord);
350                 }
351                 togglesBox.add(optionBox);
352
353                 Box directionBox = new Box(BoxLayout.Y_AXIS);
354                 {
355                     directionButtons = new ButtonGroup();
356                     JToggleButton dirUp = new JRadioButton(Config.getString("editor.find.up"));
357                     dirUp.setActionCommand(UP);
358                     directionButtons.add(dirUp);
359                     directionBox.add(dirUp);
360                     directionBox.add(Box.createVerticalStrut(6));
361                     JToggleButton dirDown = new JRadioButton(Config.getString("editor.find.down"), true);
362                     dirDown.setActionCommand(DOWN);
363                     directionButtons.add(dirDown);
364                     directionBox.add(dirDown);
365                 }
366                 togglesBox.add(directionBox);
367             }
368             textPanel.add(togglesBox);
369         }
370         getContentPane().add(textPanel, BorderLayout.CENTER);
371
372         // add buttons
373

374         JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 0, 5));
375         buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
376
377         findButton = new JButton(Config.getString("editor.find.findNext"));
378         findButton.setEnabled(false);
379         buttonPanel.add(findButton);
380         findButton.addActionListener(this);
381    
382         replaceButton = new JButton(Config.getString("editor.find.replace"));
383         buttonPanel.add(replaceButton);
384         replaceButton.setEnabled(false);
385         replaceButton.addActionListener(this);
386    
387         replaceAllButton = new JButton(Config.getString("editor.find.replaceAll"));
388         replaceAllButton.setEnabled(false);
389         buttonPanel.add(replaceAllButton);
390         replaceAllButton.addActionListener(this);
391    
392         cancelButton = new JButton(Config.getString("close"));
393         buttonPanel.add(cancelButton);
394         cancelButton.addActionListener(this);
395         getContentPane().add("East", buttonPanel);
396
397         pack();
398     }
399
400 }
401
Popular Tags