001    package net.sourceforge.mp3dings;
002    
003    /* Mp3dings - manage mp3 meta-information
004     * Copyright (C) 2003 Moritz Ringler
005     * $Id: ReplaceDialogue.java 69 2007-10-24 21:57:43Z ringler $
006     *
007     * This program is free software; you can redistribute it and/or
008     * modify it under the terms of the GNU General Public License
009     * as published by the Free Software Foundation; either version 2
010     * of the License, or (at your option) any later version.
011     *
012     * This program is distributed in the hope that it will be useful,
013     * but WITHOUT ANY WARRANTY; without even the implied warranty of
014     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
015     * GNU General Public License for more details.
016     *
017     * You should have received a copy of the GNU General Public License
018     * along with this program; if not, write to the Free Software
019     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
020     */
021    
022    import java.awt.Component;
023    import java.awt.Container;
024    import java.util.ArrayList;
025    import java.util.Arrays;
026    import java.util.List;
027    import java.util.logging.Level;
028    import java.util.logging.Logger;
029    import java.util.regex.Matcher;
030    import java.util.regex.Pattern;
031    import java.util.regex.PatternSyntaxException;
032    import javax.swing.AbstractButton;
033    import javax.swing.JDialog;
034    import javax.swing.JOptionPane;
035    import javax.swing.JTable;
036    import de.mospace.swing.JReplaceDialogue;
037    
038    /** A Replace Dialogue for the four mp3dings tables.*/
039    public final class ReplaceDialogue extends JReplaceDialogue{
040        private static final Logger logger = Logger.getLogger(ReplaceDialogue.class.getPackage().getName());
041        JOptionPane replacePane, findPane;
042        JDialog replaceDialog, findDialog;
043        AbstractButton replaceButton;
044        String replace, findNext, done;
045        private MainFrame mfOwner;
046        private Runnable runWhenDone;
047        private final boolean replaceEnabled;
048    
049        public ReplaceDialogue(MainFrame owner){
050            this(owner, true);
051        }
052    
053        public ReplaceDialogue(MainFrame owner, boolean showReplace){
054            super(owner,
055                Globals.getPrefNode().node(
056                    (showReplace)?"ReplaceHistory":"FindHistory"
057                ), 10, showReplace
058            );
059            mfOwner = owner;
060            replaceEnabled = showReplace;
061            String replacePrompt = Globals.getString("REPLACE_PROMPT");
062            String findPrompt = Globals.getString("FIND_PROMPT");
063            String[] replaceButtons = Globals.getStringArray("REPLACE_BUTTONS");
064            replace = replaceButtons[1];
065            findNext = replaceButtons[0];
066            done = replaceButtons[2];
067            String[] findButtons = new String[]{findNext, done};
068            replacePane = new JOptionPane(replacePrompt, JOptionPane.QUESTION_MESSAGE,
069                    JOptionPane.YES_NO_CANCEL_OPTION, null, replaceButtons);
070            replaceButton = getReplaceButton();
071            findPane = new JOptionPane(findPrompt, JOptionPane.INFORMATION_MESSAGE,
072                    JOptionPane.OK_CANCEL_OPTION, null, findButtons);
073            replaceDialog = replacePane.createDialog(owner, replacePrompt);
074            findDialog = findPane.createDialog(owner, findPrompt);
075        }
076    
077        private AbstractButton getReplaceButton(){
078            List children = new ArrayList();
079            children.addAll(Arrays.asList(replacePane.getComponents()));
080            for(int i=0; i<children.size(); i++){
081                Component c = (Component) children.get(i);
082                if(c instanceof AbstractButton){
083                    if (((AbstractButton) c).getText().equals(replace)){
084                        return (AbstractButton) c;
085                    }
086                } else if (c instanceof Container){
087                    children.addAll(Arrays.asList(((Container) c).getComponents()));
088                }
089            }
090            return null;
091        }
092    
093        public void performReplace(String what, String with, boolean mWord,
094                boolean mCase, boolean regExp,  boolean rAll, Object scope){
095            JOptionPane pane = null;
096            JDialog dialog = null;
097            Pattern search;
098            JTable  activeTable;
099            try {
100                activeTable = (JTable) scope;
101            } catch (ClassCastException ex) {
102                return;
103            }
104            if(activeTable == null || what == null || what.equals("")){
105                return;
106            }
107            int[]   rows        = activeTable.getSelectedRows();
108            int[]   cols        = activeTable.getSelectedColumns();
109            int     n           = rows.length;
110            int     m           = cols.length;
111            int     replacedCount  = 0;
112            int     foundCount = 0;
113            Mp3dingsTableModel t = (Mp3dingsTableModel) activeTable.getModel();
114    
115            if(what.length()==0){
116                return;
117            }
118            /* modifiers */
119            if(!regExp){
120                what = "\\Q"+what+"\\E";
121            }
122            if(mWord){
123                what = "\\b"+what+"\\b";
124            }
125            if(!mCase){
126                what = "(?i)"+what;
127            }
128            /* compile regexp */
129            try{
130                search = Pattern.compile(what);
131            } catch (PatternSyntaxException ex){
132                setStatus(Globals.getMessage("PATTERN_SYNTAX_EXCEPTION",
133                        new Object[]{ex.getPattern(),new Integer(ex.getIndex())})
134                );
135                return;
136            }
137            /* start searching */
138            this.setVisible(false);
139    
140            String  s;
141            Matcher mm;
142            Object selectedValue = null;
143            activeTable.clearSelection();
144            for(int j=0; j<m; j++){
145                if (replaceEnabled){
146                    pane = replacePane;
147                    dialog = replaceDialog;
148                    if(replaceButton != null){
149                        replaceButton.setEnabled(t.isCellEditable(0,cols[j]));
150                    }
151                }
152                if((! replaceEnabled) ||
153                   (replaceButton == null && !t.isCellEditable(0,cols[j])))
154                {
155                    pane = findPane;
156                    dialog = findDialog;
157                }
158                for(int i=0; i<n; i++){
159                    s = String.valueOf(t.getValueAt(rows[i],cols[j]));
160                    mm = search.matcher(s);
161    
162                    if(mm.find()){
163                        foundCount++;
164                        /* replace all / select all */
165                        if (rAll){
166                            if(replaceEnabled){
167                                s = mm.replaceAll(with);
168                                t.set(s,rows[i],cols[j]);
169                                replacedCount++;
170                            } else {
171                                if(activeTable.getSelectedColumn() != -1){
172                                    /* inefficient but simple */
173                                    activeTable.addRowSelectionInterval(rows[i],rows[i]);
174                                } else {
175                                    /* clear selection and select first cell with extend=false */
176                                   activeTable.changeSelection(rows[i], cols[j],
177                                            false, false);
178                                   activeTable.addColumnSelectionInterval(0, activeTable.getColumnCount()-1);
179                                }
180                            }
181                        /* otherwise select cell and bring up dialog */
182                        } else {
183                            activeTable.changeSelection(rows[i], cols[j], false, false);
184    
185                            /* assure selection is visible */
186                            try{
187                            ((Mp3dingsTable) activeTable).getFrame().scrollTo(
188                                activeTable.getCellRect(rows[i], cols[j], true),
189                                activeTable
190                            );
191                            } catch (ClassCastException ex){
192                                logger.severe("Cannot scroll active table. No Mp3dingsTable.");
193                                Globals.logStackTrace(logger, Level.SEVERE, ex);
194                            }
195    
196                            /* show prompt */
197                            dialog.setVisible(true);
198                            selectedValue = pane.getValue();
199                            if (selectedValue == replace){
200                                s = mm.replaceAll(with);
201                                t.setValueAt(s,rows[i],cols[j]);
202                                replacedCount++;
203                            } else if (selectedValue  == done){
204                                break;
205                            }
206                        }
207                    }
208                }
209                if(replacedCount > 0){
210                    t.fireDataChanged(replacedCount);
211                    t.fireTableDataChanged();
212                }
213                if (selectedValue  == done){
214                    break;
215                }
216            }
217            if(runWhenDone != null){
218                runWhenDone.run();
219            }
220            setStatus(
221                Globals.getMessage("REPLACE_STATUS",
222                    new Integer[]{new Integer(foundCount), new Integer(replacedCount)}
223                )
224            );
225    
226        }
227    
228        private void setStatus(String s){
229            if (mfOwner != null){
230                mfOwner.setStatus(s);
231            } else {
232                logger.info(s);
233            }
234        }
235    
236        /** This method is meant to assure that something is done at the end
237         * of a find replace operation. That is:
238         * <ul>
239         * <li>when the user clicks 'Cancel'
240         * <li>when the user clicks 'Replace All' and all occurrences of the
241         search term have been replaced
242         * <li>after the user has clicked Find/Replace when no more occurrences of
243         * the search term are found or the user clicks 'Done'
244         * </ul>
245         * Note that {@link de.mospace.swing.JReplaceDialogue#actionPerformed}
246         * returns when the Dialog becomes invisible again, that is <b>before</b>
247         * any action triggered by one of the dialog buttons.
248         **/
249        public void invokeWhenDone(Runnable r){
250            runWhenDone = r;
251        }
252    
253    
254    
255        /* Cancels the dialog.
256        * @see #invokeWhenDone()
257        */
258        public void cancel(){
259            super.cancel();
260            if(runWhenDone != null){
261                runWhenDone.run();
262            }
263        }
264    
265    }