Exemple #1
0
void Widget::Btn_onclicked()
{
    // 创建文件操作对象
    QFile *fp = new QFile("test.txt");

    // 检查文件是否存在
    if (!fp->exists()) {
        QMessageBox::critical(this, "Error", fp->errorString());
        return;
    }

    // 打开文件
    if (!fp->open(QIODevice::ReadWrite|QIODevice::Text)) {
        QMessageBox::critical(this, "Error", fp->errorString());
        return;
    }

    // 使用文本流对文件进行操作
    QTextStream out(fp);
    //out.setCodec("UTF-8");    // 设置编码
    QString text = out.readAll();
    ui->textEdit->setText(text);

    // 移动指针到末端并写入
    //fp->seek(fp->size());
    //out << "\r\n" << QString("321TEST");

    // 关闭文件
    fp->close();
    delete fp;

    // 设置textedit滚动到末端
    QTextCursor cursor = ui->textEdit->textCursor();
    cursor.movePosition(QTextCursor::End);
    ui->textEdit->setTextCursor(cursor);
}
Exemple #2
0
void DepExportDialog::onExportButton_clicked()
{
  QString filename = QFileDialog::getSaveFileName( this, "Save file", "", ".csv");

  if (filename.isNull())
    return;

  QFile *outputFile = new QFile(filename);
  if (outputFile->exists()) {
    if ( QMessageBox::question(this, tr("Export"), tr("Die Datei %1 existiert bereits.\nMöchten Sie sie überschreiben?").arg(filename),
                                 QMessageBox::Yes, QMessageBox::No) == QMessageBox::No )
    {
      emit onExportButton_clicked();
      return;
    }
  }

  if (depExport(outputFile))
    QMessageBox::information(0, QObject::tr("Export"), QObject::tr("DEP (DatenErfassungsProtokoll) wurde nach %1 exportiert.").arg(filename));
  else
    QMessageBox::warning(0, QObject::tr("Export"), QObject::tr("DEP (DatenErfassungsProtokoll) konnte nicht nach %1 exportiert werden.\nÜberprüfen Sie bitte Ihre Schreibberechtigung.").arg(filename));

  this->close();
}
Exemple #3
0
bool Model::importFile(const QFile& modelFile)
{
    if(!modelFile.exists())
    {
        qDebug() << "Model::importFile(): import file" << modelFile.fileName() << "does not exist!";
        return false;
    }

    mAssimpScene = mAssimpImporter.ReadFile(modelFile.fileName().toStdString(), aiProcessPreset_TargetRealtime_Quality);

    // If the import failed, report it
    if(!mAssimpScene)
    {
        qDebug() << "Model::importFile(): couldn't import file" << modelFile.fileName() << ":" << mAssimpImporter.GetErrorString();
        return false;
    }
    else
    {
//        qDebug() << "Model::importFile(): successfully imported file" << modelFile.fileName();
    }

    // We're done. Everything will be cleaned up by the importer destructor
    return true;
}
bool Bookmark::backupDatabase( QString file_name )
{
    configLS500 cfg ;
    QString file_name_bk ;

    if ( file_name.isEmpty() ) {
        QString bk_path = cfg.getBookmarkDumpPath() ;

        bk_path.replace( QRegExp( "(^\\$HOME)" ) , QDir::homePath() ) ;

        bk_path += "." ;
        bk_path += QDate::currentDate().toString( Qt::ISODate ) ;
        bk_path += "-" ;
        bk_path += QTime::currentTime().toString( Qt::ISODate ) ;

        QFile file ;
        int cnt = 1 ;

        file_name_bk = bk_path ;
        file.setFileName( file_name_bk );

        while( file.exists() ) {
            file_name_bk = bk_path + "." + "(" + QString().setNum(cnt++) + ")" ;
            file.setFileName( file_name_bk );
        }
    }

    QueryDB db ;

    int rc = db.backup( cfg.getBookmarkPath() , file_name_bk ) ;

    if ( rc == 0 )
        return true ;
    else
        return false ;
}
Exemple #5
0
QFile* MainWindow::getRequiredFilesFile() {
    QSettings settings;
    //QString folder = settings.value("swg_folder").toString();

    QFile* file = NULL;

    //if (QDir(folder).exists()) {
        file = new QFile("required2.txt");

        if (file->exists()) {
            if (file->open(QIODevice::ReadOnly | QIODevice::Text)) {
                return file;
            } else
                delete file;
        } else {
            delete file;
        }
    //}

    file = new QFile(":/files/required2.txt");
    file->open(QIODevice::ReadOnly | QIODevice::Text);

    return file;
}
void UIImageOverview::deleteFile(void) {
    QFile f;
    QString filename;
    QString uri;
    QString cacheFile;

    filename = ui->listWidget->currentItem()->text();
    if (filename != "") {
        f.setFileName(filename);

        if (f.exists()) {
            f.remove();

            ui->listWidget->takeItem(ui->listWidget->currentRow());
        }

        if (getUrlOfFilename(filename, &uri))
            blackList->add(uri);
    }

    cacheFile = tnt->getCacheFile(filename);

    emit removeFiles(QStringList(cacheFile));
}
Exemple #7
0
QString KGrGameIO::getFilePath
        (const QString & dir, const QString & prefix, const int level)
{
    QString filePath = ((level == 0) ? "ende" : prefix);
    filePath = dir + "game_" + filePath + ".txt";
    QFile test (filePath);

    // See if there is a game-file or "ENDE" screen in KGoldrunner 3 format.
    if (test.exists()) {
        return (filePath);
    }

    // If not, we are looking for a file in KGoldrunner 2 format.
    if (level == 0) {
        // End of game: show the "ENDE" screen.
        filePath = dir + "levels/level000.grl";
    }
    else {
        QString num = QString::number (level).rightJustified (3,'0');
        filePath = dir + "levels/" + prefix + num + ".grl";
    }

    return (filePath);
}
void Session::init() {
    qDebug() << "Loading sessions...";
    QFile* configFile = new QFile ( Core::configurationPath().absolutePath() +"/sessions.xml" );
    s_elems.clear();

    if ( s_dom ) {
        s_dom->clear();
        delete s_dom;
    }

    s_dom = new QDomDocument ( "Sessions" );

    if ( configFile->exists() ) {
        configFile->open ( QIODevice::ReadOnly );
        s_dom->setContent ( configFile );

        const QDomElement documentElem = s_dom->documentElement();
        const QDomNodeList l_domList = documentElem.elementsByTagName ( "Session" );

        for ( int i = 0; i < l_domList.count(); i++ ) {
            QDomElement l_node = l_domList.at ( i ).toElement();
            const QUuid l_uuid ( l_node.attribute ( "uuid" ) );
            s_elems.insert ( l_uuid, new QDomElement ( l_domList.at ( i ).toElement() ) );
        }

        qDebug() << l_domList.count() << "sessions loaded.";
    } else {
        configFile->open ( QIODevice::WriteOnly | QIODevice::Truncate );
        QDomElement l_elem = s_dom->createElement ( "Sessions" );
        s_dom->appendChild ( l_elem );
        configFile->write ( s_dom->toString ( 4 ).toLocal8Bit() );
        qDebug() << "Created session listing.";
    }

    configFile->close();
}
Exemple #9
0
QIconTheme::QIconTheme(const QString &themeName)
        : m_valid(false)
{
    QFile themeIndex;

    QStringList iconDirs = QIcon::themeSearchPaths();
    for ( int i = 0 ; i < iconDirs.size() ; ++i) {
        QDir iconDir(iconDirs[i]);
        QString themeDir = iconDir.path() + QLatin1Char('/') + themeName;
        themeIndex.setFileName(themeDir + QLatin1String("/index.theme"));
        if (themeIndex.exists()) {
            m_contentDirs << themeDir;
            m_valid = true;

            QStringList themeSearchPaths = QIcon::themeSearchPaths();
            foreach (QString path, themeSearchPaths)
            {
                if (!path.startsWith(':') && QFileInfo(path).isDir())
                    m_contentDirs.append(path + QLatin1Char('/') + themeName);
            }

            break;
        }
    }
Exemple #10
0
void MainWindow::loadfile(QString filename)
{
    QSettings settings;

    if(filename.isEmpty())
        filename = QFileDialog::getOpenFileName(this, tr("Open..."), settings.value("LoadFile/lastDirectory", QDir::homePath()).toString(), tr("FUSE files (*.fuse *.xml)"));

    if(filename.isEmpty())
        return;

    settings.setValue("LoadFile/lastDirectory", QFileInfo(filename).absolutePath());
    QFile *file = new QFile(filename, this);

    if(file->exists())
    {
        if (!file->open(QFile::ReadOnly | QFile::Text))
        {
            QMessageBox::critical(this, tr("Error!"), tr("Could not open file"));
            return;
        }
    }
    else
    {
        QMessageBox::critical(this, tr("Error!"), tr("No such file"));
        return;
    }

    struct amp_settings amplifier_set;
    struct fx_pedal_settings effects_set[4];
    QString name;
    LoadFromFile *loader = new LoadFromFile(file, &name, &amplifier_set, effects_set);

    loader->loadfile();
    file->close();
    delete loader;
    delete file;

    change_title(name);

    amp->load(amplifier_set);
    if(connected)
        amp->send_amp();
    if(settings.value("Settings/popupChangedWindows").toBool())
        amp->show();

    for(int i = 0; i < 4; i++)
    {
        switch(effects_set[i].fx_slot)
        {
        case 0x00:
            effect1->load(effects_set[i]);
            if(connected)
                effect1->send_fx();
            if(effects_set[i].effect_num)
                if(settings.value("Settings/popupChangedWindows").toBool())
                    effect1->show();
            break;

        case 0x01:
            effect2->load(effects_set[i]);
            if(connected)
                effect2->send_fx();
            if(effects_set[i].effect_num)
                if(settings.value("Settings/popupChangedWindows").toBool())
                    effect2->show();
            break;

        case 0x02:
            effect3->load(effects_set[i]);
            if(connected)
                effect3->send_fx();
            if(effects_set[i].effect_num)
                if(settings.value("Settings/popupChangedWindows").toBool())
                    effect3->show();
            break;

        case 0x03:
            effect4->load(effects_set[i]);
            if(connected)
                effect4->send_fx();
            if(effects_set[i].effect_num)
                if(settings.value("Settings/popupChangedWindows").toBool())
                    effect4->show();
            break;
        }
    }
}
Exemple #11
0
void QgsApplication::init( QString customConfigPath )
{
  if ( customConfigPath.isEmpty() )
  {
    if ( getenv( "QGIS_CUSTOM_CONFIG_PATH" ) )
    {
      customConfigPath = getenv( "QGIS_CUSTOM_CONFIG_PATH" );
    }
    else
    {
      customConfigPath = QStringLiteral( "%1/.qgis3/" ).arg( QDir::homePath() );
    }
  }

  qRegisterMetaType<QgsGeometry::Error>( "QgsGeometry::Error" );
  qRegisterMetaType<QgsProcessingFeatureSourceDefinition>( "QgsProcessingFeatureSourceDefinition" );
  qRegisterMetaType<QgsProcessingOutputLayerDefinition>( "QgsProcessingOutputLayerDefinition" );

  QString prefixPath( getenv( "QGIS_PREFIX_PATH" ) ? getenv( "QGIS_PREFIX_PATH" ) : applicationDirPath() );
  // QgsDebugMsg( QString( "prefixPath(): %1" ).arg( prefixPath ) );

  // check if QGIS is run from build directory (not the install directory)
  QFile f;
  // "/../../.." is for Mac bundled app in build directory
  Q_FOREACH ( const QString &path, QStringList() << "" << "/.." << "/bin" << "/../../.." )
  {
    f.setFileName( prefixPath + path + "/qgisbuildpath.txt" );
    if ( f.exists() )
      break;
  }
  if ( f.exists() && f.open( QIODevice::ReadOnly ) )
  {
    ABISYM( mRunningFromBuildDir ) = true;
    ABISYM( mBuildSourcePath ) = f.readLine().trimmed();
    ABISYM( mBuildOutputPath ) = f.readLine().trimmed();
    qDebug( "Running from build directory!" );
    qDebug( "- source directory: %s", ABISYM( mBuildSourcePath ).toUtf8().data() );
    qDebug( "- output directory of the build: %s", ABISYM( mBuildOutputPath ).toUtf8().data() );
#ifdef _MSC_VER
    ABISYM( mCfgIntDir ) = prefixPath.split( '/', QString::SkipEmptyParts ).last();
    qDebug( "- cfg: %s", ABISYM( mCfgIntDir ).toUtf8().data() );
#endif
  }

  if ( ABISYM( mRunningFromBuildDir ) )
  {
    // we run from source directory - not installed to destination (specified prefix)
    ABISYM( mPrefixPath ) = QString(); // set invalid path
#if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
    setPluginPath( ABISYM( mBuildOutputPath ) + '/' + QString( QGIS_PLUGIN_SUBDIR ) + '/' + ABISYM( mCfgIntDir ) );
#else
    setPluginPath( ABISYM( mBuildOutputPath ) + '/' + QStringLiteral( QGIS_PLUGIN_SUBDIR ) );
#endif
    setPkgDataPath( ABISYM( mBuildSourcePath ) ); // directly source path - used for: doc, resources, svg
    ABISYM( mLibraryPath ) = ABISYM( mBuildOutputPath ) + '/' + QGIS_LIB_SUBDIR + '/';
#if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
    ABISYM( mLibexecPath ) = ABISYM( mBuildOutputPath ) + '/' + QGIS_LIBEXEC_SUBDIR + '/' + ABISYM( mCfgIntDir ) + '/';
#else
    ABISYM( mLibexecPath ) = ABISYM( mBuildOutputPath ) + '/' + QGIS_LIBEXEC_SUBDIR + '/';
#endif
  }
  else
  {
    char *prefixPath = getenv( "QGIS_PREFIX_PATH" );
    if ( !prefixPath )
    {
#if defined(Q_OS_MACX) || defined(Q_OS_WIN)
      setPrefixPath( applicationDirPath(), true );
#elif defined(ANDROID)
      // this is  "/data/data/org.qgis.qgis" in android
      QDir myDir( QDir::homePath() );
      myDir.cdUp();
      QString myPrefix = myDir.absolutePath();
      setPrefixPath( myPrefix, true );
#else
      QDir myDir( applicationDirPath() );
      myDir.cdUp();
      QString myPrefix = myDir.absolutePath();
      setPrefixPath( myPrefix, true );
#endif
    }
    else
    {
      setPrefixPath( prefixPath, true );
    }
  }

  if ( !customConfigPath.isEmpty() )
  {
    ABISYM( mConfigPath ) = customConfigPath + '/'; // make sure trailing slash is included
  }

  ABISYM( mDefaultSvgPaths ) << qgisSettingsDirPath() + QStringLiteral( "svg/" );

  ABISYM( mAuthDbDirPath ) = qgisSettingsDirPath();
  if ( getenv( "QGIS_AUTH_DB_DIR_PATH" ) )
  {
    setAuthDatabaseDirPath( getenv( "QGIS_AUTH_DB_DIR_PATH" ) );
  }


  // store system environment variables passed to application, before they are adjusted
  QMap<QString, QString> systemEnvVarMap;
  QString passfile( QStringLiteral( "QGIS_AUTH_PASSWORD_FILE" ) ); // QString, for comparison
  Q_FOREACH ( const QString &varStr, QProcess::systemEnvironment() )
  {
    int pos = varStr.indexOf( QLatin1Char( '=' ) );
    if ( pos == -1 )
      continue;
    QString varStrName = varStr.left( pos );
    QString varStrValue = varStr.mid( pos + 1 );
    if ( varStrName != passfile )
    {
      systemEnvVarMap.insert( varStrName, varStrValue );
    }
  }
Exemple #12
0
bool plotsDialog::loadXml(bool init)
{
    tabs->clear();
    QFile file;
#ifdef Q_OS_WIN32
    if(init)
    {
        QFile ofile(globalpara.caseName);
        file.setFileName("plotTemp.xml");
        if(file.exists())
            file.remove();
        if(!ofile.copy("plotTemp.xml"))
        {
            globalpara.reportError("Fail to generate temporary file for plots.",this);
            return false;
        }
        else file.setFileName("plotTemp.xml");
    }
    else file.setFileName("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
    QDir dir = qApp->applicationDirPath();
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    QString bundleDir(dir.absolutePath());
    if(init)
    {
        QFile ofile(globalpara.caseName);
        file.setFileName(bundleDir+"/plotTemp.xml");
        if(file.exists())
            file.remove();
        if(!ofile.copy(bundleDir+"/plotTemp.xml"))
        {
            globalpara.reportError("Fail to generate temporary file for plots.",this);
            return false;
        }
        else file.setFileName(bundleDir+"/plotTemp.xml");
    }
    else file.setFileName(bundleDir+"/plotTemp.xml");
#endif
    QDomDocument doc;
    QDomElement plotData, currentPlot;
    int plotCount=0;
    Plot*newPlot;

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        globalpara.reportError("Fail to open the xml file for plots!",this);
        return false;
    }
    else
    {
        if(!doc.setContent(&file))
        {
            globalpara.reportError("Fail to set DomDoc to file content when loading xml file for plots!",this);
            file.close();
            return false;
        }
        else
        {
            if(doc.elementsByTagName("plotData").count()==0)
            {
                globalpara.reportError("Error! There is no <plotData> branch in the case xml file!",this);
                file.close();
                return false;
            }
            else
                plotData = doc.elementsByTagName("plotData").at(0).toElement();

            plotCount = plotData.childNodes().count();
            for(int i = 0; i < plotCount; i++)
            {
                currentPlot = plotData.childNodes().at(i).toElement();
                if(currentPlot.attribute("plotType")=="parametric")
                {
                    QDomElement currentRun,runInput,runOutput;
                    double currentInput;
                    int axis_info[8];
                    QStringList currentOutput, xValues, axis_name, info;
                    QMultiMap<double,double> allData;
                    axis_name.append(currentPlot.attribute("xAxisName"));
                    axis_name= axis_name + currentPlot.attribute("yAxisName").split(",");
                    info = currentPlot.attribute("scaleInfo").split(",");
                    for(int j = 0; j < 8; j++)
                        axis_info[j] = info.at(j).toInt();
                    int nRuns = currentPlot.elementsByTagName("Run").count(), nOutputs = currentPlot.attribute("outputs").toInt();
                    for(int j = 0; j < nRuns; j++)
                    {
                        currentOutput.clear();
                        currentRun = currentPlot.elementsByTagName("Run").at(j).toElement();
                        runInput = currentRun.elementsByTagName("Input").at(0).toElement();
                        currentInput = runInput.elementsByTagName("value").at(0).toElement().text().toDouble();
                        xValues.append(QString::number(currentInput));
                        for(int p = 0; p < nOutputs; p++)
                        {
                            runOutput = currentRun.elementsByTagName("Output").at(p).toElement();
                            currentOutput.append(runOutput.elementsByTagName("value").at(0).toElement().text());
                            allData.insert(currentInput,currentOutput.at(p).toDouble());
                        }
                    }


                    newPlot = new Plot(allData,xValues,nOutputs,axis_info,axis_name);


                }
                else if(currentPlot.attribute("plotType")=="property")
                {
                    QString fluid = currentPlot.attribute("fluid"),
                            subType = currentPlot.attribute("subType"),
                            unit = currentPlot.attribute("unitSystem");

                    newPlot = new Plot(fluid,subType,unit);
                    QDomElement currentCurve, currentPoint;

                    newPlot->curvePoints.clear();
                    for(int i = 0; i < currentPlot.childNodes().count(); i++)
                    {
                        if(currentPlot.childNodes().at(i).toElement().attribute("type")=="custom")
                        {
                            addvalue*value;
                            newPlot->addvaluelist.clear();
                            currentCurve = currentPlot.childNodes().at(i).toElement();
                            QString title = currentCurve.tagName();
                            for(int j = 0; j < currentCurve.childNodes().count(); j++)
                            {
                                if(currentCurve.childNodes().at(j).toElement().attribute("order")==QString::number(j))
                                {
                                    value = new addvalue;
                                    currentPoint = currentCurve.childNodes().at(j).toElement();
                                    value->index = currentPoint.attribute("index").toInt();
                                    value->add_temperature = currentPoint.attribute("t").toDouble();
                                    value->add_pressure = currentPoint.attribute("p").toDouble();
                                    value->add_concentration = currentPoint.attribute("c").toDouble();
                                    value->add_enthalpy = currentPoint.attribute("h").toDouble();
//                                    qDebug()<<"adding a new point"<<currentPoint.attribute("index")<<"t"<<currentPoint.attribute("t")<<"p"<<currentPoint.attribute("p")<<"c"<<currentPoint.attribute("c");
                                    newPlot->addvaluelist<<value;
                                }
                            }

                            if(subType == "Duhring")
                                newPlot->setupNewPropertyCurve(title,true);
                            else if(subType == "Clapeyron")
                                newPlot->setupNewPropertyCurve(title,false);
                        }
                    }


                }
                newPlot->setTitle(currentPlot.tagName());

                //load the plot settings
                QDomElement general, legend, grid, curve;

                //general
                if(currentPlot.elementsByTagName("general").count()>0)
                {
                    general = currentPlot.elementsByTagName("general").at(0).toElement();
                    QString bgColor, lMargin, rMargin, tMargin, bMargin, plotTitle, xTitle, yTitle;
                    bgColor = general.attribute("bgColor");
                    newPlot->setCanvasBackground(QColor(bgColor));
                    lMargin = general.attribute("lMargin");
                    rMargin = general.attribute("rMargin");
                    tMargin = general.attribute("tMargin");
                    bMargin = general.attribute("bMargin");
                    newPlot->setContentsMargins(lMargin.toInt(),tMargin.toInt(),rMargin.toInt(),bMargin.toInt());
                    plotTitle = general.attribute("plotTitle");
                    newPlot->setTitle(plotTitle);
                    xTitle = general.attribute("xTitle");
                    yTitle = general.attribute("yTitle");
                    newPlot->setAxisTitle(QwtPlot::xBottom,xTitle);
                    newPlot->setAxisTitle(QwtPlot::yLeft,yTitle);

                }

                //legend
                if(currentPlot.elementsByTagName("legend").count()>0)
                {
                    legend = currentPlot.elementsByTagName("legend").at(0).toElement();
                    QString plotLegend, extInt, extPos, nCol, legendSize;
                    plotLegend = legend.attribute("plotLegend");
                    if(plotLegend == "on")
                    {
                        QwtLegend* externalLegend=NULL;
                        LegendItem* internalLegend = new LegendItem();
                        newPlot->externalLegend = externalLegend;
                        newPlot->internalLegend = internalLegend;
                        internalLegend->attach(newPlot);
                        internalLegend->setBorderRadius( 4 );
                        internalLegend->setMargin( 0 );
                        internalLegend->setSpacing( 4 );
                        internalLegend->setItemMargin( 2 );
                        internalLegend->setMaxColumns(4);
                        internalLegend->setAlignment(Qt::AlignBottom|Qt::AlignRight);
                        extInt = legend.attribute("extInt");
                        if(extInt == "ext")
                        {
                            internalLegend->setVisible(false);
                            externalLegend = new QwtLegend();
                            extPos = legend.attribute("extPos");//0=L, 1=R, 2=B, 3=T
                            newPlot->insertLegend(externalLegend,QwtPlot::LegendPosition(extPos.toInt()));
                        }
                        else if(extInt == "int")
                        {
                            internalLegend->setVisible(true);
                            nCol = legend.attribute("nCol");
                            legendSize = legend.attribute("legendSize");

                            // other setting
                            newPlot->internalLegend->setMaxColumns(nCol.toInt());
                            QFont font = newPlot->internalLegend->font();
                            font.setPointSize( legendSize.toInt());
                            newPlot->internalLegend->setFont( font );
                        }
                    }
                }

                //grid
                if(currentPlot.elementsByTagName("grid").count()>0)
                {
                    grid = currentPlot.elementsByTagName("grid").at(0).toElement();
                    QString xMaj, yMaj, xMin, yMin, majColor, minColor, majSize, minSize, majStyle, minStyle;
                    xMaj = grid.attribute("xMaj");
                    yMaj = grid.attribute("yMaj");
                    xMin = grid.attribute("xMin");
                    yMin = grid.attribute("yMin");
                    majColor = grid.attribute("majColor");
                    minColor = grid.attribute("minColor");
                    majSize = grid.attribute("majSize");
                    minSize = grid.attribute("minSize");
                    majStyle = grid.attribute("majStyle");
                    minStyle = grid.attribute("minStyle");
                    newPlot->grid->enableX(xMaj=="on");
                    newPlot->grid->enableY(yMaj == "on");
                    newPlot->grid->enableXMin(xMin=="on");
                    newPlot->grid->enableYMin(yMin=="on");
                    if(newPlot->grid->xEnabled()||newPlot->grid->yEnabled())
                        newPlot->grid->setMajorPen(QColor(majColor),majSize.toInt(),Qt::PenStyle(majStyle.toInt()));
                    if(newPlot->grid->xMinEnabled()||newPlot->grid->yMinEnabled())
                        newPlot->grid->setMinorPen(QColor(minColor),minSize.toInt(),Qt::PenStyle(minStyle.toInt()));
                }

                //curve
                if(currentPlot.elementsByTagName("curve").count()>0)
                {
                    curve = currentPlot.elementsByTagName("curve").at(0).toElement();
                    if(curve.childNodes().count()==newPlot->curvelist.count())
                    {
                        QDomElement currentCurve;
                        QwtPlotCurve *thisCurve;
                        QString lineColor, lineSize, lineType, isVisible;
                        for(int i = 0; i < newPlot->curvelist.count(); i++)
                        {
                            currentCurve = curve.elementsByTagName(newPlot->curvelist[i]->title().text().replace(" ","")).at(0).toElement();
                            thisCurve = newPlot->curvelist[i];
                            lineColor = currentCurve.attribute("lineColor");
                            lineSize = currentCurve.attribute("lineSize");
                            lineType = currentCurve.attribute("lineType");
                            isVisible = currentCurve.attribute("isVisible");
                            thisCurve->setPen(QColor(lineColor),lineSize.toInt(),Qt::PenStyle(lineType.toInt()));
                            if(isVisible=="true")
                                thisCurve->setVisible(true);
                            else if(isVisible=="false")
                                thisCurve->setVisible(false);
                        }
                    }
                }


                tabs->insertTab(-1,newPlot,currentPlot.tagName());
                newPlot->replot();
            }
            file.close();
            return true;
        }
    }
}
Exemple #13
0
bool XmlDataLayer::invoiceInsertData(InvoiceData& oi_invData, int type) {
        qDebug() << __FILE__ << __LINE__ << __FUNCTION__;

	QDomDocument doc(sett().getInoiveDocName());
	QDomElement root;
	QString fileName = oi_invData.id;

	QFile file;
	if (fileName == "") {
		fileName = QDate::currentDate().toString(sett().getFnameDateFormat());

		int pNumber = 0;
		file.setFileName(sett().getInvoicesDir() + "h" + fileName + "_"
				+ sett().numberToString(pNumber) + ".xml");
		oi_invData.id = "h" + fileName + "_" + sett().numberToString(pNumber) + ".xml";
		pNumber += 1;

		while (file.exists()) {
			file.setFileName(sett().getInvoicesDir() + "h" + fileName + "_"
					+ sett().numberToString(pNumber) + ".xml");
			oi_invData.id = "h" + fileName + "_" + sett().numberToString(pNumber) + ".xml";
			pNumber += 1;
		}

		// fName = "h" + fileName + "_" + sett().numberToString(pNumber) + ".xml";
	} else {
		file.setFileName(sett().getInvoicesDir() + fileName);
		oi_invData.id = fileName + "|";
	}

	// if (!file.open (QIODevice::ReadOnly)) {

	root = doc.createElement("invoice");
	root.setAttribute("no", oi_invData.frNr);
	oi_invData.issueDate = QDate::currentDate();
	root.setAttribute("issueDate", oi_invData.issueDate.toString(sett().getDateFormat()));
	root.setAttribute("sellingDate", oi_invData.sellingDate.toString(sett().getDateFormat()));

	QString invType = oi_invData.getInvoiceTypeAndSaveNr(type);
	root.setAttribute("type", invType);

	doc.appendChild(root);

	QDomElement sprzedawca = doc.createElement("seller");
	invoiceSellerDataToElem(oi_invData, sprzedawca);
	root.appendChild(sprzedawca);


	QDomElement nabywca = doc.createElement("buyer");
	invoiceBuyerDataToElem(oi_invData, nabywca);
	root.appendChild(nabywca);

	QDomElement product;
	QDomElement products;
	products = doc.createElement("products");
	products.setAttribute("discount", sett().numberToString(oi_invData.discount));

	QMap<int, ProductData>::const_iterator i = oi_invData.products.constBegin();
	int abc = 0;
	while (i != oi_invData.products.constEnd()) {
		product = doc.createElement("product");
		// ProductData pr = i.value();
		invoiceProdDataToElem(i.value(), product);
		products.appendChild(product);
		i++;
	}

	root.appendChild(products);

	QDomElement addinfo;
	addinfo = doc.createElement("addinfo");
	addinfo.setAttribute("text", oi_invData.additText);
	addinfo.setAttribute("paymentType", oi_invData.paymentType );
	addinfo.setAttribute("liabDate", oi_invData.liabDate.toString(sett().getDateFormat()));
	addinfo.setAttribute("currency", oi_invData.currencyType);

	/*
	if (platCombo->currentIndex() == sett().value("payments").toString().split("|").count() - 1) {
		addinfo.setAttribute("payment1", custPaymData->payment1);
		addinfo.setAttribute("amount1", sett().numberToString(custPaymData->amount1, 'f', 2));
		addinfo.setAttribute("liabDate1", custPaymData->date1.toString(
				sett().getDateFormat()));

		addinfo.setAttribute("payment2", custPaymData->payment2);
		addinfo.setAttribute("amount2", sett().numberToString(custPaymData->amount2, 'f', 2));
		addinfo.setAttribute("liabDate2", custPaymData->date2.toString(
				sett().getDateFormat()));
	}
	*/
	root.appendChild(addinfo);

	QString xml = doc.toString();
	file.close();
	if (!file.open(QIODevice::WriteOnly)) {
		// saveFailed = true;
		return false;
	}
	QTextStream ts(&file);
	ts << xml;
	file.close();

	return true;
}
Exemple #14
0
/** Anm. JH
 * Hier wird das Graphik-Modell geladen?
 * @brief Methode zum einbinden der STL-Dateien
 */
int readSTL(QVector <triangle> *triangleList, QString path)
{
    int triCount = 0;
    int strIndex = 0;

    QFile file (path);
    QTextStream stream(&file);
    QString line, strX, strY, strZ, value;
    GLfloat tempPoints[3][3] = {{0.0,0.0,0.0},{0.0,0.0,0.0},{0.0,0.0,0.0}};
    triangle tri;

    strX = ""; strY = ""; strZ = "";
    value = "0123456789+-.e";

    if(!file.exists())
    {
        qDebug()<< "STL-Datei"<<path<<"existiert nicht! Ende.";
        assert(false);
    }


    file.open(QIODevice::ReadOnly);

    while(!stream.atEnd())
    {
        line = stream.readLine();
        if(line.contains("outer loop") && triCount != 0)
            return RETURN_OK;
        else if(line.contains("endloop") && triCount != 3)
            return RETURN_ERROR;
        else if(line.contains("endloop") && triCount == 3)
        {
            triCount = 0;
            memmove(tri.vertex0, tempPoints[0], sizeof(tempPoints[0]));
            memmove(tri.vertex1, tempPoints[1], sizeof(tempPoints[0]));
            memmove(tri.vertex2, tempPoints[2], sizeof(tempPoints[0]));
            getNormal(tri.normal, tri.vertex0, tri.vertex1, tri.vertex2);
            (*triangleList).push_back(tri);
        }
        else if((strIndex = line.lastIndexOf("vertex",-1)) != -1)
        {
            strIndex+=7;
            while(value.contains(line[strIndex]))
            {
                strX+=line[strIndex];
                strIndex++;
            };
            strIndex++;
            while(value.contains(line[strIndex]))
            {
                strY+=line[strIndex];
                strIndex++;
            };
            strIndex++;
            while(value.contains(line[strIndex]))
            {
                strZ+=line[strIndex];
                strIndex++;
            };
            tempPoints[triCount][0] = strX.toDouble();
            tempPoints[triCount][1] = strY.toDouble();
            tempPoints[triCount][2] = strZ.toDouble();

            strX.clear();
            strY.clear();
            strZ.clear();

            triCount++;
        }
    };
    file.close(); // Datei wieder schließen

    return RETURN_OK;
}
/*! \brief Extracts the selected .tar.gz archive to the selected folder, will try to create the target folder if it does not exist.
* @param filePath Full path to selected archive.
* @param targetFolderPath Full path to target folder.
* @return Returns full path to the extracted archive, or empty QString if failed.
*/
QString ArchiveExtractor::extractFileToTargetFolder(QString filePath, QString targetFolderPath){
  //check if the selected archive file exist
  QFile *selectedFile = new QFile(filePath);
  if(!selectedFile->exists()){
    qDebug()<<"ERROR: File marked for decompression does not exist!";
    delete selectedFile;
    return QString("");
  }
  delete selectedFile;
  struct archive *a;
  struct archive *ext;
  struct archive_entry *entry;
  int r;
  //  /* The "flags" argument selects optional behavior, 'OR' the flags you want. */
  //  /* Default: Do not try to set owner/group. */
  //#define	ARCHIVE_EXTRACT_OWNER			(0x0001)
  //  /* Default: Do obey umask, do not restore SUID/SGID/SVTX bits. */
  //#define	ARCHIVE_EXTRACT_PERM			(0x0002)
  //  /* Default: Do not restore mtime/atime. */
  //#define	ARCHIVE_EXTRACT_TIME			(0x0004)
  //  /* Default: Replace existing files. */
  //#define	ARCHIVE_EXTRACT_NO_OVERWRITE 		(0x0008)
  //  /* Default: Try create first, unlink only if create fails with EEXIST. */
  //#define	ARCHIVE_EXTRACT_UNLINK			(0x0010)
  //  /* Default: Do not restore ACLs. */
  //#define	ARCHIVE_EXTRACT_ACL			(0x0020)
  //  /* Default: Do not restore fflags. */
  //#define	ARCHIVE_EXTRACT_FFLAGS			(0x0040)
  //  /* Default: Do not restore xattrs. */
  //#define	ARCHIVE_EXTRACT_XATTR 			(0x0080)
  //  /* Default: Do not try to guard against extracts redirected by symlinks. */
  //  /* Note: With ARCHIVE_EXTRACT_UNLINK, will remove any intermediate symlink. */
  //#define	ARCHIVE_EXTRACT_SECURE_SYMLINKS		(0x0100)
  //  /* Default: Do not reject entries with '..' as path elements. */
  //#define	ARCHIVE_EXTRACT_SECURE_NODOTDOT		(0x0200)
  //  /* Default: Create parent directories as needed. */
  //#define	ARCHIVE_EXTRACT_NO_AUTODIR		(0x0400)
  //  /* Default: Overwrite files, even if one on disk is newer. */
  //#define	ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER	(0x0800)
  //  /* Detect blocks of 0 and write holes instead. */
  //#define	ARCHIVE_EXTRACT_SPARSE			(0x1000)
  //  /* Default: Do not restore Mac extended metadata. */
  //  /* This has no effect except on Mac OS. */
  //#define	ARCHIVE_EXTRACT_MAC_METADATA		(0x2000)
  int flags = 0;
  //      flags |= ARCHIVE_EXTRACT_TIME;
  //      flags |= ARCHIVE_EXTRACT_NO_AUTODIR;
  //      flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;

  QFileInfo *fileInfo = new QFileInfo(filePath);
//  qDebug()<<"resolved filename: "<<fileInfo->fileName();
  delete fileInfo;

  //MEMORY LEAK!!! (Pointers be dangerous, man. :)
  //  const char *filename = fileInfo->fileName().toUtf8().constData();
  //AVOID IT BY CONVERTING TO A QBYTEARRAY FIRST!
  QByteArray byteArray = filePath.toUtf8();
  const char *filename = byteArray.constData();
  //That's better :D

  //toggle extraction
  bool do_extract = true;

  a = archive_read_new();
  ext = archive_write_disk_new();
  archive_write_disk_set_options(ext, flags);

  //tuned for .tar.gz
  archive_read_support_filter_gzip(a);
  archive_read_support_format_gnutar(a);

  if((r = archive_read_open_filename(a, filename, 10240)) ){
    errmsg(archive_error_string(a));
  }
  for(;;){
    r = archive_read_next_header(a, &entry);
    if(r == ARCHIVE_EOF) break;
    if(r != ARCHIVE_OK){
      errmsg(archive_error_string(a));
    }
    if (verbose || !do_extract){
      qDebug()<<"Detected files in archive: ";
      msg(archive_entry_pathname(entry));
    }
    QString currentPath(archive_entry_pathname( entry ));
    qDebug()<<currentPath;

    QDir targetFolder(targetFolderPath);
    if(!targetFolder.exists()){//target folder does not exist
      //attempt to create it
      if(!targetFolder.mkpath(targetFolderPath)){//failed to create target folder
        //break procedure
        qDebug()<<"ERROR: Target folder does not exist and cannot be created";
        return QString("");
      }
    }

    QString newPath = targetFolderPath + currentPath;
    qDebug()<<"newPath: " << newPath;

    archive_entry_set_pathname( entry, newPath.toUtf8().constData() );
    if (verbose && do_extract){
//      msg("About to start extracting\n");
    }
    if (do_extract){
      qDebug()<<"Extracting...";
      r = archive_write_header(ext, entry);
      if (r != ARCHIVE_OK) errmsg(archive_error_string(a));
      else copy_data(a, ext);
      std::string returnPath;
      returnPath = archive_entry_pathname(entry);
      qDebug()<<"File extracted: " << QString::fromStdString(returnPath);
      archive_read_close(a);
      archive_read_free(a);
      archive_write_close(ext);
      archive_write_free(ext);
      return QString::fromStdString( returnPath );
    }
  }
  archive_read_close(a);
  archive_read_free(a);
  archive_write_close(ext);
  archive_write_free(ext);
  return QString("");
}
Exemple #16
0
void Setting::loadSettings()
{
	QFile file;

	// set under Linux
	settingHomeDir = QString(getenv("HOME"));
	if (!settingHomeDir)
		// set under Windows
		settingHomeDir = QString(getenv("USERPROFILE"));
	if (!settingHomeDir)
	{
		// however...
		qDebug("HOME and/or USERPROFILE are not set");
		settingHomeDir = QDir::homeDirPath();
		file.setName(settingHomeDir + "/.qgoclientrc");
		if (file.exists())
		{
			// rename, but use it anyway
			QString oldName = ".qgoclientrc";
			QString newName = ".qgoclientrc.bak";
			QDir::home().rename(oldName, newName);
			file.setName(settingHomeDir + "/.qgoclientrc.bak");
		}
		else
			// file may be already renamed
			file.setName(settingHomeDir + "/." + PACKAGE + "rc");
	}
	else
		file.setName(settingHomeDir + "/." + PACKAGE + "rc");

	if (!file.exists() || !file.open(IO_ReadOnly))
	{
		qDebug("Failed loading settings: " + file.name());

		// maybe old file available
		file.setName(QDir::homeDirPath() + "/.qgoclientrc");

		if (!file.exists() || !file.open(IO_ReadOnly))
		{
			qWarning("Failed loading settings: " + file.name());
			return;
		}
	}

	qDebug("Use settings: " + file.name());

	// read file
	QTextStream txt(&file);
	QString s;
	int pos, pos1, pos2;
	while (!txt.eof())
	{
		s = txt.readLine();
		if (s.length() > 2)
		{
			// ' ' is delitmiter between key and txt
			pos = s.find(' ');
			// find first '['
			pos1 = s.find('[');
			// find last ']'
			pos2 = s.findRev(']');
			writeEntry(s.left(pos), s.mid(pos1 + 1, pos2 - pos1 - 1));
		}
	}

	file.close();

	// init fonts and colors
	updateFont(fontStandard, "FONT_MAIN");
	updateFont(fontMarks, "FONT_MARK");
	updateFont(fontComments, "FONT_COMMENT");
	updateFont(fontLists, "FONT_LIST");
	updateFont(fontClocks, "FONT_CLOCK");
	updateFont(fontConsole, "FONT_CONSOLE");
 	s = readEntry("COLOR_BK");
	if (s)
		colorBackground = QColor(s);
	s = readEntry("COLOR_ALT_BK");
	if (s)
		colorAltBackground = QColor(s);
	s=readEntry("CHARSET");
	charset->blackStone = s.constref(0);
	charset->emptyPoint = s.constref(1);
	charset->hBorder = s.constref(2);
	charset->starPoint = s.constref(3);
	charset->vBorder = s.constref(4);
	charset->whiteStone = s.constref(5);  
}
Exemple #17
0
bool ImageThread::addImage(_IMAGE img) {
    int i,k;
    bool alreadyInList;
    bool fileExists;

    fileExists = false;

    if (_blackList->contains(img.largeURI)) {
        alreadyInList = true;
    }
    else {
        alreadyInList = false;
        k = 2;
        for (i=0; i<images.length(); i++) {
            if (images.at(i).largeURI == img.largeURI) {
                alreadyInList = true;
                break;
            }

            if (images.at(i).originalFilename == img.originalFilename) {
                QStringList tmp;

                tmp = img.originalFilename.split(QRegExp("\\(\\d+\\)"));
                if  (tmp.count() > 1) // Already has a number in brackets in filename
                    img.originalFilename = QString("%1(%2)%3").arg(tmp.at(0)).
                                           arg(k++).
                                           arg(tmp.at(1));
                else
                    img.originalFilename = img.originalFilename.replace("."," (1).");
            }
        }

        if (!alreadyInList) {
            // Check if already downloaded
            QFile f;
            if (_saveWithOriginalFilename)
                f.setFileName(getSavepath()+"/"+img.originalFilename);
            else {
                QRegExp rx(__IMAGEFILE_REGEXP__, Qt::CaseInsensitive, QRegExp::RegExp2);
                QStringList res;
                int pos;

                pos = 0;

                pos = rx.indexIn(img.largeURI);
                res = rx.capturedTexts();

                if (pos != -1) {
                    f.setFileName(getSavepath()+"/"+res.at(1)+res.at(2));
                }
            }

            if (f.exists()) {
                img.downloaded = true;
                fileExists = true;
                img.savedAs = f.fileName();
            }

            images.append(img);
        }
    }

    return (!alreadyInList && !fileExists);
}
Exemple #18
0
QIconTheme::QIconTheme(const QString &themeName)
        : m_valid(false)
{
    QFile themeIndex;

    QList <QIconDirInfo> keyList;
    QStringList iconDirs = QIcon::themeSearchPaths();
    for ( int i = 0 ; i < iconDirs.size() ; ++i) {
        QDir iconDir(iconDirs[i]);
        QString themeDir = iconDir.path() + QLatin1Char('/') + themeName;
        themeIndex.setFileName(themeDir + QLatin1String("/index.theme"));
        if (themeIndex.exists()) {
            m_contentDir = themeDir;
            m_valid = true;
            break;
        }
    }
#ifndef QT_NO_SETTINGS
    if (themeIndex.exists()) {
        const QSettings indexReader(themeIndex.fileName(), QSettings::IniFormat);
        QStringListIterator keyIterator(indexReader.allKeys());
        while (keyIterator.hasNext()) {

            const QString key = keyIterator.next();
            if (key.endsWith(QLatin1String("/Size"))) {
                // Note the QSettings ini-format does not accept
                // slashes in key names, hence we have to cheat
                if (int size = indexReader.value(key).toInt()) {
                    QString directoryKey = key.left(key.size() - 5);
                    QIconDirInfo dirInfo(directoryKey);
                    dirInfo.size = size;
                    QString type = indexReader.value(directoryKey +
                                                     QLatin1String("/Type")
                                                     ).toString();

                    if (type == QLatin1String("Fixed"))
                        dirInfo.type = QIconDirInfo::Fixed;
                    else if (type == QLatin1String("Scalable"))
                        dirInfo.type = QIconDirInfo::Scalable;
                    else
                        dirInfo.type = QIconDirInfo::Threshold;

                    dirInfo.threshold = indexReader.value(directoryKey +
                                                        QLatin1String("/Threshold"),
                                                        2).toInt();

                    dirInfo.minSize = indexReader.value(directoryKey +
                                                         QLatin1String("/MinSize"),
                                                         size).toInt();

                    dirInfo.maxSize = indexReader.value(directoryKey +
                                                        QLatin1String("/MaxSize"),
                                                        size).toInt();
                    m_keyList.append(dirInfo);
                }
            }
        }

        // Parent themes provide fallbacks for missing icons
        m_parents = indexReader.value(
                QLatin1String("Icon Theme/Inherits")).toStringList();

        // Ensure a default platform fallback for all themes
        if (m_parents.isEmpty()) {
            const QString fallback = fallbackTheme();
            if (!fallback.isEmpty())
                m_parents.append(fallback);
        }

        // Ensure that all themes fall back to hicolor
        if (!m_parents.contains(QLatin1String("hicolor")))
            m_parents.append(QLatin1String("hicolor"));
    }
#endif //QT_NO_SETTINGS
}
Exemple #19
0
void DatabaseWidget::deleteDataFromDatabase()
{
  FormDialog fDialog(this, FormDialog::SelectingRecord, "Numer wtryskiwacza:") ;

  fDialog.exec() ;

  if (fDialog.canceled) return ;

  QFile file(QDir::currentPath() + "/DatabaseSx/" + fDialog.company + '/' + fDialog.type + '/' + fDialog.number + ".txt") ;

  if(file.remove())
    QMessageBox::information(this, "Sukces",
                             "Nastawy zostały pomyślnie usunięte z bazy danych.") ;
  else
      QMessageBox::critical(this, "Błąd",
                            "Nie udało się usunąć nastaw z bazy. Może nastawy \
                            do tego wtryskiwacza nigdy nie istniały?") ;
}

void DatabaseWidget::showResult()
{
  FormDialog dialog(this, FormDialog::SelectingRecord, "Nazwa rekordu:") ;

  dialog.exec() ;

  if (dialog.canceled) return ;


  QFile dbFile;
  QFile dbResFile;
  dbFile.setFileName(QDir::currentPath() + "/DatabaseSx/" + dialog.company
                     + "/" + dialog.type + "/" + dialog.number + ".txt");
  dbResFile.setFileName(QDir::currentPath() + "/DatabaseSx/" + dialog.company
                        + "/" + dialog.type + "/Results/" + dialog.number + ".txt");

  if(!dbFile.exists() || !dbResFile.exists())
  {
    QMessageBox::warning(this, "Wynik"
                         , "Wynik o podanej nazwie nie istnieje w bazie danych.");
    return;
  }

  QStringList dbFileSL ;
  {//read from file
    dbFile.open(QFile::Text | QFile::ReadOnly) ;
    QTextStream str(&dbFile) ;
    for (int i = 0 ; i < 40 ; i++)
      dbFileSL.append(str.readLine() ) ;
    dbFile.close() ;
  }
  QStringList dbResFileSL;
  {//read from file
      dbResFile.open(QFile::Text | QFile::ReadOnly) ;
      QTextStream str(&dbResFile) ;
      for (int i = 0 ; i < 100 ; i++)
        dbResFileSL.append(str.readLine() ) ;
      dbResFile.close() ;
  }

  if(showResultWiget)
  {
     stackedWidget->removeWidget(showResultWiget);
     delete showResultWiget;
     showResultWiget = nullptr;
  }
  const QString hwName = dialog.company + "-" + dialog.type + "-" + dialog.number;
  showResultWiget =new ResultWidget(stackedWidget, dbFileSL, dbResFileSL, hwName, SHOW_ONLY);
  stackedWidget->addWidget(SHOWRESULT_WIDGET, showResultWiget);
  stackedWidget->slideInIdx(SHOWRESULT_WIDGET);
}

void DatabaseWidget::editResultInit()
{
  FormDialog dialog(this, FormDialog::SelectingRecord, "Nazwa rekordu:") ;
  dialog.exec() ;
  if (dialog.canceled)
      return ;


  QFile dbFile;
  QFile dbResFile;
  dbFile.setFileName(QDir::currentPath() + "/DatabaseSx/" + dialog.company
                     + "/" + dialog.type + "/" + dialog.number + ".txt");
  dbResFile.setFileName(QDir::currentPath() + "/DatabaseSx/" + dialog.company
                        + "/" + dialog.type + "/Results/" + dialog.number + ".txt");

  if(!dbFile.exists() || !dbResFile.exists())
  {
    QMessageBox::warning(this, "Wynik"
                         , "Wynik o podanej nazwie nie istnieje w bazie danych.");
    return;
  }

  QStringList dbFileSL ;
  {//read from file
    dbFile.open(QFile::Text | QFile::ReadOnly) ;
    QTextStream str(&dbFile) ;
    for (int i = 0 ; i < 40 ; i++)
      dbFileSL.append(str.readLine() ) ;
    dbFile.close() ;
  }
  QStringList dbResFileSL;
  {//read from file
      dbResFile.open(QFile::Text | QFile::ReadOnly) ;
      QTextStream str(&dbResFile) ;
      for (int i = 0 ; i < 100 ; i++)
        dbResFileSL.append(str.readLine() ) ;
      dbResFile.close() ;
  }
  if(showResultWiget)
  {
    stackedWidget->removeWidget(showResultWiget);
    delete showResultWiget;
    showResultWiget = nullptr;
  }
  const QString hwName = dialog.company + "-" + dialog.type + "-" + dialog.number;
  showResultWiget =new ResultWidget(stackedWidget, dbFileSL, dbResFileSL, hwName, EDIT);
  stackedWidget->addWidget(SHOWRESULT_WIDGET, showResultWiget);
  stackedWidget->slideInIdx(SHOWRESULT_WIDGET);
  connect(showResultWiget, SIGNAL(dialogClosed()), this, SLOT(editResultClosed()));
}
Exemple #20
0
void ModelWindow::on_pushButtonSave_clicked()
{
    //Slot where everything happens !
    //Create a Model depending on the type of model chosen
    //begin to check if everything is ok

    if(ui->lineEditName->text().isEmpty() ||
       ui->comboRace->currentIndex() == 0 ||
       ui->comboUnitType->currentIndex() == 0 )
    {
        QMessageBox::warning(this, tr("Info"),
                tr("Vous devez obligatoirement choisir une race, un type d'unité et remplir un nom."));
        return;
    }
    // If any type was chosen, abort instead the model is a character because character don't have a type.
    if(!ui->radioBase->isChecked() &&
       !ui->radioRare->isChecked() &&
       !ui->radioSpecial->isChecked() &&
       ui->comboUnitType->itemText(ui->comboUnitType->currentIndex()) != CHARACTER_STRING)
    {
        QMessageBox::warning(this, tr("Info"), tr("Un type (base, special ou rare) doit être choisi."));
        return;
    }
    if(ui->comboUnitType->itemText(ui->comboUnitType->currentIndex()) == CAVALERY_STRING)
    {
        if(crew->rowCount() > 1 || crew->rowCount() == 0)
        {
            QMessageBox::warning(this, tr("Info"), tr("La figurine doit posséder obligatoirement une (seule) monture."));
            return;
        }
    }

    if(ui->comboUnitType->itemText(ui->comboUnitType->currentIndex()) == CHARACTER_STRING)
    {
        if(ui->checkMounted->isChecked() && crew->rowCount() == 0)
        {
            QMessageBox::warning(this, tr("Info"), tr("Vous avez spécifié que le personnage était monté, veuillez ajouter une monture, ou décocher la case \"Monté\""));
            return;
        }
        if(crew->rowCount() > 1)
        {
            QMessageBox::warning(this, tr("Info"), tr("La figurine doit posséder obligatoirement une seule monture."));
            return;
        }
        if(crew->rowCount()!=0 && !ui->checkMounted->isChecked())
        {
            // Check mounted checkbox is forgetten by user
            ui->checkMounted->setChecked(true);
        }
    }

    QString path = "models/" + ui->comboRace->itemText(ui->comboRace->currentIndex()) +
    		"/" + ui->comboUnitType->itemText(ui->comboUnitType->currentIndex()) +
    		"/" + ui->lineEditName->text() +".unit";

    QFile f;
    f.setFileName(path);

    if(f.exists())
    {
        int rep = QMessageBox::question(this,tr("Ecraser"),
                tr("La figurine existe déjà, voulez vous l'écraser?"), QMessageBox::Yes | QMessageBox::No);
        if (rep == QMessageBox::Yes)
        {
            save(path);
            QMessageBox::information(this, tr("Info"), tr("Figurine sauvegardée avec succès."));
        }
        else if (rep == QMessageBox::No)
        {
            QMessageBox::critical(this, tr("Annulation"), tr("Sauvegarde annulée"));
        }
    }
    else{
        save(path);
        QMessageBox::information(this, tr("Info"), tr("Figurine sauvegardée avec succès."));
    }
}
Exemple #21
0
void checkForUpdates::downloadFinished()
{
    if(downloadRequestAborted)
    {
        if(file)
        {
            file->close();
            file->remove();
            delete file;
            file = NULL;
        }
        reply->deleteLater();
        progressDialog->hide();
        _button->setEnabled(true);
        return;
    }

    downloadReadyRead();
    progressDialog->hide();
    _button->setEnabled(true);
    file->flush();
    file->close();

    if(reply->error())
    {
        //Download failed
        QMessageBox::information(this, "Download failed", tr("Failed: %1").arg(reply->errorString()));
    }

    reply->deleteLater();
    reply = NULL;
    delete file;
    file = NULL;
    QFile *updater = new QFile(filename);
    if(updater->exists())
    {
        QStringList options;
        QProcess *installer = new QProcess(this);
        #ifdef Q_OS_MAC
        QProcess sh;
        sh.start("tar -xvf " + filename);
        sh.waitForFinished();
        sh.close();
        filename = "xTuple-" + serverVersion + "-" + OS + "-installer.app";
        QFileInfo *path2 = new QFileInfo(filename);
        QString filepath = path2->absoluteFilePath() + "/Contents/MacOS/osx-intel";
        if(installer->startDetached(filepath, options))
            reject();
        #endif
        #ifdef Q_OS_LINUX
        QFile launch(filename);
        launch.setPermissions(QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner|QFile::ReadGroup|QFile::WriteGroup|QFile::ExeGroup|QFile::ReadOther|QFile::WriteOther|QFile::ExeOther);
        QFileInfo *path = new QFileInfo(filename);
        if(installer->startDetached(path->absoluteFilePath(), options))
             reject();
        #endif
        #ifdef Q_OS_WIN
        int result = (int)::ShellExecuteA(0, "open", filename.toUtf8().constData(), 0, 0, SW_SHOWNORMAL);
        if (SE_ERR_ACCESSDENIED== result)
        {
            result = (int)::ShellExecuteA(0, "runas", filename.toUtf8().constData(), 0, 0, SW_SHOWNORMAL);
            reject();
        }
        if (result <= 32)
            QMessageBox::information(this, "Download failed", tr("Failed: %1").arg(result));
        #endif
    }
}
Exemple #22
0
bool MOomc::startServer()
{
    try
    {
        // evalMutex.unlock();
        QString msg;
        const char *omhome = getenv("OPENMODELICAHOME");
        QString omcPath;
#ifdef WIN32
        if (!omhome)
        {
            InfoSender::instance()->send(Info("OPEN_MODELICA_HOME_NOT_FOUND"));
            return false;
        }
        omcPath = QString( omhome ) + "bin/omc.exe";
#else /* unix */
        omcPath = (omhome ? QString(omhome)+"bin/omc" : QString(CONFIG_DEFAULT_OPENMODELICAHOME) + "/bin/omc");
#endif

        // Check the IOR file created by omc.exe
        QFile objectRefFile;
        QString fileIdentifier;
        fileIdentifier = qApp->sessionId().append(QTime::currentTime().toString(tr("hh:mm:ss:zzz")).remove(":"));

#ifdef WIN32 // Win32
        objectRefFile.setFileName(QString(QDir::tempPath()).append(QDir::separator()).append("openmodelica.objid.").append(this->mName).append(fileIdentifier));
#else // UNIX environment
        char *user = getenv("USER");
        if (!user) { user = "******"; }
        objectRefFile.setFileName(QString(QDir::tempPath()).append(QDir::separator()).append("openmodelica.").append(QString(user)).append(".objid.").append(this->mName).append(fileIdentifier));
#endif

        if (objectRefFile.exists())
            objectRefFile.remove();

        mObjectRefFile = objectRefFile.fileName();


        // Start the omc.exe
        QStringList parameters;
        parameters << QString("+c=").append(mName).append(fileIdentifier) << QString("+d=interactiveCorba") << QString("+corbaObjectReferenceFilePath=").append(QDir::tempPath());
        QProcess *omcProcess = new QProcess();
        QFile omcOutputFile;
#ifdef WIN32 // Win32
        omcOutputFile.setFileName(QString(QDir::tempPath()).append(QDir::separator()).append("openmodelica.omc.output.").append(mName));
#else // UNIX environment
        omcOutputFile.setFileName(QString(QDir::tempPath()).append(QDir::separator()).append("openmodelica.").append(( QString(user))).append(".omc.output.").append(mName));
#endif
        omcProcess->setProcessChannelMode(QProcess::MergedChannels);
        omcProcess->setStandardOutputFile(omcOutputFile.fileName());
        omcProcess->start(omcPath, parameters);
        // wait for the server to start.
        int ticks = 0;
        while (!objectRefFile.exists())
        {
            SleeperThread::msleep(1000);
            ticks++;
            if (ticks > 20)
            {
                msg = "Unable to find " + OMCHelper::applicationName + " server, Object reference file " + mObjectRefFile + " not created.";
                throw std::runtime_error(msg.toStdString());
            }
        }

        // ORB initialization.
        int argc = 2;
        static const char *argv[] = { "-ORBgiopMaxMsgSize", "10485760" };
        CORBA::ORB_var orb = CORBA::ORB_init(argc, (char **)argv);

        objectRefFile.open(QIODevice::ReadOnly);

        char buf[1024];
        objectRefFile.readLine( buf, sizeof(buf) );
        QString uri( (const char*)buf );

        CORBA::Object_var obj = orb->string_to_object(uri.trimmed().toLatin1());

        mOMC = OmcCommunication::_narrow(obj);
        mHasInitialized = true;
    }
    catch(std::exception &e)
    {
        QString msg = e.what();
        InfoSender::instance()->send(Info(msg,ListInfo::ERROR2));
        mHasInitialized = false;
        return false;
    }
    catch (CORBA::Exception&)
    {
        QString msg = "Unable to communicate with OMC";
        InfoSender::instance()->send(Info(msg,ListInfo::ERROR2));
        mHasInitialized = false;
        return false;
    }

    evalCommand("getInstallationDirectoryPath()");
    OMCHelper::OpenModelicaHome = StringHandler::removeFirstLastQuotes(getResult());

    initTempDirectory();

    // set the OpenModelicaLibrary variable.
    evalCommand("getModelicaPath()");
    OMCHelper::OpenModelicaLibrary = StringHandler::removeFirstLastQuotes(getResult());
    return true;
}
Exemple #23
0
void Desk::readDesk (bool read_sizes)
   {
   QFile oldfile;
   QFile file (_dir + DESK_FNAME);
   QString fname;

   // if there is a maxdesk.ini file, rename it to the official name
   fname = _dir + "/maxdesk.ini";
   oldfile.setName (fname);
   if (!oldfile.exists ())
      {
      fname = _dir + "/MaxDesk.ini";
      oldfile.setName (fname);
      }
   if (oldfile.exists ())
      {
      // if we have the official file, just remove this one
      if (file.exists ())
         oldfile.remove ();
      else
         oldfile.rename (_dir + DESK_FNAME);
      }

   QTextStream stream (&file);
   QString line;
   bool files = false;
   File *f;
   int pos;

   if (file.open (QIODevice::ReadOnly)) while (!stream.atEnd())
      {
      line = stream.readLine(); // line of text excluding '\n'

//      printf( "%s\n", line.latin1() );
      if (line [0] == '[')
         {
         files = line == "[Files]";
         continue;
         }

      // add a new file
      pos = line.find ('=');
      if (files && pos != -1)
         {
         QString fname = line.left (pos);

         QFile test (_dir + fname);
         if (!test.exists ())
            continue;

         if (!addToExistingFile (fname))
            {
            f = createFile (_dir, fname);
            line = line.mid (pos + 1);
            f->decodeFile (line, read_sizes);
            _files << f;
            }
         }
      }

   // advance the position past these
   advance ();
   }
void lc::ReceiptsHandler::CreateReceiptsFromPaymentFile() {
    // Get the data needed for receipts creation from the payment file
    QVector<QString> *rawParticipantsData = nullptr;
    rawParticipantsData = GetParticipantsDataFromPaymentFile();
    for ( int i = 0; i < rawParticipantsData->size(); i++ ) {
        qDebug() << "Payment file line" << QString::number( i ) << ":\t" << rawParticipantsData->at( i );
    }

    // Extract the data of the participant's whose receipts shall be printed
    /* The tab separated fields in the payment file are:
     * SUBJECT  COMPUTER    INTERESTED  NAME    PROFIT  SIGNATURE
     */
    QVector<paymentEntry_t*> *participants = new QVector<paymentEntry_t*>;
    double overall_payoff = 0.0;
    for ( QVector<QString>::iterator it = rawParticipantsData->begin(); it != rawParticipantsData->end() - 1; ++it ) {
        // Split the lines containing the participants' data into their inidivual parts
        QStringList temp_participant_data = it->split('\t', QString::KeepEmptyParts);
        qDebug() << temp_participant_data.join( " - " );
        if ( !printReceiptsForLocalClients && temp_participant_data.at( 3 ).contains( "local" ) ) {
            qDebug() << "Receipt for local client" << temp_participant_data.at( 1 ) << "will not be printed.";
        }
        else {
            // Create a new struct instance for participant data and fill it
            paymentEntry_t *participant  = new paymentEntry_t;
            participant->computer = temp_participant_data.at(1);
            participant->name = temp_participant_data.at(3);
            participant->payoff = temp_participant_data.at(4).toDouble();
            overall_payoff += participant->payoff;
            participants->append(participant);
        }
    }
    delete rawParticipantsData;
    rawParticipantsData = nullptr;

    // Make receipts overview anonymous if requested (at this stage just names are removed, so that the overview still containts the client names
    if ( !anonymousReceiptsPlaceholder.isEmpty() ) {
        MakeReceiptsAnonymous( participants, false );
    }

    // Load the LaTeX header
    QString *latexText = LoadLatexHeader();
    if ( latexText == nullptr ) {
        for ( auto s : *participants ) {
            delete s;
        }
        delete participants;
        participants = nullptr;
        return;
    }

    // Write the comprehension table
    latexText->append( "\n\\COMPREHENSION{\n" );
    unsigned short int zeile = 0;
    for ( auto s : *participants ) {
        latexText->append( expectedPaymentFileName + " & " + s->computer + " & " + s->name + " & " + QString::number( s->payoff, 'f', 2 ) + " \\EUR\\\\\n" );
        if ( zeile % 2 == 0 ) {
            latexText->append( "\\rowcolor[gray]{0.9}\n" );
        }
        ++zeile;
    }

    // MISSING: Appending show up entries to the overview

    // Make also the clients on the receipts anonymous. This is done as second step, so that the beforehand created overview still contains the clients
    if ( !anonymousReceiptsPlaceholder.isEmpty() ) {
        MakeReceiptsAnonymous( participants, true );
    }

    // Add the LaTeX middle sequence
    latexText->append( "}{" + QString::number( overall_payoff, 'f', 2 ) + "}\n\n%%Einzelquittungen\n" );

    // Write the single receipts
    for ( auto s : *participants ) {
        if ( s->payoff >= 0 ) {
            latexText->append( "\\GAINRECEIPT{" + expectedPaymentFileName + "}{" + s->computer + "}{" + s->name + "}{" + QString::number( s->payoff, 'f', 2 ) + "}\n" );
        }
        else {
            latexText->append( "\\LOSSRECEIPT{" + expectedPaymentFileName + "}{" + s->computer + "}{" + s->name + "}{" + QString::number( s->payoff, 'f', 2 ) + "}\n" );
        }
        delete s;
    }
    delete participants;
    participants = nullptr;

    // Append LaTeX ending
    latexText->append( "\\end{document}" );

    qDebug() << *latexText;

    // Create the tex file
    QFile *texFile = new QFile{ zTreeDataTargetPath + "/" + dateString + ".tex" };
    qDebug() << "Tex file" << texFile->fileName() << "will be created for receipts printing.";
    // Clean up any already existing files
    if ( texFile->exists() ) {
        if ( !texFile->remove() ) {
            QMessageBox messageBox( QMessageBox::Critical, "Tex file removing failed", "There already exists a tex file at '" + texFile->fileName()
                                    + "' which cannot be removed. The creation of the receipts printout may fail.", QMessageBox::Ok );
            messageBox.exec();
        }
    }
    // Create a new file
    if ( !texFile->open( QIODevice::Text | QIODevice::WriteOnly ) ) {
        QMessageBox messageBox( QMessageBox::Critical, "Tex file creation failed", "The creation of the tex file for receipts printing at '" + texFile->fileName()
                                + "' failed. Receipts printing will not work.", QMessageBox::Ok );
        messageBox.exec();
        return;
    }

    // Open a QTextStream to write to the file
    QTextStream out( texFile );

    out << *latexText;
    delete latexText;
    latexText = nullptr;

    receiptsPrinter = new ReceiptsPrinter{ dateString, zTreeDataTargetPath, this };
    receiptsPrinter->start();
    connect( receiptsPrinter, &ReceiptsPrinter::PrintingFinished,
             this, &ReceiptsHandler::DeleteReceiptsPrinterInstance );
    connect( receiptsPrinter, &ReceiptsPrinter::ErrorOccurred,
             this, &ReceiptsHandler::DisplayMessageBox );

    // Clean up
    texFile->close();
    delete texFile;
}
Exemple #25
0
int main(int argc, char *argv[])
{

    QDir dir;
    QString path=dir.absolutePath();

    QDate data = QDate::currentDate();
    int DaysInMonths = data.daysInMonth();
    int ActualDay = data.day();

    int currentExitCode = 0;

    do
    {
            QApplication a(argc, argv);
            a.setStyle("fusion");

            QFont font("Calibri Light", 12, QFont::Light ,false);
            QFont font_main("Calibri Light", 10, QFont::Light ,false);
            QFont splash_font("Calibri Light", 24, QFont::Bold);

            LoginDialog *logindialog = new LoginDialog;
            MainWindow w;

            logindialog->setWindowFlags(((logindialog->windowFlags() | Qt::CustomizeWindowHint) & Qt::WindowCloseButtonHint & ~Qt::WindowContextHelpButtonHint) );

            /* Ekran startowy*/
            if(currentExitCode != MainWindow::EXIT_CODE_REBOOT)
            {
                QSplashScreen * splash = new QSplashScreen;
                splash->setPixmap(QPixmap(path+"/obrazy/splash.png"));
                splash->setFont(splash_font);
                splash->show();
                splash->showMessage(QObject::tr("Uruchamianie programu "),
                                Qt::AlignLeft | Qt::AlignTop, Qt::black);  //This line represents the alignment of text, color and position

                qApp->processEvents();
                QTimer::singleShot(2000,splash,SLOT(close()));
                QString Splash_string = "Uruchamianie programu";
                QString Splash_string_add = "Uruchamianie programu";

                for(int i=0;i<12;i++)
                {
                    QThread::msleep(150);
                    Splash_string_add = Splash_string_add + ".";

                    if(i==3 || i==7 || i==11) Splash_string_add = Splash_string;

                    splash->showMessage(Splash_string_add,
                                    Qt::AlignLeft | Qt::AlignTop, Qt::black);  //This line represents the alignment of text, color and position
                }
            }



            /* signal-slot - connect login and password from logindialog with MainWindow */
            QObject::connect(logindialog, SIGNAL(sendAccess(QString,QString)),
                             &w, SLOT(receiveAccess(QString,QString)));



            logindialog->setWindowIcon(QIcon(path+"/obrazy/log_icon.png"));
            logindialog->setWindowTitle("SERWIS - Logowanie");
            logindialog->setFont(font);
            if (logindialog->exec() != QDialog::Accepted) {
                a.quit();
                return 0;
            } else {
                delete logindialog;
                w.showMaximized();
                w.setWindowTitle("SERWIS");
                w.setWindowIcon(QIcon(path+"/obrazy/services_icon.png"));
                w.setFont(font_main);
                w.show();

                QFile file;
                QString file_name="AUTO_BACKUP.txt";
                file.setFileName(file_name);
                if(!file.exists() && (DaysInMonths-ActualDay)==1){

                    QMessageBox::warning(&w,"Informacja","****************** Do końca miesiąca został 1 dzień! *******************\n"
                                                         "Wykonany zostanie automatyczny zapis kopii zapasowej bazy danych. \n"
                                                         "*************************************************************************");
                    QTimer::singleShot(500,&w,SLOT(create_backup()));

                    qDebug() << "Doesn't exists: "<<file_name;
                    file.open(QIODevice::ReadWrite | QIODevice::Text);
                    QTextStream stream(&file);
                    file.close();

                }else if (file.exists() && (DaysInMonths-ActualDay)!=1){
                    qDebug() << file_name <<" removing ...";
                    file.remove();
                }else if (file.exists() && (DaysInMonths-ActualDay)==1)
                {
                    qDebug() << file_name <<" already created ...";
                }

            }
             currentExitCode = a.exec();
     } while( currentExitCode == MainWindow::EXIT_CODE_REBOOT );

    return currentExitCode;
}
Exemple #26
0
void QvkSettings::readAll()
{
    // Read from file VERSION progname and versionsnumber
    QSettings versionSettings(":/VERSION", QSettings::IniFormat );
    versionSettings.beginGroup("Info");
      bool beta = versionSettings.value( "Beta" ).toBool();
      QString Beta;
      if ( beta )
        Beta = " Beta"; 
      else
        Beta = "";
      
      ProgName = versionSettings.value( "Progname" ).toString();
      Version = versionSettings.value( "Version" ).toString() + Beta;
    versionSettings.endGroup();
    
    // Einstellungen aus .conf einlesen
    QSettings settings( getProgName(), getProgName() );
    
    // Dient nur zum anlegen des Profils damit ffmpeglog erstellt werden kann
    settings.beginGroup("vokoscreen");
      settings.setValue("Version", getVersion());
    settings.endGroup();
  
    settings.beginGroup( "Audio" );
      AudioOnOff = settings.value( "AudioOnOff", 2 ).toUInt();
    settings.endGroup();
    
    settings.beginGroup("Alsa" );
      AlsaSelect = settings.value( "Alsa", false ).toBool();
    settings.endGroup();

    settings.beginGroup("Pulse");
      PulseSelect = settings.value( "Pulse", true ).toBool();
    settings.endGroup();

    settings.beginGroup("Record");
      FullScreenSelect = settings.value( "FullScreen", true ).toBool();
      WindowSelect = settings.value( "Window", false ).toBool();
      AreaSelect = settings.value( "Area", false ).toBool();
    settings.endGroup();
    
    settings.beginGroup( "Miscellaneous" );
      VideoPath = settings.value( "VideoPath" ).toString();
      VideoPlayer = settings.value( "Videoplayer" ).toString();
      GIFPlayer = settings.value( "GIFplayer" ).toString();
      Minimized = settings.value( "Minimized", 0 ).toUInt();
      Countdown = settings.value( "Countdown", 0 ).toUInt();
      QFile file;
      if ( file.exists( qApp->applicationDirPath().append( "/bin/ffmpeg" ) ) == true )
      {
	vokoscreenWithLibs = true;
        Recorder = qApp->applicationDirPath().append( "/bin/ffmpeg" );
      }
      else
      {
	vokoscreenWithLibs = false;
        Recorder = settings.value( "Recorder", "ffmpeg" ).toString();
      }
    settings.endGroup();
    
    settings.beginGroup( "Videooptions" );
      // Als Beispiel:
      // Frames könnte "" sein dann wird Wert 0 zugewiesen
      // er könnte aber auch größer 200 haben. In beiden Fällen wird der Standardwert 25 zugewiesen.
      Frames = settings.value( "Frames", 25 ).toInt();
      if ( ( Frames == 0 ) or ( Frames > 200 ) )
      {
	Frames = 25;
      }
      
      VideoCodec = settings.value( "Videocodec", "libx264" ).toString();
      AudioCodec = settings.value( "Audiocodec", "libmp3lame" ).toString();
      VideoContainer = settings.value( "Format", "mkv" ).toString();
      HideMouse = settings.value( "HideMouse").toUInt();
    settings.endGroup();

    settings.beginGroup( "GUI" );
      X = settings.value( "X", "100" ).toUInt();
      Y = settings.value( "Y", "100" ).toUInt();
      Tab = settings.value( "Tab", "0" ).toUInt();
      Systray = settings.value( "Systray", 2 ).toUInt();
    settings.endGroup();
    
    settings.beginGroup( "Area" );
        AreaX = settings.value( "X", 200 ).toInt();
        AreaY = settings.value( "Y", 200 ).toInt();
        AreaWidth = settings.value( "Width", 200 ).toUInt();
        AreaHeight = settings.value( "Height", 200 ).toUInt();
    settings.endGroup();

    settings.beginGroup( "Webcam" );
        webcamOnOff = settings.value( "OnOff", 0 ).toUInt();
	webcamX = settings.value( "X", 400 ).toUInt();
	webcamY = settings.value( "Y", 400 ).toUInt();
	webcamWidth = settings.value( "Width", 320 ).toUInt();
	webcamHeight = settings.value( "Height", 240 ).toUInt();
        webcamMirrored = settings.value( "Mirrored", 0 ).toInt();
	webcamBorder = settings.value( "Border", true ).toBool();
	webcamOverFullScreen = settings.value( "OverFullScreen", false ).toBool();
	webcamButtonTopMiddle = settings.value( "Top", false ).toBool();
        webcamButtonRightMiddle = settings.value( "Right", false ).toBool();
        webcamButtonBottomMiddle = settings.value( "Bottom", false ).toBool();
	webcamButtonLeftMiddle = settings.value( "Left", false ).toBool();
	if ( ( getWebcamButtonTopMiddle() == false ) and ( getWebcamButtonRightMiddle() == false ) and ( getWebcamButtonLeftMiddle() == false ) )
	{
	  webcamButtonBottomMiddle = true;
	}
    settings.endGroup();
    
    settings.beginGroup( "Magnifier" );
        magnifierOnOff = settings.value( "OnOff", 0 ).toUInt();
	magnifierFormValue = settings.value( "FormValue", 2 ).toUInt();
    settings.endGroup();
    
    settings.beginGroup( "ShowClick" );
        showClickOnOff    = settings.value( "OnOff", 0 ).toInt();
        showClickTime     = settings.value( "Showtime", 5 ).toDouble();
        showClickCircle   = settings.value( "Circle", 70 ).toInt();
        showClickRadiant  = settings.value( "Radiant", false ).toBool();
        showClickColor    = settings.value( "Color", QColor( Qt::red ) ).value<QColor>();
        showClickOpacity  = settings.value( "Opacity", 0.5 ).toDouble();
    settings.endGroup();
    
    settings.beginGroup( "ShowKey" );
        showKeyOnOff = settings.value( "OnOff", 0 ).toInt();
    settings.endGroup();
}
bool DirectoryModuleLoader::search(const std::string& module)
{
    QFile moduleFile;
    resolve(moduleFile, module);
    return moduleFile.exists();
}
Exemple #28
0
AbstractCommand::ReturnCodes Record::record()
{
    if (! checkInRepository())
        return NotInRepo;
    moveToRoot(CheckFileSystem);

    if (m_mode != Unset)
        m_all = m_mode == AllChanges;
    const bool needHunks = !m_all || m_patchName.isEmpty();

    ChangeSet changeSet;
    changeSet.fillFromCurrentChanges(rebasedArguments(), needHunks);

    changeSet.waitForFinishFirstFile();
    bool shouldDoRecord = changeSet.count() > 0;
    if (!shouldDoRecord) {
        Logger::warn() << "No changes!" << endl;
        return Ok;
    }

    QString email = m_author;
    if (email.isEmpty())
        email = getenv("EMAIL");
    QStringList environment;
    if (! email.isEmpty()) {
        QRegExp re("(.*) <([@\\S]+)>");
        if (re.exactMatch(email)) { // meaning its an email AND name
            environment << "GIT_AUTHOR_NAME="+ re.cap(1);
            environment << "GIT_COMMITTER_NAME="+ re.cap(1);
            environment << "GIT_AUTHOR_EMAIL="+ re.cap(2);
            environment << "GIT_COMMITTER_EMAIL="+ re.cap(2);
        }
        else if (m_author.isEmpty()) { // if its an account or shell wide option; just use the git defs.
            environment << "GIT_AUTHOR_EMAIL="+ email;
            environment << "GIT_COMMITTER_EMAIL="+ email;
        }
        else {
            Logger::error() << "Author format invalid. Please provide author formatted like; `name <email@host>\n";
            return InvalidOptions;
        }
    }

    if (shouldDoRecord && !m_all && m_mode != Index) { // then do interview
        HunksCursor cursor(changeSet);
        cursor.setConfiguration(m_config);
        Interview interview(cursor, name());
        interview.setUsePager(shouldUsePager());
        if (! interview.start()) {
            Logger::warn() << "Cancelled." << endl;
            return UserCancelled;
        }
    }

    if (shouldDoRecord && !m_all && m_mode != Index) { // check if there is anything selected
        shouldDoRecord = changeSet.hasAcceptedChanges();
        if (! shouldDoRecord) {
            Logger::warn() << "Ok, if you don't want to record anything, that's fine!" <<endl;
            return UserCancelled;
        }
    }
    if (dryRun())
        return Ok;

    if ((m_editComment || m_patchName.isEmpty()) && getenv("EDITOR")) {
        class Deleter : public QObject {
        public:
            Deleter() : commitMessage(0) { }
            ~Deleter() {
                if (commitMessage)
                    commitMessage->remove();
            }
            QFile *commitMessage;
        };
        Deleter parent;
        QFile *commitMessage;
        int i = 0;
        do {
            commitMessage = new QFile(QString("vng-record-%1").arg(i++), &parent);
        } while (commitMessage->exists());
        parent.commitMessage = commitMessage; // make sure the file is removed from FS.
        if (! commitMessage->open(QIODevice::WriteOnly)) {
            Logger::error() << "Vng failed. Could not create a temporary file for the record message '"
                << commitMessage->fileName() << "`\n";
            return WriteError;
        }
        const char * defaultCommitMessage1 = "\n***END OF DESCRIPTION***"; // we will look for this string later
        const char * defaultCommitMessage2 = "\nPlace the long patch description above the ***END OF DESCRIPTION*** marker.\n\nThis patch contains the following changes:\n\n";
        if (! m_patchName.isEmpty())
            commitMessage->write(m_patchName);
        else
            commitMessage->write("\n", 1);
        commitMessage->write(defaultCommitMessage1, strlen(defaultCommitMessage1));
        commitMessage->write(defaultCommitMessage2, strlen(defaultCommitMessage2));
        QBuffer buffer;
        changeSet.writeDiff(buffer, m_all ? ChangeSet::AllHunks : ChangeSet::UserSelection);
        ChangeSet actualChanges;
        actualChanges.fillFromDiffFile(buffer);
        QTextStream out (commitMessage);
        for (int i=0; i < actualChanges.count(); ++i) {
            File file = actualChanges.file(i);
            file.outputWhatsChanged(out, m_config, true, false);
        }
        for (int i=0; i < changeSet.count(); ++i) {
            File file = changeSet.file(i);
            if (file.isBinary() && (m_all || file.binaryChangeAcceptance() == Vng::Accepted))
                out << "M " << QString::fromLocal8Bit(file.fileName());
            else if (file.fileName().isEmpty() && (m_all || file.renameAcceptance() == Vng::Accepted))
                out << "D " << QString::fromLocal8Bit(file.oldFileName());
        }
        out.flush();

        commitMessage->close();
        QDateTime modification = QFileInfo(*commitMessage).lastModified();
        QString command = QString("%1 %2").arg(getenv("EDITOR")).arg(commitMessage->fileName());
        int rc = system(command.toAscii().data());
        if (rc != 0) {
            // this will keep patchName empty and we fall through to the interview.
            Logger::warn() << "Vng-Warning: Could not start editor '" << getenv("EDITOR") << "`\n";
            Logger::warn().flush();
        }
        else if (modification == QFileInfo(*commitMessage).lastModified()) {
            Logger::warn() << "unchanged, won't record\n";
            return UserCancelled;
        }
        else {
            // get data until the separator line.
            commitMessage->open(QIODevice::ReadOnly);
            m_patchName = commitMessage->readAll();
            commitMessage->close();
            int cuttoff = m_patchName.indexOf(defaultCommitMessage1);
            if (cuttoff > 0)
                m_patchName.truncate(cuttoff);
            for (int i = m_patchName.length()-1; i >= 0; --i) {
                if (m_patchName[i] == '\n' || m_patchName[i] == '\r' || m_patchName[i] == ' ')
                    m_patchName.resize(i); // shrink
                else break;
            }
        }
    }
    if (m_patchName.isEmpty())
        m_patchName = Interview::ask("What is the patch name? ").toUtf8();

    ReturnCodes rc = addFilesPerAcceptance(changeSet, m_all);
    if (rc != Ok)
        return rc;

    QProcess git;
    QStringList arguments;
    arguments << "write-tree";
    GitRunner runner(git, arguments);
    rc = runner.start(GitRunner::WaitForStandardOutput);
    if (rc != Ok) {
        Logger::error() << "Git write-tree failed!, aborting record\n";
        return rc;
    }
    char buf[1024];
    Vng::readLine(&git, buf, sizeof(buf));
    QString tree(buf);
    git.waitForFinished(); // patiently wait for it to finish..
    Logger::debug() << "The tree got git ref; " << tree;
    Logger::debug().flush(); // flush since we do an ask next

    arguments.clear();
    git.setEnvironment(environment);

    arguments << "commit-tree" << tree.left(40);
    if (!m_config.isEmptyRepo())
        arguments << "-p" << "HEAD" ;

    runner.setArguments(arguments);
    rc = runner.start(GitRunner::WaitUntilReadyForWrite);
    if (rc != Ok) {
        Logger::error() << "Git commit-tree failed!, aborting record\n";
        return rc;
    }
    git.write(m_patchName);
    git.write("\n");
    git.closeWriteChannel();
    Vng::readLine(&git, buf, sizeof(buf));
    QString commit(buf);
    Logger::debug() << "commit is ref; " << commit;
    git.waitForFinished(); // patiently wait for it to finish..
    if (commit.isEmpty()) {
        Logger::error() << "Git update-ref failed to produce a reference!, aborting record\n";
        return GitFailed;
    }
    m_sha1 = commit.left(40);

    arguments.clear();
    arguments << "update-ref" << "HEAD" << m_sha1;
    runner.setArguments(arguments);
    rc = runner.start(GitRunner::WaitUntilFinished);
    if (rc != Ok) {
        Logger::error() << "Git update-ref failed!, aborting record\n";
        return rc;
    }

    // We removed files from the index in case they were freshly added, but the user didn't want it in this commit.
    // we have to re-add those files.
    arguments.clear();
    arguments << "update-index" << "--add";
    for (int i=0; i < changeSet.count(); ++i) {
        File file = changeSet.file(i);
        if (! file.oldFileName().isEmpty())
            continue; // not a new added file.
        if (file.renameAcceptance() == Vng::Rejected)
            arguments.append(file.fileName());
    }
    if (arguments.count() > 2) {
        runner.setArguments(arguments);
        runner.start(GitRunner::WaitUntilFinished);
    }

    int endOfLine = m_patchName.indexOf('\n');
    if (endOfLine > 0)
        m_patchName.truncate(endOfLine);
    Logger::warn() << "Finished recording patch `" << m_patchName << "'" << endl;
    return Ok;
}
void DownloadManager::downloadDBFinished()
{
#ifdef QT_DEBUG
    qDebug() << "Finished downloading DB.";
#endif

    dbCacheFile.close();
    reply->deleteLater();

    QFile dbFile;
    dbFile.setFileName(m_dbFileName);
    if (dbFile.exists())
    {
#ifdef QT_DEBUG
        qDebug() << "Removing existing DB file.";
#endif
        if (!dbFile.remove())
        {
            emit dbDownloadFailed();
            setInOperation(false);
            qCritical("Failed to remove current DB file.");
            return;
        }
    }

#ifdef QT_DEBUG
    qDebug() << "Decompressing downloaded DB.";
#endif

    m_process->start(QStringLiteral("gzip"), QStringList({QStringLiteral("-d"), m_dbCacheFileName}));

#ifdef QT_DEBUG
    qDebug() << m_process->program() << m_process->arguments();
#endif

    if (m_process->exitCode() != 0) {
        emit dbDownloadFailed();
        qCritical("Failed to decompress DB.");
        if (configuration()) {
            configuration()->setDatabaseVersion(0);
        }
        setInOperation(false);
        return;
    }

    if (configuration()) {
        configuration()->setDatabaseVersion(availableVersion());
    }

    QEventLoop loop;



    if (dbManager()) {
        connect(m_timer, &QTimer::timeout, dbManager(), &DbManager::checkDB);
        m_timer->start();
    }

    emit dbDownloadFinished();

    setInOperation(false);
}
Exemple #30
0
// We return the UserSettings here because we have to make changes to the
// configuration and the location of the file may change between releases.
UserSettingsPointer Upgrade::versionUpgrade(const QString& settingsPath) {

/*  Pre-1.7.0:
*
*   Since we didn't store version numbers in the config file prior to 1.7.0,
*   we check to see if the user is upgrading if his config files are in the old location,
*   since we moved them in 1.7.0. This code takes care of moving them.
*/

    QDir oldLocation = QDir(QDir::homePath());
#ifdef __WINDOWS__
    QFileInfo* pre170Config = new QFileInfo(oldLocation.filePath("mixxx.cfg"));
#else
    QFileInfo* pre170Config = new QFileInfo(oldLocation.filePath(".mixxx.cfg"));
#endif

    if (pre170Config->exists()) {

        // Move the files to their new location
        QDir newLocation = QDir(settingsPath);

        if (!newLocation.exists()) {
            qDebug() << "Creating new settings directory" << newLocation.absolutePath();
            newLocation.mkpath(".");
        }

        QString errorText = "Error moving your %1 file %2 to the new location %3: \n";

#ifdef __WINDOWS__
        QString oldFilePath = oldLocation.filePath("mixxxtrack.xml");
#else
        QString oldFilePath = oldLocation.filePath(".mixxxtrack.xml");
#endif

        QString newFilePath = newLocation.filePath("mixxxtrack.xml");
        QFile* oldFile = new QFile(oldFilePath);
        if (oldFile->exists()) {
            if (oldFile->copy(newFilePath)) {
                oldFile->remove();
            }
            else {
                if (oldFile->error()==14) qDebug() << errorText.arg("library", oldFilePath, newFilePath) << "The destination file already exists.";
                else qDebug() << errorText.arg("library", oldFilePath, newFilePath) << "Error #" << oldFile->error();
            }
        }
        delete oldFile;

#ifdef __WINDOWS__
        oldFilePath = oldLocation.filePath("mixxxbpmschemes.xml");
#else
        oldFilePath = oldLocation.filePath(".mixxxbpmscheme.xml");
#endif
        newFilePath = newLocation.filePath("mixxxbpmscheme.xml");
        oldFile = new QFile(oldFilePath);
        if (oldFile->exists()) {
            if (oldFile->copy(newFilePath))
                oldFile->remove();
            else {
                if (oldFile->error()==14) qDebug() << errorText.arg("settings", oldFilePath, newFilePath) << "The destination file already exists.";
                else qDebug() << errorText.arg("settings", oldFilePath, newFilePath) << "Error #" << oldFile->error();
            }
        }
        delete oldFile;
#ifdef __WINDOWS__
        oldFilePath = oldLocation.filePath("MixxxMIDIBindings.xml");
#else
        oldFilePath = oldLocation.filePath(".MixxxMIDIBindings.xml");
#endif
        newFilePath = newLocation.filePath("MixxxMIDIBindings.xml");
        oldFile = new QFile(oldFilePath);
        if (oldFile->exists()) {
            qWarning() << "The MIDI mapping file format has changed in this version of Mixxx. You will need to reconfigure your MIDI controller. See the Wiki for full details on the new format.";
            if (oldFile->copy(newFilePath))
                oldFile->remove();
            else {
                if (oldFile->error()==14) qDebug() << errorText.arg("MIDI mapping", oldFilePath, newFilePath) << "The destination file already exists.";
                else qDebug() << errorText.arg("MIDI mapping", oldFilePath, newFilePath) << "Error #" << oldFile->error();
            }
        }
        // Tidy up
        delete oldFile;
#ifdef __WINDOWS__
        QFile::remove(oldLocation.filePath("MixxxMIDIDevice.xml")); // Obsolete file, so just delete it
#else
        QFile::remove(oldLocation.filePath(".MixxxMIDIDevice.xml")); // Obsolete file, so just delete it
#endif

#ifdef __WINDOWS__
        oldFilePath = oldLocation.filePath("mixxx.cfg");
#else
        oldFilePath = oldLocation.filePath(".mixxx.cfg");
#endif
        newFilePath = newLocation.filePath(SETTINGS_FILE);
        oldFile = new QFile(oldFilePath);
        if (oldFile->copy(newFilePath))
            oldFile->remove();
        else {
                if (oldFile->error()==14) qDebug() << errorText.arg("configuration", oldFilePath, newFilePath) << "The destination file already exists.";
                else qDebug() << errorText.arg("configuration", oldFilePath, newFilePath) << "Error #" << oldFile->error();
            }
        delete oldFile;

    }
    // Tidy up
    delete pre170Config;
    // End pre-1.7.0 code


/***************************************************************************
*                           Post-1.7.0 upgrade code
*
*   Add entries to the IF ladder below if anything needs to change from the
*   previous to the current version. This allows for incremental upgrades
*   in case a user upgrades from a few versions prior.
****************************************************************************/

    // Read the config file from home directory
    UserSettingsPointer config(new ConfigObject<ConfigValue>(
        QDir(settingsPath).filePath(SETTINGS_FILE)));

    QString configVersion = config->getValueString(ConfigKey("[Config]","Version"));

    if (configVersion.isEmpty()) {

#ifdef __APPLE__
        qDebug() << "Config version is empty, trying to read pre-1.9.0 config";
        // Try to read the config from the pre-1.9.0 final directory on OS X (we moved it in 1.9.0 final)
        QScopedPointer<QFile> oldConfigFile(new QFile(QDir::homePath().append("/").append(".mixxx/mixxx.cfg")));
        if (oldConfigFile->exists() && ! CmdlineArgs::Instance().getSettingsPathSet()) {
            qDebug() << "Found pre-1.9.0 config for OS X";
            // Note: We changed SETTINGS_PATH in 1.9.0 final on OS X so it must be hardcoded to ".mixxx" here for legacy.
            config = UserSettingsPointer(new ConfigObject<ConfigValue>(
                QDir::homePath().append("/.mixxx/mixxx.cfg")));
            // Just to be sure all files like logs and soundconfig go with mixxx.cfg
            // TODO(XXX) Trailing slash not needed anymore as we switches from String::append
            // to QDir::filePath elsewhere in the code. This is candidate for removal.
            CmdlineArgs::Instance().setSettingsPath(QDir::homePath().append("/.mixxx/"));
            configVersion = config->getValueString(ConfigKey("[Config]","Version"));
        }
        else {
#elif __WINDOWS__
        qDebug() << "Config version is empty, trying to read pre-1.12.0 config";
        // Try to read the config from the pre-1.12.0 final directory on Windows (we moved it in 1.12.0 final)
        QScopedPointer<QFile> oldConfigFile(new QFile(QDir::homePath().append("/Local Settings/Application Data/Mixxx/mixxx.cfg")));
        if (oldConfigFile->exists() && ! CmdlineArgs::Instance().getSettingsPathSet()) {
            qDebug() << "Found pre-1.12.0 config for Windows";
            // Note: We changed SETTINGS_PATH in 1.12.0 final on Windows so it must be hardcoded to "Local Settings/Application Data/Mixxx/" here for legacy.
            config = UserSettingsPointer(new ConfigObject<ConfigValue>(
                QDir::homePath().append("/Local Settings/Application Data/Mixxx/mixxx.cfg")));
            // Just to be sure all files like logs and soundconfig go with mixxx.cfg
            // TODO(XXX) Trailing slash not needed anymore as we switches from String::append
            // to QDir::filePath elsewhere in the code. This is candidate for removal.
            CmdlineArgs::Instance().setSettingsPath(QDir::homePath().append("/Local Settings/Application Data/Mixxx/"));
            configVersion = config->getValueString(ConfigKey("[Config]","Version"));
        }
        else {
#endif
            // This must have been the first run... right? :)
            qDebug() << "No version number in configuration file. Setting to" << MIXXX_VERSION;
            config->set(ConfigKey("[Config]","Version"), ConfigValue(MIXXX_VERSION));
            m_bFirstRun = true;
            return config;
#ifdef __APPLE__
        }
#elif __WINDOWS__
        }
#endif
    }

    // If it's already current, stop here
    if (configVersion == MIXXX_VERSION) {
        qDebug() << "Configuration file is at the current version" << MIXXX_VERSION;
        return config;
    }

    // Allows for incremental upgrades in case someone upgrades from a few versions prior
    // (I wish we could do a switch on a QString.)
    /*
    // Examples, since we didn't store the version number prior to v1.7.0
    if (configVersion.startsWith("1.6.0")) {
        qDebug() << "Upgrading from v1.6.0 to 1.6.1...";
        // Upgrade tasks go here
        configVersion = "1.6.1";
        config->set(ConfigKey("[Config]","Version"), ConfigValue("1.6.1"));
    }
    if (configVersion.startsWith("1.6.1")) {
        qDebug() << "Upgrading from v1.6.1 to 1.7.0...";
        // Upgrade tasks go here
        configVersion = "1.7.0";
        config->set(ConfigKey("[Config]","Version"), ConfigValue("1.7.0"));
    }
    */

    // We use the following blocks to detect if this is the first time
    // you've run the latest version of Mixxx. This lets us show
    // the promo tracks stats agreement stuff for all users that are
    // upgrading Mixxx.

    if (configVersion.startsWith("1.7")) {
        qDebug() << "Upgrading from v1.7.x...";
        // Upgrade tasks go here
        // Nothing to change, really
        configVersion = "1.8.0";
        config->set(ConfigKey("[Config]","Version"), ConfigValue("1.8.0"));
    }

    if (configVersion.startsWith("1.8.0~beta1") ||
        configVersion.startsWith("1.8.0~beta2")) {
        qDebug() << "Upgrading from v1.8.0~beta...";
        // Upgrade tasks go here
        configVersion = "1.8.0";
        config->set(ConfigKey("[Config]","Version"), ConfigValue("1.8.0"));
    }
    if (configVersion.startsWith("1.8") || configVersion.startsWith("1.9.0beta1")) {
        qDebug() << "Upgrading from" << configVersion << "...";
        // Upgrade tasks go here
#ifdef __APPLE__
        QString OSXLocation180 = QDir::homePath().append("/").append(".mixxx");
        QString OSXLocation190 = settingsPath;
        QDir newOSXDir(OSXLocation190);
        newOSXDir.mkpath(OSXLocation190);

        QList<QPair<QString, QString> > dirsToMove;
        dirsToMove.push_back(QPair<QString, QString>(OSXLocation180, OSXLocation190));
        dirsToMove.push_back(QPair<QString, QString>(OSXLocation180 + "/midi", OSXLocation190 + "midi"));
        dirsToMove.push_back(QPair<QString, QString>(OSXLocation180 + "/presets", OSXLocation190 + "presets"));

        QListIterator<QPair<QString, QString> > dirIt(dirsToMove);
        QPair<QString, QString> curPair;
        while (dirIt.hasNext())
        {
            curPair = dirIt.next();
            qDebug() << "Moving" << curPair.first << "to" << curPair.second;
            QDir oldSubDir(curPair.first);
            QDir newSubDir(curPair.second);
            newSubDir.mkpath(curPair.second); // Create the new destination directory

            QStringList contents = oldSubDir.entryList(QDir::Files | QDir::NoDotAndDotDot);
            QStringListIterator it(contents);
            QString cur;
            // Iterate over all the files in the source directory and copy them to the dest dir.
            while (it.hasNext())
            {
                cur = it.next();
                QString src = curPair.first + "/" + cur;
                QString dest = curPair.second + "/" + cur;
                qDebug() << "Copying" << src << "to" << dest;
                if (!QFile::copy(src, dest))
                {
                    qDebug() << "Failed to move file during upgrade.";
                }
            }

            // Rename the old directory.
            newOSXDir.rename(OSXLocation180, OSXLocation180 + "-1.8");
        }
        // Reload the configuration file from the new location.
        // (We want to make sure we save to the new location...)
        config = UserSettingsPointer(new ConfigObject<ConfigValue>(
            QDir(settingsPath).filePath(SETTINGS_FILE)));
#endif
        configVersion = "1.9.0";
        config->set(ConfigKey("[Config]","Version"), ConfigValue("1.9.0"));
    }
    if (configVersion.startsWith("1.9") || configVersion.startsWith("1.10")) {
        qDebug() << "Upgrading from v1.9.x/1.10.x...";

        bool successful = true;

        qDebug() << "Copying midi/ to controllers/";
        QString midiPath = legacyUserPresetsPath(config);
        QString controllerPath = userPresetsPath(config);
        QDir oldDir(midiPath);
        QDir newDir(controllerPath);
        newDir.mkpath(controllerPath);  // create the new directory

        QStringList contents = oldDir.entryList(QDir::Files | QDir::NoDotAndDotDot);
        QStringListIterator it(contents);
        QString cur;
        // Iterate over all the files in the source directory and copy them to the dest dir.
        while (it.hasNext()) {
            cur = it.next();
            if (newDir.exists(cur)) {
                qDebug() << cur << "already exists in"
                         << controllerPath << "Skipping.";
                continue;
            }
            QString src = oldDir.absoluteFilePath(cur);
            QString dest = newDir.absoluteFilePath(cur);
            qDebug() << "Copying" << src << "to" << dest;
            if (!QFile::copy(src, dest)) {
                qDebug() << "Failed to copy file during upgrade.";
                successful = false;
            }
        }

        bool reanalyze_choice = askReanalyzeBeats();
        BeatDetectionSettings bpmSettings(config);
        bpmSettings.setReanalyzeWhenSettingsChange(reanalyze_choice);

        if (successful) {
            qDebug() << "Upgrade Successful";
            configVersion = "1.11.0";
            config->set(ConfigKey("[Config]","Version"),
                        ConfigValue(configVersion));
        } else {
            qDebug() << "Upgrade Failed";
        }
    }

    if (configVersion.startsWith("1.11")) {
        qDebug() << "Upgrading from v1.11.x...";
        bool successful = false;
        {
            MixxxDb mixxxDb(config);
            const mixxx::DbConnectionPooler dbConnectionPooler(
                    mixxxDb.connectionPool());
            if (dbConnectionPooler.isPooling()) {
                QSqlDatabase dbConnection = mixxx::DbConnectionPooled(mixxxDb.connectionPool());
                DEBUG_ASSERT(dbConnection.isOpen());
                if (MixxxDb::initDatabaseSchema(dbConnection)) {
                    TrackCollection tc(config);
                    tc.connectDatabase(dbConnection);

                    // upgrade to the multi library folder settings
                    QString currentFolder = config->getValueString(PREF_LEGACY_LIBRARY_DIR);
                    // to migrate the DB just add the current directory to the new
                    // directories table
                    // NOTE(rryan): We don't have to ask for sandbox permission to this
                    // directory because the normal startup integrity check in Library will
                    // notice if we don't have permission and ask for access. Also, the
                    // Sandbox isn't setup yet at this point in startup because it relies on
                    // the config settings path and this function is what loads the config
                    // so it's not ready yet.
                    successful = tc.getDirectoryDAO().addDirectory(currentFolder);

                    tc.disconnectDatabase();
                }
            }
        }

        // ask for library rescan to activate cover art. We can later ask for
        // this variable when the library scanner is constructed.
        m_bRescanLibrary = askReScanLibrary();

        // Versions of mixxx until 1.11 had a hack that multiplied gain by 1/2,
        // which was compensation for another hack that set replaygain to a
        // default of 6.  We've now removed all of the hacks, so subtracting
        // 6 from everyone's replay gain should keep things consistent for
        // all users.
        int oldReplayGain = config->getValue(
                ConfigKey("[ReplayGain]", "InitialReplayGainBoost"), 6);
        int newReplayGain = math_max(-6, oldReplayGain - 6);
        config->set(ConfigKey("[ReplayGain]", "InitialReplayGainBoost"),
                    ConfigValue(newReplayGain));

        // if everything until here worked fine we can mark the configuration as
        // updated
        if (successful) {
            configVersion = MIXXX_VERSION;
            config->set(ConfigKey("[Config]","Version"), ConfigValue(MIXXX_VERSION));
        }
        else {
            qDebug() << "Upgrade failed!\n";
        }
    }

    if (configVersion.startsWith("1.12") ||
        configVersion.startsWith("2.0") ||
        configVersion.startsWith("2.1.0")) {
        // No special upgrade required, just update the value.
        configVersion = MIXXX_VERSION;
        config->set(ConfigKey("[Config]","Version"), ConfigValue(MIXXX_VERSION));
    }

    if (configVersion == MIXXX_VERSION) qDebug() << "Configuration file is now at the current version" << MIXXX_VERSION;
    else {
        qWarning() << "Configuration file is at version" << configVersion
                   << "instead of the current" << MIXXX_VERSION;
    }

    return config;
}