Fix volume key navigation.
[dorian] / bookview.cpp
1 #include <QDir>
2 #include <QtGui>
3 #include <QWebFrame>
4
5 #if defined(Q_OS_SYMBIAN)
6 #   include "mediakeysobserver.h"
7 #   include "flickcharm.h"
8 #endif
9
10 #include "book.h"
11 #include "bookview.h"
12 #include "library.h"
13 #include "settings.h"
14 #include "trace.h"
15 #include "progress.h"
16 #include "progressdialog.h"
17 #include "platform.h"
18
19 BookView::BookView(QWidget *parent): QWebView(parent), contentIndex(-1), mBook(0),
20     restorePositionAfterLoad(false), positionAfterLoad(0), loaded(false),
21     contentsHeight(0), grabbingVolumeKeys(false)
22 {
23     TRACE;
24
25     // Set up web view defaults
26     settings()->setAttribute(QWebSettings::AutoLoadImages, true);
27     settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
28     settings()->setAttribute(QWebSettings::JavaEnabled, false);
29     settings()->setAttribute(QWebSettings::PluginsEnabled, false);
30     settings()->setAttribute(QWebSettings::PrivateBrowsingEnabled, true);
31     settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, false);
32     settings()->setAttribute(QWebSettings::JavascriptCanAccessClipboard, false);
33     settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled,
34                              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     QWebFrame *frame = page()->mainFrame();
44 #if defined(Q_WS_MAEMO_5) || defined(Q_OS_SYMBIAN)
45     frame->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);
46 #endif
47     frame->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
48     connect(this, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
49     connect(frame, SIGNAL(javaScriptWindowObjectCleared()),
50             this, SLOT(addJavaScriptObjects()));
51     connect(frame, SIGNAL(contentsSizeChanged(const QSize &)),
52             this, SLOT(onContentsSizeChanged(const QSize &)));
53
54     // Suppress unwanted text selections on Maemo and Symbian
55 #if defined(Q_WS_MAEMO_5) || defined(Q_OS_SYMBIAN)
56     installEventFilter(this);
57 #endif
58
59     // Pre-load bookmark icon
60     bookmarkImage = QImage(":/icons/bookmark.png");
61
62     // Handle settings changes, force handling initial settings
63     Settings *s = Settings::instance();
64     connect(s, SIGNAL(valueChanged(const QString &)),
65             this, SLOT(onSettingsChanged(const QString &)));
66     s->setValue("zoom", s->value("zoom", 160));
67     s->setValue("font", s->value("font", Platform::defaultFont()));
68     s->setValue("scheme", s->value("scheme", "default"));
69     s->setValue("usevolumekeys", s->value("usevolumekeys", false));
70     setBook(0);
71
72     // Enable kinetic scrolling
73 #if defined(Q_WS_MAEMO_5)
74     scrollerMonitor = 0;
75     scroller = property("kineticScroller").value<QAbstractKineticScroller *>();
76 #elif defined(Q_OS_SYMBIAN)
77     scrollerMonitor = 0;
78     charm = new FlickCharm(this);
79     charm->activateOn(this);
80 #endif
81
82     // Observe media keys on Symbian
83 #ifdef Q_OS_SYMBIAN
84     MediaKeysObserver *observer = MediaKeysObserver::instance();
85     connect(observer, SIGNAL(mediaKeyPressed(MediaKeysObserver::MediaKeys)),
86             this, SLOT(onMediaKeysPressed(MediaKeysObserver::MediaKeys)));
87 #endif
88 }
89
90 void BookView::loadContent(int index)
91 {
92     TRACE;
93
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     } else {
105         loaded = false;
106         emit partLoadStart(index);
107         QUrl u = QUrl::fromLocalFile(QDir(mBook->rootPath()).
108                                      absoluteFilePath(contentFile));
109         qDebug() << "Loading" << u;
110         load(u);
111     }
112     contentIndex = index;
113 }
114
115 void BookView::setBook(Book *book)
116 {
117     TRACE;
118
119     // Save position in current book
120     setLastBookmark();
121
122     // Open new book, restore last position
123     if (book != mBook) {
124         mBook = book;
125         if (book) {
126             contentIndex = -1;
127             if (book->open()) {
128                 restoreLastBookmark();
129             } else {
130                 mBook = 0;
131                 contentIndex = 0;
132                 setHtml(tr("Failed to open book"));
133             }
134         }
135         else {
136             contentIndex = 0;
137             setHtml(tr("No book"));
138         }
139     }
140 }
141
142 Book *BookView::book()
143 {
144     return mBook;
145 }
146
147 void BookView::goPrevious()
148 {
149     TRACE;
150     if (mBook && (contentIndex > 0)) {
151         mBook->setLastBookmark(contentIndex - 1, 0);
152         loadContent(contentIndex - 1);
153     }
154 }
155
156 void BookView::goNext()
157 {
158     TRACE;
159     if (mBook && (contentIndex < (mBook->parts.size() - 1))) {
160         mBook->setLastBookmark(contentIndex + 1, 0);
161         loadContent(contentIndex + 1);
162     }
163 }
164
165 void BookView::setLastBookmark()
166 {
167     TRACE;
168     if (mBook) {
169         int height = contentsHeight;
170         int pos = page()->mainFrame()->scrollPosition().y();
171         qDebug() << QString("At %1 (%2%, height %3)").
172                 arg(pos).arg((qreal)pos / (qreal)height * 100).arg(height);
173         mBook->setLastBookmark(contentIndex, (qreal)pos / (qreal)height);
174     }
175 }
176
177 void BookView::restoreLastBookmark()
178 {
179     TRACE;
180     if (mBook) {
181         goToBookmark(mBook->lastBookmark());
182     }
183 }
184
185 void BookView::goToBookmark(const Book::Bookmark &bookmark)
186 {
187     TRACE;
188     if (mBook) {
189         if (bookmark.part != contentIndex) {
190             qDebug () << "Loading new part" << bookmark.part;
191             mBook->setLastBookmark(bookmark.part, bookmark.pos);
192             restorePositionAfterLoad = true;
193             positionAfterLoad = bookmark.pos;
194             loadContent(bookmark.part);
195         } else {
196             goToPosition(bookmark.pos);
197         }
198     }
199 }
200
201 void BookView::goToPart(int part, const QString &fragment)
202 {
203     TRACE;
204     if (mBook) {
205         if (part != contentIndex) {
206             qDebug() << "Loading new part" << part;
207             restoreFragmentAfterLoad = true;
208             fragmentAfterLoad = fragment;
209             loadContent(part);
210         } else {
211             goToFragment(fragment);
212             showProgress();
213         }
214     }
215 }
216
217 void BookView::goToFragment(const QString &fragment)
218 {
219     TRACE;
220     if (!fragment.isEmpty()) {
221         QVariant ret = page()->mainFrame()->evaluateJavaScript(
222                 QString("window.location='") + fragment + "'");
223         qDebug() << ret;
224         setLastBookmark();
225     }
226 }
227
228 void BookView::onLoadFinished(bool ok)
229 {
230     TRACE;
231     if (!ok) {
232         qDebug() << "Not OK";
233         return;
234     }
235     loaded = true;
236     onSettingsChanged("scheme");
237     onSettingsChanged("zoom");
238     onSettingsChanged("font");
239     emit partLoadEnd(contentIndex);
240     showProgress();
241 }
242
243 void BookView::onSettingsChanged(const QString &key)
244 {
245     TRACE;
246     qDebug() << key << Settings::instance()->value(key);
247
248     if (key == "zoom") {
249         setZoomFactor(Settings::instance()->value(key).toFloat() / 100.);
250     }
251     else if (key == "font") {
252         QString face = Settings::instance()->value(key).toString();
253         settings()->setFontFamily(QWebSettings::StandardFont, face);
254     }
255     else if (key == "scheme") {
256         QWebFrame *frame = page()->mainFrame();
257         QString scheme = Settings::instance()->value("scheme").toString();
258         if ((scheme != "day") && (scheme != "night") && (scheme != "sand") &&
259             (scheme != "default")) {
260             scheme = "default";
261         }
262         QFile script(":/styles/" + scheme + ".js");
263         script.open(QFile::ReadOnly);
264         QString scriptText = script.readAll();
265         script.close();
266         QVariant ret = frame->evaluateJavaScript(scriptText);
267     }
268     else if (key == "usevolumekeys") {
269         grabVolumeKeys(Settings::instance()->value(key).toBool());
270     }
271 }
272
273 void BookView::paintEvent(QPaintEvent *e)
274 {
275     QWebView::paintEvent(e);
276     if (!mBook || !loaded) {
277         return;
278     }
279
280     // Paint bookmarks
281     QPoint scrollPos = page()->mainFrame()->scrollPosition();
282     QPixmap bookmarkPixmap = QPixmap::fromImage(bookmarkImage);
283     QPainter painter(this);
284     foreach (Book::Bookmark b, mBook->bookmarks()) {
285         if (b.part != contentIndex) {
286             continue;
287         }
288         int height = contentsHeight;
289         int bookmarkPos = (int)((qreal)height * (qreal)b.pos);
290         painter.drawPixmap(2, bookmarkPos - scrollPos.y(), bookmarkPixmap);
291     }
292 }
293
294 void BookView::mousePressEvent(QMouseEvent *e)
295 {
296     QWebView::mousePressEvent(e);
297 #if defined(Q_WS_MAEMO_5)
298     // Start monitoring kinetic scroll
299     if (scrollerMonitor) {
300         killTimer(scrollerMonitor);
301         scrollerMonitor = 0;
302     }
303     if (scroller) {
304         scrollerMonitor = startTimer(500);
305     }
306 #else
307     // Handle mouse presses on the scroll bar
308     QWebFrame *frame = page()->mainFrame();
309     if (frame->scrollBarGeometry(Qt::Vertical).contains(e->pos())) {
310         e->accept();
311         return;
312     }
313 #endif // Q_WS_MAEMO_5
314     e->ignore();
315 }
316
317 void BookView::wheelEvent(QWheelEvent *e)
318 {
319     QWebView::wheelEvent(e);
320     showProgress();
321 }
322
323 void BookView::addBookmark(const QString &note)
324 {
325     TRACE;
326     if (!mBook) {
327         return;
328     }
329     int y = page()->mainFrame()->scrollPosition().y();
330     int height = page()->mainFrame()->contentsSize().height();
331     qDebug() << ((qreal)y / (qreal)height);
332     mBook->addBookmark(contentIndex, (qreal)y / (qreal)height, note);
333     update();
334 }
335
336 QString BookView::tmpPath()
337 {
338     return QDir::tempPath() + "/dorian";
339 }
340
341 bool BookView::eventFilter(QObject *o, QEvent *e)
342 {
343 #if 0
344     if (e->type() != QEvent::Paint && e->type() != QEvent::MouseMove) {
345         if (e->type() == QEvent::Resize) {
346             qDebug() << "BookView::eventFilter QEvent::Resize to"
347                     << page()->mainFrame()->contentsSize().height();
348         } else if (e->type() == QEvent::Timer) {
349             qDebug() << "BookView::eventFilter" << "QEvent::Timer"
350                     << ((QTimerEvent *)e)->timerId();
351         } else {
352             qDebug() << "BookView::eventFilter" << Trace::event(e->type());
353         }
354     }
355 #endif
356
357     // Work around Qt bug that sometimes selects web view contents during swipe
358     switch (e->type()) {
359     case QEvent::MouseButtonPress:
360         emit suppressedMouseButtonPress();
361         mousePressed = true;
362         break;
363     case QEvent::MouseButtonRelease:
364         showProgress();
365         mousePressed = false;
366         break;
367     case QEvent::MouseMove:
368         if (mousePressed) {
369             return true;
370         }
371         break;
372     case QEvent::MouseButtonDblClick:
373         return true;
374     default:
375         break;
376     }
377
378     return QObject::eventFilter(o, e);
379 }
380
381 void BookView::addJavaScriptObjects()
382 {
383     page()->mainFrame()->addToJavaScriptWindowObject("bv", this);
384 }
385
386 void BookView::onContentsSizeChanged(const QSize &size)
387 {
388     TRACE;
389     contentsHeight = size.height();
390     if (restoreFragmentAfterLoad) {
391         qDebug() << "Restorint to fragment" << fragmentAfterLoad;
392         goToFragment(fragmentAfterLoad);
393     } else if (restorePositionAfterLoad) {
394         qDebug() << "Restoring to position";
395         goToPosition(positionAfterLoad);
396     }
397     restorePositionAfterLoad = false;
398     restoreFragmentAfterLoad = false;
399 }
400
401 #ifdef Q_WS_MAEMO_5
402
403 void BookView::leaveEvent(QEvent *e)
404 {
405     TRACE;
406     // Save current position, to be restored later
407     setLastBookmark();
408     QWebView::leaveEvent(e);
409 }
410
411 void BookView::enterEvent(QEvent *e)
412 {
413     TRACE;
414     // Restore position saved at Leave event. This seems to be required,
415     // after temporarily switching from portrait to landscape and back
416     restoreLastBookmark();
417     QWebView::enterEvent(e);
418 }
419
420 #endif // Q_WS_MAEMO_5
421
422 void BookView::goToPosition(qreal position)
423 {
424     int scrollPos = (int)((qreal)contentsHeight * position);
425     page()->mainFrame()->setScrollPosition(QPoint(0, scrollPos));
426     // FIXME: update();
427     qDebug() << "BookView::goToPosition: To" << scrollPos << "("
428             << (position * 100) << "%, height" << 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 defined(Q_WS_MAEMO_5)
443     if (e->timerId() == scrollerMonitor) {
444         if (scroller &&
445             ((scroller->state() == QAbstractKineticScroller::AutoScrolling) ||
446              (scroller->state() == QAbstractKineticScroller::Pushing))) {
447             showProgress();
448         } else {
449             killTimer(scrollerMonitor);
450             scrollerMonitor = -1;
451         }
452     }
453 #endif
454     QWebView::timerEvent(e);
455 }
456
457 void BookView::goPreviousPage()
458 {
459     QWebFrame *frame = page()->mainFrame();
460     int pos = frame->scrollPosition().y();
461     frame->scroll(0, -height());
462     if (pos == frame->scrollPosition().y()) {
463         if (contentIndex > 0) {
464             Book::Bookmark bookmark(contentIndex - 1, 1.0);
465             mBook->setLastBookmark(contentIndex - 1, 1.0);
466             goToBookmark(bookmark);
467         }
468     } else {
469         showProgress();
470     }
471 }
472
473 void BookView::goNextPage()
474 {
475     TRACE;
476     QWebFrame *frame = page()->mainFrame();
477     int pos = frame->scrollPosition().y();
478     frame->scroll(0, height());
479     if (pos == frame->scrollPosition().y()) {
480         goNext();
481     } else {
482         setLastBookmark();
483         showProgress();
484     }
485 }
486
487 void BookView::grabVolumeKeys(bool grab)
488 {
489     TRACE;
490     grabbingVolumeKeys = grab;
491 }
492
493 #ifdef Q_OS_SYMBIAN
494
495 void BookView::onMediaKeysPressed(MediaKeysObserver::MediaKeys key)
496 {
497     TRACE;
498     qDebug() << "Key" << (int)key;
499     if (grabbingVolumeKeys) {
500         if (key == MediaKeysObserver::EVolIncKey) {
501             qDebug() << "Volume up";
502             goPreviousPage();
503         } else if (key == MediaKeysObserver::EVolDecKey){
504             qDebug() << "Volume down";
505             goNextPage();
506         }
507     }
508 }
509
510 #endif // Q_OS_SYMBIAN