Beispiel #1
0
void Oven::cook(QString inputContents, QString scriptContents) {
  QTemporaryFile file;
  QProcess process;
  
  if (file.open()) {
    QString filename = file.fileName();
    
    file.write(scriptContents.toUtf8());
    if (!file.error()) {
      file.close();
      
      process.setProcessChannelMode(QProcess::ForwardedChannels);
      process.start("bash", QStringList() << filename);
      
      QTextStream inputStream(&process);
      inputStream << inputContents;
      inputStream.flush();
      process.closeWriteChannel();
      
      if (process.waitForStarted() && process.waitForFinished()) {
        // success!
        return;
      }
    }
  }
  
  if (file.error() != QTemporaryFile::NoError) {
    emit error(file.errorString());
  } else {
    emit error(process.errorString());
  }
  
  // error.
  return;
}
Beispiel #2
0
ProcessPtr
Process::execute(QString const &command,
                 QStringList const &args,
                 bool useTempFile) {
  auto runner = [](QString const &commandToUse, QStringList const &argsToUse) {
    auto pr = std::make_shared<Process>( commandToUse, argsToUse );
    pr->run();
    return pr;
  };

  if (!useTempFile)
    return runner(command, args);

  QTemporaryFile optFile;

  if (!optFile.open())
    throw ProcessX{ to_utf8(QY("Error creating a temporary file (reason: %1).").arg(optFile.errorString())) };

  static const unsigned char utf8_bom[3] = {0xef, 0xbb, 0xbf};
  optFile.write(reinterpret_cast<char const *>(utf8_bom), 3);
  for (auto &arg : args)
    optFile.write(QString{"%1\n"}.arg(arg).toUtf8());
  optFile.close();

  QStringList argsToUse;
  argsToUse << QString{"@%1"}.arg(optFile.fileName());
  return runner(command, argsToUse);
}
Beispiel #3
0
bool MountProtector::lock(const QString& path) {
    if (path.isEmpty()) {
        qmlInfo(this) << "Cannot lock an empty path";
        return false;
    }

    QString p = QString("%1%2.cameraplus_tmp_XXXXXX").arg(path).arg(QDir::separator());
    QTemporaryFile *file = new QTemporaryFile(p);
    file->setAutoRemove(true);

    if (!file->open()) {
        qmlInfo(this) << "Failed to lock" << file->errorString();
        delete file;
        file = 0;
        return false;
    }

    if (!QFile::remove(file->fileName())) {
        qmlInfo(this) << "Failed to remove temporarily file" << file->fileName();
    }

    m_locks.insert(path, file);

    return true;
}
void SqlTableModel::ouvrirCSV(QString commande)
{
    QTemporaryFile* temporaryFile = new QTemporaryFile(parent());
    if (temporaryFile->open()) {
        QxtCsvModel csv(this);
        csv.insertColumns(0, columnCount());
        csv.insertRows(0, rowCount());
        for (int column = 0; column < csv.columnCount(); column ++) {
            csv.setHeaderText(column, headerData(column, Qt::Horizontal).toString());
        }
        for (int row = 0; row < csv.rowCount(); row ++) {
            for (int column = 0; column < csv.columnCount(); column ++) {
                csv.setText(row, column, QSqlTableModel::data(index(row, column)).toString());
            }
        }
        csv.toCSV(temporaryFile->fileName(), true);
        temporaryFile->close();
        QProcess* process = new QProcess();
        process->start(commande, QStringList { temporaryFile->fileName() });
        connect(process, SIGNAL(finished(int)), temporaryFile, SLOT(deleteLater()));
    } else {
        qCritical() << temporaryFile->errorString();
    }

}
QFileInfoList CDspHaClusterHelper::getReport()
{
	QFileInfoList output;
	QFileInfo p("/usr/bin/vstorage-make-report");
	if (!p.exists())
		return output;
	QDir d("/etc/vstorage/clusters");
	if (!d.exists())
		return output;
	QStringList a = d.entryList(QDir::NoDotAndDotDot | QDir::Dirs);
	foreach (QString x, a)
	{
		QTemporaryFile t;
		t.setFileTemplate(QString("%1/pstorage.%2.XXXXXX.tgz")
			.arg(QDir::tempPath()).arg(x));
		if (!t.open())
		{
			WRITE_TRACE(DBG_FATAL, "QTemporaryFile::open() error: %s",
					QSTR2UTF8(t.errorString()));
			continue;
		}
		QString b, c = QString("%1 -f %2 \"%3\"").arg(p.filePath()).arg(t.fileName()).arg(x);
		if (!HostUtils::RunCmdLineUtility(c, b, -1) || t.size() == 0)
		{
			t.close();
			continue;
		}
		t.setAutoRemove(false);
		output.append(QFileInfo(t.fileName()));
		t.close();
	}
bool StateOrchestrator::initialize()
{
    bool ret = false;

    if (isSaving()) {

        QFileInfo fi(fileName);
        QTemporaryFile *tfile = new(std::nothrow) QTemporaryFile(fi.absolutePath().append(QDir::separator()));
        file = tfile;

        if (tfile == nullptr) {
            qFatal("Cannot allocate memory for QTemporaryFile X{");
        }

        ret = tfile->open();
        if (!ret) {
            emit log(tr("Cannot open temporary state file for saving: %1").arg(tfile->errorString()),metaObject()->className(), Pip3lineConst::LERROR);
            return false;
        }
        writer = new(std::nothrow) QXmlStreamWriter(tfile);

        if (writer == nullptr) {
            qFatal("Cannot allocate memory for QXmlStreamWriter X{");
        }

        writer->writeStartDocument();
        writer->writeStartElement(GuiConst::STATE_PIP3LINE_DOC);

    } else {
        file = new(std::nothrow) QFile(fileName); // file is automatically deleted when the orchestrator is deleted
        if (file == nullptr) {
            qFatal("Cannot allocate memory for QFile X{");
        }

        ret = file->open(QIODevice::ReadOnly);
        if (!ret) {
            emit log(tr("Cannot open state file for loading: %1").arg(file->errorString()),metaObject()->className(), Pip3lineConst::LERROR);
            return false;
        }
        reader = new(std::nothrow) QXmlStreamReader(file);

        if (reader == nullptr) {
            qFatal("Cannot allocate memory for QXmlStreamReader X{");
        }

        if (!reader->readNextStartElement()) {
            emit log(tr("XML document seems empty"),metaObject()->className(), Pip3lineConst::LERROR);
            return false;
        } else if (reader->name() != GuiConst::STATE_PIP3LINE_DOC) {
            emit log(tr("This is not a Pip3line state document (%1)").arg(reader->name().toString()),metaObject()->className(), Pip3lineConst::LERROR);
            return false;
        }
    }

    return true;
}
Beispiel #7
0
void EditEntryWidget::openAttachment(const QModelIndex& index)
{
    if (!index.isValid()) {
        Q_ASSERT(false);
        return;
    }

    QString filename = m_attachmentsModel->keyByIndex(index);
    QByteArray attachmentData = m_entryAttachments->value(filename);

    // tmp file will be removed once the database (or the application) has been closed
    QString tmpFileTemplate = QDir::temp().absoluteFilePath(QString("XXXXXX.").append(filename));
    QTemporaryFile* file = new QTemporaryFile(tmpFileTemplate, this);

    if (!file->open()) {
        MessageBox::warning(this, tr("Error"),
                tr("Unable to save the attachment:\n").append(file->errorString()));
        return;
    }

    if (file->write(attachmentData) != attachmentData.size()) {
        MessageBox::warning(this, tr("Error"),
                tr("Unable to save the attachment:\n").append(file->errorString()));
        return;
    }

    if (!file->flush()) {
        MessageBox::warning(this, tr("Error"),
                tr("Unable to save the attachment:\n").append(file->errorString()));
        return;
    }

    file->close();

    QDesktopServices::openUrl(QUrl::fromLocalFile(file->fileName()));
}
Beispiel #8
0
void ExportEPUB::CreateEncryptionXML(const QString &fullfolderpath)
{
    QTemporaryFile file;

    if (!file.open()) {
        boost_throw(CannotOpenFile()
                    << errinfo_file_fullpath(file.fileName().toStdString())
                    << errinfo_file_errorstring(file.errorString().toStdString())
                   );
    }

    EncryptionXmlWriter enc(*m_Book, file);
    enc.WriteXML();
    // Write to disk immediately
    file.flush();
    QFile::copy(file.fileName(), fullfolderpath + "/" + ENCRYPTION_XML_FILE_NAME);
}
Beispiel #9
0
bool FiFoTty::listen()
{
    if (!m_serverPath.isEmpty())
        return true;
    if (!m_serverPath.isEmpty())
        return true;
    QByteArray codedServerPath;
    forever {
        {
            QTemporaryFile tf;
            if (!tf.open()) {
                m_errorString = tr("Cannot create temporary file: %1").arg(tf.errorString());
                m_serverPath.clear();
                return false;
            }
            m_serverPath = tf.fileName();
        }
        // By now the temp file was deleted again
        codedServerPath = QFile::encodeName(m_serverPath);
        if (!::mkfifo(codedServerPath.constData(), 0600))
            break;
        if (errno != EEXIST) {
            m_errorString = tr("Cannot create FiFo %1: %2").
                            arg(m_serverPath, QString::fromLocal8Bit(strerror(errno)));
            m_serverPath.clear();
            return false;
        }
    }
    if ((m_serverFd = ::open(codedServerPath.constData(), O_RDWR|O_NONBLOCK)) < 0) {
        m_errorString = tr("Cannot open FiFo %1: %2").
                        arg(m_serverPath, QString::fromLocal8Bit(strerror(errno)));
        m_serverPath.clear();
        return false;
    }
    m_serverNotifier = new QSocketNotifier(m_serverFd, QSocketNotifier::Read, this);
    connect(m_serverNotifier, SIGNAL(activated(int)), SLOT(bytesAvailable()));
    return true;
}
Beispiel #10
0
static int assemble(Input input, const QInstaller::Settings &settings, const QString &signingIdentity)
{
#ifdef Q_OS_OSX
    if (QInstaller::isInBundle(input.installerExePath)) {
        const QString bundle = input.installerExePath;
        // if the input file was a bundle
        const QSettings s(QString::fromLatin1("%1/Contents/Info.plist").arg(input.installerExePath),
            QSettings::NativeFormat);
        input.installerExePath = QString::fromLatin1("%1/Contents/MacOS/%2").arg(bundle)
            .arg(s.value(QLatin1String("CFBundleExecutable"),
            QFileInfo(input.installerExePath).completeBaseName()).toString());
    }

    const bool createDMG = input.outputPath.endsWith(QLatin1String(".dmg"));
    if (createDMG)
        input.outputPath.replace(input.outputPath.length() - 4, 4, QLatin1String(".app"));

    const bool isBundle = input.outputPath.endsWith(QLatin1String(".app"));
    const QString bundle = isBundle ? input.outputPath : QString();
    const BundleBackup bundleBackup(bundle);

    if (isBundle) {
        // output should be a bundle
        const QFileInfo fi(input.outputPath);

        const QString contentsResourcesPath = fi.filePath() + QLatin1String("/Contents/Resources/");

        QInstaller::mkpath(fi.filePath() + QLatin1String("/Contents/MacOS"));
        QInstaller::mkpath(contentsResourcesPath);

        {
            QFile pkgInfo(fi.filePath() + QLatin1String("/Contents/PkgInfo"));
            pkgInfo.open(QIODevice::WriteOnly);
            QTextStream pkgInfoStream(&pkgInfo);
            pkgInfoStream << QLatin1String("APPL????") << endl;
        }

        QString iconFile;
        if (QFile::exists(settings.installerApplicationIcon())) {
            iconFile = settings.installerApplicationIcon();
        } else {
            iconFile = QString::fromLatin1(":/resources/default_icon_mac.icns");
        }

        const QString iconTargetFile = fi.completeBaseName() + QLatin1String(".icns");
        QFile::copy(iconFile, contentsResourcesPath + iconTargetFile);
        if (QDir(qApp->applicationDirPath() + QLatin1String("/qt_menu.nib")).exists()) {
            copyDirectoryContents(qApp->applicationDirPath() + QLatin1String("/qt_menu.nib"),
                contentsResourcesPath + QLatin1String("/qt_menu.nib"));
        }

        QFile infoPList(fi.filePath() + QLatin1String("/Contents/Info.plist"));
        infoPList.open(QIODevice::WriteOnly);
        QTextStream plistStream(&infoPList);
        plistStream << QLatin1String("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") << endl;
        plistStream << QLatin1String("<!DOCTYPE plist SYSTEM \"file://localhost/System/Library/DTDs"
            "/PropertyList.dtd\">") << endl;
        plistStream << QLatin1String("<plist version=\"0.9\">") << endl;
        plistStream << QLatin1String("<dict>") << endl;
        plistStream << QLatin1String("    <key>CFBundleIconFile</key>") << endl;
        plistStream << QLatin1String("    <string>") << iconTargetFile << QLatin1String("</string>")
            << endl;
        plistStream << QLatin1String("    <key>CFBundlePackageType</key>") << endl;
        plistStream << QLatin1String("    <string>APPL</string>") << endl;
        plistStream << QLatin1String("    <key>CFBundleGetInfoString</key>") << endl;
#define QUOTE_(x) #x
#define QUOTE(x) QUOTE_(x)
        plistStream << QLatin1String("    <string>") << QLatin1String(QUOTE(IFW_VERSION_STR)) << ("</string>")
            << endl;
#undef QUOTE
#undef QUOTE_
        plistStream << QLatin1String("    <key>CFBundleSignature</key>") << endl;
        plistStream << QLatin1String("    <string> ???? </string>") << endl;
        plistStream << QLatin1String("    <key>CFBundleExecutable</key>") << endl;
        plistStream << QLatin1String("    <string>") << fi.completeBaseName() << QLatin1String("</string>")
            << endl;
        plistStream << QLatin1String("    <key>CFBundleIdentifier</key>") << endl;
        plistStream << QLatin1String("    <string>com.yourcompany.installerbase</string>") << endl;
        plistStream << QLatin1String("    <key>NOTE</key>") << endl;
        plistStream << QLatin1String("    <string>This file was generated by Qt Installer Framework.</string>")
            << endl;
        plistStream << QLatin1String("    <key>NSPrincipalClass</key>") << endl;
        plistStream << QLatin1String("    <string>NSApplication</string>") << endl;
        plistStream << QLatin1String("</dict>") << endl;
        plistStream << QLatin1String("</plist>") << endl;

        input.outputPath = QString::fromLatin1("%1/Contents/MacOS/%2").arg(input.outputPath)
            .arg(fi.completeBaseName());
    }
#elif defined(Q_OS_LINUX)
    Q_UNUSED(settings)
#endif

    QTemporaryFile file(input.outputPath);
    if (!file.open()) {
        throw Error(QString::fromLatin1("Cannot copy %1 to %2: %3").arg(input.installerExePath,
            input.outputPath, file.errorString()));
    }

    const QString tempFile = file.fileName();
    file.close();
    file.remove();

    QFile instExe(input.installerExePath);
    if (!instExe.copy(tempFile)) {
        throw Error(QString::fromLatin1("Cannot copy %1 to %2: %3").arg(instExe.fileName(),
            tempFile, instExe.errorString()));
    }

    QtPatch::patchBinaryFile(tempFile, QByteArray("MY_InstallerCreateDateTime_MY"),
        QDateTime::currentDateTime().toString(QLatin1String("yyyy-MM-dd - HH:mm:ss")).toLatin1());


    input.installerExePath = tempFile;

#if defined(Q_OS_WIN)
    // setting the windows icon must happen before we append our binary data - otherwise they get lost :-/
    if (QFile::exists(settings.installerApplicationIcon())) {
        // no error handling as this is not fatal
        setApplicationIcon(tempFile, settings.installerApplicationIcon());
    }
#elif defined(Q_OS_OSX)
    if (isBundle) {
        // no error handling as this is not fatal
        const QString copyscript = QDir::temp().absoluteFilePath(QLatin1String("copylibsintobundle.sh"));
        QFile::copy(QLatin1String(":/resources/copylibsintobundle.sh"), copyscript);
        QFile::rename(tempFile, input.outputPath);
        chmod755(copyscript);
        QProcess p;
        p.start(copyscript, QStringList() << bundle);
        p.waitForFinished(-1);
        QFile::rename(input.outputPath, tempFile);
        QFile::remove(copyscript);
    }
#endif

    QTemporaryFile out;
    QString targetName = input.outputPath;
#ifdef Q_OS_OSX
    QDir resourcePath(QFileInfo(input.outputPath).dir());
    resourcePath.cdUp();
    resourcePath.cd(QLatin1String("Resources"));
    targetName = resourcePath.filePath(QLatin1String("installer.dat"));
#endif

    {
        QFile target(targetName);
        if (target.exists() && !target.remove()) {
            qCritical("Cannot remove target %s: %s", qPrintable(target.fileName()),
                qPrintable(target.errorString()));
            QFile::remove(tempFile);
            return EXIT_FAILURE;
        }
    }

    try {
        QInstaller::openForWrite(&out);
        QFile exe(input.installerExePath);

#ifdef Q_OS_OSX
        if (!exe.copy(input.outputPath)) {
            throw Error(QString::fromLatin1("Cannot copy %1 to %2: %3").arg(exe.fileName(),
                input.outputPath, exe.errorString()));
        }
#else
        QInstaller::openForRead(&exe);
        QInstaller::appendData(&out, &exe, exe.size());
#endif

        foreach (const QInstallerTools::PackageInfo &info, input.packages) {
            QInstaller::ResourceCollection collection;
            collection.setName(info.name.toUtf8());

            qDebug() << "Creating resource archive for" << info.name;
            foreach (const QString &file, info.copiedFiles) {
                const QSharedPointer<Resource> resource(new Resource(file));
                qDebug().nospace() << "Appending " << file << " (" << humanReadableSize(resource->size()) << ")";
                collection.appendResource(resource);
            }
            input.manager.insertCollection(collection);
        }

        const QList<QInstaller::OperationBlob> operations;
        BinaryContent::writeBinaryContent(&out, operations, input.manager,
            BinaryContent::MagicInstallerMarker, BinaryContent::MagicCookie);
    } catch (const Error &e) {
        qCritical("Error occurred while assembling the installer: %s", qPrintable(e.message()));
        QFile::remove(tempFile);
        return EXIT_FAILURE;
    }

    if (!out.rename(targetName)) {
        qCritical("Cannot write installer to %s: %s", targetName.toUtf8().constData(),
            out.errorString().toUtf8().constData());
        QFile::remove(tempFile);
        return EXIT_FAILURE;
    }
    out.setAutoRemove(false);

#ifndef Q_OS_WIN
    chmod755(out.fileName());
#endif
    QFile::remove(tempFile);

#ifdef Q_OS_OSX
    if (isBundle && !signingIdentity.isEmpty()) {
        qDebug() << "Signing .app bundle...";

        QProcess p;
        p.start(QLatin1String("codesign"),
                QStringList() << QLatin1String("--force")
                              << QLatin1String("--deep")
                              << QLatin1String("--sign") << signingIdentity
                              << bundle);

        if (!p.waitForFinished(-1)) {
            qCritical("Failed to sign app bundle: error while running '%s %s': %s",
                      p.program().toUtf8().constData(),
                      p.arguments().join(QLatin1Char(' ')).toUtf8().constData(),
                      p.errorString().toUtf8().constData());
            return EXIT_FAILURE;
        }

        if (p.exitStatus() == QProcess::NormalExit) {
            if (p.exitCode() != 0) {
                qCritical("Failed to sign app bundle: running codesign failed "
                          "with exit code %d: %s", p.exitCode(),
                          p.readAllStandardError().constData());
                return EXIT_FAILURE;
            }
        }

        qDebug() << "done.";
    }

    bundleBackup.release();

    if (createDMG) {
        qDebug() << "creating a DMG disk image...";

        const QString volumeName = QFileInfo(input.outputPath).fileName();
        const QString imagePath = QString::fromLatin1("%1/%2.dmg")
                                    .arg(QFileInfo(bundle).path())
                                    .arg(volumeName);

        // no error handling as this is not fatal
        QProcess p;
        p.start(QLatin1String("/usr/bin/hdiutil"),
                QStringList() << QLatin1String("create")
                              << imagePath
                              << QLatin1String("-srcfolder")
                              << bundle
                              << QLatin1String("-ov")
                              << QLatin1String("-volname")
                              << volumeName
                              << QLatin1String("-fs")
                              << QLatin1String("HFS+"));
        qDebug() << "running " << p.program() << p.arguments();
        p.waitForFinished(-1);
        qDebug() << "removing" << bundle;
        QDir(bundle).removeRecursively();
        qDebug() <<  "done.";
    }
#else
    Q_UNUSED(signingIdentity)
#endif
    return EXIT_SUCCESS;
}
Beispiel #11
0
void HistoryManager::save()
{
    QSettings settings;
    settings.beginGroup(QLatin1String("history"));
    settings.setValue(QLatin1String("historyLimit"), m_historyLimit);

    bool saveAll = m_lastSavedUrl.isEmpty();
    int first = m_history.count() - 1;
    if (!saveAll) {
        // find the first one to save
        for (int i = 0; i < m_history.count(); ++i) {
            if (m_history.at(i).url == m_lastSavedUrl) {
                first = i - 1;
                break;
            }
        }
    }
    if (first == m_history.count() - 1)
        saveAll = true;

    QString directory = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    if (directory.isEmpty())
        directory = QDir::homePath() + QLatin1String("/.") + QCoreApplication::applicationName();
    if (!QFile::exists(directory)) {
        QDir dir;
        dir.mkpath(directory);
    }

    QFile historyFile(directory + QLatin1String("/history"));
    // When saving everything use a temporary file to prevent possible data loss.
    QTemporaryFile tempFile;
    tempFile.setAutoRemove(false);
    bool open = false;
    if (saveAll) {
        open = tempFile.open();
    } else {
        open = historyFile.open(QFile::Append);
    }

    if (!open) {
        qWarning() << "Unable to open history file for saving"
                   << (saveAll ? tempFile.fileName() : historyFile.fileName());
        return;
    }

    QDataStream out(saveAll ? &tempFile : &historyFile);
    for (int i = first; i >= 0; --i) {
        QByteArray data;
        QDataStream stream(&data, QIODevice::WriteOnly);
        HistoryItem item = m_history.at(i);
        stream << HISTORY_VERSION << item.url << item.dateTime << item.title;
        out << data;
    }
    tempFile.close();

    if (saveAll) {
        if (historyFile.exists() && !historyFile.remove())
            qWarning() << "History: error removing old history." << historyFile.errorString();
        if (!tempFile.rename(historyFile.fileName()))
            qWarning() << "History: error moving new history over old." << tempFile.errorString() << historyFile.fileName();
    }
    m_lastSavedUrl = m_history.value(0).url;
}
Beispiel #12
0
/**
 * Save the database to a file.
 *
 * This function uses QTemporaryFile instead of QSaveFile due to a bug
 * in Qt (https://bugreports.qt.io/browse/QTBUG-57299) that may prevent
 * the QSaveFile from renaming itself when using Dropbox, Drive, or OneDrive.
 *
 * The risk in using QTemporaryFile is that the rename function is not atomic
 * and may result in loss of data if there is a crash or power loss at the
 * wrong moment.
 *
 * @param filePath Absolute path of the file to save
 * @param atomic Use atomic file transactions
 * @param backup Backup the existing database file, if exists
 * @param error error message in case of failure
 * @return true on success
 */
bool Database::save(const QString& filePath, QString* error, bool atomic, bool backup)
{
    Q_ASSERT(!m_data.isReadOnly);
    if (m_data.isReadOnly) {
        return false;
    }

    if (atomic) {
        QSaveFile saveFile(filePath);
        if (saveFile.open(QIODevice::WriteOnly)) {
            // write the database to the file
            if (!writeDatabase(&saveFile, error)) {
                return false;
            }

            if (backup) {
                backupDatabase(filePath);
            }

            if (saveFile.commit()) {
                // successfully saved database file
                setFilePath(filePath);
                return true;
            }
        }

        if (error) {
            *error = saveFile.errorString();
        }
    } else {
        QTemporaryFile tempFile;
        if (tempFile.open()) {
            // write the database to the file
            if (!writeDatabase(&tempFile, error)) {
                return false;
            }

            tempFile.close(); // flush to disk

            if (backup) {
                backupDatabase(filePath);
            }

            // Delete the original db and move the temp file in place
            QFile::remove(filePath);

            // Note: call into the QFile rename instead of QTemporaryFile
            // due to an undocumented difference in how the function handles
            // errors. This prevents errors when saving across file systems.
            if (tempFile.QFile::rename(filePath)) {
                // successfully saved the database
                tempFile.setAutoRemove(false);
                setFilePath(filePath);
                return true;
            } else if (!backup || !restoreDatabase(filePath)) {
                // Failed to copy new database in place, and
                // failed to restore from backup or backups disabled
                tempFile.setAutoRemove(false);
                if (error) {
                    *error = tr("%1\nBackup database located at %2").arg(tempFile.errorString(), tempFile.fileName());
                }
                markAsModified();
                return false;
            }
        }

        if (error) {
            *error = tempFile.errorString();
        }
    }

    // Saving failed
    markAsModified();
    return false;
}
Beispiel #13
0
QVariant EpubDocument::loadResource(int type, const QUrl &name)
{
  int size;
  char *data;

  QString fileInPath = mCurrentSubDocument.resolved(name).path();

  // Get the data from the epub file
  size = epub_get_data(mEpub, fileInPath.toUtf8().constData(), &data);

  QVariant resource;

  if (data) {
    switch(type) {
    case QTextDocument::ImageResource:{
      QImage img = QImage::fromData((unsigned char *)data, size);
      const int maxHeight = maxContentHeight();
      const int maxWidth = maxContentWidth();
      if(img.height() > maxHeight)
        img = img.scaledToHeight(maxHeight);
      if(img.width() > maxWidth)
        img = img.scaledToWidth(maxWidth);
      resource.setValue(img);
      break;
    }
    case QTextDocument::StyleSheetResource: {
      QString css = QString::fromUtf8(data);
      checkCSS(css);
      resource.setValue(css);
      break;
    }
    case EpubDocument::MovieResource: {
      QTemporaryFile *tmp = new QTemporaryFile(QStringLiteral("%1/okrXXXXXX").arg(QDir::tempPath()),this);
      if(!tmp->open()) qCWarning(OkularEpuDebug) << "EPUB : error creating temporary video file";
      if(tmp->write(data,size) == -1) qCWarning(OkularEpuDebug) << "EPUB : error writing data" << tmp->errorString();
      tmp->flush();
      resource.setValue(tmp->fileName());
      break;
    }
    case EpubDocument::AudioResource: {
      QByteArray ba(data,size);
      resource.setValue(ba);
      break;
    }
    default:
      resource.setValue(QString::fromUtf8(data));
      break;
    }

    free(data);
  }

  // add to cache
  addResource(type, name, resource); 

  return resource;
}