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