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