Navigate with volume keys.
[dorian] / bookview.cpp
1 #include <QDebug>
2 #include <QWebFrame>
3 #include <QMouseEvent>
4 #include <QFile>
5 #include <QDir>
6 #include <QTimer>
7
8 #ifdef Q_WS_MAEMO_5
9 #   include <QAbstractKineticScroller>
10 #endif
11
12 #include "book.h"
13 #include "bookview.h"
14 #include "library.h"
15 #include "settings.h"
16 #include "trace.h"
17 #include "progress.h"
18
19 #ifdef Q_WS_MAC
20 #   define ICON_PREFIX ":/icons/mac/"
21 #else
22 #   define ICON_PREFIX ":/icons/"
23 #endif
24
25 BookView::BookView(QWidget *parent):
26     QWebView(parent), contentIndex(-1), mBook(0),
27     restorePositionAfterLoad(false), positionAfterLoad(0), loaded(false),
28     contentsHeight(0), decorated(false), scrollerMonitor(-1)
29 {
30     Trace t("BookView::BookView");
31     settings()->setAttribute(QWebSettings::AutoLoadImages, true);
32     settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
33     settings()->setAttribute(QWebSettings::JavaEnabled, false);
34     settings()->setAttribute(QWebSettings::PluginsEnabled, false);
35     settings()->setAttribute(QWebSettings::PrivateBrowsingEnabled, true);
36     settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, false);
37     settings()->setAttribute(QWebSettings::JavascriptCanAccessClipboard, false);
38     settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, false);
39     settings()->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled,
40                              false);
41     settings()->setAttribute(QWebSettings::LocalStorageEnabled, false);
42     settings()->setAttribute(QWebSettings::ZoomTextOnly, true);
43     settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,
44                              false);
45     settings()->setDefaultTextEncoding("utf-8");
46     page()->setContentEditable(false);
47
48 #if defined(Q_WS_MAEMO_5)
49     // Suppress unwanted text selections on Maemo
50     installEventFilter(this);
51 #endif
52     QWebFrame *frame = page()->mainFrame();
53 #if defined(Q_WS_MAEMO_5)
54     frame->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);
55 #endif
56     frame->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
57
58     bookmarkImage = QImage(":/icons/bookmark.png");
59
60     connect(this, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
61     connect(frame, SIGNAL(javaScriptWindowObjectCleared()),
62             this, SLOT(addJavaScriptObjects()));
63     connect(frame, SIGNAL(contentsSizeChanged(const QSize &)),
64             this, SLOT(onContentsSizeChanged(const QSize &)));
65     connect(Settings::instance(), SIGNAL(valueChanged(const QString &)),
66             this, SLOT(onSettingsChanged(const QString &)));
67     Settings *s = Settings::instance();
68     s->setValue("zoom", s->value("zoom", 160));
69     s->setValue("font", s->value("font",
70 #if defined(Q_WS_MAEMO_5) || defined(Q_WS_X11)
71                                  "Serif"
72 #elif defined(Q_WS_MAC)
73                                  "Hoefler Text"
74 #else
75                                  "Times New Roman"
76 #endif
77                                  ));
78     s->setValue("scheme", s->value("scheme", "default"));
79     setBook(0);
80
81     extractIcons();
82 #ifdef Q_WS_MAEMO_5
83     scroller = property("kineticScroller").value<QAbstractKineticScroller *>();
84 #endif
85 }
86
87 BookView::~BookView()
88 {
89     Trace t("BookView::~BookView");
90     removeIcons();
91 }
92
93 void BookView::loadContent(int index)
94 {
95     Trace t("BookView::loadContent");
96     if (!mBook) {
97         return;
98     }
99     if ((index < 0) || (index >= mBook->parts.size())) {
100         return;
101     }
102
103     QString contentFile(mBook->content[mBook->parts[index]].href);
104     if (mBook->parts[index] == "error") {
105         setHtml(contentFile);
106     }
107     else {
108         loaded = false;
109         decorated = false;
110         emit partLoadStart(index);
111         load(QUrl(contentFile));
112     }
113     contentIndex = index;
114 }
115
116 void BookView::setBook(Book *book)
117 {
118     Trace t("BookView::setBook");
119
120     // Save position in current book
121     setLastBookmark();
122
123     // Open new book, restore last position
124     if (book != mBook) {
125         mBook = book;
126         if (book) {
127             contentIndex = -1;
128             if (book->open()) {
129                 restoreLastBookmark();
130             } else {
131                 mBook = 0;
132                 contentIndex = 0;
133                 setHtml(tr("Failed to open book"));
134             }
135         }
136         else {
137             contentIndex = 0;
138             setHtml(tr("No book"));
139         }
140     }
141 }
142
143 Book *BookView::book()
144 {
145     return mBook;
146 }
147
148 void BookView::goPrevious()
149 {
150     Trace t("BookView::goPrevious");
151     loadContent(contentIndex - 1);
152 }
153
154 void BookView::goNext()
155 {
156     Trace t("BookView::goNext");
157     loadContent(contentIndex + 1);
158 }
159
160 void BookView::setLastBookmark()
161 {
162     Trace t("BookView::setLastBookmark");
163     if (mBook) {
164         int height = contentsHeight;
165         int pos = page()->mainFrame()->scrollPosition().y();
166         t.trace(QString("At %1 (%2%, height %3)").
167                 arg(pos).arg((qreal)pos / (qreal)height * 100).arg(height));
168         mBook->setLastBookmark(contentIndex, (qreal)pos / (qreal)height);
169     }
170 }
171
172 void BookView::restoreLastBookmark()
173 {
174     Trace t("BookView::restoreLastBookmark");
175     if (mBook) {
176         goToBookmark(mBook->lastBookmark());
177     }
178 }
179
180 void BookView::goToBookmark(const Book::Bookmark &bookmark)
181 {
182     Trace t("BookView::goToBookmark");
183     if (mBook) {
184         if (bookmark.part != contentIndex) {
185             t.trace(QString("Loading new part %1").arg(bookmark.part));
186             mBook->setLastBookmark(bookmark.part, bookmark.pos);
187             restorePositionAfterLoad = true;
188             positionAfterLoad = bookmark.pos;
189             loadContent(bookmark.part);
190         } else {
191             goToPosition(bookmark.pos);
192         }
193     }
194 }
195
196 void BookView::onLoadFinished(bool ok)
197 {
198     Trace t("BookView::onLoadFinished");
199     if (!ok) {
200         t.trace("Not OK");
201         return;
202     }
203     loaded = true;
204     addNavigationBar();
205     onSettingsChanged("scheme");
206     emit partLoadEnd(contentIndex);
207     showProgress();
208 }
209
210 void BookView::onSettingsChanged(const QString &key)
211 {
212     Trace t("BookView::onSettingsChanged " + key);
213     if (key == "zoom") {
214         setZoomFactor(Settings::instance()->value(key).toFloat() / 100.);
215     }
216     else if (key == "font") {
217         QString face = Settings::instance()->value("font").toString();
218         settings()->setFontFamily(QWebSettings::StandardFont, face);
219     }
220     else if (key == "scheme") {
221         QWebFrame *frame = page()->mainFrame();
222         QString scheme = Settings::instance()->value("scheme").toString();
223         if ((scheme != "day") && (scheme != "night") && (scheme != "sand") &&
224             (scheme != "default")) {
225             scheme = "default";
226         }
227         QFile script(":/styles/" + scheme + ".js");
228         script.open(QFile::ReadOnly);
229         QString scriptText = script.readAll();
230         script.close();
231         QVariant ret = frame->evaluateJavaScript(scriptText);
232     }
233 }
234
235 void BookView::paintEvent(QPaintEvent *e)
236 {
237     QWebView::paintEvent(e);
238     if (!mBook || !loaded) {
239         return;
240     }
241
242     // Paint bookmarks
243     QPoint scrollPos = page()->mainFrame()->scrollPosition();
244     QPixmap bookmarkPixmap = QPixmap::fromImage(bookmarkImage);
245     QPainter painter(this);
246     foreach (Book::Bookmark b, mBook->bookmarks()) {
247         if (b.part != contentIndex) {
248             continue;
249         }
250         int height = contentsHeight;
251         int bookmarkPos = (qreal)height * (qreal)b.pos;
252         painter.drawPixmap(2, bookmarkPos - scrollPos.y(), bookmarkPixmap);
253     }
254 }
255
256 void BookView::mousePressEvent(QMouseEvent *e)
257 {
258     QWebView::mousePressEvent(e);
259 #ifdef Q_WS_MAEMO_5
260     if (scroller) {
261         scrollerMonitor = startTimer(250);
262     }
263 #else
264     QWebFrame *frame = page()->mainFrame();
265     if (frame->scrollBarGeometry(Qt::Vertical).contains(e->pos())) {
266         e->accept();
267         return;
268     }
269 #endif // Q_WS_MAEMO_5
270     e->ignore();
271 }
272
273 void BookView::wheelEvent(QWheelEvent *e)
274 {
275     QWebView::wheelEvent(e);
276     showProgress();
277 }
278
279 void BookView::addBookmark()
280 {
281     Trace t("BookView::addBookmark");
282     if (!mBook) {
283         return;
284     }
285     int y = page()->mainFrame()->scrollPosition().y();
286     int height = page()->mainFrame()->contentsSize().height();
287     t.trace(QString().setNum((qreal)y / (qreal)height));
288     mBook->addBookmark(contentIndex, (qreal)y / (qreal)height);
289     update();
290 }
291
292 void BookView::addNavigationBar()
293 {
294     Trace t("BookView::addNavigationBar");
295     if (!mBook) {
296         return;
297     }
298
299     QString naviPrev =
300             "<a href=\"javascript:bv.goPrevious();\">"
301             "<img width=\"95\" height=\"95\" style=\"float:left;clear:none;\" "
302             "src=\"file://"
303             + tmpPath() +
304             "/previous.png\" />"
305             "</a>";
306     QString naviNext =
307             "<a href=\"javascript:bv.goNext();\">"
308             "<img width=\"95\" height=\"95\" style=\"float:right;clear:none;\" "
309             "src=\"file://"
310             + tmpPath() +
311             "/next.png\" />"
312             "</a>";
313     if (contentIndex == 0) {
314         naviPrev = "";
315     }
316     if (contentIndex >= mBook->parts.size() - 1) {
317         naviNext = "";
318     }
319
320     QWebFrame *frame = page()->currentFrame();
321     QString headerScript = "document.body.innerHTML = '" +
322         naviPrev + naviNext + "<br />" + "' + document.body.innerHTML;";
323     QString trailerScript = "document.body.innerHTML += '<br /><br />" +
324         naviPrev + naviNext + "';";
325
326     frame->evaluateJavaScript(headerScript);
327     frame->evaluateJavaScript(trailerScript);
328     decorated = true;
329 }
330
331 QString BookView::tmpPath()
332 {
333     return QDir::tempPath() + "/dorian";
334 }
335
336 void BookView::extractIcons()
337 {
338     QFile next(ICON_PREFIX + QString("/next.png"));
339     QFile prev(ICON_PREFIX + QString("/previous.png"));
340
341     QDir().mkpath(tmpPath());
342     next.copy(tmpPath() + "/next.png");
343     prev.copy(tmpPath() + "/previous.png");
344 }
345
346 void BookView::removeIcons()
347 {
348     QFile(ICON_PREFIX + QString("/next.png")).remove();
349     QFile(ICON_PREFIX + QString("/previous.png")).remove();
350     QDir().rmpath(tmpPath());
351 }
352
353 bool BookView::eventFilter(QObject *o, QEvent *e)
354 {
355     if (e->type() != QEvent::Paint && e->type() != QEvent::MouseMove) {
356         if (e->type() == QEvent::Resize) {
357             Trace::trace(QString("BookView::eventFilter QEvent::Resize to %1").
358                          arg(page()->mainFrame()->contentsSize().height()));
359         } else {
360             Trace::trace(QString("BookView::eventFilter %1").
361                          arg(Trace::event(e->type())));
362         }
363     }
364
365     switch (e->type()) {
366     case QEvent::MouseButtonPress:
367         emit suppressedMouseButtonPress();
368         mousePressed = true;
369         break;
370     case QEvent::MouseButtonRelease:
371         showProgress();
372         mousePressed = false;
373         break;
374     case QEvent::MouseMove:
375         if (mousePressed) {
376             return true;
377         }
378         break;
379     case QEvent::MouseButtonDblClick:
380         return true;
381     default:
382         break;
383     }
384
385     return QObject::eventFilter(o, e);
386 }
387
388 void BookView::addJavaScriptObjects()
389 {
390     page()->mainFrame()->addToJavaScriptWindowObject("bv", this);
391 }
392
393 void BookView::onContentsSizeChanged(const QSize &size)
394 {
395     contentsHeight = size.height();
396     if (decorated) {
397         if (restorePositionAfterLoad) {
398             Trace::trace("BookView::onContentSizeChanged: Time to restore");
399             restorePositionAfterLoad = false;
400             goToPosition(positionAfterLoad);
401         }
402     }
403 }
404
405 void BookView::leaveEvent(QEvent *e)
406 {
407     Trace t("BookView::leaveEvent");
408     // Save current position, to be restored later
409     setLastBookmark();
410     QWebView::leaveEvent(e);
411 }
412
413 void BookView::enterEvent(QEvent *e)
414 {
415     Trace t("BookView::enterEvent");
416     // Restore position saved at Leave event. This seems to be required,
417     // after temporarily switching from portrait to landscape and back
418     restoreLastBookmark();
419     QWebView::enterEvent(e);
420 }
421
422 void BookView::goToPosition(qreal position)
423 {
424     int scrollPos = (qreal)contentsHeight * position;
425     page()->mainFrame()->setScrollPosition(QPoint(0, scrollPos));
426     // FIXME: update();
427     Trace::trace(QString("BookView::goToPosition: To %1 (%2%, height %3)").
428             arg(scrollPos).arg(position * 100).arg(contentsHeight));
429 }
430
431 void BookView::showProgress()
432 {
433     if (mBook) {
434         qreal pos = (qreal)(page()->mainFrame()->scrollPosition().y()) /
435                     (qreal)contentsHeight;
436         emit progress(mBook->getProgress(contentIndex, pos));
437     }
438 }
439
440 void BookView::timerEvent(QTimerEvent *e)
441 {
442     if (e->timerId() == scrollerMonitor) {
443 #ifdef Q_WS_MAEMO_5
444         if (scroller &&
445             ((scroller->state() == QAbstractKineticScroller::AutoScrolling) ||
446              (scroller->state() == QAbstractKineticScroller::Pushing))) {
447             showProgress();
448         } else {
449             killTimer(scrollerMonitor);
450         }
451 #endif // Q_WS_MAEMO_5
452     }
453 }
454
455 void BookView::keyPressEvent(QKeyEvent* event)
456 {
457     switch (event->key()) {
458     case Qt::Key_F7:
459         goNextPage();
460         event->accept();
461         break;
462     case Qt::Key_F8:
463         goPreviousPage();
464         event->accept();
465         break;
466     default:
467         ;
468     }
469     QWebView::keyPressEvent(event);
470 }
471
472 void BookView::goPreviousPage()
473 {
474     QWebFrame *frame = page()->mainFrame();
475     int pos = frame->scrollPosition().y();
476     frame->scroll(0, -height());
477     if (pos == frame->scrollPosition().y()) {
478         if (contentIndex > 0) {
479             goToBookmark(Book::Bookmark(contentIndex - 1, 1.0));
480         }
481     } else {
482         showProgress();
483     }
484 }
485
486 void BookView::goNextPage()
487 {
488     Trace t("BookView::goNextPage");
489     QWebFrame *frame = page()->mainFrame();
490     int pos = frame->scrollPosition().y();
491     frame->scroll(0, height());
492     if (pos == frame->scrollPosition().y()) {
493         goNext();
494     } else {
495         showProgress();
496     }
497 }