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