void PidginRunner::match(Plasma::RunnerContext &context)
{
    qDebug() << Q_FUNC_INFO ;
    QString query = context.query();
    if ( !query.isEmpty() )
    {
        qDebug() << " Pidgin runner trigger word";
        QString contactName = query ;

        // so now let's filter all contacts from
        // pidgin
        QStringList contacts = pidgin_d.search(query);
        QList<Plasma::QueryMatch> matches;
        std::for_each(contacts.begin(), contacts.end(), [&contacts, &matches, this](const QString& c )
        {
            Plasma::QueryMatch match(this);
            QVariantMap map = pidgin_d.buddyId(c);
            match.setText(c);
            match.setSubtext(map["buddyStatus"].toString());
            match.setData(c);
            match.setId(c);
            match.setType(Plasma::QueryMatch::ExactMatch);
            QIcon icon(map["buddyIconPath"].toString());
            match.setIcon(icon);
            matches.append(match);

        });
        context.addMatches(matches);
    }
}
void RecentDocuments::match(Plasma::RunnerContext &context)
{
    if (m_recentdocuments.isEmpty()) {
        return;
    }

    const QString term = context.query();
    if (term.length() < 3) {
        return;
    }

    foreach (const QString &document, m_recentdocuments) {
        if (!context.isValid()) {
            return;
        }

        if (document.contains(term, Qt::CaseInsensitive)) {
            KConfig _config( document, KConfig::SimpleConfig );
            KConfigGroup config(&_config, "Desktop Entry" );
            QString niceName =  config.readEntry( "Name" );
            Plasma::QueryMatch match(this);
            match.setType(Plasma::QueryMatch::PossibleMatch);
            match.setRelevance(1.0);
            match.setIcon(QIcon::fromTheme(config.readEntry("Icon")));
            match.setData(document); // TODO: Read URL[$e], or can we just pass the path to the .desktop file?
            match.setText(niceName);
            match.setSubtext(i18n("Recent Document"));
            context.addMatch(match);
        }
    }
}
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());
            }
        }
    }
void RecentDocuments::match(Plasma::RunnerContext &context)
{
    if (m_recentdocuments.isEmpty()) {
        return;
    }

    const QString term = context.query();
    if (term.length() < 3) {
        return;
    }

    foreach (const QString &document, m_recentdocuments) {
        if (!context.isValid()) {
            return;
        }

        if (document.contains(term, Qt::CaseInsensitive)) {
            KDesktopFile config(document);
            Plasma::QueryMatch match(this);
            match.setType(Plasma::QueryMatch::PossibleMatch);
            match.setRelevance(1.0);
            match.setIcon(QIcon::fromTheme(config.readIcon()));
            match.setData(config.readUrl());
            match.setText(config.readName());
            match.setSubtext(i18n("Recent Document"));
            context.addMatch(match);
        }
    }
}
Exemple #5
0
void KGetRunner::match(Plasma::RunnerContext& context)
{
    QString query = context.query();
    m_urls = parseUrls(context.query());
    if (!m_urls.isEmpty()) {
        Plasma::QueryMatch match(this);
        match.setType(Plasma::QueryMatch::PossibleMatch);
        match.setRelevance(0.9);
        match.setIcon(m_icon);
        if(m_urls.size() == 1) {
            match.setText(i18n("Download %1 with KGet.", KUrl(m_urls.first()).prettyUrl()));
        }
        else {
            match.setText(i18np("Download %1 link with KGet.", "Download %1 links with KGet.", m_urls.size()));
        }
        context.addMatch(query, match);
    }
}
void ActivityRunner::match(Plasma::RunnerContext &context)
{
    if (!m_enabled) {
        return;
    }

    const QString term = context.query().trimmed();
    bool list = false;
    QString name;

    if (term.startsWith(m_keywordi18n, Qt::CaseInsensitive)) {
        if (term.size() == m_keywordi18n.size()) {
            list = true;
        } else {
            name = term.right(term.size() - m_keywordi18n.size()).trimmed();
            list = name.isEmpty();
        }
    } else if (term.startsWith(m_keyword, Qt::CaseInsensitive)) {
        if (term.size() == m_keyword.size()) {
            list = true;
        } else {
            name = term.right(term.size() - m_keyword.size()).trimmed();
            list = name.isEmpty();
        }
    } else if (context.singleRunnerQueryMode()) {
        name = term;
    } else {
        return;
    }

    QList<Plasma::QueryMatch> matches;
    QStringList activities = m_activities->listActivities();
    qSort(activities);

    const QString current = m_activities->currentActivity();

    if (!context.isValid()) {
        return;
    }

    if (list) {
        foreach (const QString &activity, activities) {
            if (current == activity) {
                continue;
            }

            KActivities::Info info(activity);
            addMatch(info, matches);

            if (!context.isValid()) {
                return;
            }
        }
    } else {
Exemple #7
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());
                }
            }
        }
void WebshortcutRunner::match(Plasma::RunnerContext &context)
{
    const QString term = context.query();

    if (term.length() < 3 || !term.contains(m_delimiter))
        return;

    // qDebug() << "checking term" << term;

    const int delimIndex = term.indexOf(m_delimiter);
    if (delimIndex == term.length() - 1)
        return;

    const QString key = term.left(delimIndex);

    if (key == m_lastFailedKey) {
        return;    // we already know it's going to suck ;)
    }

    if (!context.isValid()) {
        qDebug() << "invalid context";
        return;
    }

    // Do a fake user feedback text update if the keyword has not changed.
    // There is no point filtering the request on every key stroke.
    // filtering
    if (m_lastKey == key) {
        m_filterBeforeRun = true;
        m_match.setText(i18n("Search %1 for %2", m_lastProvider, term.mid(delimIndex + 1)));
        context.addMatch(m_match);
        return;
    }

    KUriFilterData filterData(term);
    if (!KUriFilter::self()->filterSearchUri(filterData, KUriFilter::WebShortcutFilter)) {
        m_lastFailedKey = key;
        return;
    }

    m_lastFailedKey.clear();
    m_lastKey = key;
    m_lastProvider = filterData.searchProvider();

    m_match.setData(filterData.uri().url());
    m_match.setId("WebShortcut:" + key);

    m_match.setIcon(QIcon::fromTheme(filterData.iconName()));
    m_match.setText(i18n("Search %1 for %2", m_lastProvider, filterData.searchTerm()));
    context.addMatch(m_match);
}
void Translator::match(Plasma::RunnerContext &context)
{
    const QString term = context.query();
    QString text;
    QPair<QString, QString> language;
    
    
    if (!parseTerm(term, text, language)) return;
    if (!context.isValid()) return;
    
    if (text.contains(" ")) {
        if(m_yandexPhrase) {
            QEventLoop loop;
            Yandex yandex(this, context, text, language, m_yandexKey);
            connect(&yandex, SIGNAL(finished()), &loop, SLOT(quit()));
            loop.exec();
        }
        if(m_glosbePhrase) {
            if(m_glosbeExamples) {
                QEventLoop loop;
                Glosbe glosbe(this, context, text, language, m_glosbeExamples);
                connect(&glosbe, SIGNAL(finished()), &loop, SLOT(quit()));
                loop.exec();
            }
            QEventLoop loop;
            Glosbe glosbe(this, context, text, language);
            connect(&glosbe, SIGNAL(finished()), &loop, SLOT(quit()));
            loop.exec();
        }
    } else {
        if(m_yandexWord) {
            QEventLoop loop;
            Yandex yandex(this, context, text, language, m_yandexKey);
            connect(&yandex, SIGNAL(finished()), &loop, SLOT(quit()));
            loop.exec();
        }
        if(m_glosbeWord) {
            if(m_glosbeExamples) {
                QEventLoop loop;
                Glosbe glosbe(this, context, text, language, m_glosbeExamples);
                connect(&glosbe, SIGNAL(finished()), &loop, SLOT(quit()));
                loop.exec();
            }
            QEventLoop loop;
            Glosbe glosbe(this, context, text, language);
            connect(&glosbe, SIGNAL(finished()), &loop, SLOT(quit()));
            loop.exec();
        }
    }
}
void BookmarksRunner::match(Plasma::RunnerContext &context)
{
    if(! m_browser) return;
    const QString term = context.query();
    if ((term.length() < 3) && (!context.singleRunnerQueryMode())) {
        return;
    }

    bool allBookmarks = term.compare(i18nc("list of all konqueror bookmarks", "bookmarks"),
                                     Qt::CaseInsensitive) == 0;
                                     
    QList<BookmarkMatch> matches = m_browser->match(term, allBookmarks);
    foreach(BookmarkMatch match, matches) {
        if(!context.isValid())
            return;
        context.addMatch(match.asQueryMatch(this));
    }
}
Exemple #11
0
void ShellRunner::match(Plasma::RunnerContext &context)
{
    if (!m_enabled) {
        return;
    }

    if (context.type() == Plasma::RunnerContext::Executable ||
        context.type() == Plasma::RunnerContext::ShellCommand)  {
        const QString term = context.query();
        Plasma::QueryMatch match(this);
        match.setId(term);
        match.setType(Plasma::QueryMatch::ExactMatch);
        match.setIcon(QIcon::fromTheme("system-run"));
        match.setText(i18n("Run %1", term));
        match.setRelevance(0.7);
        context.addMatch(match);
    }
}
void LocationsRunner::run(const Plasma::RunnerContext &context, const Plasma::QueryMatch &match)
{
    Q_UNUSED(match)

    QString location = context.query();

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

    location = convertCaseInsensitivePath(location);

    //qDebug() << "command: " << context.query();
    //qDebug() << "url: " << location << data;

    QUrl urlToRun(KUriFilter::self()->filteredUri(location, QStringList() << QStringLiteral("kshorturifilter")));

    new KRun(urlToRun, 0);
}
void RecentDocuments::match(Plasma::RunnerContext &context)
{
    if (m_recentdocuments.isEmpty()) {
        return;
    }

    const QString term = context.query();
    if (term.length() < 3) {
        return;
    }

    const QString homePath = QDir::homePath();

    foreach (const QString &document, m_recentdocuments) {
        if (!context.isValid()) {
            return;
        }

        if (document.contains(term, Qt::CaseInsensitive)) {
            KDesktopFile config(document);
            Plasma::QueryMatch match(this);
            match.setType(Plasma::QueryMatch::PossibleMatch);
            match.setRelevance(1.0);
            match.setIconName(config.readIcon());
            match.setData(config.readUrl());
            match.setText(config.readName());

            QUrl folderUrl = QUrl(config.readUrl()).adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash);
            if (folderUrl.isLocalFile()) {
                QString folderPath = folderUrl.toLocalFile();
                if (folderPath.startsWith(homePath)) {
                    folderPath.replace(0, homePath.length(), QStringLiteral("~"));
                }
                match.setSubtext(folderPath);
            } else {
                match.setSubtext(folderUrl.toDisplayString());
            }

            context.addMatch(match);
        }
    }
}
Exemple #14
0
void CharacterRunner::match(Plasma::RunnerContext &context)
{
    QString term = context.query();
    QString specChar;

    term = term.replace(QLatin1Char( ' ' ), QLatin1String( "" )); //remove blanks
    if (term.length() < 2) //ignore too short queries
    {
        return;
    }
    if (!term.startsWith(m_triggerWord)) //ignore queries without the triggerword
    {
      return;
    }
    term = term.remove(0, m_triggerWord.length()); //remove the triggerword

    if (m_aliases.contains(term)) //replace aliases by their hex.-code
    {
      term = m_codes[m_aliases.indexOf(term)];
    }

    bool ok; //checkvariable
    int hex = term.toInt(&ok, 16); //convert query into int
    if (!ok) //check if conversion was successful
    {
      return;
    }

    //make special caracter out of the hex.-code
    specChar=QString();
    specChar.toUtf8();
    specChar[0]=hex;

    //create match
    Plasma::QueryMatch match(this);
    match.setType(Plasma::QueryMatch::InformationalMatch);
    match.setIcon(KIcon(QLatin1String( "accessories-character-map" )));
    match.setText(specChar);
    match.setData(specChar);
    match.setId(QString());
    context.addMatch(term, match);
}
void WebshortcutRunner::run(const Plasma::RunnerContext &context, const Plasma::QueryMatch &match)
{
    QString location;

    //qDebug() << "filter before run?" << m_filterBeforeRun;
    if (m_filterBeforeRun) {
        m_filterBeforeRun = false;
        //qDebug() << "look up webshortcut:" << context.query();
        KUriFilterData filterData (context.query());
        if (KUriFilter::self()->filterSearchUri(filterData, KUriFilter::WebShortcutFilter))
            location = filterData.uri().url();
    } else {
        location = match.data().toString();
    }

    //qDebug() << location;
    if (!location.isEmpty()) {
        KToolInvocation::invokeBrowser(location);
    }
}
void WebshortcutRunner::run(const Plasma::RunnerContext &context, const Plasma::QueryMatch &match)
{
    QUrl location;

    //qDebug() << "filter before run?" << m_filterBeforeRun;
    if (m_filterBeforeRun) {
        m_filterBeforeRun = false;
        //qDebug() << "look up webshortcut:" << context.query();
        KUriFilterData filterData (context.query());
        if (KUriFilter::self()->filterSearchUri(filterData, KUriFilter::WebShortcutFilter))
            location = filterData.uri();
    } else {
        location = match.data().toUrl();
    }

    //qDebug() << location;
    if (!location.isEmpty()) {
        QDesktopServices::openUrl(location);
    }
}
Exemple #17
0
void Translator::match(Plasma::RunnerContext& context)
{
    QString term = context.query();
    QString text;
    QPair<QString, QString> language;

    if (!parseTerm(term, text, language)) {
        return;
    }

    if (!context.isValid()) {
        return;
    }

    QEventLoop loop;
    TranslatorJob job(text, language);
    connect(&job, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    parseResult(job.result(), context, text);
}
Exemple #18
0
void PlasmaRunner::match(Plasma::RunnerContext &context)
{
    QList<Plasma::QueryMatch> matches;

    const QString query = context.query();

    bool success = false;
    // TODO: how to estimate that input is in Degree, not Radian?
    GeoDataCoordinates coordinates = GeoDataCoordinates::fromString(query, success);

    if (success) {
        const QVariant coordinatesData = QVariantList()
            << QVariant(coordinates.longitude(GeoDataCoordinates::Degree))
            << QVariant(coordinates.latitude(GeoDataCoordinates::Degree))
            << QVariant(0.1); // TODO: make this distance value configurable

        Plasma::QueryMatch match(this);
        match.setIcon(QIcon::fromTheme(QStringLiteral("marble")));
        match.setText(i18n("Show the coordinates %1 in OpenStreetMap with Marble", query));
        match.setData(coordinatesData);
        match.setId(query);
        match.setRelevance(1.0);
        match.setType(Plasma::QueryMatch::ExactMatch);

        matches << match;
    }

    // TODO: BookmarkManager does not yet listen to updates, also does not sync between processes :(
    // So for now always load on demand, even if expensive possibly
    BookmarkManager bookmarkManager(new GeoDataTreeModel);
    bookmarkManager.loadFile( QStringLiteral("bookmarks/bookmarks.kml") );

    for (GeoDataFolder* folder: bookmarkManager.folders()) {
        collectMatches(matches, query, folder);
    }

    if ( ! matches.isEmpty() ) {
        context.addMatches(matches);
    }
}
void SessionRunner::match(Plasma::RunnerContext &context)
{
    const QString term = context.query();
    QString user;
    bool matchUser = false;

    QList<Plasma::QueryMatch> matches;

    if (term.size() < 3) {
        return;
    }

    // first compare with SESSIONS. this must *NOT* be translated (i18n)
    // as it is used as an internal command trigger (e.g. via d-bus),
    // not as a user supplied query. and yes, "Ugh, magic strings"
    bool listAll = term.compare(QLatin1String("SESSIONS"), Qt::CaseInsensitive) == 0 ||
                   term.compare(i18nc("User sessions", "sessions"), Qt::CaseInsensitive) == 0;

    if (!listAll) {
        //no luck, try the "switch" user command
        if (term.startsWith(m_triggerWord, Qt::CaseInsensitive)) {
            user = term.right(term.size() - m_triggerWord.length()).trimmed();
            listAll = user.isEmpty();
            matchUser = !listAll;
        } else {
            // we know it's not SESSION or "switch <something>", so let's
            // try some other possibilities
            matchCommands(matches, term);
        }
    }

    bool switchUser = listAll ||
                      term.compare(i18n("switch user"), Qt::CaseInsensitive) == 0 ||
                      term.compare(i18n("new session"), Qt::CaseInsensitive) == 0;

    if (switchUser &&
        KAuthorized::authorizeAction(QStringLiteral("start_new_session")) &&
        dm.isSwitchable() &&
        dm.numReserve() >= 0) {
        Plasma::QueryMatch match(this);
        match.setType(Plasma::QueryMatch::ExactMatch);
        match.setIconName(QStringLiteral("system-switch-user"));
        match.setText(i18n("New Session"));
        matches << match;
    }

    // now add the active sessions
    if (listAll || matchUser) {
        SessList sessions;
        dm.localSessions(sessions);

        foreach (const SessEnt& session, sessions) {
            if (!session.vt || session.self) {
                continue;
            }

            QString name = KDisplayManager::sess2Str(session);
            Plasma::QueryMatch::Type type = Plasma::QueryMatch::NoMatch;
            qreal relevance = 0.7;

            if (listAll) {
                type = Plasma::QueryMatch::ExactMatch;
                relevance = 1;
            } else if (matchUser) {
                if (name.compare(user, Qt::CaseInsensitive) == 0) {
                    // we need an elif branch here because we don't
                    // want the last conditional to be checked if !listAll
                    type = Plasma::QueryMatch::ExactMatch;
                    relevance = 1;
                } else if (name.contains(user, Qt::CaseInsensitive)) {
                    type = Plasma::QueryMatch::PossibleMatch;
                }
            }

            if (type != Plasma::QueryMatch::NoMatch) {
                Plasma::QueryMatch match(this);
                match.setType(type);
                match.setRelevance(relevance);
                match.setIconName(QStringLiteral("user-identity"));
                match.setText(name);
                match.setData(QString::number(session.vt));
                matches << match;
            }
        }
    }
Exemple #20
0
void ShellRunner::run(const Plasma::RunnerContext &context, const Plasma::QueryMatch &match)
{
    Q_UNUSED(match);

    // filter match's id to remove runner's name
    // as this is the command we want to run

    if (m_enabled) {
#ifdef Q_OS_UNIX
        //qDebug() << m_asOtherUser << m_username << m_password;
        if (m_asOtherUser && !m_username.isEmpty()) {
            //TODO: provide some user feedback on failure
            QString exec;
            QString args;
            if (m_inTerminal) {
                // we have to reimplement this from KToolInvocation because we need to use KDESu
                KConfigGroup confGroup( KGlobal::config(), "General" );
                exec = confGroup.readPathEntry("TerminalApplication", "konsole");
                if (!exec.isEmpty()) {
                    if (exec == "konsole") {
                        args += " --noclose";
                    } else if (exec == "xterm") {
                        args += " -hold";
                    }

                    args += " -e " + context.query();
                }
            } else {
                const QStringList commandLine = KShell::splitArgs(context.query(), KShell::TildeExpand);
                if (!commandLine.isEmpty()) {
                    exec = commandLine.at(0);
                }

                args = context.query().right(context.query().size() - commandLine.at(0).length());
            }

            if (!exec.isEmpty()) {
                exec = KStandardDirs::findExe(exec);
                exec.append(args);
                if (!exec.isEmpty()) {
                    KDESu::SuProcess client(m_username.toLocal8Bit(), exec.toLocal8Bit());
                    const QByteArray password = m_password.toLocal8Bit();
                    //TODO handle errors like wrong password via KNotifications in 4.7
                    client.exec(password.constData());
                }
            }
        } else
#endif
        if (m_inTerminal) {
            KToolInvocation::invokeTerminal(context.query());
        } else {
            KRun::runCommand(context.query(), NULL);
        }
    }

    // reset for the next run!
    m_inTerminal = false;
    m_asOtherUser = false;
    m_username.clear();
    m_password.clear();
}
void PowerDevilRunner::match(Plasma::RunnerContext &context)
{
    const QString term = context.query();
    if (term.length() < m_shortestCommand) {
        return;
    }

    QList<Plasma::QueryMatch> matches;

    QString parameter;

    if (parseQuery(term,
                   QList<QRegExp>() << QRegExp(i18nc("Note this is a KRunner keyword; %1 is a parameter", "power profile %1", "(.*)"), Qt::CaseInsensitive)
                                    << QRegExp(i18nc("Note this is a KRunner keyword", "power profile"), Qt::CaseInsensitive),
                   parameter)) {
        for (StringStringMap::const_iterator i = m_availableProfiles.constBegin(); i != m_availableProfiles.constEnd(); ++i) {
            if (!parameter.isEmpty()) {
                if (!i.value().startsWith(parameter, Qt::CaseInsensitive)) {
                    continue;
                }
            }
            Plasma::QueryMatch match(this);
            match.setType(Plasma::QueryMatch::ExactMatch);
            match.setIcon(KIcon(m_profileIcon[i.key()]));
            match.setText(i18n("Set Profile to '%1'", i.value()));
            match.setData(i.key());
            match.setRelevance(1);
            match.setId("ProfileChange "+ i.key());
            matches.append(match);
        }
    } else if (parseQuery(term,
                          QList<QRegExp>() << QRegExp(i18nc("Note this is a KRunner keyword; %1 is a parameter", "screen brightness %1", "(.*)"), Qt::CaseInsensitive)
                                           << QRegExp(i18nc("Note this is a KRunner keyword", "screen brightness"), Qt::CaseInsensitive)
                                           << QRegExp(i18nc("Note this is a KRunner keyword; %1 is a parameter", "dim screen %1", "(.*)"), Qt::CaseInsensitive)
                                           << QRegExp(i18nc("Note this is a KRunner keyword", "dim screen"), Qt::CaseInsensitive),
                          parameter)) {
        if (!parameter.isEmpty()) {
            bool test;
            int b = parameter.toInt(&test);
            if (test) {
                int brightness = qBound(0, b, 100);
                Plasma::QueryMatch match(this);
                match.setType(Plasma::QueryMatch::ExactMatch);
                match.setIcon(KIcon("preferences-system-power-management"));
                match.setText(i18n("Set Brightness to %1", brightness));
                match.setData(brightness);
                match.setRelevance(1);
                match.setId("BrightnessChange");
                matches.append(match);
            }
        } else {
            Plasma::QueryMatch match1(this);
            match1.setType(Plasma::QueryMatch::ExactMatch);
            match1.setIcon(KIcon("preferences-system-power-management"));
            match1.setText(i18n("Dim screen totally"));
            match1.setRelevance(1);
            match1.setId("DimTotal");
            matches.append(match1);

            Plasma::QueryMatch match2(this);
            match2.setType(Plasma::QueryMatch::ExactMatch);
            match2.setIcon(KIcon("preferences-system-power-management"));
            match2.setText(i18n("Dim screen by half"));
            match2.setRelevance(1);
            match2.setId("DimHalf");
            matches.append(match2);

            Plasma::QueryMatch match3(this);
            match3.setType(Plasma::QueryMatch::ExactMatch);
            match3.setIcon(KIcon("video-display"));
            match3.setText(i18n("Turn off screen"));
            match3.setRelevance(1);
            match3.setId("TurnOffScreen");
            matches.append(match3);
        }
    } else if (term.compare(i18nc("Note this is a KRunner keyword", "suspend"), Qt::CaseInsensitive) == 0) {
        QSet< Solid::PowerManagement::SleepState > states = Solid::PowerManagement::supportedSleepStates();

        if (states.contains(Solid::PowerManagement::SuspendState)) {
            addSuspendMatch(Solid::PowerManagement::SuspendState, matches);
        }

        if (states.contains(Solid::PowerManagement::HibernateState)) {
            addSuspendMatch(Solid::PowerManagement::HibernateState, matches);
        }
    } else if (term.compare(i18nc("Note this is a KRunner keyword", "sleep"), Qt::CaseInsensitive) == 0 ||
               term.compare(i18nc("Note this is a KRunner keyword", "to ram"), Qt::CaseInsensitive) == 0) {
        addSuspendMatch(Solid::PowerManagement::SuspendState, matches);
    } else if (term.compare(i18nc("Note this is a KRunner keyword", "hibernate"), Qt::CaseInsensitive) == 0 ||
               term.compare(i18nc("Note this is a KRunner keyword", "to disk"), Qt::CaseInsensitive) == 0) {
        addSuspendMatch(Solid::PowerManagement::HibernateState, matches);
    }

    if (!matches.isEmpty()) {
        context.addMatches(term, matches);
    }
}
void LocationsRunner::match(Plasma::RunnerContext &context)
{
    QString term = context.query();
    Plasma::RunnerContext::Type type = context.type();

    if (type == Plasma::RunnerContext::Directory || type == Plasma::RunnerContext::File) {
        Plasma::QueryMatch match(this);
        match.setType(Plasma::QueryMatch::ExactMatch);
        match.setText(i18n("Open %1", term));

        if (type == Plasma::RunnerContext::File) {
            match.setIcon(QIcon::fromTheme(KIO::iconNameForUrl(QUrl(term))));
        } else {
            match.setIcon(QIcon::fromTheme(QStringLiteral("system-file-manager")));
        }

        match.setRelevance(1);
        match.setData(term);
        match.setType(Plasma::QueryMatch::ExactMatch);

        if (type == Plasma::RunnerContext::Directory) {
            match.setId(QStringLiteral("opendir"));
        } else {
            match.setId(QStringLiteral("openfile"));
        }
        context.addMatch(match);
    } else if (type == Plasma::RunnerContext::Help) {
        //qDebug() << "Locations matching because of" << type;
        Plasma::QueryMatch match(this);
        match.setType(Plasma::QueryMatch::ExactMatch);
        match.setText(i18n("Open %1", term));
        match.setIcon(QIcon::fromTheme(QStringLiteral("system-help")));
        match.setRelevance(1);
        match.setType(Plasma::QueryMatch::ExactMatch);
        match.setId(QStringLiteral("help"));
        context.addMatch(match);
    } else if (type == Plasma::RunnerContext::NetworkLocation || type == Plasma::RunnerContext::UnknownType) {
        const bool filtered = KUriFilter::self()->filterUri(term, QStringList() << QStringLiteral("kshorturifilter"));

        if (!filtered) {
            return;
        }

        QUrl url(term);

        if (!KProtocolInfo::isKnownProtocol(url.scheme())) {
            return;
        }

        Plasma::QueryMatch match(this);
        match.setText(i18n("Go to %1", url.toDisplayString()));
        match.setIcon(QIcon::fromTheme(KProtocolInfo::icon(url.scheme())));
        match.setData(url.url());

        if (KProtocolInfo::isHelperProtocol(url.scheme())) {
            //qDebug() << "helper protocol" << url.protocol() <<"call external application" ;
            if (url.scheme() == QLatin1String("mailto")) {
                match.setText(i18n("Send email to %1",url.path()));
            } else {
                match.setText(i18n("Launch with %1", KProtocolInfo::exec(url.scheme())));
            }
        } else {
            //qDebug() << "protocol managed by browser" << url.protocol();
            match.setText(i18n("Go to %1", url.toDisplayString()));
        }

        if (type == Plasma::RunnerContext::UnknownType) {
            match.setId(QStringLiteral("openunknown"));
            match.setRelevance(0.5);
            match.setType(Plasma::QueryMatch::PossibleMatch);
        } else {
            match.setId(QStringLiteral("opennetwork"));
            match.setRelevance(0.7);
            match.setType(Plasma::QueryMatch::ExactMatch);
        }

        context.addMatch(match);
    }
}
Exemple #23
0
void KopeteRunner::match(Plasma::RunnerContext& context)
{
    if (!m_loaded) {
        return;
    }

    const QString term = context.query().toLower();
    if (term.length() < 3) {
        return;
    }

    QList<QueryMatch> matches;

    if (term == "connect")
    {
        QueryMatch match(this);

        match.setType(QueryMatch::ExactMatch);
        match.setIcon(KIcon("user-"));
        match.setText(i18n("Set all accounts as online"));
        match.setData("connect");

        matches.append(match);
    }
    else if (term == "disconnect")
    {
        QueryMatch match(this);

        match.setType(QueryMatch::ExactMatch);
        match.setIcon(KIcon("user-offline"));
        match.setText(i18n("Set all accounts as offline"));
        match.setData("disconnect");

        matches.append(match);
    }
    else if (term.startsWith(QLatin1String("status")))
    {
        QStringList query = context.query().split(' ');
        // Take the status text
        query.takeFirst();
        if (!query.isEmpty())
        {
            // Take the status to set
            const QString status = query.takeFirst();
            if (!status.isEmpty())
            {
                QueryMatch match(this);

                match.setType(QueryMatch::ExactMatch);
                match.setIcon(KIcon("user-away"));
                match.setText(i18nc("The \': \' is used as a separator", "Status: %1", status));
                // Rejoin the status message
                const QString message = query.join(" ");
                if (!message.isEmpty())
                    match.setSubtext(i18nc("The \': \' is used as a separator", "Message: %1", message));
                match.setData("status");

                matches.append(match);
            }
        }
    }
    else if (term.startsWith(QLatin1String("message")))
    {
        QStringList query = context.query().split(' ');
        // Take the status text
        query.takeFirst();
        if (!query.isEmpty())
        {
            // Rejoin the rest of the message
            const QString message = query.join(" ");
            if (!message.isEmpty())
            {
                QueryMatch match(this);

                match.setType(QueryMatch::ExactMatch);
                match.setIcon(KIcon("im-status-message-edit"));
                match.setText(i18nc("The \': \' is used as a separator", "Message: %1", message));
                match.setData(i18n("Set Status Message"));
                match.setData("status");

                matches.append(match);
            }
        }
    }
    QHashIterator<QString, QVariantMap> i(m_contactData);
    while (i.hasNext()) {
	i.next();
        // Keep a reference for easier use
        const ContactProperties& props = i.value();
        // Skip unreachable contacts
        if (!props["message_reachable"].toBool())
            continue;

        const QString name = props["display_name"].toString();
        const QString picture = props["picture"].toString();
        const QString status = props["status"].toString();
        const QString message = props["status_message"].toString();
        if (name.contains(term, Qt::CaseInsensitive))
        {
            QueryMatch match(this);

            match.setType((name.compare(context.query(), Qt::CaseInsensitive)) ? QueryMatch::PossibleMatch : QueryMatch::ExactMatch);
            match.setIcon(KIcon(KUrl(picture).isLocalFile() ? picture : "kopete"));
            match.setText(i18n("Send message to %1", name));
            const QString statusLine = i18n("Status: %1", status);
            const QString subtext = message.isEmpty() ? statusLine : i18n("%1\nMessage: %2", statusLine, message);
            match.setSubtext(subtext);
            match.setData(i.key());

            matches.append(match);
        }
    }

    context.addMatches(term, matches);
}
void AudioPlayerControlRunner::match(Plasma::RunnerContext &context)
{
    if (context.query().length() < 3) {
        return;
    }

    const QString term = context.query();

    QList<Plasma::QueryMatch> matches;

    if (m_useCommands) {
        /* DBus paths that are used in the command executes */
        /* The data variable looks like this:
         * "/PlayerQLatin1String( " " )org.freedesktop.MediaPlayerQLatin1String( " " )PlayQLatin1String( " " )actionsQLatin1String( " " )start" args...
         * <path>    <interface>                 <method> <actions> <start player>
         * <actions> is NONE if no action is needed
         */

        QVariantList playcontrol;
        playcontrol  << QLatin1String( "/Player" ) << QLatin1String( "org.freedesktop.MediaPlayer" );

        /* The commands */

        //Play
        if (context.isValid() && m_comPlay.startsWith(term, Qt::CaseInsensitive) &&
	    (!m_running || m_songsInPlaylist)) {
            QVariantList data = playcontrol;
            data << ((currentSong() == -1) ? QLatin1String( "Next" ) : QLatin1String( "Play" )) << NONE << QLatin1String( "start" );
            matches << createMatch(this, i18n("Start playing"), i18n("Audio player control"), QLatin1String( "play" ),
                                   KIcon( QLatin1String( "media-playback-start" )), data, 1.0);
        }

        if (!context.isValid() || !m_running) {
            //The interface of the player is not availalbe, so the rest of the commands
            //is not needed
            context.addMatches(matches);
            return;
        }

        if (context.isValid() && m_songsInPlaylist) {
            //The playlist isn't empty
            //Next song
            if (m_comNext.startsWith(term,Qt::CaseInsensitive)
                    && m_nextSongAvailable) {
                QVariantList data = playcontrol;
                data << QLatin1String( "Next" ) << NONE << QLatin1String( "nostart" );
                matches << createMatch(this, i18n("Play next song"), i18n("Audio player control"),
                                       QLatin1String( "next" ), KIcon( QLatin1String( "media-skip-forward" )), data, 1.0);
            }

            //Previous song
            if (context.isValid() && m_comPrev.startsWith(term,Qt::CaseInsensitive)
                    && m_prevSongAvailable) {
                QVariantList data = playcontrol;
                data << QLatin1String( "Prev" ) << NONE << QLatin1String( "nostart" );
                matches << createMatch(this, i18n("Play previous song"), i18n("Audio player control") ,
                                       QLatin1String( "previous" ), KIcon( QLatin1String( "media-skip-backward" )), data, 1.0);
            }
        }//--- if (m_songsInPlaylist)

        //Pause
        if (context.isValid() && m_comPause.startsWith(term,Qt::CaseInsensitive)) {
            QVariantList data = playcontrol;
            data << QLatin1String( "Pause" ) << NONE << QLatin1String( "nostart" );
            matches << createMatch(this, i18n("Pause playing"), i18n("Audio player control"),
                                   QLatin1String( "pause" ), KIcon( QLatin1String( "media-playback-pause" )), data, 1.0);
        }

        //Stop
        if (context.isValid() && m_comStop.startsWith(term,Qt::CaseInsensitive)) {
            QVariantList data = playcontrol;
            data << QLatin1String( "Stop" ) << NONE << QLatin1String( "nostart" );
            matches << createMatch(this, i18n("Stop playing"), i18n("Audio player control"),
                                   QLatin1String( "stop" ), KIcon( QLatin1String( "media-playback-stop" )), data, 1.0);
        }

        //Increase
        if (context.isValid() && m_comIncrease.startsWith(term,Qt::CaseInsensitive)) {
            QVariantList data = playcontrol;
            data << QLatin1String( "VolumeUp" ) << NONE << QLatin1String( "nostart" ) << m_increaseBy;
            matches << createMatch(this, i18n("Increase volume by %1" , m_increaseBy),
                                   QLatin1String( "volumeup" ), i18n("Audio player control"), KIcon(QLatin1String( "audio-volume-high" )), data, 1.0);
        } else if (context.isValid() && equals(term, QRegExp( m_comIncrease + QLatin1String( " \\d{1,2}0{0,1}" ) ) ) ) {
            int volumeChange = getNumber(term, ' ' );
            QVariantList data = playcontrol;
            data << QLatin1String( "VolumeUp" ) << NONE << QLatin1String( "nostart" ) << volumeChange;
            matches << createMatch(this, i18n("Increase volume by %1" , volumeChange),
                                   QLatin1String( "volumeup" ), i18n("Audio player control"), KIcon(QLatin1String( "audio-volume-high" )), data, 1.0);
        }

        //Decrease
        if (context.isValid() && m_comDecrease.startsWith(term,Qt::CaseInsensitive)) {
            QVariantList data = playcontrol;
            data << QLatin1String( "VolumeDown" ) << NONE << QLatin1String( "nostart" ) << m_decreaseBy;
            matches << createMatch(this, i18n("Reduce volume by %1", m_decreaseBy),
                                   QLatin1String( "volumedown" ), i18n("Audio player control"), KIcon(QLatin1String( "audio-volume-low" )), data, 1.0);
        } else if (context.isValid() && equals(term, QRegExp( m_comDecrease + QLatin1String( " \\d{1,2}0{0,1}" ) ) ) ) {
            int volumeChange = getNumber(term, ' ');
            QVariantList data = playcontrol;
            data << QLatin1String( "VolumeDown" ) << NONE << QLatin1String( "nostart" ) << volumeChange;
            matches << createMatch(this, i18n("Reduce volume by %1", volumeChange),
                                   QLatin1String( "volumedown" ), i18n("Audio player control"), KIcon(QLatin1String( "audio-volume-low" )), data, 1.0);
        }

        //Set volume to
        if (context.isValid() && equals(term, QRegExp( m_comVolume + QLatin1String( " \\d{1,2}0{0,1}" ) ) ) ) {
            QVariantList data = playcontrol;
            int newVolume = getNumber(term , ' ');
            data << QLatin1String( "VolumeSet" ) << NONE << QLatin1String( "nostart" ) << newVolume;
            matches << createMatch(this, i18n("Set volume to %1%" , newVolume),
                                   QLatin1String( "volume" ), i18n("Audio player control"), KIcon(QLatin1String( "audio-volume-medium" )), data, 1.0);
        }

        //Mute
        if (context.isValid() && m_comMute.startsWith(term,Qt::CaseInsensitive)) {
            QVariantList data = playcontrol;
            data << QLatin1String( "Mute" ) << NONE << QLatin1String( "nostart" );
            matches << createMatch(this, i18n("Mute"), i18n("Audio player control"),
                                   QLatin1String( "mute" ), KIcon( QLatin1String( "audio-volume-muted" )), data, 1.0);
        }

        //Quit player
        if (context.isValid() && m_comQuit.startsWith(term,Qt::CaseInsensitive)) {
            QVariantList data;
            data  << QLatin1String( "/" ) << QLatin1String( "org.freedesktop.MediaPlayer" ) << QLatin1String( "Quit" ) << NONE
            << QLatin1String( "nostart" );
            matches << createMatch(this, i18n("Quit %1", m_player),QLatin1String( "" ),
                                   QLatin1String( "quit" ), KIcon( QLatin1String( "application-exit" )), data, 1.0);
        }
    }//--- if (m_useCommands)

    if (context.isValid() && m_searchCollection) {
        QString actionNames;
        QString searchTerm = term;
        QString command;

        if (term.startsWith(m_comPlay,Qt::CaseInsensitive)
                && term.length() > m_comPlay.length()) {
            command = m_comPlay;
            actionNames = PLAY;
        } else if (term.startsWith(m_comAppend, Qt::CaseInsensitive)
                   && term.length() > m_comAppend.length()) {
            command = m_comAppend;
            actionNames = APPEND;
        } else if (term.startsWith(m_comQueue, Qt::CaseInsensitive)
                   && term.length() > m_comQueue.length()) {
            command = m_comQueue;
            actionNames = QUEUE;
        } else {
            actionNames = QString::fromLatin1( "%1,%2,%3").arg(PLAY).arg(APPEND).arg(QUEUE);
        }

	if (!context.isValid())
	{
	    return;
	}
        searchTerm = searchTerm.right(searchTerm.length() - (command.length() + 1));
        matches << searchCollectionFor(searchTerm, actionNames);
        //Adds matches for all song matches for term
    }

    context.addMatches(matches);
}