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