001    /* $Id: JReplaceDialogue.java 124 2007-12-22 13:38:59Z ringler $
002     * This class is part of the de.mospace.swing library.
003     * Copyright (C) 2005-2006 Moritz Ringler
004     *
005     * This program is free software; you can redistribute it and/or
006     * modify it under the terms of the GNU General Public License
007     * as published by the Free Software Foundation; either version 2
008     * of the License, or (at your option) any later version.
009     *
010     * This program is distributed in the hope that it will be useful,
011     * but WITHOUT ANY WARRANTY; without even the implied warranty of
012     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013     * GNU General Public License for more details.
014     *
015     * You should have received a copy of the GNU General Public License
016     * along with this program; if not, write to the Free Software
017     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
018     */
019    package de.mospace.swing;
020    
021    import java.awt.BorderLayout;
022    import java.awt.Component;
023    import java.awt.Container;
024    import java.awt.Dimension;
025    import java.awt.Frame;
026    import java.awt.GridLayout;
027    import java.awt.Insets;
028    import java.awt.TextField;
029    import java.awt.event.ActionEvent;
030    import java.awt.event.ActionListener;
031    import java.util.prefs.Preferences;
032    import javax.swing.AbstractAction;
033    import javax.swing.Action;
034    import javax.swing.BorderFactory;
035    import javax.swing.JButton;
036    import javax.swing.JCheckBox;
037    import javax.swing.JComboBox;
038    import javax.swing.JComponent;
039    import javax.swing.JDialog;
040    import javax.swing.JLabel;
041    import javax.swing.JPanel;
042    import javax.swing.JTextField;
043    import javax.swing.KeyStroke;
044    import javax.swing.SwingConstants;
045    import javax.swing.UIManager;
046    import javax.swing.border.CompoundBorder;
047    import de.mospace.swing.text.HistoryTextField;
048    
049    /** A customizable Replace Dialogue.
050     *
051     * @author Moritz Ringler
052     * @version $Revision: 124 $ ($Date: 2007-12-22 14:38:59 +0100 (Sa, 22 Dez 2007) $)
053     */
054    abstract public class JReplaceDialogue extends JDialog implements ActionListener{
055        /** A common interface for JComboBoxes and JTextFields. **/
056        private static interface TextField{
057            public void setText(String s);
058            public String getText();
059            public JComponent getComponent();
060        }
061    
062        /** Extracted from bsh.BSHLiteral by Pat Niemeyer */
063        private static class StringLiteral{
064            private final String value;
065    
066            public StringLiteral(String source){
067                value = stringSetup(source);
068            }
069    
070            private static String stringSetup(String str){
071                StringBuffer buffer = new StringBuffer();
072                for(int i = 0; i < str.length(); i++) {
073                    char ch = str.charAt(i);
074                    if(ch == '\\') {
075                        // get next character
076                        ch = str.charAt(++i);
077                        if(Character.isDigit(ch)) {
078                            int endPos = i;
079                            // check the next two characters
080                            while(endPos < i + 2)
081                            {
082                                if(Character.isDigit(str.charAt(endPos + 1)))
083                                    endPos++;
084                                else
085                                    break;
086                            }
087                            ch = (char)Integer.parseInt(str.substring(i, endPos + 1), 8);
088                            i = endPos;
089                        } else {
090                            ch = getEscapeChar(ch);
091                        }
092                    }
093                    buffer.append(ch);
094                }
095                return buffer.toString();
096            }
097    
098            private static char getEscapeChar(char ch)
099            {
100                switch(ch)
101                {
102                    case 'b':
103                        ch = '\b';
104                        break;
105                    case 't':
106                        ch = '\t';
107                        break;
108                    case 'n':
109                        ch = '\n';
110                        break;
111                    case 'f':
112                        ch = '\f';
113                        break;
114                    case 'r':
115                        ch = '\r';
116                        break;
117                    // do nothing - ch already contains correct character
118                    case '"':
119                    case '\'':
120                    case '\\':
121                    break;
122                }
123                return ch;
124            }
125    
126            public String toString(){
127                return value;
128            }
129        }
130    
131        /** A static class that wraps JComboBoxes and JTextFields into TextFields.
132        * @see #TextField
133        **/
134        private final static class TextFieldFactory {
135            private TextFieldFactory(){
136            }
137    
138            public static TextField getTextField(final JComboBox jcb){
139                return new TextField(){
140                    private JComboBox cb=jcb;
141    
142                    public void setText(String s){
143                        jcb.setSelectedItem(s);
144                    }
145    
146                    public String getText(){
147                        return jcb.getSelectedItem().toString();
148                    }
149    
150                    public JComponent getComponent(){
151                        return jcb;
152                    }
153                };
154            }
155    
156            public static TextField getTextField(final JTextField tf){
157             return new TextField(){
158                    public void setText(String s){
159                        tf.setText(s);
160                    }
161    
162                    public String getText(){
163                        return tf.getText();
164                    }
165    
166                    public JComponent getComponent(){
167                        return tf;
168                    }
169                };
170            }
171        }
172    
173        private JPanel cont;
174        private TextField replWhat;
175        private TextField replWith;
176        /** The action event that has triggered the dialogue **/
177        ActionEvent opener;
178        private Object scope;
179    
180        private JCheckBox matchWord;
181        private JCheckBox matchCase;
182        private JCheckBox regExp;
183        private JButton repl;
184        private JButton replAll;
185        private JButton cancel;
186        private JLabel replWhatL;
187        private JLabel replWithL;
188        private JPanel north, nwest, neast;
189        private JPanel south, swest, seast;
190        private ActionListener replListener;
191    
192        final public static int MATCH_WORD = 0;
193        final public static int MATCH_CASE = 1;
194        final public static int REG_EXP = 2;
195    
196        /** Constructs a replace dialog with no history of entered items. **/
197        public JReplaceDialogue(Frame owner){
198            this(owner,null,0);
199        }
200    
201        /** Constructs a replace dialog with a search and replace history.
202         * @param pref the preference node to use for storing history items
203         * @param len the number of items in the history
204        **/
205        public JReplaceDialogue(Frame owner, Preferences pref, int len){
206            this(owner, pref, len, true);
207        }
208    
209        /** Constructs a replace dialog with a search and replace history.
210         * @param pref the preference node to use for storing history items
211         * @param len the number of items in the history
212         * @param showReplace whether to display the Replace All button and
213         * the "[Replace ]with" field
214        **/
215        public JReplaceDialogue(Frame owner, Preferences pref, int len, boolean showReplace){
216            super(owner);
217            replListener = new ActionListener(){
218                public void actionPerformed(ActionEvent e) {
219                    boolean zAll=false;
220                    if(e.getSource() == replAll){
221                        zAll = true;
222                    }
223                    final String lookFor = replWhat.getText();
224                    if(lookFor == null || lookFor.length() == 0){
225                        return;
226                    }
227                    String rWith = replWith.getText();
228                    final boolean rE = regExp.isSelected();
229                    if(rE){
230                        rWith = (new StringLiteral(rWith)).toString();
231                    }
232                    performReplace(lookFor, rWith, matchWord.isSelected(),
233                            matchCase.isSelected(), rE, zAll, scope);
234                }
235            };
236    
237            CompoundBorder border = BorderFactory.
238                    createCompoundBorder(BorderFactory.
239                    createEmptyBorder(5,5,5,5),BorderFactory.
240                    createEtchedBorder());
241    
242            cont = new JPanel();
243            north = new JPanel();
244            neast = new JPanel();
245            nwest = new JPanel();
246            south = new JPanel();
247            swest = new JPanel();
248            seast = new JPanel();
249    
250            AbstractAction cancelAction = new AbstractAction(UIManager.getString("OptionPane.cancelButtonText")){
251                    public void actionPerformed(ActionEvent e){
252                        cancel();
253                    }
254                };
255    
256            AbstractAction findAction = new AbstractAction(
257                    GLOBALS.getString(showReplace? "Find/Replace..." : "Find...")){
258                public void actionPerformed(ActionEvent e){
259                    replListener.actionPerformed(
260                        new ActionEvent(repl,ActionEvent.ACTION_PERFORMED,""));
261                }
262            };
263    
264            this.setTitle(GLOBALS.getString(showReplace?"Replace":"Find"));
265    
266            matchWord = new JCheckBox(GLOBALS.getString("whole word"));
267            matchWord.setMnemonic(GLOBALS.getKey("W (whole word mnemonic)"));
268    
269            matchCase = new JCheckBox(GLOBALS.getString("case sensitve"));
270            matchCase.setMnemonic(GLOBALS.getKey("S (case sensitive mnemonic)"));
271    
272            regExp = new JCheckBox(GLOBALS.getString("regular expression"));
273            regExp.setMnemonic(GLOBALS.getKey("E (regular expression mnemonic)"));
274    
275            repl = new JButton(findAction);
276            repl.setMnemonic(GLOBALS.getKey(showReplace?
277                "F (Find/Replace... mnemonic)" : "F (Find... mnemonic)"));
278    
279            replAll = new JButton(GLOBALS.getString(
280                    showReplace? "Replace all" : "Select all"));
281            replAll.setMnemonic(GLOBALS.getKey(showReplace?
282                    "A (replace all mnemonic)" : "A (select all mnemonic)"));
283    
284            cancel = new JButton(cancelAction);
285            cancel.setMnemonic(GLOBALS.getKey("C (cancel mnemonic)"));
286    
287            replWhatL = new JLabel(GLOBALS.getString("Look for"));
288            replWhatL.setDisplayedMnemonic(GLOBALS.getKey("L (Look for mnemonic)"));
289    
290            replWithL = new JLabel(
291                    showReplace ? GLOBALS.getString("Replace with") : "");
292            replWithL.setDisplayedMnemonic(GLOBALS.getKey("I (with mnemonic)"));
293    
294            if(pref == null){
295                JTextField jtf1 = new JTextField(72);
296                replWhatL.setLabelFor(jtf1);
297                replWhat    = TextFieldFactory.getTextField(jtf1);
298                JTextField jtf2 = new JTextField(72);
299                replWithL.setLabelFor(jtf2);
300                replWith    = TextFieldFactory.getTextField(jtf2);
301            } else {
302                HistoryTextField htf = new HistoryTextField(pref, 0, len);
303                htf.setAutoSave(true);
304                JComboBox jcb1 = htf.getComboBox();
305                htf = new HistoryTextField(pref, 1, len);
306                htf.setAutoSave(true);
307                JComboBox jcb2 = htf.getComboBox();
308                replWhatL.setLabelFor(jcb1);
309                replWithL.setLabelFor(jcb2);
310                replWhat    = TextFieldFactory.getTextField(jcb1);
311                replWith    = TextFieldFactory.getTextField(jcb2);
312            }
313    
314            replAll.addActionListener(replListener);
315    
316            cont.setPreferredSize(new Dimension(400,130));
317            north.setBorder(border);
318            neast.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
319            nwest.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
320            swest.setBorder(BorderFactory.createEmptyBorder(0,40,5,40));
321            seast.setBorder(BorderFactory.createEmptyBorder(0,60,5,60));
322            replWith.getComponent().setPreferredSize(new Dimension(200,20));
323            replWhat.getComponent().setPreferredSize(new Dimension(200,20));
324            replWhatL.setHorizontalAlignment(SwingConstants.RIGHT);
325            replWithL.setHorizontalAlignment(SwingConstants.RIGHT);
326            final Dimension d = new Dimension(135,16);
327            Insets in = new Insets(0,3,0,2);
328            cancel.setPreferredSize(d);
329            repl.setPreferredSize(d);
330            replAll.setMargin(in);
331            cancel.setMargin(in);
332            repl.setMargin(in);
333            replAll.setPreferredSize(d);
334            matchWord.setPreferredSize(d);
335            matchCase.setPreferredSize(d);
336            regExp.setPreferredSize(d);
337    
338            cont.setLayout(new BorderLayout());
339            north.setLayout(new BorderLayout());
340            neast.setLayout(new GridLayout(0,1));
341            nwest.setLayout(new GridLayout(0,1));
342            south.setLayout(new GridLayout(1,0));
343            swest.setLayout(new GridLayout(0,1,0,3));
344            seast.setLayout(new GridLayout(0,1,0,3));
345    
346            nwest.add(replWhatL);
347            neast.add(replWhat.getComponent());
348            if (showReplace) {
349                nwest.add(replWithL);
350                neast.add(replWith.getComponent());
351            }
352            north.add(nwest, BorderLayout.WEST);
353            north.add(neast, BorderLayout.CENTER);
354    
355            swest.add(matchWord);
356            swest.add(matchCase);
357            swest.add(regExp);
358            seast.add(repl);
359            seast.add(replAll);
360            seast.add(cancel);
361            south.add(swest);
362            south.add(seast);
363    
364            cont.add(north, BorderLayout.CENTER);
365            cont.add(south, BorderLayout.SOUTH);
366            this.setContentPane(cont);
367            this.pack();
368    
369            /* Conflicts with history text fields */
370            //KeyStroke esc = KeyStroke.getKeyStroke("ESCAPE");
371            //setKeyToAction(cont,esc,cancelAction);
372            //KeyStroke ret = KeyStroke.getKeyStroke("ENTER");
373            //setKeyToAction(neast,ret,findAction);
374        }
375    
376        // /** Binds a key to an action in a component and all of its children.
377         // */
378        // private void setKeyToAction(Component component, KeyStroke k, Action a){
379            // if(component instanceof JComponent){
380                // JComponent c = (JComponent) component;
381                // c.getInputMap().put(k,"cancel");
382                // c.getActionMap().put("cancel",a);
383                // if(component instanceof Container){
384                    // Container container = (Container) component;
385                    // Component[] components = container.getComponents();
386                    // for (int i=0; i< components.length; i++){
387                        // setKeyToAction(components[i],k,a);
388                    // }
389                // }
390            // }
391        // }
392    
393        /** Specifies the scope of the next search.
394         * @see #performReplace(String what, String with, boolean mWord,
395         * boolean mCase, boolean regExp, boolean rAll, Object scope)
396         */
397        public void setScope(Object searchScope){
398            scope = searchScope;
399        }
400    
401        /** Displays the dialogue.
402        *  @deprecated
403        *  @see #setVisible
404        */
405        public void show(){
406        //Don't call setVisible here!
407        //JDialog implements setVisible(true) by calling show()
408        //therefore a call to setVisible would lead to an infinite loop
409            super.show();
410            replWhat.getComponent().requestFocus();
411        }
412    
413        /** Displays or hides the dialogue. */
414        public void setVisible(boolean b){
415            super.setVisible(b);
416            if(b) {
417                replWhat.getComponent().requestFocus();
418            }
419        }
420    
421        /** Closes the dialog without doing a search. This method is called when
422         * the user hits the cancel button. **/
423        public void cancel(){
424            setVisible(false);
425        }
426    
427        /** Hides or shows an option. Use this if you don't want to implement
428         * one of the options.
429         * @param option one of MATCH_WORD, MATCH_CASE, REG_EXP
430         */
431        public void setOptionEnabled(int option, boolean enabled){
432            switch (option){
433                case MATCH_WORD:matchWord.setVisible(enabled);break;
434                case MATCH_CASE:matchCase.setVisible(enabled);break;
435                case REG_EXP:regExp.setVisible(enabled);break;
436                default: throw new IllegalArgumentException("Unknown option " + option);
437            }
438        }
439    
440        /** Perform a find/replace operation.
441         * Overwrite this method to suit your needs.
442         * @param what string or regular expression to look for
443         * @param with replacement string
444         * @param mWord modifier: match whole word
445         * @param mCase modifier: match case
446         * @param regExp modifier: <code>what</code> is a regular expression
447         * @param rAll modifier: replace all occurences in scope
448         * @param scope search scope set by {@link #setScope(Object scope)}
449         */
450        abstract public void performReplace(String what, String with, boolean mWord,
451                boolean mCase, boolean regExp, boolean rAll, Object scope);
452    
453        /** Show the dialogue when an action is performed */
454        public void actionPerformed(ActionEvent e){
455            opener = e;
456            setVisible(true);
457        }
458    }