Fix 6143. Make library icons larger.
[dorian] / bookview.cpp
1 #include <QDebug>
2 #include <QWebFrame>
3 #include <QMouseEvent>
4 #include <QFile>
5 #include <QDir>
6 #include <QTimer>
7
8 #include "book.h"
9 #include "bookview.h"
10 #include "library.h"
11 #include "settings.h"
12 #include "trace.h"
13
14 #ifdef Q_WS_MAC
15 #   define ICON_PREFIX ":/icons/mac/"
16 #else
17 #   define ICON_PREFIX ":/icons/"
18 #endif
19
20 BookView::BookView(QWidget *parent):
21     QWebView(parent), contentIndex(-1), mBook(0),
22     restorePositionAfterLoad(false), positionAfterLoad(0), loaded(false),
23     contentsHeight(0), decorated(false)
24 {
25     Trace t("BookView::BookView");
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, false);
34     settings()->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled,
35                              false);
36     settings()->setAttribute(QWebSettings::LocalStorageEnabled, false);
37     settings()->setAttribute(QWebSettings::ZoomTextOnly, true);
38     settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,
39                              false);
40     settings()->setDefaultTextEncoding("utf-8");
41     page()->setContentEditable(false);
42
43 #if defined(Q_WS_MAEMO_5)
44     // Suppress unwanted text selections on Maemo
45     installEventFilter(this);
46 #endif
47     QWebFrame *frame = page()->mainFrame();
48 #if defined(Q_WS_MAEMO_5)
49     frame->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);
50 #endif
51     frame->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
52
53     bookmarkImage = QImage(":/icons/bookmark.png");
54
55     connect(this, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
56     connect(frame, SIGNAL(javaScriptWindowObjectCleared()),
57             this, SLOT(addJavaScriptObjects()));
58     connect(frame, SIGNAL(contentsSizeChanged(const QSize &)),
59             this, SLOT(onContentsSizeChanged(const QSize &)));
60     connect(Settings::instance(), SIGNAL(valueChanged(const QString &)),
61             this, SLOT(onSettingsChanged(const QString &)));
62     Settings *s = Settings::instance();
63     s->setValue("zoom", s->value("zoom", 160));
64     s->setValue("font", s->value("font",
65 #if defined(Q_WS_MAEMO_5) || defined(Q_WS_X11)
66                                  "Serif"
67 #elif defined(Q_WS_MAC)
68                                  "Hoefler Text"
69 #else
70                                  "Times New Roman"
71 #endif
72                                  ));
73     s->setValue("scheme", s->value("scheme", "default"));
74     setBook(0);
75
76     extractIcons();
77 }
78
79 BookView::~BookView()
80 {
81     Trace t("BookView::~BookView");
82     removeIcons();
83 }
84
85 void BookView::loadContent(int index)
86 {
87     Trace t("BookView::loadContent");
88     if (!mBook) {
89         return;
90     }
91     if ((index < 0) || (index >= mBook->toc.size())) {
92         return;
93     }
94
95     QString contentFile(mBook->content[mBook->toc[index]].href);
96     if (mBook->toc[index] == "error") {
97         setHtml(contentFile);
98     }
99     else {
100         loaded = false;
101         decorated = false;
102         emit chapterLoadStart(index);
103         load(QUrl(contentFile));
104     }
105     contentIndex = index;
106 }
107
108 void BookView::setBook(Book *book)
109 {
110     Trace t("BookView::setBook");
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             book->open();
121             restoreLastBookmark();
122         }
123         else {
124             contentIndex = 0;
125             setHtml(tr("No book"));
126         }
127     }
128 }
129
130 Book *BookView::book()
131 {
132     return mBook;
133 }
134
135 void BookView::goPrevious()
136 {
137     Trace t("BookView::goPrevious");
138     loadContent(contentIndex - 1);
139 }
140
141 void BookView::goNext()
142 {
143     Trace t("BookView::goNext");
144     loadContent(contentIndex + 1);
145 }
146
147 void BookView::setLastBookmark()
148 {
149     Trace t("BookView::setLastBookmark");
150     if (mBook) {
151         int height = contentsHeight;
152         int pos = page()->mainFrame()->scrollPosition().y();
153         t.trace(QString("At %1 (%2%, height %3)").
154                 arg(pos).arg((qreal)pos / (qreal)height * 100).arg(height));
155         mBook->setLastBookmark(contentIndex, (qreal)pos / (qreal)height);
156     }
157 }
158
159 void BookView::restoreLastBookmark()
160 {
161     Trace t("BookView::restoreLastBookmark");
162     if (mBook) {
163         goToBookmark(mBook->lastBookmark());
164     }
165 }
166
167 void BookView::goToBookmark(const Book::Bookmark &bookmark)
168 {
169     Trace t("BookView::goToBookmark");
170     if (mBook) {
171         if (bookmark.chapter != contentIndex) {
172             t.trace(QString("Loading new chapter %1").arg(bookmark.chapter));
173             mBook->setLastBookmark(bookmark.chapter, bookmark.pos);
174             restorePositionAfterLoad = true;
175             positionAfterLoad = bookmark.pos;
176             loadContent(bookmark.chapter);
177         } else {
178             goToPosition(bookmark.pos);
179         }
180     }
181 }
182
183 void BookView::onLoadFinished(bool ok)
184 {
185     Trace t("BookView::onLoadFinished");
186     if (!ok) {
187         t.trace("Not OK");
188         return;
189     }
190     loaded = true;
191     addNavigationBar();
192     onSettingsChanged("scheme");
193     emit chapterLoadEnd(contentIndex);
194 }
195
196 void BookView::onSettingsChanged(const QString &key)
197 {
198     Trace t("BookView::onSettingsChanged " + key);
199     if (key == "zoom") {
200         setZoomFactor(Settings::instance()->value(key).toFloat() / 100.);
201     }
202     else if (key == "font") {
203         QString face = Settings::instance()->value("font").toString();
204         settings()->setFontFamily(QWebSettings::StandardFont, face);
205     }
206     else if (key == "scheme") {
207         QWebFrame *frame = page()->mainFrame();
208         QString scheme = Settings::instance()->value("scheme").toString();
209         if ((scheme != "day") && (scheme != "night") && (scheme != "sand") &&
210             (scheme != "default")) {
211             scheme = "default";
212         }
213         QFile script(":/styles/" + scheme + ".js");
214         script.open(QFile::ReadOnly);
215         QString scriptText = script.readAll();
216         script.close();
217         QVariant ret = frame->evaluateJavaScript(scriptText);
218     }
219 }
220
221 void BookView::paintEvent(QPaintEvent *e)
222 {
223     QWebView::paintEvent(e);
224     if (!mBook || !loaded) {
225         return;
226     }
227
228     // Paint bookmarks
229     QPoint scrollPos = page()->mainFrame()->scrollPosition();
230     QPixmap bookmarkPixmap = QPixmap::fromImage(bookmarkImage);
231     QPainter painter(this);
232     foreach (Book::Bookmark b, mBook->bookmarks()) {
233         if (b.chapter != contentIndex) {
234             continue;
235         }
236         int height = contentsHeight;
237         int bookmarkPos = (qreal)height * (qreal)b.pos;
238         painter.drawPixmap(2, bookmarkPos - scrollPos.y(), bookmarkPixmap);
239     }
240 }
241
242 void BookView::mousePressEvent(QMouseEvent *e)
243 {
244     QWebView::mousePressEvent(e);
245 #ifndef Q_WS_MAEMO_5
246     QWebFrame *frame = page()->mainFrame();
247     if (frame->scrollBarGeometry(Qt::Vertical).contains(e->pos())) {
248         e->accept();
249         return;
250     }
251 #endif // Q_WS_MAEMO_5
252     e->ignore();
253 }
254
255 void BookView::addBookmark()
256 {
257     Trace t("BookView::addBookmark");
258     int y = page()->mainFrame()->scrollPosition().y();
259     int height = page()->mainFrame()->contentsSize().height();
260     t.trace(QString().setNum((qreal)y / (qreal)height));
261     mBook->addBookmark(contentIndex, (qreal)y / (qreal)height);
262     update();
263 }
264
265 void BookView::addNavigationBar()
266 {
267     Trace t("BookView::addNavigationBar");
268     if (!mBook) {
269         return;
270     }
271
272     QString naviPrev =
273             "<a href=\"javascript:bv.goPrevious();\">"
274             "<img width=\"95\" height=\"95\" style=\"float:left;clear:none;\" "
275             "src=\"file://"
276             + tmpPath() +
277             "/previous.png\" />"
278             "</a>";
279     QString naviNext =
280             "<a href=\"javascript:bv.goNext();\">"
281             "<img width=\"95\" height=\"95\" style=\"float:right;clear:none;\" "
282             "src=\"file://"
283             + tmpPath() +
284             "/next.png\" />"
285             "</a>";
286     if (contentIndex == 0) {
287         naviPrev = "";
288     }
289     if (contentIndex >= mBook->toc.size() - 1) {
290         naviNext = "";
291     }
292
293     QWebFrame *frame = page()->currentFrame();
294     QString headerScript = "document.body.innerHTML = '" +
295         naviPrev + naviNext + "<br />" + "' + document.body.innerHTML;";
296     QString trailerScript = "document.body.innerHTML += '<br /><br />" +
297         naviPrev + naviNext + "';";
298
299     frame->evaluateJavaScript(headerScript);
300     frame->evaluateJavaScript(trailerScript);
301     decorated = true;
302 }
303
304 QString BookView::tmpPath()
305 {
306     return QDir::tempPath() + "/dorian";
307 }
308
309 void BookView::extractIcons()
310 {
311     QFile next(ICON_PREFIX + QString("/next.png"));
312     QFile prev(ICON_PREFIX + QString("/previous.png"));
313
314     QDir().mkpath(tmpPath());
315     next.copy(tmpPath() + "/next.png");
316     prev.copy(tmpPath() + "/previous.png");
317 }
318
319 void BookView::removeIcons()
320 {
321     QFile(ICON_PREFIX + QString("/next.png")).remove();
322     QFile(ICON_PREFIX + QString("/previous.png")).remove();
323     QDir().rmpath(tmpPath());
324 }
325
326 bool BookView::eventFilter(QObject *o, QEvent *e)
327 {
328 #if 0
329     if (e->type() != QEvent::Paint && e->type() != QEvent::MouseMove) {
330         if (e->type() == QEvent::Resize) {
331             Trace::debug(QString("BookView::eventFilter QEvent::Resize to %1").
332                          arg(page()->mainFrame()->contentsSize().height()));
333         } else {
334             Trace::debug(QString("BookView::eventFilter %1").
335                          arg(Trace::event(e->type())));
336         }
337     }
338 #endif
339
340     switch (e->type()) {
341     case QEvent::MouseButtonPress:
342         emit suppressedMouseButtonPress();
343         mousePressed = true;
344         break;
345     case QEvent::MouseButtonRelease:
346         mousePressed = false;
347         break;
348     case QEvent::MouseMove:
349         if (mousePressed) {
350             return true;
351         }
352         break;
353     case QEvent::MouseButtonDblClick:
354         return true;
355     default:
356         break;
357     }
358
359     return QObject::eventFilter(o, e);
360 }
361
362 void BookView::addJavaScriptObjects()
363 {
364     page()->mainFrame()->addToJavaScriptWindowObject("bv", this);
365 }
366
367 void BookView::onContentsSizeChanged(const QSize &size)
368 {
369     contentsHeight = size.height();
370     if (decorated) {
371         if (restorePositionAfterLoad) {
372             Trace::debug("BookView::onContentSizeChanged: Time to restore");
373             restorePositionAfterLoad = false;
374             goToPosition(positionAfterLoad);
375         }
376     }
377 }
378
379 void BookView::leaveEvent(QEvent *e)
380 {
381     Trace t("BookView::leaveEvent");
382     // Save current position, to be restored later
383     setLastBookmark();
384     QWebView::leaveEvent(e);
385 }
386
387 void BookView::enterEvent(QEvent *e)
388 {
389     Trace t("BookView::enterEvent");
390     // Restore position saved at Leave event. This seems to be required,
391     // after temporarily switching from portrait to landscape and back
392     restoreLastBookmark();
393     QWebView::enterEvent(e);
394 }
395
396 void BookView::goToPosition(qreal position)
397 {
398     int scrollPos = (qreal)contentsHeight * position;
399     page()->mainFrame()->setScrollPosition(QPoint(0, scrollPos));
400     // FIXME: update();
401     Trace::debug(QString("BookView::goToPosition: To %1 (%2%, height %3)").
402             arg(scrollPos).arg(position * 100).arg(contentsHeight));
403 }