Fix part navigation on desktops.
[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     if (mBook && (contentIndex > 0)) {
152         mBook->setLastBookmark(contentIndex - 1, 0);
153         loadContent(contentIndex - 1);
154     }
155 }
156
157 void BookView::goNext()
158 {
159     Trace t("BookView::goNext");
160     if (mBook && (contentIndex < (mBook->parts.size() - 1))) {
161         mBook->setLastBookmark(contentIndex + 1, 0);
162         loadContent(contentIndex + 1);
163     }
164 }
165
166 void BookView::setLastBookmark()
167 {
168     Trace t("BookView::setLastBookmark");
169     if (mBook) {
170         int height = contentsHeight;
171         int pos = page()->mainFrame()->scrollPosition().y();
172         t.trace(QString("At %1 (%2%, height %3)").
173                 arg(pos).arg((qreal)pos / (qreal)height * 100).arg(height));
174         mBook->setLastBookmark(contentIndex, (qreal)pos / (qreal)height);
175     }
176 }
177
178 void BookView::restoreLastBookmark()
179 {
180     Trace t("BookView::restoreLastBookmark");
181     if (mBook) {
182         goToBookmark(mBook->lastBookmark());
183     }
184 }
185
186 void BookView::goToBookmark(const Book::Bookmark &bookmark)
187 {
188     Trace t("BookView::goToBookmark");
189     if (mBook) {
190         if (bookmark.part != contentIndex) {
191             t.trace(QString("Loading new part %1").arg(bookmark.part));
192             mBook->setLastBookmark(bookmark.part, bookmark.pos);
193             restorePositionAfterLoad = true;
194             positionAfterLoad = bookmark.pos;
195             loadContent(bookmark.part);
196         } else {
197             goToPosition(bookmark.pos);
198         }
199     }
200 }
201
202 void BookView::onLoadFinished(bool ok)
203 {
204     Trace t("BookView::onLoadFinished");
205     if (!ok) {
206         t.trace("Not OK");
207         return;
208     }
209     loaded = true;
210     addNavigationBar();
211     onSettingsChanged("scheme");
212     emit partLoadEnd(contentIndex);
213     showProgress();
214 }
215
216 void BookView::onSettingsChanged(const QString &key)
217 {
218     Trace t("BookView::onSettingsChanged " + key);
219     if (key == "zoom") {
220         setZoomFactor(Settings::instance()->value(key).toFloat() / 100.);
221     }
222     else if (key == "font") {
223         QString face = Settings::instance()->value("font").toString();
224         settings()->setFontFamily(QWebSettings::StandardFont, face);
225     }
226     else if (key == "scheme") {
227         QWebFrame *frame = page()->mainFrame();
228         QString scheme = Settings::instance()->value("scheme").toString();
229         if ((scheme != "day") && (scheme != "night") && (scheme != "sand") &&
230             (scheme != "default")) {
231             scheme = "default";
232         }
233         QFile script(":/styles/" + scheme + ".js");
234         script.open(QFile::ReadOnly);
235         QString scriptText = script.readAll();
236         script.close();
237         QVariant ret = frame->evaluateJavaScript(scriptText);
238     }
239 }
240
241 void BookView::paintEvent(QPaintEvent *e)
242 {
243     QWebView::paintEvent(e);
244     if (!mBook || !loaded) {
245         return;
246     }
247
248     // Paint bookmarks
249     QPoint scrollPos = page()->mainFrame()->scrollPosition();
250     QPixmap bookmarkPixmap = QPixmap::fromImage(bookmarkImage);
251     QPainter painter(this);
252     foreach (Book::Bookmark b, mBook->bookmarks()) {
253         if (b.part != contentIndex) {
254             continue;
255         }
256         int height = contentsHeight;
257         int bookmarkPos = (qreal)height * (qreal)b.pos;
258         painter.drawPixmap(2, bookmarkPos - scrollPos.y(), bookmarkPixmap);
259     }
260 }
261
262 void BookView::mousePressEvent(QMouseEvent *e)
263 {
264     QWebView::mousePressEvent(e);
265 #ifdef Q_WS_MAEMO_5
266     // Start monitoring kinetic scroll
267     if (scroller) {
268         scrollerMonitor = startTimer(250);
269     }
270 #else
271     // Handle mouse presses on the scroll bar
272     QWebFrame *frame = page()->mainFrame();
273     if (frame->scrollBarGeometry(Qt::Vertical).contains(e->pos())) {
274         e->accept();
275         return;
276     }
277 #endif // Q_WS_MAEMO_5
278     e->ignore();
279 }
280
281 void BookView::wheelEvent(QWheelEvent *e)
282 {
283     QWebView::wheelEvent(e);
284     showProgress();
285 }
286
287 void BookView::addBookmark()
288 {
289     Trace t("BookView::addBookmark");
290     if (!mBook) {
291         return;
292     }
293     int y = page()->mainFrame()->scrollPosition().y();
294     int height = page()->mainFrame()->contentsSize().height();
295     t.trace(QString().setNum((qreal)y / (qreal)height));
296     mBook->addBookmark(contentIndex, (qreal)y / (qreal)height);
297     update();
298 }
299
300 void BookView::addNavigationBar()
301 {
302     Trace t("BookView::addNavigationBar");
303     if (!mBook) {
304         return;
305     }
306
307     QString naviPrev =
308             "<a href=\"javascript:bv.goPrevious();\">"
309             "<img width=\"95\" height=\"95\" style=\"float:left;clear:none;\" "
310             "src=\"file://"
311             + tmpPath() +
312             "/previous.png\" />"
313             "</a>";
314     QString naviNext =
315             "<a href=\"javascript:bv.goNext();\">"
316             "<img width=\"95\" height=\"95\" style=\"float:right;clear:none;\" "
317             "src=\"file://"
318             + tmpPath() +
319             "/next.png\" />"
320             "</a>";
321     if (contentIndex == 0) {
322         naviPrev = "";
323     }
324     if (contentIndex >= mBook->parts.size() - 1) {
325         naviNext = "";
326     }
327
328     QWebFrame *frame = page()->currentFrame();
329     QString headerScript = "document.body.innerHTML = '" +
330         naviPrev + naviNext + "<br />" + "' + document.body.innerHTML;";
331     QString trailerScript = "document.body.innerHTML += '<br /><br />" +
332         naviPrev + naviNext + "';";
333
334     frame->evaluateJavaScript(headerScript);
335     frame->evaluateJavaScript(trailerScript);
336     decorated = true;
337 }
338
339 QString BookView::tmpPath()
340 {
341     return QDir::tempPath() + "/dorian";
342 }
343
344 void BookView::extractIcons()
345 {
346     QFile next(ICON_PREFIX + QString("/next.png"));
347     QFile prev(ICON_PREFIX + QString("/previous.png"));
348
349     QDir().mkpath(tmpPath());
350     next.copy(tmpPath() + "/next.png");
351     prev.copy(tmpPath() + "/previous.png");
352 }
353
354 void BookView::removeIcons()
355 {
356     QFile(ICON_PREFIX + QString("/next.png")).remove();
357     QFile(ICON_PREFIX + QString("/previous.png")).remove();
358     QDir().rmpath(tmpPath());
359 }
360
361 bool BookView::eventFilter(QObject *o, QEvent *e)
362 {
363     if (e->type() != QEvent::Paint && e->type() != QEvent::MouseMove) {
364         if (e->type() == QEvent::Resize) {
365             Trace::trace(QString("BookView::eventFilter QEvent::Resize to %1").
366                          arg(page()->mainFrame()->contentsSize().height()));
367         } else {
368             Trace::trace(QString("BookView::eventFilter %1").
369                          arg(Trace::event(e->type())));
370         }
371     }
372
373     // Work around Qt bug that sometimes selects web view contents during swipe
374     switch (e->type()) {
375     case QEvent::MouseButtonPress:
376         emit suppressedMouseButtonPress();
377         mousePressed = true;
378         break;
379     case QEvent::MouseButtonRelease:
380         showProgress();
381         mousePressed = false;
382         break;
383     case QEvent::MouseMove:
384         if (mousePressed) {
385             return true;
386         }
387         break;
388     case QEvent::MouseButtonDblClick:
389         return true;
390     default:
391         break;
392     }
393
394     return QObject::eventFilter(o, e);
395 }
396
397 void BookView::addJavaScriptObjects()
398 {
399     page()->mainFrame()->addToJavaScriptWindowObject("bv", this);
400 }
401
402 void BookView::onContentsSizeChanged(const QSize &size)
403 {
404     contentsHeight = size.height();
405     if (decorated) {
406         if (restorePositionAfterLoad) {
407             Trace::trace("BookView::onContentSizeChanged: Time to restore");
408             restorePositionAfterLoad = false;
409             goToPosition(positionAfterLoad);
410         }
411     }
412 }
413
414 void BookView::leaveEvent(QEvent *e)
415 {
416     Trace t("BookView::leaveEvent");
417     // Save current position, to be restored later
418     setLastBookmark();
419     QWebView::leaveEvent(e);
420 }
421
422 void BookView::enterEvent(QEvent *e)
423 {
424     Trace t("BookView::enterEvent");
425     // Restore position saved at Leave event. This seems to be required,
426     // after temporarily switching from portrait to landscape and back
427     restoreLastBookmark();
428     QWebView::enterEvent(e);
429 }
430
431 void BookView::goToPosition(qreal position)
432 {
433     int scrollPos = (qreal)contentsHeight * position;
434     page()->mainFrame()->setScrollPosition(QPoint(0, scrollPos));
435     // FIXME: update();
436     Trace::trace(QString("BookView::goToPosition: To %1 (%2%, height %3)").
437             arg(scrollPos).arg(position * 100).arg(contentsHeight));
438 }
439
440 void BookView::showProgress()
441 {
442     if (mBook) {
443         qreal pos = (qreal)(page()->mainFrame()->scrollPosition().y()) /
444                     (qreal)contentsHeight;
445         emit progress(mBook->getProgress(contentIndex, pos));
446     }
447 }
448
449 void BookView::timerEvent(QTimerEvent *e)
450 {
451     if (e->timerId() == scrollerMonitor) {
452 #ifdef Q_WS_MAEMO_5
453         if (scroller &&
454             ((scroller->state() == QAbstractKineticScroller::AutoScrolling) ||
455              (scroller->state() == QAbstractKineticScroller::Pushing))) {
456             showProgress();
457         } else {
458             killTimer(scrollerMonitor);
459         }
460 #endif // Q_WS_MAEMO_5
461     }
462 }
463
464 void BookView::keyPressEvent(QKeyEvent* event)
465 {
466     switch (event->key()) {
467     case Qt::Key_F7:
468         goNextPage();
469         event->accept();
470         break;
471     case Qt::Key_F8:
472         goPreviousPage();
473         event->accept();
474         break;
475     default:
476         ;
477     }
478     QWebView::keyPressEvent(event);
479 }
480
481 void BookView::goPreviousPage()
482 {
483     QWebFrame *frame = page()->mainFrame();
484     int pos = frame->scrollPosition().y();
485     frame->scroll(0, -height());
486     if (pos == frame->scrollPosition().y()) {
487         if (contentIndex > 0) {
488             goToBookmark(Book::Bookmark(contentIndex - 1, 1.0));
489         }
490     } else {
491         showProgress();
492     }
493 }
494
495 void BookView::goNextPage()
496 {
497     Trace t("BookView::goNextPage");
498     QWebFrame *frame = page()->mainFrame();
499     int pos = frame->scrollPosition().y();
500     frame->scroll(0, height());
501     if (pos == frame->scrollPosition().y()) {
502         goNext();
503     } else {
504         showProgress();
505     }
506 }