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