void nuclearCalculator::configChanged()
{
    KConfigGroup cg = config();

    m_massOnly = cg.readEntry("massOnly",true);
}
RecipeDB* RecipeDB::createDatabase()
{
	KConfigGroup config = KGlobal::config()->group( "DBType" );
	QString dbType = config.readEntry( "Type", "" );
	return createDatabase( dbType );
}
bool RecipeDB::restore( const QString &file, QString *errMsg )
{
	kDebug();
	m_dumpFile = KFilterDev::deviceForFile(file,"application/x-gzip");
	if ( m_dumpFile->open( QIODevice::ReadOnly ) ) {

		m_dumpFile->setTextModeEnabled( true );
		QString firstLine = QString::fromUtf8(m_dumpFile->readLine()).trimmed();
		QString dbVersion = QString::fromUtf8(m_dumpFile->readLine()).trimmed();
		dbVersion = dbVersion.right( dbVersion.length() - dbVersion.indexOf(":") - 2 );
		if ( qRound(dbVersion.toDouble()*1e5) > qRound(latestDBVersion()*1e5) ) { //correct for float's imprecision
			if ( errMsg ) *errMsg = i18n( "This backup was created with a newer version of Krecipes and cannot be restored." );
			delete m_dumpFile;
			return false;
		}

		KConfigGroup config = KGlobal::config()->group( "DBType" );
		QString dbType = QString::fromUtf8(m_dumpFile->readLine()).trimmed();
		dbType = dbType.right( dbType.length() - dbType.indexOf(":") - 2 );
		if ( dbType.isEmpty() || !firstLine.startsWith("-- Generated for Krecipes") ) {
			if ( errMsg ) *errMsg = i18n("This file is not a Krecipes backup file or has become corrupt.");
			delete m_dumpFile;
			return false;
		}
		else if ( dbType != config.readEntry("Type",QString()) ) {
			if ( errMsg ) *errMsg = i18n("This backup was created using the \"%1\" backend.  It can only be restored into a database using this backend." ,dbType);
			delete m_dumpFile;
			return false;
		}

		process = new KProcess;

		QStringList command = restoreCommand();
		kDebug()<<"Restoring backup using: "<<command[0];
		*process << command;

		QApplication::connect( process, SIGNAL(started()), this, SLOT(processStarted()) );
		QApplication::connect( process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(processError(QProcess::ProcessError)) );
		QApplication::connect( process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(processFinished(int,QProcess::ExitStatus)) );
	
		m_processStarted = false;
		m_processFinished = false;
		m_processError = false;
		m_operationHalted = false;

		emit progressBegin(0,QString(),
			QString("<center><b>%1</b></center>%2")
				.arg(i18nc("@info:progress", "Restoring backup"))
				.arg(i18n("Depending on the number of recipes and amount of data, this could take some time.")),50);

		process->start();
		m_localEventLoop = new QEventLoop;
		m_localEventLoop->exec();

		if ( m_processError && !m_processStarted ) {
			if ( errMsg ) *errMsg = i18n("Unable to find or run the program '%1'.  Either it is not installed on your system or it is not in $PATH.",
				command.first());
			delete m_localEventLoop;
			delete process;
			process = NULL;
			delete m_dumpFile;
			emit progressDone();
			return false;
		}
	
		//We have to first wipe the database structure.  Note that if we load a dump
		//with from a previous version of Krecipes, the difference in structure
		// wouldn't allow the data to be inserted.  This remains forward-compatibity
		//by loading the old schema and then porting it to the current version.
		kDebug()<<"Wiping database...";
		empty(); //the user had better be warned!
		kDebug()<<"Database wiped.";
	
		kDebug()<<"Reading backup file...";
		m_timer = new QTimer;
		QApplication::connect( m_timer, SIGNAL(timeout()), this, SLOT(processReadDump()) );
		m_timer->start();
		m_localEventLoop->exec();
		delete m_timer;
		kDebug()<<"Done.";

		//Since the process will exit when all stdin has been sent and processed,
		//just loop until the process is no longer running.  If something goes
		//wrong, the user can still hit cancel.
		process->closeWriteChannel();
		if (!m_processFinished && !m_processError) {
			kDebug()<<"Waiting for process exit...";
			m_localEventLoop->exec();
		}

		delete m_localEventLoop;
		delete process;
		process = NULL;
		emit progressDone();

		//Since we just loaded part of a file, the database won't be in a usable state.
		//We'll wipe out the database structure and recreate it, leaving no data.
		if ( haltOperation ) {
			haltOperation=false;
			empty();
			checkIntegrity();
			delete m_dumpFile;
			if ( errMsg ) { *errMsg = i18n("Restore Failed"); }
			return false;
		}

		m_dumpFile->close();

		checkIntegrity();
	}
	}
	return true;
}


void KrePropertyActionsHandler::saveElement( const QModelIndex & topLeft,
	const QModelIndex & bottomRight )
{
	//Not used parameters.
	Q_UNUSED( bottomRight )

	if ( topLeft.column() == 3 ) {
		KConfigGroup config = KGlobal::config()->group("Formatting");
	
		config.sync();
		QStringList hiddenList = config.readEntry("HiddenProperties", QStringList());
		QString propName = m_listWidget->getData( topLeft.row(), 1 ).toString();
		if ( m_listWidget->getItem( topLeft.row(), topLeft.column() )->checkState() == Qt::Checked ) {
			hiddenList.removeAll( propName );
		} else if ( !hiddenList.contains(propName) ) {
			hiddenList.append( propName );
		}

		config.writeEntry( "HiddenProperties", hiddenList );
	} else {	
		//Revert the changed text if the new name is longer than the maximum length. 
		QString newPropName = topLeft.data().toString();
		if ( !checkBounds(newPropName) ) {
			m_listWidget->reload( ForceReload ); //reset the changed text
			return ;
		}
	void SyndicationTab::loadState(KConfigGroup & g)
	{
		splitter->restoreState(g.readEntry("ver_splitter",QByteArray()));
	}
Exemple #6
0
int main(int argc, char *argv[])
{
	KCmdLineArgs::init(argc, argv, appName, "kscreensaver", ki18n("Random screen saver"), 
                KDE_VERSION_STRING, ki18n(description));


	KCmdLineOptions options;

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

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

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

	KCmdLineArgs::addCmdLineOptions(options);

	KApplication app;

	WId windowId = 0;

	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

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

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

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

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

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

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

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

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

	// If we end up here then we couldn't start a saver.
	// If we have been supplied a window id or root window then blank it.
#ifdef Q_WS_X11
	QX11Info info;
	Window win = windowId ? windowId : RootWindow(QX11Info::display(), info.screen());
	XSetWindowBackground(QX11Info::display(), win,
			BlackPixel(QX11Info::display(), info.screen()));
	XClearWindow(QX11Info::display(), win);
#endif
}
void KNode::Cleanup::loadConfig(const KConfigGroup &conf)
{
  // group expire settings
  d_oExpire = conf.readEntry( "doExpire", true );
  r_emoveUnavailable = conf.readEntry( "removeUnavailable", true );
  p_reserveThr = conf.readEntry( "saveThreads", true );
  e_xpireInterval = conf.readEntry( "expInterval", 5 );
  r_eadMaxAge = conf.readEntry( "readDays", 10 );
  u_nreadMaxAge = conf.readEntry( "unreadDays", 15 );
  mLastExpDate = conf.readEntry( "lastExpire", QDateTime() ).date();

  // folder compaction settings (only available globally)
  if (mGlobal) {
    d_oCompact = conf.readEntry( "doCompact", true );
    c_ompactInterval = conf.readEntry( "comInterval", 5 );
    mLastCompDate = conf.readEntry( "lastCompact", QDateTime() ).date();
  }

  if (!mGlobal)
    mDefault = conf.readEntry( "UseDefaultExpConf", true );
}
void SettingsWidget::readSettings(KConfigGroup& group)
{
    d->settingsExpander->readSettings(group);

    int useTimestampType = group.readEntry("Use Timestamp Type", (int)TimeAdjustSettings::APPDATE);
    if      (useTimestampType == TimeAdjustSettings::APPDATE)      d->useApplDateBtn->setChecked(true);
    else if (useTimestampType == TimeAdjustSettings::FILEDATE)     d->useFileDateBtn->setChecked(true);
    else if (useTimestampType == TimeAdjustSettings::METADATADATE) d->useMetaDateBtn->setChecked(true);
    else if (useTimestampType == TimeAdjustSettings::CUSTOMDATE)   d->useCustomDateBtn->setChecked(true);

    d->useFileDateTypeChooser->setCurrentIndex(group.readEntry("File Timestamp Type",   (int)TimeAdjustSettings::FILELASTMOD));
    d->useMetaDateTypeChooser->setCurrentIndex(group.readEntry("Meta Timestamp Type",   (int)TimeAdjustSettings::EXIFIPTCXMP));
    d->useCustDateInput->setDateTime(group.readEntry("Custom Date",                     QDateTime::currentDateTime()));
    d->useCustTimeInput->setDateTime(group.readEntry("Custom Time",                     QDateTime::currentDateTime()));

    d->adjTypeChooser->setCurrentIndex(group.readEntry("Adjustment Type",               (int)TimeAdjustSettings::COPYVALUE));
    d->adjDaysInput->setValue(group.readEntry("Adjustment Days",                        0));
    d->adjTimeInput->setDateTime(group.readEntry("Adjustment Time",                     QDateTime()));

    d->updAppDateCheck->setChecked(group.readEntry("Update Application Time",           false));
    d->updFileModDateCheck->setChecked(group.readEntry("Update File Modification Time", false));
    d->updEXIFModDateCheck->setChecked(group.readEntry("Update EXIF Modification Time", false));
    d->updEXIFOriDateCheck->setChecked(group.readEntry("Update EXIF Original Time",     false));
    d->updEXIFDigDateCheck->setChecked(group.readEntry("Update EXIF Digitization Time", false));
    d->updEXIFThmDateCheck->setChecked(group.readEntry("Update EXIF Thumbnail Time",    false));
    d->updIPTCDateCheck->setChecked(group.readEntry("Update IPTC Time",                 false));
    d->updXMPDateCheck->setChecked(group.readEntry("Update XMP Creation Time",          false));
    d->updFileNameCheck->setChecked(group.readEntry("Update File Name",                 false));

    slotSrcTimestampChanged();
    slotAdjustmentTypeChanged();
}
Exemple #9
0
double Effect::animationTime(const KConfigGroup& cfg, const QString& key, int defaultTime)
{
    int time = cfg.readEntry(key, 0);
    return time != 0 ? time : qMax(defaultTime * effects->animationTimeFactor(), 1.);
}
Exemple #10
0
QImage ThumbnailProtocol::thumbForDirectory(const QUrl& directory)
{
    QImage img;
    if (m_propagationDirectories.isEmpty()) {
        // Directories that the directory preview will be propagated into if there is no direct sub-directories
        const KConfigGroup globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
        m_propagationDirectories = globalConfig.readEntry("PropagationDirectories", QStringList() << "VIDEO_TS").toSet();
        m_maxFileSize = globalConfig.readEntry("MaximumSize", 5 * 1024 * 1024); // 5 MByte default
    }

    const int tiles = 2; //Count of items shown on each dimension
    const int spacing = 1;
    const int visibleCount = tiles * tiles;

    // TODO: the margins are optimized for the Oxygen iconset
    // Provide a fallback solution for other iconsets (e. g. draw folder
    // only as small overlay, use no margins)

    //Use the current (custom) folder icon
    const QMimeDatabase db;
    const QString iconName = db.mimeTypeForName("inode/directory").iconName();

    const QPixmap folder = QIcon::fromTheme(iconName).pixmap(qMin(m_width, m_height));

    const int folderWidth  = folder.width();
    const int folderHeight = folder.height();

    const int topMargin = folderHeight * 30 / 100;
    const int bottomMargin = folderHeight / 6;
    const int leftMargin = folderWidth / 13;
    const int rightMargin = leftMargin;

    const int segmentWidth  = (folderWidth  - leftMargin - rightMargin  + spacing) / tiles - spacing;
    const int segmentHeight = (folderHeight - topMargin  - bottomMargin + spacing) / tiles - spacing;
    if ((segmentWidth < 5) || (segmentHeight <  5)) {
        // the segment size is too small for a useful preview
        return img;
    }

    QString localFile = directory.path();

    // Multiply with a high number, so we get some semi-random sequence
    int skipValidItems = ((int)sequenceIndex()) * tiles * tiles;

    img = QImage(QSize(folderWidth, folderHeight), QImage::Format_ARGB32);
    img.fill(0);

    QPainter p;
    p.begin(&img);

    p.setCompositionMode(QPainter::CompositionMode_Source);
    p.drawPixmap(0, 0, folder);
    p.setCompositionMode(QPainter::CompositionMode_SourceOver);

    int xPos = leftMargin;
    int yPos = topMargin;

    int frameWidth = qRound(folderWidth / 85.);

    int iterations = 0;
    QString hadFirstThumbnail;
    int skipped = 0;

    const int maxYPos = folderHeight - bottomMargin - segmentHeight;

    // Setup image object for preview with only one tile
    QImage oneTileImg(folder.size(), QImage::Format_ARGB32);
    oneTileImg.fill(0);

    QPainter oneTilePainter(&oneTileImg);
    oneTilePainter.setCompositionMode(QPainter::CompositionMode_Source);
    oneTilePainter.drawPixmap(0, 0, folder);
    oneTilePainter.setCompositionMode(QPainter::CompositionMode_SourceOver);

    const int oneTileWidth = folderWidth - leftMargin - rightMargin;
    const int oneTileHeight = folderHeight - topMargin - bottomMargin;

    int validThumbnails = 0;

    while ((skipped <= skipValidItems) && (yPos <= maxYPos) && validThumbnails == 0) {
        QDirIterator dir(localFile, QDir::Files | QDir::Readable);
        if (!dir.hasNext()) {
            break;
        }

        while (dir.hasNext() && (yPos <= maxYPos)) {
            ++iterations;
            if (iterations > 500) {
                skipValidItems = skipped = 0;
                break;
            }

            dir.next();

            if (validThumbnails > 0 && hadFirstThumbnail == dir.filePath()) {
                break; // Never show the same thumbnail twice
            }

            if (dir.fileInfo().size() > m_maxFileSize) {
                // don't create thumbnails for files that exceed
                // the maximum set file size
                continue;
            }

            if (!drawSubThumbnail(p, dir.filePath(), segmentWidth, segmentHeight, xPos, yPos, frameWidth)) {
                continue;
            }

            if (validThumbnails == 0) {
                drawSubThumbnail(oneTilePainter, dir.filePath(), oneTileWidth, oneTileHeight, xPos, yPos, frameWidth);
            }

            if (skipped < skipValidItems) {
                ++skipped;
                continue;
            }

            if (hadFirstThumbnail.isEmpty()) {
                hadFirstThumbnail = dir.filePath();
            }

            ++validThumbnails;

            xPos += segmentWidth + spacing;
            if (xPos > folderWidth - rightMargin - segmentWidth) {
                xPos = leftMargin;
                yPos += segmentHeight + spacing;
            }
        }

        if (skipped != 0) { // Round up to full pages
            const int roundedDown = (skipped / visibleCount) * visibleCount;
            if (roundedDown < skipped) {
                skipped = roundedDown + visibleCount;
            } else {
                skipped = roundedDown;
            }
        }

        if (skipped == 0) {
            break; // No valid items were found
        }

        // We don't need to iterate again and again: Subtract any multiple of "skipped" from the count we still need to skip
        skipValidItems -= (skipValidItems / skipped) * skipped;
        skipped = 0;
    }

    p.end();

    if (validThumbnails == 0) {
        // Eventually propagate the contained items from a sub-directory
        QDirIterator dir(localFile, QDir::Dirs);
        int max = 50;
        while (dir.hasNext() && max > 0) {
            --max;
            dir.next();
            if (m_propagationDirectories.contains(dir.fileName())) {
                return thumbForDirectory(QUrl(dir.filePath()));
            }
        }

        // If no thumbnail could be found, return an empty image which indicates
        // that no preview for the directory is available.
        img = QImage();
    }

    // If only for one file a thumbnail could be generated then use image with only one tile
    if (validThumbnails == 1) {
        return oneTileImg;
    }

    return img;
}
Exemple #11
0
bool ThumbnailProtocol::createSubThumbnail(QImage& thumbnail, const QString& filePath,
                                           int segmentWidth, int segmentHeight)
{
    if (m_enabledPlugins.isEmpty()) {
        const KConfigGroup globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
        m_enabledPlugins = globalConfig.readEntry("Plugins", QStringList()
                                                             << "imagethumbnail"
                                                             << "jpegthumbnail"
                                                             << "videopreview");
    }

    const QMimeDatabase db;
    const QUrl fileUrl = QUrl::fromLocalFile(filePath);
    const QString subPlugin = pluginForMimeType(db.mimeTypeForUrl(fileUrl).name());
    if (subPlugin.isEmpty() || !m_enabledPlugins.contains(subPlugin)) {
        return false;
    }

    ThumbCreator* subCreator = getThumbCreator(subPlugin);
    if (!subCreator) {
        // qDebug() << "found no creator for" << dir.filePath();
        return false;
    }

    if ((segmentWidth <= 256) && (segmentHeight <= 256)) {
        // check whether a cached version of the file is available for
        // 128 x 128 or 256 x 256 pixels
        int cacheSize = 0;
        QCryptographicHash md5(QCryptographicHash::Md5);
        md5.addData(QFile::encodeName(fileUrl.toString()));
        const QString thumbName = QFile::encodeName(md5.result().toHex()).append(".png");

        if (m_thumbBasePath.isEmpty()) {
            m_thumbBasePath = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QLatin1String("/thumbnails/");
            QDir basePath(m_thumbBasePath);
            basePath.mkpath("normal/");
            QFile::setPermissions(basePath.absoluteFilePath("normal"), QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);
            basePath.mkpath("large/");
            QFile::setPermissions(basePath.absoluteFilePath("large"), QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);
        }

        QDir thumbPath(m_thumbBasePath);
        if ((segmentWidth <= 128) && (segmentHeight <= 128)) {
            cacheSize = 128;
            thumbPath.cd("normal");
        } else {
            cacheSize = 256;
            thumbPath.cd("large");
        }
        if (!thumbnail.load(thumbPath.absoluteFilePath(thumbName))) {
            // no cached version is available, a new thumbnail must be created

            QSaveFile thumbnailfile(thumbPath.absoluteFilePath(thumbName));
            bool savedCorrectly = false;
            if (subCreator->create(filePath, cacheSize, cacheSize, thumbnail)) {
                scaleDownImage(thumbnail, cacheSize, cacheSize);

                // The thumbnail has been created successfully. Store the thumbnail
                // to the cache for future access.
                if (thumbnailfile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
                    savedCorrectly = thumbnail.save(&thumbnailfile, "PNG");
                }
            } else {
                return false;
            }
            if(savedCorrectly)
            {
                thumbnailfile.commit();
            }
        }
    } else if (!subCreator->create(filePath, segmentWidth, segmentHeight, thumbnail)) {
        return false;
    }
    return true;
}
Exemple #12
0
void SettingsCore::loadSettings()
{
#ifdef ABAKUS_QTONLY
    //TODO
#else
    KConfigGroup config = KGlobal::config()->group("Settings");
    
    QString mode = config.readEntry("Trigonometric mode", "Degrees");
    if(mode == "Degrees") {
        setTrigMode(Abakus::Degrees);
    }
    else {
        setTrigMode(Abakus::Radians);
    }
    
    int precision = config.readEntry("Decimal Precision", -1);
    if(precision < -1 || precision > 75)
    {
        precision = -1;
    }
    
    Abakus::m_prec = precision;
    
    m_historyLimit = config.readEntry("History Limit", 500);
    
    
    config = KGlobal::config()->group("GUI");
    
    m_mathematicalSidebarVisible = config.readEntry("ShowMathematicalSidebar", true);
    m_mathematicalSidebarActiveView = config.readEntry("MathematicalSidebarActiveTab", "numerals");
    m_mathematicalSidebarWidth = config.readEntry("MathematicalSidebarWidth", 200);
    
    m_compactMode = config.readEntry("InCompactMode", false);
    
    m_windowSize = config.readEntry("Size", QSize(600, 220));
    
    
    config = KGlobal::config()->group("Variables");
    QStringList variableKeys = config.keyList();
    QStringList variableValues;
    Abakus::Number number;
    
    for(int i = 0; i < variableKeys.count(); ++i)
    {
        variableValues = config.readEntry(variableKeys[i], QStringList());
        if(variableValues.count() < 3) continue;
        
        number = Abakus::Number(variableValues[1].toLatin1());
        number.setNumeralSystem((Abakus::NumeralSystem) variableValues[2].toInt());
        
        NumeralModel::instance()->setValue(variableValues[0], number);
    }
    
    
    config = KGlobal::config()->group("Functions");
    QStringList functionKeys = config.keyList();
    QString functionValue;
    
    for(int i = 0; i < functionKeys.count(); ++i)
    {
        functionValue = config.readEntry(functionKeys[i], QString());
        if(functionValue.isEmpty()) continue;
                                      
        QByteArray strValue = "set " + functionValue.toLatin1();
        parseString(strValue.data()); // Run the function definitions through the parser
    }
    
    
    config = KGlobal::config()->group("History");
    QStringList historyKeys = config.keyList();
    QStringList historyValues;
    ResultModel* resultModel = ResultModel::instance();
    ResultModelItem* resultModelItem;
    
    for(int i = historyKeys.count() - 1; i >= 0; --i)
    {
        historyValues = config.readEntry(historyKeys[i], QStringList());
        if(historyValues.count() < 1) continue;
        
        if(historyValues[0].toInt() == ResultModelItem::Result)
        {
            if(historyValues.count() < 4) continue;
            number = Abakus::Number(historyValues[2].toLatin1());
            number.setNumeralSystem((Abakus::NumeralSystem) historyValues[3].toInt());
            resultModelItem = new ResultModelItem(historyValues[1], number);
        }
        else
        {
            if(historyValues.count() < 3) continue;
            resultModelItem = new ResultModelItem(historyValues[1], historyValues[2]);
        }
        resultModel->addResultModelItem(resultModelItem);
    }
    
    m_actionCollection->readSettings();
#endif
}
Exemple #13
0
void Autocorrect::readConfig()
{
    KConfigGroup interface = KoGlobal::kofficeConfig()->group("Autocorrect");

    m_enabled->setChecked(interface.readEntry("enabled", m_enabled->isChecked()));
    m_uppercaseFirstCharOfSentence = interface.readEntry("UppercaseFirstCharOfSentence", m_uppercaseFirstCharOfSentence);
    m_fixTwoUppercaseChars = interface.readEntry("FixTwoUppercaseChars", m_fixTwoUppercaseChars);
    m_autoFormatURLs = interface.readEntry("AutoFormatURLs", m_autoFormatURLs);
    m_singleSpaces = interface.readEntry("SingleSpaces", m_singleSpaces);
    m_trimParagraphs = interface.readEntry("TrimParagraphs", m_trimParagraphs);
    m_autoBoldUnderline = interface.readEntry("AutoBoldUnderline", m_autoBoldUnderline);
    m_autoFractions = interface.readEntry("AutoFractions", m_autoFractions);
    m_autoNumbering = interface.readEntry("AutoNumbering", m_autoNumbering);
    m_superscriptAppendix = interface.readEntry("SuperscriptAppendix", m_superscriptAppendix);
    m_capitalizeWeekDays = interface.readEntry("CapitalizeWeekDays", m_capitalizeWeekDays);
    m_autoFormatBulletList = interface.readEntry("AutoFormatBulletList", m_autoFormatBulletList);
    m_advancedAutocorrect = interface.readEntry("AdvancedAutocorrect", m_advancedAutocorrect);

    m_replaceDoubleQuotes = interface.readEntry("ReplaceDoubleQuotes", m_replaceDoubleQuotes);
    m_replaceSingleQuotes = interface.readEntry("ReplaceSingleQuotes", m_replaceSingleQuotes);

    m_autocorrectLang = interface.readEntry("formatLanguage", m_autocorrectLang);

    readAutocorrectXmlEntry();
}
Exemple #14
0
void DatapickerCurve::init() {
	Q_D(DatapickerCurve);

	KConfig config;
	KConfigGroup group;
	group = config.group("DatapickerCurve");
	d->posXColumn = NULL;
	d->posYColumn = NULL;
	d->posZColumn = NULL;
	d->plusDeltaXColumn = NULL;
	d->minusDeltaXColumn = NULL;
	d->plusDeltaYColumn = NULL;
	d->minusDeltaYColumn = NULL;
	d->curveErrorTypes.x = (ErrorType) group.readEntry("CurveErrorType_X", (int) NoError);
	d->curveErrorTypes.y = (ErrorType) group.readEntry("CurveErrorType_X", (int) NoError);

	// point properties
	d->pointStyle = (Symbol::Style)group.readEntry("PointStyle", (int)Symbol::Cross);
	d->pointSize = group.readEntry("Size", Worksheet::convertToSceneUnits(7, Worksheet::Point));
	d->pointRotationAngle = group.readEntry("Rotation", 0.0);
	d->pointOpacity = group.readEntry("Opacity", 1.0);
	d->pointBrush.setStyle( (Qt::BrushStyle)group.readEntry("FillingStyle", (int)Qt::NoBrush) );
	d->pointBrush.setColor( group.readEntry("FillingColor", QColor(Qt::black)) );
	d->pointPen.setStyle( (Qt::PenStyle)group.readEntry("BorderStyle", (int)Qt::SolidLine) );
	d->pointPen.setColor( group.readEntry("BorderColor", QColor(Qt::red)) );
	d->pointPen.setWidthF( group.readEntry("BorderWidth", Worksheet::convertToSceneUnits(1, Worksheet::Point)) );
	d->pointErrorBarSize = group.readEntry("ErrorBarSize", Worksheet::convertToSceneUnits(8, Worksheet::Point));
	d->pointErrorBarBrush.setStyle( (Qt::BrushStyle)group.readEntry("ErrorBarFillingStyle", (int)Qt::NoBrush) );
	d->pointErrorBarBrush.setColor( group.readEntry("ErrorBarFillingColor", QColor(Qt::black)) );
	d->pointErrorBarPen.setStyle( (Qt::PenStyle)group.readEntry("ErrorBarBorderStyle", (int)Qt::SolidLine) );
	d->pointErrorBarPen.setColor( group.readEntry("ErrorBarBorderColor", QColor(Qt::black)) );
	d->pointErrorBarPen.setWidthF( group.readEntry("ErrorBarBorderWidth", Worksheet::convertToSceneUnits(1, Worksheet::Point)) );
	d->pointVisibility = group.readEntry("PointVisibility", true);

	this->initAction();
}
Exemple #15
0
PanoLastPage::PanoLastPage(PanoManager* const mngr, QWizard* const dlg)
     : DWizardPage(dlg, i18nc("@title:window", "<b>Panorama Stitched</b>")),
       d(new Private)
{
    KConfig config;
    KConfigGroup group        = config.group("Panorama Settings");

    d->mngr                   = mngr;

    DVBox* const vbox         = new DVBox(this);

    d->title                  = new QLabel(vbox);
    d->title->setOpenExternalLinks(true);
    d->title->setWordWrap(true);

    QVBoxLayout* const formatVBox = new QVBoxLayout();

    d->saveSettingsGroupBox   = new QGroupBox(i18nc("@title:group", "Save Settings"), vbox);
    d->saveSettingsGroupBox->setLayout(formatVBox);
    formatVBox->addStretch(1);

    QLabel* const fileTemplateLabel = new QLabel(i18nc("@label:textbox", "File name template:"), d->saveSettingsGroupBox);
    formatVBox->addWidget(fileTemplateLabel);

    d->fileTemplateQLineEdit  = new QLineEdit(QLatin1String("panorama"), d->saveSettingsGroupBox);
    d->fileTemplateQLineEdit->setToolTip(i18nc("@info:tooltip", "Name of the panorama file (without its extension)."));
    d->fileTemplateQLineEdit->setWhatsThis(i18nc("@info:whatsthis", "<b>File name template</b>: Set here the base name of the files that "
                                                "will be saved. For example, if your template is <i>panorama</i> and if "
                                                "you chose a JPEG output, then your panorama will be saved with the "
                                                "name <i>panorama.jpg</i>. If you choose to save also the project file, "
                                                "it will have the name <i>panorama.pto</i>."));
    formatVBox->addWidget(d->fileTemplateQLineEdit);

    d->savePtoCheckBox        = new QCheckBox(i18nc("@option:check", "Save project file"), d->saveSettingsGroupBox);
    d->savePtoCheckBox->setChecked(group.readEntry("Save PTO", false));
    d->savePtoCheckBox->setToolTip(i18nc("@info:tooltip", "Save the project file for further processing within Hugin GUI."));
    d->savePtoCheckBox->setWhatsThis(i18nc("@info:whatsthis", "<b>Save project file</b>: You can keep the project file generated to stitch "
                                          "your panorama for further tweaking within "
                                          "<a href=\"http://hugin.sourceforge.net/\">Hugin</a> by checking this. "
                                          "This is useful if you want a different projection, modify the horizon or "
                                          "the center of the panorama, or modify the control points to get better results."));
    formatVBox->addWidget(d->savePtoCheckBox);

    d->warningLabel = new QLabel(d->saveSettingsGroupBox);
    d->warningLabel->hide();
    formatVBox->addWidget(d->warningLabel);

    d->errorLabel = new QLabel(d->saveSettingsGroupBox);
    d->errorLabel->hide();
    formatVBox->addWidget(d->errorLabel);

    vbox->setStretchFactor(new QWidget(vbox), 2);

    setPageWidget(vbox);

    QPixmap leftPix(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QLatin1String("digikam/data/assistant-hugin.png")));
    setLeftBottomPix(leftPix.scaledToWidth(128, Qt::SmoothTransformation));

    connect(d->fileTemplateQLineEdit, SIGNAL(textChanged(QString)),
            this, SLOT(slotTemplateChanged(QString)));

    connect(d->savePtoCheckBox, SIGNAL(stateChanged(int)),
            this, SLOT(slotPtoCheckBoxChanged(int)));
}
Exemple #16
0
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    App::initializeDependencies();

    auto aboutData = App::getAboutData();
    QCommandLineParser parser;
    KAboutData::setApplicationData(aboutData);
    parser.addVersionOption();
    parser.addHelpOption();
    aboutData.setupCommandLine(&parser);
    parser.process(app);
    aboutData.processCommandLine(&parser);

    KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("zanshin-migratorrc"));
    KConfigGroup group = config->group("Migrations");
    if (!group.readEntry("Migrated021Projects", false)) {
        std::cerr << "Migrating data from zanshin 0.2, please wait..." << std::endl;
        QProcess proc;
        proc.start(QStringLiteral("zanshin-migrator"));
        proc.waitForFinished(-1);
        if (proc.exitStatus() == QProcess::CrashExit) {
            std::cerr << "Migrator crashed!" << std::endl;
        } else if (proc.exitCode() == 0) {
            std::cerr << "Migration done" << std::endl;
        } else {
            std::cerr << "Migration error, code" << proc.exitCode() << std::endl;
        }
    }

    auto widget = new QWidget;
    auto components = new Widgets::ApplicationComponents(widget);
    components->setModel(Presentation::ApplicationModel::Ptr::create());

    auto layout = new QVBoxLayout;
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(components->pageView());
    widget->setLayout(layout);

    auto sourcesDock = new QDockWidget(QObject::tr("Sources"));
    sourcesDock->setObjectName(QStringLiteral("sourcesDock"));
    sourcesDock->setWidget(components->availableSourcesView());

    auto pagesDock = new QDockWidget(QObject::tr("Pages"));
    pagesDock->setObjectName(QStringLiteral("pagesDock"));
    pagesDock->setWidget(components->availablePagesView());

    auto editorDock = new QDockWidget(QObject::tr("Editor"));
    editorDock->setObjectName(QStringLiteral("editorDock"));
    editorDock->setWidget(components->editorView());

    auto window = new KXmlGuiWindow;
    window->setCentralWidget(widget);

    window->addDockWidget(Qt::RightDockWidgetArea, editorDock);
    window->addDockWidget(Qt::LeftDockWidgetArea, pagesDock);
    window->addDockWidget(Qt::LeftDockWidgetArea, sourcesDock);

    auto actions = components->globalActions();
    actions.insert(QStringLiteral("dock_sources"), sourcesDock->toggleViewAction());
    actions.insert(QStringLiteral("dock_pages"), pagesDock->toggleViewAction());
    actions.insert(QStringLiteral("dock_editor"), editorDock->toggleViewAction());

    auto ac = window->actionCollection();
    ac->addAction(KStandardAction::Quit, window, SLOT(close()));
    for (auto it = actions.constBegin(); it != actions.constEnd(); ++it) {
        auto shortcut = it.value()->shortcut();
        if (!shortcut.isEmpty()) {
            ac->setDefaultShortcut(it.value(), shortcut);
        }
        ac->addAction(it.key(), it.value());
    }

    window->setupGUI(QSize(1024, 600),
                     KXmlGuiWindow::ToolBar
                   | KXmlGuiWindow::Keys
                   | KXmlGuiWindow::Save
                   | KXmlGuiWindow::Create);
    window->show();

    return app.exec();
}
Exemple #17
0
 float ScriptingModule::readConfigEntryFloat(const QString& group, const QString& name, float default_value)
 {
     KConfigGroup g = KSharedConfig::openConfig()->group(group);
     return g.readEntry(name, default_value);
 }
Exemple #18
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;
    }
Exemple #19
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();
    }
}
void PanelBrowserMenu::initialize()
{
    _lastpress = QPoint(-1, -1);

    // don't change menu if already visible
    if (isVisible())
        return;

    if (_dirty) {
        // directory content changed while menu was visible
        slotClear();
        setInitialized(false);
        _dirty = false;
    }

    if (initialized()) return;
    setInitialized(true);

    // start watching if not already done
    if (!_dirWatch.contains(path()))
        _dirWatch.addDir( path() );

    // setup icon map
    initIconMap();

    // clear maps
    _filemap.clear();
    _mimemap.clear();

    QDir::Filters filter = QDir::Dirs | QDir::Files;
    if (KickerSettings::showHiddenFiles())
    {
        filter |= QDir::Hidden;
    }

    QDir dir(path(), QString(), QDir::DirsFirst | QDir::Name | QDir::IgnoreCase, filter);

    // does the directory exist?
    if (!dir.exists()) {
        insertItem(i18n("Failed to Read Folder"));
	return;
    }

    // get entry list
    QFileInfoList list = dir.entryInfoList();

    KUrl url;
    url.setPath(path());
    if (!KAuthorized::authorizeUrlAction("list", KUrl(), url))
    {
        insertItem(i18n("Not Authorized to Read Folder"));
        return;
    }

    // insert file manager and terminal entries
    // only the first part menu got them
    if(_startid == 0 && !_filesOnly) {
       // FIXME: no more menu titles so NOW WHAT?!
       // insertTitle(path());
       insertItem(CICON("kfm"), i18n("Open in File Manager"), this, SLOT(slotOpenFileManager()));
        if (KAuthorized::authorizeKAction("shell_access"))
            insertItem(CICON("terminal"), i18n("Open in Terminal"), this, SLOT(slotOpenTerminal()));
    }


    bool first_entry = true;
    bool dirfile_separator = false;
    unsigned int item_count = 0;
    int run_id = _startid;

    // get list iterator
    QFileInfoList::iterator it = list.begin();

    // jump to startid
    it += _startid;

    // iterate over entry list
    for (; it != list.end(); ++it)
    {
        // bump id
        run_id++;

        QFileInfo fi = *it;
        // handle directories
        if (fi.isDir())
        {
            QString name = fi.fileName();

            // ignore . and .. entries
            if (name == "." || name == "..") continue;

            QPixmap icon;
            QString path = fi.absoluteFilePath();

            // parse .directory if it does exist
            if (QFile::exists(path + "/.directory")) {

                KDesktopFile c(path + "/.directory");
                const KConfigGroup cg = c.desktopGroup();
                QString iconPath = cg.readEntry("Icon");

                if ( iconPath.startsWith("./") )
                    iconPath = path + '/' + iconPath.mid(2);

                icon = KIconLoader::global()->loadIcon(iconPath,
                                                    KIconLoader::Small, KIconLoader::SizeSmall,
                                                    KIconLoader::DefaultState, QStringList(), 0, true);
                if(icon.isNull())
                    icon = CICON("folder");
                name = cg.readEntry("Name", name);
            }

            // use cached folder icon for directories without special icon
            if (icon.isNull())
                icon = CICON("folder");

            // insert separator if we are the first menu entry
            if(first_entry) {
                if (_startid == 0 && !_filesOnly)
                    addSeparator();
                first_entry = false;
            }

            // append menu entry
            PanelBrowserMenu *submenu = new PanelBrowserMenu(path, this);
            submenu->_filesOnly = _filesOnly;
            append(icon, name, submenu);

            // bump item count
            item_count++;

            dirfile_separator = true;
        }
        // handle files
        else if(fi.isFile())
        {
            QString name = fi.fileName();
            QString title = KIO::decodeFileName(name);

            QPixmap icon;
            QString path = fi.absoluteFilePath();

            bool mimecheck = false;

            // .desktop files
            if(KDesktopFile::isDesktopFile(path))
            {
                KDesktopFile c( path );
                const KConfigGroup cg = c.desktopGroup();
                title = cg.readEntry("Name", title);

                QString s = cg.readEntry("Icon");
                if(!_icons->contains(s)) {
                    icon  = KIconLoader::global()->loadIcon(s, KIconLoader::Small, KIconLoader::SizeSmall,
                                                         KIconLoader::DefaultState, QStringList(), 0, true);

                    if(icon.isNull()) {
                        QString type = cg.readEntry("Type", "Application");
                        if (type == "Directory")
                            icon = CICON("folder");
                        else if (type == "Mimetype")
                            icon = CICON("txt");
                        else if (type == "FSDevice")
                            icon = CICON("chardevice");
                        else
                            icon = CICON("exec");
                    }
                    else
                        _icons->insert(s, icon);
                }
                else
                    icon = CICON(s);
            }
            else {
                // set unknown icon
                icon = CICON("unknown");

                // mark for delayed mimetime check
                mimecheck = true;
            }

            // insert separator if we are the first menu entry
            if(first_entry) {
                if(_startid == 0 && !_filesOnly)
                    addSeparator();
                first_entry = false;
            }

            // insert separator if we we first file after at least one directory
            if (dirfile_separator) {
                addSeparator();
                dirfile_separator = false;
            }

            // append file entry
            append(icon, title, name, mimecheck);

            // bump item count
            item_count++;
        }

        if (item_count == KickerSettings::maxEntries2())
        {
            // Only insert a "More" item if there are actually more items.
            ++it;
            if( it != list.end() ) {
                addSeparator();
                append(CICON("kdisknav"), i18n("More"), new PanelBrowserMenu(path(), this, run_id));
            }
            break;
        }
    }

#if 0
    // WABA: tear off handles don't work together with dynamically updated
    // menus. We can't update the menu while torn off, and we don't know
    // when it is torn off.
    if(KGlobalSettings::insertTearOffHandle() && item_count > 0)
        insertTearOffHandle();
#endif

    adjustSize();

    QString dirname = path();

    int maxlen = contentsRect().width() - 40;
    if(item_count == 0)
        maxlen = fontMetrics().width(dirname);

    if (fontMetrics().width(dirname) > maxlen) {
        while ((!dirname.isEmpty()) && (fontMetrics().width(dirname) > (maxlen - fontMetrics().width("..."))))
            dirname = dirname.remove(0, 1);
        dirname.prepend("...");
    }
    setWindowTitle(dirname);

    // setup and start delayed mimetype check timer
    if(_mimemap.count() > 0) {

        if(!_mimecheckTimer)
            _mimecheckTimer = new QTimer(this);

        connect(_mimecheckTimer, SIGNAL(timeout()), SLOT(slotMimeCheck()));
        _mimecheckTimer->start(0);
    }
}
void K3b::WriterSelectionWidget::loadConfig( const KConfigGroup& c )
{
    setWriterDevice( k3bcore->deviceManager()->findDevice( c.readEntry( "writer_device" ) ) );
    setSpeed( c.readEntry( "writing_speed",  s_autoSpeedValue ) );
    setWritingApp( K3b::writingAppFromString( c.readEntry( "writing_app" ) ) );
}
void WeatherWallpaper::init(const KConfigGroup & config)
{
    // Connect to weather engine.
    weatherEngine = dataEngine(QLatin1String( "weather" ));

    // Set custom weather options
    m_source = config.readEntry("source");
    m_weatherUpdateTime = config.readEntry("updateWeather", 30);

    m_color = config.readEntry("wallpapercolor", QColor(56, 111, 150));
    m_dir = KStandardDirs::installPath("wallpaper");
    m_usersWallpapers = config.readEntry("userswallpapers", QStringList());
    m_resizeMethod = (ResizeMethod)config.readEntry("wallpaperposition", (int)ScaledResize);

    m_animation = new QPropertyAnimation(this, "fadeValue");
    m_animation->setProperty("easingCurve", QEasingCurve::InQuad);
    m_animation->setProperty("duration", 1000);
    m_animation->setProperty("startValue", 0.0);
    m_animation->setProperty("endValue", 1.0);

    m_weatherMap[QLatin1String( "weather-clear" )] = config.readEntry("clearPaper", QString(m_dir + QLatin1String( "Fields_of_Peace/" )));
    m_weatherMap[QLatin1String( "weather-few-clouds" )] = config.readEntry("partlyCloudyPaper", QString(m_dir + QLatin1String( "Evening/" )));
    m_weatherMap[QLatin1String( "weather-clouds" )] = config.readEntry("cloudyPaper", QString(m_dir + QLatin1String( "Colorado_Farm/" )));
    m_weatherMap[QLatin1String( "weather-many-clouds" )] = config.readEntry("manyCloudsPaper", QString(m_dir + QLatin1String( "Beach_Reflecting_Clouds/" )));
    m_weatherMap[QLatin1String( "weather-showers" )] = config.readEntry("showersPaper", QString(m_dir + QLatin1String( "There_is_Rain_on_the_Table/" )));
    m_weatherMap[QLatin1String( "weather-showers-scattered" )] = config.readEntry("showersScatteredPaper", QString(m_dir + QLatin1String( "There_is_Rain_on_the_Table/" )));
    m_weatherMap[QLatin1String( "weather-rain" )] = config.readEntry("rainPaper", QString(m_dir + QLatin1String( "There_is_Rain_on_the_Table/" )));
    m_weatherMap[QLatin1String( "weather-mist" )] = config.readEntry("mistPaper", QString(m_dir + QLatin1String( "Fresh_Morning/" )));
    m_weatherMap[QLatin1String( "weather-storm" )] = config.readEntry("stormPaper", QString(m_dir + QLatin1String( "Storm/" )));
    m_weatherMap[QLatin1String( "weather-scattered-storms" )] = m_weatherMap[QLatin1String( "weather-storm" )];
    m_weatherMap[QLatin1String( "weather-hail" )] = config.readEntry("hailPaper", QString(m_dir + QLatin1String( "Storm/" )));
    m_weatherMap[QLatin1String( "weather-snow" )] = config.readEntry("snowPaper", QString(m_dir + QLatin1String( "Winter_Track/" )));
    m_weatherMap[QLatin1String( "weather-snow-scattered" )] = config.readEntry("snowScatteredPaper", QString(m_dir + QLatin1String( "Winter_Track/" )));
    m_weatherMap[QLatin1String( "weather-few-clouds-night" )] = config.readEntry("partlyCloudyNightPaper", QString(m_dir + QLatin1String( "JK_Bridge_at_Night/" )));
    m_weatherMap[QLatin1String( "weather-clouds-night" )] = config.readEntry("cloudyNightPaper", QString(m_dir + QLatin1String( "JK_Bridge_at_Night/" )));
    m_weatherMap[QLatin1String( "weather-clear-night" )] = config.readEntry("clearNightPaper", QString(m_dir + QLatin1String( "City_at_Night/" )));
    m_weatherMap[QLatin1String( "weather-freezing-rain" )] = config.readEntry("freezingRainPaper", QString(m_dir + QLatin1String( "Icy_Tree/" )));
    m_weatherMap[QLatin1String( "weather-snow-rain" )] = config.readEntry("snowRainPaper", QString(m_dir + QLatin1String( "Icy_Tree/" )));

    calculateGeometry();
    connectWeatherSource();
}
Exemple #23
0
void Config::load()
{
    QTime time;
    time.start();

    QStringList formats;

    KSharedConfig::Ptr conf = KGlobal::config();
    KConfigGroup group;

    group = conf->group( "General" );
    data.app.configVersion = group.readEntry( "configVersion", 0 );
    data.general.startTab = group.readEntry( "startTab", 0 );
    data.general.lastTab = group.readEntry( "lastTab", 0 );
    data.general.defaultProfile = group.readEntry( "defaultProfile", i18n("Last used") );
    data.general.lastProfile = group.readEntry( "lastProfile", i18n("High") );
    data.general.defaultFormat = group.readEntry( "defaultFormat", i18n("Last used") );
    data.general.lastFormat = group.readEntry( "lastFormat", "ogg vorbis" );
    data.general.lastOutputDirectoryMode = group.readEntry( "lastOutputDirectoryMode", 0 );
    data.general.specifyOutputDirectory = group.readEntry( "specifyOutputDirectory", QDir::homePath() + "/soundKonverter" );
    data.general.metaDataOutputDirectory = group.readEntry( "metaDataOutputDirectory", QDir::homePath() + "/soundKonverter/%b/%d - %n - %a - %t" );
    data.general.copyStructureOutputDirectory = group.readEntry( "copyStructureOutputDirectory", QDir::homePath() + "/soundKonverter" );
    data.general.lastMetaDataOutputDirectoryPaths = group.readEntry( "lastMetaDataOutputDirectoryPaths", QStringList() );
    data.general.lastNormalOutputDirectoryPaths = group.readEntry( "lastNormalOutputDirectoryPaths", QStringList() );
    data.general.waitForAlbumGain = group.readEntry( "waitForAlbumGain", true );
    data.general.useVFATNames = group.readEntry( "useVFATNames", false );
    data.general.copyIfSameCodec = group.readEntry( "copyIfSameCodec", false );
    data.general.writeLogFiles = group.readEntry( "writeLogFiles", false );
    data.general.conflictHandling = (Config::Data::General::ConflictHandling)group.readEntry( "conflictHandling", 0 );
//     data.general.priority = group.readEntry( "priority", 10 );
    data.general.numFiles = group.readEntry( "numFiles", 0 );
    data.general.numReplayGainFiles = group.readEntry( "numReplayGainFiles", 0 );
    if( data.general.numFiles == 0 || data.general.numReplayGainFiles == 0 )
    {
        QList<Solid::Device> processors = Solid::Device::listFromType(Solid::DeviceInterface::Processor, QString());
        const int num = processors.count() > 0 ? processors.count() : 1;
        if( data.general.numFiles == 0 )
            data.general.numFiles = num;
        if( data.general.numReplayGainFiles == 0 )
            data.general.numReplayGainFiles = num;
    }
//     data.general.executeUserScript = group.readEntry( "executeUserScript", false );
//     data.general.showToolBar = group.readEntry( "showToolBar", false );
//     data.general.outputFilePermissions = group.readEntry( "outputFilePermissions", 644 );
    data.general.actionMenuConvertMimeTypes = group.readEntry( "actionMenuConvertMimeTypes", QStringList() );
    data.general.actionMenuReplayGainMimeTypes = group.readEntry( "actionMenuReplayGainMimeTypes", QStringList() );
    data.general.replayGainGrouping = (Config::Data::General::ReplayGainGrouping)group.readEntry( "replayGainGrouping", 0 );
    data.general.preferredOggVorbisExtension = group.readEntry( "preferredOggVorbisExtension", "ogg" );
    data.general.preferredVorbisCommentCommentTag = group.readEntry( "preferredVorbisCommentCommentTag", "DESCRIPTION" );
    data.general.preferredVorbisCommentTrackTotalTag = group.readEntry( "preferredVorbisCommentTrackTotalTag", "TRACKTOTAL" );
    data.general.preferredVorbisCommentDiscTotalTag = group.readEntry( "preferredVorbisCommentDiscTotalTag", "DISCTOTAL" );

    // due to a bug lastNormalOutputDirectoryPaths could have more than 5 items
    while( data.general.lastNormalOutputDirectoryPaths.count() > 5 )
        data.general.lastNormalOutputDirectoryPaths.takeLast();

    group = conf->group( "Advanced" );
    data.advanced.useSharedMemoryForTempFiles = group.readEntry( "useSharedMemoryForTempFiles", false );
    data.advanced.sharedMemorySize = 0;
    if( QFile::exists("/dev/shm") )
    {
        system("df -B 1M /dev/shm | tail -1 > /dev/shm/soundkonverter_shm_size");
        QFile chkdf("/dev/shm/soundkonverter_shm_size");
        if( chkdf.open(QIODevice::ReadOnly|QIODevice::Text) )
        {
            QTextStream t( &chkdf );
            QString s = t.readLine();
            QRegExp rxlen( "^(?:\\S+)(?:\\s+)(?:\\s+)(\\d+)(?:\\s+)(\\d+)(?:\\s+)(\\d+)(?:\\s+)(\\d+)" );
            if( s.contains(rxlen) )
            {
                data.advanced.sharedMemorySize = rxlen.cap(1).toInt();
            }
            chkdf.close();
        }
        chkdf.remove();
    }
    data.advanced.maxSizeForSharedMemoryTempFiles = group.readEntry( "maxSizeForSharedMemoryTempFiles", data.advanced.sharedMemorySize / 4 );
    data.advanced.usePipes = group.readEntry( "usePipes", false );
    data.advanced.ejectCdAfterRip = group.readEntry( "ejectCdAfterRip", true );

    group = conf->group( "CoverArt" );
    data.coverArt.writeCovers = group.readEntry( "writeCovers", 1 );
    data.coverArt.writeCoverName = group.readEntry( "writeCoverName", 0 );
    data.coverArt.writeCoverDefaultName = group.readEntry( "writeCoverDefaultName", i18nc("cover file name","cover") );

    group = conf->group( "Backends" );
    formats = group.readEntry( "formats", QStringList() );
    foreach( const QString format, formats )
    {
        CodecData codecData;
        codecData.codecName = format;
        codecData.encoders = group.readEntry( format + "_encoders", QStringList() );
        codecData.decoders = group.readEntry( format + "_decoders", QStringList() );
        codecData.replaygain = group.readEntry( format + "_replaygain", QStringList() );
        data.backends.codecs += codecData;
    }
void ICCSettingsContainer::readFromConfig(KConfigGroup& group)
{
    enableCM                      = group.readEntry("EnableCM", true);

    //if (!group.hasKey("OnProfileMismatch") && group.hasKey("BehaviourICC")) // legacy
    //  behavior = group.readEntry("BehaviourICC", false) ? "convert" : "ask";

    QString sRGB = IccProfile::sRGB().filePath();

    workspaceProfile              = group.readPathEntry("WorkProfileFile", sRGB);
    monitorProfile                = group.readPathEntry("MonitorProfileFile", sRGB);
    defaultInputProfile           = group.readPathEntry("InProfileFile", QString());
    defaultProofProfile           = group.readPathEntry("ProofProfileFile", QString());

    defaultMismatchBehavior       = (Behavior)group.readEntry("DefaultMismatchBehavior", (int)EmbeddedToWorkspace);
    defaultMissingProfileBehavior = (Behavior)group.readEntry("DefaultMissingProfileBehavior", (int)SRGBToWorkspace);
    defaultUncalibratedBehavior   = (Behavior)group.readEntry("DefaultUncalibratedBehavior", (int)AutoToWorkspace);

    lastMismatchBehavior          = (Behavior)group.readEntry("LastMismatchBehavior", (int)EmbeddedToWorkspace);
    lastMissingProfileBehavior    = (Behavior)group.readEntry("LastMissingProfileBehavior", (int)SRGBToWorkspace);
    lastUncalibratedBehavior      = (Behavior)group.readEntry("LastUncalibratedBehavior", (int)AutoToWorkspace);
    lastSpecifiedAssignProfile    = group.readEntry("LastSpecifiedAssignProfile", sRGB);
    lastSpecifiedInputProfile     = group.readEntry("LastSpecifiedInputProfile", defaultInputProfile);

    useBPC                        = group.readEntry("BPCAlgorithm", true);
    useManagedView                = group.readEntry("ManagedView", true);
    useManagedPreviews            = group.readEntry("ManagedPreviews", true);
    renderingIntent               = group.readEntry("RenderingIntent", (int)IccTransform::Perceptual);

    proofingRenderingIntent       = group.readEntry("ProofingRenderingIntent", (int)IccTransform::AbsoluteColorimetric);
    doGamutCheck                  = group.readEntry("DoGamutCheck", false);
    gamutCheckMaskColor           = group.readEntry("GamutCheckMaskColor", QColor(126, 255, 255));

    iccFolder                     = group.readEntry("DefaultPath", QString());
}
soundkonverter_filter_sox::soundkonverter_filter_sox( QObject *parent, const QStringList& args  )
    : FilterPlugin( parent )
{
    Q_UNUSED(args)

    binaries["sox"] = "";

    KSharedConfig::Ptr conf = KGlobal::config();
    KConfigGroup group;

    group = conf->group( "Plugin-"+name() );
    configVersion = group.readEntry( "configVersion", 0 );
    samplingRateQuality = group.readEntry( "samplingRateQuality", "high" );
    experimentalEffectsEnabled = group.readEntry( "experimentalEffectsEnabled", false );
    soxLastModified = group.readEntry( "soxLastModified", QDateTime() );
    soxCodecList = group.readEntry( "codecList", QStringList() ).toSet();

    SoxCodecData data;

    // 8svx aif aifc aiff aiffc al amb amr-nb amr-wb anb au avr awb caf cdda cdr cvs cvsd cvu dat dvms f32 f4 f64 f8 fap flac fssd gsm gsrt hcom htk ima ircam la lpc lpc10 lu mat mat4 mat5 maud mp2 mp3 nist ogg paf prc pvf raw s1 s16 s2 s24 s3 s32 s4 s8 sb sd2 sds sf sl sln smp snd sndfile sndr sndt sou sox sph sw txw u1 u16 u2 u24 u3 u32 u4 u8 ub ul uw vms voc vorbis vox w64 wav wavpcm wv wve xa xi

    // todo
    // al amb anb au avr awb caf cdda cdr cvs cvsd cvu dat dvms f32 f4 f64 f8 fap fssd gsm gsrt hcom htk ima ircam la lpc lpc10 lu mat mat4 mat5 maud nist ogg paf prc pvf raw s1 s16 s2 s24 s3 s32 s4 s8 sb sd2 sds sf sl sln smp snd sndfile sndr sndt sou sox sph sw txw u1 u16 u2 u24 u3 u32 u4 u8 ub ul uw vms voc vox w64 wavpcm wv wve xa xi

    // WARNING enabled codecs need to be rescanned everytime new codecs are added here -> increase plugin version

    data.codecName = "wav";
    data.soxCodecName = "wav";
    data.external = false;
    data.experimental = false;
    codecList.append( data );

    data.codecName = "flac";
    data.soxCodecName = "flac";
    data.external = true;
    data.experimental = false;
    codecList.append( data );

    data.codecName = "ogg vorbis";
    data.soxCodecName = "vorbis";
    data.external = true;
    data.experimental = false;
    codecList.append( data );

    data.codecName = "mp2";
    data.soxCodecName = "mp2";
    data.external = true;
    data.experimental = false;
    codecList.append( data );

    data.codecName = "mp3";
    data.soxCodecName = "mp3";
    data.external = true;
    data.experimental = false;
    codecList.append( data );

    data.codecName = "amr nb";
    data.soxCodecName = "amr-nb";
    data.external = true;
    data.experimental = false;
    codecList.append( data );

    data.codecName = "amr wb";
    data.soxCodecName = "amr-wb";
    data.external = true;
    data.experimental = false;
    codecList.append( data );

    data.codecName = "8svx";
    data.soxCodecName = "8svx";
    data.external = false;
    data.experimental = false;
    codecList.append( data );

    data.codecName = "aiff";
    data.soxCodecName = "aiff"; // aiff has meta data, aif not
    data.external = false;
    data.experimental = false;
    codecList.append( data );

//     sox only supports uncompressed aiff-c
//     data.codecName = "aiff-c";
//     data.soxCodecName = "aifc";
//     data.external = false;
//     data.experimental = false;
//     codecList.append( data );

    for( int i=0; i<codecList.count(); i++ )
    {
        if( !codecList.at(i).external && ( !codecList.at(i).experimental || experimentalEffectsEnabled ) )
        {
            codecList[i].enabled = true;
        }
        else
        {
            codecList[i].enabled = false;
        }
    }
}
void    MassifConfigPage::loadFromConfiguration(const KConfigGroup& cfg, KDevelop::IProject *)
{
    bool wasBlocked = signalsBlocked();
    blockSignals(true);

    ui->massifParameters->setText(cfg.readEntry("Massif Arguments", ""));
    ui->launchMassifVisualizer->setChecked(cfg.readEntry("launchVisualizer", false));
    ui->massifVisualizerExecutable->setText(cfg.readEntry("visualizerExecutable", "/usr/bin/massif-visualizer"));
    ui->depth->setValue(cfg.readEntry("depth", 30));
    ui->threshold->setValue(cfg.readEntry("threshold", 1));
    ui->peakInaccuracy->setValue(cfg.readEntry("peakInaccuracy", 1));
    ui->maxSnapshots->setValue(cfg.readEntry("maxSnapshots", 100));
    ui->snapshotFreq->setValue(cfg.readEntry("snapshotFreq", 10));
    ui->timeUnit->setCurrentIndex(cfg.readEntry("timeUnit", 0));
    ui->profileHeap->setChecked(cfg.readEntry("profileHeap", true));
    ui->profileStack->setChecked(cfg.readEntry("profileStack", false));

    blockSignals(wasBlocked);
}
bool RecipeDB::backup( const QString &backup_file, QString *errMsg )
{
	kDebug()<<"Backing up current database to "<<backup_file;

	process = new KProcess;

	m_dumpFile = KFilterDev::deviceForFile(backup_file,"application/x-gzip");
	if ( !m_dumpFile->open( QIODevice::WriteOnly ) ) {
		kDebug()<<"Couldn't open "<<backup_file;
		return false;
	}

	m_dumpFile->setTextModeEnabled( true );

	QStringList command = backupCommand();
	if ( command.count() == 0 ) {
		kDebug()<<"Backup not available for this database backend";
		return false;
	}

	KConfigGroup config = KGlobal::config()->group( "DBType" );

	QString dbVersionString = QString::number(latestDBVersion());
	m_dumpFile->write(QByteArray("-- Generated for Krecipes v")); 
		m_dumpFile->write(krecipes_version().toUtf8()); m_dumpFile->write(QByteArray("\n"));
	m_dumpFile->write(QByteArray("-- Krecipes database schema: "));
		m_dumpFile->write(dbVersionString.toUtf8()); m_dumpFile->write(QByteArray("\n"));
	m_dumpFile->write(QByteArray("-- Krecipes database backend: "));
		m_dumpFile->write(config.readEntry( "Type" ).toUtf8()); m_dumpFile->write(QByteArray("\n"));

	kDebug()<<"Running '"<<command.first()<<"' to create backup file";
	*process << command /*<< ">" << backup_file*/;

	QApplication::connect( process, SIGNAL(readyRead()), this, SLOT(processDumpOutput()) );
	QApplication::connect( process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(processFinished(int,QProcess::ExitStatus)) );
	QApplication::connect( process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(processError(QProcess::ProcessError)) );

	process->setOutputChannelMode( KProcess::MergedChannels );
	m_processFinished = false;
	m_processError = false;
	haltOperation = false;
	m_operationHalted = false;

	emit progressBegin(0,QString(),
		QString("<center><b>%1</b></center>%2")
			.arg(i18nc("@info:progress", "Creating complete backup"))
			.arg(i18n("Depending on the number of recipes and amount of data, this could take some time.")),50);

	m_localEventLoop = new QEventLoop;

	//This timer is to let the GUI kill the process even if it's hanged,
	//i.e. we will not receive readyRead() signals anymore for any reason.
	m_timer = new QTimer;
	QApplication::connect( m_timer, SIGNAL(timeout()), this, SLOT(cancelWatcher()) );
	m_timer->start(1000);

	process->start();
	m_localEventLoop->exec();
	delete m_timer;
	delete m_localEventLoop;
	
	if ( m_operationHalted ) {
		//User cancelled it; we'll still consider the operation successful,
		//but delete the file we created.
		kDebug()<<"Process killed, deleting partial backup.";
		QFile::remove(backup_file);
	} else if ( m_processError && !m_processFinished) {
		if ( errMsg ) *errMsg = i18n("Unable to find or run the program '%1'.  Either it is not installed on your system or it is not in $PATH.",command.first());
		QFile::remove(backup_file);
		delete process;
		process = NULL;
		delete m_dumpFile;
		emit progressDone();
		return false;
	} else if ((m_exitCode != 0) || (m_exitStatus != QProcess::NormalExit)) {
		kDebug()<<"Process failed.";
		//Since the process failed, dumpStream should have output from the app as to why it did
		QString appOutput;
		m_dumpFile->close();
		if ( m_dumpFile->open( QIODevice::ReadOnly ) ) {
			QTextStream appErrStream( m_dumpFile );

			//ignore our own versioning output
			appErrStream.readLine();
			appErrStream.readLine();
			appErrStream.readLine();

			appOutput = appErrStream.readAll();
		}
		else
			kDebug()<<"Unable to open file to get error output.";

		if ( errMsg ) *errMsg = i18n("Backup failed.\n%1", appOutput);
		QFile::remove(backup_file);
		delete process;
		process = NULL;
		delete m_dumpFile;
		emit progressDone();
		return false;
	}

	kDebug()<<"Backup finished.";

	delete process;
	process = NULL;
	delete m_dumpFile;
	emit progressDone();
	return true;
}
Exemple #28
0
int KSaveIOConfig::proxyDisplayUrlFlags()
{
    KConfigGroup cfg (config(), QString());
    return cfg.readEntry("ProxyUrlDisplayFlags", 0);
}
void KisHSXColorSliderInput::setValue(double v)
{

    //This function returns the colour based on the type of the slider as well as the value//

    qreal h=0.0;
    qreal s=0.0;
    qreal l=0.0;
    KConfigGroup cfg =  KSharedConfig::openConfig()->group("advancedColorSelector");
    R = cfg.readEntry("lumaR", 0.2126);
    G = cfg.readEntry("lumaG", 0.7152);
    B = cfg.readEntry("lumaB", 0.0722);
    Gamma = cfg.readEntry("gamma", 2.2);

    switch (m_type) {
    case 0:
        m_hue = v;
        h=m_hue/360.0;
        s=m_sat/100.0;
        l=m_val/100.0;
        *m_color = this->converter()->fromHsvF(h, s, l);
        if (m_hueupdating==false) {
            emit(hueUpdated(static_cast<int>(m_hue)));
        }
        else {
            m_hueupdating=false;
        }
        break;
    case 3:
        m_hue = v;
        h=m_hue/360.0;
        s=m_sat/100.0;
        l=m_val/100.0;
        *m_color = this->converter()->fromHslF(h, s, l);
        if (m_hueupdating==false) {
            emit(hueUpdated(static_cast<int>(m_hue)));
        }
        else {
            m_hueupdating=false;
        }
        break;
    case 6:
        m_hue = v;
        h=m_hue/360.0;
        s=m_sat/100.0;
        l=m_val/100.0;
        *m_color = this->converter()->fromHsiF(h, s, l);
        if (m_hueupdating==false) {
            emit(hueUpdated(static_cast<int>(m_hue)));
        }
        else {
            m_hueupdating=false;
        }
        break;
    case 9:
        m_hue = v;
        h=m_hue/360.0f;
        s=m_sat/100.0f;
        l=m_val/100.0f;
        *m_color = this->converter()->fromHsyF(h, s, l, R, G, B, Gamma);
        if (m_hueupdating==false) {
            emit(hueUpdated(static_cast<int>(m_hue)));
        }
        else {
            m_hueupdating=false;
        }
        break;
    case 1:
        m_sat = v;
        h=m_hue/360.0f;
        s=m_sat/100.0f;
        l=m_val/100.0f;
        *m_color = this->converter()->fromHsvF(h, s, l);
        if (m_satupdating==false) {
            emit(satUpdated(static_cast<int>(m_sat), m_type));
        }
        else {
            m_satupdating=false;
        }
        break;
    case 2:
        m_val = v;
        h=m_hue/360.0f;
        s=m_sat/100.0f;
        l=m_val/100.0f;
        *m_color = this->converter()->fromHsvF(h, s, l);
        if (m_toneupdating==false) {
            emit(toneUpdated(static_cast<int>(m_val), m_type));
        }
        else {
            m_toneupdating=false;
        }
        break;
    case 4:
        m_sat = v;
        h=m_hue/360.0f;
        s=m_sat/100.0f;
        l=m_val/100.0f;
        *m_color = this->converter()->fromHslF(h, s, l);
        if (m_satupdating==false) {
            emit(satUpdated(static_cast<int>(m_sat), m_type));
        }
        else {
            m_satupdating=false;
        }
        break;
    case 5:
        m_val = v;
        h=m_hue/360.0f;
        s=m_sat/100.0f;
        l=m_val/100.0f;
        *m_color = this->converter()->fromHslF(h, s, l);
        if (m_toneupdating==false) {
            emit(toneUpdated(static_cast<int>(m_val), m_type));
        }
        else {
            m_toneupdating=false;
        }
        break;
    case 7:
        m_sat = v;
        h=m_hue/360.0f;
        s=m_sat/100.0f;
        l=m_val/100.0f;
        *m_color = this->converter()->fromHsiF(h, s, l);
        if (m_satupdating==false) {
            emit(satUpdated(static_cast<int>(m_sat), m_type));
        }
        else {
            m_satupdating=false;
        }
        break;
    case 8:
        m_val = v;
        h=m_hue/360.0f;
        s=m_sat/100.0f;
        l=m_val/100.0f;
        *m_color = this->converter()->fromHsiF(h, s, l);
        if (m_toneupdating==false) {
            emit(toneUpdated(static_cast<int>(m_val), m_type));
        }
        else {
            m_toneupdating=false;
        }
        break;
    case 10:
        m_sat = v;
        h=m_hue/360.0f;
        s=m_sat/100.0f;
        l=m_val/100.0f;
        *m_color = this->converter()->fromHsyF(h, s, l, R, G, B, Gamma);
        if (m_satupdating==false) {
            emit(satUpdated(static_cast<int>(m_sat), m_type));
        }
        else {
            m_satupdating=false;
        }
        break;
    case 11:
        m_val = v;
        h=m_hue/360.0f;
        s=m_sat/100.0f;
        l=m_val/100.0f;
        *m_color = this->converter()->fromHsyF(h, s, l, R, G, B, Gamma);
        if (m_toneupdating==false) {
            emit(toneUpdated(static_cast<int>(m_val), m_type));
        }
        else {
            m_toneupdating=false;
        }
        break;
    default:
        Q_ASSERT(false);
    }
    emit(updated());
}
Exemple #30
0
int main(int argc, char* argv[])
{
    QApplication app(argc, argv);

    tryInitDrMingw();

#ifdef HAVE_IMAGE_MAGICK
    InitializeMagick(nullptr);
#endif

#ifdef Q_OS_LINUX
    app.setAttribute(Qt::AA_UseHighDpiPixmaps, true);
#endif

    // if we have some local breeze icon resource, prefer it
    DXmlGuiWindow::setupIconTheme();

    KLocalizedString::setApplicationDomain("digikam");

    KAboutData aboutData(QLatin1String("digikam"), // component name
                         i18n("digiKam"),          // display name
                         digiKamVersion());

    aboutData.setShortDescription(QString::fromUtf8("%1 - %2").arg(DAboutData::digiKamSlogan()).arg(DAboutData::digiKamFamily()));
    aboutData.setLicense(KAboutLicense::GPL);
    aboutData.setCopyrightStatement(DAboutData::copyright());
    aboutData.setOtherText(additionalInformation());
    aboutData.setHomepage(DAboutData::webProjectUrl().url());

    DAboutData::authorsRegistration(aboutData);

    QCommandLineParser parser;
    KAboutData::setApplicationData(aboutData);
    parser.addVersionOption();
    parser.addHelpOption();
    aboutData.setupCommandLine(&parser);
    parser.addOption(QCommandLineOption(QStringList() << QLatin1String("download-from"),
                                        i18n("Open camera dialog at <path>"),
                                        QLatin1String("path")));
    parser.addOption(QCommandLineOption(QStringList() << QLatin1String("download-from-udi"),
                                        i18n("Open camera dialog for the device with Solid UDI <udi>"),
                                        QLatin1String("udi")));
    parser.addOption(QCommandLineOption(QStringList() << QLatin1String("detect-camera"),
                                        i18n("Automatically detect and open a connected gphoto2 camera")));
    parser.addOption(QCommandLineOption(QStringList() << QLatin1String("database-directory"),
                                        i18n("Start digikam with the SQLite database file found in the directory <dir>"),
                                        QLatin1String("dir")));
    parser.addOption(QCommandLineOption(QStringList() << QLatin1String("config"),
                                        i18n("Start digikam with the configuration file <config>"),
                                        QLatin1String("config")));

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

    MetaEngine::initializeExiv2();

    // Force to use application icon for non plasma desktop as Unity for ex.
    QApplication::setWindowIcon(QIcon::fromTheme(QLatin1String("digikam"), app.windowIcon()));

    // Check if Qt database plugins are available.

    if (!QSqlDatabase::isDriverAvailable(DbEngineParameters::SQLiteDatabaseType()) &&
        !QSqlDatabase::isDriverAvailable(DbEngineParameters::MySQLDatabaseType()))
    {
        if (QSqlDatabase::drivers().isEmpty())
        {
            QMessageBox::critical(qApp->activeWindow(),
                                  qApp->applicationName(),
                                  i18n("Run-time Qt SQLite or MySQL database plugin is not available. "
                                       "please install it.\n"
                                       "There is no database plugin installed on your computer."));
        }
        else
        {
            DMessageBox::showInformationList(QMessageBox::Warning,
                                             qApp->activeWindow(),
                                             qApp->applicationName(),
                                             i18n("Run-time Qt SQLite or MySQL database plugin are not available. "
                                                  "Please install it.\n"
                                                  "Database plugins installed on your computer are listed below."),
                                             QSqlDatabase::drivers());
        }

        qCDebug(DIGIKAM_GENERAL_LOG) << "QT Sql drivers list: " << QSqlDatabase::drivers();
        return 1;
    }

    QString commandLineDBPath;

    if (parser.isSet(QLatin1String("database-directory")))
    {
        QDir commandLineDBDir(parser.value(QLatin1String("database-directory")));

        if (!commandLineDBDir.exists())
        {
            qCDebug(DIGIKAM_GENERAL_LOG) << "The given database-directory does not exist or is not readable. Ignoring." << commandLineDBDir.path();
        }
        else
        {
            commandLineDBPath = commandLineDBDir.path();
        }
    }

    if (parser.isSet(QLatin1String("config")))
    {
        QString configFilename = parser.value(QLatin1String("config"));
        QFileInfo configFile(configFilename);

        if (configFile.isDir() || !configFile.dir().exists() ||
            !configFile.isReadable() || !configFile.isWritable())
        {
            QMessageBox::critical(qApp->activeWindow(),
                                  qApp->applicationName(),
                                  QLatin1String("--config ") + configFilename
                                  + i18n("<p>The given path for the config file "
                                         "is not valid. Either its parent "
                                         "directory does not exist, it is a "
                                         "directory itself or it cannot be read/"
                                         "written to.</p>"));
            qCDebug(DIGIKAM_GENERAL_LOG) << "Invalid path: --config"
                                         << configFilename;
            return 1;
        }
    }

    KSharedConfig::Ptr config = KSharedConfig::openConfig();
    KConfigGroup group        = config->group(QLatin1String("General Settings"));
    QString version           = group.readEntry(QLatin1String("Version"), QString());
    QString iconTheme         = group.readEntry(QLatin1String("Icon Theme"), QString());
    KConfigGroup mainConfig   = config->group(QLatin1String("Album Settings"));

    QString            firstAlbumPath;
    DbEngineParameters params;

    // Run the first run assistant if we have no or very old config
    if (!mainConfig.exists() || (version.startsWith(QLatin1String("0.5"))))
    {
        FirstRunDlg firstRun;
        firstRun.show();

        if (firstRun.exec() == QDialog::Rejected)
        {
            return 1;
        }

        // parameters are written to config
        firstAlbumPath = firstRun.firstAlbumPath();

        if (firstRun.getDbEngineParameters().isSQLite())
        {
            AlbumManager::checkDatabaseDirsAfterFirstRun(firstRun.getDbEngineParameters().getCoreDatabaseNameOrDir(), firstAlbumPath);
        }
    }

    if (!commandLineDBPath.isNull())
    {
        // command line option set?
        params = DbEngineParameters::parametersForSQLiteDefaultFile(commandLineDBPath);
        ApplicationSettings::instance()->setDatabaseDirSetAtCmd(true);
        ApplicationSettings::instance()->setDbEngineParameters(params);
    }
    else
    {
        params = DbEngineParameters::parametersFromConfig(config);
        params.legacyAndDefaultChecks(firstAlbumPath);
        // sync to config, for all first-run or upgrade situations
        params.writeToConfig(config);
    }

    // initialize database
    if (!AlbumManager::instance()->setDatabase(params, !commandLineDBPath.isNull(), firstAlbumPath))
    {
        CoreDbAccess::cleanUpDatabase();
        ThumbsDbAccess::cleanUpDatabase();
        FaceDbAccess::cleanUpDatabase();
        SimilarityDbAccess::cleanUpDatabase();
        MetaEngine::cleanupExiv2();
        return 0;
    }

    if (!iconTheme.isEmpty())
    {
        QIcon::setThemeName(iconTheme);
    }

#ifdef Q_OS_WIN
    // Necessary to open native open with dialog on windows
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
#endif

    // create main window
    DigikamApp* const digikam = new DigikamApp();

    // If application storage place in home directory to save customized XML settings files do not exist, create it,
    // else QFile will not able to create new files as well.
    if (!QFile::exists(QStandardPaths::writableLocation(QStandardPaths::DataLocation)))
    {
        QDir().mkpath(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
    }

    // If application cache place in home directory to save cached files do not exist, create it.
    if (!QFile::exists(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)))
    {
        QDir().mkpath(QStandardPaths::writableLocation(QStandardPaths::CacheLocation));
    }

    // Bug #247175:
    // Add a connection to the destroyed() signal when the digiKam mainwindow has been
    // closed. This should prevent digiKam from staying open in the background.
    //
    // Right now this is the easiest and cleanest fix for the described problem, but we might re-think the
    // solution later on, just in case there are better ways to do it.
    QObject::connect(digikam, SIGNAL(destroyed(QObject*)),
                     &app, SLOT(quit()));

    digikam->restoreSession();
    digikam->show();

    if (parser.isSet(QLatin1String("download-from")))
    {
        digikam->downloadFrom(parser.value(QLatin1String("download-from")));
    }
    else if (parser.isSet(QLatin1String("download-from-udi")))
    {
        digikam->downloadFromUdi(parser.value(QLatin1String("download-from-udi")));
    }
    else if (parser.isSet(QLatin1String("detect-camera")))
    {
        digikam->autoDetect();
    }

    int ret = app.exec();

    CoreDbAccess::cleanUpDatabase();
    ThumbsDbAccess::cleanUpDatabase();
    FaceDbAccess::cleanUpDatabase();
    SimilarityDbAccess::cleanUpDatabase();
    MetaEngine::cleanupExiv2();

#ifdef Q_OS_WIN
    // Necessary to open native open with dialog on windows
    CoUninitialize();
#endif

#ifdef HAVE_IMAGE_MAGICK
#   if MagickLibVersion >= 0x693
    TerminateMagick();
#   endif
#endif

    return ret;
}