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