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