/** FET starts here */ int main(int argc, char **argv) { terminateGeneratePointer=NULL; QCoreApplication qapplication(argc, argv); //QObject::connect(&qapplication, SIGNAL(lastWindowClosed()), &qapplication, SLOT(quit())); srand(unsigned(time(NULL))); //useless, I use randomKnuth(), but just in case I use somewhere rand() by mistake... initRandomKnuth(); OUTPUT_DIR=QDir::homePath()+FILE_SEP+"fet-results"; QStringList _args=QCoreApplication::arguments(); if(_args.count()==1){ readSimulationParameters(); QDir dir; bool t=true; //make sure that the output directory exists if(!dir.exists(OUTPUT_DIR)) t=dir.mkpath(OUTPUT_DIR); if(!t){ /* QMessageBox::critical(NULL, FetTranslate::tr("FET critical"), FetTranslate::tr("Cannot create or use %1 directory (where the results should be stored) - you can continue operation, but you might not be able to work with FET." " Maybe you can try to change the output directory from the 'Settings' menu. If this is a bug - please report it.").arg(QDir::toNativeSeparators(OUTPUT_DIR))); */ } QString testFileName=OUTPUT_DIR+FILE_SEP+"test_write_permissions_1.tmp"; QFile test(testFileName); bool existedBefore=test.exists(); bool t_t=test.open(QIODevice::ReadWrite); if(!t_t){ /* QMessageBox::critical(NULL, FetTranslate::tr("FET critical"), FetTranslate::tr("You don't have write permissions in the output directory " "(FET cannot open or create file %1) - you might not be able to work correctly with FET. Maybe you can try to change the output directory from the 'Settings' menu." " If this is a bug - please report it.").arg(testFileName)); */ } else{ test.close(); if(!existedBefore) test.remove(); } } students_schedule_ready=0; teachers_schedule_ready=0; rooms_schedule_ready=0; ///////////////////////////////////////////////// //begin command line if(_args.count()>1){ int randomSeedX=-1; int randomSeedY=-1; bool randomSeedXSpecified=false; bool randomSeedYSpecified=false; QString outputDirectory=""; INPUT_FILENAME_XML=""; QString filename=""; int secondsLimit=2000000000; TIMETABLE_HTML_LEVEL=2; FET_LANGUAGE="en_US"; PRINT_NOT_AVAILABLE_TIME_SLOTS=true; PRINT_BREAK_TIME_SLOTS=true; DIVIDE_HTML_TIMETABLES_WITH_TIME_AXIS_BY_DAYS=false; PRINT_ACTIVITIES_WITH_SAME_STARTING_TIME=false; QStringList unrecognizedOptions; SHOW_WARNING_FOR_STUDENTS_MIN_HOURS_DAILY_WITH_ALLOW_EMPTY_DAYS=true; SHOW_WARNING_FOR_NOT_PERFECT_CONSTRAINTS=true; SHOW_WARNING_FOR_STUDENTS_MIN_HOURS_DAILY_WITH_ALLOW_EMPTY_DAYS=true; bool showVersion=false; for(int i=1; i<_args.count(); i++){ QString s=_args[i]; if(s.left(12)=="--inputfile=") filename=QDir::fromNativeSeparators(s.right(s.length()-12)); else if(s.left(19)=="--timelimitseconds=") secondsLimit=s.right(s.length()-19).toInt(); else if(s.left(21)=="--timetablehtmllevel=") TIMETABLE_HTML_LEVEL=s.right(s.length()-21).toInt(); else if(s.left(12)=="--htmllevel=") TIMETABLE_HTML_LEVEL=s.right(s.length()-12).toInt(); else if(s.left(11)=="--language=") FET_LANGUAGE=s.right(s.length()-11); else if(s.left(20)=="--printnotavailable="){ if(s.right(5)=="false") PRINT_NOT_AVAILABLE_TIME_SLOTS=false; else PRINT_NOT_AVAILABLE_TIME_SLOTS=true; } else if(s.left(13)=="--printbreak="){ if(s.right(5)=="false") PRINT_BREAK_TIME_SLOTS=false; else PRINT_BREAK_TIME_SLOTS=true; } else if(s.left(23)=="--dividetimeaxisbydays="){ if(s.right(5)=="false") DIVIDE_HTML_TIMETABLES_WITH_TIME_AXIS_BY_DAYS=false; else DIVIDE_HTML_TIMETABLES_WITH_TIME_AXIS_BY_DAYS=true; } else if(s.left(12)=="--outputdir="){ outputDirectory=QDir::fromNativeSeparators(s.right(s.length()-12)); } else if(s.left(30)=="--printsimultaneousactivities="){ if(s.right(5)=="false") PRINT_ACTIVITIES_WITH_SAME_STARTING_TIME=false; else PRINT_ACTIVITIES_WITH_SAME_STARTING_TIME=true; } else if(s.left(14)=="--randomseedx="){ randomSeedXSpecified=true; randomSeedX=s.right(s.length()-14).toInt(); } else if(s.left(14)=="--randomseedy="){ randomSeedYSpecified=true; randomSeedY=s.right(s.length()-14).toInt(); } else if(s.left(35)=="--warnifusingnotperfectconstraints="){ if(s.right(5)=="false") SHOW_WARNING_FOR_NOT_PERFECT_CONSTRAINTS=false; } else if(s.left(53)=="--warnifusingstudentsminhoursdailywithallowemptydays="){ if(s.right(5)=="false") SHOW_WARNING_FOR_STUDENTS_MIN_HOURS_DAILY_WITH_ALLOW_EMPTY_DAYS=false; } else if(s=="--version"){ showVersion=true; } else unrecognizedOptions.append(s); } INPUT_FILENAME_XML=filename; QString initialDir=outputDirectory; if(initialDir!="") initialDir.append(FILE_SEP); if(outputDirectory!="") outputDirectory.append(FILE_SEP); outputDirectory.append("timetables"); ////////// if(INPUT_FILENAME_XML!=""){ outputDirectory.append(FILE_SEP); outputDirectory.append(INPUT_FILENAME_XML.right(INPUT_FILENAME_XML.length()-INPUT_FILENAME_XML.lastIndexOf(FILE_SEP)-1)); if(outputDirectory.right(4)==".fet") outputDirectory=outputDirectory.left(outputDirectory.length()-4); } ////////// QDir dir; QString logsDir=initialDir+"logs"; if(!dir.exists(logsDir)) dir.mkpath(logsDir); logsDir.append(FILE_SEP); //////// QFile logFile(logsDir+"result.txt"); bool tttt=logFile.open(QIODevice::WriteOnly); if(!tttt){ cout<<"FET critical - you don't have write permissions in the output directory - (FET cannot open or create file "<<qPrintable(logsDir)<<"result.txt)." " If this is a bug - please report it."<<endl; return 1; } QTextStream out(&logFile); /////// //setLanguage(qapplication, NULL); if(showVersion){ out<<"This file contains the result (log) of last operation"<<endl<<endl; QDate dat=QDate::currentDate(); QTime tim=QTime::currentTime(); QLocale loc(FET_LANGUAGE); QString sTime=loc.toString(dat, QLocale::ShortFormat)+" "+loc.toString(tim, QLocale::ShortFormat); out<<"FET command line request for version started on "<<qPrintable(sTime)<<endl<<endl; //QString qv=qVersion(); out<<"FET version "<<qPrintable(FET_VERSION)<<endl; out<<"Free timetabling software, licensed under GNU GPL v2 or later"<<endl; out<<"Copyright (C) 2002-2012 Liviu Lalescu"<<endl; out<<"Homepage: http://lalescu.ro/liviu/fet/"<<endl; //out<<" (Using Qt version "<<qPrintable(qv)<<")"<<endl; cout<<"FET version "<<qPrintable(FET_VERSION)<<endl; cout<<"Free timetabling software, licensed under GNU GPL v2 or later"<<endl; cout<<"Copyright (C) 2002-2012 Liviu Lalescu"<<endl; cout<<"Homepage: http://lalescu.ro/liviu/fet/"<<endl; //cout<<" (Using Qt version "<<qPrintable(qv)<<")"<<endl; if(unrecognizedOptions.count()>0){ out<<endl; cout<<endl; foreach(QString s, unrecognizedOptions){ cout<<"Unrecognized option: "<<qPrintable(s)<<endl; out<<"Unrecognized option: "<<qPrintable(s)<<endl; } }
Options::Options(QWidget *parent) : QWidget(parent) { ui.setupUi(this); SetupPluginList(); channelsChanged(0); ui.sbPaTxDelayValue->setVisible(false); ui.sbVoiceRepeatTime->setVisible(false); ui.tbSDR->setCurrentIndex(0); ui.SwMain->setCurrentIndex(0); #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) QString DocumentsLocation = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); #else QString DocumentsLocation = QDesktopServices::storageLocation(QDesktopServices:: HomeLocation); #endif QDir dir; if(dir.exists(DocumentsLocation)) { if(!dir.exists(DocumentsLocation + "/ExpertSDR")) dir.mkdir(DocumentsLocation + "/ExpertSDR"); pathDefaultWaveIQ = DocumentsLocation + "/ExpertSDR/"; } else { if(dir.mkdir(QDir::homePath() + "/ExpertSDR")) pathDefaultWaveIQ = QDir::homePath() + "/ExpertSDR/"; else { QMessageBox msgBox; msgBox.setText("Choose a directory where wave files will be located."); msgBox.exec(); // QString path = QDir::homePath(); if(path.isEmpty()) { msgBox.setText("Wave file location:\n" + QDir::homePath()); msgBox.exec(); pathDefaultWaveIQ = QDir::homePath() + "/"; } else pathDefaultWaveIQ = path + "/"; } } pathDefaultWaveIQDefault = pathDefaultWaveIQ; ui.lbWavePathIQ->setText(pathDefaultWaveIQ); pProg0 = new QProcess(this); pProg1 = new QProcess(this); pProg2 = new QProcess(this); pProg3 = new QProcess(this); pProg4 = new QProcess(this); //prepare to pupulate list in combobox with serial ports ui.cbPttPortName->clear(); ui.cbAddKeyPortName->clear(); ui.cbKeyPortName->clear(); QList<QextPortInfo> ports = QextSerialEnumerator::getPorts(); if (ports.size()!=0) { for (int i = 0; i < ports.size(); i++) { ui.cbPttPortName->addItem(ports.at(i).portName.toLocal8Bit().constData(),0); ui.cbAddKeyPortName->addItem(ports.at(i).portName.toLocal8Bit().constData(),0); ui.cbKeyPortName->addItem(ports.at(i).portName.toLocal8Bit().constData(),0); } } #ifdef Q_OS_LINUX pPttPort = new QextSerialPort("/dev/ttyS0", QextSerialPort::EventDriven); pKeyPort = new QextSerialPort("/dev/ttyS0", QextSerialPort::EventDriven); pAddKeyPort = new QextSerialPort("/dev/ttyS0", QextSerialPort::EventDriven); #else pPttPort = new QextSerialPort("COM1", QextSerialPort::EventDriven); pKeyPort = new QextSerialPort("COM1", QextSerialPort::EventDriven); pAddKeyPort = new QextSerialPort("COM1", QextSerialPort::EventDriven); #endif /*Q_OS_LINUX*/ connect(pPttPort, SIGNAL(dsrChanged(bool)), this, SLOT(OnPttDsr(bool))); connect(pPttPort, SIGNAL(ctsChanged(bool)), this, SLOT(OnPttCts(bool))); connect(pKeyPort, SIGNAL(dsrChanged(bool)), this, SLOT(OnKeyDsr(bool))); connect(pKeyPort, SIGNAL(ctsChanged(bool)), this, SLOT(OnKeyCts(bool))); connect(pAddKeyPort, SIGNAL(dsrChanged(bool)), this, SLOT(OnAddKeyDsr(bool))); connect(pAddKeyPort, SIGNAL(ctsChanged(bool)), this, SLOT(OnAddKeyCts(bool))); connect(ui.LwOptions, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(ChangePage(QListWidgetItem*, QListWidgetItem*))); connect(ui.pbOK, SIGNAL(clicked()), this, SLOT(OnOK())); connect(ui.pbCancel, SIGNAL(clicked()), this, SLOT(OnCancel())); connect(ui.slTxImRejMag, SIGNAL(valueChanged(int)), this, SLOT(OnTxGainChange(int))); connect(ui.slTxImRejPhase, SIGNAL(valueChanged(int)), this, SLOT(OnTxPhaseChange(int))); connect(ui.slTxImRejMagCw, SIGNAL(valueChanged(int)), this, SLOT(OnTxGainChangeCw(int))); connect(ui.sbTxImRejMagCw, SIGNAL(valueChanged(int)), this, SLOT(OnTxGainChangeCw(int))); connect(ui.slTxImRejPhaseCw, SIGNAL(valueChanged(int)), this, SLOT(OnTxPhaseChangeCw(int))); connect(ui.sbTxImRejPhaseCw, SIGNAL(valueChanged(int)), this, SLOT(OnTxPhaseChangeCw(int))); connect(ui.slTxImRejMagAmFm, SIGNAL(valueChanged(int)), this, SLOT(OnTxGainChangeAmFm(int))); connect(ui.sbTxImRejMagAmFm, SIGNAL(valueChanged(int)), this, SLOT(OnTxGainChangeAmFm(int))); connect(ui.slTxImRejPhaseAmFm, SIGNAL(valueChanged(int)), this, SLOT(OnTxPhaseChangeAmFm(int))); connect(ui.sbTxImRejPhaseAmFm, SIGNAL(valueChanged(int)), this, SLOT(OnTxPhaseChangeAmFm(int))); connect(ui.pbProg0, SIGNAL(clicked()), this, SLOT(OnProg0())); connect(ui.pbProg1, SIGNAL(clicked()), this, SLOT(OnProg1())); connect(ui.pbProg2, SIGNAL(clicked()), this, SLOT(OnProg2())); connect(ui.pbProg3, SIGNAL(clicked()), this, SLOT(OnProg3())); connect(ui.pbProg4, SIGNAL(clicked()), this, SLOT(OnProg4())); connect(ui.pbApply, SIGNAL(clicked()), this, SLOT(LaunchProgs())); connect(ui.pbOK, SIGNAL(clicked()), this, SLOT(LaunchProgs())); if(ui.chbExtCtrl->isChecked()) OnEnableExControl(1); else OnEnableExControl(0); connect(ui.chbExtCtrl, SIGNAL(stateChanged(int)), this, SLOT(OnEnableExControl(int))); connect(ui.spinBox_0, SIGNAL(valueChanged(int)), this, SLOT(PowerCorrect160(int))); connect(ui.spinBox_1, SIGNAL(valueChanged(int)), this, SLOT(PowerCorrect80(int))); connect(ui.spinBox_2, SIGNAL(valueChanged(int)), this, SLOT(PowerCorrect60(int))); connect(ui.spinBox_3, SIGNAL(valueChanged(int)), this, SLOT(PowerCorrect40(int))); connect(ui.spinBox_4, SIGNAL(valueChanged(int)), this, SLOT(PowerCorrect30(int))); connect(ui.spinBox_5, SIGNAL(valueChanged(int)), this, SLOT(PowerCorrect20(int))); connect(ui.spinBox_6, SIGNAL(valueChanged(int)), this, SLOT(PowerCorrect17(int))); connect(ui.spinBox_7, SIGNAL(valueChanged(int)), this, SLOT(PowerCorrect15(int))); connect(ui.spinBox_8, SIGNAL(valueChanged(int)), this, SLOT(PowerCorrect12(int))); connect(ui.spinBox_9, SIGNAL(valueChanged(int)), this, SLOT(PowerCorrect10(int))); connect(ui.spinBox_10, SIGNAL(valueChanged(int)), this, SLOT(PowerCorrect6(int))); connect(ui.spinBox_11, SIGNAL(valueChanged(int)), this, SLOT(PowerCorrect2(int))); connect(ui.spinBox_12, SIGNAL(valueChanged(int)), this, SLOT(PowerCorrect07(int))); connect(ui.chbPttEnable, SIGNAL(clicked(bool)), this, SLOT(pttOpen(bool))); ui.chbPttDtr->setVisible(false); ui.chbPttRts->setVisible(false); connect(ui.chbKeyEnable, SIGNAL(clicked(bool)), this, SLOT(keyOpen(bool))); connect(ui.chbAddKeyEnable, SIGNAL(clicked(bool)), this, SLOT(addKeyOpen(bool))); connect(ui.cbPaDriver, SIGNAL(currentIndexChanged(int)), this, SLOT(soundDrvChanged(int))); connect(ui.cbPaIn, SIGNAL(currentIndexChanged(int)), this, SLOT(soundChanged(int))); connect(ui.cbPaOut, SIGNAL(currentIndexChanged(int)), this, SLOT(soundChanged(int))); connect(ui.cbPaBufferSize, SIGNAL(currentIndexChanged(int)), this, SLOT(soundChanged(int))); connect(ui.cbPaSampleRate, SIGNAL(currentIndexChanged(int)), this, SLOT(soundChanged(int))); connect(ui.cbPaChannels, SIGNAL(currentIndexChanged(int)), this, SLOT(soundChanged(int))); connect(ui.cbPaChannels, SIGNAL(currentIndexChanged(int)), this, SLOT(channelsChanged(int))); connect(ui.sbPaLattency, SIGNAL(valueChanged(int)), this, SLOT(soundChanged(int))); connect(ui.cbPaVacDriver, SIGNAL(currentIndexChanged(int)), this, SLOT(soundVacDrvChanged(int))); connect(ui.cbPaVacIn, SIGNAL(currentIndexChanged(int)), this, SLOT(soundVacChanged(int))); connect(ui.cbPaVacOut, SIGNAL(currentIndexChanged(int)), this, SLOT(soundVacChanged(int))); connect(ui.cbPaVacBufferSize, SIGNAL(currentIndexChanged(int)), this, SLOT(soundVacChanged(int))); connect(ui.cbPaVacSampleRate, SIGNAL(currentIndexChanged(int)), this, SLOT(soundVacChanged(int))); connect(ui.sbPaVacLattency, SIGNAL(valueChanged(int)), this, SLOT(soundVacChanged(int))); connect(ui.chbVacEnable, SIGNAL(stateChanged(int)), this, SLOT(soundChanged(int))); connect(ui.cbSdrType, SIGNAL(currentIndexChanged(int)), this, SLOT(OnSdrType(int))); connect(ui.cbSdrType, SIGNAL(currentIndexChanged(int)), this, SLOT(onSdrTypeChanged(int))); onEnableXvtrx(false); connect(ui.chbXvtrxEnable, SIGNAL(clicked(bool)), this, SLOT(onEnableXvtrx(bool))); connect(ui.pbWavePath, SIGNAL(clicked()), this, SLOT(openWaveDir())); connect(ui.pbLog, SIGNAL(clicked()), this, SLOT(viewLocationLogFile())); }
void MainWindow::SaveFile(const QString& file){ setStatusTip(UTF8("保存当前进度到:")+file); QFile fp(file); fp.open(QFile::ReadOnly); QTextStream CurrentFile(&fp); QString OData; QTextStream SaveingFile(&OData); SaveingFile.setCodec("UTF-8"); SaveingFile << StartIndent <<endl; SaveingFile <<endl; SaveingFile<< "[GLOBAL]" <<endl; SaveingFile<<"\tSCREENHEIGHT: "<<singleLine( CurrentSetting->property("screenheight").toString() )<<endl; SaveingFile<<"\tSCREENWIDTH: "<<singleLine( CurrentSetting->property("screenwidth").toString() )<<endl; SaveingFile<<"\tURL: "<<singleLine( CurrentSetting->property("url").toString() )<<endl; SaveingFile<<"\tTEMPLATE: "<<singleLine( CurrentSetting->property("template").toString() )<<endl; SaveingFile<<"\tNAMESPACE: "<<singleLine( CurrentSetting->property("namespace").toString() )<<endl; SaveingFile<<"\tBGSELECTOR: "<<singleLine( CurrentSetting->property("bgselector").toString() )<<endl; SaveingFile<<"\tGENERATEBGIMAGE: "<<singleLine( CurrentSetting->property("generatebgimage").toString() )<<endl; SaveingFile<<"\tLASTPNG: "<<singleLine( CurrentSetting->property("lastpng").toString() )<<endl; SaveingFile<<"[END]"<<endl; SaveingFile <<endl; SaveingFile << wm->SessionSave(); SaveingFile << endl << EndIndent <<endl; //读取文件中的其他部分 QString Line; bool switcher = false; while( !CurrentFile.atEnd() ){ Line = CurrentFile.readLine(); if( !switcher ){ //非 配置or导出 部分 if(Line.startsWith(StartIndent) || Line.startsWith(AutoGenIndent)){ switcher = true; continue; } SaveingFile<<Line<<endl; }else{ //配置or导出 部分 switcher = !(Line.startsWith(EndIndent) || Line.startsWith(AutoGenEndIndent)); } } fp.close(); if(!fp.open(QFile::WriteOnly)) throw AlertException(UTF8("保存失败"),UTF8("无法写入文件")); CurrentFile.reset(); CurrentFilePath = file; this->setWindowTitle(file+QString(" - cssSprites")); qDebug()<<"File Save"<<file; CurrentFile<<OData; fp.close(); QDir fsd; QString target = fsd.absoluteFilePath(CurrentFilePath); target += STUFF_FOLDER; if(fsd.currentPath() != target){ //转移文件 fsd.setPath(target); if( !fsd.exists() ){ if(! fsd.mkdir(target) ) throw AlertException(UTF8("保存错误"),("目标路径无法写入(请检查权限)\n")+target); } QStringList stuff = QDir::current().entryList(QDir::Files); QString fName; foreach(fName,stuff){ qWarning(QString("Copy File ================\n\t\tfrom %1(%2)\n\t\t to %3").arg(fName).arg(QDir::currentPath()).arg(target+fName).toStdString().data()); QFile::copy(fName,target+fName); }
void MythCDROM::onDeviceMounted() { if (!QDir(m_MountPath).exists()) { LOG(VB_GENERAL, LOG_ERR, QString("Mountpoint '%1' doesn't exist") .arg(m_MountPath)); m_MediaType = MEDIATYPE_UNKNOWN; m_Status = MEDIASTAT_ERROR; return; } QFileInfo audio = QFileInfo(m_MountPath + PATHTO_AUDIO_DETECT); QDir dvd = QDir(m_MountPath + PATHTO_DVD_DETECT); QDir svcd = QDir(m_MountPath + PATHTO_SVCD_DETECT); QDir vcd = QDir(m_MountPath + PATHTO_VCD_DETECT); QDir bad_dvd = QDir(m_MountPath + PATHTO_BAD_DVD_MOUNT); QDir bd = QDir(m_MountPath + PATHTO_BD_DETECT); // Default is data media m_MediaType = MEDIATYPE_DATA; // Default is mounted media m_Status = MEDIASTAT_MOUNTED; if (dvd.exists()) { LOG(VB_MEDIA, LOG_INFO, "Probable DVD detected."); m_MediaType = MEDIATYPE_DVD; m_Status = MEDIASTAT_USEABLE; } else if (bd.exists()) { LOG(VB_MEDIA, LOG_INFO, "Probable Blu-ray detected."); m_MediaType = MEDIATYPE_BD; m_Status = MEDIASTAT_USEABLE; } else if (audio.exists()) { LOG(VB_MEDIA, LOG_INFO, "Probable Audio CD detected."); m_MediaType = MEDIATYPE_AUDIO; m_Status = MEDIASTAT_USEABLE; } else if (vcd.exists() || svcd.exists()) { LOG(VB_MEDIA, LOG_INFO, "Probable VCD/SVCD detected."); m_MediaType = MEDIATYPE_VCD; m_Status = MEDIASTAT_USEABLE; } else if (bad_dvd.exists()) { LOG(VB_GENERAL, LOG_ERR, "DVD incorrectly mounted? (ISO9660 instead of UDF)"); } else { LOG(VB_GENERAL, LOG_ERR, QString("CD/DVD '%1' contained none of\n").arg(m_MountPath) + QString("\t\t\t%1, %2, %3 or %4").arg(PATHTO_DVD_DETECT) .arg(PATHTO_AUDIO_DETECT).arg(PATHTO_VCD_DETECT) .arg(PATHTO_SVCD_DETECT)); LOG(VB_GENERAL, LOG_INFO, "Searching CD statistically - file by file!"); } // If not DVD/AudioCD/VCD/SVCD, use parent's more generic version if (MEDIATYPE_DATA == m_MediaType) MythMediaDevice::onDeviceMounted(); // Unlock the door, and if appropriate unmount the media, // so the user can press the manual eject button if (m_AllowEject) { unlock(); if (m_MediaType == MEDIATYPE_DVD || m_MediaType == MEDIATYPE_VCD) unmount(); } }
void Advanced_Settings_Window::on_Button_OK_clicked() { // Execute Before Start QEMU Settings.setValue( "Run_Before_QEMU", ui.Edit_Before_Start_Command->text() ); // Execute After Stop QEMU Settings.setValue( "Run_After_QEMU", ui.Edit_After_Stop_Command->text() ); // Use Shared Folder For All Screenshots if( ui.CH_Screenshot_Folder->isChecked() ) { Settings.setValue( "Use_Screenshots_Folder", "yes" ); QDir dir; // For Check on valid // Screenshots Shared Folder Path if( dir.exists(ui.Edit_Screenshot_Folder->text()) ) { Settings.setValue( "Screenshot_Folder_Path", ui.Edit_Screenshot_Folder->text() ); } else { AQGraphic_Warning( tr("Invalid Value!"), tr("Shared screenshot folder doesn't exist!") ); return; } } else { Settings.setValue( "Use_Screenshots_Folder", "no" ); // Screenshots Shared Folder Path Settings.setValue( "Screenshot_Folder_Path", ui.Edit_Screenshot_Folder->text() ); } // Screenshot save format if( ui.RB_Format_PNG->isChecked() ) Settings.setValue( "Screenshot_Save_Format", "PNG" ); else if( ui.RB_Format_Jpeg->isChecked() ) Settings.setValue( "Screenshot_Save_Format", "JPEG" ); else Settings.setValue( "Screenshot_Save_Format", "PPM" ); // Jpeg Quality Settings.setValue( "Jpeg_Quality", QString::number(ui.HS_Jpeg_Quality->value()) ); // Additional CDROM int old_count = Settings.value( "Additional_CDROM_Devices/Count", "0" ).toString().toInt(); if( old_count > ui.CDROM_List->count() ) { // Delete Old Items for( int dx = ui.CDROM_List->count()-1; dx < old_count; dx++ ) { Settings.remove( "Additional_CDROM_Devices/Device" + QString::number(dx) ); } } Settings.setValue( "Additional_CDROM_Devices/Count", QString::number(ui.CDROM_List->count()) ); for( int ix = 0; ix < ui.CDROM_List->count(); ix++ ) { Settings.setValue( "Additional_CDROM_Devices/Device" + QString::number(ix), ui.CDROM_List->item(ix)->text() ); } Settings.setValue( "Info/Show_Tab_Info", ui.CH_Show_Tab_Info->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Show_QEMU_Args", ui.CH_Show_QEMU_Args->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Show_Screenshot_in_Save_Mode", ui.CH_Show_Screenshot_in_Save_Mode->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Machine_Details", ui.CH_Machine_Details->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Machine_Name", ui.CH_Machine_Name->isChecked() ? "no" : "no" ); Settings.setValue( "Info/Emulator_Type", ui.CH_Emulator_Type->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Emulator_Version", ui.CH_Emulator_Version->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Computer_Type", ui.CH_Computer_Type->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Machine_Type", ui.CH_Machine_Type->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Boot_Priority", ui.CH_Boot_Priority->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/CPU_Type", ui.CH_CPU_Type->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Number_of_CPU", ui.CH_Number_of_CPU->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Video_Card", ui.CH_Video_Card->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Keyboard_Layout", ui.CH_Keyboard_Layout->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Memory_Size", ui.CH_Memory_Size->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Use_Sound", ui.CH_Use_Sound->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Fullscreen", ui.CH_Fullscreen->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Snapshot", ui.CH_Snapshot->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Localtime", ui.CH_Localtime->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Show_FDD", ui.CH_Show_FDD->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Show_CD", ui.CH_Show_CD->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Show_HDD", ui.CH_Show_HDD->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Network_Cards", ui.CH_Network_Cards->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Redirections", ui.CH_Redirections->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Serial_Port", ui.CH_Serial_Port->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Parallel_Port", ui.CH_Parallel_Port->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/USB_Port", ui.CH_USB_Port->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Win2K_Hack", ui.CH_Win2K_Hack->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/RTC_TD_Hack", ui.CH_RTC_TD_Hack->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/No_Shutdown", ui.CH_No_Shutdown->isChecked()? "yes" : "no" ); Settings.setValue( "Info/No_Reboot", ui.CH_No_Reboot->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Start_CPU", ui.CH_Start_CPU->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Check_Boot_on_FDD", ui.CH_Check_Boot_on_FDD->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/ACPI", ui.CH_ACPI->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Start_Date", ui.CH_Start_Date->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/No_Frame", ui.CH_No_Frame->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Alt_Grab", ui.CH_Alt_Grab->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/No_Quit", ui.CH_No_Quit->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Portrait", ui.CH_Portrait->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Curses", ui.CH_Curses->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Show_Cursor", ui.CH_Show_Cursor->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Init_Graphical_Mode", ui.CH_Init_Graphical_Mode->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/ROM_File", ui.CH_ROM_File->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/MTDBlock", ui.CH_MTDBlock->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/SD_Image", ui.CH_SD_Image->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/PFlash", ui.CH_PFlash->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Linux_Boot", ui.CH_Linux_Boot->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/Acceleration", ui.CH_Acceleration->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/VNC", ui.CH_VNC->isChecked() ? "yes" : "no" ); Settings.setValue( "Info/SPICE", ui.CH_SPICE->isChecked() ? "yes" : "no" ); // MAC Address Generation Mode if( ui.RB_MAC_Random->isChecked() ) Settings.setValue( "MAC_Generation_Mode", "Random" ); else if( ui.RB_MAC_QEMU->isChecked() ) Settings.setValue( "MAC_Generation_Mode", "QEMU_Segment" ); else if( ui.RB_MAC_Valid->isChecked() ) Settings.setValue( "MAC_Generation_Mode", "Model" ); // Save to Log File if( ui.CH_Log_Save_in_File->isChecked() ) Settings.setValue( "Log/Save_In_File", "yes" ); else Settings.setValue( "Log/Save_In_File", "no" ); // Print In StdOut if( ui.CH_Log_Print_in_STDIO->isChecked() ) Settings.setValue( "Log/Print_In_STDOUT", "yes" ); else Settings.setValue( "Log/Print_In_STDOUT", "no" ); // Log File Path Settings.setValue( "Log/Log_Path", ui.Edit_Log_Path->text() ); // Save to AQEMU Log if( ui.CH_Log_Debug->isChecked() ) Settings.setValue( "Log/Save_Debug", "yes" ); else Settings.setValue( "Log/Save_Debug", "no" ); if( ui.CH_Log_Warning->isChecked() ) Settings.setValue( "Log/Save_Warning", "yes" ); else Settings.setValue( "Log/Save_Warning", "no" ); if( ui.CH_Log_Error->isChecked() ) Settings.setValue( "Log/Save_Error", "yes" ); else Settings.setValue( "Log/Save_Error", "no" ); // QEMU-IMG Path Settings.setValue( "QEMU-IMG_Path", ui.Edit_QEMU_IMG_Path->text() ); // QEMU_AUDIO if( ui.CH_Audio_Default->isChecked() ) Settings.setValue( "QEMU_AUDIO/Use_Default_Driver", "no" ); else Settings.setValue( "QEMU_AUDIO/Use_Default_Driver", "yes" ); // QEMU_AUDIO_DRV Settings.setValue( "QEMU_AUDIO/QEMU_AUDIO_DRV", ui.CB_Host_Sound_System->currentText() ); // Recent CD Count Settings.setValue( "CD_ROM_Exits_Images/Max", QString::number(ui.SB_Recent_CD_Count->value()) ); // Recent FDD Count Settings.setValue( "Floppy_Exits_Images/Max", QString::number(ui.SB_Recent_FDD_Count->value()) ); // First VNC Port for Embedded Display Settings.setValue( "First_VNC_Port", QString::number(ui.SB_First_VNC_Port->value()) ); // QEMU/KVM Monitor Type #ifdef Q_OS_WIN32 Settings.setValue( "Emulator_Monitor_Type", "tcp" ); #else Settings.setValue( "Emulator_Monitor_Type", ui.RB_Monitor_TCP->isChecked() ? "tcp" : "stdio" ); #endif Settings.setValue( "Emulator_Monitor_Hostname", ui.CB_Monitor_Hostname->currentText() ); Settings.setValue( "Emulator_Monitor_Port", ui.SB_Monitor_Port->value() ); // All OK? if( Settings.status() != QSettings::NoError ) AQError( "void Advanced_Settings_Window::on_Button_OK_clicked()", "QSettings Error!" ); if( Save_Emulators_Info() ) accept(); }
// 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; }
/** * Prepares the log file for writting */ void DSEventLogger::init() { if (!m_init) { /* Initialize the timer */ m_init = true; m_timer.restart(); /* Get app info */ QString appN = qApp->applicationName(); QString appV = qApp->applicationVersion(); QString ldsV = DriverStation::libDSVersion(); QString time = GET_DATE_TIME ("MMM dd yyyy - HH:mm:ss AP"); /* Get dump directoru */ QString path = QString ("%1/%2/%3/%4/") .arg (logsPath()) .arg (GET_DATE_TIME ("yyyy")) .arg (GET_DATE_TIME ("MMMM")) .arg (GET_DATE_TIME ("ddd dd")); /* Create logs directory (if necessesary) */ QDir dir (path); if (!dir.exists()) dir.mkpath ("."); /* Get dump file path */ m_currentLog = QString ("%1/%2.log") .arg (path) .arg (GET_DATE_TIME ("HH_mm_ss AP")); /* Open dump file */ m_dump = fopen (m_currentLog.toStdString().c_str(), "w"); m_dump = !m_dump ? stderr : m_dump; /* Get OS information */ QString sysV; #if QT_VERSION >= QT_VERSION_CHECK (5, 4, 0) sysV = QSysInfo::prettyProductName(); #else #if defined Q_OS_WIN sysV = "Windows"; #elif defined Q_OS_MAC sysV = "Mac OSX"; #elif defined Q_OS_LINUX sysV = "GNU/Linux"; #else sysV = "Unknown"; #endif #endif /* Format app info */ time.prepend ("Log created on: "); ldsV.prepend ("LibDS version: "); sysV.prepend ("Operating System: "); appN.prepend ("Application name: "); appV.prepend ("Application version: "); /* Append app info */ fprintf (m_dump, "%s\n", PRINT (time)); fprintf (m_dump, "%s\n", PRINT (ldsV)); fprintf (m_dump, "%s\n", PRINT (sysV)); fprintf (m_dump, "%s\n", PRINT (appN)); fprintf (m_dump, "%s\n\n", PRINT (appV)); /* Start the table header */ fprintf (m_dump, "%s\n", PRINT (REPEAT ("-", 72))); fprintf (m_dump, PRINT_FMT, "ELAPSED TIME", "ERROR LEVEL", "MESSAGE"); fprintf (m_dump, "%s\n", PRINT (REPEAT ("-", 72))); } }
int main(int argc, char *argv[]) { QDir clamDir; QFile dbFile, confFile; QApplication app(argc, argv); QTranslator myappTranslator; QString locale = QLocale::system().name(); QString defaultLanguage = QString(APP_NAME) + "_" + locale + ".qm"; // Falls die Sprache manuell gesetzt wurde. QSettings clamui_conf(QSettings::NativeFormat, QSettings::UserScope, APP_TITLE, APP_NAME); clamui_conf.beginGroup("ClamUI"); bool languageSet = clamui_conf.value("Language_Manually", false).toBool(); QString currLanguage = clamui_conf.value( "languageFileName", defaultLanguage).toString(); bool hideWindow =clamui_conf.value("Hide_Window", false).toBool(); clamui_conf.endGroup(); // Systemsprache aus der Umgebungsvariable des Systems lesen. // Read the system language from the system environment. QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&qtTranslator); if (languageSet == false) { // Langauge from system settings myappTranslator.load(LANG_PATH + APP_NAME + "_" + locale + ".qm"); app.installTranslator(&myappTranslator); } else { // Language manually. myappTranslator.load(LANG_PATH + currLanguage); app.installTranslator(&myappTranslator); } /* * Check if there is a ClamAV directory. * In this directory are the config files stored. */ if (!clamDir.exists(CLAMAV_PATH)) clamDir.mkdir(CLAMAV_PATH); /* * The default quarantine folder. */ if (!clamDir.exists(CLAMAV_PATH + "quarantine")) clamDir.mkdir(CLAMAV_PATH + "quarantine"); /* * The directory for the virus definition stored. */ if (!clamDir.exists(CLAMAV_VDB_PATH)) clamDir.mkdir(CLAMAV_VDB_PATH); /* * Check for an existing SQLite3 database. */ if (!dbFile.exists(APP_CONFIG_PATH + SQLITE_DB_NAME)){ SQLite_DB sqliteDB; sqliteDB.connectDB(); } /* * Check for an existing config file. * * If not run the wizard. */ if (!confFile.exists(APP_CONFIG_PATH + APP_NAME + ".conf")){ FirstRunWizard startWizard; startWizard.show(); return app.exec(); } /* * If exists run clamui. */ if (confFile.exists(APP_CONFIG_PATH + APP_NAME + ".conf")){ ClamUI startClamUI; if (hideWindow){ startClamUI.hide(); return app.exec(); } else { startClamUI.show(); return app.exec(); } } } // main end
bool MkPath::rmpath(const QDir &dir #ifdef ULTRACOPIER_PLUGIN_RSYNC ,const bool &toSync #endif ) { if(!dir.exists()) return true; bool allHaveWork=true; QFileInfoList list = dir.entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden|QDir::System,QDir::DirsFirst); for (int i = 0; i < list.size(); ++i) { QFileInfo fileInfo(list.at(i)); if(!fileInfo.isDir()) { #ifdef ULTRACOPIER_PLUGIN_RSYNC if(toSync) { QFile file(fileInfo.absoluteFilePath()); if(!file.remove()) { if(toSync) { QFile file(fileInfo.absoluteFilePath()); if(!file.remove()) { ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"unable to remove a file: "+fileInfo.absoluteFilePath()+", due to: "+file.errorString()); allHaveWork=false; } } else { ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"found a file: "+fileInfo.fileName()); allHaveWork=false; } } } else { ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"found a file: "+fileInfo.fileName()); allHaveWork=false; } #else ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"found a file: "+fileInfo.fileName()); allHaveWork=false; #endif } else { //return the fonction for scan the new folder if(!rmpath(dir.absolutePath()+'/'+fileInfo.fileName()+'/')) allHaveWork=false; } } if(!allHaveWork) return false; allHaveWork=dir.rmdir(dir.absolutePath()); if(!allHaveWork) ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"unable to remove the folder: "+dir.absolutePath()); return allHaveWork; }
// // By default will open last athlete, but will also provide // a dialog to select an athlete if not found, and then upgrade // the athlete one selected before opening a mainwindow // // It will also respawn mainwindows when restarting for changes // to application settings (athlete folder, language) // // Also creates singleton instances prior to application launching // int main(int argc, char *argv[]) { int ret=2; // return code from qapplication, default to error // // PROCESS COMMAND LINE SWITCHES // // snaffle arguments into a stringlist we can play with into sargs // and only keep non-switch args in the args string list QStringList sargs, args; for (int i=0; i<argc; i++) sargs << argv[i]; #ifdef GC_DEBUG bool debug = true; #else bool debug = false; #endif bool server = false; nogui = false; bool help = false; // honour command line switches foreach (QString arg, sargs) { // help or version requested if (arg == "--help" || arg == "--version") { help = true; fprintf(stderr, "GoldenCheetah %s (%d)\nusage: GoldenCheetah [[directory] athlete]\n\n", VERSION_STRING, VERSION_LATEST); fprintf(stderr, "--help or --version to print this message and exit\n"); #ifdef GC_WANT_HTTP fprintf(stderr, "--server to run as an API server\n"); #endif #ifdef GC_DEBUG fprintf(stderr, "--debug to turn on redirection of messages to goldencheetah.log [debug build]\n"); #else fprintf(stderr, "--debug to direct diagnostic messages to the terminal instead of goldencheetah.log\n"); #endif #ifdef GC_HAS_CLOUD_DB fprintf(stderr, "--clouddbcurator to add CloudDB curator specific functions to the menus\n"); #endif fprintf (stderr, "\nSpecify the folder and/or athlete to open on startup\n"); fprintf(stderr, "If no parameters are passed it will reopen the last athlete.\n\n"); } else if (arg == "--server") { #ifdef GC_WANT_HTTP nogui = server = true; #else fprintf(stderr, "HTTP support not compiled in, exiting.\n"); exit(1); #endif } else if (arg == "--debug") { #ifdef GC_DEBUG // debug, so don't redirect stderr! debug = false; #else debug = true; #endif } else if (arg == "--clouddbcurator") { #ifdef GC_HAS_CLOUD_DB CloudDBCommon::addCuratorFeatures = true; #else fprintf(stderr, "CloudDB support not compiled in, exiting.\n"); exit(1); #endif } else { // not switches ! args << arg; } } // help or version printed so just exit now if (help) { exit(0); } // // INITIALISE ONE TIME OBJECTS // #ifdef GC_WANT_HTTP listener = NULL; #endif #ifdef Q_OS_X11 XInitThreads(); #endif #ifdef Q_OS_MACX if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 ) { // fix Mac OS X 10.9 (mavericks) font issue // https://bugreports.qt-project.org/browse/QTBUG-32789 QFont::insertSubstitution("LucidaGrande", "Lucida Grande"); } #endif #ifdef GC_WANT_R // create the singleton in the main thread // will be shared by all athletes and all charts (!!) rtool = new RTool(argc,argv); #endif // create the application -- only ever ONE regardless of restarts application = new QApplication(argc, argv); //XXXIdleEventFilter idleFilter; //XXXapplication->installEventFilter(&idleFilter); #ifdef Q_OS_MAC // get an autorelease pool setup static CocoaInitializer cocoaInitializer; #endif // set default colors GCColor::setupColors(); appsettings->migrateQSettingsSystem(); // colors must be setup before migration can take place, but reading has to be from the migrated ones GCColor::readConfig(); // set defaultfont QFont font; font.fromString(appsettings->value(NULL, GC_FONT_DEFAULT, QFont().toString()).toString()); font.setPointSize(appsettings->value(NULL, GC_FONT_DEFAULT_SIZE, 10).toInt()); application->setFont(font); // set default font // // OPEN FIRST MAINWINDOW // do { // lets not restart endlessly restarting = false; //this is the path within the current directory where GC will look for //files to allow USB stick support QString localLibraryPath="Library/GoldenCheetah"; //this is the path that used to be used for all platforms //now different platforms will use their own path //this path is checked first to make things easier for long-time users QString oldLibraryPath=QDir::home().canonicalPath()+"/Library/GoldenCheetah"; //these are the new platform-dependent library paths #if defined(Q_OS_MACX) QString libraryPath="Library/GoldenCheetah"; #elif defined(Q_OS_WIN) #if QT_VERSION > 0x050000 // windows and qt5 QStringList paths=QStandardPaths::standardLocations(QStandardPaths::DataLocation); QString libraryPath = paths.at(0); #else // windows not qt5 QString libraryPath=QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/GoldenCheetah"; #endif // qt5 #else // not windows or osx (must be Linux or OpenBSD) // Q_OS_LINUX et al QString libraryPath=".goldencheetah"; #endif // // or did we override in settings? QString sh; if ((sh=appsettings->value(NULL, GC_HOMEDIR, "").toString()) != QString("")) localLibraryPath = sh; // lets try the local library we've worked out... QDir home = QDir(); if(QDir(localLibraryPath).exists() || home.exists(localLibraryPath)) { home.cd(localLibraryPath); } else { // YIKES !! The directory we should be using doesn't exist! home = QDir::home(); if (home.exists(oldLibraryPath)) { // there is an old style path, lets fo there home.cd(oldLibraryPath); } else { if (!home.exists(libraryPath)) { if (!home.mkpath(libraryPath)) { // tell user why we aborted ! QMessageBox::critical(NULL, "Exiting", QString("Cannot create library directory (%1)").arg(libraryPath)); exit(0); } } home.cd(libraryPath); } } // set global root directory gcroot = home.canonicalPath(); appsettings->initializeQSettingsGlobal(gcroot); // now redirect stderr #ifndef WIN32 if (!debug) nostderr(home.canonicalPath()); #else Q_UNUSED(debug) #endif // install QT Translator to enable QT Dialogs translation // we may have restarted JUST to get this! QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); application->installTranslator(&qtTranslator); // Language setting (default to system locale) QVariant lang = appsettings->value(NULL, GC_LANG, QLocale::system().name()); // Load specific translation, try from GCROOT otherwise from binary QTranslator gcTranslator; QString translation_file = "/gc_" + lang.toString() + ".qm"; if (gcTranslator.load(gcroot + translation_file)) qDebug() << "Loaded translation from"+gcroot+translation_file; else gcTranslator.load(":translations" + translation_file); application->installTranslator(&gcTranslator); // Initialize metrics once the translator is installed RideMetricFactory::instance().initialize(); // Initialize global registry once the translator is installed GcWindowRegistry::initialize(); // initialise the trainDB trainDB = new TrainDB(home); #ifdef GC_WANT_R (*(rtool->R))["GC.home"] = home.absolutePath().toStdString(); #endif // lets do what the command line says ... QVariant lastOpened; if(args.count() == 2) { // $ ./GoldenCheetah Mark -or- ./GoldenCheetah --server ~/athletedir // athlete if (!server) lastOpened = args.at(1); else home.cd(args.at(1)); } else if (args.count() == 3) { // $ ./GoldenCheetah ~/Athletes Mark // first parameter is a folder that exists? if (QFileInfo(args.at(1)).isDir()) { home.cd(args.at(1)); } // folder and athlete lastOpened = args.at(2); } else { // no parameters passed lets open the last athlete we worked with lastOpened = appsettings->value(NULL, GC_SETTINGS_LAST); // does lastopened Directory exists at all QDir lastOpenedDir(gcroot+"/"+lastOpened.toString()); if (lastOpenedDir.exists()) { // but hang on, did they crash? if so we need to open with a menu appsettings->initializeQSettingsAthlete(gcroot, lastOpened.toString()); if(appsettings->cvalue(lastOpened.toString(), GC_SAFEEXIT, true).toBool() != true) lastOpened = QVariant(); } else { lastOpened = QVariant(); } } #ifdef GC_WANT_HTTP // The API server offers webservices (default port 12021, see httpserver.ini) // This is to enable integration with R and similar if (appsettings->value(NULL, GC_START_HTTP, true).toBool() || server) { // notifications etc if (nogui) { qDebug()<<"Starting GoldenCheetah API web-services... (hit ^C to close)"; qDebug()<<"Athlete directory:"<<home.absolutePath(); } else { // switch off warnings if in gui mode #ifndef GC_WANT_ALLDEBUG #if QT_VERSION > 0x50000 qInstallMessageHandler(myMessageOutput); #else qInstallMsgHandler(myMessageOutput); #endif #endif } QString httpini = home.absolutePath() + "/httpserver.ini"; if (!QFile(httpini).exists()) { // read default ini file QFile file(":webservice/httpserver.ini"); QString content; if (file.open(QIODevice::ReadOnly)) { content = file.readAll(); file.close(); } // write default ini file QFile out(httpini); if (out.open(QIODevice::WriteOnly)) { out.resize(0); QTextStream stream(&out); stream << content; out.close(); } } // use the default handler (just get an error page) QSettings* settings=new QSettings(httpini,QSettings::IniFormat,application); if (listener) { // when changing the Athlete Directory, there is already a listener running // close first to avoid errors listener->close(); } listener=new HttpListener(settings,new APIWebService(home, application),application); // if not going on to launch a gui... if (nogui) { // catch ^C exit signal(SIGINT, sigabort); ret = application->exec(); // stop web server if running qDebug()<<"Stopping GoldenCheetah API web-services..."; listener->close(); // and done terminate(0); } } #endif // lets attempt to open as asked/remembered bool anyOpened = false; if (lastOpened != QVariant()) { QStringList list = lastOpened.toStringList(); QStringListIterator i(list); while (i.hasNext()) { QString cyclist = i.next(); QString homeDir = home.canonicalPath(); if (home.cd(cyclist)) { appsettings->initializeQSettingsAthlete(homeDir, cyclist); GcUpgrade v3; if (v3.upgradeConfirmedByUser(home)) { MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); mainWindow->ridesAutoImport(); gc_opened++; home.cdUp(); anyOpened = true; } else { delete trainDB; terminate(0); } } } } // ack, didn't manage to open an athlete // and the upgradeWarning was // lets ask the user which / create a new one if (!anyOpened) { ChooseCyclistDialog d(home, true); d.setModal(true); // choose cancel? if ((ret=d.exec()) != QDialog::Accepted) { delete trainDB; terminate(0); } // chosen, so lets get the choice.. QString homeDir = home.canonicalPath(); home.cd(d.choice()); if (!home.exists()) { delete trainDB; terminate(0); } appsettings->initializeQSettingsAthlete(homeDir, d.choice()); // .. and open a mainwindow GcUpgrade v3; if (v3.upgradeConfirmedByUser(home)) { MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); mainWindow->ridesAutoImport(); gc_opened++; } else { delete trainDB; terminate(0); } } ret=application->exec(); // close trainDB delete trainDB; // reset QSettings (global & Athlete) appsettings->clearGlobalAndAthletes(); #ifndef NOWEBKIT // clear web caches (stop warning of WebKit leaks) QWebSettings::clearMemoryCaches(); #endif } while (restarting); return ret; }
QByteArray TTSAcapela::CreateNewSound(QString text, QString voice, bool forceOverwrite) { QEventLoop loop; if(!voiceList.contains(voice)) voice = "claire"; // Check (and create if needed) output folder QDir outputFolder = ttsFolder; if(!outputFolder.exists(voice)) outputFolder.mkdir(voice); if(!outputFolder.cd(voice)) { LogError(QString("Cant create TTS Folder : %1").arg(ttsFolder.absoluteFilePath(voice))); return QByteArray(); } // Compute fileName QString fileName = QCryptographicHash::hash(text.toAscii(), QCryptographicHash::Md5).toHex().append(".mp3"); QString filePath = outputFolder.absoluteFilePath(fileName); if(!forceOverwrite && QFile::exists(filePath)) return ttsHTTPUrl.arg(voice, fileName).toAscii(); // Fetch MP3 QHttp http("vaas3.acapela-group.com"); QObject::connect(&http, SIGNAL(done(bool)), &loop, SLOT(quit())); QByteArray ContentData; ContentData += "client%5Ftext=" + QUrl::toPercentEncoding(text) + "&client%5Fvoice=" + voice + "22k&client%5Frequest%5Ftype=CREATE%5FREQUEST&client%5Fpassword=demo_web&client%5Flogin=asTTS&client%5Fversion=1%2D00&actionscript%5Fversion=3"; QHttpRequestHeader Header; Header.addValue("Host", "vaas3.acapela-group.com"); Header.addValue("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; fr; rv:1.9.0.1) Gecko/2008072820 Firefox/3.0.1"); Header.addValue("Referer", "http://www.acapela-group.com/Flash/Demo_Web_AS3/demo_web.swf?path=http://vaas3.acapela-group.com/connector/1-20/&lang=FR"); Header.addValue("Content-type", "application/x-www-form-urlencoded"); Header.addValue("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); Header.addValue("Accept-Language", "fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3"); Header.addValue("Accept-Encoding", "gzip,deflate"); Header.addValue("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); Header.addValue("Keep-Alive", "300"); Header.addValue("Connection", "keep-alive"); Header.setContentLength(ContentData.length()); Header.setRequest("POST", "/connector/1-20/textToMP3.php", 1, 1); http.request(Header, ContentData); loop.exec(); QByteArray reponse = http.readAll(); QUrl url("?"+reponse); if(url.hasQueryItem("retour_php")) { //LogDebug(QString("Acapela answer : %1").arg(QString(reponse))); QString acapelaFile = url.queryItemValue("retour_php"); //LogInfo(QString("Downloading MP3 file : %1").arg(QString(acapelaFile))); http.get(acapelaFile); loop.exec(); QFile file(filePath); if (!file.open(QIODevice::WriteOnly)) { LogError("Cannot open sound file for writing"); return QByteArray(); } file.write(http.readAll()); file.close(); return ttsHTTPUrl.arg(voice, fileName).toAscii(); } LogError("Acapela demo did not return a sound file"); LogDebug(QString("Acapela answer : %1").arg(QString(reponse))); return QByteArray(); }
QString Brewtarget::getConfigDir(bool *success) { #if defined(Q_OS_LINUX) || defined(Q_OS_MAC) // Linux OS or Mac OS. QDir dir; QFileInfo fileInfo; char* xdg_config_home = getenv("XDG_CONFIG_HOME"); bool tmp; QFile::Permissions sevenFiveFive = QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner | QFile::ReadGroup | QFile::ExeGroup | QFile::ReadOther | QFile::ExeOther; // First, try XDG_CONFIG_HOME. // If that variable doesn't exist, create ~/.config if (xdg_config_home) { dir = xdg_config_home; } else { // Creating config directory. dir = QDir::home(); if( !dir.exists(".config") ) { logW( QString("Config dir \"%1\" did not exist...").arg(dir.absolutePath() + "/.config") ); tmp = dir.mkdir(".config"); logW( QString( tmp ? "...created it." : "...could not create it.") ); if( !tmp ) { // Failure. if( success != 0 ) *success = false; return ""; } // chmod 755 ~/.config QFile::setPermissions( dir.absolutePath() + "/.config", sevenFiveFive ); } // CD to config directory. if( ! dir.cd(".config") ) { logE( QString("Could not CD to \"%1\".").arg(dir.absolutePath() + "/.config") ); if( success != 0 ) *success = false; return ""; } } // See if brewtarget dir exists. if( !dir.exists("brewtarget") ) { logW( QString("\"%1\" does not exist...creating.").arg(dir.absolutePath() + "/brewtarget") ); // Try to make brewtarget dir. if( ! dir.mkdir("brewtarget") ) { logE( QString("Could not create \"%1\"").arg(dir.absolutePath() + "/brewtarget") ); if( success != 0 ) *success = false; return ""; } // chmod 755 ~/.config/brewtarget QFile::setPermissions( dir.absolutePath() + "/brewtarget", sevenFiveFive ); } if( ! dir.cd("brewtarget") ) { logE(QString("Could not CD into \"%1\"").arg(dir.absolutePath() + "/brewtarget")); if( success != 0 ) *success = false; return ""; } if( success != 0 ) *success = true; return dir.absolutePath() + "/"; #elif defined(Q_OS_WIN) // Windows OS. QDir dir; // This is the bin/ directory. dir = QDir(qApp->applicationDirPath()); dir.cdUp(); // Now we should be in the base directory (i.e. Brewtarget-2.0.0/) dir.cd("data"); if( success != 0 ) *success = true; return dir.absolutePath() + "/"; #else # error "Unsupported OS" #endif }
QMplayer::QMplayer(QWidget *parent, Qt::WFlags f) : QWidget(parent) { #ifdef QTOPIA this->setWindowState(Qt::WindowMaximized); softm = QSoftMenuBar::menuFor(this); rmMpAction = softm->addAction(tr("Remove mplayer"), this, SLOT(removeMplayer())); rmDlAction = softm->addAction(tr("Remove youtube-dl"), this, SLOT(removeYoutubeDl())); rmFlvAction = softm->addAction(tr("Remove FLV videos"), this, SLOT(removeFlv())); #else Q_UNUSED(f); #endif lw = new QListWidget(this); int h = lw->fontMetrics().height(); lw->setIconSize(QSize(h, h)); scanItem = new QListWidgetItem(tr("Scan"), lw); scanItem->setSelected(true); sharingItem = new QListWidgetItem(tr("Sharing"), lw); encodingItem = new QListWidgetItem(lw); bOk = new QPushButton(this); connect(bOk, SIGNAL(clicked()), this, SLOT(okClicked())); bBack = new QPushButton(this); connect(bBack, SIGNAL(clicked()), this, SLOT(backClicked())); bUp = new QPushButton(this); connect(bUp, SIGNAL(clicked()), this, SLOT(upClicked())); bDown = new QPushButton(this); connect(bDown, SIGNAL(clicked()), this, SLOT(downClicked())); label = new QLabel(this); lineEdit = new QLineEdit(this); progress = new QProgressBar(this); buttonLayout = new QHBoxLayout(); buttonLayout->setAlignment(Qt::AlignBottom); buttonLayout->addWidget(bOk); buttonLayout->addWidget(bBack); buttonLayout->addWidget(bUp); buttonLayout->addWidget(bDown); layout = new QVBoxLayout(this); layout->addWidget(lw); layout->addWidget(label); layout->addWidget(lineEdit); layout->addWidget(progress); layout->addLayout(buttonLayout); maxScanLevel = 0; delTmpFiles = -1; useBluetooth = -1; process = NULL; tcpServer = NULL; ubasedir = QDir::homePath(); QString basedir1 = QDir::homePath()+"/Documents"; QString basedir2 = "/media/card/Documents"; QDir dirch; if (dirch.exists(basedir1)) ubasedir = basedir1; if (dirch.exists(basedir2)) ubasedir = basedir2; tube = false; QStringList cl_args = QCoreApplication::arguments(); int ac = cl_args.count(); if (ac>1) { int tki=1; while(true) { QString a = cl_args[tki]; if (a=="--mpargs") { if (ac>tki+1) { mpargs << QString(cl_args[tki+1]).split(" "); } else { console("Not enough parameters for '--mpargs' argument"); } tki+=2; } else if (a=="--basedir") { if (ac>tki+1) { ubasedir = cl_args[tki+1]; } else { console("Not enough parameters for '--basedir' argument"); } tki+=2; } else if (a=="--youtube-dl") { tube=true; tki+=1; } else { mplist << a; tki+=1; } if (tki>=ac) break; } } mpgui = (mplist.count()==0); if (mpgui) showScreen(QMplayer::ScreenInit); else { if (tube) { while (mplist.count() > 1) mplist.removeLast(); QTimer::singleShot(0, this, SLOT(sTimerEvent())); } else { this->screen = QMplayer::ScreenInit; okClicked(); } } }
void HTMLChatTheme::readTheme(QDir dir) { qDebug() << "reading theme from filesystem" << dir; isValid_ = false; if (!dir.cd("Contents/Resources/")) { //invalid dir return; //isValid == false; } setBaseHref(dir.path() + "/"); incomingNextMessageTemplate.setContent(readFileContents(dir, "Incoming/Content.html")); if (dir.exists("Incoming/NextContent.html")) { incomingConsecutiveMessageTemplate.setContent(readFileContents(dir, "Incoming/NextContent.html")); } else { incomingConsecutiveMessageTemplate.setContent(incomingNextMessageTemplate.content()); } // outgoing messages if (dir.exists("Outgoing/NextContent.html")) { outgoingConsecutiveMessageTemplate.setContent(readFileContents(dir, "Outgoing/NextContent.html")); } else { outgoingConsecutiveMessageTemplate.setContent(incomingConsecutiveMessageTemplate.content()); } if (dir.exists("Outgoing/Content.html")) { outgoingNextMessageTemplate.setContent(readFileContents(dir, "Outgoing/Content.html")); } else { outgoingNextMessageTemplate.setContent(incomingNextMessageTemplate.content()); } noOutgoingDir = !dir.exists("Outgoing/buddy_icon.png"); //some themes have empty Outgoing dir //we will be using Incoming avatar // status/event template fileTransferEventTemplate.setContent(readFileContents(dir, "Status.html")); systemEventTemplate = HTMLChatTemplate(fileTransferEventTemplate); moodEventTemplate = HTMLChatTemplate(fileTransferEventTemplate); tuneEventTemplate = HTMLChatTemplate(fileTransferEventTemplate); // action if (dir.exists("Incoming/Action.html")) { incomingEmoteEventTemplate.setContent(readFileContents(dir, "Incoming/Action.html")); incomingEmoteEventTemplate.setEmoteTemplate(true); } else { incomingEmoteEventTemplate.setContent(fileTransferEventTemplate.content()); } if (dir.exists("Outgoing/Action.html")) { outgoingEmoteEventTemplate.setContent(readFileContents(dir, "Outgoing/Action.html")); incomingEmoteEventTemplate.setEmoteTemplate(true); } else { outgoingEmoteEventTemplate.setContent(fileTransferEventTemplate.content()); } headerTemplate_.setContent(readFileContents(dir, "Header.html")); footerTemplate_.setContent(readFileContents(dir, "Footer.html")); isValid_ = true; //read Variants variants_.clear(); if (!dir.cd("Variants/")) { qDebug() << "no Variants dir"; return; //no variants } QStringList filters; filters << "*.css"; QStringList variantFiles = dir.entryList(filters); QString variant; foreach(variant, variantFiles) { variants_.append(variant.left(variant.size() - 4)); }
bool DbPlugin::createNewCC (DBIndex *i) { FuturesData fd; QStringList l; fd.getSymbolList(l); QString pl = QObject::tr("Parms"); QString fsl = QObject::tr("Futures Symbol"); QString gl = QObject::tr("Gapless"); PrefDialog *dialog = new PrefDialog(0); dialog->setCaption(QObject::tr("New CC")); dialog->createPage (pl); dialog->setHelpFile(helpFile); dialog->addComboItem(fsl, pl, l, 0); dialog->addCheckItem(gl, pl, TRUE); int rc = dialog->exec(); if (rc != QDialog::Accepted) { delete dialog; return TRUE; } QString sym; dialog->getCombo(fsl, sym); bool f = dialog->getCheck(gl); delete dialog; QDir dir; Config config; QString s; config.getData(Config::DataPath, s); s.append("/CC"); if (! dir.exists(s)) { if (! dir.mkdir(s, TRUE)) { QMessageBox::information(0, QObject::tr("Qtstalker: Error"), QObject::tr("Could not create ~/.qtstalker/data/CC directory.")); return TRUE; } } DBIndexItem item; QString ts; chartIndex->getIndexItem(sym, item); item.getSymbol(ts); if (ts.length()) { qDebug("DbPlugin::createNewStock: duplicate symbol %s", ts.latin1()); return TRUE; } s.append("/" + sym); if (open(s, i)) { QMessageBox::information(0, QObject::tr("Qtstalker: Error"), QObject::tr("Disk error, cannot create chart")); return TRUE; } type = CC1; item.setSymbol(sym); s = "CC"; item.setType(s); s = sym + " - " + QObject::tr("Continuous Adjusted"); item.setTitle(s); chartIndex->setIndexItem(indexKey, item); s = QString::number(f); sym = "Adjustment"; setData(sym, s); return FALSE; }
QString UBImportCFF::expandFileToDir(const QFile& pZipFile, const QString& pDir) { QuaZip zip(pZipFile.fileName()); if(!zip.open(QuaZip::mdUnzip)) { qWarning() << "Import failed. Cause zip.open(): " << zip.getZipError(); return ""; } zip.setFileNameCodec("UTF-8"); QuaZipFileInfo info; QuaZipFile file(&zip); //create unique cff document root fodler //use current date/time and temp number for folder name QString documentRootFolder; int tmpNumber = 0; QDir rootDir; while (true) { QString tempPath = QString("%1/sank%2.%3") .arg(pDir) .arg(QDateTime::currentDateTime().toString("dd_MM_yyyy_HH-mm")) .arg(tmpNumber); if (!rootDir.exists(tempPath)) { documentRootFolder = tempPath; break; } tmpNumber++; if (tmpNumber == 100000) { qWarning() << "Import failed. Failed to create temporary directory for iwb file"; return ""; } } if (!rootDir.mkdir(documentRootFolder)) { qWarning() << "Import failed. Couse: failed to create temp folder for cff package"; } QFile out; char c; for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) { if(!zip.getCurrentFileInfo(&info)) { //TOD UB 4.3 O display error to user or use crash reporter qWarning() << "Import failed. Cause: getCurrentFileInfo(): " << zip.getZipError(); return ""; } // if(!file.open(QIODevice::ReadOnly)) { // qWarning() << "Import failed. Cause: file.open(): " << zip.getZipError(); // return ""; // } file.open(QIODevice::ReadOnly); if(file.getZipError()!= UNZ_OK) { qWarning() << "Import failed. Cause: file.getFileName(): " << zip.getZipError(); return ""; } QString newFileName = documentRootFolder + "/" + file.getActualFileName(); QFileInfo newFileInfo(newFileName); rootDir.mkpath(newFileInfo.absolutePath()); out.setFileName(newFileName); out.open(QIODevice::WriteOnly); while(file.getChar(&c)) out.putChar(c); out.close(); if(file.getZipError()!=UNZ_OK) { qWarning() << "Import failed. Cause: " << zip.getZipError(); return ""; } if(!file.atEnd()) { qWarning() << "Import failed. Cause: read all but not EOF"; return ""; } file.close(); if(file.getZipError()!=UNZ_OK) { qWarning() << "Import failed. Cause: file.close(): " << file.getZipError(); return ""; } } zip.close(); if(zip.getZipError()!=UNZ_OK) { qWarning() << "Import failed. Cause: zip.close(): " << zip.getZipError(); return ""; } return documentRootFolder; }
//Init settings void initSettings() { //open file #ifdef Q_OS_WIN QSettings settings("HKEY_CURRENT_USER\\Software\\moonplayer", QSettings::NativeFormat); #else QDir dir = QDir::home(); if (!dir.cd(".moonplayer")) { dir.mkdir(".moonplayer"); dir.cd(".moonplayer"); } if (!dir.exists("plugins")) dir.mkdir("plugins"); if (!dir.exists("skins")) dir.mkdir("skins"); QSettings settings(QDir::homePath() + "/.config/moonplayer.ini", QSettings::IniFormat); #endif //read settings #ifdef Q_OS_WIN if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA) vout = settings.value("Video/out", "direct3d").toString(); else vout = settings.value("Video/out", "directx").toString(); #else vout = settings.value("Video/out", "xv").toString(); path = "/usr/share/moonplayer"; #endif framedrop = settings.value("Video/framedrop", true).toBool(); doubleBuffer = settings.value("Video/double", true).toBool(); fixLastFrame = settings.value("Video/fixlastframe", false).toBool(); ffodivxvdpau = settings.value("Video/ffodivxvdpau", true).toBool(); aout = settings.value("Audio/out", "auto").toString(); softvol = settings.value("Audio/softvol", false).toBool(); volume = settings.value("Audio/volume", 10).toInt(); currentSkin = settings.value("Player/current_skin", 0).toInt(); autoResize = settings.value("Player/auto_resize", true).toBool(); enableScreenshot = settings.value("Player/screenshot", true).toBool(); rememberUnfinished = settings.value("Player/remember_unfinished", true).toBool(); proxy = settings.value("Net/proxy").toString(); port = settings.value("Net/port").toInt(); cacheSize = settings.value("Net/cache_size", 4096).toInt(); cacheMin = settings.value("Net/cache_min", 50).toInt(); maxTasks = settings.value("Net/max_tasks", 3).toInt(); downloadDir = settings.value("Net/download_dir", QDir::homePath()).toString(); quality = (Quality) settings.value("Plugins/quality", (int) SUPER).toInt(); autoCombine = settings.value("Plugins/auto_combine", false).toBool(); autoCloseWindow = settings.value("Plugins/auto_close_window", true).toBool(); danmakuAlpha = settings.value("Danmaku/alpha", 0.9).toDouble(); danmakuFont = settings.value("Danmaku/font", "").toString(); danmakuSize = settings.value("Danmaku/size", 0).toInt(); durationScrolling = settings.value("Danmaku/dm", 0).toInt(); durationStill = settings.value("Danmaku/ds", 6).toInt(); //init proxy if (proxy.isEmpty()) access_manager->setProxy(QNetworkProxy(QNetworkProxy::NoProxy)); else access_manager->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, proxy, port)); //init skins QDir skinDir(path); skinDir.cd("skins"); skinList = skinDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name); #ifdef Q_OS_LINUX dir.cd("skins"); skinList.append(dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name)); #endif if (currentSkin >= skinList.size()) currentSkin = 0; }
// Private slot to take care of processing a WMS tile delivered over the network. void WMSRequester::processTile(QNetworkReply* reply) { // Check HTTP status code QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); // Check redirection target QVariant redirectionTargetUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); // see CS001432 on how to handle this --m_dispatchedRequestCount; // no error received? if (reply->error() == QNetworkReply::NoError) { bool fromCache = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); QImageReader imageReader(reply); QImage image = imageReader.read(); if (image.isNull()) { qDebug() << "Received bad image: " << reply->header(QNetworkRequest::LocationHeader); } else { QMutexLocker locker(&m_mutex); TileBuildOperation op = m_requestedTiles.take(reply); TileAssembly* tileAssembly = op.tile; if (tileAssembly) { bool firstOp = false; if (tileAssembly->tileImage.isNull()) { tileAssembly->tileImage = QImage(tileAssembly->tileWidth, tileAssembly->tileHeight, QImage::Format_RGB888); firstOp = true; } QPainter painter(&tileAssembly->tileImage); // Clear the background to white before the first operation if (firstOp) { painter.fillRect(QRectF(0.0f, 0.0f, tileAssembly->tileImage.width(), tileAssembly->tileImage.height()), Qt::white); } painter.setRenderHints(QPainter::SmoothPixmapTransform, true); // A hack to work around some drawing problems that left occasional gaps // in tiles. There's either a bug in Qt's painter class, or some trouble // with roundoff errors. Increasing the rectangle size very slightly // eliminates the gaps. QRectF r(op.subrect); r.setSize(QSizeF(r.width() * 1.0001f, r.height() * 1.0001f)); painter.drawImage(r, image); painter.end(); tileAssembly->requestCount--; if (tileAssembly->requestCount == 0) { QString imageName = tileFileName(tileAssembly->tileName, tileAssembly->surfaceName); QFileInfo fileInfo(imageName); QDir tileDir = fileInfo.dir(); if (!tileDir.exists()) { tileDir.mkpath(tileDir.absolutePath()); } bool ok = tileAssembly->tileImage.save(imageName); if (!ok) { qDebug() << "Failed writing to " << imageName; } emit imageCompleted(tileAssembly->tileName, tileAssembly->tileImage.rgbSwapped()); delete tileAssembly; } } } } else { qDebug() << "Network error: " << reply->errorString(); } reply->deleteLater(); // If there are queued tiled requests and not too many active WMS server connections, // then make some more network requests. Prioritize requests for textures tiles that // are currently visible. while (m_dispatchedRequestCount < MaxOutstandingNetworkRequests) { int tileIndex = -1; vesta::v_uint64 mostRecent = 0; TileBuildOperation op; { QMutexLocker locker(&m_mutex); // Request a WMS tile for the most recently used texture tile for (int i = 0; i < m_queuedTiles.size(); ++i) { if (m_queuedTiles[i].tile->texture->lastUsed() > mostRecent) { tileIndex = i; mostRecent = m_queuedTiles[i].tile->texture->lastUsed(); } } if (tileIndex >= 0) { op = m_queuedTiles.takeAt(tileIndex); // Trim the queue by removing requests for tiles that haven't been visible // for a while. This will happen when the user moves the camera quickly over // the surface of a planet. We want to load tiles for the location that the // user is looking at now, not the places that they zoomed past quickly on // the way there. // // Tiles that haven't been accessed in the last cullLag frames are remove const unsigned int cullLag = 60; if (mostRecent >= cullLag) { vesta::v_uint64 cullBefore = mostRecent - cullLag; for (int i = m_queuedTiles.size() - 1; i >= 0; --i) { if (m_queuedTiles[i].tile->texture->lastUsed() < cullBefore) { // Set status to unitialized so that loading will be retried if the tile // comes into view later. m_queuedTiles[i].tile->texture->setStatus(vesta::TextureMap::Uninitialized); m_queuedTiles.removeAt(i); } } } } } if (tileIndex >= 0) { requestTile(op); } else { break; } } }
QStringList KStandardDirs::resourceDirs(const char *type) const { QStringList *candidates = dircache.find(type); if (!candidates) { // filling cache if (strcmp(type, "socket") == 0) const_cast<KStandardDirs *>(this)->createSpecialResource(type); else if (strcmp(type, "tmp") == 0) const_cast<KStandardDirs *>(this)->createSpecialResource(type); else if (strcmp(type, "cache") == 0) const_cast<KStandardDirs *>(this)->createSpecialResource(type); QDir testdir; candidates = new QStringList(); QStringList *dirs; bool restrictionActive = false; if (d && d->restrictionsActive) { if (d->dataRestrictionActive) restrictionActive = true; else if (d->restrictions["all"]) restrictionActive = true; else if (d->restrictions[type]) restrictionActive = true; d->dataRestrictionActive = false; // Reset } dirs = relatives.find(type); if (dirs) { bool local = true; const QStringList *prefixList = 0; if (strncmp(type, "xdgdata-", 8) == 0) prefixList = &(d->xdgdata_prefixes); else if (strncmp(type, "xdgconf-", 8) == 0) prefixList = &(d->xdgconf_prefixes); else prefixList = &prefixes; for (QStringList::ConstIterator pit = prefixList->begin(); pit != prefixList->end(); ++pit) { for (QStringList::ConstIterator it = dirs->begin(); it != dirs->end(); ++it) { QString path = realPath(*pit + *it); testdir.setPath(path); if (local && restrictionActive) continue; if ((local || testdir.exists()) && !candidates->contains(path)) candidates->append(path); } local = false; } } dirs = absolutes.find(type); if (dirs) for (QStringList::ConstIterator it = dirs->begin(); it != dirs->end(); ++it) { testdir.setPath(*it); if (testdir.exists()) { QString filename = realPath(*it); if (!candidates->contains(filename)) candidates->append(filename); } } dircache.insert(type, candidates); } #if 0 kdDebug() << "found dirs for resource " << type << ":" << endl; for (QStringList::ConstIterator pit = candidates->begin(); pit != candidates->end(); pit++) { fprintf(stderr, "%s\n", (*pit).latin1()); } #endif return *candidates; }
void AppDownloader::appJsonFetched() { QNetworkReply *reply = static_cast<QNetworkReply*>(sender()); reply->deleteLater(); if (reply->error() != QNetworkReply::NoError) { qWarning() << "Error fetching App Json" << reply->errorString(); return; } QJsonParseError error; QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &error); if (error.error != QJsonParseError::NoError) { qWarning() << "Error parsing App Json" << error.errorString(); return; } QVariantMap map = jsonDoc.toVariant().toMap(); if (!map.contains("data") || map.value("data").toList().length() == 0) { qWarning() << "Unexpected json content:" << jsonDoc.toJson(); return; } QVariantMap appMap = map.value("data").toList().first().toMap(); QString pbwFileUrl = appMap.value("latest_release").toMap().value("pbw_file").toString(); if (pbwFileUrl.isEmpty()) { qWarning() << "pbw file url empty." << jsonDoc.toJson(); return; } QString appid = appMap.value("id").toString(); QUuid quuid = appMap.value("uuid").toUuid(); QDir dir; Pebble *p = (Pebble *)parent(); if(p->installedAppIds().contains(quuid)) { AppInfo ai = p->appInfo(quuid); QString exId = ai.storeId(); if(appid != exId && !dir.exists(m_storagePath+appid) && dir.exists(m_storagePath+exId)) { dir.rename(m_storagePath+exId,m_storagePath+appid); } else if(appid != exId) { qWarning() << "App exists but dir is out of sync:" << exId << "<!>" << appid; } } else { dir.mkpath(m_storagePath + appid); } QString iconFile = appMap.value("list_image").toMap().value("144x144").toString(); QNetworkRequest request(iconFile); QNetworkReply *imageReply = m_nam->get(request); qDebug() << "fetching image" << iconFile; connect(imageReply, &QNetworkReply::finished, [this, imageReply, appid]() { imageReply->deleteLater(); QString targetFile = m_storagePath + appid + "/list_image.png"; qDebug() << "saving image to" << targetFile; QFile f(targetFile); if (f.open(QFile::WriteOnly)) { f.write(imageReply->readAll()); f.close(); } }); appid += ("/v" + appMap.value("latest_release").toMap().value("version").toString() + ".pbw"); fetchPackage(pbwFileUrl, appid); }
int main(int argc, char *argv[]) { // apply default settings QucsSettings.x = 60; QucsSettings.y = 30; QucsSettings.dx = 640; QucsSettings.dy = 400; QucsSettings.font = QFont("Helvetica", 12); // is application relocated? char * var = getenv ("QUCSDIR"); if (var != NULL) { QDir QucsDir = QDir (var); QString QucsDirStr = QucsDir.canonicalPath (); QucsSettings.DocDir = QDir::convertSeparators (QucsDirStr + "/share/qucs/docs/"); QucsSettings.BitmapDir = QDir::convertSeparators (QucsDirStr + "/share/qucs/bitmaps/"); QucsSettings.LangDir = QDir::convertSeparators (QucsDirStr + "/share/qucs/lang/"); } else { QucsSettings.DocDir = DOCDIR; QucsSettings.BitmapDir = BITMAPDIR; QucsSettings.LangDir = LANGUAGEDIR; } loadSettings(); QApplication a(argc, argv); a.setFont(QucsSettings.font); QTranslator tor( 0 ); QString locale = QucsSettings.Language; if(locale.isEmpty()) locale = QTextCodec::locale(); tor.load( QString("qucs_") + locale, QucsSettings.LangDir); a.installTranslator( &tor ); QucsHelpDir = QucsSettings.DocDir + locale; if (!QucsHelpDir.exists () || !QucsHelpDir.isReadable ()) { int p = locale.find ('_'); if (p != -1) { QucsHelpDir = QucsSettings.DocDir + locale.left (p); if (!QucsHelpDir.exists () || !QucsHelpDir.isReadable ()) { QucsHelpDir = QucsSettings.DocDir + "en"; } } else QucsHelpDir = QucsSettings.DocDir + "en"; } QString Page; if(argc > 1) Page = argv[1]; QucsHelp *qucs = new QucsHelp(Page); a.setMainWidget(qucs); qucs->resize(QucsSettings.dx, QucsSettings.dy); // size and position ... qucs->move(QucsSettings.x, QucsSettings.y); // ... before "show" !!! qucs->show(); int result = a.exec(); saveApplSettings(qucs); return result; }
void UniformValue::updateUniformVariableValuesFromDialog(int rowIdx, int colIdx, QVariant newValue) { switch (type) { case INT: ivalue = newValue.toInt(); break; case FLOAT: fvalue = newValue.toDouble(); break; case BOOL: bvalue = newValue.toBool() != 0; break; case VEC2: case VEC3: case VEC4: vec4[colIdx] = newValue.toDouble(); break; case IVEC2: case IVEC3: case IVEC4: ivec4[colIdx] = newValue.toInt(); break; case BVEC2: case BVEC3: case BVEC4: bvec4[colIdx] = newValue.toBool() != 0; break; case MAT2: mat2[rowIdx][colIdx] = newValue.toDouble(); break; case MAT3: mat3[rowIdx][colIdx] = newValue.toDouble(); break; case MAT4: mat4[rowIdx][colIdx] = newValue.toDouble(); break; case SAMPLER1D: case SAMPLER2D: case SAMPLER3D: case SAMPLERCUBE: case SAMPLER1DSHADOW: case SAMPLER2DSHADOW: { QString newPath; // * choose the filename with a dialog (55 by convention) if (rowIdx == 5 && colIdx == 5) { QFileDialog fd(0, "Choose new texture"); QDir texturesDir = QDir(qApp->applicationDirPath()); #if defined(Q_OS_WIN) if (texturesDir.dirName() == "debug" || texturesDir.dirName() == "release") texturesDir.cdUp(); #elif defined(Q_OS_MAC) if (texturesDir.dirName() == "MacOS") { for (int i = 0; i < 4; ++i) { texturesDir.cdUp(); if (texturesDir.exists("textures")) break; } } #endif texturesDir.cd("textures"); fd.setDirectory(texturesDir); fd.move(500, 100); if (fd.exec()) { QStringList sels = fd.selectedFiles(); newPath = sels[0]; } } else newPath = newValue.toString(); // Load the new texture from given file if(textureLoaded) glDeleteTextures(1, &textureId); QImage img, imgScaled, imgGL; QFileInfo finfo(newPath); if(!finfo.exists()) { qDebug() << "Texture" << name << "in" << newPath << ": file do not exists"; } else if (!img.load(newPath)) { QMessageBox::critical(0, "Meshlab", newPath + ": Unsupported texture format"); } glEnable(GL_TEXTURE_2D); // image has to be scaled to a 2^n size. We choose the first 2^N <= picture size. int bestW = pow(2.0, floor(::log(double(img.width())) / ::log(2.0))); int bestH = pow(2.0, floor(::log(double(img.height())) / ::log(2.0))); if (!img.isNull()) imgScaled = img.scaled(bestW, bestH, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); imgGL = QGLWidget::convertToGLFormat(imgScaled); glGenTextures(1, &textureId); glBindTexture(GL_TEXTURE_2D, textureId); glTexImage2D(GL_TEXTURE_2D, 0, 3, imgGL.width(), imgGL.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, imgGL.bits()); textureLoaded = true; break; } case OTHER: assert(0); } }
bool CommandCrossSection::process(ccCommandLineInterface &cmd) { cmd.print("[CROSS SECTION]"); static QString s_xmlCloudCompare = "CloudCompare"; static QString s_xmlBoxThickness = "BoxThickness"; static QString s_xmlBoxCenter = "BoxCenter"; static QString s_xmlRepeatDim = "RepeatDim"; static QString s_xmlRepeatGap = "RepeatGap"; static QString s_xmlFilePath = "FilePath"; static QString s_outputXmlFilePath = "OutputFilePath"; //expected argument: XML file if (cmd.arguments().empty()) return cmd.error(QString("Missing parameter: XML parameters file after \"-%1\"").arg(COMMAND_CROSS_SECTION)); QString xmlFilename = cmd.arguments().takeFirst(); //read the XML file CCVector3 boxCenter(0, 0, 0), boxThickness(0, 0, 0); bool repeatDim[3] = { false, false, false }; double repeatGap = 0.0; bool inside = true; bool autoCenter = true; QString inputFilePath; QString outputFilePath; { QFile file(xmlFilename); if (!file.open(QFile::ReadOnly | QFile::Text)) { return cmd.error(QString("Couldn't open XML file '%1'").arg(xmlFilename)); } //read file content QXmlStreamReader stream(&file); //expected: CloudCompare if (!stream.readNextStartElement() || stream.name() != s_xmlCloudCompare) { return cmd.error(QString("Invalid XML file (should start by '<%1>')").arg(s_xmlCloudCompare)); } unsigned mandatoryCount = 0; while (stream.readNextStartElement()) //loop over the elements { if (stream.name() == s_xmlBoxThickness) { QXmlStreamAttributes attributes = stream.attributes(); if (!readVector(attributes, boxThickness, s_xmlBoxThickness, cmd)) return false; stream.skipCurrentElement(); ++mandatoryCount; } else if (stream.name() == s_xmlBoxCenter) { QXmlStreamAttributes attributes = stream.attributes(); if (!readVector(attributes, boxCenter, s_xmlBoxCenter, cmd)) return false; stream.skipCurrentElement(); autoCenter = false; } else if (stream.name() == s_xmlRepeatDim) { QString itemValue = stream.readElementText(); bool ok = false; int dim = itemValue.toInt(&ok); if (!ok || dim < 0 || dim > 2) { return cmd.error(QString("Invalid XML file (invalid value for '<%1>')").arg(s_xmlRepeatDim)); } repeatDim[dim] = true; } else if (stream.name() == s_xmlRepeatGap) { QString itemValue = stream.readElementText(); bool ok = false; repeatGap = itemValue.toDouble(&ok); if (!ok) { return cmd.error(QString("Invalid XML file (invalid value for '<%1>')").arg(s_xmlRepeatGap)); } } else if (stream.name() == s_xmlFilePath) { inputFilePath = stream.readElementText(); if (!QDir(inputFilePath).exists()) { return cmd.error(QString("Invalid file path (directory pointed by '<%1>' doesn't exist)").arg(s_xmlFilePath)); } //++mandatoryCount; } else if (stream.name() == s_outputXmlFilePath) { outputFilePath = stream.readElementText(); if (!QDir(outputFilePath).exists()) { return cmd.error(QString("Invalid output file path (directory pointed by '<%1>' doesn't exist)").arg(s_outputXmlFilePath)); } //++mandatoryCount; } else { cmd.warning(QString("Unknown element: %1").arg(stream.name().toString())); stream.skipCurrentElement(); } } if (mandatoryCount < 1 || (!repeatDim[0] && !repeatDim[1] && !repeatDim[2])) { return cmd.error(QString("Some mandatory elements are missing in the XML file (see documentation)")); } } //safety checks if ( boxThickness.x < ZERO_TOLERANCE || boxThickness.y < ZERO_TOLERANCE || boxThickness.z < ZERO_TOLERANCE ) { return cmd.error(QString("Invalid box thickness")); } CCVector3 repeatStep = boxThickness + CCVector3(repeatGap, repeatGap, repeatGap); if ( (repeatDim[0] && repeatStep.x < ZERO_TOLERANCE) || (repeatDim[1] && repeatStep.y < ZERO_TOLERANCE) || (repeatDim[2] && repeatStep.z < ZERO_TOLERANCE) ) { return cmd.error(QString("Repeat gap can't be equal or smaller than 'minus' box width")); } if (outputFilePath.isEmpty()) { outputFilePath = inputFilePath; } int iterationCount = 1; //shall we load the entities? QStringList files; QDir dir; bool fromFiles = false; if (!inputFilePath.isEmpty()) { //look for all files in the input directory dir = QDir(inputFilePath); assert(dir.exists()); files = dir.entryList(QDir::Files); iterationCount = files.size(); fromFiles = true; //remove any cloud or mesh in memory! cmd.removeClouds(); cmd.removeMeshes(); } for (int f = 0; f < iterationCount; ++f) { //shall we load files? QString filename; if (fromFiles) { assert(f < files.size()); filename = dir.absoluteFilePath(files[f]); QFileInfo fileinfo(filename); if (!fileinfo.isFile() || fileinfo.suffix().toUpper() == "XML") { continue; } //let's try to load the file cmd.print(QString("Processing file: '%1'").arg(files[f])); bool result = false; { //hack: replace the current argument list by a fake 'load file' sequence QStringList realArguments = cmd.arguments(); QStringList loadArguments; loadArguments << filename; cmd.arguments() = loadArguments; result = CommandLoad().process(cmd); //end of hack: restore the current argument list cmd.arguments() = realArguments; } if (!result) { cmd.warning("\tFailed to load file!"); continue; } } else { assert(iterationCount == 1); } //repeat crop process on each file (or do it only once on the currently loaded entities) { ccHObject::Container entities; try { for (size_t i = 0; i < cmd.clouds().size(); ++i) entities.push_back(cmd.clouds()[i].pc); for (size_t j = 0; j < cmd.meshes().size(); ++j) entities.push_back(cmd.meshes()[j].mesh); } catch (const std::bad_alloc&) { return cmd.error("Not enough memory!"); } for (size_t i = 0; i < entities.size(); ++i) { //check entity bounding-box ccHObject* ent = entities[i]; ccBBox bbox = ent->getOwnBB(); if (!bbox.isValid()) { cmd.warning(QString("Entity '%1' has an invalid bounding-box!").arg(ent->getName())); continue; } //browse to/create a subdirectory with the (base) filename as name QString basename; if (fromFiles) { basename = QFileInfo(filename).baseName(); } else { basename = i < cmd.clouds().size() ? cmd.clouds()[i].basename : cmd.meshes()[i - cmd.clouds().size()].basename; } if (entities.size() > 1) basename += QString("_%1").arg(i + 1); QDir outputDir(outputFilePath); if (outputFilePath.isEmpty()) { if (fromFiles) { assert(false); outputDir = QDir::current(); } else { outputDir = QDir(i < cmd.clouds().size() ? cmd.clouds()[i].path : cmd.meshes()[i - cmd.clouds().size()].path); } } assert(outputDir.exists()); if (outputDir.cd(basename)) { //if the directory already exists... cmd.warning(QString("Subdirectory '%1' already exists").arg(basename)); } else if (outputDir.mkdir(basename)) { outputDir.cd(basename); } else { cmd.warning(QString("Failed to create subdirectory '%1' (check access rights and base name validity!)").arg(basename)); continue; } int toto = ceil(-0.4); int toto2 = ceil(-0.6); //place the initial box at the beginning of the entity bounding box CCVector3 C0 = autoCenter ? bbox.getCenter() : boxCenter; unsigned steps[3] = { 1, 1, 1 }; for (unsigned d = 0; d < 3; ++d) { if (repeatDim[d]) { PointCoordinateType boxHalfWidth = boxThickness.u[d] / 2; PointCoordinateType distToMinBorder = C0.u[d] - boxHalfWidth - bbox.minCorner().u[d]; int stepsToMinBorder = static_cast<int>(ceil(distToMinBorder / repeatStep.u[d])); C0.u[d] -= stepsToMinBorder * repeatStep.u[d]; PointCoordinateType distToMaxBorder = bbox.maxCorner().u[d] - C0.u[d] - boxHalfWidth; int stepsToMaxBoder = static_cast<int>(ceil(distToMaxBorder / repeatStep.u[d]) + 1); assert(stepsToMaxBoder >= 0); steps[d] = std::max<unsigned>(stepsToMaxBoder, 1); } } cmd.print(QString("Will extract up to (%1 x %2 x %3) = %4 sections").arg(steps[0]).arg(steps[1]).arg(steps[2]).arg(steps[0] * steps[1] * steps[2])); //now extract the slices for (unsigned dx = 0; dx < steps[0]; ++dx) { for (unsigned dy = 0; dy < steps[1]; ++dy) { for (unsigned dz = 0; dz < steps[2]; ++dz) { CCVector3 C = C0 + CCVector3(dx*repeatStep.x, dy*repeatStep.y, dz*repeatStep.z); ccBBox cropBox(C - boxThickness / 2, C + boxThickness / 2); cmd.print(QString("Box (%1;%2;%3) --> (%4;%5;%6)") .arg(cropBox.minCorner().x).arg(cropBox.minCorner().y).arg(cropBox.minCorner().z) .arg(cropBox.maxCorner().x).arg(cropBox.maxCorner().y).arg(cropBox.maxCorner().z) ); ccHObject* croppedEnt = ccCropTool::Crop(ent, cropBox, inside); if (croppedEnt) { QString outputBasename = basename + QString("_%1_%2_%3").arg(C.x).arg(C.y).arg(C.z); QString errorStr; //original entity is a cloud? if (i < cmd.clouds().size()) { CLCloudDesc desc(static_cast<ccPointCloud*>(croppedEnt), outputBasename, outputDir.absolutePath(), entities.size() > 1 ? static_cast<int>(i) : -1); errorStr = cmd.exportEntity(desc); } else //otherwise it's a mesh { CLMeshDesc desc(static_cast<ccMesh*>(croppedEnt), outputBasename, outputDir.absolutePath(), entities.size() > 1 ? static_cast<int>(i) : -1); errorStr = cmd.exportEntity(desc); } delete croppedEnt; croppedEnt = 0; if (!errorStr.isEmpty()) return cmd.error(errorStr); } } } } } if (fromFiles) { //unload entities cmd.removeClouds(); cmd.removeMeshes(); } } } return true; }
bool PureImageCache::PutImageToCache(const QByteArray &tile, const MapType::Types &type,const Point &pos,const int &zoom) { #ifdef DEBUG_PUREIMAGECACHE qDebug()<<"PutImageToCache Start:";//<<pos; #endif //DEBUG_PUREIMAGECACHE bool ret=true; QDir d; QString dir=gtilecache; Mcounter.lock(); qlonglong id=++ConnCounter; Mcounter.unlock(); #ifdef DEBUG_PUREIMAGECACHE qDebug()<<"PutImageToCache Cache dir="<<dir; qDebug()<<"PutImageToCache Cache dir="<<dir<<" Try to PUT:"<<pos.ToString(); #endif //DEBUG_PUREIMAGECACHE if(!d.exists(dir)) { d.mkdir(dir); #ifdef DEBUG_PUREIMAGECACHE qDebug()<<"Create Cache directory"; #endif //DEBUG_PUREIMAGECACHE } { QString db=dir+"Data.qmdb"; if(!QFileInfo(db).exists()) { #ifdef DEBUG_PUREIMAGECACHE qDebug()<<"Try to create EmptyDB"; #endif //DEBUG_PUREIMAGECACHE ret=CreateEmptyDB(db); } if(ret) { QSqlDatabase cn; cn = QSqlDatabase::addDatabase("QSQLITE",QString::number(id)); cn.setDatabaseName(db); if(cn.open()) { { QSqlQuery query(cn); query.prepare("INSERT INTO Tiles(X, Y, Zoom, Type,Date) VALUES(?, ?, ?, ?,?)"); query.addBindValue(pos.X()); query.addBindValue(pos.Y()); query.addBindValue(zoom); query.addBindValue((int)type); query.addBindValue(QDateTime::currentDateTime().toString()); query.exec(); } { QSqlQuery query(cn); query.prepare("INSERT INTO TilesData(id, Tile) VALUES((SELECT last_insert_rowid()), ?)"); query.addBindValue(tile); query.exec(); } cn.close(); } else return false; } else { #ifdef DEBUG_PUREIMAGECACHE qDebug()<<"PutImageToCache Could not create DB"; #endif //DEBUG_PUREIMAGECACHE return false; } } QSqlDatabase::removeDatabase(QString::number(id)); return true; }
int main(int argc, char *argv[]) { int ret=2; // return code from qapplication, default to error // // PROCESS COMMAND LINE SWITCHES // // snaffle arguments into a stringlist we can play with into sargs // and only keep non-switch args in the args string list QStringList sargs, args; for (int i=0; i<argc; i++) sargs << argv[i]; #ifdef GC_DEBUG bool debug = true; #else bool debug = false; #endif bool help = false; // honour command line switches foreach (QString arg, sargs) { // help or version requested if (arg == "--help" || arg == "--version") { help = true; fprintf(stderr, "GoldenCheetah %s (%d)\nusage: GoldenCheetah [[directory] athlete]\n\n", VERSION_STRING, VERSION_LATEST); fprintf(stderr, "--help or --version to print this message and exit\n"); #ifdef GC_DEBUG fprintf(stderr, "--debug to turn on redirection of messages to goldencheetah.log [debug build]\n"); #else fprintf(stderr, "--debug to direct diagnostic messages to the terminal instead of goldencheetah.log\n"); #endif fprintf (stderr, "\nSpecify the folder and/or athlete to open on startup\n"); fprintf(stderr, "If no parameters are passed it will reopen the last athlete.\n\n"); } else if (arg == "--debug") { #ifdef GC_DEBUG // debug, so don't redirect stderr! debug = false; #else debug = true; #endif } else { // not switches ! args << arg; } } // help or version printed so just exit now if (help) { exit(0); } // // INITIALISE ONE TIME OBJECTS // #ifdef Q_OS_X11 XInitThreads(); #endif #ifdef Q_OS_MACX if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 ) { // fix Mac OS X 10.9 (mavericks) font issue // https://bugreports.qt-project.org/browse/QTBUG-32789 QFont::insertSubstitution("LucidaGrande", "Lucida Grande"); } #endif // create the application -- only ever ONE regardless of restarts application = new QApplication(argc, argv); #ifdef Q_OS_MAC // get an autorelease pool setup static CocoaInitializer cocoaInitializer; #endif // set defaultfont QFont font; font.fromString(appsettings->value(NULL, GC_FONT_DEFAULT, QFont().toString()).toString()); font.setPointSize(appsettings->value(NULL, GC_FONT_DEFAULT_SIZE, 12).toInt()); application->setFont(font); // set default font // // OPEN FIRST MAINWINDOW // do { // lets not restart endlessly restarting = false; //this is the path within the current directory where GC will look for //files to allow USB stick support QString localLibraryPath="Library/GoldenCheetah"; //this is the path that used to be used for all platforms //now different platforms will use their own path //this path is checked first to make things easier for long-time users QString oldLibraryPath=QDir::home().path()+"/Library/GoldenCheetah"; //these are the new platform-dependent library paths #if defined(Q_OS_MACX) QString libraryPath="Library/GoldenCheetah"; #elif defined(Q_OS_WIN) #if QT_VERSION > 0x050000 // windows and qt5 QStringList paths=QStandardPaths::standardLocations(QStandardPaths::DataLocation); QString libraryPath = paths.at(0) + "/GoldenCheetah"; #else // windows not qt5 QString libraryPath=QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/GoldenCheetah"; #endif // qt5 #else // not windows or osx (must be Linux or OpenBSD) // Q_OS_LINUX et al QString libraryPath=".goldencheetah"; #endif // // or did we override in settings? QString sh; if ((sh=appsettings->value(NULL, GC_HOMEDIR).toString()) != "") localLibraryPath = sh; // lets try the local library we've worked out... QDir home = QDir(); if(home.exists(localLibraryPath)) { home.cd(localLibraryPath); } else { // YIKES !! The directory we should be using doesn't exist! home = QDir::home(); if (home.exists(oldLibraryPath)) { // there is an old style path, lets fo there home.cd(oldLibraryPath); } else { if (!home.exists(libraryPath)) { if (!home.mkpath(libraryPath)) { qDebug()<<"Failed to create library path\n"; exit(0); } } home.cd(libraryPath); } } // set global root directory gcroot = home.absolutePath(); // now redirect stderr #ifndef WIN32 if (!debug) nostderr(home.absolutePath()); #endif // install QT Translator to enable QT Dialogs translation // we may have restarted JUST to get this! QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); application->installTranslator(&qtTranslator); // Language setting (default to system locale) QVariant lang = appsettings->value(NULL, GC_LANG, QLocale::system().name()); // Load specific translation QTranslator gcTranslator; gcTranslator.load(":translations/gc_" + lang.toString() + ".qm"); application->installTranslator(&gcTranslator); // Initialize metrics once the translator is installed RideMetricFactory::instance().initialize(); // Initialize global registry once the translator is installed GcWindowRegistry::initialize(); // initialise the trainDB trainDB = new TrainDB(home); // lets do what the command line says ... QVariant lastOpened; if(args.count() == 2) { // $ ./GoldenCheetah Mark // athlete lastOpened = args.at(1); } else if (args.count() == 3) { // $ ./GoldenCheetah ~/Athletes Mark // first parameter is a folder that exists? if (QFileInfo(args.at(1)).isDir()) { home.cd(args.at(1)); } // folder and athlete lastOpened = args.at(2); } else { // no parameters passed lets open the last athlete we worked with lastOpened = appsettings->value(NULL, GC_SETTINGS_LAST); // but hang on, did they crash? if so we need to open with a menu if(appsettings->cvalue(lastOpened.toString(), GC_SAFEEXIT, true).toBool() != true) lastOpened = QVariant(); } // lets attempt to open as asked/remembered bool anyOpened = false; if (lastOpened != QVariant()) { QStringList list = lastOpened.toStringList(); QStringListIterator i(list); while (i.hasNext()) { QString cyclist = i.next(); if (home.cd(cyclist)) { MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); home.cdUp(); anyOpened = true; } } } // ack, didn't manage to open an athlete // lets ask the user which / create a new one if (!anyOpened) { ChooseCyclistDialog d(home, true); d.setModal(true); // choose cancel? if ((ret=d.exec()) != QDialog::Accepted) { delete trainDB; return ret; } // chosen, so lets get the choice.. home.cd(d.choice()); if (!home.exists()) { delete trainDB; exit(0); } // .. and open a mainwindow MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); } ret=application->exec(); // close trainDB delete trainDB; } while (restarting); return ret; }
void FileOps::copy(QList<PlayListTrack *> tracks, const QString &dest, MetaDataFormatter *formatter) { QProgressDialog progress(qApp->activeWindow ()); progress.setWindowModality(Qt::WindowModal); progress.setWindowTitle(tr("Copying")); progress.setCancelButtonText(tr("Stop")); progress.show(); progress.setAutoClose (false); int i = 0; foreach(PlayListTrack *track, tracks) { if (!QFile::exists(track->url())) continue; QString fileName = formatter->format(track); //generate file name QString ext = QString(".") + track->url().section(".", -1).toLower(); if (!ext.isEmpty() && !fileName.endsWith(ext, Qt::CaseInsensitive)) fileName += ext; //append extension //create destination path QString path = dest + "/" + fileName; QDir dir = QFileInfo(path).dir(); if(!dir.exists()) { if(!dir.mkpath(dir.absolutePath())) { qWarning("FileOps: unable to create directory"); continue; } } if(track->url() == path) continue; //copy file QFile in(track->url()); QFile out(path); if (!in.open(QIODevice::ReadOnly)) { qWarning("FileOps: %s", qPrintable(in.errorString ())); continue; } if (!out.open(QIODevice::WriteOnly)) { qWarning("FileOps: %s", qPrintable(out.errorString ())); continue; } progress.setMaximum(int(in.size()/COPY_BLOCK_SIZE)); progress.setValue(0); progress.setLabelText (QString(tr("Copying file %1/%2")).arg(++i).arg(tracks.size())); progress.update(); while (!in.atEnd ()) { out.write(in.read(COPY_BLOCK_SIZE)); progress.setValue(int(out.size()/COPY_BLOCK_SIZE)); qApp->processEvents(); } if(progress.wasCanceled ()) break; } progress.close(); }
void PrefixControlWidget::prefixImport_Click(){ /* Function for importing preefix from file */ if (!prefixTable->currentIndex().isValid()) return; if(prefixTable->currentIndex().row()<0) return; QString prefixName = model->index(prefixTable->currentIndex().row(), 0, QModelIndex()).data().toString(); QString targetDir = model->index(prefixTable->currentIndex().row(), 2, QModelIndex()).data().toString(); if (prefixName.isEmpty()) return; if (targetDir.isEmpty()){ targetDir.append(QDir::homePath()); targetDir.append("/.wine/"); } QString openpath = QDir::homePath(); openpath.append("/.config/"); openpath.append(APP_SHORT_NAME); openpath.append("/prefixes/"); #if QT_VERSION >= 0x040500 QFileDialog::Options options; if (CoreLib->getSetting("advanced", "useNativeFileDialog", false, 1)==0) options = QFileDialog::DontUseNativeDialog; QString fileName = QFileDialog::getOpenFileName(this, tr("Select file to import"), openpath , tr("Prefix archive images (*.tbz)"), 0, options); #else QString fileName = QFileDialog::getOpenFileName(this, tr("Select file to import"), openpath , tr("Prefix archive images (*.tbz)")); #endif if (!fileName.isEmpty()){ QDir dir; if (dir.exists(targetDir)){ if(QMessageBox::warning(this, tr("Warning"), tr("Do you really wish to delete all old prefix files?"), QMessageBox::Ok, QMessageBox::Cancel)==QMessageBox::Ok){ QStringList args; args << "-rdf"; args << targetDir; Process exportProcess(args, CoreLib->getWhichOut("rm"), QDir::homePath(), tr("Removing old fake drive.<br>This can take a while..."), tr("Removing old fake drive")); if (exportProcess.exec()!=QDialog::Accepted){ return; } } else { return; } } dir.mkdir(targetDir); QStringList args; args << "-xjf"; args << fileName; args << "-C" << targetDir; //Creating process dialog Process exportProcess(args, CoreLib->getSetting("system", "tar").toString(), QDir::homePath(), tr("Importing prefix.<br>This can take a while..."), tr("Importing prefix")); exportProcess.exec(); } return; }
bool DbPlugin::createNewSpread (DBIndex *i) { bool ok = FALSE; QString sn = QInputDialog::getText(QObject::tr("New Spread"), QObject::tr("Enter symbol name for the new Spread"), QLineEdit::Normal, QString::null, &ok, 0); if (! sn.length() || ok == FALSE) return TRUE; QDir dir; Config config; QString s; config.getData(Config::DataPath, s); s.append("/Spread"); if (! dir.exists(s)) { if (! dir.mkdir(s, TRUE)) { QMessageBox::information(0, QObject::tr("Qtstalker: Error"), QObject::tr("Could not create Spread directory.")); return TRUE; } } s.append("/" + sn); if (dir.exists(s)) { QMessageBox::information(0, QObject::tr("Qtstalker: Error"), QObject::tr("This Spread already exists.")); return TRUE; } DBIndexItem item; QString ts; chartIndex->getIndexItem(sn, item); item.getSymbol(ts); if (ts.length()) { qDebug("DbPlugin::createNewStock: duplicate symbol %s", sn.latin1()); return TRUE; } if (open(s, i)) { QMessageBox::information(0, QObject::tr("Qtstalker: Error"), QObject::tr("Disk error, cannot create chart")); return TRUE; } type = Spread1; item.setSymbol(indexKey); s = "Spread"; item.setType(s); item.setTitle(indexKey); chartIndex->setIndexItem(indexKey, item); spreadPref(); return FALSE; }
/*! constructs command line of htags(1) and executes it. * \retval TRUE success * \retval FALSE an error has occurred. */ bool Htags::execute(const QCString &htmldir) { static QStrList &inputSource = Config_getList("INPUT"); static bool quiet = Config_getBool("QUIET"); static bool warnings = Config_getBool("WARNINGS"); static QCString htagsOptions = ""; //Config_getString("HTAGS_OPTIONS"); static QCString projectName = Config_getString("PROJECT_NAME"); static QCString projectNumber = Config_getString("PROJECT_NUMBER"); QCString cwd = QDir::currentDirPath().utf8(); if (inputSource.isEmpty()) { g_inputDir.setPath(cwd); } else if (inputSource.count()==1) { g_inputDir.setPath(inputSource.first()); if (!g_inputDir.exists()) err("Cannot find directory %s. " "Check the value of the INPUT tag in the configuration file.\n", inputSource.first() ); } else { err("If you use USE_HTAGS then INPUT should specific a single directory. \n"); return FALSE; } /* * Construct command line for htags(1). */ QCString commandLine = " -g -s -a -n "; if (!quiet) commandLine += "-v "; if (warnings) commandLine += "-w "; if (!htagsOptions.isEmpty()) { commandLine += ' '; commandLine += htagsOptions; } if (!projectName.isEmpty()) { commandLine += "-t \""; commandLine += projectName; if (!projectNumber.isEmpty()) { commandLine += '-'; commandLine += projectNumber; } commandLine += "\" "; } commandLine += " \"" + htmldir + "\""; QCString oldDir = QDir::currentDirPath().utf8(); QDir::setCurrent(g_inputDir.absPath()); //printf("CommandLine=[%s]\n",commandLine.data()); portable_sysTimerStart(); bool result=portable_system("htags",commandLine,FALSE)==0; portable_sysTimerStop(); QDir::setCurrent(oldDir); return result; }
void readSimulationParameters() { const QString predefDir=QDir::homePath()+FILE_SEP+"fet-results"; QSettings newSettings(COMPANY, PROGRAM); if(newSettings.contains("output-directory")){ OUTPUT_DIR=newSettings.value("output-directory").toString(); QDir dir; if(!dir.exists(OUTPUT_DIR)){ bool t=dir.mkpath(OUTPUT_DIR); if(!t){ /* QMessageBox::warning(NULL, FetTranslate::tr("FET warning"), FetTranslate::tr("Output directory %1 does not exist and cannot be" " created - output directory will be made the default value %2") .arg(QDir::toNativeSeparators(OUTPUT_DIR)).arg(QDir::toNativeSeparators(predefDir))); OUTPUT_DIR=predefDir; */ } } } else{ OUTPUT_DIR=predefDir; } FET_LANGUAGE=newSettings.value("language", "en_US").toString(); if(FET_LANGUAGE=="en_GB") //because older versions of FET used en_GB as the default language. I changed it to en_US FET_LANGUAGE="en_US"; WORKING_DIRECTORY=newSettings.value("working-directory", "examples").toString(); IMPORT_DIRECTORY=newSettings.value("import-directory", OUTPUT_DIR).toString(); QDir d(WORKING_DIRECTORY); if(!d.exists()) WORKING_DIRECTORY="examples"; QDir d2(WORKING_DIRECTORY); if(!d2.exists()) WORKING_DIRECTORY=QDir::homePath(); else WORKING_DIRECTORY=d2.absolutePath(); QDir i(IMPORT_DIRECTORY); if(!i.exists()) IMPORT_DIRECTORY=OUTPUT_DIR; checkForUpdates=newSettings.value("check-for-updates", "false").toBool(); QString ver=newSettings.value("version", "-1").toString(); TIMETABLE_HTML_LEVEL=newSettings.value("html-level", "2").toInt(); PRINT_ACTIVITIES_WITH_SAME_STARTING_TIME=newSettings.value("print-activities-with-same-starting-time", "false").toBool(); PRINT_NOT_AVAILABLE_TIME_SLOTS=newSettings.value("print-not-available", "true").toBool(); PRINT_BREAK_TIME_SLOTS=newSettings.value("print-break", "true").toBool(); DIVIDE_HTML_TIMETABLES_WITH_TIME_AXIS_BY_DAYS=newSettings.value("divide-html-timetables-with-time-axis-by-days", "false").toBool(); USE_GUI_COLORS=newSettings.value("use-gui-colors", "false").toBool(); /////////confirmations CONFIRM_ACTIVITY_PLANNING=newSettings.value("confirm-activity-planning", "true").toBool(); CONFIRM_SPREAD_ACTIVITIES=newSettings.value("confirm-spread-activities", "true").toBool(); CONFIRM_REMOVE_REDUNDANT=newSettings.value("confirm-remove-redundant", "true").toBool(); CONFIRM_SAVE_TIMETABLE=newSettings.value("confirm-save-data-and-timetable", "true").toBool(); ///////// ENABLE_ACTIVITY_TAG_MAX_HOURS_DAILY=newSettings.value("enable-activity-tag-max-hours-daily", "false").toBool(); ENABLE_STUDENTS_MAX_GAPS_PER_DAY=newSettings.value("enable-students-max-gaps-per-day", "false").toBool(); SHOW_WARNING_FOR_NOT_PERFECT_CONSTRAINTS=newSettings.value("warn-if-using-not-perfect-constraints", "true").toBool(); ENABLE_STUDENTS_MIN_HOURS_DAILY_WITH_ALLOW_EMPTY_DAYS=newSettings.value("enable-students-min-hours-daily-with-allow-empty-days", "false").toBool(); SHOW_WARNING_FOR_STUDENTS_MIN_HOURS_DAILY_WITH_ALLOW_EMPTY_DAYS=newSettings.value("warn-if-using-students-min-hours-daily-with-allow-empty-days", "true").toBool(); //main form QRect rect=newSettings.value("FetMainForm/geometry", QRect(0,0,0,0)).toRect(); mainFormSettingsRect=rect; MAIN_FORM_SHORTCUTS_TAB_POSITION=newSettings.value("FetMainForm/shortcuts-tab-position", "0").toInt(); SHOW_SHORTCUTS_ON_MAIN_WINDOW=newSettings.value("FetMainForm/show-shortcuts", "true").toBool(); cout<<"Settings read"<<endl; }