link gui frame to search
[fanfix.git] / src / be / nikiroo / fanfix / reader / ui / GuiReader.java
1 package be.nikiroo.fanfix.reader.ui;
2
3 import java.awt.Desktop;
4 import java.awt.EventQueue;
5 import java.awt.event.WindowAdapter;
6 import java.awt.event.WindowEvent;
7 import java.io.File;
8 import java.io.IOException;
9 import java.net.URISyntaxException;
10
11 import javax.swing.JEditorPane;
12 import javax.swing.JFrame;
13 import javax.swing.JLabel;
14 import javax.swing.JOptionPane;
15 import javax.swing.event.HyperlinkEvent;
16 import javax.swing.event.HyperlinkListener;
17
18 import be.nikiroo.fanfix.Instance;
19 import be.nikiroo.fanfix.VersionCheck;
20 import be.nikiroo.fanfix.bundles.StringIdGui;
21 import be.nikiroo.fanfix.bundles.UiConfig;
22 import be.nikiroo.fanfix.data.MetaData;
23 import be.nikiroo.fanfix.data.Story;
24 import be.nikiroo.fanfix.library.BasicLibrary;
25 import be.nikiroo.fanfix.library.CacheLibrary;
26 import be.nikiroo.fanfix.reader.BasicReader;
27 import be.nikiroo.fanfix.reader.Reader;
28 import be.nikiroo.fanfix.supported.SupportType;
29 import be.nikiroo.utils.Progress;
30 import be.nikiroo.utils.Version;
31 import be.nikiroo.utils.ui.UIUtils;
32
33 /**
34 * This class implements a graphical {@link Reader} using the Swing library from
35 * Java.
36 * <p>
37 * It can thus be themed to look native-like, or metal-like, or use any other
38 * theme you may want to try.
39 * <p>
40 * We actually try to enable native look-alike mode on start.
41 *
42 * @author niki
43 */
44 class GuiReader extends BasicReader {
45 static private boolean nativeLookLoaded;
46
47 private CacheLibrary cacheLib;
48
49 private File cacheDir;
50
51 /**
52 * Create a new graphical {@link Reader}.
53 *
54 * @throws IOException
55 * in case of I/O errors
56 */
57 public GuiReader() throws IOException {
58 // TODO: allow different themes?
59 if (!nativeLookLoaded) {
60 UIUtils.setLookAndFeel();
61 nativeLookLoaded = true;
62 }
63
64 cacheDir = Instance.getReaderDir();
65 cacheDir.mkdirs();
66 if (!cacheDir.exists()) {
67 throw new IOException(
68 "Cannote create cache directory for local reader: "
69 + cacheDir);
70 }
71 }
72
73 @Override
74 public synchronized BasicLibrary getLibrary() {
75 if (cacheLib == null) {
76 BasicLibrary lib = super.getLibrary();
77 if (lib instanceof CacheLibrary) {
78 cacheLib = (CacheLibrary) lib;
79 } else {
80 cacheLib = new CacheLibrary(cacheDir, lib);
81 }
82 }
83
84 return cacheLib;
85 }
86
87 @Override
88 public void read(boolean sync) throws IOException {
89 MetaData meta = getMeta();
90
91 if (meta == null) {
92 throw new IOException("No story to read");
93 }
94
95 read(meta.getLuid(), sync, null);
96 }
97
98 /**
99 * Check if the {@link Story} denoted by this Library UID is present in the
100 * {@link GuiReader} cache.
101 *
102 * @param luid
103 * the Library UID
104 *
105 * @return TRUE if it is
106 */
107 public boolean isCached(String luid) {
108 return cacheLib.isCached(luid);
109 }
110
111 @Override
112 public void browse(String type) {
113 final Boolean[] done = new Boolean[] { false };
114
115 // TODO: improve presentation of update message
116 final VersionCheck updates = VersionCheck.check();
117 StringBuilder builder = new StringBuilder();
118
119 final JEditorPane updateMessage = new JEditorPane("text/html", "");
120 if (updates.isNewVersionAvailable()) {
121 builder.append(trans(StringIdGui.NEW_VERSION_AVAILABLE,
122 "<span style='color: blue;'>https://github.com/nikiroo/fanfix/releases</span>"));
123 builder.append("<br>");
124 builder.append("<br>");
125 for (Version v : updates.getNewer()) {
126 builder.append("\t<b>"
127 + trans(StringIdGui.NEW_VERSION_VERSION, v.toString())
128 + "</b>");
129 builder.append("<br>");
130 builder.append("<ul>");
131 for (String item : updates.getChanges().get(v)) {
132 builder.append("<li>" + item + "</li>");
133 }
134 builder.append("</ul>");
135 }
136
137 // html content
138 updateMessage.setText("<html><body>" //
139 + builder//
140 + "</body></html>");
141
142 // handle link events
143 updateMessage.addHyperlinkListener(new HyperlinkListener() {
144 @Override
145 public void hyperlinkUpdate(HyperlinkEvent e) {
146 if (e.getEventType().equals(
147 HyperlinkEvent.EventType.ACTIVATED))
148 try {
149 Desktop.getDesktop().browse(e.getURL().toURI());
150 } catch (IOException ee) {
151 Instance.getTraceHandler().error(ee);
152 } catch (URISyntaxException ee) {
153 Instance.getTraceHandler().error(ee);
154 }
155 }
156 });
157 updateMessage.setEditable(false);
158 updateMessage.setBackground(new JLabel().getBackground());
159 }
160
161 final String typeFinal = type;
162 EventQueue.invokeLater(new Runnable() {
163 @Override
164 public void run() {
165 if (updates.isNewVersionAvailable()) {
166 int rep = JOptionPane.showConfirmDialog(null,
167 updateMessage,
168 trans(StringIdGui.NEW_VERSION_TITLE),
169 JOptionPane.OK_CANCEL_OPTION);
170 if (rep == JOptionPane.OK_OPTION) {
171 updates.ok();
172 } else {
173 updates.ignore();
174 }
175 }
176
177 new Thread(new Runnable() {
178 @Override
179 public void run() {
180 try {
181 GuiReaderFrame gui = new GuiReaderFrame(
182 GuiReader.this, typeFinal);
183 sync(gui);
184 } catch (Exception e) {
185 Instance.getTraceHandler().error(e);
186 } finally {
187 done[0] = true;
188 }
189
190 }
191 }).start();
192 }
193 });
194
195 // This action must be synchronous, so wait until the frame is closed
196 while (!done[0]) {
197 try {
198 Thread.sleep(100);
199 } catch (InterruptedException e) {
200 }
201 }
202 }
203
204 @Override
205 public void start(File target, String program, boolean sync)
206 throws IOException {
207
208 boolean handled = false;
209 if (program == null && !sync) {
210 try {
211 Desktop.getDesktop().browse(target.toURI());
212 handled = true;
213 } catch (UnsupportedOperationException e) {
214 }
215 }
216
217 if (!handled) {
218 super.start(target, program, sync);
219 }
220 }
221
222 @Override
223 public void search(SupportType searchOn, String keywords, int page, int item) {
224 // TODO: !!!
225 throw new java.lang.IllegalStateException("Not implemented yet.");
226 }
227
228 @Override
229 public void searchTag(SupportType searchOn, int page, int item,
230 Integer... tags) {
231 // TODO: !!!
232 throw new java.lang.IllegalStateException("Not implemented yet.");
233 }
234
235 /**
236 * Delete the {@link Story} from the cache if it is present, but <b>NOT</b>
237 * from the main library.
238 * <p>
239 * The next time we try to retrieve the {@link Story}, it may be required to
240 * cache it again.
241 *
242 * @param luid
243 * the luid of the {@link Story}
244 */
245 void clearLocalReaderCache(String luid) {
246 try {
247 cacheLib.clearFromCache(luid);
248 } catch (IOException e) {
249 Instance.getTraceHandler().error(e);
250 }
251 }
252
253 /**
254 * Forward the delete operation to the main library.
255 * <p>
256 * The {@link Story} will be deleted from the main library as well as the
257 * cache if present.
258 *
259 * @param luid
260 * the {@link Story} to delete
261 */
262 void delete(String luid) {
263 try {
264 cacheLib.delete(luid);
265 } catch (IOException e) {
266 Instance.getTraceHandler().error(e);
267 }
268 }
269
270 /**
271 * "Open" the given {@link Story}. It usually involves starting an external
272 * program adapted to the given file type.
273 * <p>
274 * Asynchronous method.
275 *
276 * @param luid
277 * the luid of the {@link Story} to open
278 * @param sync
279 * execute the process synchronously (wait until it is terminated
280 * before returning)
281 * @param pg
282 * the optional progress (we may need to prepare the
283 * {@link Story} for reading
284 *
285 * @throws IOException
286 * in case of I/O errors
287 */
288 void read(String luid, boolean sync, Progress pg) throws IOException {
289 MetaData meta = cacheLib.getInfo(luid);
290
291 boolean textInternal = Instance.getUiConfig().getBoolean(
292 UiConfig.NON_IMAGES_DOCUMENT_USE_INTERNAL_READER, true);
293 boolean imageInternal = Instance.getUiConfig().getBoolean(
294 UiConfig.IMAGES_DOCUMENT_USE_INTERNAL_READER, true);
295
296 boolean useInternalViewer = true;
297 if (meta.isImageDocument() && !imageInternal) {
298 useInternalViewer = false;
299 }
300 if (!meta.isImageDocument() && !textInternal) {
301 useInternalViewer = false;
302 }
303
304 if (useInternalViewer) {
305 GuiReaderViewer viewer = new GuiReaderViewer(cacheLib,
306 cacheLib.getStory(luid, null));
307 if (sync) {
308 sync(viewer);
309 } else {
310 viewer.setVisible(true);
311 }
312 } else {
313 File file = cacheLib.getFile(luid, pg);
314 openExternal(meta, file, sync);
315 }
316 }
317
318 /**
319 * Change the source of the given {@link Story} (the source is the main
320 * information used to group the stories together).
321 * <p>
322 * In other words, <b>move</b> the {@link Story} into other source.
323 * <p>
324 * The source can be a new one, it needs not exist before hand.
325 *
326 * @param luid
327 * the luid of the {@link Story} to move
328 * @param newSource
329 * the new source
330 */
331 void changeSource(String luid, String newSource) {
332 try {
333 cacheLib.changeSource(luid, newSource, null);
334 } catch (IOException e) {
335 Instance.getTraceHandler().error(e);
336 }
337 }
338
339 /**
340 * Change the title of the given {@link Story}.
341 *
342 * @param luid
343 * the luid of the {@link Story} to change
344 * @param newTitle
345 * the new title
346 */
347 void changeTitle(String luid, String newTitle) {
348 try {
349 cacheLib.changeTitle(luid, newTitle, null);
350 } catch (IOException e) {
351 Instance.getTraceHandler().error(e);
352 }
353 }
354
355 /**
356 * Change the author of the given {@link Story}.
357 * <p>
358 * The author can be a new one, it needs not exist before hand.
359 *
360 * @param luid
361 * the luid of the {@link Story} to change
362 * @param newAuthor
363 * the new author
364 */
365 void changeAuthor(String luid, String newAuthor) {
366 try {
367 cacheLib.changeAuthor(luid, newAuthor, null);
368 } catch (IOException e) {
369 Instance.getTraceHandler().error(e);
370 }
371 }
372
373 /**
374 * Simple shortcut method to call {link Instance#getTransGui()#getString()}.
375 *
376 * @param id
377 * the ID to translate
378 *
379 * @return the translated result
380 */
381 static String trans(StringIdGui id, Object... params) {
382 return Instance.getTransGui().getString(id, params);
383 }
384
385 /**
386 * Start a frame and wait until it is closed before returning.
387 *
388 * @param frame
389 * the frame to start
390 */
391 static private void sync(final JFrame frame) {
392 if (EventQueue.isDispatchThread()) {
393 throw new IllegalStateException(
394 "Cannot call a sync method in the dispatch thread");
395 }
396
397 final Boolean[] done = new Boolean[] { false };
398 try {
399 Runnable run = new Runnable() {
400 @Override
401 public void run() {
402 try {
403 frame.addWindowListener(new WindowAdapter() {
404 @Override
405 public void windowClosing(WindowEvent e) {
406 super.windowClosing(e);
407 done[0] = true;
408 }
409 });
410
411 frame.setVisible(true);
412 } catch (Exception e) {
413 done[0] = true;
414 }
415 }
416 };
417
418 if (EventQueue.isDispatchThread()) {
419 run.run();
420 } else {
421 EventQueue.invokeLater(run);
422 }
423 } catch (Exception e) {
424 Instance.getTraceHandler().error(e);
425 done[0] = true;
426 }
427
428 // This action must be synchronous, so wait until the frame is closed
429 while (!done[0]) {
430 try {
431 Thread.sleep(100);
432 } catch (InterruptedException e) {
433 }
434 }
435 }
436 }