Fix progress and bookmark positions. Fix runaway scroll monitor timer.
[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     }
270     if (scroller) {
271         scrollerMonitor = startTimer(500);
272     }
273 #else
274     // Handle mouse presses on the scroll bar
275     QWebFrame *frame = page()->mainFrame();
276     if (frame->scrollBarGeometry(Qt::Vertical).contains(e->pos())) {
277         e->accept();
278         return;
279     }
280 #endif // Q_WS_MAEMO_5
281     e->ignore();
282 }
283
284 void BookView::wheelEvent(QWheelEvent *e)
285 {
286     QWebView::wheelEvent(e);
287     showProgress();
288 }
289
290 void BookView::addBookmark()
291 {
292     Trace t("BookView::addBookmark");
293     if (!mBook) {
294         return;
295     }
296     int y = page()->mainFrame()->scrollPosition().y();
297     int height = page()->mainFrame()->contentsSize().height();
298     qDebug() << ((qreal)y / (qreal)height);
299     mBook->addBookmark(contentIndex, (qreal)y / (qreal)height);
300     update();
301 }
302
303 QString BookView::tmpPath()
304 {
305     return QDir::tempPath() + "/dorian";
306 }
307
308 bool BookView::eventFilter(QObject *o, QEvent *e)
309 {
310     if (e->type() != QEvent::Paint && e->type() != QEvent::MouseMove) {
311         if (e->type() == QEvent::Resize) {
312             qDebug() << "BookView::eventFilter QEvent::Resize to"
313                     << page()->mainFrame()->contentsSize().height();
314         } else if (e->type() == QEvent::Timer) {
315             qDebug() << "BookView::eventFilter" << "QEvent::Timer"
316                     << ((QTimerEvent *)e)->timerId();
317         } else {
318             qDebug() << "BookView::eventFilter" << Trace::event(e->type());
319         }
320     }
321
322     // Work around Qt bug that sometimes selects web view contents during swipe
323     switch (e->type()) {
324     case QEvent::MouseButtonPress:
325         emit suppressedMouseButtonPress();
326         mousePressed = true;
327         break;
328     case QEvent::MouseButtonRelease:
329         showProgress();
330         mousePressed = false;
331         break;
332     case QEvent::MouseMove:
333         if (mousePressed) {
334             return true;
335         }
336         break;
337     case QEvent::MouseButtonDblClick:
338         return true;
339     default:
340         break;
341     }
342
343     return QObject::eventFilter(o, e);
344 }
345
346 void BookView::addJavaScriptObjects()
347 {
348     page()->mainFrame()->addToJavaScriptWindowObject("bv", this);
349 }
350
351 void BookView::onContentsSizeChanged(const QSize &size)
352 {
353     contentsHeight = size.height();
354     if (restorePositionAfterLoad) {
355         qDebug() << "BookView::onContentSizeChanged: Time to restore";
356         restorePositionAfterLoad = false;
357         goToPosition(positionAfterLoad);
358     }
359 }
360
361 void BookView::leaveEvent(QEvent *e)
362 {
363     Trace t("BookView::leaveEvent");
364     // Save current position, to be restored later
365     setLastBookmark();
366     QWebView::leaveEvent(e);
367 }
368
369 void BookView::enterEvent(QEvent *e)
370 {
371     Trace t("BookView::enterEvent");
372     // Restore position saved at Leave event. This seems to be required,
373     // after temporarily switching from portrait to landscape and back
374     restoreLastBookmark();
375     QWebView::enterEvent(e);
376 }
377
378 void BookView::goToPosition(qreal position)
379 {
380     int scrollPos = (int)((qreal)contentsHeight * position);
381     page()->mainFrame()->setScrollPosition(QPoint(0, scrollPos));
382     // FIXME: update();
383     qDebug() << "BookView::goToPosition: To" << scrollPos << "("
384             << (position * 100) << "%, height" << contentsHeight << ")";
385 }
386
387 void BookView::showProgress()
388 {
389     if (mBook) {
390         qreal pos = (qreal)(page()->mainFrame()->scrollPosition().y()) /
391                     (qreal)contentsHeight;
392         emit progress(mBook->getProgress(contentIndex, pos));
393     }
394 }
395
396 void BookView::timerEvent(QTimerEvent *e)
397 {
398     if (e->timerId() == scrollerMonitor) {
399 #ifdef Q_WS_MAEMO_5
400         if (scroller &&
401             ((scroller->state() == QAbstractKineticScroller::AutoScrolling) ||
402              (scroller->state() == QAbstractKineticScroller::Pushing))) {
403             showProgress();
404         } else {
405             killTimer(scrollerMonitor);
406         }
407 #endif // Q_WS_MAEMO_5
408     }
409 }
410
411 void BookView::keyPressEvent(QKeyEvent* event)
412 {
413     switch (event->key()) {
414     case Qt::Key_F7:
415         goNextPage();
416         event->accept();
417         break;
418     case Qt::Key_F8:
419         goPreviousPage();
420         event->accept();
421         break;
422     default:
423         ;
424     }
425     QWebView::keyPressEvent(event);
426 }
427
428 void BookView::goPreviousPage()
429 {
430     QWebFrame *frame = page()->mainFrame();
431     int pos = frame->scrollPosition().y();
432     frame->scroll(0, -height());
433     if (pos == frame->scrollPosition().y()) {
434         if (contentIndex > 0) {
435             Book::Bookmark bookmark(contentIndex - 1, 1.0);
436             mBook->setLastBookmark(contentIndex - 1, 1.0);
437             goToBookmark(bookmark);
438         }
439     } else {
440         showProgress();
441     }
442 }
443
444 void BookView::goNextPage()
445 {
446     Trace t("BookView::goNextPage");
447     QWebFrame *frame = page()->mainFrame();
448     int pos = frame->scrollPosition().y();
449     frame->scroll(0, height());
450     if (pos == frame->scrollPosition().y()) {
451         goNext();
452     } else {
453         setLastBookmark();
454         showProgress();
455     }
456 }