Avoid complex types as statics.
[dorian] / bookview.cpp
1 #include <QDir>
2 #include <QtGui>
3 #include <QWebFrame>
4
5 #if defined(Q_OS_SYMBIAN)
6 #   include "mediakeysobserver.h"
7 #   include "flickcharm.h"
8 #endif
9
10 #include "book.h"
11 #include "bookview.h"
12 #include "library.h"
13 #include "settings.h"
14 #include "trace.h"
15 #include "progress.h"
16 #include "progressdialog.h"
17 #include "platform.h"
18
19 BookView::BookView(QWidget *parent): QWebView(parent), contentIndex(-1),
20     mBook(0), restorePositionAfterLoad(false), positionAfterLoad(0),
21     restoreFragmentAfterLoad(false), loaded(false), grabbingVolumeKeys(false)
22 {
23     TRACE;
24
25     // Set up web view defaults
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     QWebFrame *frame = page()->mainFrame();
44 #if defined(Q_WS_MAEMO_5) || defined(Q_OS_SYMBIAN)
45     frame->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);
46 #endif
47     frame->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
48     connect(this, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
49     connect(frame, SIGNAL(javaScriptWindowObjectCleared()),
50             this, SLOT(addJavaScriptObjects()));
51
52     // Suppress unwanted text selections on Maemo and Symbian
53 #if defined(Q_WS_MAEMO_5) || defined(Q_OS_SYMBIAN)
54     installEventFilter(this);
55 #endif
56
57     // Pre-load bookmark icon
58     bookmarkImage = QImage(":/icons/bookmark.png");
59
60     // Handle settings changes, force handling initial settings
61     Settings *s = Settings::instance();
62     connect(s, SIGNAL(valueChanged(const QString &)),
63             this, SLOT(onSettingsChanged(const QString &)));
64     s->setValue("zoom", s->value("zoom", 160));
65     s->setValue("font", s->value("font", Platform::instance()->defaultFont()));
66     s->setValue("scheme", s->value("scheme", "default"));
67     s->setValue("usevolumekeys", s->value("usevolumekeys", false));
68     setBook(0);
69
70     // Enable kinetic scrolling
71 #if defined(Q_WS_MAEMO_5)
72     scrollerMonitor = 0;
73     scroller = property("kineticScroller").value<QAbstractKineticScroller *>();
74 #elif defined(Q_OS_SYMBIAN)
75     scrollerMonitor = 0;
76     charm = new FlickCharm(this);
77     charm->activateOn(this);
78 #endif
79
80     // Observe media keys on Symbian
81 #ifdef Q_OS_SYMBIAN
82     MediaKeysObserver *observer = MediaKeysObserver::instance();
83     connect(observer, SIGNAL(mediaKeyPressed(MediaKeysObserver::MediaKeys)),
84             this, SLOT(onMediaKeysPressed(MediaKeysObserver::MediaKeys)));
85 #endif
86 }
87
88 void BookView::loadContent(int index)
89 {
90     TRACE;
91
92     if (!mBook) {
93         return;
94     }
95     if ((index < 0) || (index >= mBook->parts.size())) {
96         return;
97     }
98
99     QString contentFile(mBook->content[mBook->parts[index]].href);
100     if (mBook->parts[index] == "error") {
101         setHtml(contentFile);
102     } else {
103         loaded = false;
104         emit partLoadStart(index);
105         QUrl u = QUrl::fromLocalFile(QDir(mBook->rootPath()).
106                                      absoluteFilePath(contentFile));
107         qDebug() << "Loading" << u;
108         load(u);
109     }
110     contentIndex = index;
111 }
112
113 void BookView::setBook(Book *book)
114 {
115     TRACE;
116
117     // Save position in current book
118     setLastBookmark();
119
120     // Open new book, restore last position
121     if (book != mBook) {
122         mBook = book;
123         if (book) {
124             contentIndex = -1;
125             if (book->open()) {
126                 restoreLastBookmark();
127             } else {
128                 mBook = 0;
129                 contentIndex = 0;
130                 setHtml(tr("Failed to open book"));
131             }
132         }
133         else {
134             contentIndex = 0;
135             setHtml(tr("No book"));
136         }
137     }
138 }
139
140 Book *BookView::book()
141 {
142     return mBook;
143 }
144
145 void BookView::goPrevious()
146 {
147     TRACE;
148     if (mBook && (contentIndex > 0)) {
149         mBook->setLastBookmark(contentIndex - 1, 0);
150         loadContent(contentIndex - 1);
151     }
152 }
153
154 void BookView::goNext()
155 {
156     TRACE;
157     if (mBook && (contentIndex < (mBook->parts.size() - 1))) {
158         mBook->setLastBookmark(contentIndex + 1, 0);
159         loadContent(contentIndex + 1);
160     }
161 }
162
163 void BookView::setLastBookmark()
164 {
165     TRACE;
166     if (mBook) {
167         QWebFrame *frame = page()->mainFrame();
168         int height = frame->contentsSize().height();
169         int pos = frame->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;
179     if (mBook) {
180         goToBookmark(mBook->lastBookmark());
181     }
182 }
183
184 void BookView::goToBookmark(const Book::Bookmark &bookmark)
185 {
186     TRACE;
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::goToPart(int part, const QString &fragment)
201 {
202     TRACE;
203     if (mBook) {
204         if (fragment.isEmpty()) {
205             goToBookmark(Book::Bookmark(part, 0));
206         } else {
207             if (part != contentIndex) {
208                 qDebug() << "Loading new part" << part;
209                 restoreFragmentAfterLoad = true;
210                 fragmentAfterLoad = fragment;
211                 loadContent(part);
212             } else {
213                 goToFragment(fragment);
214                 showProgress();
215             }
216         }
217     }
218 }
219
220 void BookView::goToFragment(const QString &fragment)
221 {
222     TRACE;
223     if (!fragment.isEmpty()) {
224         QVariant ret = page()->mainFrame()->evaluateJavaScript(
225                 QString("window.location='") + fragment + "'");
226         qDebug() << ret;
227         // FIXME: setLastBookmark();
228     }
229 }
230
231 void BookView::onLoadFinished(bool ok)
232 {
233     TRACE;
234     if (!ok) {
235         qDebug() << "Not OK";
236         return;
237     }
238     loaded = true;
239     onSettingsChanged("scheme");
240     onSettingsChanged("zoom");
241     onSettingsChanged("font");
242
243     QTimer::singleShot(210, this, SLOT(restoreAfterLoad()));
244 }
245
246 void BookView::restoreAfterLoad()
247 {
248     TRACE;
249     if (restoreFragmentAfterLoad) {
250         qDebug() << "Restorint to fragment" << fragmentAfterLoad;
251         goToFragment(fragmentAfterLoad);
252         restoreFragmentAfterLoad = false;
253     } else if (restorePositionAfterLoad) {
254         qDebug() << "Restoring to position" << positionAfterLoad;
255         goToPosition(positionAfterLoad);
256         restorePositionAfterLoad = false;
257     }
258
259     emit partLoadEnd(contentIndex);
260     showProgress();
261 }
262
263 void BookView::onSettingsChanged(const QString &key)
264 {
265     TRACE;
266     qDebug() << key << Settings::instance()->value(key);
267
268     if (key == "zoom") {
269         setZoomFactor(Settings::instance()->value(key).toFloat() / 100.);
270     }
271     else if (key == "font") {
272         QString face = Settings::instance()->value(key).toString();
273         settings()->setFontFamily(QWebSettings::StandardFont, face);
274     }
275     else if (key == "scheme") {
276         QWebFrame *frame = page()->mainFrame();
277         QString scheme = Settings::instance()->value("scheme").toString();
278         if ((scheme != "day") && (scheme != "night") && (scheme != "sand") &&
279             (scheme != "default")) {
280             scheme = "default";
281         }
282         QFile script(":/styles/" + scheme + ".js");
283         script.open(QFile::ReadOnly);
284         QString scriptText = script.readAll();
285         script.close();
286         QVariant ret = frame->evaluateJavaScript(scriptText);
287     }
288     else if (key == "usevolumekeys") {
289         grabVolumeKeys(Settings::instance()->value(key).toBool());
290     }
291 }
292
293 void BookView::paintEvent(QPaintEvent *e)
294 {
295     QWebView::paintEvent(e);
296     if (!mBook || !loaded) {
297         return;
298     }
299
300     // Paint bookmarks
301     QWebFrame *frame = page()->mainFrame();
302     int contentsHeight = frame->contentsSize().height();
303     QPoint scrollPos = frame->scrollPosition();
304     QPixmap bookmarkPixmap = QPixmap::fromImage(bookmarkImage);
305     QPainter painter(this);
306     foreach (Book::Bookmark b, mBook->bookmarks()) {
307         if (b.part != contentIndex) {
308             continue;
309         }
310         int height = contentsHeight;
311         int bookmarkPos = (int)((qreal)height * (qreal)b.pos);
312         painter.drawPixmap(2, bookmarkPos - scrollPos.y(), bookmarkPixmap);
313     }
314 }
315
316 void BookView::mousePressEvent(QMouseEvent *e)
317 {
318     QWebView::mousePressEvent(e);
319 #if defined(Q_WS_MAEMO_5)
320     // Start monitoring kinetic scroll
321     if (scrollerMonitor) {
322         killTimer(scrollerMonitor);
323         scrollerMonitor = 0;
324     }
325     if (scroller) {
326         scrollerMonitor = startTimer(500);
327     }
328 #else
329     // Handle mouse presses on the scroll bar
330     QWebFrame *frame = page()->mainFrame();
331     if (frame->scrollBarGeometry(Qt::Vertical).contains(e->pos())) {
332         e->accept();
333         return;
334     }
335 #endif // Q_WS_MAEMO_5
336     e->ignore();
337 }
338
339 void BookView::wheelEvent(QWheelEvent *e)
340 {
341     QWebView::wheelEvent(e);
342     showProgress();
343 }
344
345 void BookView::addBookmark(const QString &note)
346 {
347     TRACE;
348     if (!mBook) {
349         return;
350     }
351     int y = page()->mainFrame()->scrollPosition().y();
352     int height = page()->mainFrame()->contentsSize().height();
353     qDebug() << ((qreal)y / (qreal)height);
354     mBook->addBookmark(contentIndex, (qreal)y / (qreal)height, note);
355     update();
356 }
357
358 QString BookView::tmpPath()
359 {
360     return QDir::tempPath() + "/dorian";
361 }
362
363 bool BookView::eventFilter(QObject *o, QEvent *e)
364 {
365 #if 0
366     if (e->type() != QEvent::Paint && e->type() != QEvent::MouseMove) {
367         if (e->type() == QEvent::Resize) {
368             qDebug() << "BookView::eventFilter QEvent::Resize to"
369                     << page()->mainFrame()->contentsSize().height();
370         } else if (e->type() == QEvent::Timer) {
371             qDebug() << "BookView::eventFilter" << "QEvent::Timer"
372                     << ((QTimerEvent *)e)->timerId();
373         } else {
374             qDebug() << "BookView::eventFilter" << Trace::event(e->type());
375         }
376     }
377 #endif
378
379     // Work around Qt bug that sometimes selects web view contents during swipe
380     switch (e->type()) {
381     case QEvent::MouseButtonPress:
382         emit suppressedMouseButtonPress();
383         mousePressed = true;
384         break;
385     case QEvent::MouseButtonRelease:
386         showProgress();
387         mousePressed = false;
388         break;
389     case QEvent::MouseMove:
390         if (mousePressed) {
391             return true;
392         }
393         break;
394     case QEvent::MouseButtonDblClick:
395         return true;
396     default:
397         break;
398     }
399
400     return QObject::eventFilter(o, e);
401 }
402
403 void BookView::addJavaScriptObjects()
404 {
405     page()->mainFrame()->addToJavaScriptWindowObject("bv", this);
406 }
407
408 #ifdef Q_WS_MAEMO_5
409
410 void BookView::leaveEvent(QEvent *e)
411 {
412     TRACE;
413     // Save current position, to be restored later
414     setLastBookmark();
415     QWebView::leaveEvent(e);
416 }
417
418 void BookView::resizeEvent(QEvent *e)
419 {
420     TRACE;
421     // Restore position saved at Leave event. This seems to be required,
422     // after temporarily switching from portrait to landscape and back
423     restoreLastBookmark();
424     QWebView::enterEvent(e);
425 }
426
427 #endif // Q_WS_MAEMO_5
428
429 void BookView::goToPosition(qreal position)
430 {
431     int contentsHeight = page()->mainFrame()->contentsSize().height();
432     int scrollPos = (int)((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         int contentsHeight = page()->mainFrame()->contentsSize().height();
443         qreal pos = (qreal)(page()->mainFrame()->scrollPosition().y()) /
444                     (qreal)contentsHeight;
445         emit progress(mBook->getProgress(contentIndex, pos));
446     }
447 }
448
449 void BookView::timerEvent(QTimerEvent *e)
450 {
451 #if defined(Q_WS_MAEMO_5)
452     if (e->timerId() == scrollerMonitor) {
453         if (scroller &&
454             ((scroller->state() == QAbstractKineticScroller::AutoScrolling) ||
455              (scroller->state() == QAbstractKineticScroller::Pushing))) {
456             showProgress();
457         } else {
458             killTimer(scrollerMonitor);
459             scrollerMonitor = -1;
460         }
461     }
462 #endif
463     QWebView::timerEvent(e);
464 }
465
466 void BookView::goPreviousPage()
467 {
468     QWebFrame *frame = page()->mainFrame();
469     int pos = frame->scrollPosition().y();
470     frame->scroll(0, -height());
471     if (pos == frame->scrollPosition().y()) {
472         if (contentIndex > 0) {
473             Book::Bookmark bookmark(contentIndex - 1, 1.0);
474             mBook->setLastBookmark(contentIndex - 1, 1.0);
475             goToBookmark(bookmark);
476         }
477     } else {
478         showProgress();
479     }
480 }
481
482 void BookView::goNextPage()
483 {
484     TRACE;
485     QWebFrame *frame = page()->mainFrame();
486     int pos = frame->scrollPosition().y();
487     frame->scroll(0, height());
488     if (pos == frame->scrollPosition().y()) {
489         goNext();
490     } else {
491         setLastBookmark();
492         showProgress();
493     }
494 }
495
496 void BookView::grabVolumeKeys(bool grab)
497 {
498     TRACE;
499     grabbingVolumeKeys = grab;
500 }
501
502 #ifdef Q_OS_SYMBIAN
503
504 void BookView::onMediaKeysPressed(MediaKeysObserver::MediaKeys key)
505 {
506     TRACE;
507     qDebug() << "Key" << (int)key;
508     if (grabbingVolumeKeys) {
509         if (key == MediaKeysObserver::EVolIncKey) {
510             qDebug() << "Volume up";
511             goPreviousPage();
512         } else if (key == MediaKeysObserver::EVolDecKey){
513             qDebug() << "Volume down";
514             goNextPage();
515         }
516     }
517 }
518
519 #endif // Q_OS_SYMBIAN