Exemple #1
0
KService::Ptr ArkViewer::getViewer(const QString &mimeType)
{
    // No point in even trying to find anything for application/octet-stream
    if (mimeType == QStringLiteral("application/octet-stream")) {
        return KService::Ptr();
    }

    // Try to get a read-only kpart for the internal viewer
    KService::List offers = KMimeTypeTrader::self()->query(mimeType, QStringLiteral("KParts/ReadOnlyPart"));

    auto arkPartIt = std::find_if(offers.begin(), offers.end(), [](KService::Ptr service) {
        return service->storageId() == QLatin1String("ark_part.desktop");
    });

    // Use the Ark part only when the mime type matches an archive type directly.
    // Many file types (e.g. Open Document) are technically just archives
    // but browsing their internals is typically not what the user wants.
    if (arkPartIt != offers.end()) {
        // Not using hasMimeType() as we're explicitly not interested in inheritance.
        if (!(*arkPartIt)->mimeTypes().contains(mimeType)) {
            offers.erase(arkPartIt);
        }
    }

    // If we can't find a kpart, try to get an external application
    if (offers.isEmpty()) {
        offers = KMimeTypeTrader::self()->query(mimeType, QStringLiteral("Application"));
    }

    if (!offers.isEmpty()) {
        return offers.first();
    } else {
        return KService::Ptr();
    }
}
void KonqPopupMenuPrivate::addPlugins()
{
    QString commonMimeType = m_popupItemProperties.mimeType();
    if (commonMimeType.isEmpty()) {
        commonMimeType = QLatin1String("application/octet-stream");
    }
    const KService::List konqPlugins = KMimeTypeTrader::self()->query(commonMimeType, "KonqPopupMenu/Plugin", "exist Library");

    if (!konqPlugins.isEmpty()) {
        m_popupMenuInfo.setItemListProperties(m_popupItemProperties);
        m_popupMenuInfo.setParentWidget(m_parentWidget);
        KService::List::ConstIterator iterator = konqPlugins.begin();
        const KService::List::ConstIterator end = konqPlugins.end();
        for(; iterator != end; ++iterator) {
            //kDebug() << (*iterator)->name() << (*iterator)->library();
            KonqPopupMenuPlugin *plugin = (*iterator)->createInstance<KonqPopupMenuPlugin>(q);
            if (!plugin)
                continue;
            plugin->setParent(q);
            plugin->setup(&m_ownActionCollection, m_popupMenuInfo, q);
        }
    }

    const KService::List fileItemPlugins = KMimeTypeTrader::self()->query(commonMimeType, "KFileItemAction/Plugin", "exist Library");
    if (!fileItemPlugins.isEmpty()) {
        const KConfig config("kservicemenurc", KConfig::NoGlobals);
        const KConfigGroup showGroup = config.group("Show");

        foreach (const KSharedPtr<KService>& service, fileItemPlugins) {
            if (!showGroup.readEntry(service->desktopEntryName(), true)) {
                // The plugin has been disabled
                continue;
            }

            // Old API (kdelibs-4.6.0 only)
            KFileItemActionPlugin* plugin = service->createInstance<KFileItemActionPlugin>();
            if (plugin) {
                plugin->setParent(q);
                q->addActions(plugin->actions(m_popupItemProperties, m_parentWidget));
            }
            // New API (kdelibs >= 4.6.1)
            KAbstractFileItemActionPlugin* abstractPlugin = service->createInstance<KAbstractFileItemActionPlugin>();
            if (abstractPlugin) {
                abstractPlugin->setParent(q);
                q->addActions(abstractPlugin->actions(m_popupItemProperties, m_parentWidget));
            }
        }
    }
}
void ServiceRunner::match(Plasma::RunnerContext &context)
{
    const QString term = context.query();
    if (term.length() <  3) {
        return;
    }

    // Search for applications which are executable and case-insensitively match the search term
    // See http://techbase.kde.org/Development/Tutorials/Services/Traders#The_KTrader_Query_Language
    // if the following is unclear to you.
    QString query = QString("exist Exec and ('%1' =~ Name)").arg(term);
    KService::List services = KServiceTypeTrader::self()->query("Application", query);

    QList<Plasma::QueryMatch> matches;

    QSet<QString> seen;
    if (!services.isEmpty()) {
        //kDebug() << service->name() << "is an exact match!" << service->storageId() << service->exec();
        foreach (const KService::Ptr &service, services) {
            if (!service->noDisplay() && service->property("NotShowIn", QVariant::String) != "KDE") {
                Plasma::QueryMatch match(this);
                match.setType(Plasma::QueryMatch::ExactMatch);
                setupMatch(service, match);
                match.setRelevance(1);
                matches << match;
                seen.insert(service->storageId());
                seen.insert(service->exec());
            }
        }
    }
bool
EngineController::installDistroCodec()
{
    KService::List services = KServiceTypeTrader::self()->query( "Amarok/CodecInstall"
        , QString( "[X-KDE-Amarok-codec] == 'mp3' and [X-KDE-Amarok-engine] == 'phonon-%1'").arg( "xine" ) );
    //todo - figure out how to query Phonon for the current backend loaded
    if( !services.isEmpty() )
    {
        KService::Ptr service = services.first(); //list is not empty
        QString installScript = service->exec();
        if( !installScript.isNull() ) //just a sanity check
        {
            KGuiItem installButton( i18n( "Install MP3 Support" ) );
            if(KMessageBox::questionYesNo( The::mainWindow()
            , i18n("Amarok currently cannot play MP3 files. Do you want to install support for MP3?")
            , i18n( "No MP3 Support" )
            , installButton
            , KStandardGuiItem::no()
            , "codecInstallWarning" ) == KMessageBox::Yes )
            {
                    KRun::runCommand(installScript, 0);
                    return true;
            }
        }
    }

    return false;
}
TubeChannelApprover::TubeChannelApprover(const Tp::TubeChannelPtr& channel, QObject* parent):
    ChannelApprover(0),
    m_channel(channel)
{
    Q_UNUSED(parent);

    qCDebug(APPROVER) << "Incoming tube channel";
    qCDebug(APPROVER) << "\tTube Type:" << channel->channelType();

    connect(m_channel.data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)), SLOT(onChannelInvalidated()));

    QString serviceName;
    if (Tp::StreamTubeChannelPtr streamTube = Tp::StreamTubeChannelPtr::dynamicCast(channel)) {
        qCDebug(APPROVER) << "\tService:" << streamTube->service();
        serviceName = streamTube->service();
    } else if (Tp::DBusTubeChannelPtr dbusTube = Tp::DBusTubeChannelPtr::dynamicCast(channel)) {
        qCDebug(APPROVER) << "\tService name:" << dbusTube->serviceName();
        serviceName = dbusTube->serviceName();
    }

    KService::List services = KServiceTypeTrader::self()->query(QLatin1String("KTpApprover"));
    qCDebug(APPROVER) << "Found" << services.count() << "KTpApprover services";
    if (!services.isEmpty()) {
        Q_FOREACH(const KService::Ptr &service, services) {
            if ((service->property(QLatin1String("X-KTp-ChannelType")) != channel->channelType()) ||
                (service->property(QLatin1String("X-KTp-Service")) != serviceName)) {

                continue;
            }
            m_service = service;
        }
    }
void KonqPopupMenuPrivate::addPlugins()
{
    QString commonMimeType = m_popupItemProperties.mimeType();
    if (commonMimeType.isEmpty()) {
        commonMimeType = QLatin1String("application/octet-stream");
    }

    const KService::List fileItemPlugins = KMimeTypeTrader::self()->query(commonMimeType, QStringLiteral("KFileItemAction/Plugin"), QStringLiteral("exist Library"));
    if (!fileItemPlugins.isEmpty()) {
        const KConfig config(QStringLiteral("kservicemenurc"), KConfig::NoGlobals);
        const KConfigGroup showGroup = config.group("Show");

        foreach (const auto &service, fileItemPlugins) {
            if (!showGroup.readEntry(service->desktopEntryName(), true)) {
                // The plugin has been disabled
                continue;
            }

            KAbstractFileItemActionPlugin *abstractPlugin = service->createInstance<KAbstractFileItemActionPlugin>();
            if (abstractPlugin) {
                abstractPlugin->setParent(q);
                q->addActions(abstractPlugin->actions(m_popupItemProperties, m_parentWidget));
            }
        }
    }
}
TestDataEngineBlackBox::TestDataEngineBlackBox(QString identifier)
{
    Plasma::DataEngine* engine = 0;
    // load the engine, add it to the engines
    QString constraint = QString("[X-KDE-PluginInfo-Name] == '" + identifier + '\'').arg(identifier);
    KService::List offers = KServiceTypeTrader::self()->query("Plasma/DataEngine", constraint);
    QString error;

    if (!offers.isEmpty()) {
        QVariantList allArgs;
        allArgs << offers.first()->storageId();
        QString api = offers.first()->property("X-Plasma-API").toString();
        if (api.isEmpty()) {
            if (offers.first()) {
                KPluginLoader plugin(*offers.first());
                if (Plasma::isPluginVersionCompatible(plugin.pluginVersion())) {
                   engine = offers.first()->createInstance<Plasma::DataEngine>(0, allArgs, &error);
               }
            }
        } else {
            engine = new Plasma::DataEngine(0, offers.first());
        }
    }
    
    m_engine = engine;
}
Exemple #8
0
bool DocumentationViewer::urlSelected(const QString &url, int button, int state, const QString &_target, const KParts::OpenUrlArguments &args, const KParts::BrowserArguments & /* browserArgs */)
{
	KUrl cURL = completeURL(url);
	QString mime = KMimeType::findByUrl(cURL).data()->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(( mime == KMimeType::defaultMimeType() ) || (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;
		}
		KUrl::List lst;
		lst.append(cURL);
		KRun::run(*(offers.first()), lst, view());
	}
	return true;
}
KParts::Factory* IPartController::findPartFactory ( const QString& mimetype, const QString& parttype, const QString& preferredName )
{
    // parttype may be a interface type not derived from KParts/ReadOnlyPart
    const KService::List offers = KMimeTypeTrader::self()->query( mimetype,
                                        QString::fromLatin1( "KParts/ReadOnlyPart" ),
                                        QString::fromLatin1( "'%1' in ServiceTypes" ).arg( parttype ) );
    if ( ! offers.isEmpty() )
    {
        KService::Ptr ptr;
        // if there is a preferred plugin we'll take it
        if ( !preferredName.isEmpty() )
        {
            KService::List::ConstIterator it;
            for ( it = offers.constBegin(); it != offers.constEnd(); ++it )
            {
                if ( ( *it ) ->desktopEntryName() == preferredName )
                {
                    ptr = ( *it );
                    break;
                }
            }
        }
        // else we just take the first in the list
        if ( !ptr )
        {
            ptr = offers.first();
        }
        KPluginLoader loader( QFile::encodeName( ptr->library() ) );
        return static_cast<KParts::Factory*>( loader.factory() );
    }
                                                                                                  
    return 0;
}
Exemple #10
0
void Handler::activateConnection(const QString& connection, const QString& device, const QString& specificObject)
{
    NetworkManager::Connection::Ptr con = NetworkManager::findConnection(connection);

    if (!con) {
        qCWarning(NM) << "Not possible to activate this connection";
        return;
    }

    if (con->settings()->connectionType() == NetworkManager::ConnectionSettings::Vpn) {
        NetworkManager::VpnSetting::Ptr vpnSetting = con->settings()->setting(NetworkManager::Setting::Vpn).staticCast<NetworkManager::VpnSetting>();
        if (vpnSetting) {
//            qCDebug(NM) << "Checking VPN" << con->name() << "type:" << vpnSetting->serviceType();
#if 0
            // get the list of supported VPN service types
            const KService::List services = KServiceTypeTrader::self()->query("PlasmaNetworkManagement/VpnUiPlugin",
                                                                              QString::fromLatin1("[X-NetworkManager-Services]=='%1'").arg(vpnSetting->serviceType()));
            if (services.isEmpty()) {
                qCWarning(NM) << "VPN" << vpnSetting->serviceType() << "not found, skipping";
                KNotification *notification = new KNotification("MissingVpnPlugin", KNotification::CloseOnTimeout, this);
                notification->setComponentName("networkmanagement");
                notification->setTitle(con->name());
                notification->setText(i18n("Missing VPN plugin"));
                notification->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(KIconLoader::SizeHuge));
                notification->sendEvent();
                return;
            }
#endif
        }
    }

#if WITH_MODEMMANAGER_SUPPORT
    if (con->settings()->connectionType() == NetworkManager::ConnectionSettings::Gsm) {
        NetworkManager::ModemDevice::Ptr nmModemDevice = NetworkManager::findNetworkInterface(device).objectCast<NetworkManager::ModemDevice>();
        if (nmModemDevice) {
            ModemManager::ModemDevice::Ptr mmModemDevice = ModemManager::findModemDevice(nmModemDevice->udi());
            if (mmModemDevice) {
                ModemManager::Modem::Ptr modem = mmModemDevice->interface(ModemManager::ModemDevice::ModemInterface).objectCast<ModemManager::Modem>();
                NetworkManager::GsmSetting::Ptr gsmSetting = con->settings()->setting(NetworkManager::Setting::Gsm).staticCast<NetworkManager::GsmSetting>();
                if (gsmSetting && gsmSetting->pinFlags() == NetworkManager::Setting::NotSaved &&
                    modem && modem->unlockRequired() > MM_MODEM_LOCK_NONE) {
                    QDBusInterface managerIface("org.kde.plasmanetworkmanagement", "/org/kde/plasmanetworkmanagement", "org.kde.plasmanetworkmanagement", QDBusConnection::sessionBus(), this);
                    managerIface.call("unlockModem", mmModemDevice->uni());
                    connect(modem.data(), &ModemManager::Modem::unlockRequiredChanged, this, &Handler::unlockRequiredChanged);
                    m_tmpConnectionPath = connection;
                    m_tmpDevicePath = device;
                    m_tmpSpecificPath = specificObject;
                    return;
                }
            }
        }
    }
#endif

    QDBusPendingReply<QDBusObjectPath> reply = NetworkManager::activateConnection(connection, device, specificObject);
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
    watcher->setProperty("action", Handler::ActivateConnection);
    watcher->setProperty("connection", con->name());
    connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished);
}
Exemple #11
0
void Clock::launchDateKcm() //SLOT
{
    KService::List offers = KServiceTypeTrader::self()->query("KCModule", "Library == 'kcm_locale'");
    if (!offers.isEmpty()) {
        KService::Ptr service = offers.first();
        KRun::run(*service, KUrl::List(), 0);
    }
    update();
}
Exemple #12
0
QVariant ibanBicData::findPropertyByCountry(const QString& countryCode, const QString& property, const QVariant::Type type)
{
  const KService::List services = KServiceTypeTrader::self()->query("KMyMoney/IbanBicData",
                                  QString("'%1' ~in [X-KMyMoney-CountryCodes] and exist [%2]").arg(countryCode).arg(property)
                                                                   );
  if (!services.isEmpty())
    return services.first()->property(property, type);

  // Something went wrong
  return QVariant();
}
Exemple #13
0
bool PlacesModel::activityLinkingEnabled()
{
    const KService::List services = KServiceTypeTrader::self()->query(QStringLiteral("KFileItemAction/Plugin"),
        QStringLiteral("Library == 'kactivitymanagerd_fileitem_linking_plugin'"));

    if (services.isEmpty()) {
        return false;
    }

    return !services.at(0).data()->noDisplay();
}
Exemple #14
0
KFileWritePlugin*
KFileWriterProvider::loadPlugin(const QString& key) {
    //kDebug() << "loading writer for key " << key;
    const QString constraint = QString::fromLatin1("'%1' in MetaDataKeys")
        .arg(key);
    const KService::List offers = KServiceTypeTrader::self()->query(
        "KFileWrite", constraint);
    if (offers.isEmpty()) {
        return 0;
    }
    return offers.first()->createInstance<KFileWritePlugin>();
}
Exemple #15
0
void KJiebaRunner::match(Plasma::RunnerContext &context)
{
    const QString term = context.query();
    QList<Plasma::QueryMatch> matches;
    QSet<QString> seen;

    if (term.length() > 1) {
#if DEBUG
        qDebug() << "DEBUG:" << __PRETTY_FUNCTION__ << term;
#endif
        KService::List services = KServiceTypeTrader::self()->query("Application");
        services.erase(std::remove_if(services.begin(),
                                      services.end(),
                                      [=](QExplicitlySharedDataPointer<KService> it) {
            return it->exec().isEmpty() ||
                   (!kjiebaPtr->query(it->genericName()).contains(term)             &&
                    !kjiebaPtr->topinyin(it->genericName()).contains(term)          &&
                    !kjiebaPtr->topinyin(it->genericName(), false).contains(term)   &&
                    !kjiebaPtr->query(it->name()).contains(term)                    &&
                    !kjiebaPtr->topinyin(it->name()).contains(term)                 &&
                    !kjiebaPtr->topinyin(it->name(), false).contains(term));
        }), services.end());

		if (!services.isEmpty()) {
            Q_FOREACH (const KService::Ptr &service, services) {
                if (!service->noDisplay() &&
                    service->property(QStringLiteral("NotShowIn"), QVariant::String) != "KDE") {
                    Plasma::QueryMatch match(this);
                    match.setType(Plasma::QueryMatch::ExactMatch);

					const QString name = service->name();
#if DEBUG
                    qDebug() << "DEBUG:" << name;
#endif
                    match.setText(name);
                    match.setData(service->storageId());

                    if (!service->genericName().isEmpty() && service->genericName() != name)
                        match.setSubtext(service->genericName());
                    else if (!service->comment().isEmpty())
                        match.setSubtext(service->comment());
                   
                    if (!service->icon().isEmpty())
                        match.setIcon(QIcon::fromTheme(service->icon()));

                    match.setRelevance(1);
                    matches << match;
                    seen.insert(service->storageId());
                    seen.insert(service->exec());
                }
            }
        }
Exemple #16
0
/**
 * @warning At the moment the completion may fail if bicModel was created in more than one thread
 * (it uses a QSqlDatabase object over all instances of bicModel, so the first created bicModel defines
 * the thread)
 *
 * @todo Make thread safe.
 */
bicModel::bicModel(QObject* parent)
    : QSqlQueryModel(parent)
{

  QSqlDatabase db = QSqlDatabase::database("bicModel", true);
  // Save if the database was opened before
  bool attachDatabases = false;

  if (!db.isValid()) {
    db = QSqlDatabase::addDatabase("QSQLITE", "bicModel");
    db.setDatabaseName(":memory:");
    db.setConnectOptions("QSQLITE_OPEN_READONLY=1;QSQLITE_ENABLE_SHARED_CACHE=1;");
    db.open();
    // Database was not opened before
    attachDatabases = true;
  }

  if (!db.isOpen()) {
    qWarning() << QString("Could not open in-memory database for bic data.");
  }
  QSqlQuery query(db);

  // Get services which support iban2bic and have a database entry
  KService::List services = KServiceTypeTrader::self()->query("KMyMoney/IbanBicData",
                            QString("exist [X-KMyMoney-Bankdata-Database]")
                                                             );

  if (services.isEmpty()) {
    // Set a valid query
    query.exec("SELECT null;");
    setQuery(query);
    return;
  }

  QStringList databases;
  QStringList dbNames;

  unsigned int databaseCount = 0;

  foreach (KService::Ptr service, services) {
    QString database = service->property(QLatin1String("X-KMyMoney-Bankdata-Database")).toString();

    // Locate database
    QString path = QStandardPaths::locate(QStandardPaths::DataLocation, QLatin1String("kmymoney/ibanbicdata/") + database);
    if (path.isEmpty()) {
      qWarning() << QString("Could not locate database file \"%1\" to receive BIC data.").arg(database);
    } else {
      databases << path;
      dbNames << QString("db%1").arg(++databaseCount);
    }
  }
void Configuration::findApplication(const QString &query)
{
    for (int i = (m_findApplicationUi.resultsLayout->count() - 1); i >= 0; --i)
    {
        m_findApplicationUi.resultsLayout->takeAt(i)->widget()->deleteLater();
        m_findApplicationUi.resultsLayout->removeItem(m_findApplicationUi.resultsLayout->itemAt(i));
    }

    if (query.length() < 3)
    {
        m_findApplicationDialog->adjustSize();

        return;
    }

    KService::List services = KServiceTypeTrader::self()->query("Application", QString("exist Exec and ( (exist Keywords and '%1' ~subin Keywords) or (exist GenericName and '%1' ~~ GenericName) or (exist Name and '%1' ~~ Name) )").arg(query));

    if (!services.isEmpty())
    {
        foreach (const KService::Ptr &service, services)
        {
            if (!service->noDisplay() && service->property("NotShowIn", QVariant::String) != "KDE")
            {
                Launcher* launcher = new Launcher(KUrl(service->entryPath()), m_applet);

                QWidget* entryWidget = new QWidget(static_cast<QWidget*>(parent()));
                QLabel* iconLabel = new QLabel(entryWidget);
                QLabel* textLabel = new QLabel(QString("%1<br /><small>%3</small>").arg(launcher->title()).arg(launcher->description()), entryWidget);

                iconLabel->setPixmap(launcher->icon().pixmap(32, 32));

                textLabel->setFixedSize(240, 40);

                QHBoxLayout* entryWidgetLayout = new QHBoxLayout(entryWidget);
                entryWidgetLayout->addWidget(iconLabel);
                entryWidgetLayout->addWidget(textLabel);
                entryWidgetLayout->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);

                entryWidget->setToolTip(QString("<b>%1</b><br /><i>%2</i>").arg(launcher->title()).arg(launcher->description()));
                entryWidget->setLayout(entryWidgetLayout);
                entryWidget->setFixedSize(300, 40);
                entryWidget->setObjectName(service->entryPath());
                entryWidget->installEventFilter(this);
                entryWidget->setCursor(QCursor(Qt::PointingHandCursor));

                m_findApplicationUi.resultsLayout->addWidget(entryWidget);

                delete launcher;
            }
        }
    }
/**
 * @todo enable delegates again
 */
QAbstractItemDelegate* payeeIdentifierLoader::createItemDelegate(const QString& payeeIdentifierId, QObject* parent)
{
  /** @todo escape ' in  payeeIdentifierId */
  KService::List offers = KServiceTypeTrader::self()->query(QLatin1String("KMyMoney/PayeeIdentifierDelegate"), QString("'%1' ~in [X-KMyMoney-payeeIdentifierIds]").arg(payeeIdentifierId));
  if (!offers.isEmpty()) {
    QString error;
    QAbstractItemDelegate* ptr = offers.at(0)->createInstance<QAbstractItemDelegate>(parent, QVariantList(), &error);
    if (ptr == nullptr) {
      qWarning() << "could not load delegate" << error << payeeIdentifierId;
    }
    return ptr;
  }
  return nullptr;
}
Exemple #19
0
void FileOperation::openFilesWithDefaultApplication(const QList<QUrl>& urls, QWidget* const parentWidget)
{
    if (urls.isEmpty())
    {
        return;
    }

    // Create a map of service depending of type mimes to route and start only one instance of relevant application with all same type mime files.

    QMap<KService::Ptr, QList<QUrl>> servicesMap;

    foreach (const QUrl& url, urls)
    {
        const QString mimeType = QMimeDatabase().mimeTypeForFile(url.path(), QMimeDatabase::MatchExtension).name();
        KService::List offers  = KMimeTypeTrader::self()->query(mimeType, QLatin1String("Application"));

        if (offers.isEmpty())
        {
            return;
        }

        KService::Ptr ptr                                   = offers.first();
        QMap<KService::Ptr, QList<QUrl>>::const_iterator it = servicesMap.constFind(ptr);

        if (it != servicesMap.constEnd())
        {
            servicesMap[ptr] << url;
        }
        else
        {
            servicesMap.insert(ptr, QList<QUrl>() << url);
        }
    }

    for (QMap<KService::Ptr, QList<QUrl>>::const_iterator it = servicesMap.constBegin();
         it != servicesMap.constEnd(); ++it)
    {
        // Run the dedicated app to open the item.

#if KIO_VERSION < QT_VERSION_CHECK(5,6,0)
        KRun::run(*it.key(), it.value(), parentWidget);
#else
        KRun::runService(*it.key(), it.value(), parentWidget);
#endif
    }
}
Exemple #20
0
QString ibanBicData::iban2Bic(const QString& iban)
{
  Q_ASSERT(iban.length() < 1 || iban.at(0).isLetterOrNumber());
  Q_ASSERT(iban.length() < 2 || iban.at(1).isLetterOrNumber());
  Q_ASSERT(iban == payeeIdentifiers::ibanBic::ibanToElectronic(iban));

  if (iban.length() <= 4)   // This iban is to short to extract a BIC
    return QString("");

  // Get bank identifier
  const QString bankCode = extractBankIdentifier(iban);
  if (bankCode.isEmpty())
    return bankCode; // keep .isEmpty() or .isNull()

  // Get countryCode
  const QString countryCode = iban.left(2);

  // Get services which support iban2bic and have a database entry
  KService::List services = KServiceTypeTrader::self()->query("KMyMoney/IbanBicData",
                            QString("(\'%1' ~in [X-KMyMoney-CountryCodes] or '*' in [X-KMyMoney-CountryCodes]) and true == [X-KMyMoney-IBAN-2-BIC-supported] and exist [X-KMyMoney-Bankdata-Database]").arg(countryCode)
                                                             );

  if (services.isEmpty())
    return QString();

  QSqlDatabase db = createDatabaseConnection(services.first()->property(QLatin1String("X-KMyMoney-Bankdata-Database"), QVariant::String).toString());
  if (!db.isOpen())   // This is an error
    return QString();

  QSqlQuery query = QSqlQuery(db);
  query.prepare("SELECT bic FROM institutions WHERE bankcode=? and country=?");
  query.bindValue(0, bankCode);
  query.bindValue(1, countryCode);

  if (!query.exec()) {
    qWarning() << QString("Could not execute query on \"%1\" to receive BIC. Error: %2").arg(db.databaseName()).arg(query.lastError().text());
    return QString();
  }

  if (query.next()) {
    return query.value(0).toString();
  }

  return QString("");
}
//---------------------------------------------------------------------------
//
// Read the command line needed to run the screensaver given a .desktop file.
//
void ScreenSaverWindow::readSaver()
{
    if (!m_saver.isEmpty())
    {
        QString entryName = m_saver;
        if( entryName.endsWith( QLatin1String( ".desktop" ) ))
            entryName = entryName.left( entryName.length() - 8 ); // strip it
        const KService::List offers = KServiceTypeTrader::self()->query( QLatin1String( "ScreenSaver" ),
            QLatin1String( "DesktopEntryName == '" ) + entryName.toLower() + QLatin1Char( '\'' ) );
        if( offers.isEmpty() )
        {
            kDebug(1204) << "Cannot find screesaver: " << m_saver;
            return;
        }
        const QString file = KStandardDirs::locate("services", offers.first()->entryPath());

        const bool opengl = KAuthorized::authorizeKAction(QLatin1String( "opengl_screensavers" ));
        const bool manipulatescreen = KAuthorized::authorizeKAction(QLatin1String( "manipulatescreen_screensavers" ));
        KDesktopFile config( file );
        KConfigGroup desktopGroup = config.desktopGroup();
        foreach (const QString &type, desktopGroup.readEntry("X-KDE-Type").split(QLatin1Char(';'))) {
            if (type == QLatin1String("ManipulateScreen")) {
                if (!manipulatescreen) {
                    kDebug(1204) << "Screensaver is type ManipulateScreen and ManipulateScreen is forbidden";
                    m_forbidden = true;
                }
            } else if (type == QLatin1String("OpenGL")) {
                m_openGLVisual = true;
                if (!opengl) {
                    kDebug(1204) << "Screensaver is type OpenGL and OpenGL is forbidden";
                    m_forbidden = true;
                }
            }
        }

        kDebug(1204) << "m_forbidden: " << (m_forbidden ? "true" : "false");

        if (config.hasActionGroup(QLatin1String( "InWindow" )))
        {
            m_saverExec = config.actionGroup(QLatin1String( "InWindow" )).readPathEntry("Exec", QString());
        }
    }
Exemple #22
0
QVariantList createListForFileItem(const KFileItem &fileItem)
{
    QVariantList list;
    if (fileItem.url() == KUrl("trash:/")) {
        list << createEmptyTrashItem() << createSeparatorActionItem();
    }
    KService::List services = KMimeTypeTrader::self()->query(fileItem.mimetype(), "Application");
    if (!services.isEmpty()) {
        list << createTitleActionItem(i18n("Open with:"));
        Q_FOREACH(const KService::Ptr service, services) {
            const QString text = service->name().replace('&', "&&");
            QVariantMap item = createActionItem(text, "_homerun_fileItem_openWith", service->entryPath());
            QString iconName = service->icon();
            if (!iconName.isEmpty()) {
                item["icon"] = KIcon(service->icon());
            }
            list << item;
        }
        list << createSeparatorActionItem();
    }
Exemple #23
0
bool ClientApp::kde_open(const KUrl& url, const QString& mimeType, bool allowExec)
{
    if ( mimeType.isEmpty() ) {
        kDebug() << url;
        KRun * run = new KRun( url, 0 );
        run->setRunExecutables(allowExec);
        QObject::connect( run, SIGNAL( finished() ), this, SLOT( delayedQuit() ));
        QObject::connect( run, SIGNAL( error() ), this, SLOT( delayedQuit() ));
        this->exec();
        return !krun_has_error;
    } else {
        KUrl::List urls;
        urls.append( url );
        const KService::List offers = KMimeTypeTrader::self()->query(
            mimeType, QLatin1String( "Application" ) );
        if (offers.isEmpty()) return 1;
        KService::Ptr serv = offers.first();
        return KRun::run( *serv, urls, 0 );
    }
}
PopupMenuGUIClient::PopupMenuGUIClient( const KService::List &embeddingServices,
                                        KParts::BrowserExtension::ActionGroupMap& actionGroups,
                                        QAction* showMenuBar, QAction* stopFullScreen )
    : m_actionCollection(this),
      m_embeddingServices(embeddingServices)
{
    QList<QAction *> topActions;
    if (showMenuBar) {
        topActions.append(showMenuBar);
        KAction* separator = new KAction(&m_actionCollection);
        separator->setSeparator(true);
        topActions.append(separator);
    }

    if (stopFullScreen) {
        topActions.append(stopFullScreen);
        KAction* separator = new KAction(&m_actionCollection);
        separator->setSeparator(true);
        topActions.append(separator);
    }

    if (!embeddingServices.isEmpty()) {
        QList<QAction *> previewActions;
        if (embeddingServices.count() == 1) {
            KService::Ptr service = embeddingServices.first();
            QAction* act = addEmbeddingService( 0, i18n( "Preview &in %1", service->name() ), service );
            previewActions.append(act);
        } else if (embeddingServices.count() > 1) {
            KService::List::ConstIterator it = embeddingServices.begin();
            const KService::List::ConstIterator end = embeddingServices.end();
            int idx = 0;
            for (; it != end; ++it, ++idx ) {
                QAction* act = addEmbeddingService( idx, (*it)->name(), *it );
                previewActions.append(act);
            }
        }
        actionGroups.insert("preview", previewActions);
    }
    actionGroups.insert("topactions", topActions);
}
bool BrowserFrame::Private::loadPartForMimetype(const QString& mimetype)
{
    KService::List offers = KMimeTypeTrader::self()->query( mimetype, "KParts/ReadOnlyPart" );

    kDebug() <<"BrowserFrame::loadPartForMimetype("<< mimetype <<"):" << offers.size() <<" offers";

    if (offers.isEmpty())
        return false;
    // delete old part
    // FIXME: do this only if part can't be reused for the new mimetype
    if (part)
    {
        part->disconnect( this );
        layout->removeWidget(part->widget());
        delete part;
        delete extension;
    }

    KService::Ptr ptr = offers.first();
    KPluginFactory* factory = KPluginLoader(*ptr).factory();
    if (!factory)
        return false;
    part = factory->create<KParts::ReadOnlyPart>(q);
    if (!part)
        return false;

    // Parts can be destroyed from within the part itself, thus we must listen to destroyed()
    // partDestroyed() requests deletion of this BrowserFrame, which deletes the part, which crashes as
    // the part is already half-destructed (destroyed() is emitted from the dtor) but the QPointer is not yet reset to 0.
    // Thus queue the signal to avoid he double deletion.
    connect(part, SIGNAL(destroyed(QObject*)), this, SLOT(partDestroyed(QObject*)), Qt::QueuedConnection);

    part->setObjectName(ptr->name());
    extension = KParts::BrowserExtension::childObject(part);

    layout->addWidget(part->widget());
    connectPart();
    this->mimetype = mimetype;
    return true;
}
Exemple #26
0
ibanBicData::bicAllocationStatus ibanBicData::isBicAllocated(const QString& bic)
{
  // Get countryCode
  const QString countryCode = bic.mid(4, 2);
  if (countryCode.length() != 2)
    return bicNotAllocated;

  // Get services which have a database entry
  KService::List services = KServiceTypeTrader::self()->query("KMyMoney/IbanBicData",
                            QString("(\'%1' ~in [X-KMyMoney-CountryCodes] or '*' in [X-KMyMoney-CountryCodes]) and exist [X-KMyMoney-Bankdata-Database]").arg(countryCode)
                                                             );

  if (services.isEmpty())
    return bicAllocationUncertain;

  QSqlDatabase db = createDatabaseConnection(services.first()->property(QLatin1String("X-KMyMoney-Bankdata-Database"), QVariant::String).toString());
  if (!db.isOpen())   // This is an error
    return bicAllocationUncertain;

  QSqlQuery query(db);
  query.prepare("SELECT ? IN (SELECT bic FROM institutions)");
  query.bindValue(0, bic);

  if (!query.exec() || !query.next()) {
    qWarning() << QString("Could not execute query on \"%1\" to check if bic exists. Error: %2").arg(db.databaseName()).arg(query.lastError().text());
    return bicAllocationUncertain;
  }

  if (query.value(0).toBool())   // Bic found
    return bicAllocated;

  // Bic not found, test if database is complete
  if (services.first()->property(QLatin1String("X-KMyMoney-Bankdata-IsComplete"), QVariant::Bool).toBool())
    return bicNotAllocated;

  return bicAllocationUncertain;
}
Exemple #27
0
QString ThumbnailProtocol::pluginForMimeType(const QString& mimeType) {
    KService::List offers = KMimeTypeTrader::self()->query( mimeType, QLatin1String("ThumbCreator"));
    if (!offers.isEmpty()) {
        KService::Ptr serv;
        serv = offers.first();
        return serv->library();
    }

    //Match group mimetypes
    ///@todo Move this into some central location together with the related matching code in previewjob.cpp. This doesn't handle inheritance and such
    const KService::List plugins = KServiceTypeTrader::self()->query("ThumbCreator");
    foreach(KService::Ptr plugin, plugins) {
        const QStringList mimeTypes = plugin->serviceTypes();
        foreach(QString mime, mimeTypes) {
            if(mime.endsWith('*')) {
                mime = mime.left(mime.length()-1);
                if(mimeType.startsWith(mime))
                    return plugin->library();
            }
        }
    }

    return QString();
}
Exemple #28
0
void BackendSelection::showBackendKcm(const KService::Ptr &backendService)
{
    const QString parentComponent = backendService->library();
    if (!m_kcms.contains(parentComponent)) {
        const KService::List offers = KServiceTypeTrader::self()->query("KCModule",
                QString("'%1' in [X-KDE-ParentComponents]").arg(parentComponent));
        if (offers.isEmpty()) {
            m_kcms.insert(parentComponent, 0);
        } else {
            KCModuleProxy *proxy = new KCModuleProxy(offers.first());
            connect(proxy, SIGNAL(changed(bool)), SIGNAL(changed()));
            m_kcms.insert(parentComponent, proxy);
            stackedWidget->addWidget(proxy);
        }
    }
    QWidget *w = m_kcms.value(parentComponent);
    if (w) {
        stackedWidget->show();
        stackedWidget->setCurrentWidget(w);
    } else {
        stackedWidget->hide();
        stackedWidget->setCurrentIndex(m_emptyPage);
    }
}
Exemple #29
0
QString ibanBicData::bankNameByBic(QString bic)
{
  if (bic.length() == 8)
    bic += QLatin1String("XXX");
  else if (bic.length() != 11)
    return QString();

  const QString countryCode = bic.mid(4, 2);

  // Get services which have a database entry
  KService::List services = KServiceTypeTrader::self()->query("KMyMoney/IbanBicData",
                            QString("(\'%1' ~in [X-KMyMoney-CountryCodes] or '*' in [X-KMyMoney-CountryCodes]) and exist [X-KMyMoney-Bankdata-Database]").arg(countryCode)
                                                             );

  if (services.isEmpty())
    return QString();

  QSqlDatabase db = createDatabaseConnection(services.first()->property("X-KMyMoney-Bankdata-Database", QVariant::String).toString());
  if (!db.isOpen())   // This is an error
    return QString();

  QSqlQuery query = QSqlQuery(db);
  query.prepare("SELECT name FROM institutions WHERE bic=?");
  query.bindValue(0, bic);

  if (!query.exec()) {
    qWarning() << QString("Could not execute query on \"%1\" to receive bank name. Error: %2").arg(db.databaseName()).arg(query.lastError().text());
    return QString();
  }

  if (query.next()) {
    return query.value(0).toString();
  }

  return QString("");
}
Exemple #30
0
bool MigrateManagerInternal::lookupDrivers()
{
    if (!lookupDriversNeeded)
        return true;

    if (qApp) {
        connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(slotAppQuits()));
    }
//! @todo for Qt-only version check for KComponentData wrapper
//  KexiDBWarn << "cannot work without KComponentData (KGlobal::mainComponent()==0)!";
//  setError("Driver Manager cannot work without KComponentData (KGlobal::mainComponent()==0)!");

    lookupDriversNeeded = false;
    clearError();
    KService::List tlist = KServiceTypeTrader::self()->query("Kexi/MigrationDriver");
    KService::List::ConstIterator it(tlist.constBegin());
    for (; it != tlist.constEnd(); ++it) {
        KService::Ptr ptr = (*it);
        QString srv_name = ptr->property("X-Kexi-MigrationDriverName").toString();
        if (srv_name.isEmpty()) {
            KexiDBWarn << "X-Kexi-MigrationDriverName must be set for migration driver"
            << ptr->property("Name").toString() << "service!\n -- skipped!";
            continue;
        }
        if (m_services_lcase.contains(srv_name.toLower())) {
            continue;
        }

//! @todo could be merged. Copied from KexiDB::DriverManager.
//<COPIED>
        QString srv_ver_str = ptr->property("X-Kexi-KexiMigrationVersion").toString();
        QStringList lst(srv_ver_str.split('.'));
        int minor_ver, major_ver;
        bool ok = (lst.count() == 2);
        if (ok)
            major_ver = lst[0].toUInt(&ok);
        if (ok)
            minor_ver = lst[1].toUInt(&ok);
#if 0 //temp. disable
        if (!ok) {
            KexiDBWarn << "problem with detecting" << srv_name.toLower() << "driver's version -- skipping it!";
            possibleProblems += QString("\"%1\" migration driver has unrecognized version; "
                                        "required driver version is \"%2.%3\"")
                                .arg(srv_name.toLower())
                                .arg(KexiMigration::version().major).arg(KexiMigration::version().minor);
            continue;
        }
        if (!KexiMigration::version().matches(major_ver, minor_ver)) {
            KexiDBWarn << QString("'%1' driver"
                                  " has version '%2' but required migration driver version is '%3.%4'\n"
                                  " -- skipping this driver!").arg(srv_name.toLower()).arg(srv_ver_str)
            .arg(KexiMigration::version().major).arg(KexiMigration::version().minor);
            possibleProblems += QString("\"%1\" migration driver has version \"%2\" "
                                        "but required driver version is \"%3.%4\"")
                                .arg(srv_name.toLower()).arg(srv_ver_str)
                                .arg(KexiMigration::version().major).arg(KexiMigration::version().minor);
            continue;
        }
#endif
//</COPIED>

        QString mime = ptr->property("X-Kexi-FileDBDriverMime").toString().toLower();
        QString drvType = ptr->property("X-Kexi-MigrationDriverType").toString().toLower();
        if (drvType == "file") {
            if (!mime.isEmpty()) {
                if (!m_services_by_mimetype.contains(mime)) {
                    m_services_by_mimetype.insert(mime, ptr);
                } else {
                    KexiDBWarn << "more than one driver for" << mime << "mime type!";
                }
            }
        }
        m_services.insert(srv_name, ptr);
        m_services_lcase.insert(srv_name.toLower(), ptr);
        KexiDBDbg << "registered driver:" << ptr->name() << '(' << ptr->library() << ")";
    }

    if (tlist.isEmpty()) {
        setError(ERR_DRIVERMANAGER, i18n("Could not find any import/export database drivers."));
        return false;
    }
    return true;
}