EMMA Coverage Report (generated Sun Apr 20 22:38:01 CEST 2008)
[all classes][net.sf.jomic.ui]

COVERAGE SUMMARY FOR SOURCE FILE [ConvertWorker.java]

nameclass, %method, %block, %line, %
ConvertWorker.java100% (1/1)78%  (7/9)49%  (261/532)59%  (61/104)

COVERAGE BREAKDOWN BY CLASS AND METHOD

nameclass, %method, %block, %line, %
     
class ConvertWorker100% (1/1)78%  (7/9)49%  (261/532)59%  (61/104)
actionPerformed (ActionEvent): void 0%   (0/1)0%   (0/48)0%   (0/10)
addComicsToConvert (List, File, File): void 0%   (0/1)0%   (0/164)0%   (0/25)
ConvertWorker (File, File [], Conversion): void 100% (1/1)75%  (47/63)83%  (9.2/11)
construct (): Object 100% (1/1)79%  (110/139)87%  (31.2/36)
<static initializer> 100% (1/1)80%  (12/15)80%  (0.8/1)
ConvertWorker (): void 100% (1/1)84%  (26/31)98%  (7.8/8)
getComicsToConvert (): List 100% (1/1)88%  (45/51)89%  (8/9)
getNormalizedProgress (long, long): int 100% (1/1)100% (11/11)100% (2/2)
progressChanged (Task): void 100% (1/1)100% (10/10)100% (2/2)

1// Jomic - a viewer for comic book archives.
2// Copyright (C) 2004-2008 Thomas Aglassinger
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// This program is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with this program.  If not, see <http://www.gnu.org/licenses/>.
16package net.sf.jomic.ui;
17 
18import java.awt.event.ActionEvent;
19import java.awt.event.ActionListener;
20import java.io.File;
21import java.util.ArrayList;
22import java.util.Collections;
23import java.util.Iterator;
24import java.util.List;
25 
26import javax.swing.JProgressBar;
27 
28import net.sf.jomic.comic.ComicException;
29import net.sf.jomic.comic.ComicFileFilter;
30import net.sf.jomic.comic.ComicToConvert;
31import net.sf.jomic.comic.Conversion;
32import net.sf.jomic.comic.ConversionReport;
33import net.sf.jomic.comic.ConversionReportItem;
34import net.sf.jomic.comic.ConvertComicTask;
35import net.sf.jomic.common.JomicTools;
36import net.sf.jomic.tools.FileTools;
37import net.sf.jomic.tools.LocaleTools;
38import net.sf.jomic.tools.NaturalCaseInsensitiveOrderComparator;
39import net.sf.jomic.tools.NestedTask;
40import net.sf.jomic.tools.ProgressChangeListener;
41import net.sf.jomic.tools.StringTools;
42import net.sf.jomic.tools.SwingWorker;
43import net.sf.jomic.tools.Task;
44import net.sf.wraplog.Logger;
45 
46/**
47 *  SwingWorker to convert comics.
48 *
49 * @author    Thomas Aglassinger
50 */
51public class ConvertWorker extends SwingWorker implements ActionListener, ProgressChangeListener
52{
53    private ComicFileFilter comicFileFilter;
54    private Conversion conversion;
55    private FileTools fileTools;
56    private File[] filesToConvert;
57    private JomicTools jomicTools;
58    private LocaleTools localeTools;
59    private Logger logger;
60    private JProgressBar progressBar;
61    private StringTools stringTools;
62    private File targetDir;
63 
64    public ConvertWorker(File newTargetDir, File[] newFilesToConvert, Conversion newConversion) {
65        this();
66        assert newTargetDir != null;
67        assert newFilesToConvert != null;
68        assert newFilesToConvert.length != 0;
69        assert newConversion != null;
70 
71        if (logger.isInfoEnabled()) {
72            logger.info("setup worker to convert to: " + stringTools.sourced(newTargetDir));
73        }
74        targetDir = newTargetDir;
75        filesToConvert = newFilesToConvert;
76        conversion = newConversion;
77    }
78 
79    private ConvertWorker() {
80        super();
81        logger = Logger.getLogger(ConvertWorker.class);
82        fileTools = FileTools.instance();
83        jomicTools = JomicTools.instance();
84        stringTools = StringTools.instance();
85        localeTools = LocaleTools.instance();
86        comicFileFilter = new ComicFileFilter();
87    }
88 
89    /**
90     *  Create a list of comics to be converted to <code>targetDir</code>. according to the rules
91     *  listed below.
92     *  <ul>
93     *    <li> For all files in <code>filesToConvert</code>, add a target comic with the same name
94     *    directly in <code>targetDir</code>. For example, /comics/s00paman/issue03.cbz with a
95     *    <code>targetDir</code> /stuff converts the comic to /stuff/issue03.cbz.
96     *    <li> For all directories in <code>filesToConvert</code>, recursively scan the directory
97     *    for comic files, and add target comics in <code>targetDir</code> relative to the path of
98     *    the source comic regarding the initial source directory from which the scan started. For
99     *    example a scan starting at /comics and detecting /comics/s00paman/issue03.cbz with a
100     *    <code>targetDir</code> /stuff converts the comic to /stuff/s00paman/issue03.cbz.
101     *  </ul>
102     *
103     */
104    public List getComicsToConvert() {
105        List result = new ArrayList();
106 
107        for (int i = 0; i < filesToConvert.length; i += 1) {
108            File fileToConvert = filesToConvert[i];
109 
110            if (fileToConvert.isDirectory()) {
111                addComicsToConvert(result, fileToConvert, fileToConvert);
112            } else {
113                ComicToConvert comicToConvert = new ComicToConvert(
114                        fileToConvert.getParentFile(),
115                        targetDir,
116                        fileToConvert.getName(),
117                        conversion.getComicFormatSuffix());
118 
119                result.add(comicToConvert);
120            }
121        }
122        // TODO: remove comics with same source and target
123        // TODO: warn about comics with different source and same target
124        Collections.sort(result, new NaturalCaseInsensitiveOrderComparator());
125        return result;
126    }
127 
128    /**
129     *  Get int-progress from long currentValue normalized in relation to maxValue.
130     */
131    private int getNormalizedProgress(long currentValue, long maxValue) {
132        double value = (double) currentValue / maxValue;
133 
134        return (int) (value * (Integer.MAX_VALUE / 2));
135    }
136 
137    /**
138     *  Called when on of the buttons in report frame is pressed.
139     */
140    public void actionPerformed(ActionEvent event) {
141        try {
142            assert event != null;
143            String command = event.getActionCommand();
144 
145            assert command != null;
146            if (command.equals(ConversionReportFrame.COMMAND_CANCEL)) {
147                interrupt();
148            } else {
149                assert false : "command=" + command;
150            }
151        } catch (Throwable error) {
152            jomicTools.showError(event, error);
153        }
154    }
155 
156    public Object construct() {
157        // Reduce thread priority so the user can still reasonbly view comics
158        // while the conversion takes place in the background.
159        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
160 
161        ConversionReportFrame reportFrame = new ConversionReportFrame();
162 
163        progressBar = reportFrame.getProgressBar();
164        reportFrame.addActionListener(this);
165 
166        try {
167            reportFrame.setVisible(true);
168 
169            List comicsToConvert = getComicsToConvert();
170            Iterator comicRider;
171 
172            // Set up report and compute total size of all comics to convert.
173            ConversionReport report = new ConversionReport();
174            Task[] convertTasks = new Task[comicsToConvert.size()];
175            int convertTaskIndex = 0;
176 
177            comicRider = comicsToConvert.iterator();
178            while (comicRider.hasNext()) {
179                ComicToConvert comicToConvert = (ComicToConvert) comicRider.next();
180                Task convertTask;
181                ConversionReportItem reportItem;
182 
183                report.put(comicToConvert);
184                reportItem = report.get(comicToConvert);
185                convertTask = new ConvertComicTask(
186                        comicToConvert.getSourceComicFile(), comicToConvert.getTargetComicFile(),
187                        conversion, reportItem);
188                convertTasks[convertTaskIndex] = convertTask;
189                convertTaskIndex += 1;
190            }
191 
192            // Convert comics.
193            Task convertAllComicsTask = new NestedTask(convertTasks);
194            long totalSize = convertAllComicsTask.getMaxProgress();
195 
196            progressBar.setMaximum(getNormalizedProgress(totalSize, totalSize));
197            progressBar.setValue(0);
198            progressBar.setIndeterminate(false);
199            reportFrame.setReport(report);
200            convertAllComicsTask.addProgressChangeListener(this);
201            try {
202                convertAllComicsTask.start();
203            } catch (Exception error) {
204                String errorMessage = localeTools.getMessage("errors.cannotConvertComics");
205 
206                throw new ComicException(errorMessage, error);
207            } finally {
208                convertAllComicsTask.removeProgressChangeListener(this);
209            }
210        } finally {
211            reportFrame.removeActionListener(this);
212            reportFrame.done();
213            progressBar = null;
214        }
215 
216        return reportFrame;
217    }
218 
219    /**
220     *  Update progress bar in report frame.
221     */
222    public void progressChanged(Task source) {
223        progressBar.setValue(getNormalizedProgress(source.getProgress(), source.getMaxProgress()));
224    }
225 
226    private void addComicsToConvert(
227            List comicsToBeConverted, File initialDir, File dirToScanForComics) {
228        assert comicsToBeConverted != null;
229        assert initialDir != null;
230        assert dirToScanForComics != null;
231        assert initialDir.equals(dirToScanForComics)
232                || (fileTools.getRelativePath(initialDir, dirToScanForComics) != null);
233 
234        if (logger.isDebugEnabled()) {
235            logger.debug("lookup comics in " + stringTools.sourced(dirToScanForComics));
236        }
237        File[] filesToConsiderForAdding = dirToScanForComics.listFiles();
238 
239        for (int i = 0; i < filesToConsiderForAdding.length; i += 1) {
240            File fileToConsiderForAdding = filesToConsiderForAdding[i];
241 
242            if (fileToConsiderForAdding.isDirectory()) {
243                addComicsToConvert(comicsToBeConverted, initialDir, fileToConsiderForAdding);
244            } else if (comicFileFilter.accept(
245                    fileToConsiderForAdding.getParentFile(), fileToConsiderForAdding.getName())) {
246                String targetSuffix;
247                String comicFormat = conversion.getComicFormat();
248 
249                if (comicFormat.equals(Conversion.COMIC_FORMAT_CBZ)) {
250                    targetSuffix = "cbz";
251                } else if (comicFormat.equals(Conversion.COMIC_FORMAT_PDF)) {
252                    targetSuffix = "pdf";
253                } else {
254                    assert false : "comicFormat=" + stringTools.sourced(comicFormat);
255                    targetSuffix = null;
256                }
257 
258                ComicToConvert comicToConvert = new ComicToConvert(
259                        initialDir,
260                        targetDir,
261                        fileTools.getRelativePath(initialDir, fileToConsiderForAdding),
262                        targetSuffix);
263 
264                comicsToBeConverted.add(comicToConvert);
265            } else {
266                if (logger.isDebugEnabled()) {
267                    logger.debug("ignore for conversion: " + stringTools.sourced(fileToConsiderForAdding));
268                }
269            }
270        }
271    }
272}

[all classes][net.sf.jomic.ui]
EMMA 2.0.4217 (C) Vladimir Roubtsov