Improve traces. Simplify folder management.
[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 #ifdef Q_WS_MAEMO_5
83     scroller = property("kineticScroller").value<QAbstractKineticScroller *>();
84 #endif
85 }
86
87 BookView::~BookView()
88 {
89     Trace t("BookView::~BookView");
90     removeIcons();
91 }
92
93 void BookView::loadContent(int index)
94 {
95     Trace t("BookView::loadContent");
96     if (!mBook) {
97         return;
98     }
99     if ((index < 0) || (index >= mBook->parts.size())) {
100         return;
101     }
102
103     QString contentFile(mBook->content[mBook->parts[index]].href);
104     if (mBook->parts[index] == "error") {
105         setHtml(contentFile);
106     }
107     else {
108         loaded = false;
109         decorated = false;
110         emit partLoadStart(index);
111         load(QUrl(contentFile));
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     addNavigationBar();
211     onSettingsChanged("scheme");
212     emit partLoadEnd(contentIndex);
213     showProgress();
214 }
215
216 void BookView::onSettingsChanged(const QString &key)
217 {
218     Trace t("BookView::onSettingsChanged " + key);
219     if (key == "zoom") {
220         setZoomFactor(Settings::instance()->value(key).toFloat() / 100.);
221     }
222     else if (key == "font") {
223         QString face = Settings::instance()->value("font").toString();
224         settings()->setFontFamily(QWebSettings::StandardFont, face);
225     }
226     else if (key == "scheme") {
227         QWebFrame *frame = page()->mainFrame();
228         QString scheme = Settings::instance()->value("scheme").toString();
229         if ((scheme != "day") && (scheme != "night") && (scheme != "sand") &&
230             (scheme != "default")) {
231             scheme = "default";
232         }
233         QFile script(":/styles/" + scheme + ".js");
234         script.open(QFile::ReadOnly);
235         QString scriptText = script.readAll();
236         script.close();
237         QVariant ret = frame->evaluateJavaScript(scriptText);
238     }
239 }
240
241 void BookView::paintEvent(QPaintEvent *e)
242 {
243     QWebView::paintEvent(e);
244     if (!mBook || !loaded) {
245         return;
246     }
247
248     // Paint bookmarks
249     QPoint scrollPos = page()->mainFrame()->scrollPosition();
250     QPixmap bookmarkPixmap = QPixmap::fromImage(bookmarkImage);
251     QPainter painter(this);
252     foreach (Book::Bookmark b, mBook->bookmarks()) {
253         if (b.part != contentIndex) {
254             continue;
255         }
256         int height = contentsHeight;
257         int bookmarkPos = (qreal)height * (qreal)b.pos;
258         painter.drawPixmap(2, bookmarkPos - scrollPos.y(), bookmarkPixmap);
259     }
260 }
261
262 void BookView::mousePressEvent(QMouseEvent *e)
263 {
264     QWebView::mousePressEvent(e);
265 #ifdef Q_WS_MAEMO_5
266     // Start monitoring kinetic scroll
267     if (scroller) {
268         scrollerMonitor = startTimer(250);
269     }
270 #else
271     // Handle mouse presses on the scroll bar
272     QWebFrame *frame = page()->mainFrame();
273     if (frame->scrollBarGeometry(Qt::Vertical).contains(e->pos())) {
274         e->accept();
275         return;
276     }
277 #endif // Q_WS_MAEMO_5
278     e->ignore();
279 }
280
281 void BookView::wheelEvent(QWheelEvent *e)
282 {
283     QWebView::wheelEvent(e);
284     showProgress();
285 }
286
287 void BookView::addBookmark()
288 {
289     Trace t("BookView::addBookmark");
290     if (!mBook) {
291         return;
292     }
293     int y = page()->mainFrame()->scrollPosition().y();
294     int height = page()->mainFrame()->contentsSize().height();
295     qDebug() << ((qreal)y / (qreal)height);
296     mBook->addBookmark(contentIndex, (qreal)y / (qreal)height);
297     update();
298 }
299
300 void BookView::addNavigationBar()
301 {
302     Trace t("BookView::addNavigationBar");
303     if (!mBook) {
304         return;
305     }
306
307     QString naviPrev =
308             "<a href=\"javascript:bv.goPrevious();\">"
309             "<img width=\"95\" height=\"95\" style=\"float:left;clear:none;\" "
310             "src=\"file://"
311             + tmpPath() +
312             "/previous.png\" />"
313             "</a>";
314     QString naviNext =
315             "<a href=\"javascript:bv.goNext();\">"
316             "<img width=\"95\" height=\"95\" style=\"float:right;clear:none;\" "
317             "src=\"file://"
318             + tmpPath() +
319             "/next.png\" />"
320             "</a>";
321     if (contentIndex == 0) {
322         naviPrev = "";
323     }
324     if (contentIndex >= mBook->parts.size() - 1) {
325         naviNext = "";
326     }
327
328     QWebFrame *frame = page()->currentFrame();
329     QString headerScript = "document.body.innerHTML = '" +
330         naviPrev + naviNext + "<br />" + "' + document.body.innerHTML;";
331     QString trailerScript = "document.body.innerHTML += '<br /><br />" +
332         naviPrev + naviNext + "';";
333
334     frame->evaluateJavaScript(headerScript);
335     frame->evaluateJavaScript(trailerScript);
336     decorated = true;
337 }
338
339 QString BookView::tmpPath()
340 {
341     return QDir::tempPath() + "/dorian";
342 }
343
344 void BookView::extractIcons()
345 {
346     QFile next(ICON_PREFIX + QString("/next.png"));
347     QFile prev(ICON_PREFIX + QString("/previous.png"));
348
349     QDir().mkpath(tmpPath());
350     next.copy(tmpPath() + "/next.png");
351     prev.copy(tmpPath() + "/previous.png");
352 }
353
354 void BookView::removeIcons()
355 {
356     QFile(ICON_PREFIX + QString("/next.png")).remove();
357     QFile(ICON_PREFIX + QString("/previous.png")).remove();
358     QDir().rmpath(tmpPath());
359 }
360
361 bool BookView::eventFilter(QObject *o, QEvent *e)
362 {
363     if (e->type() != QEvent::Paint && e->type() != QEvent::MouseMove) {
364         if (e->type() == QEvent::Resize) {
365             qDebug() << "BookView::eventFilter QEvent::Resize to"
366                     << page()->mainFrame()->contentsSize().height();
367         } else {
368             qDebug() << "BookView::eventFilter" << Trace::event(e->type());
369         }
370     }
371
372     // Work around Qt bug that sometimes selects web view contents during swipe
373     switch (e->type()) {
374     case QEvent::MouseButtonPress:
375         emit suppressedMouseButtonPress();
376         mousePressed = true;
377         break;
378     case QEvent::MouseButtonRelease:
379         showProgress();
380         mousePressed = false;
381         break;
382     case QEvent::MouseMove:
383         if (mousePressed) {
384             return true;
385         }
386         break;
387     case QEvent::MouseButtonDblClick:
388         return true;
389     default:
390         break;
391     }
392
393     return QObject::eventFilter(o, e);
394 }
395
396 void BookView::addJavaScriptObjects()
397 {
398     page()->mainFrame()->addToJavaScriptWindowObject("bv", this);
399 }
400
401 void BookView::onContentsSizeChanged(const QSize &size)
402 {
403     contentsHeight = size.height();
404     if (decorated) {
405         if (restorePositionAfterLoad) {
406             qDebug() << "BookView::onContentSizeChanged: Time to restore";
407             restorePositionAfterLoad = false;
408             goToPosition(positionAfterLoad);
409         }
410     }
411 }
412
413 void BookView::leaveEvent(QEvent *e)
414 {
415     Trace t("BookView::leaveEvent");
416     // Save current position, to be restored later
417     setLastBookmark();
418     QWebView::leaveEvent(e);
419 }
420
421 void BookView::enterEvent(QEvent *e)
422 {
423     Trace t("BookView::enterEvent");
424     // Restore position saved at Leave event. This seems to be required,
425     // after temporarily switching from portrait to landscape and back
426     restoreLastBookmark();
427     QWebView::enterEvent(e);
428 }
429
430 void BookView::goToPosition(qreal position)
431 {
432     int scrollPos = (qreal)contentsHeight * position;
433     page()->mainFrame()->setScrollPosition(QPoint(0, scrollPos));
434     // FIXME: update();
435     qDebug() << "BookView::goToPosition: To" << scrollPos << "("
436             << (position * 100) << "%, height" << contentsHeight << ")";
437 }
438
439 void BookView::showProgress()
440 {
441     if (mBook) {
442         qreal pos = (qreal)(page()->mainFrame()->scrollPosition().y()) /
443                     (qreal)contentsHeight;
444         emit progress(mBook->getProgress(contentIndex, pos));
445     }
446 }
447
448 void BookView::timerEvent(QTimerEvent *e)
449 {
450     if (e->timerId() == scrollerMonitor) {
451 #ifdef Q_WS_MAEMO_5
452         if (scroller &&
453             ((scroller->state() == QAbstractKineticScroller::AutoScrolling) ||
454              (scroller->state() == QAbstractKineticScroller::Pushing))) {
455             showProgress();
456         } else {
457             killTimer(scrollerMonitor);
458         }
459 #endif // Q_WS_MAEMO_5
460     }
461 }
462
463 void BookView::keyPressEvent(QKeyEvent* event)
464 {
465     switch (event->key()) {
466     case Qt::Key_F7:
467         goNextPage();
468         event->accept();
469         break;
470     case Qt::Key_F8:
471         goPreviousPage();
472         event->accept();
473         break;
474     default:
475         ;
476     }
477     QWebView::keyPressEvent(event);
478 }
479
480 void BookView::goPreviousPage()
481 {
482     QWebFrame *frame = page()->mainFrame();
483     int pos = frame->scrollPosition().y();
484     frame->scroll(0, -height());
485     if (pos == frame->scrollPosition().y()) {
486         if (contentIndex > 0) {
487             goToBookmark(Book::Bookmark(contentIndex - 1, 1.0));
488         }
489     } else {
490         showProgress();
491     }
492 }
493
494 void BookView::goNextPage()
495 {
496     Trace t("BookView::goNextPage");
497     QWebFrame *frame = page()->mainFrame();
498     int pos = frame->scrollPosition().y();
499     frame->scroll(0, height());
500     if (pos == frame->scrollPosition().y()) {
501         goNext();
502     } else {
503         showProgress();
504     }
505 }