void PluginManager::loadPlugins()
{
    DEBUG_FUNC_NAME
    KConfigGroup group = KGlobal::config()->group( "Plugins" );
    KService::List offers = KServiceTypeTrader::self()->query(
                                QString::fromLatin1( "GluonCreator/Plugin" ),
                                QString( "[X-KDE-GluonCreatorPluginVersion] == %1" ).arg( GLUONCREATOR_PLUGIN_VERSION ) );

    KService::List::const_iterator iter;
    for( iter = offers.begin(); iter < offers.end(); ++iter )
    {
        QString error;
        KService::Ptr service = *iter;

        QString serviceName = service->desktopEntryName();
        bool loadPlugin = group.readEntry<bool>( QString( "%1Enabled" ).arg( serviceName ), true );

        if( !d->loadedPlugins.contains( serviceName ) && loadPlugin )
        {
            KPluginFactory* factory = KPluginLoader( service->library() ).factory();

            if( !factory )
            {
                DEBUG_TEXT( QString( "KPluginFactory could not load the plugin: %1" ).arg( service->library() ) );
                continue;
            }

            Plugin* plugin = factory->create<Plugin>( this );

            if( plugin )
            {
                DEBUG_TEXT( QString( "Load plugin: %1" ).arg( service->name() ) );
                plugin->load( d->mainWindow );
                d->loadedPlugins.insert( serviceName, plugin );
            }
            else
            {
                DEBUG_TEXT( error );
            }
        }
        else if( !loadPlugin && d->loadedPlugins.contains( serviceName ) )
        {
            Plugin* plugin = d->loadedPlugins.value( serviceName );
            plugin->unload( d->mainWindow );
            delete plugin;
            d->loadedPlugins.remove( serviceName );
        }
    }
}
Beispiel #2
0
void BackendSelection::loadServices(const KService::List &offers)
{
    m_services.clear();
    m_select->clear();

    KService::List::const_iterator it = offers.begin();
    const KService::List::const_iterator end = offers.end();
    for (; it != end; ++it)
    {
        KService::Ptr service = *it;
        m_select->addItem(service->name());
        m_services[service->name()] = service;
    }
    m_select->setItemSelected(m_select->item(0), true);
}
bool PartController::canCreatePart(const KUrl& url)
{
    if (!url.isValid()) return false;

    QString mimeType;
    if ( url.isEmpty() )
        mimeType = QString::fromLatin1("text/plain");
    else
        mimeType = KMimeType::findByUrl( url )->name();

    KService::List offers = KMimeTypeTrader::self()->query(
                                mimeType,
                                "KParts/ReadOnlyPart" );

    return offers.count() > 0;
}
Beispiel #4
0
// Helper method for all the trader tests
static bool offerListHasService(const KService::List &offers,
                                const QString &entryPath)
{
    bool found = false;
    KService::List::const_iterator it = offers.begin();
    for (; it != offers.end(); ++it) {
        if ((*it)->entryPath() == entryPath) {
            if (found) {  // should be there only once
                qWarning("ERROR: %s was found twice in the list", qPrintable(entryPath));
                return false; // make test fail
            }
            found = true;
        }
    }
    return found;
}
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));
            }
        }
    }
}
ToggleViewGUIClient::ToggleViewGUIClient( KonqMainWindow *mainWindow )
: QObject( mainWindow )
{
  m_mainWindow = mainWindow;

  KService::List offers = KServiceTypeTrader::self()->query( "Browser/View" );
  KService::List::Iterator it = offers.begin();
  while ( it != offers.end() )
  {
    QVariant prop = (*it)->property( "X-KDE-BrowserView-Toggable" );
    QVariant orientation = (*it)->property( "X-KDE-BrowserView-ToggableView-Orientation" );

    if ( !prop.isValid() || !prop.toBool() ||
         !orientation.isValid() || orientation.toString().isEmpty() )
    {
      offers.erase( it );
      it = offers.begin();
    }
    else
      ++it;
  }

  m_empty = ( offers.count() == 0 );

  if ( m_empty )
    return;

  KService::List::ConstIterator cIt = offers.constBegin();
  KService::List::ConstIterator cEnd = offers.constEnd();
  for (; cIt != cEnd; ++cIt )
  {
    QString description = i18n( "Show %1" ,  (*cIt)->name() );
    QString name = (*cIt)->desktopEntryName();
    //kDebug() << "ToggleViewGUIClient: name=" << name;
    KToggleAction *action = new KToggleAction( description, this );
    mainWindow->actionCollection()->addAction( name.toLatin1(), action );

    // HACK
    if ( (*cIt)->icon() != "unknown" )
      action->setIcon( KIcon((*cIt)->icon()) );

    connect( action, SIGNAL(toggled(bool)),
             this, SLOT(slotToggleView(bool)) );

    m_actions.insert( name, action );

    QVariant orientation = (*cIt)->property( "X-KDE-BrowserView-ToggableView-Orientation" );
    bool horizontal = orientation.toString().toLower() == "horizontal";
    m_mapOrientation.insert( name, horizontal );
  }

  connect( m_mainWindow, SIGNAL(viewAdded(KonqView*)),
           this, SLOT(slotViewAdded(KonqView*)) );
  connect( m_mainWindow, SIGNAL(viewRemoved(KonqView*)),
           this, SLOT(slotViewRemoved(KonqView*)) );
}
Beispiel #7
0
void KMimeTypeTest::testMimeTypeTraderForAlias()
{
    if (!KSycoca::isAvailable()) {
        QSKIP("ksycoca not available");
    }

    const KService::List referenceOffers = KMimeTypeTrader::self()->query("application/xml", "KParts/ReadOnlyPart");
    QVERIFY(offerListHasService(referenceOffers, "faketextpart.desktop"));
    QVERIFY(!offerListHasService(referenceOffers, "fakepatchpart.desktop"));

    // Querying mimetype trader for services associated with text/xml, which is an alias for application/xml
    const KService::List offers = KMimeTypeTrader::self()->query("text/xml", "KParts/ReadOnlyPart");
    QVERIFY(offerListHasService(offers, "faketextpart.desktop"));
    QVERIFY(!offerListHasService(offers, "fakepatchpart.desktop"));

    QCOMPARE(offers.count(), referenceOffers.count());
}
Beispiel #8
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
    }
}
Beispiel #9
0
STDMETHODIMP CShellExt::QueryContextMenu(HMENU hMenu, UINT indexMenu, UINT idCmdFirst, UINT idCmdLast, UINT uFlags)
{
    UINT idCmd = idCmdFirst;
    BOOL bAppendItems=TRUE;
    TCHAR szFileUserClickedOn[MAX_PATH];

    FORMATETC fmte = {
        CF_HDROP,
        (DVTARGETDEVICE FAR *)NULL,
        DVASPECT_CONTENT,
        -1,
        TYMED_HGLOBAL
    };

    HRESULT hres = m_pDataObj->GetData(&fmte, &m_stgMedium);

    if (SUCCEEDED(hres)) {
        if (m_stgMedium.hGlobal)
            m_cbFiles = DragQueryFile((HDROP)m_stgMedium.hGlobal, (UINT)-1, 0, 0);
            qDebug() << "number of files:" << m_cbFiles;
            for (unsigned i = 0; i < m_cbFiles; i++) {
                DragQueryFile((HDROP)m_stgMedium.hGlobal, i, szFileUserClickedOn, MAX_PATH);
                qDebug() << "file to open:" << lptstr2QString(szFileUserClickedOn);
            }
    }
    QString path = lptstr2QString(szFileUserClickedOn);

    UINT nIndex = indexMenu++;
    
    KMimeType::Ptr ptr = KMimeType::findByPath(path);

    KService::List lst = KMimeTypeTrader::self()->query(ptr->name(), "Application");
    
    if(lst.size() > 0)
    {
        TCHAR str[256];
        wsprintf(str, TEXT("Open with %s"), (LPTSTR)lst.at(0)->name().utf16());
        InsertMenu(hMenu, nIndex, MF_STRING|MF_BYPOSITION, idCmd++, str );

        if (m_hKdeLogoBmp) {
            SetMenuItemBitmaps(hMenu, nIndex, MF_BYPOSITION, m_hKdeLogoBmp, m_hKdeLogoBmp);
        }
    }

    return ResultFromShort(idCmd-idCmdFirst);
}
Beispiel #10
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("");
}
Beispiel #11
0
void FilterOptions::load()
{
  KConfig config(KURISearchFilterEngine::self()->name() + QStringLiteral("rc"), KConfig::NoGlobals);
  KConfigGroup group = config.group("General");

  const QString defaultSearchEngine = group.readEntry("DefaultWebShortcut");
  const QStringList favoriteEngines = group.readEntry("PreferredWebShortcuts", DEFAULT_PREFERRED_SEARCH_PROVIDERS);

  QList<SearchProvider*> providers;
  const KService::List services = KServiceTypeTrader::self()->query(QStringLiteral("SearchProvider"));
  int defaultProviderIndex = services.size(); //default is "None", it is last in the list

  Q_FOREACH(const KService::Ptr &service, services)
  {
    SearchProvider* provider = new SearchProvider(service);
    if (defaultSearchEngine == provider->desktopEntryName())
      defaultProviderIndex = providers.size();
    providers.append(provider);
  }
//---------------------------------------------------------------------------
//
// 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());
        }
    }
Beispiel #13
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 );
    }
}
Beispiel #14
0
void KMimeTypeTest::testMimeTypeTraderForTextPlain()
{
    if ( !KSycoca::isAvailable() )
        QSKIP( "ksycoca not available", SkipAll );

    // Querying mimetype trader for services associated with text/plain
    KService::List offers = KMimeTypeTrader::self()->query("text/plain", "KParts/ReadOnlyPart");
    QVERIFY( offerListHasService( offers, "katepart.desktop" ) );
    QVERIFY( offerListHasService( offers, "faketextpart.desktop" ) );

    offers = KMimeTypeTrader::self()->query("text/plain", "KTextEditor/Plugin");
    QVERIFY( offers.count() > 0 );

    // We should have at least the fake text plugin that we created for this.
    // (The actual plugins from kdelibs don't mention text/plain anymore)
    QVERIFY( offerListHasService( offers, "faketextplugin.desktop" ) );

    // We shouldn't have non-plugins
    QVERIFY( !offerListHasService( offers, "katepart.desktop" ) );
}
Beispiel #15
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();
    }
Beispiel #16
0
KService::Ptr ArkViewer::getViewer(const KMimeType::Ptr &mimeType)
{
    // No point in even trying to find anything for application/octet-stream
    if (mimeType->isDefault()) {
        return KService::Ptr();
    }

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

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

    if (offers.size() > 0) {
        return offers.first();
    } else {
        return KService::Ptr();
    }
}
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;
}
Beispiel #18
0
void KInetD::loadServiceList()
{
	m_portListeners.clear();


	KService::List kinetdModules =
		KServiceType::offers("KInetDModule");
	for(KService::List::ConstIterator it = kinetdModules.begin();
		it != kinetdModules.end();
		it++) {
		KService::Ptr s = *it;
		PortListener *pl = new PortListener(s, m_config, m_srvreg);
		if (pl->isValid())
			m_portListeners.append(pl);
		else
			delete pl;
	}

	setExpirationTimer();
	setPortRetryTimer(true);
	setReregistrationTimer();
}
Beispiel #19
0
// Scans for plugins and stores the information for them in "pluginInfo"
static void scanPlugins() {
    KST::PluginInfoList tmpList;

    KstDebug::self()->log(i18n("Scanning for data-source plugins."));

    KService::List sl = KServiceType::offers("Kst Data Source");
    for (KService::List::ConstIterator it = sl.begin(); it != sl.end(); ++it) {
        for (KST::PluginInfoList::ConstIterator i2 = pluginInfo.begin(); i2 != pluginInfo.end(); ++i2) {
            if ((*i2)->service == *it) {
                tmpList.append(*i2);
                continue;
            }
        }

        KstSharedPtr<KST::Plugin> p = new KST::Plugin(*it);
        tmpList.append(p);
    }

    // This cleans up plugins that have been uninstalled and adds in new ones.
    // Since it is a shared pointer it can't dangle anywhere.
    pluginInfo = tmpList;
}
Beispiel #20
0
void DesktopCorona::checkAddPanelAction(const QStringList &sycocaChanges)
{
    if (!sycocaChanges.isEmpty() && !sycocaChanges.contains("services")) {
        return;
    }

    delete m_addPanelAction;
    m_addPanelAction = 0;

    delete m_addPanelsMenu;
    m_addPanelsMenu = 0;

    KPluginInfo::List panelContainmentPlugins = Plasma::Containment::listContainmentsOfType("panel");
    const QString constraint = QString("[X-Plasma-Shell] == '%1' and 'panel' ~in [X-Plasma-ContainmentCategories]")
                                      .arg(KGlobal::mainComponent().componentName());
    KService::List templates = KServiceTypeTrader::self()->query("Plasma/LayoutTemplate", constraint);

    if (panelContainmentPlugins.count() + templates.count() == 1) {
        m_addPanelAction = new QAction(i18n("Add Panel"), this);
        m_addPanelAction->setData(Plasma::AbstractToolBox::AddTool);
        connect(m_addPanelAction, SIGNAL(triggered(bool)), this, SLOT(addPanel()));
    } else if (!panelContainmentPlugins.isEmpty()) {
Beispiel #21
0
bool ArkViewer::viewInInternalViewer(const QString& fileName, const QMimeType &mimeType)
{
    setWindowFilePath(fileName);

    // Set icon and comment for the mimetype.
    m_iconLabel->setPixmap(QIcon::fromTheme(mimeType.iconName()).pixmap(IconSize(KIconLoader::Small), IconSize(KIconLoader::Small)));
    m_commentLabel->setText(mimeType.comment());

    // Create the ReadOnlyPart instance.
    m_part = KMimeTypeTrader::self()->createPartInstanceFromQuery<KParts::ReadOnlyPart>(mimeType.name(), this, this);

    // Drop the KHTMLPart, if necessary.
    const KService::Ptr service = KMimeTypeTrader::self()->preferredService(mimeType.name(), QStringLiteral("KParts/ReadOnlyPart"));
    qCDebug(ARK) << "Preferred service for mimetype" << mimeType.name() << "is" << service->library();
    if (service.constData()->desktopEntryName() == QLatin1String("khtml")) {
        KService::List offers = KMimeTypeTrader::self()->query(mimeType.name(), QStringLiteral("KParts/ReadOnlyPart"));
        offers.removeFirst();
        qCDebug(ARK) << "Removed KHTMLPart from the offers for mimetype" << mimeType.name()
                     << ". Using" << offers.first().constData()->desktopEntryName() << "instead.";
        m_part = offers.first().constData()->createInstance<KParts::ReadOnlyPart>(this, this);
    }

    if (!m_part.data()) {
        return false;
    }

    // Insert the KPart into its placeholder.
    centralWidget()->layout()->replaceWidget(m_partPlaceholder, m_part.data()->widget());

    createGUI(m_part.data());
    setAutoSaveSettings(QStringLiteral("Viewer"), true);

    m_part.data()->openUrl(QUrl::fromLocalFile(fileName));
    m_part.data()->widget()->setFocus();
    m_fileName = fileName;

    return true;
}
Beispiel #22
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;
}
Beispiel #23
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();
}
void RecordItNowPluginManager::loadInfos(const QString &type)
{

    KConfig cfg("recorditnowrc");
    KConfigGroup pCfg(&cfg, "Plugins");

    KService::List offers = KServiceTypeTrader::self()->query(type);
    KService::List::const_iterator iter;

    for (iter = offers.begin(); iter < offers.end(); ++iter) {
        KService::Ptr service = *iter;
        KPluginInfo info(service);

        if (!info.isValid()) {
            kWarning() << "invalid plugin info:" << service->entryPath();
            continue;
        } else {
            info.setConfig(pCfg);
            info.load(pCfg);
            m_plugins[info] = 0;
        }
    }

}
Beispiel #25
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);
    }
}
Beispiel #26
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("");
}
Beispiel #27
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());
                }
            }
        }
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);
}
Beispiel #29
0
int main( int argc, char **argv )
{
    QCoreApplication app(argc, argv);

    KLocalizedString::setApplicationDomain("ktraderclient");
    KAboutData aboutData(QLatin1String("ktraderclient"), i18n("KTraderClient"), QLatin1String(PROJECT_VERSION));
    aboutData.addAuthor(i18n("David Faure"), QString(), "*****@*****.**");

    aboutData.setShortDescription(i18n("A command-line tool for querying the KDE trader system"));
    QCommandLineParser parser;
    KAboutData::setApplicationData(aboutData);
    parser.addVersionOption();
    parser.addHelpOption();
    aboutData.setupCommandLine(&parser);

    parser.addOption(QCommandLineOption(QStringList() << QLatin1String("mimetype"), i18n("A mimetype"), QLatin1String("mimetype")));
    parser.addOption(QCommandLineOption(QStringList() << QLatin1String("servicetype"), i18n("A servicetype, like KParts/ReadOnlyPart or KMyApp/Plugin"), QLatin1String("servicetype")));
    parser.addOption(QCommandLineOption(QStringList() << QLatin1String("constraint"), i18n("A constraint expressed in the trader query language"), QLatin1String("constraint")));

    parser.addOption(QCommandLineOption(QStringList() << QLatin1String("short"), i18n("Output only paths to desktop files")));

    parser.process(app);
    aboutData.processCommandLine(&parser);

    const QString mimetype = parser.value("mimetype");
    QString servicetype = parser.value("servicetype");
    const QString constraint = parser.value("constraint");
    const bool outputProperties = !parser.isSet("short");

    if ( mimetype.isEmpty() && servicetype.isEmpty() )
        parser.showHelp();

    if ( !mimetype.isEmpty() )
        printf( "mimetype is : %s\n", qPrintable( mimetype ) );
    if ( !servicetype.isEmpty() )
        printf( "servicetype is : %s\n", qPrintable( servicetype ) );
    if ( !constraint.isEmpty() )
        printf( "constraint is : %s\n", qPrintable( constraint ) );

    KService::List offers;
    if ( !mimetype.isEmpty() ) {
        if ( servicetype.isEmpty() )
            servicetype = "Application";
        offers = KMimeTypeTrader::self()->query( mimetype, servicetype, constraint );
    }
    else
        offers = KServiceTypeTrader::self()->query( servicetype, constraint );

    printf("got %d offers.\n", offers.count());

    int i = 0;
    KService::List::ConstIterator it = offers.constBegin();
    const KService::List::ConstIterator end = offers.constEnd();
    for (; it != end; ++it, ++i )
    {
        if (outputProperties) {
            printf("---- Offer %d ----\n", i);
            QStringList props = (*it)->propertyNames();
            QStringList::ConstIterator propIt = props.constBegin();
            QStringList::ConstIterator propEnd = props.constEnd();
            for (; propIt != propEnd; ++propIt )
            {
                QVariant prop = (*it)->property( *propIt );

                if ( !prop.isValid() )
                {
                    printf("Invalid property %s\n", (*propIt).toLocal8Bit().data());
                    continue;
                }

                QString outp = *propIt;
                outp += " : '";

                switch ( prop.type() )
                {
                    case QVariant::StringList:
                        outp += prop.toStringList().join(" - ");
                        break;
                    case QVariant::Bool:
                        outp += prop.toBool() ? "TRUE" : "FALSE";
                        break;
                    default:
                        outp += prop.toString();
                        break;
                }

                if ( !outp.isEmpty() )
                    printf("%s'\n", outp.toLocal8Bit().constData());
            }
        } else {
            printf("%s\n", (*it)->entryPath().toLocal8Bit().constData());
        }
    }
    return 0;
}
Beispiel #30
0
int main(int argc, char *argv[])
{
	KCmdLineArgs::init(argc, argv, appName, "kscreensaver", ki18n("Random screen saver"), 
                KDE_VERSION_STRING, ki18n(description));


	KCmdLineOptions options;

	options.add("setup", ki18n("Setup screen saver"));

	options.add("window-id wid", ki18n("Run in the specified XWindow"));

	options.add("root", ki18n("Run in the root XWindow"));

	KCmdLineArgs::addCmdLineOptions(options);

	KApplication app;

	WId windowId = 0;

	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

	if (args->isSet("setup"))
	{
		KRandomSetup setup;
		setup.exec();
		exit(0);
	}

	if (args->isSet("window-id"))
	{
		windowId = args->getOption("window-id").toInt();
	}

#ifdef Q_WS_X11
	if (args->isSet("root"))
	{
		QX11Info info;
		windowId = RootWindow(QX11Info::display(), info.screen());
	}
#endif
	args->clear();
	const KService::List lst = KServiceTypeTrader::self()->query( "ScreenSaver");
        KService::List availableSavers;

	KConfig type("krandom.kssrc", KConfig::NoGlobals);
        const KConfigGroup configGroup = type.group("Settings");
	const bool opengl = configGroup.readEntry("OpenGL", false);
	const bool manipulatescreen = configGroup.readEntry("ManipulateScreen", false);
        // TODO replace this with TryExec=fortune in the desktop files
        const bool fortune = !KStandardDirs::findExe("fortune").isEmpty();
        foreach( const KService::Ptr& service, lst ) {
            //QString file = KStandardDirs::locate("services", service->entryPath());
            //kDebug() << "Looking at " << file;
            const QString saverType = service->property("X-KDE-Type").toString();
            foreach (const QString &type, saverType.split(QLatin1Char(';'))) {
                //kDebug() << "saverTypes is "<< type;
                if (type == QLatin1String("ManipulateScreen")) {
                    if (!manipulatescreen)
                        goto fail;
                } else if (type == QLatin1String("OpenGL")) {
                    if (!opengl)
                        goto fail;
                } else if (type == QLatin1String("Fortune")) {
                    if (!fortune)
                        goto fail;
                }
            }
            availableSavers.append(service);
          fail: ;
        }

	KRandomSequence rnd;
	const int indx = rnd.getLong(availableSavers.count());
        const KService::Ptr service = availableSavers.at(indx);
        const QList<KServiceAction> actions = service->actions();

	QString cmd;
	if (windowId)
            cmd = exeFromActionGroup(actions, "InWindow");
        if (cmd.isEmpty() && windowId == 0)
            cmd = exeFromActionGroup(actions, "Root");
        if (cmd.isEmpty())
            cmd = service->exec();

    QHash<QChar, QString> keyMap;
    keyMap.insert('w', QString::number(windowId));
    const QStringList words = KShell::splitArgs(KMacroExpander::expandMacrosShellQuote(cmd, keyMap));
    if (!words.isEmpty()) {
        QString exeFile = KStandardDirs::findExe(words.first());
        if (!exeFile.isEmpty()) {
            char **sargs = new char *[words.size() + 1];
            int i = 0;
            for (; i < words.size(); i++)
                sargs[i] = qstrdup(words[i].toLocal8Bit().constData());
            sargs[i] = 0;

            execv(exeFile.toLocal8Bit(), sargs);
        }
    }

	// If we end up here then we couldn't start a saver.
	// If we have been supplied a window id or root window then blank it.
#ifdef Q_WS_X11
	QX11Info info;
	Window win = windowId ? windowId : RootWindow(QX11Info::display(), info.screen());
	XSetWindowBackground(QX11Info::display(), win,
			BlackPixel(QX11Info::display(), info.screen()));
	XClearWindow(QX11Info::display(), win);
#endif
}