1 package be
.nikiroo
.fanfix
.reader
.ui
;
3 import java
.awt
.BorderLayout
;
5 import java
.awt
.Component
;
6 import java
.awt
.EventQueue
;
8 import java
.awt
.Toolkit
;
9 import java
.awt
.datatransfer
.DataFlavor
;
10 import java
.awt
.event
.ActionEvent
;
11 import java
.awt
.event
.ActionListener
;
12 import java
.awt
.event
.FocusAdapter
;
13 import java
.awt
.event
.FocusEvent
;
15 import java
.io
.IOException
;
16 import java
.lang
.reflect
.InvocationTargetException
;
18 import java
.net
.UnknownHostException
;
19 import java
.util
.ArrayList
;
20 import java
.util
.LinkedList
;
21 import java
.util
.List
;
23 import java
.util
.TreeMap
;
25 import javax
.swing
.BoxLayout
;
26 import javax
.swing
.JFileChooser
;
27 import javax
.swing
.JLabel
;
28 import javax
.swing
.JMenuBar
;
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
;
36 import be
.nikiroo
.fanfix
.Instance
;
37 import be
.nikiroo
.fanfix
.bundles
.StringIdGui
;
38 import be
.nikiroo
.fanfix
.bundles
.UiConfig
;
39 import be
.nikiroo
.fanfix
.data
.MetaData
;
40 import be
.nikiroo
.fanfix
.data
.Story
;
41 import be
.nikiroo
.fanfix
.library
.BasicLibrary
;
42 import be
.nikiroo
.fanfix
.library
.BasicLibrary
.Status
;
43 import be
.nikiroo
.fanfix
.library
.LocalLibrary
;
44 import be
.nikiroo
.fanfix
.reader
.BasicReader
;
45 import be
.nikiroo
.fanfix
.reader
.ui
.GuiReaderBook
.BookActionListener
;
46 import be
.nikiroo
.fanfix
.reader
.ui
.GuiReaderBookInfo
.Type
;
47 import be
.nikiroo
.utils
.Progress
;
48 import be
.nikiroo
.utils
.ui
.ProgressBar
;
51 * A {@link Frame} that will show a {@link GuiReaderBook} item for each
52 * {@link Story} in the main cache ({@link Instance#getCache()}), and offer a
53 * way to copy them to the {@link GuiReader} cache (
54 * {@link BasicReader#getLibrary()}), read them, delete them...
58 class GuiReaderMainPanel
extends JPanel
{
59 private static final long serialVersionUID
= 1L;
60 private FrameHelper helper
;
61 private Map
<String
, GuiReaderGroup
> books
;
62 private GuiReaderGroup bookPane
; // for more "All"
65 private ProgressBar pgBar
;
67 private GuiReaderBook selectedBook
;
68 private boolean words
; // words or authors (secondary info on books)
69 private boolean currentType
; // type/source or author mode (All and Listing)
72 * An object that offers some helper methods to access the frame that host
73 * it and the Fanfix-related functions.
77 public interface FrameHelper
{
79 * Return the reader associated to this {@link FrameHelper}.
83 public GuiReader
getReader();
86 * Create the main menu bar.
88 * Will invalidate the layout.
91 * the library status, <b>must not</b> be NULL
93 public void createMenu(Status status
);
96 * Create a popup menu for a {@link GuiReaderBook} that represents a
99 * @return the popup menu to display
101 public JPopupMenu
createBookPopup();
104 * Create a popup menu for a {@link GuiReaderBook} that represents a
105 * source/type or an author.
107 * @return the popup menu to display
109 public JPopupMenu
createSourceAuthorPopup();
113 * A {@link Runnable} with a {@link MetaData} parameter.
117 public interface MetaDataRunnable
{
122 * the meta of the story
124 public void run(MetaData meta
);
128 * Create a new {@link GuiReaderMainPanel}.
131 * the associated {@link FrameHelper} to forward some commands
132 * and access its {@link LocalLibrary}
134 * the type of {@link Story} to load, or NULL for all types
136 public GuiReaderMainPanel(FrameHelper parent
, String type
) {
137 super(new BorderLayout(), true);
139 this.helper
= parent
;
142 pane
.setLayout(new BoxLayout(pane
, BoxLayout
.PAGE_AXIS
));
143 JScrollPane scroll
= new JScrollPane(pane
);
145 Integer icolor
= Instance
.getUiConfig().getColor(
146 UiConfig
.BACKGROUND_COLOR
);
147 if (icolor
!= null) {
148 color
= new Color(icolor
);
149 setBackground(color
);
150 pane
.setBackground(color
);
151 scroll
.setBackground(color
);
154 scroll
.getVerticalScrollBar().setUnitIncrement(16);
155 add(scroll
, BorderLayout
.CENTER
);
157 String message
= parent
.getReader().getLibrary().getLibraryName();
158 if (!message
.isEmpty()) {
159 JLabel name
= new JLabel(message
, SwingConstants
.CENTER
);
160 add(name
, BorderLayout
.NORTH
);
163 pgBar
= new ProgressBar();
164 add(pgBar
, BorderLayout
.SOUTH
);
166 pgBar
.addActionListener(new ActionListener() {
168 public void actionPerformed(ActionEvent e
) {
170 pgBar
.setProgress(null);
176 pgBar
.addUpdateListener(new ActionListener() {
178 public void actionPerformed(ActionEvent e
) {
185 books
= new TreeMap
<String
, GuiReaderGroup
>();
187 addFocusListener(new FocusAdapter() {
189 public void focusGained(FocusEvent e
) {
194 pane
.setVisible(false);
195 final Progress pg
= new Progress();
196 final String typeF
= type
;
197 outOfUi(pg
, true, new Runnable() {
200 final BasicLibrary lib
= helper
.getReader().getLibrary();
201 final Status status
= lib
.getStatus();
203 if (status
== Status
.READ_WRITE
) {
207 inUi(new Runnable() {
210 if (status
.isReady()) {
211 helper
.createMenu(status
);
212 pane
.setVisible(true);
215 addBookPane(true, false);
216 } catch (IOException e
) {
217 error(e
.getLocalizedMessage(),
221 addBookPane(typeF
, true);
224 helper
.createMenu(status
);
227 String desc
= Instance
.getTransGui().getStringX(
228 StringIdGui
.ERROR_LIB_STATUS
,
232 .trans(StringIdGui
.ERROR_LIB_STATUS
);
235 String err
= lib
.getLibraryName() + "\n" + desc
;
237 .trans(StringIdGui
.TITLE_ERROR_LIBRARY
),
246 public boolean getCurrentType() {
251 * Add a new {@link GuiReaderGroup} on the frame to display all the
252 * sources/types or all the authors, or a listing of all the books sorted
253 * either by source or author.
255 * A display of all the sources/types or all the authors will show one icon
256 * per source/type or author.
258 * A listing of all the books sorted by source/type or author will display
262 * TRUE for type/source, FALSE for author
264 * TRUE to get a listing of all the sources or authors, FALSE to
265 * get one icon per source or author
267 * @throws IOException
268 * in case of I/O error
270 public void addBookPane(boolean type
, boolean listMode
) throws IOException
{
271 this.currentType
= type
;
272 BasicLibrary lib
= helper
.getReader().getLibrary();
275 addListPane(GuiReader
.trans(StringIdGui
.MENU_SOURCES
),
276 lib
.getSources(), type
);
278 for (String tt
: lib
.getSources()) {
280 addBookPane(tt
, type
);
286 addListPane(GuiReader
.trans(StringIdGui
.MENU_AUTHORS
),
287 lib
.getAuthors(), type
);
289 for (String tt
: lib
.getAuthors()) {
291 addBookPane(tt
, type
);
299 * Add a new {@link GuiReaderGroup} on the frame to display the books of the
300 * selected type or author.
302 * Will invalidate the layout.
305 * the author or the type, or NULL to get all the
308 * TRUE for type/source, FALSE for author
310 public void addBookPane(String value
, boolean type
) {
311 this.currentType
= type
;
313 GuiReaderGroup bookPane
= new GuiReaderGroup(helper
.getReader(), value
,
316 books
.put(value
, bookPane
);
321 bookPane
.setActionListener(new BookActionListener() {
323 public void select(GuiReaderBook book
) {
328 public void popupRequested(GuiReaderBook book
, Component target
,
330 JPopupMenu popup
= helper
.createBookPopup();
331 popup
.show(target
, x
, y
);
335 public void action(final GuiReaderBook book
) {
344 * Clear the pane from any book that may be present, usually prior to adding
347 * Will invalidate the layout.
349 public void removeBookPanes() {
356 * Refresh the list of {@link GuiReaderBook}s from disk.
358 * Will validate the layout, as it is a "refresh" operation.
360 public void refreshBooks() {
361 BasicLibrary lib
= helper
.getReader().getLibrary();
362 for (String value
: books
.keySet()) {
363 List
<GuiReaderBookInfo
> infos
= new ArrayList
<GuiReaderBookInfo
>();
365 List
<MetaData
> metas
;
368 metas
= lib
.getListBySource(value
);
370 metas
= lib
.getListByAuthor(value
);
372 } catch (IOException e
) {
373 error(e
.getLocalizedMessage(), "IOException", e
);
374 metas
= new ArrayList
<MetaData
>();
377 for (MetaData meta
: metas
) {
378 infos
.add(GuiReaderBookInfo
.fromMeta(meta
));
381 books
.get(value
).refreshBooks(infos
, words
);
384 if (bookPane
!= null) {
385 bookPane
.refreshBooks(words
);
392 * Open a {@link GuiReaderBook} item.
395 * the {@link GuiReaderBook} to open
397 public void openBook(final GuiReaderBook book
) {
398 final Progress pg
= new Progress();
399 outOfUi(pg
, false, new Runnable() {
403 helper
.getReader().read(book
.getInfo().getMeta().getLuid(),
405 SwingUtilities
.invokeLater(new Runnable() {
408 book
.setCached(true);
411 } catch (IOException e
) {
412 Instance
.getTraceHandler().error(e
);
413 error(GuiReader
.trans(StringIdGui
.ERROR_CANNOT_OPEN
),
414 GuiReader
.trans(StringIdGui
.TITLE_ERROR
), e
);
421 * Prefetch a {@link GuiReaderBook} item (which can be a group, in which
422 * case we prefetch all its members).
425 * the {@link GuiReaderBook} to open
427 public void prefetchBook(final GuiReaderBook book
) {
428 final List
<String
> luids
= new LinkedList
<String
>();
430 switch (book
.getInfo().getType()) {
432 luids
.add(book
.getInfo().getMeta().getLuid());
435 for (MetaData meta
: helper
.getReader().getLibrary()
436 .getListBySource(book
.getInfo().getMainInfo())) {
437 luids
.add(meta
.getLuid());
441 for (MetaData meta
: helper
.getReader().getLibrary()
442 .getListByAuthor(book
.getInfo().getMainInfo())) {
443 luids
.add(meta
.getLuid());
447 } catch (IOException e
) {
448 Instance
.getTraceHandler().error(e
);
451 final Progress pg
= new Progress();
452 pg
.setMax(luids
.size());
454 outOfUi(pg
, false, new Runnable() {
458 for (String luid
: luids
) {
459 Progress pgStep
= new Progress();
460 pg
.addProgress(pgStep
, 1);
462 helper
.getReader().prefetch(luid
, pgStep
);
465 // TODO: also set the green button on sources/authors?
466 // requires to do the same when all stories inside are green
467 if (book
.getInfo().getType() == Type
.STORY
) {
468 SwingUtilities
.invokeLater(new Runnable() {
471 book
.setCached(true);
475 } catch (IOException e
) {
476 Instance
.getTraceHandler().error(e
);
477 error(GuiReader
.trans(StringIdGui
.ERROR_CANNOT_OPEN
),
478 GuiReader
.trans(StringIdGui
.TITLE_ERROR
), e
);
485 * Process the given action out of the Swing UI thread and link the given
486 * {@link ProgressBar} to the action.
488 * The code will make sure that the {@link ProgressBar} (if not NULL) is set
489 * to done when the action is done.
492 * the {@link ProgressBar} or NULL
493 * @param refreshBooks
494 * TRUE to refresh the books after
498 public void outOfUi(Progress progress
, final boolean refreshBooks
,
499 final Runnable run
) {
500 final Progress pg
= new Progress();
501 final Progress reload
= new Progress(
502 GuiReader
.trans(StringIdGui
.PROGRESS_OUT_OF_UI_RELOAD_BOOKS
));
504 if (progress
== null) {
505 progress
= new Progress();
509 pg
.addProgress(progress
, 100);
511 pg
.addProgress(progress
, 90);
512 pg
.addProgress(reload
, 10);
516 pgBar
.setProgress(pg
);
520 new Thread(new Runnable() {
531 // will trigger pgBar ActionListener:
536 }, "outOfUi thread").start();
540 * Process the given action in the main Swing UI thread.
542 * The code will make sure the current thread is the main UI thread and, if
543 * not, will switch to it before executing the runnable.
545 * Synchronous operation.
550 public void inUi(final Runnable run
) {
551 if (EventQueue
.isDispatchThread()) {
555 EventQueue
.invokeAndWait(run
);
556 } catch (InterruptedException e
) {
557 Instance
.getTraceHandler().error(e
);
558 } catch (InvocationTargetException e
) {
559 Instance
.getTraceHandler().error(e
);
565 * Import a {@link Story} into the main {@link LocalLibrary}.
567 * Should be called inside the UI thread.
570 * TRUE for an {@link URL}, false for a {@link File}
572 public void imprt(boolean askUrl
) {
573 JFileChooser fc
= new JFileChooser();
577 String clipboard
= "";
579 clipboard
= ("" + Toolkit
.getDefaultToolkit()
580 .getSystemClipboard().getData(DataFlavor
.stringFlavor
))
582 } catch (Exception e
) {
583 // No data will be handled
586 if (clipboard
== null || !(clipboard
.startsWith("http://") || //
587 clipboard
.startsWith("https://"))) {
591 url
= JOptionPane
.showInputDialog(GuiReaderMainPanel
.this,
592 GuiReader
.trans(StringIdGui
.SUBTITLE_IMPORT_URL
),
593 GuiReader
.trans(StringIdGui
.TITLE_IMPORT_URL
),
594 JOptionPane
.QUESTION_MESSAGE
, null, null, clipboard
);
595 } else if (fc
.showOpenDialog(this) != JFileChooser
.CANCEL_OPTION
) {
596 url
= fc
.getSelectedFile().getAbsolutePath();
601 if (url
!= null && !url
.toString().isEmpty()) {
602 imprt(url
.toString(), null, null);
607 * Actually import the {@link Story} into the main {@link LocalLibrary}.
609 * Should be called inside the UI thread.
612 * the {@link Story} to import by {@link URL}
614 * Action to execute on success
615 * @param onSuccessPgName
616 * the name to use for the onSuccess progress bar
618 public void imprt(final String url
, final MetaDataRunnable onSuccess
,
619 String onSuccessPgName
) {
620 final Progress pg
= new Progress();
621 final Progress pgImprt
= new Progress();
622 final Progress pgOnSuccess
= new Progress(onSuccessPgName
);
623 pg
.addProgress(pgImprt
, 95);
624 pg
.addProgress(pgOnSuccess
, 5);
626 outOfUi(pg
, true, new Runnable() {
630 MetaData meta
= null;
632 meta
= helper
.getReader().getLibrary()
633 .imprt(BasicReader
.getUrl(url
), pgImprt
);
634 } catch (IOException e
) {
638 final Exception e
= ex
;
640 final boolean ok
= (e
== null);
642 pgOnSuccess
.setProgress(0);
644 if (e
instanceof UnknownHostException
) {
645 error(GuiReader
.trans(
646 StringIdGui
.ERROR_URL_NOT_SUPPORTED
, url
),
647 GuiReader
.trans(StringIdGui
.TITLE_ERROR
), null);
649 error(GuiReader
.trans(
650 StringIdGui
.ERROR_URL_IMPORT_FAILED
, url
,
651 e
.getMessage()), GuiReader
652 .trans(StringIdGui
.TITLE_ERROR
), e
);
655 if (onSuccess
!= null) {
665 * Enables or disables this component, depending on the value of the
666 * parameter <code>b</code>. An enabled component can respond to user input
667 * and generate events. Components are enabled initially by default.
669 * Enabling or disabling <b>this</b> component will also affect its
673 * If <code>true</code>, this component is enabled; otherwise
674 * this component is disabled
677 public void setEnabled(boolean b
) {
682 for (GuiReaderGroup group
: books
.values()) {
689 public void setWords(boolean words
) {
693 public GuiReaderBook
getSelectedBook() {
697 public void unsetSelectedBook() {
701 private void addListPane(String name
, List
<String
> values
,
702 final boolean type
) {
703 GuiReader reader
= helper
.getReader();
704 BasicLibrary lib
= reader
.getLibrary();
706 bookPane
= new GuiReaderGroup(reader
, name
, color
);
708 List
<GuiReaderBookInfo
> infos
= new ArrayList
<GuiReaderBookInfo
>();
709 for (String value
: values
) {
711 infos
.add(GuiReaderBookInfo
.fromSource(lib
, value
));
713 infos
.add(GuiReaderBookInfo
.fromAuthor(lib
, value
));
717 bookPane
.refreshBooks(infos
, words
);
725 bookPane
.setActionListener(new BookActionListener() {
727 public void select(GuiReaderBook book
) {
732 public void popupRequested(GuiReaderBook book
, Component target
,
734 JPopupMenu popup
= helper
.createSourceAuthorPopup();
735 popup
.show(target
, x
, y
);
739 public void action(final GuiReaderBook book
) {
741 addBookPane(book
.getInfo().getMainInfo(), type
);
750 * Focus the first {@link GuiReaderGroup} we find.
752 private void focus() {
753 GuiReaderGroup group
= null;
754 Map
<String
, GuiReaderGroup
> books
= this.books
;
755 if (books
.size() > 0) {
756 group
= books
.values().iterator().next();
764 group
.requestFocusInWindow();
769 * Display an error message and log the linked {@link Exception}.
774 * the title of the error message
776 * the exception to log if any
778 private void error(final String message
, final String title
, Exception e
) {
779 Instance
.getTraceHandler().error(title
+ ": " + message
);
781 Instance
.getTraceHandler().error(e
);
784 SwingUtilities
.invokeLater(new Runnable() {
787 JOptionPane
.showMessageDialog(GuiReaderMainPanel
.this, message
,
788 title
, JOptionPane
.ERROR_MESSAGE
);