Improve remote, fix bugs, update nikiroo-utils
[nikiroo-utils.git] / src / be / nikiroo / fanfix / reader / GuiReaderFrame.java
1 package be.nikiroo.fanfix.reader;
2
3 import java.awt.BorderLayout;
4 import java.awt.Color;
5 import java.awt.Frame;
6 import java.awt.Toolkit;
7 import java.awt.datatransfer.DataFlavor;
8 import java.awt.event.ActionEvent;
9 import java.awt.event.ActionListener;
10 import java.awt.event.KeyEvent;
11 import java.awt.event.MouseEvent;
12 import java.awt.event.WindowEvent;
13 import java.io.File;
14 import java.io.IOException;
15 import java.net.URL;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Map.Entry;
21
22 import javax.swing.BoxLayout;
23 import javax.swing.JFileChooser;
24 import javax.swing.JFrame;
25 import javax.swing.JLabel;
26 import javax.swing.JMenu;
27 import javax.swing.JMenuBar;
28 import javax.swing.JMenuItem;
29 import javax.swing.JOptionPane;
30 import javax.swing.JPanel;
31 import javax.swing.JPopupMenu;
32 import javax.swing.JScrollPane;
33 import javax.swing.SwingConstants;
34 import javax.swing.SwingUtilities;
35 import javax.swing.filechooser.FileFilter;
36 import javax.swing.filechooser.FileNameExtensionFilter;
37
38 import be.nikiroo.fanfix.Instance;
39 import be.nikiroo.fanfix.bundles.Config;
40 import be.nikiroo.fanfix.bundles.UiConfig;
41 import be.nikiroo.fanfix.data.MetaData;
42 import be.nikiroo.fanfix.data.Story;
43 import be.nikiroo.fanfix.library.LocalLibrary;
44 import be.nikiroo.fanfix.output.BasicOutput.OutputType;
45 import be.nikiroo.fanfix.reader.GuiReaderBook.BookActionListener;
46 import be.nikiroo.utils.Progress;
47 import be.nikiroo.utils.Version;
48 import be.nikiroo.utils.ui.ConfigEditor;
49 import be.nikiroo.utils.ui.ProgressBar;
50
51 /**
52 * A {@link Frame} that will show a {@link GuiReaderBook} item for each
53 * {@link Story} in the main cache ({@link Instance#getCache()}), and offer a
54 * way to copy them to the {@link GuiReader} cache (
55 * {@link BasicReader#getLibrary()}), read them, delete them...
56 *
57 * @author niki
58 */
59 class GuiReaderFrame extends JFrame {
60 private static final long serialVersionUID = 1L;
61 private GuiReader reader;
62 private Map<GuiReaderGroup, String> booksByType;
63 private Map<GuiReaderGroup, String> booksByAuthor;
64 private JPanel pane;
65 private Color color;
66 private ProgressBar pgBar;
67 private JMenuBar bar;
68 private GuiReaderBook selectedBook;
69 private boolean words; // words or authors (secondary info on books)
70
71 /**
72 * A {@link Runnable} with a {@link Story} parameter.
73 *
74 * @author niki
75 */
76 private interface StoryRunnable {
77 /**
78 * Run the action.
79 *
80 * @param story
81 * the story
82 */
83 public void run(Story story);
84 }
85
86 /**
87 * Create a new {@link GuiReaderFrame}.
88 *
89 * @param reader
90 * the associated {@link GuiReader} to forward some commands and
91 * access its {@link LocalLibrary}
92 * @param type
93 * the type of {@link Story} to load, or NULL for all types
94 */
95 public GuiReaderFrame(GuiReader reader, String type) {
96 super(String.format("Fanfix %s Library", Version.getCurrentVersion()));
97
98 this.reader = reader;
99
100 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
101 setSize(800, 600);
102 setLayout(new BorderLayout());
103
104 pane = new JPanel();
105 pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
106
107 color = Instance.getUiConfig().getColor(UiConfig.BACKGROUND_COLOR);
108 if (color != null) {
109 setBackground(color);
110 pane.setBackground(color);
111 }
112
113 JScrollPane scroll = new JScrollPane(pane);
114 scroll.getVerticalScrollBar().setUnitIncrement(16);
115 add(scroll, BorderLayout.CENTER);
116
117 String message = reader.getLibrary().getLibraryName();
118 if (!message.isEmpty()) {
119 JLabel name = new JLabel(message, SwingConstants.CENTER);
120 add(name, BorderLayout.NORTH);
121 }
122
123 pgBar = new ProgressBar();
124 add(pgBar, BorderLayout.SOUTH);
125
126 pgBar.addActionListener(new ActionListener() {
127 @Override
128 public void actionPerformed(ActionEvent e) {
129 invalidate();
130 pgBar.setProgress(null);
131 validate();
132 setEnabled(true);
133 }
134 });
135
136 pgBar.addUpdateListener(new ActionListener() {
137 @Override
138 public void actionPerformed(ActionEvent e) {
139 invalidate();
140 validate();
141 repaint();
142 }
143 });
144
145 booksByType = new HashMap<GuiReaderGroup, String>();
146 booksByAuthor = new HashMap<GuiReaderGroup, String>();
147
148 pane.setVisible(false);
149 final Progress pg = new Progress();
150 final String typeF = type;
151 outOfUi(pg, new Runnable() {
152 @Override
153 public void run() {
154 GuiReaderFrame.this.reader.getLibrary().refresh(false, pg);
155 invalidate();
156 setJMenuBar(createMenu());
157 addBookPane(typeF, true);
158 refreshBooks();
159 validate();
160 pane.setVisible(true);
161 }
162 });
163
164 setVisible(true);
165 }
166
167 private void addSourcePanes() {
168 // Sources -> i18n
169 GuiReaderGroup bookPane = new GuiReaderGroup(reader, "Sources", color);
170
171 List<MetaData> sources = new ArrayList<MetaData>();
172 for (String source : reader.getLibrary().getSources()) {
173 MetaData mSource = new MetaData();
174 mSource.setLuid(null);
175 mSource.setTitle(source);
176 mSource.setSource(source);
177 sources.add(mSource);
178 }
179
180 bookPane.refreshBooks(sources, false);
181
182 this.invalidate();
183 pane.invalidate();
184 pane.add(bookPane);
185 pane.validate();
186 this.validate();
187
188 bookPane.setActionListener(new BookActionListener() {
189 @Override
190 public void select(GuiReaderBook book) {
191 selectedBook = book;
192 }
193
194 @Override
195 public void popupRequested(GuiReaderBook book, MouseEvent e) {
196 JPopupMenu popup = new JPopupMenu();
197 popup.add(createMenuItemOpenBook());
198 popup.show(e.getComponent(), e.getX(), e.getY());
199 }
200
201 @Override
202 public void action(final GuiReaderBook book) {
203 removeBookPanes();
204 addBookPane(book.getMeta().getSource(), true);
205 refreshBooks();
206 }
207 });
208 }
209
210 /**
211 * Add a new {@link GuiReaderGroup} on the frame to display the books of the
212 * selected type or author.
213 *
214 * @param value
215 * the author or the type, or NULL to get all the
216 * authors-or-types
217 * @param type
218 * TRUE for type, FALSE for author
219 */
220 private void addBookPane(String value, boolean type) {
221 if (value == null) {
222 if (type) {
223 if (Instance.getUiConfig().getBoolean(UiConfig.SOURCE_PAGE,
224 false)) {
225 addSourcePanes();
226 } else {
227 for (String tt : reader.getLibrary().getSources()) {
228 if (tt != null) {
229 addBookPane(tt, type);
230 }
231 }
232 }
233 } else {
234 for (String tt : reader.getLibrary().getAuthors()) {
235 if (tt != null) {
236 addBookPane(tt, type);
237 }
238 }
239 }
240
241 return;
242 }
243
244 GuiReaderGroup bookPane = new GuiReaderGroup(reader, value, color);
245 if (type) {
246 booksByType.put(bookPane, value);
247 } else {
248 booksByAuthor.put(bookPane, value);
249 }
250
251 this.invalidate();
252 pane.invalidate();
253 pane.add(bookPane);
254 pane.validate();
255 this.validate();
256
257 bookPane.setActionListener(new BookActionListener() {
258 @Override
259 public void select(GuiReaderBook book) {
260 selectedBook = book;
261 }
262
263 @Override
264 public void popupRequested(GuiReaderBook book, MouseEvent e) {
265 JPopupMenu popup = new JPopupMenu();
266 popup.add(createMenuItemOpenBook());
267 popup.addSeparator();
268 popup.add(createMenuItemExport());
269 popup.add(createMenuItemMove());
270 popup.add(createMenuItemSetCover());
271 popup.add(createMenuItemClearCache());
272 popup.add(createMenuItemRedownload());
273 popup.addSeparator();
274 popup.add(createMenuItemDelete());
275 popup.show(e.getComponent(), e.getX(), e.getY());
276 }
277
278 @Override
279 public void action(final GuiReaderBook book) {
280 openBook(book);
281 }
282 });
283 }
284
285 private void removeBookPanes() {
286 booksByType.clear();
287 booksByAuthor.clear();
288 pane.invalidate();
289 this.invalidate();
290 pane.removeAll();
291 pane.validate();
292 this.validate();
293 }
294
295 /**
296 * Refresh the list of {@link GuiReaderBook}s from disk.
297 *
298 */
299 private void refreshBooks() {
300 for (GuiReaderGroup group : booksByType.keySet()) {
301 List<MetaData> stories = reader.getLibrary().getListBySource(
302 booksByType.get(group));
303 group.refreshBooks(stories, words);
304 }
305
306 for (GuiReaderGroup group : booksByAuthor.keySet()) {
307 List<MetaData> stories = reader.getLibrary().getListByAuthor(
308 booksByAuthor.get(group));
309 group.refreshBooks(stories, words);
310 }
311
312 pane.repaint();
313 this.repaint();
314 }
315
316 /**
317 * Create the main menu bar.
318 *
319 * @return the bar
320 */
321 private JMenuBar createMenu() {
322 bar = new JMenuBar();
323
324 JMenu file = new JMenu("File");
325 file.setMnemonic(KeyEvent.VK_F);
326
327 JMenuItem imprt = new JMenuItem("Import URL...", KeyEvent.VK_U);
328 imprt.addActionListener(new ActionListener() {
329 @Override
330 public void actionPerformed(ActionEvent e) {
331 imprt(true);
332 }
333 });
334 JMenuItem imprtF = new JMenuItem("Import File...", KeyEvent.VK_F);
335 imprtF.addActionListener(new ActionListener() {
336 @Override
337 public void actionPerformed(ActionEvent e) {
338 imprt(false);
339 }
340 });
341 JMenuItem exit = new JMenuItem("Exit", KeyEvent.VK_X);
342 exit.addActionListener(new ActionListener() {
343 @Override
344 public void actionPerformed(ActionEvent e) {
345 GuiReaderFrame.this.dispatchEvent(new WindowEvent(
346 GuiReaderFrame.this, WindowEvent.WINDOW_CLOSING));
347 }
348 });
349
350 file.add(createMenuItemOpenBook());
351 file.add(createMenuItemExport());
352 file.add(createMenuItemMove());
353 file.addSeparator();
354 file.add(imprt);
355 file.add(imprtF);
356 file.addSeparator();
357 file.add(exit);
358
359 bar.add(file);
360
361 JMenu edit = new JMenu("Edit");
362 edit.setMnemonic(KeyEvent.VK_E);
363
364 edit.add(createMenuItemClearCache());
365 edit.add(createMenuItemRedownload());
366 edit.addSeparator();
367 edit.add(createMenuItemDelete());
368
369 bar.add(edit);
370
371 JMenu view = new JMenu("View");
372 view.setMnemonic(KeyEvent.VK_V);
373 JMenuItem vauthors = new JMenuItem("Author");
374 vauthors.setMnemonic(KeyEvent.VK_A);
375 vauthors.addActionListener(new ActionListener() {
376 @Override
377 public void actionPerformed(ActionEvent e) {
378 words = false;
379 refreshBooks();
380 }
381 });
382 view.add(vauthors);
383 JMenuItem vwords = new JMenuItem("Word count");
384 vwords.setMnemonic(KeyEvent.VK_W);
385 vwords.addActionListener(new ActionListener() {
386 @Override
387 public void actionPerformed(ActionEvent e) {
388 words = true;
389 refreshBooks();
390 }
391 });
392 view.add(vwords);
393 bar.add(view);
394
395 JMenu sources = new JMenu("Sources");
396 sources.setMnemonic(KeyEvent.VK_S);
397
398 List<String> tt = reader.getLibrary().getSources();
399 tt.add(0, null);
400 for (final String type : tt) {
401 JMenuItem item = new JMenuItem(type == null ? "All" : type);
402 item.addActionListener(new ActionListener() {
403 @Override
404 public void actionPerformed(ActionEvent e) {
405 removeBookPanes();
406 addBookPane(type, true);
407 refreshBooks();
408 }
409 });
410 sources.add(item);
411
412 if (type == null) {
413 sources.addSeparator();
414 }
415 }
416
417 bar.add(sources);
418
419 JMenu authors = new JMenu("Authors");
420 authors.setMnemonic(KeyEvent.VK_A);
421
422 List<String> aa = reader.getLibrary().getAuthors();
423 aa.add(0, null);
424 for (final String author : aa) {
425 JMenuItem item = new JMenuItem(author == null ? "All"
426 : author.isEmpty() ? "[unknown]" : author);
427 item.addActionListener(new ActionListener() {
428 @Override
429 public void actionPerformed(ActionEvent e) {
430 removeBookPanes();
431 addBookPane(author, false);
432 refreshBooks();
433 }
434 });
435 authors.add(item);
436
437 if (author == null || author.isEmpty()) {
438 authors.addSeparator();
439 }
440 }
441
442 bar.add(authors);
443
444 JMenu options = new JMenu("Options");
445 options.setMnemonic(KeyEvent.VK_O);
446 options.add(createMenuItemConfig());
447 options.add(createMenuItemUiConfig());
448 bar.add(options);
449
450 return bar;
451 }
452
453 /**
454 * Create the Fanfix Configuration menu item.
455 *
456 * @return the item
457 */
458 private JMenuItem createMenuItemConfig() {
459 final String title = "Fanfix Configuration";
460 JMenuItem item = new JMenuItem(title);
461 item.setMnemonic(KeyEvent.VK_F);
462
463 item.addActionListener(new ActionListener() {
464 @Override
465 public void actionPerformed(ActionEvent e) {
466 ConfigEditor<Config> ed = new ConfigEditor<Config>(
467 Config.class, Instance.getConfig(),
468 "This is where you configure the options of the program.");
469 JFrame frame = new JFrame(title);
470 frame.add(ed);
471 frame.setSize(800, 600);
472 frame.setVisible(true);
473 }
474 });
475
476 return item;
477 }
478
479 /**
480 * Create the UI Configuration menu item.
481 *
482 * @return the item
483 */
484 private JMenuItem createMenuItemUiConfig() {
485 final String title = "UI Configuration";
486 JMenuItem item = new JMenuItem(title);
487 item.setMnemonic(KeyEvent.VK_U);
488
489 item.addActionListener(new ActionListener() {
490 @Override
491 public void actionPerformed(ActionEvent e) {
492 ConfigEditor<UiConfig> ed = new ConfigEditor<UiConfig>(
493 UiConfig.class, Instance.getUiConfig(),
494 "This is where you configure the graphical appearence of the program.");
495 JFrame frame = new JFrame(title);
496 frame.add(ed);
497 frame.setSize(800, 600);
498 frame.setVisible(true);
499 }
500 });
501
502 return item;
503 }
504
505 /**
506 * Create the export menu item.
507 *
508 * @return the item
509 */
510 private JMenuItem createMenuItemExport() {
511 final JFileChooser fc = new JFileChooser();
512 fc.setAcceptAllFileFilterUsed(false);
513
514 final Map<FileFilter, OutputType> filters = new HashMap<FileFilter, OutputType>();
515 for (OutputType type : OutputType.values()) {
516 String ext = type.getDefaultExtension(false);
517 String desc = type.getDesc(false);
518
519 if (ext == null || ext.isEmpty()) {
520 filters.put(createAllFilter(desc), type);
521 } else {
522 filters.put(new FileNameExtensionFilter(desc, ext), type);
523 }
524 }
525
526 // First the "ALL" filters, then, the extension filters
527 for (Entry<FileFilter, OutputType> entry : filters.entrySet()) {
528 if (!(entry.getKey() instanceof FileNameExtensionFilter)) {
529 fc.addChoosableFileFilter(entry.getKey());
530 }
531 }
532 for (Entry<FileFilter, OutputType> entry : filters.entrySet()) {
533 if (entry.getKey() instanceof FileNameExtensionFilter) {
534 fc.addChoosableFileFilter(entry.getKey());
535 }
536 }
537 //
538
539 JMenuItem export = new JMenuItem("Save as...", KeyEvent.VK_S);
540 export.addActionListener(new ActionListener() {
541 @Override
542 public void actionPerformed(ActionEvent e) {
543 if (selectedBook != null) {
544 fc.showDialog(GuiReaderFrame.this, "Save");
545 if (fc.getSelectedFile() != null) {
546 final OutputType type = filters.get(fc.getFileFilter());
547 final String path = fc.getSelectedFile()
548 .getAbsolutePath()
549 + type.getDefaultExtension(false);
550 final Progress pg = new Progress();
551 outOfUi(pg, new Runnable() {
552 @Override
553 public void run() {
554 try {
555 reader.getLibrary().export(
556 selectedBook.getMeta().getLuid(),
557 type, path, pg);
558 } catch (IOException e) {
559 Instance.syserr(e);
560 }
561 }
562 });
563 }
564 }
565 }
566 });
567
568 return export;
569 }
570
571 /**
572 * Create a {@link FileFilter} that accepts all files and return the given
573 * description.
574 *
575 * @param desc
576 * the description
577 *
578 * @return the filter
579 */
580 private FileFilter createAllFilter(final String desc) {
581 return new FileFilter() {
582 @Override
583 public String getDescription() {
584 return desc;
585 }
586
587 @Override
588 public boolean accept(File f) {
589 return true;
590 }
591 };
592 }
593
594 /**
595 * Create the refresh (delete cache) menu item.
596 *
597 * @return the item
598 */
599 private JMenuItem createMenuItemClearCache() {
600 JMenuItem refresh = new JMenuItem("Clear cache", KeyEvent.VK_C);
601 refresh.addActionListener(new ActionListener() {
602 @Override
603 public void actionPerformed(ActionEvent e) {
604 if (selectedBook != null) {
605 outOfUi(null, new Runnable() {
606 @Override
607 public void run() {
608 reader.clearLocalReaderCache(selectedBook.getMeta()
609 .getLuid());
610 selectedBook.setCached(false);
611 GuiReaderBook.clearIcon(selectedBook.getMeta());
612 SwingUtilities.invokeLater(new Runnable() {
613 @Override
614 public void run() {
615 selectedBook.repaint();
616 }
617 });
618 }
619 });
620 }
621 }
622 });
623
624 return refresh;
625 }
626
627 /**
628 * Create the delete menu item.
629 *
630 * @return the item
631 */
632 private JMenuItem createMenuItemMove() {
633 JMenu moveTo = new JMenu("Move to...");
634 moveTo.setMnemonic(KeyEvent.VK_M);
635
636 List<String> types = new ArrayList<String>();
637 types.add(null);
638 types.addAll(reader.getLibrary().getSources());
639
640 for (String type : types) {
641 JMenuItem item = new JMenuItem(type == null ? "New type..." : type);
642
643 moveTo.add(item);
644 if (type == null) {
645 moveTo.addSeparator();
646 }
647
648 final String ftype = type;
649 item.addActionListener(new ActionListener() {
650 @Override
651 public void actionPerformed(ActionEvent e) {
652 if (selectedBook != null) {
653 String type = ftype;
654 if (type == null) {
655 Object rep = JOptionPane.showInputDialog(
656 GuiReaderFrame.this, "Move to:",
657 "Moving story",
658 JOptionPane.QUESTION_MESSAGE, null, null,
659 selectedBook.getMeta().getSource());
660
661 if (rep == null) {
662 return;
663 }
664
665 type = rep.toString();
666 }
667
668 final String ftype = type;
669 outOfUi(null, new Runnable() {
670 @Override
671 public void run() {
672 reader.changeType(selectedBook.getMeta()
673 .getLuid(), ftype);
674
675 selectedBook = null;
676
677 SwingUtilities.invokeLater(new Runnable() {
678 @Override
679 public void run() {
680 setJMenuBar(createMenu());
681 }
682 });
683 }
684 });
685 }
686 }
687 });
688 }
689
690 return moveTo;
691 }
692
693 /**
694 * Create the redownload (then delete original) menu item.
695 *
696 * @return the item
697 */
698 private JMenuItem createMenuItemRedownload() {
699 JMenuItem refresh = new JMenuItem("Redownload", KeyEvent.VK_R);
700 refresh.addActionListener(new ActionListener() {
701 @Override
702 public void actionPerformed(ActionEvent e) {
703 if (selectedBook != null) {
704 final MetaData meta = selectedBook.getMeta();
705 imprt(meta.getUrl(), new StoryRunnable() {
706 @Override
707 public void run(Story story) {
708 reader.delete(meta.getLuid());
709 GuiReaderFrame.this.selectedBook = null;
710 MetaData newMeta = story.getMeta();
711 if (!newMeta.getSource().equals(meta.getSource())) {
712 reader.changeType(newMeta.getLuid(),
713 meta.getSource());
714 }
715 }
716 }, "Removing old copy");
717 }
718 }
719 });
720
721 return refresh;
722 }
723
724 /**
725 * Create the delete menu item.
726 *
727 * @return the item
728 */
729 private JMenuItem createMenuItemDelete() {
730 JMenuItem delete = new JMenuItem("Delete", KeyEvent.VK_D);
731 delete.addActionListener(new ActionListener() {
732 @Override
733 public void actionPerformed(ActionEvent e) {
734 if (selectedBook != null) {
735 outOfUi(null, new Runnable() {
736 @Override
737 public void run() {
738 reader.delete(selectedBook.getMeta().getLuid());
739 selectedBook = null;
740 }
741 });
742 }
743 }
744 });
745
746 return delete;
747 }
748
749 /**
750 * Create the open menu item for a book or a source (no LUID).
751 *
752 * @return the item
753 */
754 private JMenuItem createMenuItemOpenBook() {
755 JMenuItem open = new JMenuItem("Open", KeyEvent.VK_O);
756 open.addActionListener(new ActionListener() {
757 @Override
758 public void actionPerformed(ActionEvent e) {
759 if (selectedBook != null) {
760 if (selectedBook.getMeta().getLuid() == null) {
761 removeBookPanes();
762 addBookPane(selectedBook.getMeta().getSource(), true);
763 refreshBooks();
764 } else {
765 openBook(selectedBook);
766 }
767 }
768 }
769 });
770
771 return open;
772 }
773
774 /**
775 * Create the SetCover menu item for a book to change the linked source
776 * cover.
777 *
778 * @return the item
779 */
780 private JMenuItem createMenuItemSetCover() {
781 JMenuItem open = new JMenuItem("Set as cover for source", KeyEvent.VK_C);
782 open.addActionListener(new ActionListener() {
783 @Override
784 public void actionPerformed(ActionEvent e) {
785 if (selectedBook != null) {
786 reader.getLibrary().setSourceCover(
787 selectedBook.getMeta().getSource(),
788 selectedBook.getMeta().getLuid());
789 MetaData source = selectedBook.getMeta().clone();
790 source.setLuid(null);
791 GuiReaderBook.clearIcon(source);
792 }
793 }
794 });
795
796 return open;
797 }
798
799 /**
800 * Open a {@link GuiReaderBook} item.
801 *
802 * @param book
803 * the {@link GuiReaderBook} to open
804 */
805 private void openBook(final GuiReaderBook book) {
806 final Progress pg = new Progress();
807 outOfUi(pg, new Runnable() {
808 @Override
809 public void run() {
810 try {
811 reader.read(book.getMeta().getLuid(), pg);
812 SwingUtilities.invokeLater(new Runnable() {
813 @Override
814 public void run() {
815 book.setCached(true);
816 }
817 });
818 } catch (IOException e) {
819 // TODO: error message?
820 Instance.syserr(e);
821 }
822 }
823 });
824 }
825
826 /**
827 * Process the given action out of the Swing UI thread and link the given
828 * {@link ProgressBar} to the action.
829 * <p>
830 * The code will make sure that the {@link ProgressBar} (if not NULL) is set
831 * to done when the action is done.
832 *
833 * @param progress
834 * the {@link ProgressBar} or NULL
835 * @param run
836 * the action to run
837 */
838 private void outOfUi(Progress progress, final Runnable run) {
839 final Progress pg = new Progress();
840 final Progress reload = new Progress("Reload books");
841 if (progress == null) {
842 progress = new Progress();
843 }
844
845 pg.addProgress(progress, 90);
846 pg.addProgress(reload, 10);
847
848 invalidate();
849 pgBar.setProgress(pg);
850 validate();
851 setEnabled(false);
852
853 new Thread(new Runnable() {
854 @Override
855 public void run() {
856 run.run();
857 refreshBooks();
858 reload.done();
859 if (!pg.isDone()) {
860 // will trigger pgBar ActionListener:
861 pg.done();
862 }
863 }
864 }, "outOfUi thread").start();
865 }
866
867 /**
868 * Import a {@link Story} into the main {@link LocalLibrary}.
869 * <p>
870 * Should be called inside the UI thread.
871 *
872 * @param askUrl
873 * TRUE for an {@link URL}, false for a {@link File}
874 */
875 private void imprt(boolean askUrl) {
876 JFileChooser fc = new JFileChooser();
877
878 Object url;
879 if (askUrl) {
880 String clipboard = "";
881 try {
882 clipboard = ("" + Toolkit.getDefaultToolkit()
883 .getSystemClipboard().getData(DataFlavor.stringFlavor))
884 .trim();
885 } catch (Exception e) {
886 // No data will be handled
887 }
888
889 if (clipboard == null || !clipboard.startsWith("http")) {
890 clipboard = "";
891 }
892
893 url = JOptionPane.showInputDialog(GuiReaderFrame.this,
894 "url of the story to import?", "Importing from URL",
895 JOptionPane.QUESTION_MESSAGE, null, null, clipboard);
896 } else if (fc.showOpenDialog(this) != JFileChooser.CANCEL_OPTION) {
897 url = fc.getSelectedFile().getAbsolutePath();
898 } else {
899 url = null;
900 }
901
902 if (url != null && !url.toString().isEmpty()) {
903 imprt(url.toString(), null, null);
904 }
905 }
906
907 /**
908 * Actually import the {@link Story} into the main {@link LocalLibrary}.
909 * <p>
910 * Should be called inside the UI thread.
911 *
912 * @param url
913 * the {@link Story} to import by {@link URL}
914 * @param onSuccess
915 * Action to execute on success
916 */
917 private void imprt(final String url, final StoryRunnable onSuccess,
918 String onSuccessPgName) {
919 final Progress pg = new Progress();
920 final Progress pgImprt = new Progress();
921 final Progress pgOnSuccess = new Progress(onSuccessPgName);
922 pg.addProgress(pgImprt, 95);
923 pg.addProgress(pgOnSuccess, 5);
924
925 outOfUi(pg, new Runnable() {
926 @Override
927 public void run() {
928 Exception ex = null;
929 Story story = null;
930 try {
931 story = reader.getLibrary().imprt(BasicReader.getUrl(url),
932 pgImprt);
933 } catch (IOException e) {
934 ex = e;
935 }
936
937 final Exception e = ex;
938
939 final boolean ok = (e == null);
940
941 pgOnSuccess.setProgress(0);
942 if (!ok) {
943 Instance.syserr(e);
944 SwingUtilities.invokeLater(new Runnable() {
945 @Override
946 public void run() {
947 JOptionPane.showMessageDialog(GuiReaderFrame.this,
948 "Cannot import: " + url, e.getMessage(),
949 JOptionPane.ERROR_MESSAGE);
950 }
951 });
952 } else {
953 if (onSuccess != null) {
954 onSuccess.run(story);
955 }
956 }
957 pgOnSuccess.done();
958 }
959 });
960 }
961
962 /**
963 * Enables or disables this component, depending on the value of the
964 * parameter <code>b</code>. An enabled component can respond to user input
965 * and generate events. Components are enabled initially by default.
966 * <p>
967 * Disabling this component will also affect its children.
968 *
969 * @param b
970 * If <code>true</code>, this component is enabled; otherwise
971 * this component is disabled
972 */
973 @Override
974 public void setEnabled(boolean b) {
975 if (bar != null) {
976 bar.setEnabled(b);
977 }
978
979 for (GuiReaderGroup group : booksByType.keySet()) {
980 group.setEnabled(b);
981 }
982 for (GuiReaderGroup group : booksByAuthor.keySet()) {
983 group.setEnabled(b);
984 }
985 super.setEnabled(b);
986 repaint();
987 }
988 }