Exemple #1
0
QVariant MessageComposer::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.column() != 0 || index.row() < 0 || index.row() >= m_attachments.size())
        return QVariant();

    switch (role) {
    case Qt::DisplayRole:
        return m_attachments[index.row()]->caption();
    case Qt::ToolTipRole:
        return m_attachments[index.row()]->tooltip();
    case Qt::DecorationRole:
    {
        // This is more or less copy-pasted from Gui/AttachmentView.cpp. Unfortunately, sharing the implementation
        // is not trivial due to the way how the static libraries are currently built.
        QMimeType mimeType = QMimeDatabase().mimeTypeForName(QString::fromUtf8(m_attachments[index.row()]->mimeType()));
        if (mimeType.isValid() && !mimeType.isDefault()) {
            return QIcon::fromTheme(mimeType.iconName(), UiUtils::loadIcon(QStringLiteral("mail-attachment")));
        } else {
            return UiUtils::loadIcon(QStringLiteral("mail-attachment"));
        }
    }
    case Imap::Mailbox::RoleAttachmentContentDispositionMode:
        return static_cast<int>(m_attachments[index.row()]->contentDispositionMode());
    }
    return QVariant();
}
Vector<String> MIMETypeRegistry::getExtensionsForMIMEType(const String& mimeTypeName)
{
    Vector<String> extensions;
    QMimeType mimeType = QMimeDatabase().mimeTypeForName(mimeTypeName);
    if (mimeType.isValid() && !mimeType.isDefault()) {
        Q_FOREACH(const QString& suffix, mimeType.suffixes()) {
            extensions.append(suffix);
        }
    }
String MIMETypeRegistry::getMIMETypeForPath(const String& path)
{
    QMimeType type = QMimeDatabase().mimeTypeForFile(path, QMimeDatabase::MatchExtension);
    if (type.isValid() && !type.isDefault())
        return type.name();

    const ExtensionMap *e = extensionMap;
    while (e->extension) {
        if (path.endsWith(e->dotExtension))
            return e->mimeType;
        ++e;
    }

    return defaultMIMEType();
}
void tst_QMimeDatabase::mimeTypeForName()
{
    QMimeDatabase db;
    QMimeType s0 = db.mimeTypeForName(QString::fromLatin1("application/x-zerosize"));
    QVERIFY(s0.isValid());
    QCOMPARE(s0.name(), QString::fromLatin1("application/x-zerosize"));
    QCOMPARE(s0.comment(), QString::fromLatin1("empty document"));

    QMimeType s0Again = db.mimeTypeForName(QString::fromLatin1("application/x-zerosize"));
    QCOMPARE(s0Again.name(), s0.name());

    QMimeType s1 = db.mimeTypeForName(QString::fromLatin1("text/plain"));
    QVERIFY(s1.isValid());
    QCOMPARE(s1.name(), QString::fromLatin1("text/plain"));
    //qDebug("Comment is %s", qPrintable(s1.comment()));

    QMimeType krita = db.mimeTypeForName(QString::fromLatin1("application/x-krita"));
    QVERIFY(krita.isValid());

    // Test <comment> parsing with application/rdf+xml which has the english comment after the other ones
    QMimeType rdf = db.mimeTypeForName(QString::fromLatin1("application/rdf+xml"));
    QVERIFY(rdf.isValid());
    QCOMPARE(rdf.comment(), QString::fromLatin1("RDF file"));

    QMimeType bzip2 = db.mimeTypeForName(QString::fromLatin1("application/x-bzip2"));
    QVERIFY(bzip2.isValid());
    QCOMPARE(bzip2.comment(), QString::fromLatin1("Bzip archive"));

    QMimeType defaultMime = db.mimeTypeForName(QString::fromLatin1("application/octet-stream"));
    QVERIFY(defaultMime.isValid());
    QVERIFY(defaultMime.isDefault());

    QMimeType doesNotExist = db.mimeTypeForName(QString::fromLatin1("foobar/x-doesnot-exist"));
    QVERIFY(!doesNotExist.isValid());

    // TODO move to findByFile
#ifdef Q_OS_LINUX
    QString exePath = QStandardPaths::findExecutable(QLatin1String("ls"));
    if (exePath.isEmpty())
        qWarning() << "ls not found";
    else {
        const QString executableType = QString::fromLatin1("application/x-executable");
        //QTest::newRow("executable") << exePath << executableType;
        QCOMPARE(db.mimeTypeForFile(exePath).name(), executableType);
    }
#endif

}
KisImportExportFilter::ConversionStatus KisImportExportManager::exportDocument(const QString& url, QByteArray& mimeType)
{
    bool userCancelled = false;

    // The import url should already be set correctly (null if we have a KisDocument
    // file manager and to the correct URL if we have an embedded manager)
    m_direction = Export; // vital information!
    m_exportUrl = url;

    KisFilterChain::Ptr chain;
    if (m_document) {
        // We have to pick the right native mimetype as source.
        QStringList nativeMimeTypes;
        nativeMimeTypes.append(m_document->nativeFormatMimeType());
        nativeMimeTypes += m_document->extraNativeMimeTypes();
        QStringList::ConstIterator it = nativeMimeTypes.constBegin();
        const QStringList::ConstIterator end = nativeMimeTypes.constEnd();
        for (; !chain && it != end; ++it) {
            m_graph.setSourceMimeType((*it).toLatin1());
            if (m_graph.isValid())
                chain = m_graph.chain(this, mimeType);
        }
    } else if (!m_importUrlMimetypeHint.isEmpty()) {
        dbgFile << "Using the mimetype hint:" << m_importUrlMimetypeHint;
        m_graph.setSourceMimeType(m_importUrlMimetypeHint);
    } else {
        QUrl u;
        u.setPath(m_importUrl);
        QMimeDatabase db;
        QMimeType t = db.mimeTypeForFile(u.path(), QMimeDatabase::MatchExtension);
        if (!t.isValid() || t.isDefault()) {
            errFile << "No mimetype found for" << m_importUrl;
            return KisImportExportFilter::BadMimeType;
        }
        m_graph.setSourceMimeType(t.name().toLatin1());

        if (!m_graph.isValid()) {
            warnFile << "Can't open" << t.name() << ", trying filter chooser";

            QApplication::setOverrideCursor(Qt::ArrowCursor);
            KisFilterChooser chooser(0, KisImportExportManager::mimeFilter(), QString(), u);
            if (chooser.exec())
                m_graph.setSourceMimeType(chooser.filterSelected().toLatin1());
            else
                userCancelled = true;

            QApplication::restoreOverrideCursor();
        }
    }

    if (!m_graph.isValid()) {
        errFile << "Couldn't create a valid graph for this source mimetype.";
        if (!d->batch && !userCancelled) {
            QMessageBox::critical(0, i18nc("@title:window", "Krita"), i18n("Could not export file: the export filter is missing."));
        }
        return KisImportExportFilter::BadConversionGraph;
    }

    if (!chain)   // already set when coming from the m_document case
        chain = m_graph.chain(this, mimeType);

    if (!chain) {
        errFile << "Couldn't create a valid filter chain to " << mimeType << " !" << endl;
        if (!d->batch) {
            QMessageBox::critical(0, i18nc("@title:window", "Krita"), i18n("Could not export file: the export filter is missing."));
        }
        return KisImportExportFilter::BadConversionGraph;
    }

    return chain->invokeChain();
}
Exemple #6
0
void ArkViewer::view(const QString& fileName)
{
    QMimeDatabase db;
    QMimeType mimeType = db.mimeTypeForFile(fileName);
    qCDebug(ARK) << "viewing" << fileName << "with mime type:" << mimeType.name();
    KService::Ptr viewer = ArkViewer::getViewer(mimeType.name());

    const bool needsExternalViewer = (viewer &&
                                      !viewer->hasServiceType(QStringLiteral("KParts/ReadOnlyPart")));
    if (needsExternalViewer) {
        // We have already resolved the MIME type and the service above.
        // So there is no point in using KRun::runUrl() which would need
        // to do the same again.

        qCDebug(ARK) << "Using external viewer";

        const QList<QUrl> fileUrlList = {QUrl::fromLocalFile(fileName)};
        // The last argument (tempFiles) set to true means that the temporary
        // file will be removed when the viewer application exits.
        KRun::runService(*viewer, fileUrlList, nullptr, true);
        return;
    }

    qCDebug(ARK) << "Attempting to use internal viewer";
    bool viewInInternalViewer = true;
    if (!viewer) {
        // No internal viewer available for the file.  Ask the user if it
        // should be previewed as text/plain.

        qCDebug(ARK) << "Internal viewer not available";

        int response;
        if (!mimeType.isDefault()) {
            // File has a defined MIME type, and not the default
            // application/octet-stream.  So it could be viewable as
            // plain text, ask the user.
            response = KMessageBox::warningContinueCancel(nullptr,
                xi18n("The internal viewer cannot preview this type of file<nl/>(%1).<nl/><nl/>Do you want to try to view it as plain text?", mimeType.name()),
                i18nc("@title:window", "Cannot Preview File"),
                KGuiItem(i18nc("@action:button", "Preview as Text"), QIcon::fromTheme(QStringLiteral("text-plain"))),
                KStandardGuiItem::cancel(),
                QStringLiteral("PreviewAsText_%1").arg(mimeType.name()));
        }
        else {
            // No defined MIME type, or the default application/octet-stream.
            // There is still a possibility that it could be viewable as plain
            // text, so ask the user.  Not the same as the message/question
            // above, because the wording and default are different.
            response = KMessageBox::warningContinueCancel(nullptr,
                xi18n("The internal viewer cannot preview this unknown type of file.<nl/><nl/>Do you want to try to view it as plain text?"),
                i18nc("@title:window", "Cannot Preview File"),
                KGuiItem(i18nc("@action:button", "Preview as Text"), QIcon::fromTheme(QStringLiteral("text-plain"))),
                KStandardGuiItem::cancel(),
                QString(),
                KMessageBox::Dangerous);
        }

        if (response == KMessageBox::Cancel) {
            viewInInternalViewer = false;
        }
        else {						// set for viewer later
            mimeType = db.mimeTypeForName(QStringLiteral("text/plain"));
        }
    }

    if (viewInInternalViewer) {
        qCDebug(ARK) << "Opening internal viewer";
        ArkViewer *internalViewer = new ArkViewer();
        internalViewer->show();
        if (internalViewer->viewInInternalViewer(fileName, mimeType)) {
            // The internal viewer is showing the file, and will
            // remove the temporary file in its destructor.  So there
            // is no more to do here.
            return;
        }
        else {
            KMessageBox::sorry(nullptr, i18n("The internal viewer cannot preview this file."));
            delete internalViewer;
        }
    }

    // Only get here if there is no internal viewer available or could be
    // used for the file, and no external viewer was opened.  Nothing can be
    // done with the temporary file, so remove it now.
    qCDebug(ARK) << "Removing temporary file:" << fileName;
    QFile::remove(fileName);
}
int main(int argc, char **argv)
{
    KLocalizedString::setApplicationDomain( "koconverter" );

    K4AboutData aboutData("calligraconverter", 0, ki18n("CalligraConverter"), CalligraVersionWrapper::versionString().toLatin1(),
                         ki18n("Calligra Document Converter"),
                         K4AboutData::License_GPL,
                         ki18n("(c) 2001-2011 Calligra developers"));
    aboutData.addAuthor(ki18n("David Faure"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Nicolas Goutte"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Dan Leinir Turthra Jensen"), KLocalizedString(), "*****@*****.**");
    KCmdLineArgs::init(argc, argv, &aboutData);

    KCmdLineOptions options;
    options.add("+in", ki18n("Input file"));
    options.add("+out", ki18n("Output file"));
    options.add("backup", ki18n("Make a backup of the destination file"));
    options.add("batch", ki18n("Batch mode: do not show dialogs"));
    options.add("interactive", ki18n("Interactive mode: show dialogs (default)"));
    options.add("mimetype <mime>", ki18n("Mimetype of the output file"));

    // PDF related options.
    options.add("print-orientation <name>", ki18n("The print orientation. This could be either Portrait or Landscape."));
    options.add("print-papersize <name>", ki18n("The paper size. A4, Legal, Letter, ..."));
    options.add("print-margin <size>", ki18n("The size of the paper margin. By default this is 0.2."));

    KCmdLineArgs::addCmdLineOptions(options);

    KApplication app;

    // Get the command line arguments which we have to parse
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if (args->count() != 2) {
        KCmdLineArgs::usageError(i18n("Two arguments required"));
        return 3;
    }

    const QUrl urlIn = args->url(0);
    const QUrl urlOut = args->url(1);

    // Are we in batch mode or in interactive mode.
    bool batch = args->isSet("batch");
    if (args->isSet("interactive")) {
        batch = false;
    }

    if (args->isSet("backup")) {
        // Code form koDocument.cc
        KIO::UDSEntry entry;
        if (KIO::NetAccess::stat(urlOut, entry, 0L)) {   // this file exists => backup
            kDebug() << "Making backup...";
            QUrl backup(urlOut);
            backup.setPath(urlOut.path() + '~');
            KIO::FileCopyJob *job = KIO::file_copy(urlOut, backup, -1, KIO::Overwrite | KIO::HideProgressInfo);
            job->exec();
        }
    }

    QMimeDatabase db;
    QMimeType inputMimetype = db.mimeTypeForUrl(urlIn);
    if (!inputMimetype.isValid() || inputMimetype.isDefault()) {
        kError() << i18n("Mimetype for input file %1 not found!", urlIn.toDisplayString()) << endl;
        return 1;
    }

    QMimeType outputMimetype;
    if (args->isSet("mimetype")) {
        QString mime = args->getOption("mimetype");
        outputMimetype = db.mimeTypeForName(mime);
        if (! outputMimetype.isValid()) {
            kError() << i18n("Mimetype not found %1", mime) << endl;
            return 1;
        }
    } else {
        outputMimetype = db.mimeTypeForUrl(urlOut);
        if (!outputMimetype.isValid() || outputMimetype.isDefault()) {
            kError() << i18n("Mimetype not found, try using the -mimetype option") << endl;
            return 1;
        }
    }

    QApplication::setOverrideCursor(Qt::WaitCursor);

    QString outputFormat = outputMimetype.name();
    bool ok = false;
    if (outputFormat == "application/pdf") {
        QString orientation = args->getOption("print-orientation");
        QString papersize = args->getOption("print-papersize");
        QString margin = args->getOption("print-margin");
        ok = convertPdf(urlIn, inputMimetype.name(), urlOut, outputFormat, orientation, papersize, margin);
    } else {
        ok = convert(urlIn, inputMimetype.name(), urlOut, outputFormat, batch);
    }

    QTimer::singleShot(0, &app, SLOT(quit()));
    app.exec();

    QApplication::restoreOverrideCursor();

    if (!ok) {
        kError() << i18n("*** The conversion failed! ***") << endl;
        return 2;
    }

    return 0;
}
void NetworkAccessManager::HandleDownload(QObject *object){
#ifdef WEBENGINEVIEW
    static QSet<QObject*> set;
    if(set.contains(object)) return;
    set << object;
    connect(object, &QObject::destroyed, [object](){ set.remove(object);});

    Application::AskDownloadPolicyIfNeed();

    DownloadItem *item = new DownloadItem(object);
    QWebEngineDownloadItem *orig_item = qobject_cast<QWebEngineDownloadItem*>(object);

    QString dir = Application::GetDownloadDirectory();
    QString filename;
    QString mime;
    QUrl url;
    if(orig_item){
        if(WebEngineView *w = qobject_cast<WebEngineView*>(Application::CurrentWidget())){
            if(TreeBank *tb = w->GetTreeBank()) tb->GoBackOrCloseForDownload(w);
        }
        filename = orig_item->path();
        mime = orig_item->mimeType();
        url = orig_item->url();
    } else {
        if(QuickWebEngineView *w = qobject_cast<QuickWebEngineView*>(Application::CurrentWidget())){
            if(TreeBank *tb = w->GetTreeBank()) tb->GoBackOrCloseForDownload(w);
        }
        filename = object->property("path").toString();
        mime = object->property("mimeType").toString();
        url = object->property("url").toUrl();
    }

    filename = filename.isEmpty() ? dir
        : dir + filename.split(QStringLiteral("/")).last();

    if(filename.isEmpty() ||
       Application::GetDownloadPolicy() == Application::Undefined_ ||
       Application::GetDownloadPolicy() == Application::AskForEachDownload){

        QString filter;

        QMimeDatabase db;
        QMimeType mimeType = db.mimeTypeForName(mime);
        if(!mimeType.isValid() || mimeType.isDefault()) mimeType = db.mimeTypeForFile(filename);
        if(!mimeType.isValid() || mimeType.isDefault()) mimeType = db.mimeTypeForUrl(url);

        if(mimeType.isValid() && !mimeType.isDefault()) filter = mimeType.filterString();

        filename = ModalDialog::GetSaveFileName_(QString(), filename, filter);
    }

    if(filename.isEmpty()){
        QMetaObject::invokeMethod(object, "cancel");
        item->deleteLater();
        return;
    }

    item->SetPath(filename);
    if(orig_item){
        orig_item->setPath(filename);
    } else {
        object->setProperty("path", filename);
    }
    QMetaObject::invokeMethod(object, "accept");
    MainWindow *win = Application::GetCurrentWindow();
    if(win && win->GetTreeBank()->GetNotifier())
        win->GetTreeBank()->GetNotifier()->RegisterDownload(item);

    QStringList path = filename.split(QStringLiteral("/"));
    path.removeLast();
    Application::SetDownloadDirectory(path.join(QStringLiteral("/")) + QStringLiteral("/"));
#else
    Q_UNUSED(object);
#endif
}