Enable tracing to file. Attempt to fix last position restoration on S^3.
[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     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     if (restoreFragmentAfterLoad) {
245         qDebug() << "Restorint to fragment" << fragmentAfterLoad;
246         goToFragment(fragmentAfterLoad);
247         restoreFragmentAfterLoad = false;
248     } else if (restorePositionAfterLoad) {
249         qDebug() << "Restoring to position" << positionAfterLoad;
250         goToPosition(positionAfterLoad);
251         restorePositionAfterLoad = false;
252     }
253
254     emit partLoadEnd(contentIndex);
255     showProgress();
256 }
257
258 void BookView::onSettingsChanged(const QString &key)
259 {
260     TRACE;
261     qDebug() << key << Settings::instance()->value(key);
262
263     if (key == "zoom") {
264         setZoomFactor(Settings::instance()->value(key).toFloat() / 100.);
265     }
266     else if (key == "font") {
267         QString face = Settings::instance()->value(key).toString();
268         settings()->setFontFamily(QWebSettings::StandardFont, face);
269     }
270     else if (key == "scheme") {
271         QWebFrame *frame = page()->mainFrame();
272         QString scheme = Settings::instance()->value("scheme").toString();
273         if ((scheme != "day") && (scheme != "night") && (scheme != "sand") &&
274             (scheme != "default")) {
275             scheme = "default";
276         }
277         QFile script(":/styles/" + scheme + ".js");
278         script.open(QFile::ReadOnly);
279         QString scriptText = script.readAll();
280         script.close();
281         QVariant ret = frame->evaluateJavaScript(scriptText);
282     }
283     else if (key == "usevolumekeys") {
284         grabVolumeKeys(Settings::instance()->value(key).toBool());
285     }
286 }
287
288 void BookView::paintEvent(QPaintEvent *e)
289 {
290     QWebView::paintEvent(e);
291     if (!mBook || !loaded) {
292         return;
293     }
294
295     // Paint bookmarks
296     QWebFrame *frame = page()->mainFrame();
297     int contentsHeight = frame->contentsSize().height();
298     QPoint scrollPos = frame->scrollPosition();
299     QPixmap bookmarkPixmap = QPixmap::fromImage(bookmarkImage);
300     QPainter painter(this);
301     foreach (Book::Bookmark b, mBook->bookmarks()) {
302         if (b.part != contentIndex) {
303             continue;
304         }
305         int height = contentsHeight;
306         int bookmarkPos = (int)((qreal)height * (qreal)b.pos);
307         painter.drawPixmap(2, bookmarkPos - scrollPos.y(), bookmarkPixmap);
308     }
309 }
310
311 void BookView::mousePressEvent(QMouseEvent *e)
312 {
313     QWebView::mousePressEvent(e);
314 #if defined(Q_WS_MAEMO_5)
315     // Start monitoring kinetic scroll
316     if (scrollerMonitor) {
317         killTimer(scrollerMonitor);
318         scrollerMonitor = 0;
319     }
320     if (scroller) {
321         scrollerMonitor = startTimer(500);
322     }
323 #else
324     // Handle mouse presses on the scroll bar
325     QWebFrame *frame = page()->mainFrame();
326     if (frame->scrollBarGeometry(Qt::Vertical).contains(e->pos())) {
327         e->accept();
328         return;
329     }
330 #endif // Q_WS_MAEMO_5
331     e->ignore();
332 }
333
334 void BookView::wheelEvent(QWheelEvent *e)
335 {
336     QWebView::wheelEvent(e);
337     showProgress();
338 }
339
340 void BookView::addBookmark(const QString &note)
341 {
342     TRACE;
343     if (!mBook) {
344         return;
345     }
346     int y = page()->mainFrame()->scrollPosition().y();
347     int height = page()->mainFrame()->contentsSize().height();
348     qDebug() << ((qreal)y / (qreal)height);
349     mBook->addBookmark(contentIndex, (qreal)y / (qreal)height, note);
350     update();
351 }
352
353 QString BookView::tmpPath()
354 {
355     return QDir::tempPath() + "/dorian";
356 }
357
358 bool BookView::eventFilter(QObject *o, QEvent *e)
359 {
360 #if 0
361     if (e->type() != QEvent::Paint && e->type() != QEvent::MouseMove) {
362         if (e->type() == QEvent::Resize) {
363             qDebug() << "BookView::eventFilter QEvent::Resize to"
364                     << page()->mainFrame()->contentsSize().height();
365         } else if (e->type() == QEvent::Timer) {
366             qDebug() << "BookView::eventFilter" << "QEvent::Timer"
367                     << ((QTimerEvent *)e)->timerId();
368         } else {
369             qDebug() << "BookView::eventFilter" << Trace::event(e->type());
370         }
371     }
372 #endif
373
374     // Work around Qt bug that sometimes selects web view contents during swipe
375     switch (e->type()) {
376     case QEvent::MouseButtonPress:
377         emit suppressedMouseButtonPress();
378         mousePressed = true;
379         break;
380     case QEvent::MouseButtonRelease:
381         showProgress();
382         mousePressed = false;
383         break;
384     case QEvent::MouseMove:
385         if (mousePressed) {
386             return true;
387         }
388         break;
389     case QEvent::MouseButtonDblClick:
390         return true;
391     default:
392         break;
393     }
394
395     return QObject::eventFilter(o, e);
396 }
397
398 void BookView::addJavaScriptObjects()
399 {
400     page()->mainFrame()->addToJavaScriptWindowObject("bv", this);
401 }
402
403 #ifdef Q_WS_MAEMO_5
404
405 void BookView::leaveEvent(QEvent *e)
406 {
407     TRACE;
408     // Save current position, to be restored later
409     setLastBookmark();
410     QWebView::leaveEvent(e);
411 }
412
413 void BookView::enterEvent(QEvent *e)
414 {
415     TRACE;
416     // Restore position saved at Leave event. This seems to be required,
417     // after temporarily switching from portrait to landscape and back
418     restoreLastBookmark();
419     QWebView::enterEvent(e);
420 }
421
422 #endif // Q_WS_MAEMO_5
423
424 void BookView::goToPosition(qreal position)
425 {
426     int contentsHeight = page()->mainFrame()->contentsSize().height();
427     int scrollPos = (int)((qreal)contentsHeight * position);
428     page()->mainFrame()->setScrollPosition(QPoint(0, scrollPos));
429     // FIXME: update();
430     qDebug() << "BookView::goToPosition: To" << scrollPos << "("
431             << (position * 100) << "%, height" << contentsHeight << ")";
432 }
433
434 void BookView::showProgress()
435 {
436     if (mBook) {
437         int contentsHeight = page()->mainFrame()->contentsSize().height();
438         qreal pos = (qreal)(page()->mainFrame()->scrollPosition().y()) /
439                     (qreal)contentsHeight;
440         emit progress(mBook->getProgress(contentIndex, pos));
441     }
442 }
443
444 void BookView::timerEvent(QTimerEvent *e)
445 {
446 #if defined(Q_WS_MAEMO_5)
447     if (e->timerId() == scrollerMonitor) {
448         if (scroller &&
449             ((scroller->state() == QAbstractKineticScroller::AutoScrolling) ||
450              (scroller->state() == QAbstractKineticScroller::Pushing))) {
451             showProgress();
452         } else {
453             killTimer(scrollerMonitor);
454             scrollerMonitor = -1;
455         }
456     }
457 #endif
458     QWebView::timerEvent(e);
459 }
460
461 void BookView::goPreviousPage()
462 {
463     QWebFrame *frame = page()->mainFrame();
464     int pos = frame->scrollPosition().y();
465     frame->scroll(0, -height());
466     if (pos == frame->scrollPosition().y()) {
467         if (contentIndex > 0) {
468             Book::Bookmark bookmark(contentIndex - 1, 1.0);
469             mBook->setLastBookmark(contentIndex - 1, 1.0);
470             goToBookmark(bookmark);
471         }
472     } else {
473         showProgress();
474     }
475 }
476
477 void BookView::goNextPage()
478 {
479     TRACE;
480     QWebFrame *frame = page()->mainFrame();
481     int pos = frame->scrollPosition().y();
482     frame->scroll(0, height());
483     if (pos == frame->scrollPosition().y()) {
484         goNext();
485     } else {
486         setLastBookmark();
487         showProgress();
488     }
489 }
490
491 void BookView::grabVolumeKeys(bool grab)
492 {
493     TRACE;
494     grabbingVolumeKeys = grab;
495 }
496
497 #ifdef Q_OS_SYMBIAN
498
499 void BookView::onMediaKeysPressed(MediaKeysObserver::MediaKeys key)
500 {
501     TRACE;
502     qDebug() << "Key" << (int)key;
503     if (grabbingVolumeKeys) {
504         if (key == MediaKeysObserver::EVolIncKey) {
505             qDebug() << "Volume up";
506             goPreviousPage();
507         } else if (key == MediaKeysObserver::EVolDecKey){
508             qDebug() << "Volume down";
509             goNextPage();
510         }
511     }
512 }
513
514 #endif // Q_OS_SYMBIAN