Improve chapter navigation: work around a QUrl bug.
[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)
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 #ifdef Q_WS_MAEMO_5
82     scrollerMonitor = 0;
83     scroller = property("kineticScroller").value<QAbstractKineticScroller *>();
84 #endif
85 }
86
87 BookView::~BookView()
88 {
89     Trace t("BookView::~BookView");
90 }
91
92 void BookView::loadContent(int index)
93 {
94     Trace t("BookView::loadContent");
95     if (!mBook) {
96         return;
97     }
98     if ((index < 0) || (index >= mBook->parts.size())) {
99         return;
100     }
101
102     QString contentFile(mBook->content[mBook->parts[index]].href);
103     if (mBook->parts[index] == "error") {
104         setHtml(contentFile);
105     }
106     else {
107         loaded = false;
108         emit partLoadStart(index);
109         QUrl u = QUrl::fromLocalFile(QDir(mBook->rootPath()).
110                                      absoluteFilePath(contentFile));
111         qDebug() << "Loading" << u;
112         load(u);
113     }
114     contentIndex = index;
115 }
116
117 void BookView::setBook(Book *book)
118 {
119     Trace t("BookView::setBook");
120
121     // Save position in current book
122     setLastBookmark();
123
124     // Open new book, restore last position
125     if (book != mBook) {
126         mBook = book;
127         if (book) {
128             contentIndex = -1;
129             if (book->open()) {
130                 restoreLastBookmark();
131             } else {
132                 mBook = 0;
133                 contentIndex = 0;
134                 setHtml(tr("Failed to open book"));
135             }
136         }
137         else {
138             contentIndex = 0;
139             setHtml(tr("No book"));
140         }
141     }
142 }
143
144 Book *BookView::book()
145 {
146     return mBook;
147 }
148
149 void BookView::goPrevious()
150 {
151     Trace t("BookView::goPrevious");
152     if (mBook && (contentIndex > 0)) {
153         mBook->setLastBookmark(contentIndex - 1, 0);
154         loadContent(contentIndex - 1);
155     }
156 }
157
158 void BookView::goNext()
159 {
160     Trace t("BookView::goNext");
161     if (mBook && (contentIndex < (mBook->parts.size() - 1))) {
162         mBook->setLastBookmark(contentIndex + 1, 0);
163         loadContent(contentIndex + 1);
164     }
165 }
166
167 void BookView::setLastBookmark()
168 {
169     Trace t("BookView::setLastBookmark");
170     if (mBook) {
171         int height = contentsHeight;
172         int pos = page()->mainFrame()->scrollPosition().y();
173         qDebug() << QString("At %1 (%2%, height %3)").
174                 arg(pos).arg((qreal)pos / (qreal)height * 100).arg(height);
175         mBook->setLastBookmark(contentIndex, (qreal)pos / (qreal)height);
176     }
177 }
178
179 void BookView::restoreLastBookmark()
180 {
181     Trace t("BookView::restoreLastBookmark");
182     if (mBook) {
183         goToBookmark(mBook->lastBookmark());
184     }
185 }
186
187 void BookView::goToBookmark(const Book::Bookmark &bookmark)
188 {
189     Trace t("BookView::goToBookmark");
190     if (mBook) {
191         if (bookmark.part != contentIndex) {
192             qDebug () << "Loading new part" << bookmark.part;
193             mBook->setLastBookmark(bookmark.part, bookmark.pos);
194             restorePositionAfterLoad = true;
195             positionAfterLoad = bookmark.pos;
196             loadContent(bookmark.part);
197         } else {
198             goToPosition(bookmark.pos);
199         }
200     }
201 }
202
203 void BookView::onLoadFinished(bool ok)
204 {
205     Trace t("BookView::onLoadFinished");
206     if (!ok) {
207         qDebug() << "Not OK";
208         return;
209     }
210     loaded = true;
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 = (int)((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 (scrollerMonitor) {
268         killTimer(scrollerMonitor);
269         scrollerMonitor = 0;
270     }
271     if (scroller) {
272         scrollerMonitor = startTimer(500);
273     }
274 #else
275     // Handle mouse presses on the scroll bar
276     QWebFrame *frame = page()->mainFrame();
277     if (frame->scrollBarGeometry(Qt::Vertical).contains(e->pos())) {
278         e->accept();
279         return;
280     }
281 #endif // Q_WS_MAEMO_5
282     e->ignore();
283 }
284
285 void BookView::wheelEvent(QWheelEvent *e)
286 {
287     QWebView::wheelEvent(e);
288     showProgress();
289 }
290
291 void BookView::addBookmark()
292 {
293     Trace t("BookView::addBookmark");
294     if (!mBook) {
295         return;
296     }
297     int y = page()->mainFrame()->scrollPosition().y();
298     int height = page()->mainFrame()->contentsSize().height();
299     qDebug() << ((qreal)y / (qreal)height);
300     mBook->addBookmark(contentIndex, (qreal)y / (qreal)height);
301     update();
302 }
303
304 QString BookView::tmpPath()
305 {
306     return QDir::tempPath() + "/dorian";
307 }
308
309 bool BookView::eventFilter(QObject *o, QEvent *e)
310 {
311     if (e->type() != QEvent::Paint && e->type() != QEvent::MouseMove) {
312         if (e->type() == QEvent::Resize) {
313             qDebug() << "BookView::eventFilter QEvent::Resize to"
314                     << page()->mainFrame()->contentsSize().height();
315         } else if (e->type() == QEvent::Timer) {
316             qDebug() << "BookView::eventFilter" << "QEvent::Timer"
317                     << ((QTimerEvent *)e)->timerId();
318         } else {
319             qDebug() << "BookView::eventFilter" << Trace::event(e->type());
320         }
321     }
322
323     // Work around Qt bug that sometimes selects web view contents during swipe
324     switch (e->type()) {
325     case QEvent::MouseButtonPress:
326         emit suppressedMouseButtonPress();
327         mousePressed = true;
328         break;
329     case QEvent::MouseButtonRelease:
330         showProgress();
331         mousePressed = false;
332         break;
333     case QEvent::MouseMove:
334         if (mousePressed) {
335             return true;
336         }
337         break;
338     case QEvent::MouseButtonDblClick:
339         return true;
340     default:
341         break;
342     }
343
344     return QObject::eventFilter(o, e);
345 }
346
347 void BookView::addJavaScriptObjects()
348 {
349     page()->mainFrame()->addToJavaScriptWindowObject("bv", this);
350 }
351
352 void BookView::onContentsSizeChanged(const QSize &size)
353 {
354     contentsHeight = size.height();
355     if (restorePositionAfterLoad) {
356         qDebug() << "BookView::onContentSizeChanged: Time to restore";
357         restorePositionAfterLoad = false;
358         goToPosition(positionAfterLoad);
359     }
360 }
361
362 void BookView::leaveEvent(QEvent *e)
363 {
364     Trace t("BookView::leaveEvent");
365     // Save current position, to be restored later
366     setLastBookmark();
367     QWebView::leaveEvent(e);
368 }
369
370 void BookView::enterEvent(QEvent *e)
371 {
372     Trace t("BookView::enterEvent");
373     // Restore position saved at Leave event. This seems to be required,
374     // after temporarily switching from portrait to landscape and back
375     restoreLastBookmark();
376     QWebView::enterEvent(e);
377 }
378
379 void BookView::goToPosition(qreal position)
380 {
381     int scrollPos = (int)((qreal)contentsHeight * position);
382     page()->mainFrame()->setScrollPosition(QPoint(0, scrollPos));
383     // FIXME: update();
384     qDebug() << "BookView::goToPosition: To" << scrollPos << "("
385             << (position * 100) << "%, height" << contentsHeight << ")";
386 }
387
388 void BookView::showProgress()
389 {
390     if (mBook) {
391         qreal pos = (qreal)(page()->mainFrame()->scrollPosition().y()) /
392                     (qreal)contentsHeight;
393         emit progress(mBook->getProgress(contentIndex, pos));
394     }
395 }
396
397 void BookView::timerEvent(QTimerEvent *e)
398 {
399 #ifdef Q_WS_MAEMO_5
400     if (e->timerId() == scrollerMonitor) {
401         if (scroller &&
402             ((scroller->state() == QAbstractKineticScroller::AutoScrolling) ||
403              (scroller->state() == QAbstractKineticScroller::Pushing))) {
404             showProgress();
405         } else {
406             killTimer(scrollerMonitor);
407         }
408     }
409 #else
410     Q_UNUSED(e);
411 #endif // Q_WS_MAEMO_5
412 }
413
414 void BookView::keyPressEvent(QKeyEvent* event)
415 {
416     switch (event->key()) {
417     case Qt::Key_F7:
418         goNextPage();
419         event->accept();
420         break;
421     case Qt::Key_F8:
422         goPreviousPage();
423         event->accept();
424         break;
425     default:
426         ;
427     }
428     QWebView::keyPressEvent(event);
429 }
430
431 void BookView::goPreviousPage()
432 {
433     QWebFrame *frame = page()->mainFrame();
434     int pos = frame->scrollPosition().y();
435     frame->scroll(0, -height());
436     if (pos == frame->scrollPosition().y()) {
437         if (contentIndex > 0) {
438             Book::Bookmark bookmark(contentIndex - 1, 1.0);
439             mBook->setLastBookmark(contentIndex - 1, 1.0);
440             goToBookmark(bookmark);
441         }
442     } else {
443         showProgress();
444     }
445 }
446
447 void BookView::goNextPage()
448 {
449     Trace t("BookView::goNextPage");
450     QWebFrame *frame = page()->mainFrame();
451     int pos = frame->scrollPosition().y();
452     frame->scroll(0, height());
453     if (pos == frame->scrollPosition().y()) {
454         goNext();
455     } else {
456         setLastBookmark();
457         showProgress();
458     }
459 }