Пример #1
0
void ColorScheme::writeColorEntry(KConfig& config , int index) const
{
    KConfigGroup configGroup = config.group(colorNameForIndex(index));

    const ColorEntry& entry = colorTable()[index];

    configGroup.writeEntry("Color", entry.color);
    if (configGroup.hasKey("Transparent")) {
        configGroup.deleteEntry("Transparent");
    }
    if (configGroup.hasKey("Transparency")) {
        configGroup.deleteEntry("Transparency");
    }
    if (entry.fontWeight != ColorEntry::UseCurrentFormat) {
        configGroup.writeEntry("Bold", entry.fontWeight == ColorEntry::Bold);
    }

    RandomizationRange random = _randomTable != 0 ? _randomTable[index] : RandomizationRange();

    // record randomization if this color has randomization or
    // if one of the keys already exists
    if (!random.isNull() || configGroup.hasKey("MaxRandomHue")) {
        configGroup.writeEntry("MaxRandomHue", static_cast<int>(random.hue));
        configGroup.writeEntry("MaxRandomValue", static_cast<int>(random.value));
        configGroup.writeEntry("MaxRandomSaturation", static_cast<int>(random.saturation));
    }
}
Пример #2
0
void AkuViewOptionWidget::restoreDefaults()
{
    KConfigGroup viewOptionConfig = KGlobal::config()->group("Views Option");

    viewOptionConfig.deleteEntry("Active View");
    viewOptionConfig.deleteEntry("IconView item size");

    loadSettings();
}
Пример #3
0
void Clock::clockConfigChanged()
{
    KConfigGroup cg = config();
    m_showTimezone = cg.readEntry("showTimezone", !isLocalTimezone());

    kDebug() << "showTimezone:" << m_showTimezone;

    if (cg.hasKey("showDate")) {    //legacy config entry as of 2011-1-4
        m_dateStyle = cg.readEntry("showDate", false) ? 2 : 0; //short date : no date
        cg.deleteEntry("showDate");
    }
    else {
        m_dateStyle = cg.readEntry("dateStyle", 0);
    }

    if (cg.hasKey("showYear")) {   //legacy config entry as of 2011-1-4
        if( m_dateStyle ) {
            m_dateStyle = cg.readEntry("showYear", false) ? 2 : 1; //short date : compact date
        }
        cg.deleteEntry("showYear");
    }

    m_showSeconds = cg.readEntry("showSeconds", false);
    if (m_showSeconds) {
        //We don't need to cache the applet if it update every seconds
        setCacheMode(QGraphicsItem::NoCache);
    } else {
        setCacheMode(QGraphicsItem::DeviceCoordinateCache);
    }

    QFont f = cg.readEntry("plainClockFont", m_plainClockFont);
    m_isDefaultFont = f == m_plainClockFont;
    m_plainClockFont = f;

    m_useCustomColor = cg.readEntry("useCustomColor", m_useCustomColor);
    m_plainClockColor = cg.readEntry("plainClockColor", m_plainClockColor);
    m_useCustomShadowColor = cg.readEntry("useCustomShadowColor", m_useCustomShadowColor);
    m_plainClockShadowColor = cg.readEntry("plainClockShadowColor", m_plainClockShadowColor);
    m_drawShadow = cg.readEntry("plainClockDrawShadow", m_drawShadow);

    updateColors();

    if (m_useCustomColor) {
        m_pixmap = QPixmap();
        delete m_svg;
        m_svg = 0;
    }

    const QFontMetricsF metrics(KGlobalSettings::smallestReadableFont());
    const QString timeString = KGlobal::locale()->formatTime(QTime(23, 59), m_showSeconds);
    setMinimumSize(metrics.size(Qt::TextSingleLine, timeString));

    if (isUserConfiguring()) {
        updateSize();
    }
}
Пример #4
0
void Koushin_TownEditor::Editor::fieldClicked(Koushin_TownEditor::EditorField* field)
{
  int x = field->boundingRect().topLeft().x() / m_fieldSize;
  int y = field->boundingRect().topLeft().y() / m_fieldSize;
  QString xString = QString("%1").arg(QString::number(x), 3, QLatin1Char('0'));
  QString yString = QString("%1").arg(QString::number(y), 3, QLatin1Char('0'));
  kDebug() << "Field clicked at " << xString << "," << yString;
  if(m_type == "plainField")
    field->setBrush(QBrush(Qt::white));
  if(m_type == "fieldWithForest")
    field->setBrush(QBrush(Qt::green));
  if(m_type == "fieldWithRocks")
    field->setBrush(QBrush(Qt::black));
  if(m_type == "fieldWithWater")
    field->setBrush(QBrush(Qt::blue));
  if(m_type == "fieldNotUsable")
    field->setBrush(QBrush(Qt::yellow));
  field->update(field->boundingRect());
  if(m_config) {
    foreach(QString groupName, m_fieldTypes) {
      if(groupName == m_type) {
	KConfigGroup group = m_config->group(groupName);
	group.writeEntry("field"+xString+yString, QString::number(x) + "," + QString::number(y));
	group.config()->sync();
      } else {
	KConfigGroup group = m_config->group(groupName);
	group.deleteEntry("field"+xString+yString);
	group.config()->sync();
      }
    }
  }
}
Пример #5
0
void CheckIndexingManager::indexingFinished(qint64 index, bool reindexCollection)
{
    if (index != -1) {
        if (!mCollectionsIndexed.contains(index)) {
            mCollectionsIndexed.append(index);
        }
    }
    if (reindexCollection) {
        if (!mCollectionsNeedToBeReIndexed.contains(index)) {
            mCollectionsNeedToBeReIndexed.append(index);
        }
        if (mCollectionsNeedToBeReIndexed.count() > 30) {
            callToReindexCollection();
            mCollectionsNeedToBeReIndexed.clear();
        }
    }
    mIndex++;
    if (mIndex < mListCollection.count()) {
        mTimer->start();
    } else {
        mIsReady = true;
        mIndex = 0;
        callToReindexCollection();
        mListCollection.clear();
        mCollectionsNeedToBeReIndexed.clear();

        const KSharedConfig::Ptr cfg = KSharedConfig::openConfig(QStringLiteral("kmailsearchindexingrc"));
        KConfigGroup grp = cfg->group(QStringLiteral("General"));
        grp.writeEntry(QStringLiteral("lastCheck"), QDateTime::currentDateTime());
        grp.deleteEntry(QStringLiteral("collectionsIndexed"));
        grp.sync();
    }
}
Пример #6
0
void
MountPointManager::handleMusicLocation()
{
    // For users who were using QDesktopServices::MusicLocation exclusively up
    // to v2.2.2, which did not store the location into config.
    // and also for versions up to 2.7-git that did wrote the Use MusicLocation entry

    KConfigGroup folders = Amarok::config( "Collection Folders" );
    const QString entryKey( "Use MusicLocation" );
    if( !folders.hasKey( entryKey ) )
        return; // good, already solved, nothing to do

    // write the music location as another collection folder in this case
    if( folders.readEntry( entryKey, false ) )
    {
        const KUrl musicUrl = QDesktopServices::storageLocation( QDesktopServices::MusicLocation );
        const QString musicDir = musicUrl.toLocalFile( KUrl::RemoveTrailingSlash );
        const QDir dir( musicDir );
        if( dir.exists() && dir.isReadable() )
        {
            QStringList currentFolders = collectionFolders();
            if( !currentFolders.contains( musicDir ) )
                setCollectionFolders( currentFolders << musicDir );
        }
    }

    folders.deleteEntry( entryKey ); // get rid of it for good
}
Пример #7
0
void FbWindow::writeSettings()
{
    KConfig config("kipirc");
    KConfigGroup grp = config.group("Facebook Settings");
    grp.writeEntry("Access Token",    m_accessToken);

    /* If we have both access token and session key, then we have just converted one into the other. */
    if (! m_accessToken.isEmpty())
    {
        if (! m_sessionKey.isEmpty())
        {
            grp.deleteEntry("Session Key");
        }

        if (! m_sessionSecret.isEmpty())
        {
            grp.deleteEntry("Session Secret");
        }
    }

    // If the access token has not been obtained, leave the values as they are.
    /*
    else
    {
        grp.writeEntry("Session Key",     m_sessionKey);
        grp.writeEntry("Session Secret",  m_sessionSecret);
    }
    */
    grp.writeEntry("Session Expires", m_sessionExpires);
    grp.writeEntry("Current Album",   m_currentAlbumID);
    grp.writeEntry("Resize",          m_widget->m_resizeChB->isChecked());
    grp.writeEntry("Maximum Width",   m_widget->m_dimensionSpB->value());
    grp.writeEntry("Image Quality",   m_widget->m_imageQualitySpB->value());

    if (m_import)
    {
        KConfigGroup dialogGroup = config.group("Facebook Import Dialog");
        saveDialogSize(dialogGroup);
    }
    else
    {
        KConfigGroup dialogGroup = config.group("Facebook Export Dialog");
        saveDialogSize(dialogGroup);
    }

    config.sync();
}
Пример #8
0
Файл: rules.cpp Проект: KDE/kwin
void Rules::write(KConfigGroup& cfg) const
{
    cfg.writeEntry("Description", description);
    // always write wmclass
    WRITE_MATCH_STRING(wmclass, true);
    cfg.writeEntry("wmclasscomplete", wmclasscomplete);
    WRITE_MATCH_STRING(windowrole, false);
    WRITE_MATCH_STRING(title, false);
    WRITE_MATCH_STRING(clientmachine, false);
    if (types != NET::AllTypesMask)
        cfg.writeEntry("types", uint(types));
    else
        cfg.deleteEntry("types");
    WRITE_FORCE_RULE(placement, Placement::policyToString);
    WRITE_SET_RULE(position,);
    WRITE_SET_RULE(size,);
    WRITE_FORCE_RULE(minsize,);
    WRITE_FORCE_RULE(maxsize,);
    WRITE_FORCE_RULE(opacityactive,);
    WRITE_FORCE_RULE(opacityinactive,);
    WRITE_SET_RULE(ignoregeometry,);
    WRITE_SET_RULE(desktop,);
    WRITE_SET_RULE(screen,);
    WRITE_SET_RULE(activity,);
    WRITE_FORCE_RULE(type, int);
    WRITE_SET_RULE(maximizevert,);
    WRITE_SET_RULE(maximizehoriz,);
    WRITE_SET_RULE(minimize,);
    WRITE_SET_RULE(shade,);
    WRITE_SET_RULE(skiptaskbar,);
    WRITE_SET_RULE(skippager,);
    WRITE_SET_RULE(skipswitcher,);
    WRITE_SET_RULE(above,);
    WRITE_SET_RULE(below,);
    WRITE_SET_RULE(fullscreen,);
    WRITE_SET_RULE(noborder,);
    auto colorToString = [](const QString &value) -> QString {
        if (value.endsWith(QLatin1String(".colors"))) {
            return QFileInfo(value).baseName();
        } else {
            return value;
        }
    };
    WRITE_FORCE_RULE(decocolor, colorToString);
    WRITE_FORCE_RULE(blockcompositing,);
    WRITE_FORCE_RULE(fsplevel,);
    WRITE_FORCE_RULE(fpplevel,);
    WRITE_FORCE_RULE(acceptfocus,);
    WRITE_FORCE_RULE(closeable,);
    WRITE_FORCE_RULE(autogroup,);
    WRITE_FORCE_RULE(autogroupfg,);
    WRITE_FORCE_RULE(autogroupid,);
    WRITE_FORCE_RULE(strictgeometry,);
    WRITE_SET_RULE(shortcut,);
    WRITE_FORCE_RULE(disableglobalshortcuts,);
}
Пример #9
0
void DesktopThemeDetails::setDesktopTheme(QString themeRoot)
{
    KConfig config(QStandardPaths::locate(QStandardPaths::ConfigLocation, "plasmarc"));
    KConfigGroup cg = KConfigGroup(&config, "Theme");
    if (themeRoot == "default") {
        cg.deleteEntry("name");
    } else {
        cg.writeEntry("name", themeRoot);
    }
    cg.sync();
}
Пример #10
0
void removeOverrideBuildDirIndex( KDevelop::IProject* project, bool writeToMainIndex )
{
    KConfigGroup baseGrp = baseGroup(project);

    if( !baseGrp.hasKey(Config::buildDirOverrideIndexKey) )
        return;
    if( writeToMainIndex )
        baseGrp.writeEntry( Config::buildDirIndexKey, baseGrp.readEntry(Config::buildDirOverrideIndexKey) );

    baseGrp.deleteEntry(Config::buildDirOverrideIndexKey);
}
Пример #11
0
void AlarmResource::writeConfig(KConfigGroup& group)
{
	group.writeEntry("AlarmType", static_cast<int>(mType));
	if (mColour.isValid())
		group.writeEntry("Color", mColour);
	else
		group.deleteEntry("Color");
	group.writeEntry("Standard", mStandard);
	ResourceCached::writeConfig(group);
	ResourceCalendar::writeConfig(group);
}
Пример #12
0
void BasicTab::apply()
{
    if (_menuEntryInfo)
    {
        _menuEntryInfo->setDirty();
        _menuEntryInfo->setCaption(_nameEdit->text());
        _menuEntryInfo->setDescription(_descriptionEdit->text());
        _menuEntryInfo->setIcon(_iconButton->icon());

        KDesktopFile *df = _menuEntryInfo->desktopFile();
        KConfigGroup dg = df->desktopGroup();
        dg.writeEntry("Comment", _commentEdit->text());
        if (_systrayCB->isChecked())
          dg.writeEntry("Exec", _execEdit->lineEdit()->text().prepend("ksystraycmd "));
        else
          dg.writeEntry("Exec", _execEdit->lineEdit()->text());

        dg.writePathEntry("Path", _pathEdit->lineEdit()->text());

        if (_terminalCB->isChecked())
            dg.writeEntry("Terminal", 1);
        else
            dg.writeEntry("Terminal", 0);

        dg.writeEntry("TerminalOptions", _termOptEdit->text());
        dg.writeEntry("X-KDE-SubstituteUID", _uidCB->isChecked());
        dg.writeEntry("X-KDE-Username", _uidEdit->text());
        dg.writeEntry("StartupNotify", _launchCB->isChecked());
        dg.writeEntry( "NoDisplay", _hiddenEntryCB->isChecked() );

        QStringList onlyShowIn = df->desktopGroup().readXdgListEntry("OnlyShowIn");
        /* the exact semantics of this checkbox are unclear if there is more than just KDE in the list...
         * For example: - The list is "Gnome;", the user enables "Only show in KDE" - should we remove Gnome?
         *              - The list is "Gnome;KDE;", the user unchecks the box - should we keep Gnome?
         */
        if ( _onlyShowInKdeCB->isChecked() && !onlyShowIn.contains("KDE"))
            onlyShowIn << "KDE";
        else if ( !_onlyShowInKdeCB->isChecked() && onlyShowIn.contains("KDE"))
            onlyShowIn.removeAll("KDE");
        if (onlyShowIn.isEmpty())
            dg.deleteEntry("OnlyShowIn");
        else
            dg.writeXdgListEntry("OnlyShowIn", onlyShowIn);
    }
    else
    {
        _menuFolderInfo->setCaption(_nameEdit->text());
        _menuFolderInfo->setGenericName(_descriptionEdit->text());
        _menuFolderInfo->setComment(_commentEdit->text());
        _menuFolderInfo->setIcon(_iconButton->icon());
    }
}
Пример #13
0
void KMFolder::writeConfig( KConfigGroup & configGroup ) const
{
  // KConfigGroup configGroup(config, "");
  configGroup.writeEntry("SystemLabel", mSystemLabel);
  configGroup.writeEntry("ExpireMessages", mExpireMessages);
  configGroup.writeEntry("ReadExpireAge", mReadExpireAge);
  configGroup.writeEntry("ReadExpireUnits", (int)mReadExpireUnits);
  configGroup.writeEntry("UnreadExpireAge", mUnreadExpireAge);
  configGroup.writeEntry("UnreadExpireUnits", (int)mUnreadExpireUnits);
  configGroup.writeEntry("ExpireAction", mExpireAction == ExpireDelete ? "Delete" : "Move");
  configGroup.writeEntry("ExpireToFolder", mExpireToFolderId);

  configGroup.writeEntry("UseCustomIcons", mUseCustomIcons);
  configGroup.writeEntry("NormalIconPath", mNormalIconPath);
  configGroup.writeEntry("UnreadIconPath", mUnreadIconPath);

  configGroup.writeEntry("MailingListEnabled", mMailingListEnabled);
  mMailingList.writeConfig( configGroup );


  configGroup.writeEntry( "UseDefaultIdentity", mUseDefaultIdentity );
  if ( !mUseDefaultIdentity && ( !mStorage || !mStorage->account() ||
                           mIdentity != mStorage->account()->identityId() ) )
      configGroup.writeEntry("Identity", mIdentity);
  else
      configGroup.deleteEntry("Identity");

  configGroup.writeEntry("WhoField", mUserWhoField);
  configGroup.writeEntry("Id", mId);
  configGroup.writeEntry( "PutRepliesInSameFolder", mPutRepliesInSameFolder );
  configGroup.writeEntry( "HideInSelectionDialog", mHideInSelectionDialog );
  configGroup.writeEntry( "IgnoreNewMail", mIgnoreNewMail );
  if ( !mShortcut.isEmpty() )
    configGroup.writeEntry( "Shortcut", mShortcut.toString() );
  else
    configGroup.deleteEntry( "Shortcut" );
}
Пример #14
0
void attemptMigrate( KDevelop::IProject* project )
{
    if ( !baseGroup(project).hasKey( Config::Old::projectBuildDirs ) )
    {
        qCDebug(CMAKE) << "CMake settings migration: already done, exiting";
        return;
    }

    KConfigGroup baseGrp = baseGroup(project);

    KDevelop::Path buildDir( baseGrp.readEntry( Config::Old::currentBuildDirKey, QString() ) );
    int buildDirIndex = -1;
    const QStringList existingBuildDirs = baseGrp.readEntry( Config::Old::projectBuildDirs, QStringList() );
    {
        // also, find current build directory in this list (we need an index, not path)
        QString currentBuildDirCanonicalPath = QDir( buildDir.toLocalFile() ).canonicalPath();

        for( int i = 0; i < existingBuildDirs.count(); ++i )
        {
            const QString& nextBuildDir = existingBuildDirs.at(i);
            if( QDir(nextBuildDir).canonicalPath() == currentBuildDirCanonicalPath )
            {
                buildDirIndex = i;
            }
        }
    }
    int buildDirsCount = existingBuildDirs.count();

    qCDebug(CMAKE) << "CMake settings migration: existing build directories" << existingBuildDirs;
    qCDebug(CMAKE) << "CMake settings migration: build directory count" << buildDirsCount;
    qCDebug(CMAKE) << "CMake settings migration: current build directory" << buildDir << "(index" << buildDirIndex << ")";

    baseGrp.writeEntry( Config::buildDirCountKey, buildDirsCount );
    baseGrp.writeEntry( Config::buildDirIndexKey, buildDirIndex );

    for (int i = 0; i < buildDirsCount; ++i)
    {
        qCDebug(CMAKE) << "CMake settings migration: writing group" << i << ": path" << existingBuildDirs.at(i);

        KConfigGroup buildDirGrp = buildDirGroup( project, i );
        buildDirGrp.writeEntry( Config::Specific::buildDirPathKey, existingBuildDirs.at(i) );
    }

    baseGrp.deleteEntry( Config::Old::currentBuildDirKey );
    baseGrp.deleteEntry( Config::Old::currentCMakeBinaryKey );
    baseGrp.deleteEntry( Config::Old::currentBuildTypeKey );
    baseGrp.deleteEntry( Config::Old::currentInstallDirKey );
    baseGrp.deleteEntry( Config::Old::currentEnvironmentKey );
    baseGrp.deleteEntry( Config::Old::currentExtraArgumentsKey );
    baseGrp.deleteEntry( Config::Old::projectBuildDirs );
}
Пример #15
0
bool ClearAllCookiesPoliciesAction::action()
{
   // load the config file and section
   KConfig cfg(QLatin1String( "kcookiejarrc" ));
   KConfigGroup group = cfg.group("Cookie Policy");

   kDebug() << "removing all saved cookie policies" ;
   group.deleteEntry("CookieDomainAdvice");
   cfg.sync();

   // inform the cookie jar we pillaged it
   QDBusInterface kcookiejar(QLatin1String( "org.kde.kded" ), QLatin1String( "/modules/kcookiejar" ), QLatin1String( "org.kde.KCookieServer" ));
   QDBusReply<void> reply = kcookiejar.call(QLatin1String( "reloadPolicy" ));

   return reply.isValid();
}
Пример #16
0
void SearchTextBar::doSaveState()
{
    KConfigGroup group = getConfigGroup();

    if (completer()->completionMode() != QCompleter::PopupCompletion)
    {
        group.writeEntry(entryName(d->optionAutoCompletionModeEntry), (int)completer()->completionMode());
    }
    else
    {
        group.deleteEntry(entryName(d->optionAutoCompletionModeEntry));
    }

    group.writeEntry(entryName(d->optionCaseSensitiveEntry), (int)d->settings.caseSensitive);
    group.sync();
}
Пример #17
0
void Rules::write(KConfigGroup& cfg) const
{
    cfg.writeEntry("Description", description);
    // always write wmclass
    WRITE_MATCH_STRING(wmclass, (const char*), true);
    cfg.writeEntry("wmclasscomplete", wmclasscomplete);
    WRITE_MATCH_STRING(windowrole, (const char*), false);
    WRITE_MATCH_STRING(title, , false);
    WRITE_MATCH_STRING(clientmachine, (const char*), false);
    if (types != NET::AllTypesMask)
        cfg.writeEntry("types", uint(types));
    else
        cfg.deleteEntry("types");
    WRITE_FORCE_RULE(placement, Placement::policyToString);
    WRITE_SET_RULE(position,);
    WRITE_SET_RULE(size,);
    WRITE_FORCE_RULE(minsize,);
    WRITE_FORCE_RULE(maxsize,);
    WRITE_FORCE_RULE(opacityactive,);
    WRITE_FORCE_RULE(opacityinactive,);
    WRITE_FORCE_RULE(tilingoption,);
    WRITE_FORCE_RULE(ignoreposition,);
    WRITE_SET_RULE(desktop,);
    WRITE_SET_RULE(activity,);
    WRITE_FORCE_RULE(type, int);
    WRITE_SET_RULE(maximizevert,);
    WRITE_SET_RULE(maximizehoriz,);
    WRITE_SET_RULE(minimize,);
    WRITE_SET_RULE(shade,);
    WRITE_SET_RULE(skiptaskbar,);
    WRITE_SET_RULE(skippager,);
    WRITE_SET_RULE(skipswitcher,);
    WRITE_SET_RULE(above,);
    WRITE_SET_RULE(below,);
    WRITE_SET_RULE(fullscreen,);
    WRITE_SET_RULE(noborder,);
    WRITE_FORCE_RULE(blockcompositing,);
    WRITE_FORCE_RULE(fsplevel,);
    WRITE_FORCE_RULE(acceptfocus,);
    WRITE_FORCE_RULE(closeable,);
    WRITE_FORCE_RULE(autogroup,);
    WRITE_FORCE_RULE(autogroupfg,);
    WRITE_FORCE_RULE(autogroupid,);
    WRITE_FORCE_RULE(strictgeometry,);
    WRITE_SET_RULE(shortcut,);
    WRITE_FORCE_RULE(disableglobalshortcuts,);
}
Пример #18
0
void ResourceKolab::fromKMailDelSubresource( const QString& type,
                                             const QString& subResource )
{
  kDebug(5500) <<"ResourceKolab::fromKMailDelSubresource(" << type <<"," << subResource
	                  << ")";
  if ( type != configGroupName )
    // Not ours
    return;

  if ( !mSubResources.contains( subResource ) )
    // Not registered
    return;

  // Ok, it's our job, and we have it here
  mSubResources.remove( subResource );

  KConfig config( configFile() );
  KConfigGroup group = config.group( configGroupName );
  group.deleteEntry( subResource );
  group.sync();

  // Make a list of all uids to remove
  Kolab::UidMap::ConstIterator mapIt;
  QStringList uids;
  for ( mapIt = mUidMap.constBegin(); mapIt != mUidMap.constEnd(); ++mapIt )
    if ( mapIt.value().resource() == subResource )
      // We have a match
      uids << mapIt.key();

  // Finally delete all the incidences
  if ( !uids.isEmpty() ) {
    const bool silent = mSilent;
    mSilent = true;
    QStringList::ConstIterator it;
    for ( it = uids.constBegin(); it != uids.constEnd(); ++it ) {
      KCal::Journal* j = mCalendar.journal( *it );
      if( j )
        deleteNote( j );
    }
    mSilent = silent;
  }

  emit signalSubresourceRemoved( this, type, subResource );
}
Пример #19
0
void VkontakteWindow::writeSettings()
{
    KConfig config(QString::fromLatin1("kipirc"));
    KConfigGroup grp = config.group("VKontakte Settings");

    grp.writeEntry("VkAppId", m_appId);

    if (!m_vkapi->accessToken().isEmpty())
        grp.writeEntry("AccessToken", m_vkapi->accessToken());

    int aid = 0;
    if (!m_albumsBox->getCurrentAlbumId(aid))
    {
        grp.deleteEntry("SelectedAlbumId");
    }
    else
    {
        grp.writeEntry("SelectedAlbumId", aid);
    }
}
Пример #20
0
void KonfUpdate::gotScript(const QString &_script)
{
    QString script, interpreter;
    int i = _script.indexOf(',');
    if (i == -1) {
        script = _script.trimmed();
    } else {
        script = _script.left(i).trimmed();
        interpreter = _script.mid(i + 1).trimmed();
    }


    if (script.isEmpty()) {
        logFileError() << "Script fails to specify filename";
        m_skip = true;
        return;
    }



    QString path = KStandardDirs::locate("data", "kconf_update/" + script);
    if (path.isEmpty()) {
        if (interpreter.isEmpty()) {
            path = KStandardDirs::locate("lib", "kconf_update_bin/" + script);
        }

        if (path.isEmpty()) {
            logFileError() << "Script '" << script << "' not found" << endl;
            m_skip = true;
            return;
        }
    }

    if (!m_arguments.isNull()) {
        log() << m_currentFilename << ": Running script '" << script << "' with arguments '" << m_arguments << "'" << endl;
    } else {
        log() << m_currentFilename << ": Running script '" << script << "'" << endl;
    }

    QString cmd;
    if (interpreter.isEmpty()) {
        cmd = path;
    } else {
        cmd = interpreter + ' ' + path;
    }

    if (!m_arguments.isNull()) {
        cmd += ' ';
        cmd += m_arguments;
    }

    KTemporaryFile scriptIn;
    scriptIn.open();
    KTemporaryFile scriptOut;
    scriptOut.open();
    KTemporaryFile scriptErr;
    scriptErr.open();

    int result;
    if (m_oldConfig1) {
        if (m_debug) {
            scriptIn.setAutoRemove(false);
            log() << "Script input stored in " << scriptIn.fileName() << endl;
        }
        KConfig cfg(scriptIn.fileName(), KConfig::SimpleConfig);

        if (m_oldGroup.isEmpty()) {
            // Write all entries to tmpFile;
            const QStringList grpList = m_oldConfig1->groupList();
            for (QStringList::ConstIterator it = grpList.begin();
                    it != grpList.end();
                    ++it) {
                copyGroup(m_oldConfig1, *it, &cfg, *it);
            }
        } else {
            KConfigGroup cg1 = KConfigUtils::openGroup(m_oldConfig1, m_oldGroup);
            KConfigGroup cg2(&cfg, QString());
            copyGroup(cg1, cg2);
        }
        cfg.sync();
#ifndef _WIN32_WCE
        result = system(QFile::encodeName(QString("%1 < %2 > %3 2> %4").arg(cmd, scriptIn.fileName(), scriptOut.fileName(), scriptErr.fileName())));
#else
        QString path_ = QDir::convertSeparators ( QFileInfo ( cmd ).absoluteFilePath() );
        QString file_ = QFileInfo ( cmd ).fileName();
        SHELLEXECUTEINFO execInfo;
        memset ( &execInfo,0,sizeof ( execInfo ) );
        execInfo.cbSize = sizeof ( execInfo );
        execInfo.fMask =  SEE_MASK_FLAG_NO_UI;
        execInfo.lpVerb = L"open";
        execInfo.lpFile = (LPCWSTR) path_.utf16();
        execInfo.lpDirectory = (LPCWSTR) file_.utf16();
        execInfo.lpParameters = (LPCWSTR) QString(" < %1 > %2 2> %3").arg( scriptIn.fileName(), scriptOut.fileName(), scriptErr.fileName()).utf16();
        result = ShellExecuteEx ( &execInfo );
        if (result != 0)
        {
            result = 0;
        }
        else
        {
            result = -1;
        }
#endif
    } else {
        // No config file
#ifndef _WIN32_WCE
        result = system(QFile::encodeName(QString("%1 2> %2").arg(cmd, scriptErr.fileName())));
#else
        QString path_ = QDir::convertSeparators ( QFileInfo ( cmd ).absoluteFilePath() );
        QString file_ = QFileInfo ( cmd ).fileName();
        SHELLEXECUTEINFO execInfo;
        memset ( &execInfo,0,sizeof ( execInfo ) );
        execInfo.cbSize = sizeof ( execInfo );
        execInfo.fMask =  SEE_MASK_FLAG_NO_UI;
        execInfo.lpVerb = L"open";
        execInfo.lpFile = (LPCWSTR) path_.utf16();
        execInfo.lpDirectory = (LPCWSTR) file_.utf16();
        execInfo.lpParameters = (LPCWSTR) QString(" 2> %1").arg( scriptErr.fileName()).utf16();
        result = ShellExecuteEx ( &execInfo );
        if (result != 0)
        {
            result = 0;
        }
        else
        {
            result = -1;
        }
#endif
    }

    // Copy script stderr to log file
    {
        QFile output(scriptErr.fileName());
        if (output.open(QIODevice::ReadOnly)) {
            QTextStream ts(&output);
            ts.setCodec(QTextCodec::codecForName("UTF-8"));
            while (!ts.atEnd()) {
                QString line = ts.readLine();
                log() << "[Script] " << line << endl;
            }
        }
    }

    if (result) {
        log() << m_currentFilename << ": !! An error occurred while running '" << cmd << "'" << endl;
        return;
    }

    if (!m_oldConfig1) {
        return; // Nothing to merge
    }

    if (m_debug) {
        scriptOut.setAutoRemove(false);
        log() << "Script output stored in " << scriptOut.fileName() << endl;
    }

    // Deleting old entries
    {
        QStringList group = m_oldGroup;
        QFile output(scriptOut.fileName());
        if (output.open(QIODevice::ReadOnly)) {
            QTextStream ts(&output);
            ts.setCodec(QTextCodec::codecForName("UTF-8"));
            while (!ts.atEnd()) {
                QString line = ts.readLine();
                if (line.startsWith('[')) {
                    group = parseGroupString(line);
                } else if (line.startsWith(QLatin1String("# DELETE "))) {
                    QString key = line.mid(9);
                    if (key[0] == '[') {
                        int j = key.lastIndexOf(']') + 1;
                        if (j > 0) {
                            group = parseGroupString(key.left(j));
                            key = key.mid(j);
                        }
                    }
                    KConfigGroup cg = KConfigUtils::openGroup(m_oldConfig2, group);
                    cg.deleteEntry(key);
                    log() << m_currentFilename << ": Script removes " << m_oldFile << ":" << group << ":" << key << endl;
                    /*if (m_oldConfig2->deleteGroup(group, KConfig::Normal)) { // Delete group if empty.
                       log() << m_currentFilename << ": Removing empty group " << m_oldFile << ":" << group << endl;
                    } (this should be automatic)*/
                } else if (line.startsWith(QLatin1String("# DELETEGROUP"))) {
                    QString str = line.mid(13).trimmed();
                    if (!str.isEmpty()) {
                        group = parseGroupString(str);
                    }
                    KConfigGroup cg = KConfigUtils::openGroup(m_oldConfig2, group);
                    cg.deleteGroup();
                    log() << m_currentFilename << ": Script removes group " << m_oldFile << ":" << group << endl;
                }
            }
        }
    }

    // Merging in new entries.
    KConfig scriptOutConfig(scriptOut.fileName(), KConfig::NoGlobals);
    if (m_newGroup.isEmpty()) {
        // Copy "default" keys as members of "default" keys
        copyGroup(&scriptOutConfig, QString(), m_newConfig, QString());
    } else {
        // Copy default keys as members of m_newGroup
        KConfigGroup srcCg = KConfigUtils::openGroup(&scriptOutConfig, QStringList());
        KConfigGroup dstCg = KConfigUtils::openGroup(m_newConfig, m_newGroup);
        copyGroup(srcCg, dstCg);
    }
    Q_FOREACH(const QString &group, scriptOutConfig.groupList()) {
        copyGroup(&scriptOutConfig, group, m_newConfig, group);
    }
}
Пример #21
0
MainWindow::MainWindow()
    : KXmlGuiWindow()
    , _bookmarkHandler(0)
    , _pluggedController(0)
    , _menuBarInitialVisibility(true)
    , _menuBarInitialVisibilityApplied(false)
{
    if (!KonsoleSettings::saveGeometryOnExit()) {
        // If we are not using the global Konsole save geometry on exit,
        // remove all Height and Width from [MainWindow] from konsolerc
        // Each screen resolution will have entries (Width 1280=619)
        KSharedConfigPtr konsoleConfig = KSharedConfig::openConfig("konsolerc");
        KConfigGroup group = konsoleConfig->group("MainWindow");
        QMap<QString, QString> configEntries = group.entryMap();
        QMapIterator<QString, QString> i(configEntries);
        while (i.hasNext()) {
            i.next();
            if (i.key().startsWith(QLatin1String("Width"))
                    || i.key().startsWith(QLatin1String("Height"))) {
                group.deleteEntry(i.key());
            }
        }
    }

    if (useTransparency()) {
        // It is useful to have translucent terminal area
        setAttribute(Qt::WA_TranslucentBackground, true);
        // But it is mostly annoying to have translucent menubar and tabbar
        setAttribute(Qt::WA_NoSystemBackground, false);
    }

    // create actions for menus
    setupActions();

    // create view manager
    _viewManager = new ViewManager(this, actionCollection());
    connect(_viewManager, SIGNAL(empty()), this, SLOT(close()));
    connect(_viewManager, SIGNAL(activeViewChanged(SessionController*)), this,
            SLOT(activeViewChanged(SessionController*)));
    connect(_viewManager, SIGNAL(unplugController(SessionController*)), this,
            SLOT(disconnectController(SessionController*)));
    connect(_viewManager, SIGNAL(viewPropertiesChanged(QList<ViewProperties*>)),
            bookmarkHandler(), SLOT(setViews(QList<ViewProperties*>)));

    connect(_viewManager, SIGNAL(updateWindowIcon()), this,
            SLOT(updateWindowIcon()));
    connect(_viewManager, SIGNAL(newViewRequest(Profile::Ptr)),
            this, SLOT(newFromProfile(Profile::Ptr)));
    connect(_viewManager, SIGNAL(newViewRequest()),
            this, SLOT(newTab()));
    connect(_viewManager, SIGNAL(viewDetached(Session*)),
            this, SIGNAL(viewDetached(Session*)));

    // create the main widget
    setupMainWidget();

    // disable automatically generated accelerators in top-level
    // menu items - to avoid conflicting with Alt+[Letter] shortcuts
    // in terminal applications
    KAcceleratorManager::setNoAccel(menuBar());

    // create menus
    createGUI();

    // remember the original menu accelerators for later use
    rememberMenuAccelerators();

    // replace standard shortcuts which cannot be used in a terminal
    // emulator (as they are reserved for use by terminal applications)
    correctStandardShortcuts();

    setProfileList(new ProfileList(true, this));

    // this must come at the end
    applyKonsoleSettings();
    connect(KonsoleSettings::self(), SIGNAL(configChanged()), this, SLOT(applyKonsoleSettings()));
}
Пример #22
0
void UserAgentDlg::save()
{
    Q_ASSERT (m_config);

    // Put all the groups except the default into the delete list.
    QStringList deleteList = m_config->groupList();

    //Remove all the groups that DO NOT contain a "UserAgent" entry...
    QStringList::ConstIterator endIt = deleteList.constEnd();
    for (QStringList::ConstIterator it = deleteList.constBegin(); it != endIt; ++it) {
        if ( (*it) == QLatin1String ("<default>"))
            continue;

        KConfigGroup cg (m_config, *it);
        if (!cg.hasKey ("UserAgent"))
            deleteList.removeAll (*it);
    }

    QString domain;
    QTreeWidgetItem* item;
    int itemCount = ui.sitePolicyTreeWidget->topLevelItemCount();

    // Save and remove from the delete list all the groups that were
    // not deleted by the end user.
    for (int i = 0; i < itemCount; i++) {
        item = ui.sitePolicyTreeWidget->topLevelItem (i);
        domain = item->text (0);
        KConfigGroup cg (m_config, domain);
        cg.writeEntry ("UserAgent", item->text (2));
        deleteList.removeAll (domain);
        qDebug ("UserAgentDlg::save: Removed [%s] from delete list", domain.toLatin1().constData());
    }

    // Write the global configuration information...
    KConfigGroup cg (m_config, QString());
    cg.writeEntry ("SendUserAgent", ui.sendUACheckBox->isChecked());
    cg.writeEntry ("UserAgentKeys", m_ua_keys);

    // Sync up all the changes so far...
    m_config->sync();

    // If delete list is not empty, delete the specified domains.
    if (!deleteList.isEmpty()) {
        // Remove entries from local file.
        endIt = deleteList.constEnd();
        KConfig cfg (QStringLiteral("kio_httprc"), KConfig::SimpleConfig);

        for (QStringList::ConstIterator it = deleteList.constBegin(); it != endIt; ++it) {
            KConfigGroup cg (&cfg, *it);
            cg.deleteEntry ("UserAgent");
            qDebug ("UserAgentDlg::save: Deleting UserAgent of group [%s]", (*it).toLatin1().constData());
            if (cg.keyList().count() < 1)
                cg.deleteGroup();
        }

        // Sync up the configuration...
        cfg.sync();

        // Check everything is gone, reset to blank otherwise.
        m_config->reparseConfiguration();
        endIt = deleteList.constEnd();
        for (QStringList::ConstIterator it = deleteList.constBegin(); it != endIt; ++it) {
            KConfigGroup cg (m_config, *it);
            if (cg.hasKey ("UserAgent"))
                cg.writeEntry ("UserAgent", QString());
        }

        // Sync up the configuration...
        m_config->sync();
    }

    KSaveIOConfig::updateRunningIOSlaves (this);
    configChanged (false);
}
Пример #23
0
KEquityPriceUpdateDlg::KEquityPriceUpdateDlg(QWidget *parent, const QString& securityId) :
    KEquityPriceUpdateDlgDecl(parent),
    m_fUpdateAll(false)
{
  QStringList headerList;
  headerList << i18n("Symbol") << i18nc("Equity name", "Name")
  << i18n("Price") << i18n("Date");

  lvEquityList->header()->setSortIndicator(0, Qt::AscendingOrder);
  lvEquityList->setColumnWidth(NAME_COL, 125);

  // This is a "get it up and running" hack.  Will replace this in the future.
  headerList << i18nc("Internal identifier", "ID")
  << i18nc("Online quote source", "Source");
  lvEquityList->setColumnWidth(ID_COL, 0);

  lvEquityList->setHeaderLabels(headerList);

  lvEquityList->setSelectionMode(QAbstractItemView::MultiSelection);
  lvEquityList->setAllColumnsShowFocus(true);

  btnUpdateAll->setEnabled(false);

  btnOK->setGuiItem(KStandardGuiItem::ok());
  btnCancel->setGuiItem(KStandardGuiItem::cancel());

  MyMoneyFile* file = MyMoneyFile::instance();

  //
  // Add each price pair that we know about
  //

  // send in securityId == "XXX YYY" to get a single-shot update for XXX to YYY.
  // for consistency reasons, this accepts the same delimiters as WebPriceQuote::launch()
  QRegExp splitrx("([0-9a-z\\.]+)[^a-z0-9]+([0-9a-z\\.]+)", Qt::CaseInsensitive);
  MyMoneySecurityPair currencyIds;
  if (splitrx.indexIn(securityId) != -1) {
    currencyIds = MyMoneySecurityPair(splitrx.cap(1).toUtf8(), splitrx.cap(2).toUtf8());
  }

  MyMoneyPriceList prices = file->priceList();
  for (MyMoneyPriceList::ConstIterator it_price = prices.constBegin(); it_price != prices.constEnd(); ++it_price) {
    const MyMoneySecurityPair& pair = it_price.key();
    if (file->security(pair.first).isCurrency() && (securityId.isEmpty() || (pair == currencyIds))) {
      const MyMoneyPriceEntries& entries = (*it_price);
      if (entries.count() > 0 && entries.begin().key() <= QDate::currentDate()) {
        addPricePair(pair);
        btnUpdateAll->setEnabled(true);
      }
    }
  }

  //
  // Add each investment
  //

  QList<MyMoneySecurity> securities = file->securityList();
  for (QList<MyMoneySecurity>::const_iterator it = securities.constBegin(); it != securities.constEnd(); ++it) {
    if (!(*it).isCurrency()
        && (securityId.isEmpty() || ((*it).id() == securityId))
        && !(*it).value("kmm-online-source").isEmpty()
       ) {
      addInvestment(*it);
      btnUpdateAll->setEnabled(true);
    }
  }

  // if list is empty, add the request price pair
  if (lvEquityList->invisibleRootItem()->childCount() == 0) {
    addPricePair(currencyIds, true);
  }

  connect(btnOK, SIGNAL(clicked()), this, SLOT(accept()));
  connect(btnCancel, SIGNAL(clicked()), this, SLOT(reject()));
  connect(btnUpdateSelected, SIGNAL(clicked()), this, SLOT(slotUpdateSelectedClicked()));
  connect(btnUpdateAll, SIGNAL(clicked()), this, SLOT(slotUpdateAllClicked()));

  connect(&m_webQuote, SIGNAL(quote(QString,QString,QDate,double)),
          this, SLOT(slotReceivedQuote(QString,QString,QDate,double)));
  connect(&m_webQuote, SIGNAL(failed(QString,QString)),
          this, SLOT(slotQuoteFailed(QString,QString)));
  connect(&m_webQuote, SIGNAL(status(QString)),
          this, SLOT(logStatusMessage(QString)));
  connect(&m_webQuote, SIGNAL(error(QString)),
          this, SLOT(logErrorMessage(QString)));

  connect(lvEquityList, SIGNAL(itemSelectionChanged()), this, SLOT(slotUpdateSelection()));

  // Not implemented yet.
  btnConfigure->hide();
  //connect(btnConfigure, SIGNAL(clicked()), this, SLOT(slotConfigureClicked()));

  if (!securityId.isEmpty()) {
    btnUpdateSelected->hide();
    btnUpdateAll->hide();
    // delete layout1;

    QTimer::singleShot(100, this, SLOT(slotUpdateAllClicked()));
  }

  // Hide OK button until we have received the first update
  btnOK->setEnabled(false);

  slotUpdateSelection();

  // previous versions of this dialog allowed to store a "Don't ask again" switch.
  // Since we don't support it anymore, we just get rid of it
  KSharedConfigPtr config = KGlobal::config();
  KConfigGroup grp = config->group("Notification Messages");
  grp.deleteEntry("KEquityPriceUpdateDlg::slotQuoteFailed::Price Update Failed");
}
Пример #24
0
void process(Mode mode, KConfigGroup &grp, QString key, QString value)
{
    switch (mode) {
    case Read:
        if (IS_A_TTY(1))
            std::cout << CHAR(key) << ": " << CHAR(grp.readEntry(key, "does not exist")) << " (" << CHAR(path(grp)) << ")" << std::endl;
        else
            std::cout << CHAR(grp.readEntry(key, ""));
        break;
    case Write: {
        if (grp.isImmutable()) {
            std::cout << "The component/group " << CHAR(path(grp)) << " cannot be modified" << std::endl;
            exit(1);
        }
        bool added = !grp.hasKey(key);
        QString oldv;
        if (!added) oldv = grp.readEntry(key);
        grp.writeEntry(key, QString(value));
        grp.sync();
        if (added)
            std::cout << "New " << CHAR(key) << ": " << CHAR(grp.readEntry(key)) << std::endl;
        else
            std::cout << CHAR(key) << ": " << CHAR(oldv) << " -> " << CHAR(grp.readEntry(key)) << std::endl;
        break;
    }
    case Delete: {
        if (grp.isImmutable()) {
            std::cout << "The component/group " << CHAR(path(grp)) << " cannot be modified" << std::endl;
            exit(1);
        }
        if (grp.hasKey(key)) {
            std::cout << "Removed " << CHAR(key) << ": " << CHAR(grp.readEntry(key)) << std::endl;
            grp.deleteEntry(key);
            grp.sync();
        } else if (grp.hasGroup(key)) {
            std::cout << "There's a group, but no key: " << CHAR(key) << "\nPlease explicitly use deletegroup" << std::endl;
            exit(1);
        } else {
            std::cout << "There's no key " << CHAR(key) << " in " << CHAR(path(grp)) << std::endl;
            exit(1);
        }
        break;
    }
    case DeleteGroup: {
        if (grp.hasGroup(key)) {
            grp = grp.group(key);
            if (grp.isImmutable()) {
                std::cout << "The component/group " << CHAR(path(grp)) << " cannot be modified" << std::endl;
                exit(1);
            }
            QMap<QString, QString> map = grp.entryMap();
            std::cout << "Removed " << CHAR(key) << gs_separator << std::endl;
            for (QMap<QString, QString>::const_iterator it = map.constBegin(), end = map.constEnd(); it != end; ++it) {
                std::cout << CHAR(it.key()) << ": " << CHAR(it.value()) << std::endl;
            }
            grp.deleteGroup();
            grp.sync();
        } else {
            std::cout << "There's no group " << CHAR(key) << " in " << CHAR(path(grp)) << std::endl;
            exit(1);
        }
        break;
    }
    case List:
    case ListKeys: {
        if (!grp.exists()) { // could be parent group
            if (mode == ListKeys)
                exit(1);
            QStringList groups = grp.parent().exists() ? grp.parent().groupList() : grp.config()->groupList();
            if (groups.isEmpty()) {
                std::cout << "The component/group " << CHAR(path(grp)) << " does not exist" << std::endl;
                exit(1);
            }
            std::cout << "Groups in " << CHAR(path(grp)) << gs_separator << std::endl;
            foreach (const QString &s, groups)
                if (key.isEmpty() || s.contains(key, Qt::CaseInsensitive))
                    std::cout << CHAR(s) << std::endl;
            exit(0);
        }

        QMap<QString, QString> map = grp.entryMap();
        if (map.isEmpty()) {
            std::cout << "The group " << CHAR(path(grp)) << " is empty" << std::endl;
            break;
        }

        if (mode == List) {
            bool matchFound = false;
            for (QMap<QString, QString>::const_iterator it = map.constBegin(), end = map.constEnd(); it != end; ++it) {
                if (key.isEmpty() || it.key().contains(key, Qt::CaseInsensitive)) {
                    if (!matchFound)
                        std::cout << std::endl << CHAR(path(grp)) << gs_separator << std::endl;
                    matchFound = true;
                    std::cout << CHAR(it.key()) << ": " << CHAR(it.value()) << std::endl;
                }
            }

            if (!matchFound)
                std::cout << "No present key matches \"" << CHAR(key) << "\" in " << CHAR(path(grp));
            std::cout << std::endl;
        } else {
            for (QMap<QString, QString>::const_iterator it = map.constBegin(), end = map.constEnd(); it != end; ++it) {
                if (key.isEmpty() || it.key().contains(key, Qt::CaseInsensitive)) {
                    std::cout << CHAR(it.key()) << std::endl;
                }
            }
        }
        break;
    }
    case ListGroups: {
        QStringList groups = grp.parent().exists() ? grp.parent().groupList() : grp.config()->groupList();
        foreach (const QString &s, groups)
            if (key.isEmpty() || s.contains(key, Qt::CaseInsensitive))
                std::cout << CHAR(s) << std::endl;
        exit(0);
    }
    case Replace: {
        if (grp.isImmutable()) {
            std::cout << "The component/group " << CHAR(path(grp)) << " cannot be modified" << std::endl;
            exit(1);
        }
        QStringList match = key.split("=");
        if (match.count() != 2) {
            std::cout << "The match sequence must be of the form <key regexp>=<value regexp>" << std::endl;
            exit(1);
        }
        QRegExp keyMatch(match.at(0), Qt::CaseInsensitive);
        QRegExp valueMatch(match.at(1), Qt::CaseInsensitive);
        QStringList replace = value.split("=");
        if (replace.count() != 2) {
            std::cout << "The replace sequence must be of the form <key string>=<value string>" << std::endl;
            exit(1);
        }
        QMap<QString, QString> map = grp.entryMap();
        QStringList keys;
        for (QMap<QString, QString>::const_iterator it = map.constBegin(), end = map.constEnd(); it != end; ++it) {
            if (keyMatch.exactMatch(it.key()) && valueMatch.exactMatch(it.value())) {
                keys << it.key();
            }
        }
        foreach (const QString &key, keys) {
            QString newKey = key;
            newKey.replace(keyMatch, replace.at(0));
            QString newValue = grp.readEntry(key);
            const QString oldValue = newValue;
            newValue.replace(valueMatch, replace.at(1));
            if (key != newKey)
                grp.deleteEntry(key);
            grp.writeEntry(newKey, newValue);
            std::cout << CHAR(key) << ": " << CHAR(oldValue) << " -> " << CHAR(newKey) << ": " << CHAR(grp.readEntry(newKey)) << std::endl;
            grp.sync();
        }
        break;
    }
    Invalid:
    default:
        break;
    }
Пример #25
0
Settings SettingsIO::readSettings( KConfigGroup cg, KConfigGroup cgGlobal,
                                   Plasma::DataEngine *publictransportEngine )
{
    Settings settings;
    if ( !cg.hasKey("departureTimeFlags") && (cg.hasKey("showRemainingMinutes") ||
         cg.hasKey("showDepartureTime") || cg.hasKey("displayTimeBold")) )
    {
        // DEPRECATED This reads settings stored in old format (version < 0.11)
        kDebug() << "Reading settings in old format, will be converted to new format";
        settings.setShowRemainingTime( cg.readEntry("showRemainingMinutes", true) );
        cg.deleteEntry( "showRemainingMinutes" );


        settings.setDisplayDepartureTimeBold( cg.readEntry("displayTimeBold", true) );
        cg.deleteEntry( "displayTimeBold" );

        cg.writeEntry( "departureTimeFlags", static_cast<int>(settings.departureTimeFlags()) );
        cg.sync();
    } else {
        settings.setDepartureTimeFlags( static_cast< Settings::DepartureTimeFlags >(
                cg.readEntry("departureTimeFlags", static_cast<int>(Settings::DefaultDepartureTimeFlags))) );
    }

    const Settings::AdditionalDataRequestType requestType = static_cast< Settings::AdditionalDataRequestType >(
            cg.readEntry("additionalDataRequestType", static_cast<int>(Settings::DefaultAdditionalDataRequestType)));
    settings.setAdditionalDataRequestType( requestType );

    // Read stop settings TODO: Store in config groups like filters
    StopSettingsList stopSettingsList;
    int stopSettingCount = cgGlobal.readEntry( "stopSettings", 1 );
    QString test = "location";
    int i = 1;
    while ( cgGlobal.hasKey(test) ) {
        StopSettings stopSettings;
        QString suffix = i == 1 ? QString() : '_' + QString::number( i );
        stopSettings.set( LocationSetting, cgGlobal.readEntry("location" + suffix, "showAll") );
        stopSettings.set( ServiceProviderSetting,
                          cgGlobal.readEntry("serviceProvider" + suffix, "de_db") );
        stopSettings.set( CitySetting, cgGlobal.readEntry("city" + suffix, QString()) );
        stopSettings.setStops( cgGlobal.readEntry("stop" + suffix, QStringList()),
                               cgGlobal.readEntry("stopID" + suffix, QStringList()) );
        stopSettings.set( TimeOffsetOfFirstDepartureSetting,
                          cgGlobal.readEntry("timeOffsetOfFirstDeparture" + suffix, 0) );
        stopSettings.set( TimeOfFirstDepartureSetting,
                          QTime::fromString(cgGlobal.readEntry("timeOfFirstDepartureCustom" + suffix,
                                                               "12:00"), "hh:mm") );
        stopSettings.set( FirstDepartureConfigModeSetting,
                          cgGlobal.readEntry("firstDepartureConfigMode" + suffix,
                                             static_cast<int>(RelativeToCurrentTime)) );
        stopSettings.set( AlarmTimeSetting, cgGlobal.readEntry("alarmTime" + suffix, 5) );

        // Read favorite/recent journey search items for the current stop settings
        QByteArray journeySearchesData =
                cgGlobal.readEntry( "journeySearches" + suffix, QByteArray() );
        stopSettings.set( Settings::JourneySearchSetting, QVariant::fromValue(
                SettingsIO::decodeJourneySearchItems(&journeySearchesData)) );
        stopSettingsList << stopSettings;

        ++i;
        test = "location_" + QString::number( i );
        if ( i > stopSettingCount ) {
            break;
        }
    }

    settings.setCurrentStop( cg.readEntry("currentStopIndex", 0) );

    // Add initial stop settings when no settings are available
    if ( stopSettingsList.isEmpty() ) {
        kDebug() << "Stop settings list in settings is empty";
        if ( publictransportEngine ) {
            QString countryCode = KGlobal::locale()->country();
            Plasma::DataEngine::Data locationData = publictransportEngine->query( "Locations" );
            QString defaultServiceProviderId =
                    locationData[countryCode].toHash()["defaultProvider"].toString();

            StopSettings stopSettings;
            if ( defaultServiceProviderId.isEmpty() ) {
                stopSettings.set( LocationSetting, "showAll" );
            } else {
                stopSettings.set( LocationSetting, countryCode );
                stopSettings.set( ServiceProviderSetting, defaultServiceProviderId );
            }
            stopSettings.setStop( QString() );
            // TODO: Get initial stop names using StopFinder

            stopSettingsList << stopSettings;
        } else {
            stopSettingsList << StopSettings();
        }

    }
    settings.setStops( stopSettingsList );

    if ( settings.currentStopIndex() < 0 ) {
        settings.setCurrentStop( 0 ); // For compatibility with versions < 0.7
    } else if ( settings.currentStopIndex() >= settings.stops().count() ) {
        kDebug() << "Current stop index in settings invalid";
        settings.setCurrentStop( settings.stops().count() - 1 );
    }

    settings.setMaximalNumberOfDepartures( cg.readEntry("maximalNumberOfDepartures", 50) );
    settings.setLinesPerRow( cg.readEntry("linesPerRow", 2) );
    settings.setSizeFactor( Settings::sizeFactorFromSize(cg.readEntry("size", 2)) );
    settings.setDepartureArrivalListType( static_cast<DepartureArrivalListType>(
            cg.readEntry("departureArrivalListType", static_cast<int>(DepartureList))) );

    settings.setDrawShadows( cg.readEntry("drawShadows", true) );
    settings.setHideTargetColumn( cg.readEntry("hideColumnTarget", false) );
    settings.setColorize( cg.readEntry("colorize", true) );

    QString fontFamily = cg.readEntry( "fontFamily", QString() );
    settings.setUseThemeFont( fontFamily.isEmpty() );
    if ( !settings.useThemeFont() ) {
        settings.setFont( QFont(fontFamily) );
    } else {
        settings.setFont( Plasma::Theme::defaultTheme()->font(Plasma::Theme::DefaultFont) );
    }

    // ***************** DEPRECATED BEGIN *****************************************************
    // *** Used for migration of filter settings from versions prior to version 0.10 RC1 ******
    FilterSettingsList filtersList;
    if ( cgGlobal.hasKey("filterConfigurationList") ) {
        kDebug() << "DEPRECATED Filter settings will be restructured for new version";
        QStringList filterConfigurationList =
                cgGlobal.readEntry( "filterConfigurationList", QStringList() );
        for ( int i = filterConfigurationList.count() - 1; i >= 0; --i ) {
            const QString &filterConfiguration = filterConfigurationList[ i ];
            if ( filterConfiguration.isEmpty() ) {
                filterConfigurationList.removeAt( i );
            }
        }

        kDebug() << "Config group list" << cgGlobal.groupList();
        kDebug() << "Filter config list:" << filterConfigurationList;

        // Read old filter settings
        foreach( const QString &filterConfiguration, filterConfigurationList ) {
            FilterSettings filters =
                    readFilterConfig( cgGlobal.group("filterConfig_" + filterConfiguration) );
            filters.name = filterConfiguration;
            filtersList << filters;
        }
void TestScriptedEffectLoader::testLoadAllEffects()
{
    MockEffectsHandler mockHandler(KWin::XRenderCompositing);
    KWin::ScriptedEffectLoader loader;

    KSharedConfig::Ptr config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig);

    const QString kwin4 = QStringLiteral("kwin4_effect_");

    // prepare the configuration to hard enable/disable the effects we want to load
    KConfigGroup plugins = config->group("Plugins");
    plugins.writeEntry(kwin4 + QStringLiteral("dialogparentEnabled"), false);
    plugins.writeEntry(kwin4 + QStringLiteral("fadeEnabled"), false);
    plugins.writeEntry(kwin4 + QStringLiteral("fadedesktopEnabled"), false);
    plugins.writeEntry(kwin4 + QStringLiteral("loginEnabled"), false);
    plugins.writeEntry(kwin4 + QStringLiteral("maximizeEnabled"), false);
    plugins.writeEntry(kwin4 + QStringLiteral("minimizeanimationEnabled"), false);
    plugins.writeEntry(kwin4 + QStringLiteral("scaleinEnabled"), false);
    plugins.writeEntry(kwin4 + QStringLiteral("translucencyEnabled"), false);
    plugins.writeEntry(kwin4 + QStringLiteral("eyeonscreenEnabled"), false);
    plugins.writeEntry(kwin4 + QStringLiteral("windowapertureEnabled"), false);
    plugins.writeEntry(kwin4 + QStringLiteral("morphingpopupsEnabled"), false);
    plugins.sync();

    loader.setConfig(config);

    qRegisterMetaType<KWin::Effect*>();
    QSignalSpy spy(&loader, SIGNAL(effectLoaded(KWin::Effect*,QString)));
    // connect to signal to ensure that we delete the Effect again as the Effect doesn't have a parent
    connect(&loader, &KWin::ScriptedEffectLoader::effectLoaded,
        [](KWin::Effect *effect) {
            effect->deleteLater();
        }
    );

    // the config is prepared so that no Effect gets loaded!
    loader.queryAndLoadAll();

    // we need to wait some time because it's queued and in a thread
    QVERIFY(!spy.wait(100));

    // now let's prepare a config which has one effect explicitly enabled
    plugins.writeEntry(kwin4 + QStringLiteral("scaleinEnabled"), true);
    plugins.sync();

    loader.queryAndLoadAll();
    // should load one effect in first go
    QVERIFY(spy.wait(100));
    // and afterwards it should not load another one
    QVERIFY(!spy.wait(10));

    QCOMPARE(spy.size(), 1);
    // if we caught a signal it should have the effect name we passed in
    QList<QVariant> arguments = spy.takeFirst();
    QCOMPARE(arguments.count(), 2);
    QCOMPARE(arguments.at(1).toString(), kwin4 + QStringLiteral("scalein"));
    spy.clear();

    // let's delete one of the default entries
    plugins.deleteEntry(kwin4 + QStringLiteral("fadeEnabled"));
    plugins.sync();

    QVERIFY(spy.isEmpty());
    loader.queryAndLoadAll();

    // let's use qWait as we need to wait for two signals to be emitted
    QTest::qWait(100);
    QCOMPARE(spy.size(), 2);
    QStringList loadedEffects;
    for (auto &list : spy) {
        QCOMPARE(list.size(), 2);
        loadedEffects << list.at(1).toString();
    }
    qSort(loadedEffects);
    QCOMPARE(loadedEffects.at(0), kwin4 + QStringLiteral("fade"));
    QCOMPARE(loadedEffects.at(1), kwin4 + QStringLiteral("scalein"));
}