Initial steps to keep library in a database.
[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 BookView::BookView(QWidget *parent):
20     QWebView(parent), contentIndex(-1), mBook(0),
21     restorePositionAfterLoad(false), positionAfterLoad(0), loaded(false),
22     contentsHeight(0)
23 {
24     Trace t("BookView::BookView");
25     settings()->setAttribute(QWebSettings::AutoLoadImages, true);
26     settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
27     settings()->setAttribute(QWebSettings::JavaEnabled, false);
28     settings()->setAttribute(QWebSettings::PluginsEnabled, false);
29     settings()->setAttribute(QWebSettings::PrivateBrowsingEnabled, true);
30     settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, false);
31     settings()->setAttribute(QWebSettings::JavascriptCanAccessClipboard, false);
32     settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, false);
33     settings()->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled,
34                              false);
35     settings()->setAttribute(QWebSettings::LocalStorageEnabled, false);
36     settings()->setAttribute(QWebSettings::ZoomTextOnly, true);
37     settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,
38                              false);
39     settings()->setDefaultTextEncoding("utf-8");
40     page()->setContentEditable(false);
41
42 #if defined(Q_WS_MAEMO_5)
43     // Suppress unwanted text selections on Maemo
44     installEventFilter(this);
45 #endif
46     QWebFrame *frame = page()->mainFrame();
47 #if defined(Q_WS_MAEMO_5)
48     frame->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);
49 #endif
50     frame->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
51
52     bookmarkImage = QImage(":/icons/bookmark.png");
53
54     connect(this, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
55     connect(frame, SIGNAL(javaScriptWindowObjectCleared()),
56             this, SLOT(addJavaScriptObjects()));
57     connect(frame, SIGNAL(contentsSizeChanged(const QSize &)),
58             this, SLOT(onContentsSizeChanged(const QSize &)));
59     connect(Settings::instance(), SIGNAL(valueChanged(const QString &)),
60             this, SLOT(onSettingsChanged(const QString &)));
61     Settings *s = Settings::instance();
62     s->setValue("zoom", s->value("zoom", 160));
63     s->setValue("font", s->value("font",
64 #if defined(Q_WS_MAEMO_5) || defined(Q_WS_X11)
65                                  "Serif"
66 #elif defined(Q_WS_MAC)
67                                  "Hoefler Text"
68 #else
69                                  "Times New Roman"
70 #endif
71                                  ));
72     s->setValue("scheme", s->value("scheme", "default"));
73     setBook(0);
74
75 #ifdef Q_WS_MAEMO_5
76     scrollerMonitor = 0;
77     scroller = property("kineticScroller").value<QAbstractKineticScroller *>();
78 #endif
79 }
80
81 BookView::~BookView()
82 {
83     Trace t("BookView::~BookView");
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         emit partLoadStart(index);
103         QUrl u = QUrl::fromLocalFile(QDir(mBook->rootPath()).
104                                      absoluteFilePath(contentFile));
105         qDebug() << "Loading" << u;
106         load(u);
107     }
108     contentIndex = index;
109 }
110
111 void BookView::setBook(Book *book)
112 {
113     Trace t("BookView::setBook");
114
115     // Save position in current book
116     setLastBookmark();
117
118     // Open new book, restore last position
119     if (book != mBook) {
120         mBook = book;
121         if (book) {
122             contentIndex = -1;
123             if (book->open()) {
124                 restoreLastBookmark();
125             } else {
126                 mBook = 0;
127                 contentIndex = 0;
128                 setHtml(tr("Failed to open book"));
129             }
130         }
131         else {
132             contentIndex = 0;
133             setHtml(tr("No book"));
134         }
135     }
136 }
137
138 Book *BookView::book()
139 {
140     return mBook;
141 }
142
143 void BookView::goPrevious()
144 {
145     Trace t("BookView::goPrevious");
146     if (mBook && (contentIndex > 0)) {
147         mBook->setLastBookmark(contentIndex - 1, 0);
148         loadContent(contentIndex - 1);
149     }
150 }
151
152 void BookView::goNext()
153 {
154     Trace t("BookView::goNext");
155     if (mBook && (contentIndex < (mBook->parts.size() - 1))) {
156         mBook->setLastBookmark(contentIndex + 1, 0);
157         loadContent(contentIndex + 1);
158     }
159 }
160
161 void BookView::setLastBookmark()
162 {
163     Trace t("BookView::setLastBookmark");
164     if (mBook) {
165         int height = contentsHeight;
166         int pos = page()->mainFrame()->scrollPosition().y();
167         qDebug() << QString("At %1 (%2%, height %3)").
168                 arg(pos).arg((qreal)pos / (qreal)height * 100).arg(height);
169         mBook->setLastBookmark(contentIndex, (qreal)pos / (qreal)height);
170     }
171 }
172
173 void BookView::restoreLastBookmark()
174 {
175     Trace t("BookView::restoreLastBookmark");
176     if (mBook) {
177         goToBookmark(mBook->lastBookmark());
178     }
179 }
180
181 void BookView::goToBookmark(const Book::Bookmark &bookmark)
182 {
183     Trace t("BookView::goToBookmark");
184     if (mBook) {
185         if (bookmark.part != contentIndex) {
186             qDebug () << "Loading new part" << bookmark.part;
187             mBook->setLastBookmark(bookmark.part, bookmark.pos);
188             restorePositionAfterLoad = true;
189             positionAfterLoad = bookmark.pos;
190             loadContent(bookmark.part);
191         } else {
192             goToPosition(bookmark.pos);
193         }
194     }
195 }
196
197 void BookView::onLoadFinished(bool ok)
198 {
199     Trace t("BookView::onLoadFinished");
200     if (!ok) {
201         qDebug() << "Not OK";
202         return;
203     }
204     loaded = true;
205     onSettingsChanged("scheme");
206     emit partLoadEnd(contentIndex);
207     showProgress();
208 }
209
210 void BookView::onSettingsChanged(const QString &key)
211 {
212     Trace t("BookView::onSettingsChanged " + key);
213     if (key == "zoom") {
214         setZoomFactor(Settings::instance()->value(key).toFloat() / 100.);
215     }
216     else if (key == "font") {
217         QString face = Settings::instance()->value("font").toString();
218         settings()->setFontFamily(QWebSettings::StandardFont, face);
219     }
220     else if (key == "scheme") {
221         QWebFrame *frame = page()->mainFrame();
222         QString scheme = Settings::instance()->value("scheme").toString();
223         if ((scheme != "day") && (scheme != "night") && (scheme != "sand") &&
224             (scheme != "default")) {
225             scheme = "default";
226         }
227         QFile script(":/styles/" + scheme + ".js");
228         script.open(QFile::ReadOnly);
229         QString scriptText = script.readAll();
230         script.close();
231         QVariant ret = frame->evaluateJavaScript(scriptText);
232     }
233 }
234
235 void BookView::paintEvent(QPaintEvent *e)
236 {
237     QWebView::paintEvent(e);
238     if (!mBook || !loaded) {
239         return;
240     }
241
242     // Paint bookmarks
243     QPoint scrollPos = page()->mainFrame()->scrollPosition();
244     QPixmap bookmarkPixmap = QPixmap::fromImage(bookmarkImage);
245     QPainter painter(this);
246     foreach (Book::Bookmark b, mBook->bookmarks()) {
247         if (b.part != contentIndex) {
248             continue;
249         }
250         int height = contentsHeight;
251         int bookmarkPos = (int)((qreal)height * (qreal)b.pos);
252         painter.drawPixmap(2, bookmarkPos - scrollPos.y(), bookmarkPixmap);
253     }
254 }
255
256 void BookView::mousePressEvent(QMouseEvent *e)
257 {
258     QWebView::mousePressEvent(e);
259 #ifdef Q_WS_MAEMO_5
260     // Start monitoring kinetic scroll
261     if (scrollerMonitor) {
262         killTimer(scrollerMonitor);
263         scrollerMonitor = 0;
264     }
265     if (scroller) {
266         scrollerMonitor = startTimer(500);
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 QString BookView::tmpPath()
299 {
300     return QDir::tempPath() + "/dorian";
301 }
302
303 bool BookView::eventFilter(QObject *o, QEvent *e)
304 {
305     if (e->type() != QEvent::Paint && e->type() != QEvent::MouseMove) {
306         if (e->type() == QEvent::Resize) {
307             qDebug() << "BookView::eventFilter QEvent::Resize to"
308                     << page()->mainFrame()->contentsSize().height();
309         } else if (e->type() == QEvent::Timer) {
310             qDebug() << "BookView::eventFilter" << "QEvent::Timer"
311                     << ((QTimerEvent *)e)->timerId();
312         } else {
313             qDebug() << "BookView::eventFilter" << Trace::event(e->type());
314         }
315     }
316
317     // Work around Qt bug that sometimes selects web view contents during swipe
318     switch (e->type()) {
319     case QEvent::MouseButtonPress:
320         emit suppressedMouseButtonPress();
321         mousePressed = true;
322         break;
323     case QEvent::MouseButtonRelease:
324         showProgress();
325         mousePressed = false;
326         break;
327     case QEvent::MouseMove:
328         if (mousePressed) {
329             return true;
330         }
331         break;
332     case QEvent::MouseButtonDblClick:
333         return true;
334     default:
335         break;
336     }
337
338     return QObject::eventFilter(o, e);
339 }
340
341 void BookView::addJavaScriptObjects()
342 {
343     page()->mainFrame()->addToJavaScriptWindowObject("bv", this);
344 }
345
346 void BookView::onContentsSizeChanged(const QSize &size)
347 {
348     contentsHeight = size.height();
349     if (restorePositionAfterLoad) {
350         qDebug() << "BookView::onContentSizeChanged: Time to restore";
351         restorePositionAfterLoad = false;
352         goToPosition(positionAfterLoad);
353     }
354 }
355
356 void BookView::leaveEvent(QEvent *e)
357 {
358     Trace t("BookView::leaveEvent");
359     // Save current position, to be restored later
360     setLastBookmark();
361     QWebView::leaveEvent(e);
362 }
363
364 void BookView::enterEvent(QEvent *e)
365 {
366     Trace t("BookView::enterEvent");
367     // Restore position saved at Leave event. This seems to be required,
368     // after temporarily switching from portrait to landscape and back
369     restoreLastBookmark();
370     QWebView::enterEvent(e);
371 }
372
373 void BookView::goToPosition(qreal position)
374 {
375     int scrollPos = (int)((qreal)contentsHeight * position);
376     page()->mainFrame()->setScrollPosition(QPoint(0, scrollPos));
377     // FIXME: update();
378     qDebug() << "BookView::goToPosition: To" << scrollPos << "("
379             << (position * 100) << "%, height" << contentsHeight << ")";
380 }
381
382 void BookView::showProgress()
383 {
384     if (mBook) {
385         qreal pos = (qreal)(page()->mainFrame()->scrollPosition().y()) /
386                     (qreal)contentsHeight;
387         emit progress(mBook->getProgress(contentIndex, pos));
388     }
389 }
390
391 void BookView::timerEvent(QTimerEvent *e)
392 {
393 #ifdef Q_WS_MAEMO_5
394     if (e->timerId() == scrollerMonitor) {
395         if (scroller &&
396             ((scroller->state() == QAbstractKineticScroller::AutoScrolling) ||
397              (scroller->state() == QAbstractKineticScroller::Pushing))) {
398             showProgress();
399         } else {
400             killTimer(scrollerMonitor);
401         }
402     }
403 #else
404     Q_UNUSED(e);
405 #endif // Q_WS_MAEMO_5
406 }
407
408 void BookView::keyPressEvent(QKeyEvent* event)
409 {
410     switch (event->key()) {
411     case Qt::Key_F7:
412         goNextPage();
413         event->accept();
414         break;
415     case Qt::Key_F8:
416         goPreviousPage();
417         event->accept();
418         break;
419     default:
420         ;
421     }
422     QWebView::keyPressEvent(event);
423 }
424
425 void BookView::goPreviousPage()
426 {
427     QWebFrame *frame = page()->mainFrame();
428     int pos = frame->scrollPosition().y();
429     frame->scroll(0, -height());
430     if (pos == frame->scrollPosition().y()) {
431         if (contentIndex > 0) {
432             Book::Bookmark bookmark(contentIndex - 1, 1.0);
433             mBook->setLastBookmark(contentIndex - 1, 1.0);
434             goToBookmark(bookmark);
435         }
436     } else {
437         showProgress();
438     }
439 }
440
441 void BookView::goNextPage()
442 {
443     Trace t("BookView::goNextPage");
444     QWebFrame *frame = page()->mainFrame();
445     int pos = frame->scrollPosition().y();
446     frame->scroll(0, height());
447     if (pos == frame->scrollPosition().y()) {
448         goNext();
449     } else {
450         setLastBookmark();
451         showProgress();
452     }
453 }