Show better bookmark descriptions.
[dorian] / model / book.cpp
1 #include <QDir>
2 #include <QString>
3 #include <QDebug>
4 #include <QtXml>
5 #include <qtextdocument.h>  // Qt::escape is currently defined here...
6 #include <QDirIterator>
7 #include <QFileInfo>
8 #include <QtAlgorithms>
9 #include <QCryptographicHash>
10
11 #include "book.h"
12 #include "opshandler.h"
13 #include "xmlerrorhandler.h"
14 #include "extractzip.h"
15 #include "library.h"
16 #include "containerhandler.h"
17 #include "ncxhandler.h"
18 #include "trace.h"
19
20 const int COVER_WIDTH = 53;
21 const int COVER_HEIGHT = 59;
22
23 static QImage makeCover(const QString &path)
24 {
25     return QImage(path).scaled(COVER_WIDTH, COVER_HEIGHT,
26         Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation).
27         scaled(COVER_WIDTH, COVER_HEIGHT, Qt::KeepAspectRatio);
28 }
29
30 Book::Book(const QString &p, QObject *parent): QObject(parent)
31 {
32     mPath = "";
33     if (p.size()) {
34         QFileInfo info(p);
35         mPath = info.absoluteFilePath();
36         title = info.baseName();
37         cover = makeCover(":/icons/book.png");
38         mTempFile.open();
39     }
40 }
41
42 QString Book::path() const
43 {
44     return mPath;
45 }
46
47 bool Book::open()
48 {
49     Trace t("Book::open");
50     t.trace(path());
51     close();
52     clear();
53     if (path().isEmpty()) {
54         title = "No book";
55         return false;
56     }
57     if (!extract()) {
58         return false;
59     }
60     if (!parse()) {
61         return false;
62     }
63     save();
64     emit opened(path());
65     return true;
66 }
67
68 void Book::peek()
69 {
70     Trace t("Book::peek");
71     t.trace(path());
72     close();
73     clear();
74     if (path().isEmpty()) {
75         title = "No book";
76         return;
77     }
78     if (!extractMetaData()) {
79         return;
80     }
81     if (!parse()) {
82         return;
83     }
84     save();
85     close();
86 }
87
88 void Book::close()
89 {
90     Trace t("Book::close");
91     content.clear();
92     parts.clear();
93     QDir::setCurrent(QDir::rootPath());
94     clearDir(tmpDir());
95 }
96
97 QString Book::tmpDir() const
98 {
99     QString tmpName = QFileInfo(mTempFile.fileName()).fileName();
100     return QDir::tempPath() + "/dorian/" + tmpName;
101 }
102
103 bool Book::extract()
104 {
105     Trace t("Book::extract");
106     bool ret = false;
107     QString tmp = tmpDir();
108     t.trace("Extracting " + mPath + " to " + tmp);
109
110     QDir::setCurrent(QDir::rootPath());
111     if (!clearDir(tmp)) {
112         qCritical() << "Book::extract: Failed to remove" << tmp;
113         return false;
114     }
115     QDir d;
116     if (!d.mkpath(tmp)) {
117         qCritical() << "Book::extract: Could not create" << tmp;
118         return false;
119     }
120
121     // If book comes from resource, copy it to the temporary directory first
122     QString bookPath = path();
123     if (bookPath.startsWith(":/books/")) {
124         QFile src(bookPath);
125         QString dst(tmp + "/book.epub");
126         if (!src.copy(dst)) {
127             qCritical() << "Book::extract: Failed to copy built-in book to"
128                     << dst;
129             return false;
130         }
131         bookPath = dst;
132     }
133
134     QString oldDir = QDir::currentPath();
135     if (!QDir::setCurrent(tmp)) {
136         qCritical() << "Book::extract: Could not change to" << tmp;
137         return false;
138     }
139     ret = extractZip(bookPath);
140     if (!ret) {
141         qCritical() << "Book::extract: Extracting ZIP failed";
142     }
143     QDir::setCurrent(oldDir);
144     return ret;
145 }
146
147 bool Book::parse()
148 {
149     Trace t("Book::parse");
150
151     // Parse OPS file
152     bool ret = false;
153     QString opsFileName = opsPath();
154     t.trace("Parsing OPS file" + opsFileName);
155     QFile opsFile(opsFileName);
156     QXmlSimpleReader reader;
157     QXmlInputSource *source = new QXmlInputSource(&opsFile);
158     OpsHandler *opsHandler = new OpsHandler(*this);
159     XmlErrorHandler *errorHandler = new XmlErrorHandler();
160     reader.setContentHandler(opsHandler);
161     reader.setErrorHandler(errorHandler);
162     ret = reader.parse(source);
163     delete errorHandler;
164     delete opsHandler;
165     delete source;
166
167     // Initially, put all content items in the chapter list.
168     // This will be refined by parsing the NCX file later
169     chapters = parts;
170
171     // Load cover image
172     QStringList coverKeys;
173     coverKeys << "cover-image" << "img-cover-jpeg" << "cover";
174     foreach (QString key, coverKeys) {
175         if (content.contains(key)) {
176             t.trace("Loading cover image from " + content[key].href);
177             cover = makeCover(content[key].href);
178             break;
179         }
180     }
181
182     // If there is an "ncx" item in content, parse it: That's the real table of
183     // contents
184     if (content.contains("ncx")) {
185         QString ncxFileName = content["ncx"].href;
186         t.trace("Parsing NCX file " + ncxFileName);
187         QFile ncxFile(ncxFileName);
188         source = new QXmlInputSource(&ncxFile);
189         NcxHandler *ncxHandler = new NcxHandler(*this);
190         errorHandler = new XmlErrorHandler();
191         reader.setContentHandler(ncxHandler);
192         reader.setErrorHandler(errorHandler);
193         ret = reader.parse(source);
194         delete ncxHandler;
195         delete errorHandler;
196         delete source;
197     }
198
199     // Calculate book part sizes
200     size = 0;
201     foreach (QString part, parts) {
202         QFileInfo info(content[part].href);
203         content[part].size = info.size();
204         size += content[part].size;
205     }
206
207     return ret;
208 }
209
210 bool Book::clearDir(const QString &dir)
211 {
212     QDir d(dir);
213     if (!d.exists()) {
214         return true;
215     }
216     QDirIterator i(dir, QDirIterator::Subdirectories);
217     while (i.hasNext()) {
218         QString entry = i.next();
219         if (entry.endsWith("/.") || entry.endsWith("/..")) {
220             continue;
221         }
222         QFileInfo info(entry);
223         if (info.isDir()) {
224             if (!clearDir(entry)) {
225                 return false;
226             }
227         }
228         else {
229             if (!QFile::remove(entry)) {
230                 qCritical() << "Book::clearDir: Could not remove" << entry;
231                 // FIXME: To be investigated: This is happening too often
232                 // return false;
233             }
234         }
235     }
236     (void)d.rmpath(dir);
237     return true;
238 }
239
240 void Book::clear()
241 {
242     close();
243     title = "";
244     creators.clear();
245     date = "";
246     publisher = "";
247     datePublished = "";
248     subject = "";
249     source = "";
250     rights = "";
251 }
252
253 void Book::load()
254 {
255     Trace t("Book::load");
256     t.trace("path: " + path());
257     QSettings settings;
258     QString key = "book/" + path() + "/";
259     t.trace("key: " + key);
260
261     // Load book info
262     title = settings.value(key + "title").toString();
263     t.trace(title);
264     creators = settings.value(key + "creators").toStringList();
265     date = settings.value(key + "date").toString();
266     publisher = settings.value(key + "publisher").toString();
267     datePublished = settings.value(key + "datepublished").toString();
268     subject = settings.value(key + "subject").toString();
269     source = settings.value(key + "source").toString();
270     rights = settings.value(key + "rights").toString();
271     mLastBookmark.part = settings.value(key + "lastpart").toInt();
272     mLastBookmark.pos = settings.value(key + "lastpos").toReal();
273     cover = settings.value(key + "cover").value<QImage>().scaled(COVER_WIDTH,
274         COVER_HEIGHT, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
275     if (cover.isNull()) {
276         cover = makeCover(":/icons/book.png");
277     }
278
279     // Load bookmarks
280     int size = settings.value(key + "bookmarks").toInt();
281     for (int i = 0; i < size; i++) {
282         int part = settings.value(key + "bookmark" + QString::number(i) +
283                                      "/part").toInt();
284         qreal pos = settings.value(key + "bookmark" + QString::number(i) +
285                                    "/pos").toReal();
286         t.trace(QString("Bookmark %1 at part %2, %3").
287                 arg(i).arg(part).arg(pos));
288         mBookmarks.append(Bookmark(part, pos));
289     }
290 }
291
292 void Book::save()
293 {
294     Trace t("Book::save");
295     QSettings settings;
296     QString key = "book/" + path() + "/";
297     t.trace("key: " + key);
298
299     // Save book info
300     settings.setValue(key + "title", title);
301     t.trace("title: " + title);
302     settings.setValue(key + "creators", creators);
303     settings.setValue(key + "date", date);
304     settings.setValue(key + "publisher", publisher);
305     settings.setValue(key + "datepublished", datePublished);
306     settings.setValue(key + "subject", subject);
307     settings.setValue(key + "source", source);
308     settings.setValue(key + "rights", rights);
309     settings.setValue(key + "lastpart", mLastBookmark.part);
310     settings.setValue(key + "lastpos", mLastBookmark.pos);
311     settings.setValue(key + "cover", cover);
312
313     // Save bookmarks
314     settings.setValue(key + "bookmarks", mBookmarks.size());
315     for (int i = 0; i < mBookmarks.size(); i++) {
316         t.trace(QString("Bookmark %1 at %2, %3").
317                 arg(i).arg(mBookmarks[i].part).arg(mBookmarks[i].pos));
318         settings.setValue(key + "bookmark" + QString::number(i) + "/part",
319                           mBookmarks[i].part);
320         settings.setValue(key + "bookmark" + QString::number(i) + "/pos",
321                           mBookmarks[i].pos);
322     }
323 }
324
325 void Book::setLastBookmark(int part, qreal position)
326 {
327     mLastBookmark.part = part;
328     mLastBookmark.pos = position;
329     save();
330 }
331
332 Book::Bookmark Book::lastBookmark() const
333 {
334     return Book::Bookmark(mLastBookmark);
335 }
336
337 void Book::addBookmark(int part, qreal position)
338 {
339     mBookmarks.append(Bookmark(part, position));
340     qSort(mBookmarks.begin(), mBookmarks.end());
341     save();
342 }
343
344 void Book::deleteBookmark(int index)
345 {
346     mBookmarks.removeAt(index);
347     save();
348 }
349
350 QList<Book::Bookmark> Book::bookmarks() const
351 {
352     return mBookmarks;
353 }
354
355 QString Book::opsPath()
356 {
357     Trace t("Book::opsPath");
358     QString ret;
359
360     QFile container(tmpDir() + "/META-INF/container.xml");
361     t.trace(container.fileName());
362     QXmlSimpleReader reader;
363     QXmlInputSource *source = new QXmlInputSource(&container);
364     ContainerHandler *containerHandler = new ContainerHandler();
365     XmlErrorHandler *errorHandler = new XmlErrorHandler();
366     reader.setContentHandler(containerHandler);
367     reader.setErrorHandler(errorHandler);
368     if (reader.parse(source)) {
369         ret = tmpDir() + "/" + containerHandler->rootFile;
370         mRootPath = QFileInfo(ret).absoluteDir().absolutePath();
371         t.trace("OSP path: " + ret);
372         t.trace("Root dir: " + mRootPath);
373     }
374     delete errorHandler;
375     delete containerHandler;
376     delete source;
377     return ret;
378 }
379
380 QString Book::rootPath() const
381 {
382     return mRootPath;
383 }
384
385 QString Book::name() const
386 {
387     if (title.size()) {
388         QString ret = title;
389         if (creators.length()) {
390             ret += "\nBy " + creators[0];
391             for (int i = 1; i < creators.length(); i++) {
392                 ret += ", " + creators[i];
393             }
394         }
395         return ret;
396     } else {
397         return path();
398     }
399 }
400
401 QString Book::shortName() const
402 {
403     return (title.isEmpty())? QFileInfo(path()).baseName(): title;
404 }
405
406 int Book::chapterFromPart(int index)
407 {
408     int ret = -1;
409
410     QString partId = parts[index];
411     QString partHref = content[partId].href;
412
413     for (int i = 0; i < chapters.size(); i++) {
414         QString id = chapters[i];
415         QString href = content[id].href;
416         QString baseRef(href);
417         QUrl url(QString("file://") + href);
418         if (url.hasFragment()) {
419             QString fragment = url.fragment();
420             baseRef.chop(fragment.length() + 1);
421         }
422         if (baseRef == partHref) {
423             ret = i;
424             // Don't break, keep looking
425         }
426     }
427
428     return ret;
429 }
430
431 int Book::partFromChapter(int index)
432 {
433     Trace t("Book::partFromChapter");
434     QString id = chapters[index];
435     QString href = content[id].href;
436     QString baseRef(href);
437     QUrl url(QString("file://") + href);
438     if (url.hasFragment()) {
439         QString fragment = url.fragment();
440         baseRef.chop(fragment.length() + 1);
441     }
442
443     // Swipe through all content items to find the one matching the chapter href
444     // FIXME: Do we need to index content items by href, too?
445     QString contentKey;
446     bool found = false;
447     foreach (contentKey, content.keys()) {
448         if (contentKey == id) {
449             continue;
450         }
451         if (content[contentKey].href == baseRef) {
452             found = true;
453             t.trace(QString("Key for %1 is %2").arg(baseRef).arg(contentKey));
454             break;
455         }
456     }
457     if (!found) {
458         t.trace("Could not find key for " + baseRef);
459         return -1;
460     }
461     int partIndex = parts.indexOf(contentKey);
462     if (partIndex == -1) {
463         qCritical()
464             << "Book::partFromChapter: Could not find part index of chapter"
465             << id;
466     }
467     return partIndex;
468 }
469
470 qreal Book::getProgress(int part, qreal position)
471 {
472     Q_ASSERT(part < parts.size());
473     QString key;
474     qreal partSize = 0;
475     for (int i = 0; i < part; i++) {
476         key = parts[i];
477         partSize += content[key].size;
478     }
479     key = parts[part];
480     partSize += content[key].size * position;
481     return partSize / (qreal)size;
482 }
483
484 bool Book::extractMetaData()
485 {
486     // FIXME
487     return extract();
488 }