001    package net.sourceforge.mp3dings;
002    
003    /* Mp3dings - manage mp3 meta-information
004     * Copyright (C) 2003 Moritz Ringler
005     * $Id: FileTableModel.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.Frame;
023    import java.io.File;
024    import java.io.FileInputStream;
025    import java.io.FileOutputStream;
026    import java.io.IOException;
027    import java.io.ObjectInputStream;
028    import java.io.ObjectOutputStream;
029    import java.io.ObjectStreamException;
030    import java.util.ArrayList;
031    import java.util.Arrays;
032    import java.util.List;
033    import java.util.Stack;
034    import java.util.logging.Logger;
035    import net.sourceforge.mp3dings.utils.RenamingPattern;
036    import net.sourceforge.mp3dings.utils.TimeIntensiveTask;
037    
038    /** The TableModel for the 'Names' table. Holds the data that is used
039     * for renaming of the mp3 files. **/
040    public final class FileTableModel extends DependentTableModel{
041        private static final Logger logger = Logger.getLogger(FileTableModel.class.getPackage().getName());
042        private List data = new ArrayList();
043        protected Stack patternStack = new Stack();
044        public static final int EMPTY_NAME = 0;
045        public static final int FILE_EXISTS = 1;
046        public static final int RENAME_FAILED = 2;
047    
048        /**
049         * Constructor
050         */
051        public FileTableModel(DataTableModel t){
052            init();
053            setMaster(t);
054            try{
055                loadPatterns(new File(Globals.getDir("HOME"), "patterns"));
056            } catch (IOException ex){
057                logger.warning("Error restoring file renaming patterns.");
058                logger.warning(ex.getMessage());
059            }
060        }
061    
062        private class RenameTask extends TimeIntensiveTask{
063            final boolean overwrite;
064            final boolean removeEmptyParents;
065            int fileCount       = 0;
066            int failedCount     = 0;
067            int[] err = new int[3];
068    
069            public RenameTask(Frame owner,
070                              boolean overwrite,
071                              boolean removeEmptyParents){
072                super(owner, Globals.getString("FILE_RENAME_PROGRESS"), "");
073                this.overwrite = overwrite;
074                this.removeEmptyParents = removeEmptyParents;
075            }
076    
077            public void run(){
078                Arrays.fill(err,0);
079                fileCount = 0;
080                failedCount = 0;
081    
082                int colNewName = getColumn(Field.NEW_FILENAME);
083                int colOldName = getColumn(Field.OLD_FILENAME);
084                int colInclude = getColumn(Field.INCLUDE);
085                int n = data.size();
086    
087                Mp3FileReader mp3FileReader = new Mp3FileReader(filters);
088                getMonitor().setProgress(1);
089                /* loop over all rows */
090                for(int row = 0; row < n; row++){
091                    if(((Boolean) getValueAt(row, colInclude)).booleanValue()){
092                        /* increase fileCount */
093                        fileCount++;
094    
095                        /* index in the master table */
096                        int masterRow = thisToMasterTable(row);
097    
098                        /* the file to be renamed */
099                        File oldFile = getMaster().getFile(masterRow);
100    
101                        /* the new filename */
102                        String newName  = ((String) getValueAt(row, colNewName));
103                        if(newName.length()<1 || newName == null){
104                            failedCount++;
105                            err[EMPTY_NAME]++;
106                            continue;
107                        }
108    
109                        /* file object corresponding to the new filename */
110                        File newFile = new File(newName);
111                        if(!newFile.isAbsolute()){
112                            newFile = new File(oldFile.getAbsoluteFile().getParent(), newName);
113                        }
114    
115                        /*test if a file with the new filename already exists
116                        and is different from the file to be renamed
117                        {delete it}                 {true}
118                        if so {fail     } if overwrite is {false}.*/
119                        if(newFile.exists() && !newFile.equals(oldFile)){
120                            if(overwrite){
121                                newFile.delete();
122                            } else {
123                                failedCount++;
124                                err[FILE_EXISTS]++;
125                                continue;
126                            }
127                        }
128    
129                        /* rename the file, creating parents if necessary */
130                        if(!oldFile.renameTo(newFile)){
131                            File parent = newFile.getAbsoluteFile().getParentFile();
132                            if(!parent.exists()){
133                                parent.mkdirs();
134                            }
135                            if(!oldFile.renameTo(newFile)){
136                                failedCount++;
137                                err[RENAME_FAILED]++;
138                                continue;
139                            }
140                        }
141    
142                        /* remove empty parents */
143                        if(removeEmptyParents){
144                            oldFile = oldFile.getAbsoluteFile().getParentFile();
145                            File[] children;
146                            while(oldFile != null){
147                                children = oldFile.listFiles();
148                                if(children != null && children.length == 0){
149                                    oldFile.delete();
150                                    oldFile = oldFile.getParentFile();
151                                } else {
152                                    oldFile = null;
153                                }
154                            }
155                        }
156    
157                        /* refresh data tab */
158                        try{
159                            newFile = newFile.getCanonicalFile();
160                        } catch (IOException ignore) {
161                        }
162                        getMaster().silentlySetFile(newFile, masterRow);
163    
164                        /* refresh names tab */
165                        int c;
166                        if ((c = getColumn(Field.FULLPATH)) >= 0){
167                            set(mp3FileReader.getField(newFile, Field.FULLPATH),
168                            row, c);
169                        }
170                        if (colOldName>=0){
171                            set(mp3FileReader.getField(newFile,Field.FILENAME),
172                            row, colOldName);
173                        }
174                        set("", row, colNewName);
175                        set(Boolean.FALSE, row, colInclude);
176                        getMonitor().setProgress(1 + row * 99 / n);
177                        fireTableCellUpdated(row, colNewName);
178                        fireTableCellUpdated(row, colOldName);
179                        fireTableCellUpdated(row, colInclude);
180                    }
181                }
182                getMaster().fireAllColumnsUpdated();
183            }
184    
185            public void finished(){
186                String statusOut = Globals.getMessage("FILE_RENAME_STATUS",
187                        fileCount - failedCount);
188                // "Successfully renamed x file(s)"
189                if(failedCount>0){
190                    statusOut += Globals.getMessage("FILE_RENAME_ERRORS",
191                    new Object[]{
192                        new Integer(failedCount),
193                        new Integer(err[EMPTY_NAME]),
194                        new Integer(err[FILE_EXISTS]),
195                        new Integer(err[RENAME_FAILED])
196                    });
197                    // ", failed to rename x file(s)  [ empty filename:y, file exists:z, rename failure:zz ]."
198                } else {
199                    statusOut += ".";
200                }
201                fireMessageSent(statusOut);
202                fireDataChanged((fileCount-failedCount)*3); //might not be 100% accurate, because the number of columns changed might have been different from 3
203                fireTableDataChanged();
204            }
205        }
206    
207        public void renameFiles(Frame owner, boolean overwrite, boolean rmEmptyParents){
208            (new RenameTask(owner, overwrite, rmEmptyParents)).start();
209        }
210    
211        List getData(){
212            return data;
213        }
214    
215        protected void setData(List v){
216            data = v;
217        }
218    
219        private class BuildNewFilenamesTask extends TimeIntensiveTask{
220            final boolean append;
221            final RenamingPattern pattern;
222            int n;
223    
224            public BuildNewFilenamesTask(Frame owner, RenamingPattern pattern, boolean append){
225                super(owner, Globals.getString("APPLY_PATTERN_PROGRESS"), "");
226                this.append = append;
227                this.pattern = pattern;
228            }
229    
230            public void run(){
231                Mp3FileReader mp3FileReader = new Mp3FileReader(filters);
232                DataTableModel master = getMaster();
233                /* in "append" modus (Shift-Click) get first parts of new
234                * filenames */
235                n = master.getRowCount();
236                int nc = getColumnCount();
237                List newData = new ArrayList(n);
238    
239                getMonitor().setProgress(1);
240                /* rebuild the table (progress 1 - 100) */
241                for(int entry=0; entry<n; entry++){
242                    Object[] newRow = new Object[nc];
243                    int masterRow = master.getRows(entry);
244    
245                    for (int c=0; c<nc; c++){
246                        Field field = getField(c);
247                        int masterC = master.getColumn(field);
248    
249                        if(field == Field.NEW_FILENAME){
250                            /* construct new filename by applying pattern */
251                            String newVal = (String) mp3FileReader.postProcessField(
252                                    Field.NEW_FILENAME,
253                                    pattern.valueOf(master, entry));
254                            if(newVal == null){
255                                newVal = "";
256                            }
257    
258                            /* prepend old value if desired*/
259                            if(append){
260                                int oldRow = getRows(entry);
261                                if(oldRow > 0){
262                                    String oldval = (String) getValueAt(oldRow, c);
263                                    if(oldval != null){
264                                        newVal = oldval + newVal;
265                                    }
266                                }
267                            }
268    
269                            /* set new value */
270                            newRow[c] = newVal;
271    
272                        } else if (field == Field.OLD_FILENAME){
273    
274                            /* old filename */
275                            newRow[c] = mp3FileReader.postProcessField(
276                                Field.OLD_FILENAME,
277                                master.getFile(masterRow).getName());
278    
279                        } else if( masterC  > 0){
280    
281                            /* field exists in data, copy value */
282                            newRow[c] = mp3FileReader.postProcessField(
283                                field,
284                                master.getValueAt(masterRow, masterC));
285    
286                        }
287                        if(newRow[c] == null){
288    
289                            /* field does not exist in data
290                               or new value is null
291                               -> create null value */
292                            newRow[c] = Globals.getNullFor(getColumnClass(c));
293    
294                        }
295                    }
296                    newData.add(newRow);
297                    getMonitor().setProgress(1 + entry * 99 / n);
298                }
299                remAllRowsFromSorter();
300                data = newData;
301                addRowsToSorter(n,n);
302                setSorted(false);
303            }
304    
305            public void finished(){
306                fireTableDataChanged();
307                fireMessageSent(
308                        Globals.getMessage("FILE_TABLE_REFRESH_STATUS", n));
309                /* informs the listening Mp3dingsTable that something has changed
310                  and that it needs to doLayout(), does not increment attached
311                  change counters */
312                fireDataChanged(0);
313            }
314        }
315    
316        public void applyPattern(Frame owner, RenamingPattern pattern,
317                boolean append){
318            savePattern(pattern);
319            if(!discardChanges(owner)){
320                return;
321            }
322            (new BuildNewFilenamesTask(owner, pattern, append)).start();
323        }
324    
325        protected boolean savePattern(RenamingPattern pattern){
326            if(!patternStack.empty()){
327                if( patternStack.peek().equals(pattern)){
328                    return false;
329                } else {
330                    patternStack.remove(pattern);
331                }
332            }
333            patternStack.push(RenamingPattern.newInstance(pattern));
334            try{
335                writePatterns(new File(Globals.getDir("HOME"), "patterns"));
336            } catch (IOException ex){
337                logger.warning("Error saving file renaming patterns.");
338                logger.warning(ex.getMessage());
339            }
340            return true;
341        }
342    
343        protected void writePatterns(File f) throws IOException{
344            FileOutputStream fos = null;
345            ObjectOutputStream out = null;
346            if(f.exists() && !f.isDirectory()){
347                f.delete();
348            }
349            f.mkdirs();
350            int stop = Math.max(-1, patternStack.size() - 11);
351            for(int i = patternStack.size() - 1, j = 0; i > stop; i--, j++){
352                File ff = new File(f, j+".pattern");
353                try {
354                    fos = new FileOutputStream(ff);
355                    out = new ObjectOutputStream(fos);
356                    out.writeObject(patternStack.get(i));
357                } finally {
358                    if(out != null){
359                        out.close();
360                    } else if(fos != null){
361                        fos.close();
362                    }
363                }
364            }
365        }
366    
367        protected void loadPatterns(File f) throws IOException{
368            String lastJavaVersion = Globals.getPrefNode().get("JavaVersion", null);
369            String myJavaVersion = System.getProperty("java.version");
370            if(!f.isDirectory()){
371                return;
372            }
373            if(lastJavaVersion != null && !lastJavaVersion.equals(myJavaVersion)){
374                //Move *.pattern to lastJavaVersion (create if necessary)
375                File ljv = new File(f, lastJavaVersion);
376                if(!ljv.exists() || ljv.isDirectory() || ljv.delete()){
377                    ljv.mkdirs();
378                    File[] patterns = f.listFiles();
379                    for(int i=0; i<patterns.length; i++){
380                        if(patterns[i].isFile()){
381                            patterns[i].renameTo(new File(ljv, patterns[i].getName()));
382                        }
383                    }
384                }
385                //Look for patterns according to own version
386                //Move them to f.
387                if(myJavaVersion != null){
388                    File njv = new File(f, myJavaVersion);
389                    if(njv.isDirectory()){
390                        File[] patterns = njv.listFiles();
391                        for(int i=0; i<patterns.length; i++){
392                            if(patterns[i].isFile()){
393                                patterns[i].renameTo(new File(f, patterns[i].getName()));
394                            }
395                        }
396                    }
397                }
398            }
399            if(myJavaVersion != null){
400                Globals.getPrefNode().put("JavaVersion", myJavaVersion);
401            }
402            FileInputStream fis = null;
403            ObjectInputStream in = null;
404    
405            File[] files = f.listFiles();
406            patternStack.ensureCapacity(files.length);
407            Arrays.sort(files);
408            for(int i = files.length - 1; i > -1; i--){
409                if(!files[i].isFile()){
410                    continue;
411                }
412                Exception deserializationException = null;
413                try{
414                    fis = new FileInputStream(files[i]);
415                    in = new ObjectInputStream(fis);
416                    Object o = null;
417                    try{
418                        o = in.readObject();
419                    } catch (ClassNotFoundException ex){
420                        deserializationException = ex;
421                    } catch (ObjectStreamException ex){
422                        deserializationException = ex;
423                    }
424                    if ( (deserializationException == null) &&
425                         (o instanceof RenamingPattern) ){
426                        patternStack.push(o);
427                    }
428                } finally {
429                    if(in != null){
430                        in.close();
431                    } else if(fis != null){
432                        fis.close();
433                    }
434                    if(deserializationException != null){
435                        String name = files[i].getName();
436                        logger.warning(
437                                "Error restoring pattern " +
438                                name.substring(0, name.indexOf(".pattern")) + ":");
439                        logger.warning(
440                                deserializationException.toString());
441    
442                        File junkFile = files[i].getAbsoluteFile().getParentFile();
443                        junkFile = new File(junkFile, "dead");
444                        junkFile.mkdirs();
445                        junkFile = new File(junkFile, files[i].getName());
446                        if(junkFile.exists()){
447                            junkFile.delete();
448                        }
449                        if(files[i].renameTo(junkFile)){
450                            logger.warning("Moved defective pattern file to "
451                                + junkFile);
452                        }
453                    }
454                }
455            }
456        }
457    
458    
459        /* methods defined in Mp3dingsSortableTabelModel */
460        public Field[] getAllowedFields(){
461            return new Field[]{
462                Field.OLD_FILENAME,
463                Field.NEW_FILENAME,
464                Field.INCLUDE,
465                Field.ARTIST,
466                Field.ORIGINAL_ARTIST,
467                Field.LYRICIST,
468                Field.ORIGINAL_LYRICIST,
469                Field.CONDUCTOR,
470                Field.REMIXED_BY,
471                Field.TITLE,
472                Field.SUBTITLE,
473                Field.CONTENT_GROUP,
474                Field.ALBUM,
475                Field.ORIGINAL_ALBUM,
476                Field.TRACK,
477                Field.PART_OF_SET,
478                Field.SET_SUBTITLE,
479                Field.ISRC,
480                Field.YEAR,
481                Field.GENRE,
482                Field.COMMENT,
483                Field.FULLPATH,
484                Field.LENGTH,
485                Field.SIZE,
486                Field.COMPOSER,
487                Field.BPM,
488                Field.ORIGINAL_FILENAME,
489                Field.COPYRIGHT,
490                Field.ENCODER,
491                Field.MOOD,
492                Field.LANGUAGE,
493                Field.ORCHESTRA,
494                Field.PUBLISHER,
495                Field.KEY,
496                Field.COM_INFO_URL,
497                Field.LEGAL_URL,
498                Field.OFFICIAL_URL,
499                Field.ARTIST_URL,
500                Field.SOURCE_URL,
501                Field.WEB_RADIO_URL,
502                Field.PAY_URL,
503                Field.PUBLISHER_URL
504            };
505        }
506    
507        public Field[] getDefaultFields(){
508            return new Field[]{
509                Field.OLD_FILENAME,
510                Field.NEW_FILENAME,
511                Field.INCLUDE
512            };
513        }
514    
515        public Field[] getPersistentFields(){
516            return new Field[]{
517                Field.NEW_FILENAME,
518                Field.INCLUDE
519            };
520        }
521    
522        public boolean getEditable(Field field){
523            return (field == Field.NEW_FILENAME  || field == Field.INCLUDE);
524        }
525    
526        public String getPrefKey(){
527            return "names";
528        }
529    }