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