5 #include <qtextdocument.h> // Qt::escape is currently defined here...
6 #include <QDirIterator>
8 #include <QtAlgorithms>
9 #include <QVariantHash>
12 #include "opshandler.h"
13 #include "xmlerrorhandler.h"
14 #include "extractzip.h"
16 #include "containerhandler.h"
17 #include "ncxhandler.h"
21 const int COVER_WIDTH = 53;
22 const int COVER_HEIGHT = 59;
24 static QImage makeCover(const QString &path)
26 return QImage(path).scaled(COVER_WIDTH, COVER_HEIGHT,
27 Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation).
28 scaled(COVER_WIDTH, COVER_HEIGHT, Qt::KeepAspectRatio);
31 Book::Book(const QString &p, QObject *parent): QObject(parent)
36 mPath = info.absoluteFilePath();
37 title = info.baseName();
38 cover = makeCover(":/icons/book.png");
43 QString Book::path() const
50 Trace t("Book::open");
54 if (path().isEmpty()) {
58 if (!extract(QStringList())) {
71 Trace t("Book::peek");
75 if (path().isEmpty()) {
79 if (!extractMetaData()) {
91 Trace t("Book::close");
94 QDir::setCurrent(QDir::rootPath());
98 QString Book::tmpDir() const
100 QString tmpName = QFileInfo(mTempFile.fileName()).fileName();
101 return QDir(QDir::temp().absoluteFilePath("dorian")).
102 absoluteFilePath(tmpName);
105 bool Book::extract(const QStringList &excludedExtensions)
107 Trace t("Book::extract");
109 QString tmp = tmpDir();
110 qDebug() << "Extracting" << mPath << "to" << tmp;
112 QDir::setCurrent(QDir::rootPath());
113 if (!clearDir(tmp)) {
114 qCritical() << "Book::extract: Failed to remove" << tmp;
119 if (!d.mkpath(tmp)) {
120 qCritical() << "Book::extract: Could not create" << tmp;
125 // If book comes from resource, copy it to the temporary directory first
126 QString bookPath = path();
127 if (bookPath.startsWith(":/books/")) {
129 QString dst(QDir(tmp).absoluteFilePath("book.epub"));
130 if (!src.copy(dst)) {
131 qCritical() << "Book::extract: Failed to copy built-in book"
132 << bookPath << "to" << dst;
138 QString oldDir = QDir::currentPath();
139 if (!QDir::setCurrent(tmp)) {
140 qCritical() << "Book::extract: Could not change to" << tmp;
143 ret = extractZip(bookPath, excludedExtensions);
145 qCritical() << "Book::extract: Extracting ZIP failed";
147 QDir::setCurrent(oldDir);
153 Trace t("Book::parse");
157 QString opsFileName = opsPath();
158 qDebug() << "Parsing OPS file" << opsFileName;
159 QFile opsFile(opsFileName);
160 QXmlSimpleReader reader;
161 QXmlInputSource *source = new QXmlInputSource(&opsFile);
162 OpsHandler *opsHandler = new OpsHandler(*this);
163 XmlErrorHandler *errorHandler = new XmlErrorHandler();
164 reader.setContentHandler(opsHandler);
165 reader.setErrorHandler(errorHandler);
166 ret = reader.parse(source);
171 // Initially, put all content items in the chapter list.
172 // This will be refined by parsing the NCX file later
177 QStringList coverKeys;
178 coverKeys << "cover-image" << "img-cover-jpeg" << "cover";
179 foreach (QString key, coverKeys) {
180 if (content.contains(key)) {
181 coverPath = QDir(rootPath()).absoluteFilePath(content[key].href);
185 if (coverPath.isEmpty()) {
187 QString coverJpeg = QDir(rootPath()).absoluteFilePath("cover.jpg");
188 if (QFileInfo(coverJpeg).exists()) {
189 coverPath = coverJpeg;
192 if (!coverPath.isEmpty()) {
193 qDebug() << "Loading cover image from" << coverPath;
194 cover = makeCover(coverPath);
197 // If there is an "ncx" item in content, parse it: That's the real table of
200 if (content.contains("ncx")) {
201 ncxFileName = content["ncx"].href;
202 } else if (content.contains("ncxtoc")) {
203 ncxFileName = content["ncxtoc"].href;
204 } else if (content.contains("toc")) {
205 ncxFileName = content["toc"].href;
207 qDebug() << "No NCX table of contents";
209 if (!ncxFileName.isEmpty()) {
210 qDebug() << "Parsing NCX file" << ncxFileName;
211 QFile ncxFile(QDir(rootPath()).absoluteFilePath(ncxFileName));
212 source = new QXmlInputSource(&ncxFile);
213 NcxHandler *ncxHandler = new NcxHandler(*this);
214 errorHandler = new XmlErrorHandler();
215 reader.setContentHandler(ncxHandler);
216 reader.setErrorHandler(errorHandler);
217 ret = reader.parse(source);
223 // Calculate book part sizes
225 foreach (QString part, parts) {
226 QFileInfo info(QDir(rootPath()).absoluteFilePath(content[part].href));
227 content[part].size = info.size();
228 size += content[part].size;
234 bool Book::clearDir(const QString &dir)
240 QDirIterator i(dir, QDirIterator::Subdirectories);
241 while (i.hasNext()) {
242 QString entry = i.next();
243 if (entry.endsWith("/.") || entry.endsWith("/..")) {
246 QFileInfo info(entry);
248 if (!clearDir(entry)) {
253 if (!QFile::remove(entry)) {
254 qCritical() << "Book::clearDir: Could not remove" << entry;
255 // FIXME: To be investigated: This is happening too often
279 Trace t("Book::load");
280 qDebug() << "path" << path();
282 QVariantHash data = BookDb::instance()->load(path());
283 title = data["title"].toString();
285 creators = data["creators"].toStringList();
286 date = data["date"].toString();
287 publisher = data["publisher"].toString();
288 datePublished = data["datepublished"].toString();
289 subject = data["subject"].toString();
290 source = data["source"].toString();
291 rights = data["rights"].toString();
292 mLastBookmark.part = data["lastpart"].toInt();
293 mLastBookmark.pos = data["lastpos"].toReal();
294 cover = data["cover"].value<QImage>().scaled(COVER_WIDTH,
295 COVER_HEIGHT, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
296 if (cover.isNull()) {
297 cover = makeCover(":/icons/book.png");
299 int size = data["bookmarks"].toInt();
300 for (int i = 0; i < size; i++) {
301 int part = data[QString("bookmark%1part").arg(i)].toInt();
302 qreal pos = data[QString("bookmark%1pos").arg(i)].toReal();
303 QString note = data[QString("bookmark%1note").arg(i)].toString();
304 mBookmarks.append(Bookmark(part, pos, note));
310 Trace t("Book::save");
313 data["title"] = title;
314 data["creators"] = creators;
316 data["publisher"] = publisher;
317 data["datepublished"] = datePublished;
318 data["subject"] = subject;
319 data["source"] = source;
320 data["rights"] = rights;
321 data["lastpart"] = mLastBookmark.part;
322 data["lastpos"] = mLastBookmark.pos;
323 data["cover"] = cover;
324 data["bookmarks"] = mBookmarks.size();
325 for (int i = 0; i < mBookmarks.size(); i++) {
326 data[QString("bookmark%1part").arg(i)] = mBookmarks[i].part;
327 data[QString("bookmark%1pos").arg(i)] = mBookmarks[i].pos;
328 data[QString("bookmark%1note").arg(i)] = mBookmarks[i].note;
330 BookDb::instance()->save(path(), data);
333 void Book::setLastBookmark(int part, qreal position)
335 Trace t("Book:setLastBookmark");
336 qDebug() << "part" << part << "position" << position;
337 mLastBookmark.part = part;
338 mLastBookmark.pos = position;
342 Book::Bookmark Book::lastBookmark() const
344 return Book::Bookmark(mLastBookmark);
347 void Book::addBookmark(int part, qreal position, const QString ¬e)
349 mBookmarks.append(Bookmark(part, position, note));
350 qSort(mBookmarks.begin(), mBookmarks.end());
354 void Book::deleteBookmark(int index)
356 mBookmarks.removeAt(index);
360 QList<Book::Bookmark> Book::bookmarks() const
365 QString Book::opsPath()
367 Trace t("Book::opsPath");
370 QFile container(tmpDir() + "/META-INF/container.xml");
371 qDebug() << container.fileName();
372 QXmlSimpleReader reader;
373 QXmlInputSource *source = new QXmlInputSource(&container);
374 ContainerHandler *containerHandler = new ContainerHandler();
375 XmlErrorHandler *errorHandler = new XmlErrorHandler();
376 reader.setContentHandler(containerHandler);
377 reader.setErrorHandler(errorHandler);
378 if (reader.parse(source)) {
379 ret = tmpDir() + "/" + containerHandler->rootFile;
380 mRootPath = QFileInfo(ret).absoluteDir().absolutePath();
381 qDebug() << "OSP path" << ret << "\nRoot dir" << mRootPath;
384 delete containerHandler;
389 QString Book::rootPath() const
394 QString Book::name() const
398 if (creators.length()) {
399 ret += "\nBy " + creators[0];
400 for (int i = 1; i < creators.length(); i++) {
401 ret += ", " + creators[i];
410 QString Book::shortName() const
412 return (title.isEmpty())? QFileInfo(path()).baseName(): title;
415 int Book::chapterFromPart(int index)
419 QString partId = parts[index];
420 QString partHref = content[partId].href;
422 for (int i = 0; i < chapters.size(); i++) {
423 QString id = chapters[i];
424 QString href = content[id].href;
425 QString baseRef(href);
426 QUrl url(QString("file://") + href);
427 if (url.hasFragment()) {
428 QString fragment = url.fragment();
429 baseRef.chop(fragment.length() + 1);
431 if (baseRef == partHref) {
433 // Don't break, keep looking
440 int Book::partFromChapter(int index)
442 Trace t("Book::partFromChapter");
443 QString id = chapters[index];
444 QString href = content[id].href;
445 int hashPos = href.indexOf("#");
447 href = href.left(hashPos);
450 qDebug() << "Chapter" << index;
451 qDebug() << " id" << id;
452 qDebug() << " href" << href;
454 for (int i = 0; i < parts.size(); i++) {
455 QString partId = parts[i];
456 if (content[partId].href == href) {
457 qDebug() << "Part index for" << href << "is" << i;
462 qWarning() << "Book::partFromChapter: Could not find part index for"
467 qreal Book::getProgress(int part, qreal position)
469 Q_ASSERT(part < parts.size());
472 for (int i = 0; i < part; i++) {
474 partSize += content[key].size;
477 partSize += content[key].size * position;
478 return partSize / (qreal)size;
481 bool Book::extractMetaData()
483 QStringList excludedExtensions;
484 excludedExtensions << ".html" << ".xhtml" << ".xht" << ".htm";
485 return extract(excludedExtensions);
490 Trace t("Book::upgrade");
494 // Load book from old database (QSettings)
497 QString key = "book/" + path() + "/";
498 title = settings.value(key + "title").toString();
500 creators = settings.value(key + "creators").toStringList();
501 date = settings.value(key + "date").toString();
502 publisher = settings.value(key + "publisher").toString();
503 datePublished = settings.value(key + "datepublished").toString();
504 subject = settings.value(key + "subject").toString();
505 source = settings.value(key + "source").toString();
506 rights = settings.value(key + "rights").toString();
507 mLastBookmark.part = settings.value(key + "lastpart").toInt();
508 mLastBookmark.pos = settings.value(key + "lastpos").toReal();
509 cover = settings.value(key + "cover").value<QImage>().scaled(COVER_WIDTH,
510 COVER_HEIGHT, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
511 if (cover.isNull()) {
512 cover = makeCover(":/icons/book.png");
514 int size = settings.value(key + "bookmarks").toInt();
515 for (int i = 0; i < size; i++) {
516 int part = settings.value(key + "bookmark" + QString::number(i) +
518 qreal pos = settings.value(key + "bookmark" + QString::number(i) +
520 qDebug() << QString("Bookmark %1 at part %2, %3").
521 arg(i).arg(part).arg(pos);
522 mBookmarks.append(Bookmark(part, pos));
525 // Save book to new database
532 Trace t("Book::remove");
533 BookDb::instance()->remove(path());