(README update)
[fanfix.git] / src / be / nikiroo / fanfix / output / BasicOutput.java
1 package be.nikiroo.fanfix.output;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.ArrayList;
6 import java.util.List;
7
8 import be.nikiroo.fanfix.Instance;
9 import be.nikiroo.fanfix.bundles.StringId;
10 import be.nikiroo.fanfix.data.Chapter;
11 import be.nikiroo.fanfix.data.Paragraph;
12 import be.nikiroo.fanfix.data.Paragraph.ParagraphType;
13 import be.nikiroo.fanfix.data.Story;
14 import be.nikiroo.utils.Progress;
15
16 /**
17 * This class is the base class used by the other output classes. It can be used
18 * outside of this package, and have static method that you can use to get
19 * access to the correct support class.
20 *
21 * @author niki
22 */
23 public abstract class BasicOutput {
24 /**
25 * The supported output types for which we can get a {@link BasicOutput}
26 * object.
27 *
28 * @author niki
29 */
30 public enum OutputType {
31 /** EPUB files created with this program */
32 EPUB,
33 /** Pure text file with some rules */
34 TEXT,
35 /** TEXT but with associated .info file */
36 INFO_TEXT,
37 /** DEBUG output to console */
38 SYSOUT,
39 /** ZIP with (PNG) images */
40 CBZ,
41 /** LaTeX file with "book" template */
42 LATEX,
43 /** HTML files in a dedicated directory */
44 HTML,
45
46 ;
47
48 public String toString() {
49 return super.toString().toLowerCase();
50 }
51
52 /**
53 * A description of this output type.
54 *
55 * @param longDesc
56 * TRUE for the long description, FALSE for the short one
57 *
58 * @return the description
59 */
60 public String getDesc(boolean longDesc) {
61 StringId id = longDesc ? StringId.OUTPUT_DESC
62 : StringId.OUTPUT_DESC_SHORT;
63
64 String desc = Instance.getTrans().getStringX(id, this.name());
65
66 if (desc == null) {
67 desc = Instance.getTrans().getString(id, this);
68 }
69
70 if (desc == null) {
71 desc = this.toString();
72 }
73
74 return desc;
75 }
76
77 /**
78 * The default extension to add to the output files.
79 *
80 * @param readerTarget
81 * the target to point to to read the {@link Story} (for
82 * instance, the main entry point if this {@link Story} is in
83 * a directory bundle)
84 *
85 * @return the extension
86 */
87 public String getDefaultExtension(boolean readerTarget) {
88 BasicOutput output = BasicOutput.getOutput(this, false);
89 if (output != null) {
90 return output.getDefaultExtension(readerTarget);
91 }
92
93 return null;
94 }
95
96 /**
97 * Call {@link OutputType#valueOf(String.toUpperCase())}.
98 *
99 * @param typeName
100 * the possible type name
101 *
102 * @return NULL or the type
103 */
104 public static OutputType valueOfUC(String typeName) {
105 return OutputType.valueOf(typeName == null ? null : typeName
106 .toUpperCase());
107 }
108
109 /**
110 * Call {@link OutputType#valueOf(String.toUpperCase())} but return NULL
111 * for NULL and empty instead of raising an exception.
112 *
113 * @param typeName
114 * the possible type name
115 *
116 * @return NULL or the type
117 */
118 public static OutputType valueOfNullOkUC(String typeName) {
119 if (typeName == null || typeName.isEmpty()) {
120 return null;
121 }
122
123 return OutputType.valueOfUC(typeName);
124 }
125
126 /**
127 * Call {@link OutputType#valueOf(String.toUpperCase())} but return NULL
128 * in case of error instead of raising an exception.
129 *
130 * @param typeName
131 * the possible type name
132 *
133 * @return NULL or the type
134 */
135 public static OutputType valueOfAllOkUC(String typeName) {
136 try {
137 return OutputType.valueOfUC(typeName);
138 } catch (Exception e) {
139 return null;
140 }
141 }
142 }
143
144 /** The creator name (this program, by me!) */
145 static final String EPUB_CREATOR = "Fanfix (by Niki)";
146
147 /** The current best name for an image */
148 private String imageName;
149 private File targetDir;
150 private String targetName;
151 private OutputType type;
152 private boolean writeCover;
153 private boolean writeInfo;
154 private Progress storyPg;
155 private Progress chapPg;
156
157 /**
158 * Process the {@link Story} into the given target.
159 *
160 * @param story
161 * the {@link Story} to export
162 * @param target
163 * the target where to save to (will not necessary be taken as is
164 * by the processor, for instance an extension can be added)
165 * @param pg
166 * the optional progress reporter
167 *
168 * @return the actual main target saved, which can be slightly different
169 * that the input one
170 *
171 * @throws IOException
172 * in case of I/O error
173 */
174 public File process(Story story, String target, Progress pg)
175 throws IOException {
176 storyPg = pg;
177
178 target = new File(target).getAbsolutePath();
179 File targetDir = new File(target).getParentFile();
180 String targetName = new File(target).getName();
181
182 String ext = getDefaultExtension(false);
183 if (ext != null && !ext.isEmpty()) {
184 if (targetName.toLowerCase().endsWith(ext)) {
185 targetName = targetName.substring(0,
186 targetName.length() - ext.length());
187 }
188 }
189
190 return process(story, targetDir, targetName);
191 }
192
193 /**
194 * Process the {@link Story} into the given target.
195 * <p>
196 * This method is expected to be overridden in most cases.
197 *
198 * @param story
199 * the {@link Story} to export
200 * @param targetDir
201 * the target dir where to save to
202 * @param targetName
203 * the target filename (will not necessary be taken as is by the
204 * processor, for instance an extension can be added)
205 *
206 *
207 * @return the actual main target saved, which can be slightly different
208 * that the input one
209 *
210 * @throws IOException
211 * in case of I/O error
212 */
213 protected File process(Story story, File targetDir, String targetName)
214 throws IOException {
215 this.targetDir = targetDir;
216 this.targetName = targetName;
217
218 writeStory(story);
219
220 return null;
221 }
222
223 /**
224 * The output type.
225 *
226 * @return the type
227 */
228 public OutputType getType() {
229 return type;
230 }
231
232 /**
233 * The output type.
234 *
235 * @param type
236 * the new type
237 * @param infoCover
238 * TRUE to enable the creation of a .info file and a cover if
239 * possible
240 *
241 * @return this
242 */
243 protected BasicOutput setType(OutputType type, boolean writeCover,
244 boolean writeInfo) {
245 this.type = type;
246 this.writeCover = writeCover;
247 this.writeInfo = writeInfo;
248
249 return this;
250 }
251
252 /**
253 * The default extension to add to the output files.
254 *
255 * @param readerTarget
256 * the target to point to to read the {@link Story} (for
257 * instance, the main entry point if this {@link Story} is in a
258 * directory bundle)
259 *
260 * @return the extension
261 */
262 public String getDefaultExtension(boolean readerTarget) {
263 return "";
264 }
265
266 protected void writeStoryHeader(Story story) throws IOException {
267 }
268
269 protected void writeChapterHeader(Chapter chap) throws IOException {
270 }
271
272 protected void writeParagraphHeader(Paragraph para) throws IOException {
273 }
274
275 protected void writeStoryFooter(Story story) throws IOException {
276 }
277
278 protected void writeChapterFooter(Chapter chap) throws IOException {
279 }
280
281 protected void writeParagraphFooter(Paragraph para) throws IOException {
282 }
283
284 protected void writeStory(Story story) throws IOException {
285 if (storyPg == null) {
286 storyPg = new Progress(0, story.getChapters().size() + 2);
287 } else {
288 storyPg.setMinMax(0, story.getChapters().size() + 2);
289 }
290
291 String chapterNameNum = String.format("%03d", 0);
292 String paragraphNumber = String.format("%04d", 0);
293 imageName = paragraphNumber + "_" + chapterNameNum + ".png";
294
295 if (story.getMeta() != null) {
296 story.getMeta().setType("" + getType());
297 }
298
299 if (writeCover) {
300 InfoCover.writeCover(targetDir, targetName, story.getMeta());
301 }
302 if (writeInfo) {
303 InfoCover.writeInfo(targetDir, targetName, story.getMeta());
304 }
305
306 storyPg.setProgress(1);
307
308 List<Progress> chapPgs = new ArrayList<Progress>(story.getChapters()
309 .size());
310 for (Chapter chap : story) {
311 chapPg = new Progress(0, chap.getParagraphs().size());
312 storyPg.addProgress(chapPg, 1);
313 chapPgs.add(chapPg);
314 chapPg = null;
315 }
316
317 writeStoryHeader(story);
318 for (int i = 0; i < story.getChapters().size(); i++) {
319 chapPg = chapPgs.get(i);
320 writeChapter(story.getChapters().get(i));
321 chapPg.setProgress(chapPg.getMax());
322 chapPg = null;
323 }
324 writeStoryFooter(story);
325
326 storyPg.setProgress(storyPg.getMax());
327 storyPg = null;
328 }
329
330 protected void writeChapter(Chapter chap) throws IOException {
331 String chapterNameNum;
332 if (chap.getName() == null || chap.getName().isEmpty()) {
333 chapterNameNum = String.format("%03d", chap.getNumber());
334 } else {
335 chapterNameNum = String.format("%03d", chap.getNumber()) + "_"
336 + chap.getName().replace(" ", "_");
337 }
338
339 int num = 0;
340 String paragraphNumber = String.format("%04d", num++);
341 imageName = chapterNameNum + "_" + paragraphNumber + ".png";
342
343 writeChapterHeader(chap);
344 int i = 1;
345 for (Paragraph para : chap) {
346 paragraphNumber = String.format("%04d", num++);
347 imageName = chapterNameNum + "_" + paragraphNumber + ".png";
348 writeParagraph(para);
349 if (chapPg != null) {
350 chapPg.setProgress(i++);
351 }
352 }
353 writeChapterFooter(chap);
354 }
355
356 protected void writeParagraph(Paragraph para) throws IOException {
357 writeParagraphHeader(para);
358 writeTextLine(para.getType(), para.getContent());
359 writeParagraphFooter(para);
360 }
361
362 protected void writeTextLine(ParagraphType type, String line)
363 throws IOException {
364 }
365
366 /**
367 * Return the current best guess for an image name, based upon the current
368 * {@link Chapter} and {@link Paragraph}.
369 *
370 * @param prefix
371 * add the original target name as a prefix
372 *
373 * @return the guessed name
374 */
375 protected String getCurrentImageBestName(boolean prefix) {
376 if (prefix) {
377 return targetName + "_" + imageName;
378 }
379
380 return imageName;
381 }
382
383 /**
384 * Return the given word or sentence as <b>bold</b>.
385 *
386 * @param word
387 * the input
388 *
389 * @return the bold output
390 */
391 protected String enbold(String word) {
392 return word;
393 }
394
395 /**
396 * Return the given word or sentence as <i>italic</i>.
397 *
398 * @param word
399 * the input
400 *
401 * @return the italic output
402 */
403 protected String italize(String word) {
404 return word;
405 }
406
407 /**
408 * Decorate the given text with <b>bold</b> and <i>italic</i> words,
409 * according to {@link BasicOutput#enbold(String)} and
410 * {@link BasicOutput#italize(String)}.
411 *
412 * @param text
413 * the input
414 *
415 * @return the decorated output
416 */
417 protected String decorateText(String text) {
418 StringBuilder builder = new StringBuilder();
419
420 int bold = -1;
421 int italic = -1;
422 char prev = '\0';
423 for (char car : text.toCharArray()) {
424 switch (car) {
425 case '*':
426 if (bold >= 0 && prev != ' ') {
427 String data = builder.substring(bold);
428 builder.setLength(bold);
429 builder.append(enbold(data));
430 bold = -1;
431 } else if (bold < 0
432 && (prev == ' ' || prev == '\0' || prev == '\n')) {
433 bold = builder.length();
434 } else {
435 builder.append(car);
436 }
437
438 break;
439 case '_':
440 if (italic >= 0 && prev != ' ') {
441 String data = builder.substring(italic);
442 builder.setLength(italic);
443 builder.append(enbold(data));
444 italic = -1;
445 } else if (italic < 0
446 && (prev == ' ' || prev == '\0' || prev == '\n')) {
447 italic = builder.length();
448 } else {
449 builder.append(car);
450 }
451
452 break;
453 default:
454 builder.append(car);
455 break;
456 }
457
458 prev = car;
459 }
460
461 if (bold >= 0) {
462 builder.insert(bold, '*');
463 }
464
465 if (italic >= 0) {
466 builder.insert(italic, '_');
467 }
468
469 return builder.toString();
470 }
471
472 /**
473 * Return a {@link BasicOutput} object compatible with the given
474 * {@link OutputType}.
475 *
476 * @param type
477 * the type
478 * @param infoCover
479 * force the <tt>.info</tt> file and the cover to be saved next
480 * to the main target file
481 *
482 * @return the {@link BasicOutput}
483 */
484 public static BasicOutput getOutput(OutputType type, boolean infoCover) {
485 if (type != null) {
486 switch (type) {
487 case EPUB:
488 return new Epub().setType(type, infoCover, infoCover);
489 case TEXT:
490 return new Text().setType(type, true, infoCover);
491 case INFO_TEXT:
492 return new InfoText().setType(type, true, true);
493 case SYSOUT:
494 return new Sysout().setType(type, false, false);
495 case CBZ:
496 return new Cbz().setType(type, infoCover, infoCover);
497 case LATEX:
498 return new LaTeX().setType(type, infoCover, infoCover);
499 case HTML:
500 return new Html().setType(type, infoCover, infoCover);
501 }
502 }
503
504 return null;
505 }
506 }