More naming fixes.
[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->parts.size())) {
92         return;
93     }
94
95     QString contentFile(mBook->content[mBook->parts[index]].href);
96     if (mBook->parts[index] == "error") {
97         setHtml(contentFile);
98     }
99     else {
100         loaded = false;
101         decorated = false;
102         emit partLoadStart(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             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 t("BookView::goPrevious");
143     loadContent(contentIndex - 1);
144 }
145
146 void BookView::goNext()
147 {
148     Trace t("BookView::goNext");
149     loadContent(contentIndex + 1);
150 }
151
152 void BookView::setLastBookmark()
153 {
154     Trace t("BookView::setLastBookmark");
155     if (mBook) {
156         int height = contentsHeight;
157         int pos = page()->mainFrame()->scrollPosition().y();
158         t.trace(QString("At %1 (%2%, height %3)").
159                 arg(pos).arg((qreal)pos / (qreal)height * 100).arg(height));
160         mBook->setLastBookmark(contentIndex, (qreal)pos / (qreal)height);
161     }
162 }
163
164 void BookView::restoreLastBookmark()
165 {
166     Trace t("BookView::restoreLastBookmark");
167     if (mBook) {
168         goToBookmark(mBook->lastBookmark());
169     }
170 }
171
172 void BookView::goToBookmark(const Book::Bookmark &bookmark)
173 {
174     Trace t("BookView::goToBookmark");
175     if (mBook) {
176         if (bookmark.part != contentIndex) {
177             t.trace(QString("Loading new part %1").arg(bookmark.part));
178             mBook->setLastBookmark(bookmark.part, bookmark.pos);
179             restorePositionAfterLoad = true;
180             positionAfterLoad = bookmark.pos;
181             loadContent(bookmark.part);
182         } else {
183             goToPosition(bookmark.pos);
184         }
185     }
186 }
187
188 void BookView::onLoadFinished(bool ok)
189 {
190     Trace t("BookView::onLoadFinished");
191     if (!ok) {
192         t.trace("Not OK");
193         return;
194     }
195     loaded = true;
196     addNavigationBar();
197     onSettingsChanged("scheme");
198     emit partLoadEnd(contentIndex);
199 }
200
201 void BookView::onSettingsChanged(const QString &key)
202 {
203     Trace t("BookView::onSettingsChanged " + key);
204     if (key == "zoom") {
205         setZoomFactor(Settings::instance()->value(key).toFloat() / 100.);
206     }
207     else if (key == "font") {
208         QString face = Settings::instance()->value("font").toString();
209         settings()->setFontFamily(QWebSettings::StandardFont, face);
210     }
211     else if (key == "scheme") {
212         QWebFrame *frame = page()->mainFrame();
213         QString scheme = Settings::instance()->value("scheme").toString();
214         if ((scheme != "day") && (scheme != "night") && (scheme != "sand") &&
215             (scheme != "default")) {
216             scheme = "default";
217         }
218         QFile script(":/styles/" + scheme + ".js");
219         script.open(QFile::ReadOnly);
220         QString scriptText = script.readAll();
221         script.close();
222         QVariant ret = frame->evaluateJavaScript(scriptText);
223     }
224 }
225
226 void BookView::paintEvent(QPaintEvent *e)
227 {
228     QWebView::paintEvent(e);
229     if (!mBook || !loaded) {
230         return;
231     }
232
233     // Paint bookmarks
234     QPoint scrollPos = page()->mainFrame()->scrollPosition();
235     QPixmap bookmarkPixmap = QPixmap::fromImage(bookmarkImage);
236     QPainter painter(this);
237     foreach (Book::Bookmark b, mBook->bookmarks()) {
238         if (b.part != contentIndex) {
239             continue;
240         }
241         int height = contentsHeight;
242         int bookmarkPos = (qreal)height * (qreal)b.pos;
243         painter.drawPixmap(2, bookmarkPos - scrollPos.y(), bookmarkPixmap);
244     }
245 }
246
247 void BookView::mousePressEvent(QMouseEvent *e)
248 {
249     QWebView::mousePressEvent(e);
250 #ifndef Q_WS_MAEMO_5
251     QWebFrame *frame = page()->mainFrame();
252     if (frame->scrollBarGeometry(Qt::Vertical).contains(e->pos())) {
253         e->accept();
254         return;
255     }
256 #endif // Q_WS_MAEMO_5
257     e->ignore();
258 }
259
260 void BookView::addBookmark()
261 {
262     Trace t("BookView::addBookmark");
263     if (!mBook) {
264         return;
265     }
266     int y = page()->mainFrame()->scrollPosition().y();
267     int height = page()->mainFrame()->contentsSize().height();
268     t.trace(QString().setNum((qreal)y / (qreal)height));
269     mBook->addBookmark(contentIndex, (qreal)y / (qreal)height);
270     update();
271 }
272
273 void BookView::addNavigationBar()
274 {
275     Trace t("BookView::addNavigationBar");
276     if (!mBook) {
277         return;
278     }
279
280     QString naviPrev =
281             "<a href=\"javascript:bv.goPrevious();\">"
282             "<img width=\"95\" height=\"95\" style=\"float:left;clear:none;\" "
283             "src=\"file://"
284             + tmpPath() +
285             "/previous.png\" />"
286             "</a>";
287     QString naviNext =
288             "<a href=\"javascript:bv.goNext();\">"
289             "<img width=\"95\" height=\"95\" style=\"float:right;clear:none;\" "
290             "src=\"file://"
291             + tmpPath() +
292             "/next.png\" />"
293             "</a>";
294     if (contentIndex == 0) {
295         naviPrev = "";
296     }
297     if (contentIndex >= mBook->parts.size() - 1) {
298         naviNext = "";
299     }
300
301     QWebFrame *frame = page()->currentFrame();
302     QString headerScript = "document.body.innerHTML = '" +
303         naviPrev + naviNext + "<br />" + "' + document.body.innerHTML;";
304     QString trailerScript = "document.body.innerHTML += '<br /><br />" +
305         naviPrev + naviNext + "';";
306
307     frame->evaluateJavaScript(headerScript);
308     frame->evaluateJavaScript(trailerScript);
309     decorated = true;
310 }
311
312 QString BookView::tmpPath()
313 {
314     return QDir::tempPath() + "/dorian";
315 }
316
317 void BookView::extractIcons()
318 {
319     QFile next(ICON_PREFIX + QString("/next.png"));
320     QFile prev(ICON_PREFIX + QString("/previous.png"));
321
322     QDir().mkpath(tmpPath());
323     next.copy(tmpPath() + "/next.png");
324     prev.copy(tmpPath() + "/previous.png");
325 }
326
327 void BookView::removeIcons()
328 {
329     QFile(ICON_PREFIX + QString("/next.png")).remove();
330     QFile(ICON_PREFIX + QString("/previous.png")).remove();
331     QDir().rmpath(tmpPath());
332 }
333
334 bool BookView::eventFilter(QObject *o, QEvent *e)
335 {
336 #if 0
337     if (e->type() != QEvent::Paint && e->type() != QEvent::MouseMove) {
338         if (e->type() == QEvent::Resize) {
339             Trace::trace(QString("BookView::eventFilter QEvent::Resize to %1").
340                          arg(page()->mainFrame()->contentsSize().height()));
341         } else {
342             Trace::trace(QString("BookView::eventFilter %1").
343                          arg(Trace::event(e->type())));
344         }
345     }
346 #endif
347
348     switch (e->type()) {
349     case QEvent::MouseButtonPress:
350         emit suppressedMouseButtonPress();
351         mousePressed = true;
352         break;
353     case QEvent::MouseButtonRelease:
354         mousePressed = false;
355         break;
356     case QEvent::MouseMove:
357         if (mousePressed) {
358             return true;
359         }
360         break;
361     case QEvent::MouseButtonDblClick:
362         return true;
363     default:
364         break;
365     }
366
367     return QObject::eventFilter(o, e);
368 }
369
370 void BookView::addJavaScriptObjects()
371 {
372     page()->mainFrame()->addToJavaScriptWindowObject("bv", this);
373 }
374
375 void BookView::onContentsSizeChanged(const QSize &size)
376 {
377     contentsHeight = size.height();
378     if (decorated) {
379         if (restorePositionAfterLoad) {
380             Trace::trace("BookView::onContentSizeChanged: Time to restore");
381             restorePositionAfterLoad = false;
382             goToPosition(positionAfterLoad);
383         }
384     }
385 }
386
387 void BookView::leaveEvent(QEvent *e)
388 {
389     Trace t("BookView::leaveEvent");
390     // Save current position, to be restored later
391     setLastBookmark();
392     QWebView::leaveEvent(e);
393 }
394
395 void BookView::enterEvent(QEvent *e)
396 {
397     Trace t("BookView::enterEvent");
398     // Restore position saved at Leave event. This seems to be required,
399     // after temporarily switching from portrait to landscape and back
400     restoreLastBookmark();
401     QWebView::enterEvent(e);
402 }
403
404 void BookView::goToPosition(qreal position)
405 {
406     int scrollPos = (qreal)contentsHeight * position;
407     page()->mainFrame()->setScrollPosition(QPoint(0, scrollPos));
408     // FIXME: update();
409     Trace::trace(QString("BookView::goToPosition: To %1 (%2%, height %3)").
410             arg(scrollPos).arg(position * 100).arg(contentsHeight));
411 }