Beispiel #1
0
bool DocumentationViewer::urlSelected(const QString &url, int button, int state, const QString &_target, const KParts::OpenUrlArguments &args, const KParts::BrowserArguments & /* browserArgs */)
{
	QUrl cURL = completeURL(url);
	QMimeDatabase db;
	QString mime = db.mimeTypeForUrl(cURL).name();

	//load this URL in the embedded viewer if KHTML can handle it, or when mimetype detection failed
	KService::Ptr service = KService::serviceByDesktopName("khtml");
	if (db.mimeTypeForUrl(cURL).isDefault() || (service && service->hasServiceType(mime))) {
		KHTMLPart::urlSelected(url, button, state, _target, args);
		openUrl(cURL);
		addToHistory(cURL.url());
	}
	//KHTML can't handle it, look for an appropriate application
	else {
		KService::List offers = KMimeTypeTrader::self()->query(mime, "Type == 'Application'");
		if(offers.isEmpty()) {
			KMessageBox::error(view(), i18n("No KDE service found for the MIME type \"%1\".", mime));
			return false;
		}
		QList<QUrl> lst;
		lst.append(cURL);
		KRun::runService(*(offers.first()), lst, view());
	}
	return true;
}
Beispiel #2
0
void ProjectView::slotClicked(QTreeWidgetItem *item)
{
	if(!item) {
		item = currentItem();
	}

	ProjectViewItem *itm = static_cast<ProjectViewItem*>(item);
	if(itm) {
		if(itm->type() == KileType::File) {
			emit(fileSelected(itm->url()));
		}
		else if(itm->type() == KileType::ProjectItem) {
			emit(fileSelected(itm->projectItem()));
		}
		else if(itm->type() != KileType::Folder) {
			// don't open project configuration files (*.kilepr)
			if(itm->url().toLocalFile().right(7) != ".kilepr") {
				//determine mimeType and open file with preferred application
				QMimeDatabase db;
				QMimeType pMime = db.mimeTypeForUrl(itm->url());
				if(pMime.name().startsWith("text/")) {
					emit(fileSelected(itm->url()));
				}
				else {
					KRun::runUrl(itm->url(), pMime.name(), this);
				}
			}
		}
		clearSelection();
	}
}
Beispiel #3
0
const QString& vfile::vfile_getMime()
{
    if (vfile_mimeType.isEmpty()) {
        if(vfile_isdir)
            vfile_mimeType = "inode/directory";
        else if(vfile_isBrokenLink())
            vfile_mimeType = "unknown";
        else {
            QMimeDatabase db;
            QMimeType mt = db.mimeTypeForUrl(vfile_getUrl());
            vfile_mimeType = mt.isValid() ? mt.name() : "unknown";
            if (mt.isValid())
                vfile_icon = mt.iconName();
            if (vfile_mimeType == "inode/directory") {
                vfile_perm[0] = 'd';
                vfile_isdir = true;
            }
        }

        if (vfile_isdir && vfile_userDefinedFolderIcons) {
            QUrl url = vfile_getUrl();
            if (url.isLocalFile()) {
                QString file = url.toLocalFile() + "/.directory";
                KDesktopFile cfg(file);
                QString icon = cfg.readIcon();
                if(icon.startsWith(QLatin1String("./"))) // relative path
                    icon = url.toLocalFile() + '/' + icon;
                if (!icon.isEmpty())
                    vfile_icon = icon;
            }
        }
    }
    return vfile_mimeType;
}
Beispiel #4
0
QString AnimationResult::mimeType()
{
    QMimeDatabase db;
    QMimeType type = db.mimeTypeForUrl(d->url);

    return type.name();
}
Beispiel #5
0
bool GDMPForm::addFile(const QString& path)
{
    QByteArray str;
    qCDebug(DIGIKAM_WEBSERVICES_LOG) << "in addfile" << path;

    QMimeDatabase db;
    QMimeType ptr = db.mimeTypeForUrl(QUrl::fromLocalFile(path));
    QString mime  = ptr.name();
    str += "--";
    str += m_boundary;
    str += "\r\n";
    str += "Content-Type: ";
    str += mime.toLatin1();
    str += "\r\n\r\n";

    QFile imageFile(path);

    if (!imageFile.open(QIODevice::ReadOnly))
    {
        return false;
    }

    QByteArray imageData = imageFile.readAll();
    m_file_size          = QString::number(imageFile.size());

    imageFile.close();

    m_buffer.append(str);
    m_buffer.append(imageData);
    m_buffer.append("\r\n");

    return true;
}
Beispiel #6
0
QMimeType KFileItem::determineMimeType() const
{
    if (!d) {
        return QMimeType();
    }

    if (!d->m_mimeType.isValid() || !d->m_bMimeTypeKnown) {
        QMimeDatabase db;
        if (isDir()) {
            d->m_mimeType = db.mimeTypeForName(QStringLiteral("inode/directory"));
        } else {
            bool isLocalUrl;
            const QUrl url = mostLocalUrl(&isLocalUrl);
            d->m_mimeType = db.mimeTypeForUrl(url);
            // was:  d->m_mimeType = KMimeType::findByUrl( url, d->m_fileMode, isLocalUrl );
            // => we are no longer using d->m_fileMode for remote URLs.
            Q_ASSERT(d->m_mimeType.isValid());
            //qDebug() << d << "finding final mimetype for" << url << ":" << d->m_mimeType.name();
        }
        d->m_bMimeTypeKnown = true;
    }

    if (d->m_delayedMimeTypes) { // if we delayed getting the iconName up till now, this is the right point in time to do so
        d->m_delayedMimeTypes = false;
        d->m_useIconNameCache = false;
        (void)iconName();
    }

    return d->m_mimeType;
}
void PlacesItemEditDialog::initialize()
{
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
    m_okButton = buttonBox->button(QDialogButtonBox::Ok);
    m_okButton->setDefault(true);
    m_okButton->setShortcut(Qt::CTRL | Qt::Key_Return);
    connect(buttonBox, &QDialogButtonBox::accepted, this, &PlacesItemEditDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &PlacesItemEditDialog::reject);
    setModal(true);
    m_okButton->setDefault(true);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    setLayout(mainLayout);
    QWidget* mainWidget = new QWidget(this);
    mainLayout->addWidget(mainWidget);
    mainLayout->addWidget(buttonBox);

    QVBoxLayout* vBox = new QVBoxLayout(mainWidget);

    QFormLayout* formLayout = new QFormLayout();
    vBox->addLayout( formLayout );

    m_textEdit = new QLineEdit(mainWidget);
    formLayout->addRow(i18nc("@label", "Label:"), m_textEdit);
    m_textEdit->setText(m_text);
    m_textEdit->setPlaceholderText(i18n("Enter descriptive label here"));

    m_urlEdit = new KUrlRequester(m_url, mainWidget);
    m_urlEdit->setMode(KFile::Directory);
    formLayout->addRow(i18nc("@label", "Location:"), m_urlEdit);
    // Provide room for at least 40 chars (average char width is half of height)
    m_urlEdit->setMinimumWidth(m_urlEdit->fontMetrics().height() * (40 / 2));
    connect(m_urlEdit, &KUrlRequester::textChanged, this, &PlacesItemEditDialog::slotUrlChanged);

    m_iconButton = new KIconButton(mainWidget);
    formLayout->addRow(i18nc("@label", "Choose an icon:"), m_iconButton);
    m_iconButton->setIconSize(IconSize(KIconLoader::Desktop));
    m_iconButton->setIconType(KIconLoader::NoGroup, KIconLoader::Place);
    if (m_icon.isEmpty()) {
        QMimeDatabase db;
        m_iconButton->setIcon(db.mimeTypeForUrl(m_url).iconName());
    } else {
        m_iconButton->setIcon(m_icon);
    }

    if (m_allowGlobal) {
        const QString appName = KAboutData::applicationData().displayName();
        m_appLocal = new QCheckBox( i18n("&Only show when using this application (%1)",  appName ), mainWidget );
        m_appLocal->setChecked(false);
        vBox->addWidget(m_appLocal);
    }

    if (m_text.isEmpty()) {
        m_urlEdit->setFocus();
    } else {
        m_textEdit->setFocus();
    }

}
Beispiel #8
0
QString ExportManager::makeSaveMimetype(const QUrl &url)
{
    QMimeDatabase mimedb;
    QString type = mimedb.mimeTypeForUrl(url).preferredSuffix();

    if (type.isEmpty()) {
        return QStringLiteral("png");
    }
    return type;
}
Beispiel #9
0
void DappLoader::downloadComplete(QNetworkReply* _reply)
{
	QUrl requestUrl = _reply->request().url();
	if (m_pageUrls.count(requestUrl) != 0)
	{
		//inject web3 js
		QByteArray content = "<script>\n";
		content.append(web3Content());
		content.append("</script>\n");
		content.append(_reply->readAll());
		QString contentType = _reply->header(QNetworkRequest::ContentTypeHeader).toString();
		if (contentType.isEmpty())
		{
			QMimeDatabase db;
			contentType = db.mimeTypeForUrl(requestUrl).name();
		}
		pageReady(content, contentType, requestUrl);
		return;
	}

	try
	{
		//try to interpret as rlp
		QByteArray data = _reply->readAll();
		_reply->deleteLater();

		h256 expected = m_uriHashes[requestUrl];
		bytes package(reinterpret_cast<unsigned char const*>(data.constData()), reinterpret_cast<unsigned char const*>(data.constData() + data.size()));
		Secp256k1 dec;
		dec.decrypt(expected, package);
		h256 got = sha3(package);
		if (got != expected)
		{
			//try base64
			data = QByteArray::fromBase64(data);
			package = bytes(reinterpret_cast<unsigned char const*>(data.constData()), reinterpret_cast<unsigned char const*>(data.constData() + data.size()));
			dec.decrypt(expected, package);
			got = sha3(package);
			if (got != expected)
				throw dev::Exception() << errinfo_comment("Dapp content hash does not match");
		}

		RLP rlp(package);
		loadDapp(rlp);
	}
	catch (...)
	{
		qWarning() << tr("Error downloading DApp: ") << boost::current_exception_diagnostic_information().c_str();
		emit dappError();
	}

}
void KUrlNavigatorPlacesSelector::dropEvent(QDropEvent *event)
{
    setDisplayHintEnabled(DraggedHint, false);
    update();

    QMimeDatabase db;
    const QList<QUrl> urlList = KUrlMimeData::urlsFromMimeData(event->mimeData());
    foreach (const QUrl &url, urlList) {
        QMimeType mimetype = db.mimeTypeForUrl(url);
        if (mimetype.inherits(QStringLiteral("inode/directory"))) {
            m_placesModel->addPlace(url.fileName(), url);
        }
    }
Beispiel #11
0
bool FlickrMPForm::addFile(const QString& name, const QString& path)
{
    QMimeDatabase db;
    QMimeType ptr = db.mimeTypeForUrl(QUrl::fromLocalFile(path));
    QString mime  = ptr.name();

    if (mime.isEmpty())
    {
        // if we ourselves can't determine the mime of the local file,
        // very unlikely the remote site will be able to identify it
        return false;
    }

    QFile imageFile(path);

    if (!imageFile.open(QIODevice::ReadOnly))
    {
        return false;
    }

    QByteArray imageData = imageFile.readAll();

    QByteArray str;
    QString file_size = QString::fromLatin1("%1").arg(imageFile.size());
    imageFile.close();

    str += "--";
    str += m_boundary;
    str += "\r\n";
    str += "Content-Disposition: form-data; name=\"";
    str += name.toLatin1();
    str += "\"; ";
    str += "filename=\"";
    str += QFile::encodeName(QUrl::fromLocalFile(path).fileName());
    str += "\"\r\n";
    str += "Content-Length: ";
    str += file_size.toLatin1();
    str += "\r\n";
    str += "Content-Type: ";
    str +=  mime.toLatin1();
    str += "\r\n\r\n";

    m_buffer.append(str);
    m_buffer.append(imageData);
    m_buffer.append("\r\n");

    return true;
}
MessageCore::AttachmentFromUrlBaseJob *AttachmentFromUrlUtils::createAttachmentJob(const QUrl &url, QObject *parent)
{
    MessageCore::AttachmentFromUrlBaseJob *ajob = 0;
    QMimeDatabase db;
    if (db.mimeTypeForUrl(url).name() == QLatin1String("inode/directory")) {
        qCDebug(MESSAGECORE_LOG) << "Creating attachment from folder";
        ajob = new MessageCore::AttachmentFromFolderJob(url, parent);
    } else {
        ajob = new MessageCore::AttachmentFromUrlJob(url, parent);
        qCDebug(MESSAGECORE_LOG) << "Creating attachment from file";
    }
    if (MessageCore::MessageCoreSettings::maximumAttachmentSize() > 0) {
        ajob->setMaximumAllowedSize(MessageCore::MessageCoreSettings::maximumAttachmentSize());
    }
    return ajob;
}
Beispiel #13
0
void ProjectView::contextMenuEvent(QContextMenuEvent *event)
{
	QSignalMapper signalMapper, serviceSignalMapper;
	QMenu popup;
	QAction *action = Q_NULLPTR;

	QTreeWidgetItem* treeWidgetItem = itemAt(event->pos());
	if(!treeWidgetItem) {
		return;
	}

	ProjectViewItem *projectViewItem = dynamic_cast<ProjectViewItem*>(treeWidgetItem);
	if(!projectViewItem) {
		return;
	}

	if(projectViewItem->type() == KileType::Folder) {
		return;
	}

	bool insertsep = false;
	bool isKilePrFile = false;
	if(projectViewItem->type() != KileType::Project && projectViewItem->projectItem()
	                                                && projectViewItem->projectItem()->project()) {
		isKilePrFile = projectViewItem->projectItem()->project()->url() == projectViewItem->url();
	}

	if(projectViewItem->type() == KileType::ProjectExtra && !isKilePrFile) {
		QMenu *servicesMenu = popup.addMenu(QIcon::fromTheme("fork"), i18n("&Open With"));
		connect(&serviceSignalMapper, SIGNAL(mapped(int)), this, SLOT(slotRun(int)));
QMimeDatabase db;
		m_offerList = KMimeTypeTrader::self()->query(db.mimeTypeForUrl(projectViewItem->url()).name(), "Application");
		for (int i = 0; i < m_offerList.count(); ++i) {
			action = new QAction(servicesMenu);
			action->setIcon(QIcon::fromTheme(m_offerList[i]->icon()));
			action->setText(m_offerList[i]->name());
			connect(action, SIGNAL(triggered()), &serviceSignalMapper, SLOT(map()));
			serviceSignalMapper.setMapping(action, i + 1);
			servicesMenu->addAction(action);
		}

		servicesMenu->addSeparator();
		action = servicesMenu->addAction(i18n("Other..."), &serviceSignalMapper, SLOT(map()));
		serviceSignalMapper.setMapping(action, 0);
		insertsep = true;
	}
Beispiel #14
0
bool DropHandler::handleURL(const QList<QUrl>& urls_) {
  bool hasUnknown = false;
  QList<QUrl> tc, pdf, bib, ris, ciw;
  foreach(const QUrl& url, urls_) {
    QMimeType ptr;
    // findByURL doesn't work for http, so actually query
    // the url itself
    if(url.scheme() != QLatin1String("http")) {
      QMimeDatabase db;
      ptr = db.mimeTypeForUrl(url);
    } else {
      KIO::MimetypeJob* job = KIO::mimetype(url, KIO::HideProgressInfo);
      KJobWidgets::setWindow(job, GUI::Proxy::widget());
      job->exec();
      QMimeDatabase db;
      ptr = db.mimeTypeForName(job->mimetype());
    }
    if(ptr.inherits(QLatin1String("application/x-tellico"))) {
      tc << url;
    } else if(ptr.inherits(QLatin1String("application/pdf"))) {
      pdf << url;
    } else if(ptr.inherits(QLatin1String("text/x-bibtex")) ||
              ptr.inherits(QLatin1String("application/x-bibtex")) ||
              ptr.inherits(QLatin1String("application/bibtex"))) {
      bib << url;
    } else if(ptr.inherits(QLatin1String("application/x-research-info-systems"))) {
      ris << url;
    } else if(url.fileName().endsWith(QLatin1String(".bib"))) {
      bib << url;
    } else if(url.fileName().endsWith(QLatin1String(".ris"))) {
      ris << url;
    } else if(url.fileName().endsWith(QLatin1String(".ciw"))) {
      ciw << url;
    } else if(ptr.inherits(QLatin1String("text/plain")) && Import::BibtexImporter::maybeBibtex(url)) {
      bib << url;
    } else if(ptr.inherits(QLatin1String("text/plain")) && Import::RISImporter::maybeRIS(url)) {
      ris << url;
    } else if(ptr.inherits(QLatin1String("text/plain")) && Import::CIWImporter::maybeCIW(url)) {
      ciw << url;
    } else {
      myDebug() << "unrecognized type: " << ptr.name() << " (" << url << ")";
      hasUnknown = true;
    }
  }
Beispiel #15
0
/*!
  \brief Returns id of the default program that is capable to open given \a url.
*/
QString QDefaultProgram::defaultProgram(const QUrl &url)
{
    QMimeDatabase db;
    QMimeType mimeType = db.mimeTypeForUrl(url);

//    if (!mimeType.isValid())
//        return;

//    QMimeType mt = mimeType;
//    while (mt.isValid()) {
//        qDebug() << mt.name();
//        qDebug() << QDefaultProgram::defaultProgram(mt.name());
//        if (mt.parentMimeTypes().isEmpty())
//            break;
//        mt = db.mimeTypeForName(mt.parentMimeTypes().first());
//    }

    return defaultProgram(mimeType.name());
}
Beispiel #16
0
void GDMPForm::addPair(const QString& name,
                       const QString& description,
                       const QString& path,
                       const QString& id)
{
    QMimeDatabase db;
    QMimeType ptr = db.mimeTypeForUrl(QUrl::fromLocalFile(path));
    QString mime  = ptr.name();
    qCDebug(DIGIKAM_WEBSERVICES_LOG) << "in add pair:"
                                 << name << " "
                                 << description
                                 << " " << path
                                 << " " << id
                                 << " " << mime;

    // Generate JSON
    QJsonObject photoInfo;
    photoInfo.insert(QLatin1String("title"),       QJsonValue(name));
    photoInfo.insert(QLatin1String("description"), QJsonValue(description));
    photoInfo.insert(QLatin1String("mimeType"),    QJsonValue(mime));

    QVariantMap parentId;
    parentId.insert(QLatin1String("id"), id);
    QVariantList parents;
    parents << parentId;
    photoInfo.insert(QLatin1String("parents"),     QJsonValue(QJsonArray::fromVariantList(parents)));

    QJsonDocument doc(photoInfo);
    QByteArray json = doc.toJson();

    // Append to the multipart
    QByteArray str;
    str += "--";
    str += m_boundary;
    str += "\r\n";
    str += "Content-Type:application/json; charset=UTF-8\r\n\r\n";
    str += json;
    str += "\r\n";
    m_buffer.append(str);
}
Beispiel #17
0
void TwitterMicroBlog::createPostWithAttachment(Choqok::Account *theAccount, Choqok::Post *post,
        const QString &mediumToAttach)
{
    if (mediumToAttach.isEmpty()) {
        TwitterApiMicroBlog::createPost(theAccount, post);
    } else {
        const QUrl picUrl = QUrl::fromUserInput(mediumToAttach);
        KIO::StoredTransferJob *picJob = KIO::storedGet(picUrl, KIO::Reload, KIO::HideProgressInfo);
        picJob->exec();
        if (picJob->error()) {
            qCCritical(CHOQOK) << "Job error:" << picJob->errorString();
            KMessageBox::detailedError(Choqok::UI::Global::mainWindow(),
                                       i18n("Uploading medium failed: cannot read the medium file."),
                                       picJob->errorString());
            return;
        }
        const QByteArray picData = picJob->data();
        if (picData.count() == 0) {
            qCCritical(CHOQOK) << "Cannot read the media file, please check if it exists.";
            KMessageBox::error(Choqok::UI::Global::mainWindow(),
                               i18n("Uploading medium failed: cannot read the medium file."));
            return;
        }

        TwitterAccount *account = qobject_cast<TwitterAccount *>(theAccount);
        QUrl url = account->uploadUrl();
        url.setPath(url.path() + QStringLiteral("/statuses/update_with_media.%1").arg(format));
        const QMimeDatabase db;
        QByteArray fileContentType = db.mimeTypeForUrl(picUrl).name().toUtf8();

        QMap<QString, QByteArray> formdata;
        formdata[QLatin1String("status")] = post->content.toUtf8();
        if (!post->replyToPostId.isEmpty()) {
            formdata[QLatin1String("in_reply_to_status_id")] = post->replyToPostId.toLatin1();
        }
        formdata[QLatin1String("source")] = QCoreApplication::applicationName().toLatin1();

        QMap<QString, QByteArray> mediafile;
        mediafile[QLatin1String("name")] = "media[]";
        mediafile[QLatin1String("filename")] = picUrl.fileName().toUtf8();
        mediafile[QLatin1String("mediumType")] = fileContentType;
        mediafile[QLatin1String("medium")] = picData;
        QList< QMap<QString, QByteArray> > listMediafiles;
        listMediafiles.append(mediafile);

        QByteArray data = Choqok::MediaManager::createMultipartFormData(formdata, listMediafiles);

        KIO::StoredTransferJob *job = KIO::storedHttpPost(data, url, KIO::HideProgressInfo) ;
        if (!job) {
            qCCritical(CHOQOK) << "Cannot create a http POST request!";
            return;
        }
        job->addMetaData(QStringLiteral("content-type"),
                         QStringLiteral("Content-Type: multipart/form-data; boundary=AaB03x"));
        job->addMetaData(QStringLiteral("customHTTPHeader"),
                         QStringLiteral("Authorization: ") +
                         QLatin1String(authorizationHeader(account, url, QOAuth::POST)));
        mCreatePostMap[ job ] = post;
        mJobsAccount[job] = theAccount;
        connect(job, SIGNAL(result(KJob*)),
                SLOT(slotCreatePost(KJob*)));
        job->start();
    }
}
Beispiel #18
0
void TestBuddies::testDUChainBuddy()
{
    enableBuddies();
    enableOpenAfterCurrent();

    QTemporaryDir dirA;

    TestFile header("void myfunction();\n", "h", nullptr, dirA.path());
    TestFile other("void otherfunction() {}\n", "cpp", nullptr, dirA.path());
    TestFile source(
        QString("#include \"%1\"\nvoid myfunction() {}\n").arg(header.url().toUrl().fileName()),
        "cpp", nullptr, dirA.path()
    );

    header.parseAndWait();
    other.parseAndWait();
    source.parseAndWait();

    // Test IBuddyDocumentFinder::getPotentialBuddies()
    QMimeDatabase db;
    IBuddyDocumentFinder* sourceBuddyFinder = IBuddyDocumentFinder::finderForMimeType(db.mimeTypeForUrl(source.url().toUrl()).name());
    QVector< QUrl > sourceBuddies = sourceBuddyFinder->getPotentialBuddies(source.url().toUrl());
    if (!sourceBuddies.contains(header.url().toUrl())) {
        qDebug() << "got source buddies: " << sourceBuddies;
        qDebug() << "expected: " << header.url().toUrl();
        QFAIL("Failed to find buddy for source file");
    }
    QVERIFY2(!sourceBuddies.contains(other.url().toUrl()), "source buddy list contains unrelated file");

    IBuddyDocumentFinder* headerBuddyFinder = IBuddyDocumentFinder::finderForMimeType(db.mimeTypeForUrl(header.url().toUrl()).name());
    QVector< QUrl > headerBuddies = headerBuddyFinder->getPotentialBuddies(header.url().toUrl());
    if (!headerBuddies.contains(source.url().toUrl())) {
        qDebug() << "got header buddies: " << headerBuddies;
        qDebug() << "expected: " << source.url().toUrl();
        QFAIL("Failed to find buddy for header file");
    }
    QVERIFY2(!headerBuddies.contains(other.url().toUrl()), "header buddy list contains unrelated file");

    // Test IBuddyDocumentFinder::areBuddies()
    QVERIFY(sourceBuddyFinder->areBuddies(source.url().toUrl(), header.url().toUrl()));
}
Beispiel #19
0
void TestBuddies::testDUChainBuddyVote()
{
    /*
     * Test that the DUChain buddy system finds the buddy file with the most
     * common declarations/definitions
     */

    enableBuddies();
    enableOpenAfterCurrent();

    QTemporaryDir dirA;

    TestFile header("void func1();\nvoid func2();\nvoid func3();\n", "h", nullptr, dirA.path());
    TestFile source1(
        QString("#include \"%1\"\nvoid func1() {}\n").arg(header.url().toUrl().fileName()),
        "cpp", nullptr, dirA.path()
    );
    TestFile source2(
        QString("#include \"%1\"\nvoid func2() {}\nvoid func3() {}\n").arg(header.url().toUrl().fileName()),
        "cpp", nullptr, dirA.path()
    );

    // -> buddy(header) should resolve to source2

    header.parseAndWait();
    source1.parseAndWait();
    source2.parseAndWait();

    // Test IBuddyDocumentFinder::getPotentialBuddies()
    QMimeDatabase db;
    IBuddyDocumentFinder* sourceBuddyFinder = IBuddyDocumentFinder::finderForMimeType(db.mimeTypeForUrl(source1.url().toUrl()).name());
    QVector< QUrl > sourceBuddies = sourceBuddyFinder->getPotentialBuddies(source1.url().toUrl());
    if (!sourceBuddies.contains(header.url().toUrl())) {
        qDebug() << "got source buddies: " << sourceBuddies;
        qDebug() << "expected: " << header.url().toUrl();
        QFAIL("Failed to find buddy for source file");
    }

    IBuddyDocumentFinder* source2BuddyFinder = IBuddyDocumentFinder::finderForMimeType(db.mimeTypeForUrl(source2.url().toUrl()).name());
    QVector< QUrl > source2Buddies = source2BuddyFinder->getPotentialBuddies(source2.url().toUrl());
    if (!source2Buddies.contains(header.url().toUrl())) {
        qDebug() << "got source2 buddies: " << source2Buddies;
        qDebug() << "expected: " << header.url().toUrl();
        QFAIL("Failed to find buddy for source2 file");
    }

    IBuddyDocumentFinder* headerBuddyFinder = IBuddyDocumentFinder::finderForMimeType(db.mimeTypeForUrl(header.url().toUrl()).name());
    QVector< QUrl > headerBuddies = headerBuddyFinder->getPotentialBuddies(header.url().toUrl());
    if (!headerBuddies.contains(source2.url().toUrl())) {
        qDebug() << "got header buddies: " << headerBuddies;
        qDebug() << "expected: " << source2.url().toUrl();
        QFAIL("Failed to find buddy for header file");
    }
    QVERIFY2(!headerBuddies.contains(source1.url().toUrl()), "header buddy list contains weaker file");
}
Beispiel #20
0
QString ImageshackTalker::mimeType(const QString& path)
{
    QMimeDatabase db;
    QMimeType ptr = db.mimeTypeForUrl(QUrl::fromLocalFile(path));
    return ptr.name();
}
Beispiel #21
0
void KRSearchMod::scanLocalDir(QUrl urlToScan)
{
    QString dir = vfs::ensureTrailingSlash(urlToScan).path();

    QT_DIR* d = QT_OPENDIR(dir.toLocal8Bit());
    if (!d) return ;

    QT_DIRENT* dirEnt;

    while ((dirEnt = QT_READDIR(d)) != NULL) {
        QString name = QString::fromLocal8Bit(dirEnt->d_name);

        // we don't scan the ".",".." enteries
        if (name == "." || name == "..") continue;

        QT_STATBUF stat_p;
        QT_LSTAT((dir + name).toLocal8Bit(), &stat_p);

        QUrl url = QUrl::fromLocalFile(dir + name);

        QString mime;
        if (query->searchInArchives() || !query->hasMimeType()) {
            QMimeDatabase db;
            QMimeType mt = db.mimeTypeForUrl(url);
            if (mt.isValid())
                mime = mt.name();
        }

        // creating a vfile object for matching with krquery
        vfile * vf = new vfile(name, (KIO::filesize_t)stat_p.st_size, KRpermHandler::mode2QString(stat_p.st_mode),
                               stat_p.st_mtime, S_ISLNK(stat_p.st_mode), false/*FIXME*/, stat_p.st_uid, stat_p.st_gid,
                               mime, "", stat_p.st_mode, -1, url);

        if (query->isRecursive()) {
            if (S_ISLNK(stat_p.st_mode) && query->followLinks())
                unScannedUrls.push(QUrl::fromLocalFile(QDir(dir + name).canonicalPath()));
            else if (S_ISDIR(stat_p.st_mode))
                unScannedUrls.push(url);
        }
        if (query->searchInArchives()) {
            if (KRarcHandler::arcSupported(mime)) {
                QUrl archiveURL = url;
                bool encrypted;
                QString realType = arcHandler.getType(encrypted, url.path(), mime);

                if (!encrypted) {
                    if (realType == "tbz" || realType == "tgz" || realType == "tarz" || realType == "tar" || realType == "tlz")
                        archiveURL.setScheme("tar");
                    else
                        archiveURL.setScheme("krarc");

                    unScannedUrls.push(archiveURL);
                }
            }
        }

        if (query->match(vf)) {
            // if we got here - we got a winner
            results.append(dir + name);
            emit found(name, dir, (KIO::filesize_t) stat_p.st_size, stat_p.st_mtime,
                       KRpermHandler::mode2QString(stat_p.st_mode), stat_p.st_uid, stat_p.st_gid, query->foundText());
        }
        delete vf;

        if (timer.elapsed() >= EVENT_PROCESS_DELAY) {
            qApp->processEvents();
            timer.start();
            if (stopSearch) return;
        }
    }
    // clean up
    QT_CLOSEDIR(d);
}
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;
}
Beispiel #23
0
bool ThumbnailProtocol::createSubThumbnail(QImage& thumbnail, const QString& filePath,
                                           int segmentWidth, int segmentHeight)
{
    if (m_enabledPlugins.isEmpty()) {
        const KConfigGroup globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
        m_enabledPlugins = globalConfig.readEntry("Plugins", QStringList()
                                                             << "imagethumbnail"
                                                             << "jpegthumbnail"
                                                             << "videopreview");
    }

    const QMimeDatabase db;
    const QUrl fileUrl = QUrl::fromLocalFile(filePath);
    const QString subPlugin = pluginForMimeType(db.mimeTypeForUrl(fileUrl).name());
    if (subPlugin.isEmpty() || !m_enabledPlugins.contains(subPlugin)) {
        return false;
    }

    ThumbCreator* subCreator = getThumbCreator(subPlugin);
    if (!subCreator) {
        // qDebug() << "found no creator for" << dir.filePath();
        return false;
    }

    if ((segmentWidth <= 256) && (segmentHeight <= 256)) {
        // check whether a cached version of the file is available for
        // 128 x 128 or 256 x 256 pixels
        int cacheSize = 0;
        QCryptographicHash md5(QCryptographicHash::Md5);
        md5.addData(QFile::encodeName(fileUrl.toString()));
        const QString thumbName = QFile::encodeName(md5.result().toHex()).append(".png");

        if (m_thumbBasePath.isEmpty()) {
            m_thumbBasePath = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QLatin1String("/thumbnails/");
            QDir basePath(m_thumbBasePath);
            basePath.mkpath("normal/");
            QFile::setPermissions(basePath.absoluteFilePath("normal"), QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);
            basePath.mkpath("large/");
            QFile::setPermissions(basePath.absoluteFilePath("large"), QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);
        }

        QDir thumbPath(m_thumbBasePath);
        if ((segmentWidth <= 128) && (segmentHeight <= 128)) {
            cacheSize = 128;
            thumbPath.cd("normal");
        } else {
            cacheSize = 256;
            thumbPath.cd("large");
        }
        if (!thumbnail.load(thumbPath.absoluteFilePath(thumbName))) {
            // no cached version is available, a new thumbnail must be created

            QSaveFile thumbnailfile(thumbPath.absoluteFilePath(thumbName));
            bool savedCorrectly = false;
            if (subCreator->create(filePath, cacheSize, cacheSize, thumbnail)) {
                scaleDownImage(thumbnail, cacheSize, cacheSize);

                // The thumbnail has been created successfully. Store the thumbnail
                // to the cache for future access.
                if (thumbnailfile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
                    savedCorrectly = thumbnail.save(&thumbnailfile, "PNG");
                }
            } else {
                return false;
            }
            if(savedCorrectly)
            {
                thumbnailfile.commit();
            }
        }
    } else if (!subCreator->create(filePath, segmentWidth, segmentHeight, thumbnail)) {
        return false;
    }
    return true;
}
Beispiel #24
0
void ThumbnailProtocol::get(const QUrl &url)
{
    m_mimeType = metaData("mimeType");
    //qDebug() << "Wanting MIME Type:" << m_mimeType;
#ifdef THUMBNAIL_HACK
    // ### HACK
    bool direct=false;
    if (m_mimeType.isEmpty()) {
        QFileInfo info(url.path());
        //qDebug() << "PATH: " << url.path() << "isDir:" << info.isDir();
        if (!info.exists()) {
            // The file does not exist
            error(KIO::ERR_DOES_NOT_EXIST,url.path());
            return;
        } else if (!info.isReadable()) {
            // The file is not readable!
            error(KIO::ERR_COULD_NOT_READ,url.path());
            return;
        }

        if (info.isDir()) {
            m_mimeType = "inode/directory";
        } else {
            const QMimeDatabase db;

            m_mimeType = db.mimeTypeForUrl(QUrl(info.filePath())).name();
        }

        //qDebug() << "Guessing MIME Type:" << m_mimeType;
        direct=true; // thumbnail: URL was probably typed in Konqueror
    }
#endif

    if (m_mimeType.isEmpty()) {
        error(KIO::ERR_INTERNAL, i18n("No MIME Type specified."));
        return;
    }

    m_width = metaData("width").toInt();
    m_height = metaData("height").toInt();
    int iconSize = metaData("iconSize").toInt();

    if (m_width < 0 || m_height < 0) {
        error(KIO::ERR_INTERNAL, i18n("No or invalid size specified."));
        return;
    }
#ifdef THUMBNAIL_HACK
    else if (!m_width || !m_height) {
        //qDebug() << "Guessing height, width, icon size!";
        m_width = 128;
        m_height = 128;
        iconSize = 128;
    }
#endif

    if (!iconSize) {
        iconSize = KIconLoader::global()->currentSize(KIconLoader::Desktop);
    }
    if (iconSize != m_iconSize) {
        m_iconDict.clear();
    }
    m_iconSize = iconSize;

    m_iconAlpha = metaData("iconAlpha").toInt();

    QImage img;

    KConfigGroup group( KSharedConfig::openConfig(), "PreviewSettings" );
    bool kfmiThumb = false; // TODO Figure out if we can use KFileMetadata as a last resource

    ThumbCreator::Flags flags = ThumbCreator::None;

    if (!kfmiThumb) {
        QString plugin = metaData("plugin");
        if ((plugin.isEmpty() || plugin == "directorythumbnail") && m_mimeType == "inode/directory") {
            img = thumbForDirectory(url);
            if(img.isNull()) {
              error(KIO::ERR_INTERNAL, i18n("Cannot create thumbnail for directory"));
              return;
            }
        } else {
#ifdef THUMBNAIL_HACK
            if (plugin.isEmpty()) {
                plugin = pluginForMimeType(m_mimeType);
            }

            //qDebug() << "Guess plugin: " << plugin;
#endif
            if (plugin.isEmpty()) {
                error(KIO::ERR_INTERNAL, i18n("No plugin specified."));
                return;
            }

            ThumbCreator* creator = getThumbCreator(plugin);
            if(!creator) {
                error(KIO::ERR_INTERNAL, i18n("Cannot load ThumbCreator %1", plugin));
                return;
            }

            ThumbSequenceCreator* sequenceCreator = dynamic_cast<ThumbSequenceCreator*>(creator);
            if(sequenceCreator)
                sequenceCreator->setSequenceIndex(sequenceIndex());

            if (!creator->create(url.path(), m_width, m_height, img)) {
                error(KIO::ERR_INTERNAL, i18n("Cannot create thumbnail for %1", url.path()));
                return;
            }
            flags = creator->flags();
        }
    }

    scaleDownImage(img, m_width, m_height);

    if (flags & ThumbCreator::DrawFrame) {
        int x2 = img.width() - 1;
        int y2 = img.height() - 1;
        // paint a black rectangle around the "page"
        QPainter p;
        p.begin( &img );
        p.setPen( QColor( 48, 48, 48 ));
        p.drawLine( x2, 0, x2, y2 );
        p.drawLine( 0, y2, x2, y2 );
        p.setPen( QColor( 215, 215, 215 ));
        p.drawLine( 0, 0, x2, 0 );
        p.drawLine( 0, 0, 0, y2 );
        p.end();
    }

    if ((flags & ThumbCreator::BlendIcon) && KIconLoader::global()->alphaBlending(KIconLoader::Desktop)) {
        // blending the mimetype icon in
        QImage icon = getIcon();

        int x = img.width() - icon.width() - 4;
        x = qMax( x, 0 );
        int y = img.height() - icon.height() - 6;
        y = qMax( y, 0 );
        QPainter p(&img);
        p.setOpacity(m_iconAlpha/255.0);
        p.drawImage(x, y, icon);
    }

    if (img.isNull()) {
        error(KIO::ERR_INTERNAL, i18n("Failed to create a thumbnail."));
        return;
    }

    const QString shmid = metaData("shmid");
    if (shmid.isEmpty()) {
#ifdef THUMBNAIL_HACK
        if (direct) {
            // If thumbnail was called directly from Konqueror, then the image needs to be raw
            //qDebug() << "RAW IMAGE TO STREAM";
            QBuffer buf;
            if (!buf.open(QIODevice::WriteOnly)) {
                error(KIO::ERR_INTERNAL, i18n("Could not write image."));
                return;
            }
            img.save(&buf,"PNG");
            buf.close();
            mimeType("image/png");
            data(buf.buffer());
        }
        else
#endif
        {
            QByteArray imgData;
            QDataStream stream( &imgData, QIODevice::WriteOnly );
            //qDebug() << "IMAGE TO STREAM";
            stream << img;
            mimeType("application/octet-stream");
            data(imgData);
        }
    } else {
#ifndef Q_OS_WIN
        QByteArray imgData;
        QDataStream stream( &imgData, QIODevice::WriteOnly );
        //qDebug() << "IMAGE TO SHMID";
        void *shmaddr = shmat(shmid.toInt(), 0, 0);
        if (shmaddr == (void *)-1) {
            error(KIO::ERR_INTERNAL, i18n("Failed to attach to shared memory segment %1", shmid));
            return;
        }
        if (img.width() * img.height() > m_width * m_height) {
            error(KIO::ERR_INTERNAL, i18n("Image is too big for the shared memory segment"));
            shmdt((char*)shmaddr);
            return;
        }
        if( img.format() != QImage::Format_ARGB32 ) { // KIO::PreviewJob and this code below completely ignores colortable :-/,
            img = img.convertToFormat(QImage::Format_ARGB32); //  so make sure there is none
        }
        // Keep in sync with kdelibs/kio/kio/previewjob.cpp
        stream << img.width() << img.height() << quint8(img.format());
        memcpy(shmaddr, img.bits(), img.byteCount());
        shmdt((char*)shmaddr);
        mimeType("application/octet-stream");
        data(imgData);
#endif
    }
    finished();
}
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
}