Show progress during kinetic scrolling, too.
[dorian] / bookview.cpp
1 #include <QDebug>
2 #include <QWebFrame>
3 #include <QMouseEvent>
4 #include <QFile>
5 #include <QDir>
6 #include <QTimer>
7
8 #ifdef Q_WS_MAEMO_5
9 #   include <QAbstractKineticScroller>
10 #endif
11
12 #include "book.h"
13 #include "bookview.h"
14 #include "library.h"
15 #include "settings.h"
16 #include "trace.h"
17 #include "progress.h"
18
19 #ifdef Q_WS_MAC
20 #   define ICON_PREFIX ":/icons/mac/"
21 #else
22 #   define ICON_PREFIX ":/icons/"
23 #endif
24
25 BookView::BookView(QWidget *parent):
26     QWebView(parent), contentIndex(-1), mBook(0),
27     restorePositionAfterLoad(false), positionAfterLoad(0), loaded(false),
28     contentsHeight(0), decorated(false), scrollerMonitor(-1)
29 {
30     Trace t("BookView::BookView");
31     settings()->setAttribute(QWebSettings::AutoLoadImages, true);
32     settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
33     settings()->setAttribute(QWebSettings::JavaEnabled, false);
34     settings()->setAttribute(QWebSettings::PluginsEnabled, false);
35     settings()->setAttribute(QWebSettings::PrivateBrowsingEnabled, true);
36     settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, false);
37     settings()->setAttribute(QWebSettings::JavascriptCanAccessClipboard, false);
38     settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, false);
39     settings()->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled,
40                              false);
41     settings()->setAttribute(QWebSettings::LocalStorageEnabled, false);
42     settings()->setAttribute(QWebSettings::ZoomTextOnly, true);
43     settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,
44                              false);
45     settings()->setDefaultTextEncoding("utf-8");
46     page()->setContentEditable(false);
47
48 #if defined(Q_WS_MAEMO_5)
49     // Suppress unwanted text selections on Maemo
50     installEventFilter(this);
51 #endif
52     QWebFrame *frame = page()->mainFrame();
53 #if defined(Q_WS_MAEMO_5)
54     frame->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);
55 #endif
56     frame->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
57
58     bookmarkImage = QImage(":/icons/bookmark.png");
59
60     connect(this, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
61     connect(frame, SIGNAL(javaScriptWindowObjectCleared()),
62             this, SLOT(addJavaScriptObjects()));
63     connect(frame, SIGNAL(contentsSizeChanged(const QSize &)),
64             this, SLOT(onContentsSizeChanged(const QSize &)));
65     connect(Settings::instance(), SIGNAL(valueChanged(const QString &)),
66             this, SLOT(onSettingsChanged(const QString &)));
67     Settings *s = Settings::instance();
68     s->setValue("zoom", s->value("zoom", 160));
69     s->setValue("font", s->value("font",
70 #if defined(Q_WS_MAEMO_5) || defined(Q_WS_X11)
71                                  "Serif"
72 #elif defined(Q_WS_MAC)
73                                  "Hoefler Text"
74 #else
75                                  "Times New Roman"
76 #endif
77                                  ));
78     s->setValue("scheme", s->value("scheme", "default"));
79     setBook(0);
80
81     extractIcons();
82
83 #ifdef Q_WS_MAEMO_5
84     scroller = property("kineticScroller").value<QAbstractKineticScroller *>();
85     if (scroller) {
86         t.trace("Got scroller");
87     }
88 #endif
89 }
90
91 BookView::~BookView()
92 {
93     Trace t("BookView::~BookView");
94     removeIcons();
95 }
96
97 void BookView::loadContent(int index)
98 {
99     Trace t("BookView::loadContent");
100     if (!mBook) {
101         return;
102     }
103     if ((index < 0) || (index >= mBook->parts.size())) {
104         return;
105     }
106
107     QString contentFile(mBook->content[mBook->parts[index]].href);
108     if (mBook->parts[index] == "error") {
109         setHtml(contentFile);
110     }
111     else {
112         loaded = false;
113         decorated = false;
114         emit partLoadStart(index);
115         load(QUrl(contentFile));
116     }
117     contentIndex = index;
118 }
119
120 void BookView::setBook(Book *book)
121 {
122     Trace t("BookView::setBook");
123
124     // Save position in current book
125     setLastBookmark();
126
127     // Open new book, restore last position
128     if (book != mBook) {
129         mBook = book;
130         if (book) {
131             contentIndex = -1;
132             if (book->open()) {
133                 restoreLastBookmark();
134             } else {
135                 mBook = 0;
136                 contentIndex = 0;
137                 setHtml(tr("Failed to open book"));
138             }
139         }
140         else {
141             contentIndex = 0;
142             setHtml(tr("No book"));
143         }
144     }
145 }
146
147 Book *BookView::book()
148 {
149     return mBook;
150 }
151
152 void BookView::goPrevious()
153 {
154     Trace t("BookView::goPrevious");
155     loadContent(contentIndex - 1);
156 }
157
158 void BookView::goNext()
159 {
160     Trace t("BookView::goNext");
161     loadContent(contentIndex + 1);
162 }
163
164 void BookView::setLastBookmark()
165 {
166     Trace t("BookView::setLastBookmark");
167     if (mBook) {
168         int height = contentsHeight;
169         int pos = page()->mainFrame()->scrollPosition().y();
170         t.trace(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 t("BookView::restoreLastBookmark");
179     if (mBook) {
180         goToBookmark(mBook->lastBookmark());
181     }
182 }
183
184 void BookView::goToBookmark(const Book::Bookmark &bookmark)
185 {
186     Trace t("BookView::goToBookmark");
187     if (mBook) {
188         if (bookmark.part != contentIndex) {
189             t.trace(QString("Loading new part %1").arg(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::onLoadFinished(bool ok)
201 {
202     Trace t("BookView::onLoadFinished");
203     if (!ok) {
204         t.trace("Not OK");
205         return;
206     }
207     loaded = true;
208     addNavigationBar();
209     onSettingsChanged("scheme");
210     emit partLoadEnd(contentIndex);
211     showProgress();
212 }
213
214 void BookView::onSettingsChanged(const QString &key)
215 {
216     Trace t("BookView::onSettingsChanged " + key);
217     if (key == "zoom") {
218         setZoomFactor(Settings::instance()->value(key).toFloat() / 100.);
219     }
220     else if (key == "font") {
221         QString face = Settings::instance()->value("font").toString();
222         settings()->setFontFamily(QWebSettings::StandardFont, face);
223     }
224     else if (key == "scheme") {
225         QWebFrame *frame = page()->mainFrame();
226         QString scheme = Settings::instance()->value("scheme").toString();
227         if ((scheme != "day") && (scheme != "night") && (scheme != "sand") &&
228             (scheme != "default")) {
229             scheme = "default";
230         }
231         QFile script(":/styles/" + scheme + ".js");
232         script.open(QFile::ReadOnly);
233         QString scriptText = script.readAll();
234         script.close();
235         QVariant ret = frame->evaluateJavaScript(scriptText);
236     }
237 }
238
239 void BookView::paintEvent(QPaintEvent *e)
240 {
241     QWebView::paintEvent(e);
242     if (!mBook || !loaded) {
243         return;
244     }
245
246     // Paint bookmarks
247     QPoint scrollPos = page()->mainFrame()->scrollPosition();
248     QPixmap bookmarkPixmap = QPixmap::fromImage(bookmarkImage);
249     QPainter painter(this);
250     foreach (Book::Bookmark b, mBook->bookmarks()) {
251         if (b.part != contentIndex) {
252             continue;
253         }
254         int height = contentsHeight;
255         int bookmarkPos = (qreal)height * (qreal)b.pos;
256         painter.drawPixmap(2, bookmarkPos - scrollPos.y(), bookmarkPixmap);
257     }
258 }
259
260 void BookView::mousePressEvent(QMouseEvent *e)
261 {
262     QWebView::mousePressEvent(e);
263 #ifdef Q_WS_MAEMO_5
264     if (scroller) {
265         scrollerMonitor = startTimer(250);
266     }
267 #else
268     QWebFrame *frame = page()->mainFrame();
269     if (frame->scrollBarGeometry(Qt::Vertical).contains(e->pos())) {
270         e->accept();
271         return;
272     }
273 #endif // Q_WS_MAEMO_5
274     e->ignore();
275 }
276
277 void BookView::wheelEvent(QWheelEvent *e)
278 {
279     QWebView::wheelEvent(e);
280     showProgress();
281 }
282
283 void BookView::addBookmark()
284 {
285     Trace t("BookView::addBookmark");
286     if (!mBook) {
287         return;
288     }
289     int y = page()->mainFrame()->scrollPosition().y();
290     int height = page()->mainFrame()->contentsSize().height();
291     t.trace(QString().setNum((qreal)y / (qreal)height));
292     mBook->addBookmark(contentIndex, (qreal)y / (qreal)height);
293     update();
294 }
295
296 void BookView::addNavigationBar()
297 {
298     Trace t("BookView::addNavigationBar");
299     if (!mBook) {
300         return;
301     }
302
303     QString naviPrev =
304             "<a href=\"javascript:bv.goPrevious();\">"
305             "<img width=\"95\" height=\"95\" style=\"float:left;clear:none;\" "
306             "src=\"file://"
307             + tmpPath() +
308             "/previous.png\" />"
309             "</a>";
310     QString naviNext =
311             "<a href=\"javascript:bv.goNext();\">"
312             "<img width=\"95\" height=\"95\" style=\"float:right;clear:none;\" "
313             "src=\"file://"
314             + tmpPath() +
315             "/next.png\" />"
316             "</a>";
317     if (contentIndex == 0) {
318         naviPrev = "";
319     }
320     if (contentIndex >= mBook->parts.size() - 1) {
321         naviNext = "";
322     }
323
324     QWebFrame *frame = page()->currentFrame();
325     QString headerScript = "document.body.innerHTML = '" +
326         naviPrev + naviNext + "<br />" + "' + document.body.innerHTML;";
327     QString trailerScript = "document.body.innerHTML += '<br /><br />" +
328         naviPrev + naviNext + "';";
329
330     frame->evaluateJavaScript(headerScript);
331     frame->evaluateJavaScript(trailerScript);
332     decorated = true;
333 }
334
335 QString BookView::tmpPath()
336 {
337     return QDir::tempPath() + "/dorian";
338 }
339
340 void BookView::extractIcons()
341 {
342     QFile next(ICON_PREFIX + QString("/next.png"));
343     QFile prev(ICON_PREFIX + QString("/previous.png"));
344
345     QDir().mkpath(tmpPath());
346     next.copy(tmpPath() + "/next.png");
347     prev.copy(tmpPath() + "/previous.png");
348 }
349
350 void BookView::removeIcons()
351 {
352     QFile(ICON_PREFIX + QString("/next.png")).remove();
353     QFile(ICON_PREFIX + QString("/previous.png")).remove();
354     QDir().rmpath(tmpPath());
355 }
356
357 bool BookView::eventFilter(QObject *o, QEvent *e)
358 {
359 #if 0
360     if (e->type() != QEvent::Paint && e->type() != QEvent::MouseMove) {
361         if (e->type() == QEvent::Resize) {
362             Trace::trace(QString("BookView::eventFilter QEvent::Resize to %1").
363                          arg(page()->mainFrame()->contentsSize().height()));
364         } else {
365             Trace::trace(QString("BookView::eventFilter %1").
366                          arg(Trace::event(e->type())));
367         }
368     }
369 #endif
370
371     switch (e->type()) {
372     case QEvent::MouseButtonPress:
373         emit suppressedMouseButtonPress();
374         mousePressed = true;
375         break;
376     case QEvent::MouseButtonRelease:
377         showProgress();
378         mousePressed = false;
379         break;
380     case QEvent::MouseMove:
381         if (mousePressed) {
382             return true;
383         }
384         break;
385     case QEvent::MouseButtonDblClick:
386         return true;
387     default:
388         break;
389     }
390
391     return QObject::eventFilter(o, e);
392 }
393
394 void BookView::addJavaScriptObjects()
395 {
396     page()->mainFrame()->addToJavaScriptWindowObject("bv", this);
397 }
398
399 void BookView::onContentsSizeChanged(const QSize &size)
400 {
401     contentsHeight = size.height();
402     if (decorated) {
403         if (restorePositionAfterLoad) {
404             Trace::trace("BookView::onContentSizeChanged: Time to restore");
405             restorePositionAfterLoad = false;
406             goToPosition(positionAfterLoad);
407         }
408     }
409 }
410
411 void BookView::leaveEvent(QEvent *e)
412 {
413     Trace t("BookView::leaveEvent");
414     // Save current position, to be restored later
415     setLastBookmark();
416     QWebView::leaveEvent(e);
417 }
418
419 void BookView::enterEvent(QEvent *e)
420 {
421     Trace t("BookView::enterEvent");
422     // Restore position saved at Leave event. This seems to be required,
423     // after temporarily switching from portrait to landscape and back
424     restoreLastBookmark();
425     QWebView::enterEvent(e);
426 }
427
428 void BookView::goToPosition(qreal position)
429 {
430     int scrollPos = (qreal)contentsHeight * position;
431     page()->mainFrame()->setScrollPosition(QPoint(0, scrollPos));
432     // FIXME: update();
433     Trace::trace(QString("BookView::goToPosition: To %1 (%2%, height %3)").
434             arg(scrollPos).arg(position * 100).arg(contentsHeight));
435 }
436
437 void BookView::showProgress()
438 {
439     if (mBook) {
440         qreal pos = (qreal)(page()->mainFrame()->scrollPosition().y()) /
441                     (qreal)contentsHeight;
442         emit progress(mBook->getProgress(contentIndex, pos));
443     }
444 }
445
446 void BookView::timerEvent(QTimerEvent *e)
447 {
448     if (e->timerId() == scrollerMonitor) {
449 #ifdef Q_WS_MAEMO_5
450         if (scroller &&
451             ((scroller->state() == QAbstractKineticScroller::AutoScrolling) ||
452              (scroller->state() == QAbstractKineticScroller::Pushing))) {
453             showProgress();
454         } else {
455             killTimer(scrollerMonitor);
456         }
457     }
458 #endif // Q_WS_MAEMO_5
459 }