Navigate by pages instead of book parts.
[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 #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         decorated = false;
108         emit partLoadStart(index);
109         load(QUrl(contentFile));
110     }
111     contentIndex = index;
112 }
113
114 void BookView::setBook(Book *book)
115 {
116     Trace t("BookView::setBook");
117
118     // Save position in current book
119     setLastBookmark();
120
121     // Open new book, restore last position
122     if (book != mBook) {
123         mBook = book;
124         if (book) {
125             contentIndex = -1;
126             if (book->open()) {
127                 restoreLastBookmark();
128             } else {
129                 mBook = 0;
130                 contentIndex = 0;
131                 setHtml(tr("Failed to open book"));
132             }
133         }
134         else {
135             contentIndex = 0;
136             setHtml(tr("No book"));
137         }
138     }
139 }
140
141 Book *BookView::book()
142 {
143     return mBook;
144 }
145
146 void BookView::goPrevious()
147 {
148     Trace t("BookView::goPrevious");
149     if (mBook && (contentIndex > 0)) {
150         mBook->setLastBookmark(contentIndex - 1, 0);
151         loadContent(contentIndex - 1);
152     }
153 }
154
155 void BookView::goNext()
156 {
157     Trace t("BookView::goNext");
158     if (mBook && (contentIndex < (mBook->parts.size() - 1))) {
159         mBook->setLastBookmark(contentIndex + 1, 0);
160         loadContent(contentIndex + 1);
161     }
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         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 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             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::onLoadFinished(bool ok)
201 {
202     Trace t("BookView::onLoadFinished");
203     if (!ok) {
204         qDebug() << "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     // Start monitoring kinetic scroll
265     if (scroller) {
266         scrollerMonitor = startTimer(250);
267     }
268 #else
269     // Handle mouse presses on the scroll bar
270     QWebFrame *frame = page()->mainFrame();
271     if (frame->scrollBarGeometry(Qt::Vertical).contains(e->pos())) {
272         e->accept();
273         return;
274     }
275 #endif // Q_WS_MAEMO_5
276     e->ignore();
277 }
278
279 void BookView::wheelEvent(QWheelEvent *e)
280 {
281     QWebView::wheelEvent(e);
282     showProgress();
283 }
284
285 void BookView::addBookmark()
286 {
287     Trace t("BookView::addBookmark");
288     if (!mBook) {
289         return;
290     }
291     int y = page()->mainFrame()->scrollPosition().y();
292     int height = page()->mainFrame()->contentsSize().height();
293     qDebug() << ((qreal)y / (qreal)height);
294     mBook->addBookmark(contentIndex, (qreal)y / (qreal)height);
295     update();
296 }
297
298 void BookView::addNavigationBar()
299 {
300     decorated = true;
301 }
302
303 QString BookView::tmpPath()
304 {
305     return QDir::tempPath() + "/dorian";
306 }
307
308 bool BookView::eventFilter(QObject *o, QEvent *e)
309 {
310     if (e->type() != QEvent::Paint && e->type() != QEvent::MouseMove) {
311         if (e->type() == QEvent::Resize) {
312             qDebug() << "BookView::eventFilter QEvent::Resize to"
313                     << page()->mainFrame()->contentsSize().height();
314         } else {
315             qDebug() << "BookView::eventFilter" << Trace::event(e->type());
316         }
317     }
318
319     // Work around Qt bug that sometimes selects web view contents during swipe
320     switch (e->type()) {
321     case QEvent::MouseButtonPress:
322         emit suppressedMouseButtonPress();
323         mousePressed = true;
324         break;
325     case QEvent::MouseButtonRelease:
326         showProgress();
327         mousePressed = false;
328         break;
329     case QEvent::MouseMove:
330         if (mousePressed) {
331             return true;
332         }
333         break;
334     case QEvent::MouseButtonDblClick:
335         return true;
336     default:
337         break;
338     }
339
340     return QObject::eventFilter(o, e);
341 }
342
343 void BookView::addJavaScriptObjects()
344 {
345     page()->mainFrame()->addToJavaScriptWindowObject("bv", this);
346 }
347
348 void BookView::onContentsSizeChanged(const QSize &size)
349 {
350     contentsHeight = size.height();
351     if (decorated) {
352         if (restorePositionAfterLoad) {
353             qDebug() << "BookView::onContentSizeChanged: Time to restore";
354             restorePositionAfterLoad = false;
355             goToPosition(positionAfterLoad);
356         }
357     }
358 }
359
360 void BookView::leaveEvent(QEvent *e)
361 {
362     Trace t("BookView::leaveEvent");
363     // Save current position, to be restored later
364     setLastBookmark();
365     QWebView::leaveEvent(e);
366 }
367
368 void BookView::enterEvent(QEvent *e)
369 {
370     Trace t("BookView::enterEvent");
371     // Restore position saved at Leave event. This seems to be required,
372     // after temporarily switching from portrait to landscape and back
373     restoreLastBookmark();
374     QWebView::enterEvent(e);
375 }
376
377 void BookView::goToPosition(qreal position)
378 {
379     int scrollPos = (qreal)contentsHeight * position;
380     page()->mainFrame()->setScrollPosition(QPoint(0, scrollPos));
381     // FIXME: update();
382     qDebug() << "BookView::goToPosition: To" << scrollPos << "("
383             << (position * 100) << "%, height" << contentsHeight << ")";
384 }
385
386 void BookView::showProgress()
387 {
388     if (mBook) {
389         qreal pos = (qreal)(page()->mainFrame()->scrollPosition().y()) /
390                     (qreal)contentsHeight;
391         emit progress(mBook->getProgress(contentIndex, pos));
392     }
393 }
394
395 void BookView::timerEvent(QTimerEvent *e)
396 {
397     if (e->timerId() == scrollerMonitor) {
398 #ifdef Q_WS_MAEMO_5
399         if (scroller &&
400             ((scroller->state() == QAbstractKineticScroller::AutoScrolling) ||
401              (scroller->state() == QAbstractKineticScroller::Pushing))) {
402             showProgress();
403         } else {
404             killTimer(scrollerMonitor);
405         }
406 #endif // Q_WS_MAEMO_5
407     }
408 }
409
410 void BookView::keyPressEvent(QKeyEvent* event)
411 {
412     switch (event->key()) {
413     case Qt::Key_F7:
414         goNextPage();
415         event->accept();
416         break;
417     case Qt::Key_F8:
418         goPreviousPage();
419         event->accept();
420         break;
421     default:
422         ;
423     }
424     QWebView::keyPressEvent(event);
425 }
426
427 void BookView::goPreviousPage()
428 {
429     QWebFrame *frame = page()->mainFrame();
430     int pos = frame->scrollPosition().y();
431     frame->scroll(0, -height());
432     if (pos == frame->scrollPosition().y()) {
433         if (contentIndex > 0) {
434             Book::Bookmark bookmark(contentIndex - 1, 1.0);
435             mBook->setLastBookmark(contentIndex - 1, 1.0);
436             goToBookmark(bookmark);
437         }
438     } else {
439         showProgress();
440     }
441 }
442
443 void BookView::goNextPage()
444 {
445     Trace t("BookView::goNextPage");
446     QWebFrame *frame = page()->mainFrame();
447     int pos = frame->scrollPosition().y();
448     frame->scroll(0, height());
449     if (pos == frame->scrollPosition().y()) {
450         goNext();
451     } else {
452         setLastBookmark();
453         showProgress();
454     }
455 }