Fix kinetic scrolling on Symbian. Fix timer handling.
[dorian] / bookview.cpp
1 #include <QDebug>
2 #include <QWebFrame>
3 #include <QMouseEvent>
4 #include <QFile>
5 #include <QDir>
6 #include <QTimer>
7
8 #if defined(Q_WS_MAEMO_5)
9 #   include <QAbstractKineticScroller>
10 #elif defined(Q_OS_SYMBIAN)
11 #   include "flickcharm.h"
12 #endif
13
14 #include "book.h"
15 #include "bookview.h"
16 #include "library.h"
17 #include "settings.h"
18 #include "trace.h"
19 #include "progress.h"
20
21 BookView::BookView(QWidget *parent):
22     QWebView(parent), contentIndex(-1), mBook(0),
23     restorePositionAfterLoad(false), positionAfterLoad(0), loaded(false),
24     contentsHeight(0)
25 {
26     Trace t("BookView::BookView");
27     settings()->setAttribute(QWebSettings::AutoLoadImages, true);
28     settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
29     settings()->setAttribute(QWebSettings::JavaEnabled, false);
30     settings()->setAttribute(QWebSettings::PluginsEnabled, false);
31     settings()->setAttribute(QWebSettings::PrivateBrowsingEnabled, true);
32     settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, false);
33     settings()->setAttribute(QWebSettings::JavascriptCanAccessClipboard, false);
34     settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, false);
35     settings()->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled,
36                              false);
37     settings()->setAttribute(QWebSettings::LocalStorageEnabled, false);
38     settings()->setAttribute(QWebSettings::ZoomTextOnly, true);
39     settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,
40                              false);
41     settings()->setDefaultTextEncoding("utf-8");
42     page()->setContentEditable(false);
43
44 #if defined(Q_WS_MAEMO_5) || defined(Q_OS_SYMBIAN)
45     // Suppress unwanted text selections on Maemo and Symbian
46     installEventFilter(this);
47 #endif
48     QWebFrame *frame = page()->mainFrame();
49 #if defined(Q_WS_MAEMO_5) || defined(Q_OS_SYMBIAN)
50     frame->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);
51 #endif
52     frame->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
53
54     bookmarkImage = QImage(":/icons/bookmark.png");
55
56     connect(this, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
57     connect(frame, SIGNAL(javaScriptWindowObjectCleared()),
58             this, SLOT(addJavaScriptObjects()));
59     connect(frame, SIGNAL(contentsSizeChanged(const QSize &)),
60             this, SLOT(onContentsSizeChanged(const QSize &)));
61     connect(Settings::instance(), SIGNAL(valueChanged(const QString &)),
62             this, SLOT(onSettingsChanged(const QString &)));
63     Settings *s = Settings::instance();
64     s->setValue("zoom", s->value("zoom", 160));
65     s->setValue("font", s->value("font",
66 #if defined(Q_WS_MAEMO_5) || defined(Q_WS_X11)
67                                  "Serif"
68 #elif defined(Q_WS_MAC)
69                                  "Hoefler Text"
70 #else
71                                  "Times New Roman"
72 #endif
73                                  ));
74     s->setValue("scheme", s->value("scheme", "default"));
75     setBook(0);
76
77 #if defined(Q_WS_MAEMO_5)
78     scrollerMonitor = 0;
79     scroller = property("kineticScroller").value<QAbstractKineticScroller *>();
80 #elif defined(Q_OS_SYMBIAN)
81     FlickCharm *charm = new FlickCharm(this);
82     charm->activateOn(this);
83 #endif
84 }
85
86 BookView::~BookView()
87 {
88     Trace t("BookView::~BookView");
89 }
90
91 void BookView::loadContent(int index)
92 {
93     Trace t("BookView::loadContent");
94     if (!mBook) {
95         return;
96     }
97     if ((index < 0) || (index >= mBook->parts.size())) {
98         return;
99     }
100
101     QString contentFile(mBook->content[mBook->parts[index]].href);
102     if (mBook->parts[index] == "error") {
103         setHtml(contentFile);
104     }
105     else {
106         loaded = false;
107         emit partLoadStart(index);
108         QUrl u = QUrl::fromLocalFile(QDir(mBook->rootPath()).
109                                      absoluteFilePath(contentFile));
110         qDebug() << "Loading" << u;
111         load(u);
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         qDebug() << 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             qDebug () << "Loading new part" << 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         qDebug() << "Not OK";
207         return;
208     }
209     loaded = true;
210     onSettingsChanged("scheme");
211     emit partLoadEnd(contentIndex);
212     showProgress();
213 }
214
215 void BookView::onSettingsChanged(const QString &key)
216 {
217     Trace t("BookView::onSettingsChanged " + key);
218     if (key == "zoom") {
219         setZoomFactor(Settings::instance()->value(key).toFloat() / 100.);
220     }
221     else if (key == "font") {
222         QString face = Settings::instance()->value("font").toString();
223         settings()->setFontFamily(QWebSettings::StandardFont, face);
224     }
225     else if (key == "scheme") {
226         QWebFrame *frame = page()->mainFrame();
227         QString scheme = Settings::instance()->value("scheme").toString();
228         if ((scheme != "day") && (scheme != "night") && (scheme != "sand") &&
229             (scheme != "default")) {
230             scheme = "default";
231         }
232         QFile script(":/styles/" + scheme + ".js");
233         script.open(QFile::ReadOnly);
234         QString scriptText = script.readAll();
235         script.close();
236         QVariant ret = frame->evaluateJavaScript(scriptText);
237     }
238 }
239
240 void BookView::paintEvent(QPaintEvent *e)
241 {
242     QWebView::paintEvent(e);
243     if (!mBook || !loaded) {
244         return;
245     }
246
247     // Paint bookmarks
248     QPoint scrollPos = page()->mainFrame()->scrollPosition();
249     QPixmap bookmarkPixmap = QPixmap::fromImage(bookmarkImage);
250     QPainter painter(this);
251     foreach (Book::Bookmark b, mBook->bookmarks()) {
252         if (b.part != contentIndex) {
253             continue;
254         }
255         int height = contentsHeight;
256         int bookmarkPos = (int)((qreal)height * (qreal)b.pos);
257         painter.drawPixmap(2, bookmarkPos - scrollPos.y(), bookmarkPixmap);
258     }
259 }
260
261 void BookView::mousePressEvent(QMouseEvent *e)
262 {
263     QWebView::mousePressEvent(e);
264 #ifdef Q_WS_MAEMO_5
265     // Start monitoring kinetic scroll
266     if (scrollerMonitor) {
267         killTimer(scrollerMonitor);
268         scrollerMonitor = 0;
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 #ifdef Q_WS_MAEMO_5
399     if (e->timerId() == scrollerMonitor) {
400         if (scroller &&
401             ((scroller->state() == QAbstractKineticScroller::AutoScrolling) ||
402              (scroller->state() == QAbstractKineticScroller::Pushing))) {
403             showProgress();
404         } else {
405             killTimer(scrollerMonitor);
406         }
407     }
408 #endif
409     QWebView::timerEvent(e);
410 }
411
412 void BookView::keyPressEvent(QKeyEvent* event)
413 {
414     switch (event->key()) {
415     case Qt::Key_F7:
416         goNextPage();
417         event->accept();
418         break;
419     case Qt::Key_F8:
420         goPreviousPage();
421         event->accept();
422         break;
423     default:
424         ;
425     }
426     QWebView::keyPressEvent(event);
427 }
428
429 void BookView::goPreviousPage()
430 {
431     QWebFrame *frame = page()->mainFrame();
432     int pos = frame->scrollPosition().y();
433     frame->scroll(0, -height());
434     if (pos == frame->scrollPosition().y()) {
435         if (contentIndex > 0) {
436             Book::Bookmark bookmark(contentIndex - 1, 1.0);
437             mBook->setLastBookmark(contentIndex - 1, 1.0);
438             goToBookmark(bookmark);
439         }
440     } else {
441         showProgress();
442     }
443 }
444
445 void BookView::goNextPage()
446 {
447     Trace t("BookView::goNextPage");
448     QWebFrame *frame = page()->mainFrame();
449     int pos = frame->scrollPosition().y();
450     frame->scroll(0, height());
451     if (pos == frame->scrollPosition().y()) {
452         goNext();
453     } else {
454         setLastBookmark();
455         showProgress();
456     }
457 }