void SvnRecursiveAdd::test()
{
    KTempDir reposDir;
    KProcess cmd;
    cmd.setWorkingDirectory(reposDir.name());
    cmd << "svnadmin" << "create" << reposDir.name();
    QCOMPARE(cmd.execute(10000), 0);
    AutoTestShell::init();
    std::auto_ptr<TestCore> core(new TestCore());
    core->initialize(Core::Default);
    QList<IPlugin*> plugins = Core::self()->pluginController()->allPluginsForExtension("org.kdevelop.IBasicVersionControl");
    IBasicVersionControl* vcs = NULL;
    foreach(IPlugin* p,  plugins) {
        qDebug() << "checking plugin" << p;    
        ICentralizedVersionControl* icentr = p->extension<ICentralizedVersionControl>();
        if (!icentr)
            continue;
        if (icentr->name() == "Subversion") {
            vcs = icentr;
            break;
        }
    }
예제 #2
0
bool K3b::CdrdaoProgram::scanFeatures( ExternalBin& bin ) const
{
    // probe features
    KProcess fp;
    fp.setOutputChannelMode( KProcess::MergedChannels );
    fp << bin.path() << "write" << "-h";

    if( fp.execute() >= 0 ) {
        QByteArray out = fp.readAll();
        if( out.contains( "--overburn" ) )
            bin.addFeature( "overburn" );
        if( out.contains( "--multi" ) )
            bin.addFeature( "multisession" );

        if( out.contains( "--buffer-under-run-protection" ) )
            bin.addFeature( "disable-burnproof" );

        // SuSE 9.0 ships with a patched cdrdao 1.1.7 which contains an updated libschily
        // Gentoo ships with a patched cdrdao 1.1.7 which contains scglib support
        if( bin.version() > K3b::Version( 1, 1, 7 ) ||
            bin.version() == K3b::Version( 1, 1, 7, "-gentoo" ) ||
            bin.version() == K3b::Version( 1, 1, 7, "-suse" ) ) {
            //    bin.addFeature( "plain-atapi" );
            bin.addFeature( "hacked-atapi" );
        }

        if( bin.version() >= K3b::Version( 1, 1, 8 ) )
            bin.addFeature( "plain-atapi" );

        return SimpleExternalProgram::scanFeatures( bin );
    }
    else {
        qDebug() << "could not start " << bin.path();
        return false;
    }
}
예제 #3
0
void LocalPatchSource::update()
{
    if( !m_command.isEmpty() ) {
        QTemporaryFile temp(QDir::tempPath() + QLatin1String("/patchreview_XXXXXX.diff"));
        if( temp.open() ) {
            temp.setAutoRemove( false );
            QString filename = temp.fileName();
            qCDebug(PLUGIN_PATCHREVIEW) << "temp file: " << filename;
            temp.close();
            KProcess proc;
            proc.setWorkingDirectory( m_baseDir.toLocalFile() );
            proc.setOutputChannelMode( KProcess::OnlyStdoutChannel );
            proc.setStandardOutputFile( filename );
            ///Try to apply, if it works, the patch is not applied
            proc << KShell::splitArgs( m_command );

            qCDebug(PLUGIN_PATCHREVIEW) << "calling " << m_command;

            if ( proc.execute() ) {
                qWarning() << "returned with bad exit code";
                return;
            }
            if ( !m_filename.isEmpty() ) {
                QFile::remove( m_filename.toLocalFile() );
            }
            m_filename = QUrl::fromLocalFile( filename );
            qCDebug(PLUGIN_PATCHREVIEW) << "success, diff: " << m_filename;
        }else{
            qWarning() << "PROBLEM";
        }
    }
    if (m_widget) {
        m_widget->updatePatchFromEdit();
    }
    emit patchChanged();
}
예제 #4
0
파일: kprocess.cpp 프로젝트: vasi/kdelibs
// static
int KProcess::execute(const QStringList &argv, int msecs)
{
    KProcess p;
    p.setProgram(argv);
    return p.execute(msecs);
}
예제 #5
0
파일: kprocess.cpp 프로젝트: vasi/kdelibs
// static
int KProcess::execute(const QString &exe, const QStringList &args, int msecs)
{
    KProcess p;
    p.setProgram(exe, args);
    return p.execute(msecs);
}
ActionReply RtcWakeAction::settimer(const QVariantMap& args)
{
    unsigned t = args["time"].toUInt();
    qDebug() << "RtcWakeAction::settimer(" << t << ")";

    // Find the rtcwake executable
    QString exe("/usr/sbin/rtcwake");   // default location
    FILE* wh = popen("whereis -b rtcwake", "r");
    if (wh)
    {
        char buff[512] = { '\0' };
        fgets(buff, sizeof(buff), wh);
        pclose(wh);
        // The string should be in the form "rtcwake: /path/rtcwake"
        char* start = strchr(buff, ':');
        if (start)
        {
            if (*++start == ' ')
                ++start;
            char* end = strpbrk(start, " \r\n");
            if (end)
                *end = 0;
            if (*start)
            {
                exe = QString::fromLocal8Bit(start);
                qDebug() << "RtcWakeAction::settimer:" << exe;
            }
        }
    }

    // Set the wakeup by executing the rtcwake command
    int result = -2;   // default = command not found
    KProcess proc;
    if (!exe.isEmpty())
    {
        // The wakeup time is set using a time from now ("-s") in preference to
        // an absolute time ("-t") so that if the hardware clock is not in sync
        // with the system clock, the alarm will still occur at the correct time.
        // The "-m no" option sets the wakeup time without suspending the computer.

        // If 't' is zero, the current wakeup is cancelled by setting a new wakeup
        // time 2 seconds from now, which will then expire.
        unsigned now = KDateTime::currentUtcDateTime().toTime_t();
        proc << exe << "-m" << "no" << "-s" << QString::number(t ? t - now : 2);
        result = proc.execute(5000);   // allow a timeout of 5 seconds
    }
    QString errmsg;
    switch (result)
    {
        case 0:
            return ActionReply::SuccessReply;
        case -2:
            errmsg = i18nc("@text/plain", "Could not run <command>%1</command> to set wake from suspend", "rtcwake");
            break;
        default:
            errmsg = i18nc("@text/plain", "Error setting wake from suspend.<nl/>Command was: <command>%1</command><nl/>Error code: %2.", proc.program().join(" "), result);
            break;
    }
    ActionReply reply(ActionReply::HelperError);
    reply.setErrorCode(result);
    reply.setErrorDescription(errmsg);
    qDebug() << "RtcWakeAction::settimer: Code=" << reply.errorCode() << reply.errorDescription();
    return reply;
}
예제 #7
0
void CameraController::slotCheckRename(const QString& folder, const QString& file,
                                       const QString& destination, const QString& temp,
                                       const QString& script)
{
    // this is the direct continuation of executeCommand, case CameraCommand::cam_download
    bool skip      = false;
    bool cancel    = false;
    bool overwrite = d->overwriteAll;
    QString dest   = destination;

    // Check if dest file already exist, unless we overwrite anyway

    QFileInfo info(dest);

    if (!d->overwriteAll)
    {

        while (info.exists())
        {
            if (d->skipAll)
            {
                skip = true;
                break;
            }

            QPointer<KIO::RenameDialog> dlg = new KIO::RenameDialog(d->parent, i18nc("@title:window", "Rename File"),
                    QString(folder + QLatin1String("/") + file), dest,
                    KIO::RenameDialog_Mode(KIO::M_MULTI     |
                                           KIO::M_OVERWRITE |
                                           KIO::M_SKIP));

            int result = dlg->exec();
            dest       = dlg->newDestUrl().toLocalFile();
            info       = QFileInfo(dest);

            delete dlg;

            switch (result)
            {
            case KIO::R_CANCEL:
            {
                cancel = true;
                break;
            }

            case KIO::R_SKIP:
            {
                skip = true;
                break;
            }

            case KIO::R_AUTO_SKIP:
            {
                d->skipAll = true;
                skip       = true;
                break;
            }

            case KIO::R_OVERWRITE:
            {
                overwrite = true;
                break;
            }

            case KIO::R_OVERWRITE_ALL:
            {
                d->overwriteAll = true;
                overwrite       = true;
                break;
            }

            default:
                break;
            }

            if (cancel || skip || overwrite)
            {
                break;
            }
        }
    }

    if (cancel)
    {
        unlink(QFile::encodeName(temp));
        slotCancel();
        emit signalSkipped(folder, file);
        return;
    }
    else if (skip)
    {
        unlink(QFile::encodeName(temp));
        sendLogMsg(i18n("Skipped file <filename>%1</filename>", file), DHistoryView::WarningEntry, folder, file);
        emit signalSkipped(folder, file);
        return;
    }

    kDebug() << "Checking whether (" << temp << ") has a sidecar";

    // move the file to the destination file
    if (DMetadata::hasSidecar(temp))
    {
        kDebug() << "  Yes, renaming it to " << dest;
        if (KDE::rename(DMetadata::sidecarPath(temp), DMetadata::sidecarPath(dest)) != 0)
        {
            sendLogMsg(i18n("Failed to save sidecar file for <filename>%1</filename>", file), DHistoryView::ErrorEntry,  folder, file);
        }
    }

    if (KDE::rename(temp, dest) != 0)
    {
        kDebug() << "Renaming " << temp << " to " << dest << " failed";
        // rename failed. delete the temp file
        unlink(QFile::encodeName(temp));
        emit signalDownloaded(folder, file, CamItemInfo::DownloadFailed);
        sendLogMsg(i18n("Failed to download <filename>%1</filename>", file), DHistoryView::ErrorEntry,  folder, file);
    }
    else
    {
        kDebug() << "Rename done, emiting downloaded signals:" << file << " info.filename: " << info.fileName();
        // TODO why two signals??
        emit signalDownloaded(folder, file, CamItemInfo::DownloadedYes);
        emit signalDownloadComplete(folder, file, info.path(), info.fileName());

        // Run script
        if (!script.isEmpty())
        {
            kDebug() << "Got a script, processing: " << script;
            KProcess process;

            process.setOutputChannelMode(KProcess::SeparateChannels);
            QString s;

            if (script.indexOf('%') > -1)
            {
                QHash<QString, QString> map;
                map.insert("file", dest);
                map.insert("filename", info.fileName());
                map.insert("path", info.path());
                map.insert("orgfilename", file);
                map.insert("orgpath", folder);
                s = KMacroExpander::expandMacros(script, map);
            }
            else
            {
                s = script + " \"" + dest + "\"";
            }

            process.setShellCommand(s);
            kDebug() << "Running: " << s;
            int ret = process.execute();

            if (ret != 0)
            {
                sendLogMsg(i18n("Failed to run script for <filename>%1</filename>", file), DHistoryView::ErrorEntry,  folder, file);
            }

            kDebug() << "stdout" << process.readAllStandardOutput();
            kDebug() << "stderr" << process.readAllStandardError();
        }
    }
}
예제 #8
0
파일: psgs.cpp 프로젝트: JPriya/Okular
void ghostscript_interface::gs_generate_graphics_file(const PageNumber& page, const QString& filename, long magnification) {
#ifdef DEBUG_PSGS
  kDebug(kvs::dvi) << "ghostscript_interface::gs_generate_graphics_file( " << page << ", " << filename << " )";
#endif

  if (knownDevices.isEmpty()) {
    kError(kvs::dvi) << "No known devices found" << endl;
    return;
  }

  pageInfo *info = pageList.value(page);

  // Generate a PNG-file
  // Step 1: Write the PostScriptString to a File
  KTemporaryFile PSfile;
  PSfile.setAutoRemove(false);
  PSfile.setSuffix(".ps");
  PSfile.open();
  const QString PSfileName = PSfile.fileName();

  QTextStream os(&PSfile);
  os << "%!PS-Adobe-2.0\n"
     << "%%Creator: kdvi\n"
     << "%%Title: KDVI temporary PostScript\n"
     << "%%Pages: 1\n"
     << "%%PageOrder: Ascend\n"
        // HSize and VSize in 1/72 inch
     << "%%BoundingBox: 0 0 "
     << (qint32)(72*(pixel_page_w/resolution)) << ' '
     << (qint32)(72*(pixel_page_h/resolution)) << '\n'
     << "%%EndComments\n"
     << "%!\n"
     << psheader
     << "TeXDict begin "
        // HSize in (1/(65781.76*72))inch
     << (qint32)(72*65781*(pixel_page_w/resolution)) << ' '
        // VSize in (1/(65781.76*72))inch
     << (qint32)(72*65781*(pixel_page_h/resolution)) << ' '
        // Magnification
     << (qint32)(magnification)
        // dpi and vdpi
     << " 300 300"
        // Name
     << " (test.dvi)"
     << " @start end\n"
     << "TeXDict begin\n"
        // Start page
     << "1 0 bop 0 0 a \n";

  if (!PostScriptHeaderString->toLatin1().isNull())
    os << PostScriptHeaderString->toLatin1();

  if (info->background != Qt::white) {
    QString colorCommand = QString("gsave %1 %2 %3 setrgbcolor clippath fill grestore\n").
      arg(info->background.red()/255.0).
      arg(info->background.green()/255.0).
      arg(info->background.blue()/255.0);
    os << colorCommand.toLatin1();
  }

  if (!info->PostScriptString->isNull())
    os << *(info->PostScriptString);

  os << "end\n"
     << "showpage \n";

  PSfile.close();

  // Step 2: Call GS with the File
  QFile::remove(filename.toAscii());
  KProcess proc;
  proc.setOutputChannelMode(KProcess::SeparateChannels);
  QStringList argus;
  argus << "gs";
  argus << "-dSAFER" << "-dPARANOIDSAFER" << "-dDELAYSAFER" << "-dNOPAUSE" << "-dBATCH";
  argus << QString("-sDEVICE=%1").arg(*gsDevice);
  argus << QString("-sOutputFile=%1").arg(filename);
  argus << QString("-sExtraIncludePath=%1").arg(includePath);
  argus << QString("-g%1x%2").arg(pixel_page_w).arg(pixel_page_h); // page size in pixels
  argus << QString("-r%1").arg(resolution);                       // resolution in dpi
  argus << "-dTextAlphaBits=4 -dGraphicsAlphaBits=2"; // Antialiasing
  argus << "-c" << "<< /PermitFileReading [ ExtraIncludePath ] /PermitFileWriting [] /PermitFileControl [] >> setuserparams .locksafe";
  argus << "-f" << PSfileName;

#ifdef DEBUG_PSGS
  kDebug(kvs::dvi) << argus.join(" ");
#endif
 
  proc << argus;
  int res = proc.execute();
  
  if ( res ) {
    // Starting ghostscript did not work. 
    // TODO: Issue error message, switch PS support off.
    kError(kvs::dvi) << "ghostview could not be started" << endl;
  } 

  PSfile.remove();

 // Check if gs has indeed produced a file.
  if (QFile::exists(filename) == false) {
    kError(kvs::dvi) << "GS did not produce output." << endl;

    // No. Check is the reason is that the device is not compiled into
    // ghostscript. If so, try again with another device.
    QString GSoutput;
    proc.setReadChannel(QProcess::StandardOutput);
    while(proc.canReadLine()) {
      GSoutput = QString::fromLocal8Bit(proc.readLine());
      if (GSoutput.contains("Unknown device")) {
	kDebug(kvs::dvi) << QString("The version of ghostview installed on this computer does not support "
                                     "the '%1' ghostview device driver.").arg(*gsDevice) << endl;
	knownDevices.erase(gsDevice);
	gsDevice = knownDevices.begin();
	if (knownDevices.isEmpty())
	  // TODO: show a requestor of some sort.
#if 0
	  KMessageBox::detailedError(0, 
				     i18n("<qt>The version of Ghostview that is installed on this computer does not contain "
					  "any of the Ghostview device drivers that are known to Okular. PostScript "
					  "support has therefore been turned off in Okular.</qt>"), 
				     i18n("<qt><p>The Ghostview program, which Okular uses internally to display the "
					  "PostScript graphics that is included in this DVI file, is generally able to "
					  "write its output in a variety of formats. The sub-programs that Ghostview uses "
					  "for these tasks are called 'device drivers'; there is one device driver for "
					  "each format that Ghostview is able to write. Different versions of Ghostview "
					  "often have different sets of device drivers available. It seems that the "
					  "version of Ghostview that is installed on this computer does not contain "
					  "<strong>any</strong> of the device drivers that are known to Okular.</p>"
					  "<p>It seems unlikely that a regular installation of Ghostview would not contain "
					  "these drivers. This error may therefore point to a serious misconfiguration of "
					  "the Ghostview installation on your computer.</p>"
					  "<p>If you want to fix the problems with Ghostview, you can use the command "
					  "<strong>gs --help</strong> to display the list of device drivers contained in "
					  "Ghostview. Among others, Okular can use the 'png256', 'jpeg' and 'pnm' "
					  "drivers. Note that Okular needs to be restarted to re-enable PostScript support."
					  "</p></qt>"));
#else
	{}
#endif
	else {
	  kDebug(kvs::dvi) << QString("Okular will now try to use the '%1' device driver.").arg(*gsDevice);
	  gs_generate_graphics_file(page, filename, magnification);
	}
	return;
      }
예제 #9
0
QStringList gccSetupStandardIncludePaths(bool withStdCpp0x)
{
    QStringList includePaths;
    
    KProcess proc;
    proc.setOutputChannelMode(KProcess::MergedChannels);

    // The following command will spit out a bnuch of information we don't care
    // about before spitting out the include paths.  The parts we care about
    // look like this:
    // #include "..." search starts here:
    // #include <...> search starts here:
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2/i486-linux-gnu
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2/backward
    //  /usr/local/include
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/include
    //  /usr/include
    // End of search list.
    proc << "gcc";
    if (withStdCpp0x) {
        // see also: https://bugs.kde.org/show_bug.cgi?id=298252
        proc << "-std=c++0x";
    }
    proc << "-xc++" << "-E" << "-v" << NULL_DEVICE;

    // We'll use the following constants to know what we're currently parsing.
    const short parsingInitial = 0;
    const short parsedFirstSearch = 1;
    const short parsingIncludes = 2;
    const short parsingFinished = 3;
    short parsingMode = parsingInitial;

    if (proc.execute(5000) == 0) {
        QString line;
        while (proc.canReadLine() && parsingMode != parsingFinished) {
            QByteArray buff = proc.readLine();
            if (!buff.isEmpty()) {
                line = buff;
                switch (parsingMode) {
                case parsingInitial:
                    if (line.indexOf("#include \"...\"") != -1) {
                        parsingMode = parsedFirstSearch;
                    }
                    break;
                case parsedFirstSearch:
                    if (line.indexOf("#include <...>") != -1) {
                        parsingMode = parsingIncludes;
                        break;
                    }
                case parsingIncludes:
                    //if (!line.indexOf(QDir::separator()) == -1 && line != "." ) {
                    //Detect the include-paths by the first space that is prepended. Reason: The list may contain relative paths like "."
                    if (!line.startsWith(" ") ) {
                        // We've reached the end of the list.
                        parsingMode = parsingFinished;
                    } else {
                        line = line.trimmed();
                        // This is an include path, add it to the list.
                        includePaths << QDir::cleanPath(line);
                    }
                    break;
                }
            }
        }
    } else if (withStdCpp0x) {
        // fallback to include-path computation without -std=c++0x arg for old gcc versions
        return gccSetupStandardIncludePaths(false);
    } else {
        kDebug(9007) <<"Unable to read standard c++ macro definitions from gcc:" <<QString(proc.readAll()) ;
    }
    
    return includePaths;
}
예제 #10
0
파일: kio_man.cpp 프로젝트: KDE/kio-extras
char *MANProtocol::readManPage(const char *_filename)
{
    QByteArray filename = _filename;
    QByteArray array;

    /* Determine type of man page file by checking its path. Determination by
     * MIME type with KMimeType doesn't work reliablely. E.g., Solaris 7:
     * /usr/man/sman7fs/pcfs.7fs -> text/x-csrc : WRONG
     * If the path name constains the string sman, assume that it's SGML and
     * convert it to roff format (used on Solaris). */
    //QString file_mimetype = KMimeType::findByPath(QString(filename), 0, false)->name();
    if (QString(filename).contains("sman", Qt::CaseInsensitive)) //file_mimetype == "text/html" || )
    {
        KProcess proc;
        // Determine path to sgml2roff, if not already done.
        getProgramPath();
        proc << mySgml2RoffPath << filename;
        proc.setOutputChannelMode( KProcess::OnlyStdoutChannel );
        proc.execute();
        array = proc.readAllStandardOutput();
    }
    else
    {
      if (QDir::isRelativePath(filename))
      {
          qCDebug(KIO_MAN_LOG) << "relative " << filename;
          filename = QDir::cleanPath(lastdir + '/' + filename).toUtf8();
          qCDebug(KIO_MAN_LOG) << "resolved to " << filename;
      }

      lastdir = filename.left(filename.lastIndexOf('/'));

      if ( !QFile::exists(QFile::decodeName(filename)) )  // if given file does not exist, find with suffix
      {
          qCDebug(KIO_MAN_LOG) << "not existing " << filename;
          QDir mandir(lastdir);
          mandir.setNameFilters(QStringList() << (filename.mid(filename.lastIndexOf('/') + 1) + ".*"));
          filename = lastdir + '/' + QFile::encodeName(mandir.entryList().first());
          qCDebug(KIO_MAN_LOG) << "resolved to " << filename;
      }

      QIODevice *fd = KFilterDev::deviceForFile(filename);

      if ( !fd || !fd->open(QIODevice::ReadOnly))
      {
         delete fd;
         return 0;
      }
      array = fd->readAll();
      qCDebug(KIO_MAN_LOG) << "read " << array.size();
      fd->close();
      delete fd;
    }

    if (array.isEmpty())
      return 0;

    // as we do not know in which encoding the man source is, try to automatically
    // detect it and always return it as UTF-8
    KEncodingProber encodingProber;
    encodingProber.feed(array);
    qCDebug(KIO_MAN_LOG) << "auto-detect encoding for" << filename << "guess=" << encodingProber.encoding()
                 << "confidence=" << encodingProber.confidence();
    QString out = QTextCodec::codecForName(encodingProber.encoding())->toUnicode(array);
    array = out.toUtf8();

    const int len = array.size();
    char *buf = new char[len + 4];
    memmove(buf + 1, array.data(), len);
    buf[0] = buf[len+1] = '\n'; // Start and end with an end of line
    buf[len+2] = buf[len+3] = '\0'; // Two NUL characters at end

    return buf;
}
예제 #11
0
Defines MsvcCompiler::defines(const QString&) const
{
    Defines ret;
    //Get standard macros from kdevmsvcdefinehelpers
    KProcess proc;
    proc.setOutputChannelMode( KProcess::MergedChannels );
    proc.setTextModeEnabled( true );

    // we want to use kdevmsvcdefinehelper as a pseudo compiler backend which
    // returns the defines used in msvc. there is no such thing as -dM with cl.exe
    proc << path() << "/nologo" << "/Bxkdevmsvcdefinehelper" << "empty.cpp";

    // this will fail, so check on that as well
    if ( proc.execute( 5000 ) == 2 ) {
        QString line;
        proc.readLine(); // read the filename

        while ( proc.canReadLine() ) {
            QByteArray buff = proc.readLine();
            definesAndIncludesDebug() << "msvcstandardmacros:" << buff;
            if ( !buff.isEmpty() ) {
                line = buff;
                if ( line.startsWith( "#define " ) ) {
                    line = line.right( line.length() - 8 ).trimmed();
                    int pos = line.indexOf( ' ' );

                    if ( pos != -1 ) {
                        ret[line.left( pos )] = line.right( line.length() - pos - 1 ).toUtf8();
                    } else {
                        ret[line] = "";
                    }
                }
            }
        }
    } else {
        definesAndIncludesDebug() << "Unable to read standard c++ macro definitions from " + path();
        while ( proc.canReadLine() ){
            definesAndIncludesDebug()  << proc.readLine();
        }
        definesAndIncludesDebug()  << proc.exitCode();
    }

    // MSVC builtin attributes
    {
        ret["__cdecl"] = "";
        ret["__fastcall"] = "";
        ret["__stdcall"] = "";
        ret["__thiscall"] = "";
    }

    // MSVC builtin types
    // see http://msdn.microsoft.com/en-us/library/cc953fe1.aspx
    {
        ret["__int8"] = "char";
        ret["__int16"] = "short";
        ret["__int32"] = "int";
        ret["__int64"] = "long long";
        ret["__int16"] = "short";
        ret["__ptr32"] = "";
        ret["__ptr64"] = "";
    }

    // MSVC specific modifiers
    // see http://msdn.microsoft.com/en-us/library/vstudio/s04b5w00.aspx
    {
        ret["__sptr"] = "";
        ret["__uptr"] = "";
        ret["__unaligned"] = "";
        ret["__w64"] = "";
    }

    // MSVC function specifiers
    // see http://msdn.microsoft.com/de-de/library/z8y1yy88.aspx
    {
        ret["__inline"] = "";
        ret["__forceinline"] = "";
    }

    return ret;
}
예제 #12
0
int main( int argc, char **argv )
{
    KAboutData aboutData( "nspluginscan", "nsplugin", ki18n("nspluginscan"),
                          "0.3", ki18n("nspluginscan"), KAboutData::License_GPL,
                          ki18n("(c) 2000,2001 by Stefan Schimanski") );

    KCmdLineArgs::init( argc, argv, &aboutData );

    KCmdLineOptions options;
    options.add("verbose", ki18n("Show progress output for GUI"));
    KCmdLineArgs::addCmdLineOptions( options );
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    showProgress = args->isSet("verbose");
    if (showProgress) {
      printf("10\n"); fflush(stdout);
    }

    KApplication app(false);

    // Set up SIGCHLD handler
    struct sigaction act;
    act.sa_handler=sigChildHandler;
    sigemptyset(&(act.sa_mask));
    sigaddset(&(act.sa_mask), SIGCHLD);
    // Make sure we don't block this signal. gdb tends to do that :-(
    sigprocmask(SIG_UNBLOCK, &(act.sa_mask), 0);

    act.sa_flags = SA_NOCLDSTOP;

    // CC: take care of SunOS which automatically restarts interrupted system
    // calls (and thus does not have SA_RESTART)

#ifdef SA_RESTART
    act.sa_flags |= SA_RESTART;
#endif

    struct sigaction oldact;
    sigaction( SIGCHLD, &act, &oldact );


    // set up the paths used to look for plugins
    QStringList searchPaths = getSearchPaths();
    QStringList mimeInfoList;

    infoConfig = new KConfig( KGlobal::dirs()->saveLocation("data", "nsplugins") +
                              "/pluginsinfo" );
    infoConfig->group("<default>").writeEntry( "number", 0 );

    // open the cache file for the mime information
    QString cacheName = KGlobal::dirs()->saveLocation("data", "nsplugins")+"/cache";
    kDebug(1433) << "Creating MIME cache file " << cacheName;
    QFile cachef(cacheName);
    if (!cachef.open(QIODevice::WriteOnly))
        return -1;
    QTextStream cache(&cachef);
    if (showProgress) {
      printf("20\n"); fflush(stdout);
    }

    // read in the plugins mime information
    kDebug(1433) << "Scanning directories" << searchPaths;
    int count = searchPaths.count();
    int i = 0;
    for ( QStringList::const_iterator it = searchPaths.constBegin();
          it != searchPaths.constEnd(); ++it, ++i)
    {
        if ((*it).isEmpty())
            continue;
        scanDirectory( *it, mimeInfoList, cache );
        if (showProgress) {
          printf("%d\n", 25 + (50*i) / count ); fflush(stdout);
        }
    }

    if (showProgress) {
      printf("75\n"); fflush(stdout);
    }

    // We're done with forking,
    // KProcess needs SIGCHLD to be reset to what it was initially
    sigaction( SIGCHLD, &oldact, 0 );

    // delete old mime types
    kDebug(1433) << "Removing old mimetypes";
    const QStringList oldMimes = deletePluginMimeTypes();
    bool mimeTypesChanged = !oldMimes.isEmpty();

    if (showProgress) {
      printf("80\n");  fflush(stdout);
    }

    // write mimetype files
    kDebug(1433) << "Creating MIME type descriptions";
    QStringList mimeTypes;
    for ( QStringList::const_iterator it=mimeInfoList.constBegin();
          it!=mimeInfoList.constEnd(); ++it) {

      kDebug(1433) << "Handling MIME type " << *it;

      QStringList info = (*it).split(':', QString::KeepEmptyParts);
      if ( info.count()==4 ) {
          QString pluginName = info[0];
          QString type = info[1].toLower();
          QString extension = info[2];
          QString desc = info[3];

          // append to global mime type list
          if ( !mimeTypes.contains(type) ) {
              kDebug(1433) << " - mimeType=" << type;
              mimeTypes.append( type );

              // write or update mime type file, if
              // 1) it doesn't exist in ksycoca (meaning we never heard of it)
              // 2) or we just deleted it [it's still in ksycoca though]
              // This prevents noticing that a shared-mime-info upgrade brought
              // us a mimetype we needed; but doing this right requires launching
              // kbuildsycoca4 after removing mimetypes above, and that's really slow
              bool mustWriteMimeType = KMimeType::mimeType(type).isNull();
              if (!mustWriteMimeType)
                  mustWriteMimeType = oldMimes.contains(type);
              if ( mustWriteMimeType ) {
                  kDebug(1433) << " - creating MIME type description";
                  removeExistingExtensions( extension );
                  generateMimeType( type, extension, pluginName, desc );
                  mimeTypesChanged = true;
              } else {
                  kDebug(1433) << " - already exists";
              }
          }
        }
    }

    // done with new mimetypes, run update-mime-database
    if (mimeTypesChanged) {
        MimeTypeWriter::runUpdateMimeDatabase();
        // note that we'll run kbuildsycoca below anyway
    }

    if (showProgress) {
      printf("85\n"); fflush(stdout);
    }

    // close files
    kDebug(1433) << "Closing cache file";
    cachef.close();

    infoConfig->sync();
    delete infoConfig;

    // write plugin lib service file
    writeServicesFile( mimeTypes );
    if (showProgress) {
      printf("90\n"); fflush(stdout);
    }

    if (QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kded")) {
        // Tell kded to update sycoca database.
        QDBusInterface kbuildsycoca("org.kde.kded", "/kbuildsycoca",
                                    "org.kde.kded");
        kbuildsycoca.call("recreate");
    } else {
        // kded not running? fallback to calling kbuildsycoca directly:
        KProcess proc;
        proc << KStandardDirs::findExe(KBUILDSYCOCA_EXENAME);
        proc.setOutputChannelMode(KProcess::MergedChannels); // silence kbuildsycoca output
        proc.execute();
    }
}
예제 #13
0
파일: krdb.cpp 프로젝트: KDE/kde-workspace
void runRdb( uint flags )
{
  // Obtain the application palette that is about to be set.
  bool exportColors      = flags & KRdbExportColors;
  bool exportQtColors    = flags & KRdbExportQtColors;
  bool exportQtSettings  = flags & KRdbExportQtSettings;
  bool exportXftSettings = flags & KRdbExportXftSettings;
  bool exportGtkTheme    = flags & KRdbExportGtkTheme;

  KSharedConfigPtr kglobalcfg = KSharedConfig::openConfig( "kdeglobals" );
  KConfigGroup kglobals(kglobalcfg, "KDE");
  QPalette newPal = KGlobalSettings::createApplicationPalette(kglobalcfg);

  KTemporaryFile tmpFile;
  if (!tmpFile.open())
  {
    kDebug() << "Couldn't open temp file";
    exit(0);
  }


  KConfigGroup generalCfgGroup(kglobalcfg, "General");

  QString gtkTheme;
  if (generalCfgGroup.hasKey("widgetStyle"))
    gtkTheme = generalCfgGroup.readEntry("widgetStyle");
  else
    gtkTheme = "oxygen";

  createGtkrc( exportColors, newPal, exportGtkTheme, gtkTheme, 1 );
  createGtkrc( exportColors, newPal, exportGtkTheme, gtkTheme, 2 );

  // Export colors to non-(KDE/Qt) apps (e.g. Motif, GTK+ apps)
  if (exportColors)
  {
    KGlobal::dirs()->addResourceType("appdefaults", "data", "kdisplay/app-defaults/");

    QString preproc;
    QColor backCol = newPal.color( QPalette::Active, QPalette::Background );
    addColorDef(preproc, "FOREGROUND"         , newPal.color( QPalette::Active, QPalette::Foreground ) );
    addColorDef(preproc, "BACKGROUND"         , backCol);
    addColorDef(preproc, "HIGHLIGHT"          , backCol.light(100+(2*KGlobalSettings::contrast()+4)*16/1));
    addColorDef(preproc, "LOWLIGHT"           , backCol.dark(100+(2*KGlobalSettings::contrast()+4)*10));
    addColorDef(preproc, "SELECT_BACKGROUND"  , newPal.color( QPalette::Active, QPalette::Highlight));
    addColorDef(preproc, "SELECT_FOREGROUND"  , newPal.color( QPalette::Active, QPalette::HighlightedText));
    addColorDef(preproc, "WINDOW_BACKGROUND"  , newPal.color( QPalette::Active, QPalette::Base ) );
    addColorDef(preproc, "WINDOW_FOREGROUND"  , newPal.color( QPalette::Active, QPalette::Foreground ) );
    addColorDef(preproc, "INACTIVE_BACKGROUND", KGlobalSettings::inactiveTitleColor());
    addColorDef(preproc, "INACTIVE_FOREGROUND", KGlobalSettings::inactiveTitleColor());
    addColorDef(preproc, "ACTIVE_BACKGROUND"  , KGlobalSettings::activeTitleColor());
    addColorDef(preproc, "ACTIVE_FOREGROUND"  , KGlobalSettings::activeTitleColor());
    //---------------------------------------------------------------

    tmpFile.write( preproc.toLatin1(), preproc.length() );

    QStringList list;

    const QStringList adPaths = KGlobal::dirs()->findDirs("appdefaults", "");
    for (QStringList::ConstIterator it = adPaths.constBegin(); it != adPaths.constEnd(); ++it) {
      QDir dSys( *it );

      if ( dSys.exists() ) {
        dSys.setFilter( QDir::Files );
        dSys.setSorting( QDir::Name );
        dSys.setNameFilters(QStringList("*.ad"));
        list += dSys.entryList();
      }
    }

    for (QStringList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it)
      copyFile(tmpFile, KStandardDirs::locate("appdefaults", *it ), true);
  }

  // Merge ~/.Xresources or fallback to ~/.Xdefaults
  QString homeDir = QDir::homePath();
  QString xResources = homeDir + "/.Xresources";

  // very primitive support for ~/.Xresources by appending it
  if ( QFile::exists( xResources ) )
    copyFile(tmpFile, xResources, true);
  else
    copyFile(tmpFile, homeDir + "/.Xdefaults", true);

  // Export the Xcursor theme & size settings
  KConfigGroup mousecfg(KSharedConfig::openConfig( "kcminputrc" ), "Mouse" );
  QString theme = mousecfg.readEntry("cursorTheme", QString());
  QString size  = mousecfg.readEntry("cursorSize", QString());
  QString contents;

  if (!theme.isNull())
    contents = "Xcursor.theme: " + theme + '\n';

  if (!size.isNull())
    contents += "Xcursor.size: " + size + '\n';

  if (exportXftSettings)
  {
    if (generalCfgGroup.hasKey("XftAntialias"))
    {
      contents += "Xft.antialias: ";
      if(generalCfgGroup.readEntry("XftAntialias", true))
        contents += "1\n";
      else
        contents += "0\n";
    }

    if (generalCfgGroup.hasKey("XftHintStyle"))
    {
      QString hintStyle = generalCfgGroup.readEntry("XftHintStyle", "hintmedium");
      contents += "Xft.hinting: ";
      if(hintStyle.isEmpty())
        contents += "-1\n";
      else
      {
        if(hintStyle!="hintnone")
          contents += "1\n";
        else
          contents += "0\n";
        contents += "Xft.hintstyle: " + hintStyle + '\n';
      }
    }

    if (generalCfgGroup.hasKey("XftSubPixel"))
    {
      QString subPixel = generalCfgGroup.readEntry("XftSubPixel");
      if(!subPixel.isEmpty())
        contents += "Xft.rgba: " + subPixel + '\n';
    }

    KConfig _cfgfonts( "kcmfonts" );
    KConfigGroup cfgfonts(&_cfgfonts, "General");

    if( cfgfonts.readEntry( "forceFontDPI", 0 ) != 0 )
      contents += "Xft.dpi: " + cfgfonts.readEntry( "forceFontDPI" ) + '\n';
    else
    {
      KProcess proc;
      proc << "xrdb" << "-quiet" << "-remove" << "-nocpp";
      proc.start();
      if (proc.waitForStarted())
      {
        proc.write( QByteArray( "Xft.dpi\n" ) );
        proc.closeWriteChannel();
        proc.waitForFinished();
      }
    }
  }

  if (contents.length() > 0)
    tmpFile.write( contents.toLatin1(), contents.length() );

  tmpFile.flush();

  KProcess proc;
#ifndef NDEBUG
  proc << "xrdb" << "-merge" << tmpFile.fileName();
#else
  proc << "xrdb" << "-quiet" << "-merge" << tmpFile.fileName();
#endif
  proc.execute();

  applyGtkStyles(exportColors, 1);
  applyGtkStyles(exportColors, 2);

  /* Qt exports */
  if ( exportQtColors || exportQtSettings )
  {
    QSettings* settings = new QSettings(QLatin1String("Trolltech"));

    if ( exportQtColors )
      applyQtColors( kglobalcfg, *settings, newPal );    // For kcmcolors

    if ( exportQtSettings )
      applyQtSettings( kglobalcfg, *settings );          // For kcmstyle

    delete settings;
    QApplication::flush();
#if HAVE_X11
    if (qApp->platformName() == QStringLiteral("xcb")) {
        // We let KIPC take care of ourselves, as we are in a KDE app with
        // QApp::setDesktopSettingsAware(false);
        // Instead of calling QApp::x11_apply_settings() directly, we instead
        // modify the timestamp which propagates the settings changes onto
        // Qt-only apps without adversely affecting ourselves.

        // Cheat and use the current timestamp, since we just saved to qtrc.
        QDateTime settingsstamp = QDateTime::currentDateTime();

        static Atom qt_settings_timestamp = 0;
        if (!qt_settings_timestamp) {
            QString atomname("_QT_SETTINGS_TIMESTAMP_");
            atomname += XDisplayName( 0 ); // Use the $DISPLAY envvar.
            qt_settings_timestamp = XInternAtom( QX11Info::display(), atomname.toLatin1(), False);
        }

        QBuffer stamp;
        QDataStream s(&stamp.buffer(), QIODevice::WriteOnly);
        s << settingsstamp;
        XChangeProperty( QX11Info::display(), QX11Info::appRootWindow(), qt_settings_timestamp,
                        qt_settings_timestamp, 8, PropModeReplace,
                        (unsigned char*) stamp.buffer().data(),
                        stamp.buffer().size() );
        QApplication::flush();
    }
#endif
  }
}
void runRdb( uint flags )
{
  // Obtain the application palette that is about to be set.
  bool exportColors      = flags & KRdbExportColors;
  bool exportQtColors    = flags & KRdbExportQtColors;
  bool exportQtSettings  = flags & KRdbExportQtSettings;
  bool exportXftSettings = flags & KRdbExportXftSettings;
  bool exportGtkTheme    = flags & KRdbExportGtkTheme;

  KSharedConfigPtr kglobalcfg = KSharedConfig::openConfig( QStringLiteral("kdeglobals") );
  KConfigGroup kglobals(kglobalcfg, "KDE");
  QPalette newPal = KColorScheme::createApplicationPalette(kglobalcfg);

  QTemporaryFile tmpFile;
  if (!tmpFile.open())
  {
    qDebug() << "Couldn't open temp file";
    exit(0);
  }


  KConfigGroup generalCfgGroup(kglobalcfg, "General");

  QString gtkTheme;
  if (kglobals.hasKey("widgetStyle"))
    gtkTheme = kglobals.readEntry("widgetStyle");
  else
    gtkTheme = QStringLiteral("oxygen");

  createGtkrc( exportColors, newPal, exportGtkTheme, gtkTheme, 1 );
  createGtkrc( exportColors, newPal, exportGtkTheme, gtkTheme, 2 );

  // Export colors to non-(KDE/Qt) apps (e.g. Motif, GTK+ apps)
  if (exportColors)
  {
    KConfigGroup g(KSharedConfig::openConfig(), "WM");
    QString preproc;
    QColor backCol = newPal.color( QPalette::Active, QPalette::Background );
    addColorDef(preproc, "FOREGROUND"         , newPal.color( QPalette::Active, QPalette::Foreground ) );
    addColorDef(preproc, "BACKGROUND"         , backCol);
    addColorDef(preproc, "HIGHLIGHT"          , backCol.light(100+(2*KColorScheme::contrast()+4)*16/1));
    addColorDef(preproc, "LOWLIGHT"           , backCol.dark(100+(2*KColorScheme::contrast()+4)*10));
    addColorDef(preproc, "SELECT_BACKGROUND"  , newPal.color( QPalette::Active, QPalette::Highlight));
    addColorDef(preproc, "SELECT_FOREGROUND"  , newPal.color( QPalette::Active, QPalette::HighlightedText));
    addColorDef(preproc, "WINDOW_BACKGROUND"  , newPal.color( QPalette::Active, QPalette::Base ) );
    addColorDef(preproc, "WINDOW_FOREGROUND"  , newPal.color( QPalette::Active, QPalette::Text ) );
    addColorDef(preproc, "INACTIVE_BACKGROUND", g.readEntry("inactiveBackground", QColor(224, 223, 222)));
    addColorDef(preproc, "INACTIVE_FOREGROUND", g.readEntry("inactiveBackground", QColor(224, 223, 222)));
    addColorDef(preproc, "ACTIVE_BACKGROUND"  , g.readEntry("activeBackground", QColor(48, 174, 232)));
    addColorDef(preproc, "ACTIVE_FOREGROUND"  , g.readEntry("activeBackground", QColor(48, 174, 232)));
    //---------------------------------------------------------------

    tmpFile.write( preproc.toLatin1(), preproc.length() );

    QStringList list;

    const QStringList adPaths = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation,
        QStringLiteral("kdisplay/app-defaults/"), QStandardPaths::LocateDirectory);
    for (QStringList::ConstIterator it = adPaths.constBegin(); it != adPaths.constEnd(); ++it) {
      QDir dSys( *it );

      if ( dSys.exists() ) {
        dSys.setFilter( QDir::Files );
        dSys.setSorting( QDir::Name );
        dSys.setNameFilters(QStringList(QStringLiteral("*.ad")));
        list += dSys.entryList();
      }
    }

    for (QStringList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it)
      copyFile(tmpFile, QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kdisplay/app-defaults/"+(*it)), true);
  }

  // Merge ~/.Xresources or fallback to ~/.Xdefaults
  QString homeDir = QDir::homePath();
  QString xResources = homeDir + "/.Xresources";

  // very primitive support for ~/.Xresources by appending it
  if ( QFile::exists( xResources ) )
    copyFile(tmpFile, xResources, true);
  else
    copyFile(tmpFile, homeDir + "/.Xdefaults", true);

  // Export the Xcursor theme & size settings
  KConfigGroup mousecfg(KSharedConfig::openConfig( QStringLiteral("kcminputrc") ), "Mouse" );
  QString theme = mousecfg.readEntry("cursorTheme", QString());
  QString size  = mousecfg.readEntry("cursorSize", QString());
  QString contents;

  if (!theme.isNull())
    contents = "Xcursor.theme: " + theme + '\n';

  if (!size.isNull())
    contents += "Xcursor.size: " + size + '\n';

  if (exportXftSettings)
  {
    if (generalCfgGroup.hasKey("XftAntialias"))
    {
      contents += QLatin1String("Xft.antialias: ");
      if(generalCfgGroup.readEntry("XftAntialias", true))
        contents += QLatin1String("1\n");
      else
        contents += QLatin1String("0\n");
    }

    if (generalCfgGroup.hasKey("XftHintStyle"))
    {
      QString hintStyle = generalCfgGroup.readEntry("XftHintStyle", "hintmedium");
      contents += QLatin1String("Xft.hinting: ");
      if(hintStyle.isEmpty())
        contents += QLatin1String("-1\n");
      else
      {
        if(hintStyle!=QLatin1String("hintnone"))
          contents += QLatin1String("1\n");
        else
          contents += QLatin1String("0\n");
        contents += "Xft.hintstyle: " + hintStyle + '\n';
      }
    }

    if (generalCfgGroup.hasKey("XftSubPixel"))
    {
      QString subPixel = generalCfgGroup.readEntry("XftSubPixel");
      if(!subPixel.isEmpty())
        contents += "Xft.rgba: " + subPixel + '\n';
    }

    KConfig _cfgfonts( QStringLiteral("kcmfonts") );
    KConfigGroup cfgfonts(&_cfgfonts, "General");

    if( cfgfonts.readEntry( "forceFontDPI", 0 ) != 0 )
      contents += "Xft.dpi: " + cfgfonts.readEntry( "forceFontDPI" ) + '\n';
    else
    {
      KProcess proc;
      proc << QStringLiteral("xrdb") << QStringLiteral("-quiet") << QStringLiteral("-remove") << QStringLiteral("-nocpp");
      proc.start();
      if (proc.waitForStarted())
      {
        proc.write( QByteArray( "Xft.dpi\n" ) );
        proc.closeWriteChannel();
        proc.waitForFinished();
      }
    }
  }

  if (contents.length() > 0)
    tmpFile.write( contents.toLatin1(), contents.length() );

  tmpFile.flush();

  KProcess proc;
#ifndef NDEBUG
  proc << QStringLiteral("xrdb") << QStringLiteral("-merge") << tmpFile.fileName();
#else
  proc << "xrdb" << "-quiet" << "-merge" << tmpFile.fileName();
#endif
  proc.execute();

  applyGtkStyles(exportColors, 1);
  applyGtkStyles(exportColors, 2);

  /* Qt exports */
  if ( exportQtColors || exportQtSettings )
  {
    QSettings* settings = new QSettings(QStringLiteral("Trolltech"));

    if ( exportQtColors )
      applyQtColors( kglobalcfg, *settings, newPal );    // For kcmcolors

    if ( exportQtSettings )
      applyQtSettings( kglobalcfg, *settings );          // For kcmstyle

    delete settings;
    QApplication::flush();
#if HAVE_X11
    if (qApp->platformName() == QStringLiteral("xcb")) {
        // We let KIPC take care of ourselves, as we are in a KDE app with
        // QApp::setDesktopSettingsAware(false);
        // Instead of calling QApp::x11_apply_settings() directly, we instead
        // modify the timestamp which propagates the settings changes onto
        // Qt-only apps without adversely affecting ourselves.

        // Cheat and use the current timestamp, since we just saved to qtrc.
        QDateTime settingsstamp = QDateTime::currentDateTime();

        static Atom qt_settings_timestamp = 0;
        if (!qt_settings_timestamp) {
            QString atomname(QStringLiteral("_QT_SETTINGS_TIMESTAMP_"));
            atomname += XDisplayName( 0 ); // Use the $DISPLAY envvar.
            qt_settings_timestamp = XInternAtom( QX11Info::display(), atomname.toLatin1(), False);
        }

        QBuffer stamp;
        QDataStream s(&stamp.buffer(), QIODevice::WriteOnly);
        s << settingsstamp;
        XChangeProperty( QX11Info::display(), QX11Info::appRootWindow(), qt_settings_timestamp,
                        qt_settings_timestamp, 8, PropModeReplace,
                        (unsigned char*) stamp.buffer().data(),
                        stamp.buffer().size() );
        QApplication::flush();
    }
#endif
  }

  //Legacy support:
  //Try to sync kde4 settings with ours

  Kdelibs4Migration migration;
  //kf5 congig groups for general and icons
  KConfigGroup generalGroup(kglobalcfg, "General");
  KConfigGroup iconsGroup(kglobalcfg, "Icons");

  const QString colorSchemeName = generalGroup.readEntry("ColorScheme", QString());
  //if no valid color scheme saved, something weird is going on, abort
  if (colorSchemeName.isEmpty()) {
      return;
  }
  //fix filename, copied from ColorsCM::saveScheme()
  QString colorSchemeFilename = colorSchemeName;
  colorSchemeFilename.remove('\''); // So Foo's does not become FooS
  QRegExp fixer(QStringLiteral("[\\W,.-]+(.?)"));
  int offset;
  while ((offset = fixer.indexIn(colorSchemeFilename)) >= 0)
      colorSchemeFilename.replace(offset, fixer.matchedLength(), fixer.cap(1).toUpper());
  colorSchemeFilename.replace(0, 1, colorSchemeFilename.at(0).toUpper());

  //clone the color scheme
  QString src = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "color-schemes/" +  colorSchemeFilename + ".colors");
  QString dest = migration.saveLocation("data", QStringLiteral("color-schemes")) + colorSchemeName + ".colors";

  QFile::remove(dest);
  QFile::copy(src, dest);

  //Apply the color scheme
  QString configFilePath = migration.saveLocation("config") + "kdeglobals";

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

  KConfig kde4config(configFilePath, KConfig::SimpleConfig);

  KConfigGroup kde4generalGroup(&kde4config, "General");
  kde4generalGroup.writeEntry("ColorScheme", colorSchemeName);

  //fonts
  QString font = generalGroup.readEntry("font", QString());
  if (!font.isEmpty()) {
      kde4generalGroup.writeEntry("font", font);
  }
  font = generalGroup.readEntry("desktopFont", QString());
  if (!font.isEmpty()) {
      kde4generalGroup.writeEntry("desktopFont", font);
  }
  font = generalGroup.readEntry("menuFont", QString());
  if (!font.isEmpty()) {
      kde4generalGroup.writeEntry("menuFont", font);
  }
  font = generalGroup.readEntry("smallestReadableFont", QString());
  if (!font.isEmpty()) {
      kde4generalGroup.writeEntry("smallestReadableFont", font);
  }
  font = generalGroup.readEntry("taskbarFont", QString());
  if (!font.isEmpty()) {
      kde4generalGroup.writeEntry("taskbarFont", font);
  }
  font = generalGroup.readEntry("toolBarFont", QString());
  if (!font.isEmpty()) {
      kde4generalGroup.writeEntry("toolBarFont", font);
  }

  //TODO: does exist any way to check if a qt4 widget style is present from a qt5 app?
  //kde4generalGroup.writeEntry("widgetStyle", "qtcurve");
  kde4generalGroup.sync();

  KConfigGroup kde4IconGroup(&kde4config, "Icons");
  QString iconTheme = iconsGroup.readEntry("Theme", QString());
  if (!iconTheme.isEmpty()) {
      kde4IconGroup.writeEntry("Theme", iconTheme);
  }
  kde4IconGroup.sync();

  //copy all the groups in the color scheme in kdeglobals
  KSharedConfigPtr kde4ColorConfig = KSharedConfig::openConfig(src, KConfig::SimpleConfig);

  foreach (const QString &grp, kde4ColorConfig->groupList()) {
      KConfigGroup cg(kde4ColorConfig, grp);
      KConfigGroup cg2(&kde4config, grp);
      cg.copyTo(&cg2);
  }

  //widgets settings
  KConfigGroup kglobals4(&kde4config, "KDE");
  kglobals4.writeEntry("ShowIconsInMenuItems", kglobals.readEntry("ShowIconsInMenuItems", true));
  kglobals4.writeEntry("ShowIconsOnPushButtons", kglobals.readEntry("ShowIconsOnPushButtons", true));
  kglobals4.writeEntry("contrast", kglobals.readEntry("contrast", 4));
  //FIXME: this should somehow check if the kde4 version of the style is installed
  kde4generalGroup.writeEntry("widgetStyle", kglobals.readEntry("widgetStyle", "breeze"));

  //toolbar style
  KConfigGroup toolbars4(&kde4config, "Toolbar style");
  KConfigGroup toolbars5(kglobalcfg, "Toolbar style");
  toolbars4.writeEntry("ToolButtonStyle", toolbars5.readEntry("ToolButtonStyle", "TextBesideIcon"));
  toolbars4.writeEntry("ToolButtonStyleOtherToolbars", toolbars5.readEntry("ToolButtonStyleOtherToolbars", "TextBesideIcon"));
}
void QGpgMECryptoConfigComponent::sync( bool runtime )
{
  KTemporaryFile tmpFile;
  tmpFile.open();

  QList<QGpgMECryptoConfigEntry *> dirtyEntries;

  // Collect all dirty entries
  const QList<QString> keylist = mGroupsByName.uniqueKeys();
  Q_FOREACH (const QString & key, keylist) {
    const QHash<QString,QGpgMECryptoConfigEntry*> entry = mGroupsByName[key]->mEntriesByName;
    const QList<QString> keylistentry = entry.uniqueKeys();
    Q_FOREACH (const QString & keyentry, keylistentry) {
      if(entry[keyentry]->isDirty())
      {
       // OK, we can set it.currentKey() to it.current()->outputString()
        QString line = keyentry;
        if ( entry[keyentry]->isSet() ) { // set option
          line += ":0:";
          line += entry[keyentry]->outputString();
        } else {                       // unset option
          line += ":16:";
        }
#ifdef Q_OS_WIN
        line += '\r';
#endif
        line += '\n';
        const QByteArray line8bit = line.toUtf8(); // encode with utf8, and K3ProcIO uses utf8 when reading.
        tmpFile.write( line8bit );
        dirtyEntries.append( entry[keyentry] );

      }
    }
  }

  tmpFile.flush();
  if ( dirtyEntries.isEmpty() )
    return;

  // Call gpgconf --change-options <component>
  const QString gpgconf = QGpgMECryptoConfig::gpgConfPath();
  QString commandLine = gpgconf.isEmpty()
      ? QString::fromLatin1( "gpgconf" )
      : KShell::quoteArg( gpgconf ) ;
  if ( runtime )
    commandLine += " --runtime";
  commandLine += " --change-options ";
  commandLine += KShell::quoteArg( mName );
  commandLine += " < ";
  commandLine += KShell::quoteArg( tmpFile.fileName() );

  //kDebug(5150) << commandLine;
  //system( QCString( "cat " ) + tmpFile.name().toLatin1() ); // DEBUG

  KProcess proc;
  proc.setShellCommand( commandLine );

  // run the process:
  int rc = proc.execute();

  if ( rc == -2 )
  {
    QString wmsg = i18n( "Could not start gpgconf.\nCheck that gpgconf is in the PATH and that it can be started." );
    kWarning(5150) << wmsg;
    KMessageBox::error(0, wmsg);
  }
  else if( rc != 0 ) // Happens due to bugs in gpgconf (e.g. issues 104/115)
  {
    QString wmsg = i18n( "Error from gpgconf while saving configuration: %1", QString::fromLocal8Bit( strerror( rc ) ) );
    kWarning(5150) <<":" << strerror( rc );
    KMessageBox::error(0, wmsg);
  }
  else
  {
    QList<QGpgMECryptoConfigEntry *>::const_iterator it = dirtyEntries.constBegin();
    for( ; it != dirtyEntries.constEnd(); ++it ) {
      (*it)->setDirty( false );
    }
  }
}