void Advanced_Settings_Window::done(int r) { if ( r == QDialog::Accepted ) { // 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() ? "yes" : "no" ); Settings.setValue( "Info/Machine_Accelerator", ui.CH_Machine_Accelerator->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/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() ); // First VNC Port for Embedded Display Settings.setValue( "First_VNC_Port", QString::number(ui.SB_First_VNC_Port->value()) ); // QEMU 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() ); // USB if( ui.RB_USB_Style_device->isChecked() ) Settings.setValue( "USB_Style", "device" ); else Settings.setValue( "USB_Style", "usbdevice" ); if( ui.RB_USB_ID_BusAddr->isChecked() ) Settings.setValue( "USB_ID_Style", "BusAddr" ); else if( ui.RB_USB_ID_BusPath->isChecked() ) Settings.setValue( "USB_ID_Style", "BusPath" ); else if( ui.RB_USB_ID_VendorProduct->isChecked() ) Settings.setValue( "USB_ID_Style", "VendorProduct" ); // All OK? if( Settings.status() != QSettings::NoError ) AQError( "void Advanced_Settings_Window::done(int)", "QSettings Error!" ); QDir dir; // For Check on valid Settings.setValue( "Default_VM_Template", ui.CB_Default_VM_Template->currentText() ); ui.Edit_VM_Folder->setText( QDir::toNativeSeparators(ui.Edit_VM_Folder->text()) ); // VM Folder if( ! (ui.Edit_VM_Folder->text().endsWith("/") || ui.Edit_VM_Folder->text().endsWith("\\")) ) ui.Edit_VM_Folder->setText( ui.Edit_VM_Folder->text() + QDir::toNativeSeparators("/") ); if( dir.exists(ui.Edit_VM_Folder->text()) ) { if( ! dir.exists(ui.Edit_VM_Folder->text() + QDir::toNativeSeparators("/os_templates/")) ) dir.mkdir( ui.Edit_VM_Folder->text() + QDir::toNativeSeparators("/os_templates/") ); Settings.setValue( "VM_Directory", ui.Edit_VM_Folder->text() ); } else { int mes_res = QMessageBox::question( this, tr("Invalid Value!"), tr("AQEMU VM folder doesn't exist! Do you want to create it?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes ); if( mes_res == QMessageBox::Yes ) { if( ! (dir.mkdir(ui.Edit_VM_Folder->text()) && dir.mkdir(ui.Edit_VM_Folder->text() + QDir::toNativeSeparators("/os_templates/"))) ) { AQGraphic_Warning( tr("Error!"), tr("Cannot Create New Folder!") ); return; } else Settings.setValue( "VM_Directory", ui.Edit_VM_Folder->text() ); } else return; } // Use New Emulator Control Removable Device Menu if( ui.CH_Use_New_Device_Changer->isChecked() ) Settings.setValue( "Use_New_Device_Changer", "yes" ); else Settings.setValue( "Use_New_Device_Changer", "no" ); // Interface Language if( ui.CB_Language->currentIndex() == 0 ) Settings.setValue( "Language", "en" ); else Settings.setValue( "Language", ui.CB_Language->itemText(ui.CB_Language->currentIndex()) ); // VM Icons Size switch( ui.CB_VM_Icons_Size->currentIndex() ) { case 0: Settings.setValue( "VM_Icons_Size", 16 ); break; case 1: Settings.setValue( "VM_Icons_Size", 24 ); break; case 2: Settings.setValue( "VM_Icons_Size", 32 ); break; case 3: Settings.setValue( "VM_Icons_Size", 48 ); break; case 4: Settings.setValue( "VM_Icons_Size", 64 ); break; default: Settings.setValue( "VM_Icons_Size", 48 ); break; } /* // USB Support if( ui.CH_Use_USB->isChecked() ) Settings.setValue( "Use_USB", "yes" ); else Settings.setValue( "Use_USB", "no" ); */ // Screenshot for OS Logo if( ui.CH_Screenshot_for_OS_Logo->isChecked() ) Settings.setValue( "Use_Screenshot_for_OS_Logo", "yes" ); else Settings.setValue( "Use_Screenshot_for_OS_Logo", "no" ); /* // 64x64 Icons if( ui.CH_64_Icons->isChecked() ) Settings.setValue( "64x64_Icons", "yes" ); else Settings.setValue( "64x64_Icons", "no" );*/ Settings.sync(); if( Settings.status() != QSettings::NoError ) { AQError( "void Settings_Window::on_Button_Box_clicked( QAbstractButton* button )", "QSettings Error!" ); } // Emulator Control if( ui.RB_Emul_Show_Window->isChecked() ) { Settings.setValue( "Show_Emulator_Control_Window", "yes" ); Settings.setValue( "Use_VNC_Display", "no" ); Settings.setValue( "Include_Emulator_Control", "no" ); } else if( ui.RB_Emul_Show_VNC->isChecked() ) { Settings.setValue( "Show_Emulator_Control_Window", "yes" ); Settings.setValue( "Use_VNC_Display", "yes" ); Settings.setValue( "Include_Emulator_Control", "no" ); } else if( ui.RB_Emul_Show_In_Main_Window->isChecked() ) { Settings.setValue( "Show_Emulator_Control_Window", "yes" ); Settings.setValue( "Use_VNC_Display", "no" ); Settings.setValue( "Include_Emulator_Control", "yes" ); } else if( ui.RB_Emul_Show_VNC_In_Main_Window->isChecked() ) { Settings.setValue( "Show_Emulator_Control_Window", "yes" ); Settings.setValue( "Use_VNC_Display", "yes" ); Settings.setValue( "Include_Emulator_Control", "yes" ); } else if( ui.RB_Emul_No_Show->isChecked() ) { Settings.setValue( "Show_Emulator_Control_Window", "no" ); Settings.setValue( "Use_VNC_Display", "no" ); Settings.setValue( "Include_Emulator_Control", "no" ); } } QDialog::done(r); }
int main(int argc, char *argv[]) { #ifdef KSTARS_LITE QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QApplication app(argc, argv); #ifdef Q_OS_OSX //Note, this function will return true on OS X if the data directories are good to go. If not, quit with error code 1! if(!KSUtils::copyDataFolderFromAppBundleIfNeeded()){ KMessageBox::sorry(0, i18n("Sorry, without a KStars Data Directory, KStars cannot operate. Exiting program now.")); return 1; } #endif app.setApplicationVersion(KSTARS_VERSION); /** * enable high dpi support */ app.setAttribute(Qt::AA_UseHighDpiPixmaps, true); KLocalizedString::setApplicationDomain("kstars"); #ifndef KSTARS_LITE KCrash::initialize(); KAboutData aboutData( "kstars", i18n("KStars"), KSTARS_VERSION, i18n(description), KAboutLicense::GPL, "2001-" + QString::number(QDate::currentDate().year()) + i18n("(c), The KStars Team"), i18n(notice), "http://edu.kde.org/kstars"); aboutData.addAuthor(i18n("Jason Harris"), i18n("Original Author"), "*****@*****.**", "http://www.30doradus.org"); aboutData.addAuthor(i18n("Jasem Mutlaq"), i18n("Current Maintainer"), "*****@*****.**", "http://www.indilib.org"); // Active developers aboutData.addAuthor(i18n("Akarsh Simha"), QString(), "*****@*****.**", "http://www.ph.utexas.edu/~asimha"); aboutData.addAuthor(i18n("Artem Fedoskin"), i18n("KStars Lite"), "*****@*****.**"); aboutData.addAuthor(i18n("Robert Lancaster"), i18n("FITSViewer Improvements. KStars OSX Port"), "*****@*****.**"); // Inactive developers aboutData.addAuthor(i18n("James Bowlin"), QString(), "*****@*****.**"); aboutData.addAuthor(i18n("Pablo de Vicente"), QString(), "*****@*****.**"); aboutData.addAuthor(i18n("Thomas Kabelmann"), QString(), "*****@*****.**"); aboutData.addAuthor(i18n("Heiko Evermann"),QString(), "*****@*****.**", "http://www.evermann.de"); aboutData.addAuthor(i18n("Carsten Niehaus"), QString(), "*****@*****.**"); aboutData.addAuthor(i18n("Mark Hollomon"), QString(), "*****@*****.**"); aboutData.addAuthor(i18n("Alexey Khudyakov"), QString(), "*****@*****.**"); aboutData.addAuthor(i18n("Médéric Boquien"), QString(), "*****@*****.**"); aboutData.addAuthor(i18n("Jérôme Sonrier"), QString(), "*****@*****.**"); aboutData.addAuthor(i18n("Prakash Mohan"), QString(), "*****@*****.**"); aboutData.addAuthor(i18n("Victor Cărbune"), QString(), "*****@*****.**"); aboutData.addAuthor(i18n("Henry de Valence"), QString(), "*****@*****.**"); aboutData.addAuthor(i18n("Samikshan Bairagya"), QString(), "*****@*****.**"); aboutData.addAuthor(i18n("Rafał Kułaga"), QString(), "*****@*****.**"); aboutData.addAuthor(i18n("Rishab Arora"), QString(), "*****@*****.**"); // Contributors aboutData.addCredit(i18n("Valery Kharitonov"), i18n("Converted labels containing technical terms to links to documentation") ); aboutData.addCredit(i18n("Ana-Maria Constantin"), i18n("Technical documentation on Astronomy and KStars") ); aboutData.addCredit(i18n("Andrew Stepanenko"), i18n("Guiding code based on lin_guider") ); aboutData.addCredit(i18n("Nuno Pinheiro"), i18n("Artwork") ); aboutData.addCredit(i18n("Utkarsh Simha"), i18n("Improvements to observation plan execution, star hopper etc.") ); aboutData.addCredit(i18n("Daniel Holler"), i18n("Extensive testing and suggestions for Ekos/INDI.") ); aboutData.addCredit(i18n("Stephane Lucas"), i18n("Extensive testing and suggestions for Ekos Scheduler.") ); aboutData.addCredit(i18n("Yuri Fabirovsky"), i18n("Splash screen for both regular KStars and KStars Lite.") ); KAboutData::setApplicationData(aboutData); QCommandLineParser parser; aboutData.setupCommandLine(&parser); parser.setApplicationDescription(aboutData.shortDescription()); parser.addVersionOption(); parser.addHelpOption(); //parser.addHelpOption(INSERT_DESCRIPTION_HERE); parser.addOption(QCommandLineOption(QStringList() << "dump", i18n( "Dump sky image to file" ))); parser.addOption(QCommandLineOption(QStringList() << "script ", i18n( "Script to execute" ))); parser.addOption(QCommandLineOption(QStringList() << "width ", i18n( "Width of sky image" ), "640")); parser.addOption(QCommandLineOption(QStringList() << "height ", i18n( "Height of sky image" ), "480")); parser.addOption(QCommandLineOption(QStringList() << "filename ", i18n( "Filename for sky image" ), "kstars.png")); parser.addOption(QCommandLineOption(QStringList() << "date", i18n( "Date and time" ))); parser.addOption(QCommandLineOption(QStringList() << "paused", i18n( "Start with clock paused" ))); // urls to open parser.addPositionalArgument(QStringLiteral("urls"), i18n("FITS file(s) to open."), QStringLiteral("[urls...]")); parser.process(app); aboutData.processCommandLine(&parser); if ( parser.isSet( "dump" ) ) { qDebug() << "Dumping sky image"; //parse filename and image format const char* format = "PNG"; QString fname = parser.value( "filename" ); QString ext = fname.mid( fname.lastIndexOf(".")+1 ); if ( ext.toLower() == "png" ) { format = "PNG"; } else if ( ext.toLower() == "jpg" || ext.toLower() == "jpeg" ) { format = "JPG"; } else if ( ext.toLower() == "gif" ) { format = "GIF"; } else if ( ext.toLower() == "pnm" ) { format = "PNM"; } else if ( ext.toLower() == "bmp" ) { format = "BMP"; } else { qWarning() << i18n( "Could not parse image format of %1; assuming PNG.", fname ) ; } //parse width and height bool ok(false); int w(0), h(0); w = parser.value( "width" ).toInt( &ok ); if ( ok ) h = parser.value( "height" ).toInt( &ok ); if ( !ok ) { qWarning() << "Unable to parse arguments: " ; qWarning() << "Width: " << parser.value( "width" ) << " Height: " << parser.value( "height" ) << endl; return 1; } KStarsData *dat = KStarsData::Create(); QObject::connect( dat, SIGNAL( progressText(QString) ), dat, SLOT( slotConsoleMessage(QString) ) ); dat->initialize(); //Set Geographic Location dat->setLocationFromOptions(); //Set color scheme dat->colorScheme()->loadFromConfig(); //set clock now that we have a location: //Check to see if user provided a date/time string. If not, use current CPU time QString datestring = parser.value( "date" ); KStarsDateTime kdt; if ( ! datestring.isEmpty() ) { if ( datestring.contains( "-" ) ) { //assume ISODate format if ( datestring.contains( ":" ) ) { //also includes time //kdt = QDateTime::fromString( datestring, QDateTime::ISODate ); kdt = QDateTime::fromString( datestring, Qt::ISODate ); } else { //string probably contains date only //kdt.setDate( QDate::fromString( datestring, Qt::ISODate ) ); kdt.setDate( QDate::fromString( datestring, Qt::ISODate ) ); kdt.setTime( QTime( 0, 0, 0 ) ); } } else { //assume Text format for date string kdt = dat->geo()->LTtoUT( QDateTime::fromString( datestring, Qt::TextDate ) ); } if ( ! kdt.isValid() ) { qWarning() << i18n( "Using CPU date/time instead." ) ; kdt = KStarsDateTime::currentDateTimeUtc(); } } else { kdt = KStarsDateTime::currentDateTimeUtc(); } dat->clock()->setUTC( kdt ); SkyMap *map = SkyMap::Create(); map->resize( w, h ); QPixmap sky( w, h ); dat->setFullTimeUpdate(); dat->updateTime(dat->geo(), map ); SkyPoint dest( Options::focusRA(), Options::focusDec() ); map->setDestination( dest ); map->destination()->EquatorialToHorizontal( dat->lst(), dat->geo()->lat() ); map->setFocus( map->destination() ); map->focus()->EquatorialToHorizontal( dat->lst(), dat->geo()->lat() ); //Execute the specified script QString scriptfile = parser.value( "script" ); if ( ! scriptfile.isEmpty() ) { if ( dat->executeScript( scriptfile, map ) ) { std::cout << i18n( "Script executed." ).toUtf8().data() << std::endl; } else { qWarning() << i18n( "Could not execute script." ) ; } } qApp->processEvents(); map->setupProjector(); map->exportSkyImage( &sky ); qApp->processEvents(); if ( ! sky.save( fname, format ) ) qWarning() << "Unable to save image: " << fname; else qDebug() << "Saved to file: %1" << fname; delete map; delete dat; return 0; } //Try to parse the given date string QString datestring = parser.value( "date" ); if ( ! datestring.isEmpty() && ! KStarsDateTime::fromString( datestring ).isValid() ) { qWarning() << i18n( "Using CPU date/time instead." ) ; datestring.clear(); } #endif // Create writable data dir if it does not exist QDir writableDir; writableDir.mkdir(KSPaths::writableLocation(QStandardPaths::GenericDataLocation)); #ifndef KSTARS_LITE KStars::createInstance( true, ! parser.isSet( "paused" ), datestring ); // no session.. just start up normally const QStringList urls = parser.positionalArguments(); // take arguments if( ! urls.isEmpty() ) { foreach (const QString &url, urls) { const QUrl u = QUrl::fromUserInput(url, QDir::currentPath()); KStars::Instance()->openFITS(u); } }
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 SecurityManager::loadMembers() { if (isSql()) { loadSqlMembers(); return; } const char *path = "serverdb/members.txt"; const char *backup = "serverdb/members.backup.txt"; { QDir d; d.mkdir("serverdb"); } if (!QFile::exists(path) && QFile::exists(backup)) { QFile::rename(backup, path); } memberFile.setFileName(path); if (!memberFile.open(QFile::ReadWrite)) { throw QObject::tr("Error: cannot open the file that contains the members (%1)").arg(path); } int pos = memberFile.pos(); while (!memberFile.atEnd()) { QByteArray arr = memberFile.readLine(); QString s = QString::fromUtf8(arr.constData(), std::max(0,arr.length()-1)); //-1 to remove the \n QStringList ls = s.split('%'); if (ls.size() >= 6 && isValid(ls[0])) { Member m (ls[0], ls[1].trimmed(), ls[2][0].toLatin1() - '0', ls[2][1] == '1', ls[3].trimmed().toLatin1(), ls[4].trimmed().toLatin1(), ls[5].trimmed()); if (ls.size() >= 7) { m.ban_expire_time = ls[6].toInt(); } m.filepos = pos; members[ls[0]] = m; /* Update pos for next iteration */ pos = memberFile.pos(); if (m.isBanned()) { bannedIPs.insert(m.ip, m.ban_expire_time); bannedMembers.insert(m.name.toLower(), std::pair<QString, int>(m.ip, m.ban_expire_time)); } if (m.authority() > 0) { authed.insert(m.name); } playersByIp.insert(m.ip, m.name); } lastPlace = memberFile.pos(); } //We also clean up the file by rewritting it with only the valid contents QFile temp (backup); if (!temp.open(QFile::WriteOnly | QFile::Truncate)) throw QObject::tr("Impossible to change %1").arg(backup); pos = temp.pos(); for(auto it = members.begin(); it != members.end(); ++it) { Member &m = it->second; m.write(&temp); m.filepos = pos; pos = temp.pos(); } lastPlace = temp.pos(); temp.flush(); memberFile.remove(); if (!temp.rename(path)) { throw QObject::tr("Error: cannot rename the file that contains the members (%1 -> %2)").arg(backup).arg(path); } temp.rename(path); if (!memberFile.open(QFile::ReadWrite)) { throw QObject::tr("Error: cannot reopen the file that contains the members (%1)").arg(path); } }
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; }
void LinkBackupThread::processDir(QDir& currentFromDir, QDir& currentToDir) { long numErrors = getLogger().errorCount(); if (numErrors > 1000) { QString errorMessage = QString("%1 errors found, quit?"); QMessageBox::StandardButton reply = QMessageBox::question(nullptr, "Test", errorMessage, QMessageBox::Yes|QMessageBox::No); if (reply == QMessageBox::Yes) { requestCancel(); } else { getLogger().clearErrorCount(); } } TRACE_MSG(QString("Processing directory %1").arg(currentFromDir.canonicalPath()), 1); // Process directories, then process files. QList<QFileInfo> list = currentFromDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks | QDir::Hidden | QDir::Readable); QFileInfo info; foreach (info, list) { if (isCancelRequested()) { return; } TRACE_MSG(QString("Found Dir to processes %1").arg(info.canonicalFilePath()), 2); if (passes(info)) { DEBUG_MSG(QString("Dir Passes: %1").arg(info.canonicalFilePath()), 2); if (!currentToDir.mkdir(info.fileName())) { ERROR_MSG(QString("Failed to create directory %1/%2").arg(currentToDir.canonicalPath(), info.fileName()), 1); } else if (!currentToDir.cd(info.fileName())) { ERROR_MSG(QString("Failed to cd to directory %1/%2").arg(currentToDir.canonicalPath(), info.fileName()), 1); } else if (!currentFromDir.cd(info.fileName())) { ERROR_MSG(QString("Failed to cd to directory %1/%2").arg(currentFromDir.canonicalPath(), info.fileName()), 1); if (!currentToDir.cdUp()) { ERROR_MSG("Failed to cd up a directory for the to directory", 1); requestCancel(); return; } } else { processDir(currentFromDir, currentToDir); if (!currentToDir.cdUp()) { ERROR_MSG("Failed to cd up a directory for the to directory", 1); requestCancel(); return; } if (!currentFromDir.cdUp()) { ERROR_MSG("Failed to cd up a directory for the from directory", 1); requestCancel(); return; } } } else { DEBUG_MSG(QString("Skipping Dir: %1").arg(info.canonicalFilePath()), 2); } } // Now handle files list = currentFromDir.entryInfoList(QDir::Files | QDir::NoSymLinks | QDir::Hidden | QDir::Readable); foreach (info, list) { if (isCancelRequested()) { return; } QString fullPathFileToRead = info.canonicalFilePath(); //TRACE_MSG(QString("Found File to test %1").arg(fullPathFileToRead), 2); if (passes(info)) { //TRACE_MSG(QString("File passes %1").arg(fullPathFileToRead), 2); QFile fileToRead(fullPathFileToRead); // Just in case someone deleted the file. if (fileToRead.exists()) { DBFileEntry* currentEntry = new DBFileEntry(info, m_fromDirWithoutTopDirName); const DBFileEntry* linkEntry = m_oldEntries->findEntry(m_backupSet.getCriteria(), currentEntry, m_fromDirWithoutTopDirName); QString pathToLinkFile = m_previousDirRoot; // If not in the old backup, search the current backup. if (linkEntry == nullptr) { linkEntry = m_currentEntries->findEntry(m_backupSet.getCriteria(), currentEntry, m_fromDirWithoutTopDirName); pathToLinkFile = m_toDirRoot; } if (linkEntry == nullptr) { bool failedToCopy = false; QString fullFileNameToWrite = m_toDirRoot + "/" + currentEntry->getPath(); bool needHash = (currentEntry->getHash().length() == 0); if (needHash) { failedToCopy = !::getCopyLinkUtil().copyFileGenerateHash(fullPathFileToRead, fullFileNameToWrite); if (!failedToCopy) { currentEntry->setHash(getCopyLinkUtil().getLastHash()); } } else if (!getCopyLinkUtil().copyFile(fullPathFileToRead, fullFileNameToWrite)) { failedToCopy = true; } if (failedToCopy) { ERROR_MSG(QString(tr("EC %1")).arg(currentEntry->getPath()), 1); } else { INFO_MSG(QString(tr("C %1")).arg(currentEntry->getPath()), 1); currentEntry->setLinkTypeCopy(); m_currentEntries->addEntry(currentEntry); currentEntry = nullptr; } } else { if (getCopyLinkUtil().linkFile(pathToLinkFile + "/" + linkEntry->getPath(), m_toDirRoot + "/" + currentEntry->getPath())) { currentEntry->setLinkTypeLink(); currentEntry->setHash(linkEntry->getHash()); m_currentEntries->addEntry(currentEntry); INFO_MSG(QString(tr("L %1")).arg(currentEntry->getPath()), 1); currentEntry = nullptr; } else { ERROR_MSG(QString(tr("EL %1")).arg(currentEntry->getPath()), 1); ERROR_MSG(QString(tr("(%1)(%2)(%3)")).arg(pathToLinkFile, linkEntry->getPath(), m_toDirRoot), 1); } } if (currentEntry != nullptr) { delete currentEntry; currentEntry= nullptr; } } } } TRACE_MSG(QString("Finished with directory %1").arg(currentFromDir.canonicalPath()), 1); }
bool MdiEditor::WriteXmlFile(QString filename) { //getParameters(); QFile file(filename); if(file.open(QIODevice::WriteOnly | QIODevice::Truncate |QIODevice::Text)) { QString str; QDomDocument doc; QDomText text; QDomElement element; QDomAttr attribute; QDomProcessingInstruction instruction = doc.createProcessingInstruction("xml","version=\'1.0\'"); doc.appendChild(instruction); QDomElement root = doc.createElement("project"); doc.appendChild(root); //Images QDomElement eimages=doc.createElement("images"); root.appendChild(eimages); attribute=doc.createAttribute("image1"); attribute.setValue("/image1.png"); eimages.setAttributeNode(attribute); QString filename; filename.sprintf("%s/image1.png",pro_path.toLatin1().data()); cv::imwrite(filename.toLatin1().data(),image1); attribute=doc.createAttribute("image2"); attribute.setValue("\\image2.png"); eimages.setAttributeNode(attribute); filename.sprintf("%s\\image2.png",pro_path.toLatin1().data()); cv::imwrite(filename.toLatin1().data(),image2); //layer QDomElement elayers=doc.createElement("layers"); root.appendChild(elayers); attribute=doc.createAttribute("num"); attribute.setValue(str.sprintf("%d",layer_num)); elayers.setAttributeNode(attribute); for(int index=0;index<layer_num;index++) { QDomElement elayer=doc.createElement(str.sprintf("l%d",index)); elayers.appendChild(elayer); QDir dir; QString filename; filename.sprintf("%s\\%d",pro_path.toLatin1().data(),index); dir.mkdir(filename); //masks QDomElement emask=doc.createElement("masks"); elayer.appendChild(emask); attribute=doc.createAttribute("mask1"); attribute.setValue(str.sprintf("\\%d\\mask1.png",index)); emask.setAttributeNode(attribute); filename.sprintf("%s\\%d\\mask1.png",pro_path.toLatin1().data(),index); cv::imwrite(filename.toLatin1().data(),parameters[index].mask1); attribute=doc.createAttribute("mask2"); attribute.setValue(str.sprintf("\\%d\\mask2.png",index)); emask.setAttributeNode(attribute); filename.sprintf("%s\\%d\\mask2.png",pro_path.toLatin1().data(),index); cv::imwrite(filename.toLatin1().data(),parameters[index].mask2); //parameters QDomElement epara=doc.createElement("parameters"); elayer.appendChild(epara); //weight element=doc.createElement("weight"); epara.appendChild(element); attribute=doc.createAttribute("ssim"); attribute.setValue(str.sprintf("%f",parameters[index].w_ssim)); element.setAttributeNode(attribute); attribute=doc.createAttribute("tps"); attribute.setValue(str.sprintf("%f",parameters[index].w_tps)); element.setAttributeNode(attribute); attribute=doc.createAttribute("ui"); attribute.setValue(str.sprintf("%f",parameters[index].w_ui)); element.setAttributeNode(attribute); attribute=doc.createAttribute("ssimclamp"); attribute.setValue(str.sprintf("%f",1.0-parameters[index].ssim_clamp)); element.setAttributeNode(attribute); //control points element=doc.createElement("points"); epara.appendChild(element); attribute=doc.createAttribute("image1"); str=""; for(size_t i=0;i<parameters[index].ui_points.size();i++) { QString num; str.append(num.sprintf("%f ",parameters[index].ui_points[i].lp.x)); str.append(num.sprintf("%f ",parameters[index].ui_points[i].lp.y)); } attribute.setValue(str); element.setAttributeNode(attribute); attribute=doc.createAttribute("image2"); str=""; for(size_t i=0;i<parameters[index].ui_points.size();i++) { QString num; str.append(num.sprintf("%f ",parameters[index].ui_points[i].rp.x)); str.append(num.sprintf("%f ",parameters[index].ui_points[i].rp.y)); } attribute.setValue(str); element.setAttributeNode(attribute); //boundary element=doc.createElement("boundary"); epara.appendChild(element); attribute=doc.createAttribute("lock"); int bcond=0; switch(parameters[index].bcond) { case BCOND_NONE: bcond=0; break; case BCOND_CORNER: bcond=1; break; case BCOND_BORDER: bcond=2; break; } attribute.setValue(str.sprintf("%d",bcond)); element.setAttributeNode(attribute); //debug element=doc.createElement("debug"); epara.appendChild(element); attribute=doc.createAttribute("iternum"); attribute.setValue(str.sprintf("%d",parameters[index].max_iter)); element.setAttributeNode(attribute); attribute=doc.createAttribute("dropfactor"); attribute.setValue(str.sprintf("%f",parameters[index].max_iter_drop_factor)); element.setAttributeNode(attribute); attribute=doc.createAttribute("eps"); attribute.setValue(str.sprintf("%f",parameters[index].eps)); element.setAttributeNode(attribute); attribute=doc.createAttribute("startres"); attribute.setValue(str.sprintf("%d",parameters[index].start_res)); element.setAttributeNode(attribute); } QTextStream out(&file); out.setCodec("UTF-8"); doc.save(out,4); file.close(); return true; } return false; }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QStringList args = a.arguments(); if (args.size() < 4) { out << "Usage: " << args[0] << " <version> <qtdir> <platform> [load]\n" << flush; return 1; } const QString version = args[1]; const QDir qtdir = QDir(args[2]); const QString platform = args[3]; if (args.size() > 5) { if (args[4] == "load") { silent = false; } } if (!QRegularExpression("\\d\\.\\d\\.\\d").match(version).hasMatch()) { out << "<version> has to be in the format #.#.#\n" << flush; return 1; } const QString short_version = version.left(3); GetFiles::version = version; // mappings etc. QList<FileGroup> mappings; mappings.append(FileGroup("bin", &GetFiles::binaryFiles)); mappings.append(FileGroup("doc", &GetFiles::docFiles)); mappings.append(FileGroup("examples", &GetFiles::exampleFiles)); mappings.append(FileGroup("imports", &GetFiles::importsFiles)); mappings.append(FileGroup("include", &GetFiles::includeFolders)); mappings.append(FileGroup("lib", &GetFiles::libFiles)); mappings.append(FileGroup("libexec", &GetFiles::libExecFiles)); mappings.append(FileGroup("mkspecs", &GetFiles::mkSpecFiles)); mappings.append(FileGroup("phrasebooks", &GetFiles::phrasebookFiles)); mappings.append(FileGroup("plugins", &GetFiles::pluginNames)); mappings.append(FileGroup("qml", &GetFiles::qmlFiles)); mappings.append(FileGroup("translations", &GetFiles::translationFiles)); QStringList modules; for (const FileGroup &files : mappings) { modules.append((files.fileGetter)().keys()); } modules.removeDuplicates(); out << "Copying files for the following modules: " << modules.join(", ") << "\n" << flush; QDir baseDir; for (const QString &module : modules) { if (baseDir.exists(module + ".tar.gz")) { out << "Skiping already existing module " << module << "\n" << flush; continue; } out << "Copying files for module " << module << "\n" << flush; baseDir.mkdir(module); QDir dir(baseDir); dir.cd(module); for (const FileGroup &files : mappings) { QStringList fs = (files.fileGetter)()[module]; if (fs.isEmpty()) { continue; } out << " Copying " << files.name << " files...\n" << flush; QDir fromDir(qtdir); fromDir.cd(files.name); QDir toDir(dir); toDir.mkdir(files.name); toDir.cd(files.name); copyFiles(fs, fromDir, toDir); } out << " Creating install file for module " << module << "...\n" << flush; { QFile installFile(dir.absoluteFilePath("install.js")); if (!installFile.open(QFile::WriteOnly | QFile::Truncate)) { out << "Error opening install file: " << installFile.errorString() << "\n"; return -1; } QTextStream js(&installFile); js << "FileSystem.mkpath(Paths.installPath);\n"; for (const FileGroup &groups : mappings) { if (groups.fileGetter().contains(module)) { js << "FileSystem.install(\"" << groups.name << "\", Paths.installPath + \"/" << groups.name << "\");\n"; } } js << "\n"; js.flush(); installFile.close(); } out << " Creating removal file for module " << module << "...\n" << flush; { QFile removalFile(dir.absoluteFilePath("remove.js")); if (!removalFile.open(QFile::WriteOnly | QFile::Truncate)) { out << "Error opening remove file: " << removalFile.errorString() << "\n"; return -1; } QTextStream js(&removalFile); for (const FileGroup &group : mappings) { QStringList files = (group.fileGetter)()[module]; for (const QString &file : files) { js << "FileSystem.remove(Paths.installPath + \"/" << group.name << "/" << file << "\");\n"; } } js << "\n"; js.flush(); removalFile.close(); } out << " Creating archive for module " << module << "...\n" << flush; { KArchive *arch = new KTar(baseDir.absoluteFilePath( QString("%1-%2-%3.tar.gz").arg(module, version, platform))); arch->open(QIODevice::ReadWrite); for (const QString &directory : dir.entryList(QDir::NoDotAndDotDot | QDir::Dirs)) { arch->addLocalDirectory(dir.absoluteFilePath(directory), directory); } for (const QString &file : dir.entryList(QDir::NoDotAndDotDot | QDir::Files)) { arch->addLocalFile(dir.absoluteFilePath(file), file); } arch->close(); } } out << "Creating metadata file...\n" << flush; { QFile meta(baseDir.absoluteFilePath("meta.json")); meta.open(QFile::WriteOnly | QFile::Truncate); QMap<QString, QString> descs = GetFiles::descriptions(); QMap<QString, QStringList> deps = GetFiles::dependencies(); QMap<QString, QMap<QString, QStringList>> ndeps = GetFiles::nativeDependencies(); QJsonArray root; for (const QString &module : modules) { QStringList dependencies = deps[module]; dependencies.removeAll(""); dependencies.removeDuplicates(); QMap<QString, QStringList> nDependencies = ndeps[module]; QJsonObject m; m.insert("id", module); m.insert("description", descs[module]); m.insert("version", version); m.insert("platform", platform); m.insert("url", QString("http://localhost/soqute/archives/%1-%2-%3.tar.gz") .arg(module, version, platform)); QJsonArray deps; for (const QString &dep : dependencies) { QJsonObject obj; obj.insert("id", dep); obj.insert("version", version); deps.append(obj); } m.insert("dependencies", deps); QJsonObject nativeDependencies; for (const QString &manager : nDependencies.keys()) { QJsonArray packages = QJsonArray::fromStringList(nDependencies[manager]); nativeDependencies.insert(manager, packages); } m.insert("nativeDependencies", nativeDependencies); root.append(m); } meta.write(QJsonDocument(root).toJson()); } out << "Installing files to server...\n" << flush; { QDir serverRoot("/var/www"); if (!serverRoot.exists("soqute")) { serverRoot.mkdir("soqute"); } serverRoot.cd("soqute"); if (!serverRoot.exists("archives")) { serverRoot.mkdir("archives"); } serverRoot.cd("archives"); for (const QString &archive : baseDir.entryList(QStringList() << "*.tar.gz", QDir::Files)) { out << " Installing " << archive << " to server...\n" << flush; if (serverRoot.exists(archive)) { serverRoot.remove(archive); } QFile::copy(baseDir.absoluteFilePath(archive), serverRoot.absoluteFilePath(archive)); } serverRoot.cdUp(); out << " Installing meta.json to server...\n" << flush; if (serverRoot.exists("meta.json")) { QFile server(serverRoot.absoluteFilePath("meta.json")); Q_ASSERT(server.open(QFile::ReadOnly | QFile::Truncate)); QFile local(baseDir.absoluteFilePath("meta.json")); Q_ASSERT(local.open(QFile::ReadOnly)); QJsonDocument serverDoc = QJsonDocument::fromJson(server.readAll()); server.close(); QJsonArray serverArray = serverDoc.array(); QJsonDocument localDoc = QJsonDocument::fromJson(local.readAll()); local.close(); QJsonArray localArray = localDoc.array(); QVariantList res = serverArray.toVariantList(); res.append(localArray.toVariantList()); Q_ASSERT(server.open(QFile::WriteOnly | QFile::Truncate)); server.write(QJsonDocument(QJsonArray::fromVariantList(res)).toJson()); server.close(); } else { QFile::copy(baseDir.absoluteFilePath("meta.json"), serverRoot.absoluteFilePath("meta.json")); } } out << "Done\n" << flush; return 0; }
void YouGetBridge::onFinished() { QJsonParseError json_error; QJsonObject obj = QJsonDocument::fromJson(process->readAllStandardOutput(), &json_error).object(); if (json_error.error == QJsonParseError::NoError) { if (obj.contains("streams")) { QString title = obj["title"].toString(); QJsonObject streams = obj["streams"].toObject(); QJsonObject::const_iterator i; for (i = streams.constBegin(); i != streams.constEnd(); i++) { QJsonObject item = i.value().toObject(); if (item.contains("src")) { QString container = item["container"].toString(); QJsonArray json_urls = item["src"].toArray(); QStringList names, urls; // Make file list for (int i = 0; i < json_urls.size(); i++) { names << QString("%1_%2.%3").arg(title, QString::number(i), container); urls << json_urls[i].toString(); } // Download if (download) { // Build file path list QDir dir = QDir(Settings::downloadDir); QString dirname = title + '.' + container; if (urls.size() > 1) { if (!dir.cd(dirname)) { dir.mkdir(dirname); dir.cd(dirname); } } for (int i = 0; i < names.size(); i++) names[i] = dir.filePath(names[i]); // Download more than 1 video clips with danmaku if (!danmaku.isEmpty() && urls.size() > 1) new DanmakuDelayGetter(names, urls, danmaku, true); // Download without danmaku or only 1 clip with danmaku else { for (int i = 0; i < urls.size(); i++) downloader->addTask(urls[i].toUtf8(), names[i], urls.size() > 1, danmaku.toUtf8()); } QMessageBox::information(NULL, "Message", tr("Add download task successfully!")); } // Play else { // Play more than 1 clips with danmaku if (!danmaku.isEmpty() && urls.size() > 1) new DanmakuDelayGetter(names, urls, danmaku, false); // Play clips without danmaku or only 1 clip with danmaku else { playlist->addFileAndPlay(names[0], urls[0], danmaku); for (int i = 1; i < urls.size(); i++) playlist->addFile(names[i], urls[i]); } if (Settings::autoCloseWindow) webvideo->close(); } return; } } } } QMessageBox::warning(NULL, "Error", " Parse failed!\n" + QString::fromUtf8(process->readAllStandardError())); }
QGeoMappingManagerEngineCm::QGeoMappingManagerEngineCm(const QMap<QString, QVariant> ¶meters, QGeoServiceProvider::Error *error, QString *errorString) : QGeoTiledMappingManagerEngine(parameters), m_parameters(parameters), m_host("b.tile.cloudmade.com"), m_token(QGeoServiceProviderFactoryCm::defaultToken) { Q_UNUSED(error) Q_UNUSED(errorString) setTileSize(QSize(256,256)); setMinimumZoomLevel(0.0); setMaximumZoomLevel(18.0); m_styleId = m_parameters.value("style", "1").toString(); //SL_MAP_TYPE QList<QGraphicsGeoMap::MapType> types; types << QGraphicsGeoMap::StreetMap; setSupportedMapTypes(types); m_nam = new QNetworkAccessManager(this); //m_cache = new QNetworkDiskCache(this); m_cacheSize = DEFAULT_TILE_CACHE_SIZE; QList<QString> keys = m_parameters.keys(); if (keys.contains("mapping.proxy")) { QString proxy = m_parameters.value("mapping.proxy").toString(); if (!proxy.isEmpty()) m_nam->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, proxy, 8080)); } if (keys.contains("mapping.host")) { QString host = m_parameters.value("mapping.host").toString(); if (!host.isEmpty()) m_host = host; } if (keys.contains("mapping.cache.directory")) { QString cacheDir = m_parameters.value("mapping.cache.directory").toString(); if (!cacheDir.isEmpty()) m_cacheDir = cacheDir; //m_cache->setCacheDirectory(cacheDir); } else { // set default cache dir // QDir dir = QDir::temp(); QDir dir = QDir(QDesktopServices::storageLocation(QDesktopServices::CacheLocation)); qDebug() << __FUNCTION__ << "Cache at" << dir; dir.mkdir(DEFAULT_TILE_CACHE_DIR); // QFileInfo info(dir.absolutePath()); // qDebug() << __FUNCTION__ << "Cache size" << info.size(); dir.cd(DEFAULT_TILE_CACHE_DIR); //m_cache->setCacheDirectory(dir.path()); m_cacheDir = dir.path(); } DBG_CM(TILES_M, INFO_L, "Setting tile cache dir to " << m_cacheDir); if (keys.contains("mapping.cache.size")) { bool ok = false; qint64 cacheSize = m_parameters.value("mapping.cache.size").toString().toLongLong(&ok); if (ok) { //m_cache->setMaximumCacheSize(cacheSize); m_cacheSize = cacheSize; DBG_CM(TILES_M, INFO_L, "Setting tile cache size = " << m_cacheSize); } } // first of all: delete all *.png files that may still be lurking in // the old cache dir as they may affect the gallery (they are named // png, but are not real png files) QDir dir = QDir::temp(); if(dir.cd("maptiles-cm")) { QStringList pngFilters; pngFilters << "*.png"; dir.setNameFilters(pngFilters); QStringList pngList = dir.entryList(); foreach(QString name, pngList) dir.remove(name); dir.cd(".."); dir.rmdir("maptiles-cm"); } // if (m_cacheSize > 0) cleanCacheToSize(m_cacheSize); }
LeechCraft::Application::Application (int& argc, char **argv) : QApplication (argc, argv) , CatchExceptions_ (true) { Arguments_ = arguments (); bpo::options_description desc ("Allowed options"); bpo::command_line_parser parser (argc, argv); VarMap_ = Parse (parser, &desc); if (VarMap_.count ("help")) { std::cout << "LeechCraft " << LEECHCRAFT_VERSION << " (http://leechcraft.org)" << std::endl; std::cout << std::endl; std::cout << desc << std::endl; std::exit (EHelpRequested); } if (VarMap_.count ("version")) { std::cout << "LeechCraft " << LEECHCRAFT_VERSION << " (http://leechcraft.org)" << std::endl; #ifdef Q_OS_WIN32 std::cout << " <this version does not have UNLIMITED CAT POWA :(>" << std::endl; #else std::cout << " this version can haz teh UNLIMITED CAT POWA :3 ε:" << std::endl; #endif std::exit (EVersionRequested); } if (VarMap_.count ("no-app-catch")) CatchExceptions_ = false; if (VarMap_.count ("clrsckt")) QLocalServer::removeServer (GetSocketName ()); if (VarMap_.count ("restart")) { EnterRestartMode (); return; } // Sanity checks if (!VarMap_.count ("plugin") && IsAlreadyRunning ()) std::exit (EAlreadyRunning); Util::InstallTranslator ("", "qt", "qt4"); QDir home = QDir::home (); if (!home.exists (".leechcraft")) if (!home.mkdir (".leechcraft")) { QMessageBox::critical (0, "LeechCraft", QDir::toNativeSeparators (tr ("Could not create path %1/.leechcraft") .arg (QDir::homePath ()))); std::exit (EPaths); } // Things are sane, prepare QCoreApplication::setApplicationName ("Leechcraft"); QCoreApplication::setApplicationVersion (LEECHCRAFT_VERSION); QCoreApplication::setOrganizationName ("Deviant"); Translator_.reset (LeechCraft::Util::InstallTranslator ("")); qRegisterMetaType<QModelIndex> ("QModelIndex"); qRegisterMetaType<QModelIndex*> ("QModelIndexStar"); qRegisterMetaType<TagsManager::TagsDictionary_t> ("LeechCraft::TagsManager::TagsDictionary_t"); qRegisterMetaType<LeechCraft::Entity> ("LeechCraft::Entity"); qRegisterMetaType<LeechCraft::Entity> ("Entity"); qRegisterMetaType<LeechCraft::IHookProxy_ptr> ("LeechCraft::IHookProxy_ptr"); qRegisterMetaType<LeechCraft::Sync::ChainID_t> ("LeechCraft::Sync::ChainID_t"); qRegisterMetaType<LeechCraft::Sync::ChainID_t> ("Sync::ChainID_t"); qRegisterMetaType<LeechCraft::Sync::ChainID_t> ("ChainID_t"); qRegisterMetaType<QKeySequences_t> ("QKeySequences_t"); qRegisterMetaTypeStreamOperators<QKeySequences_t> ("QKeySequences_t"); qRegisterMetaTypeStreamOperators<TagsManager::TagsDictionary_t> ("LeechCraft::TagsManager::TagsDictionary_t"); qRegisterMetaTypeStreamOperators<LeechCraft::Entity> ("LeechCraft::Entity"); ParseCommandLine (); setWindowIcon (QIcon (":/resources/images/leechcraft.svg")); // Say hello to logs qDebug () << "======APPLICATION STARTUP======"; qWarning () << "======APPLICATION STARTUP======"; // And finally!.. new LeechCraft::MainWindow (); }
bool KImGalleryPlugin::createHtml(const KURL& url, const QString& sourceDirName, int recursionLevel, const QString& imageFormat) { if(m_cancelled) return false; if( !parent() || !parent()->inherits("KonqDirPart")) return false; KonqDirPart * part = static_cast<KonqDirPart *>(parent()); QStringList subDirList; if (m_recurseSubDirectories && (recursionLevel >= 0)) { //recursionLevel == 0 means endless QDir toplevel_dir = QDir( sourceDirName ); toplevel_dir.setFilter( QDir::Dirs | QDir::Readable | QDir::Writable ); subDirList = toplevel_dir.entryList(); for (QStringList::ConstIterator it = subDirList.begin(); it != subDirList.end() && !m_cancelled; it++) { const QString currentDir = *it; if (currentDir == "." || currentDir == "..") { continue;} //disregard the "." and ".." directories QDir subDir = QDir( url.directory() + "/" + currentDir ); if (!subDir.exists()) { subDir.setPath( url.directory() ); if (!(subDir.mkdir(currentDir, false))) { KMessageBox::sorry(part->widget(), i18n("Couldn't create folder: %1").arg(subDir.path())); continue; } else { subDir.setPath( url.directory() + "/" + currentDir ); } } if(!createHtml( KURL( subDir.path() + "/" + url.fileName() ), sourceDirName + "/" + currentDir, recursionLevel > 1 ? recursionLevel - 1 : 0, imageFormat)) { return false; } } } if (m_useCommentFile) { loadCommentFile(); } kdDebug(90170) << "sourceDirName: " << sourceDirName << endl; //We're interested in only the patterns, so look for the first | //#### perhaps an accessor should be added to KImageIO instead? QString filter = KImageIO::pattern(KImageIO::Reading).section('|', 0, 0); QDir imageDir( sourceDirName, filter.latin1(), QDir::Name|QDir::IgnoreCase, QDir::Files|QDir::Readable); const QString imgGalleryDir = url.directory(); kdDebug(90170) << "imgGalleryDir: " << imgGalleryDir << endl; // Create the "thumbs" subdirectory if necessary QDir thumb_dir( imgGalleryDir + QString::fromLatin1("/thumbs/")); if (createDirectory(thumb_dir, imgGalleryDir, "thumbs") == false) return false; // Create the "images" subdirectory if necessary QDir images_dir( imgGalleryDir + QString::fromLatin1("/images/")); if (m_copyFiles) { if (createDirectory(images_dir, imgGalleryDir, "images") == false) return false; } QFile file( url.path() ); kdDebug(90170) << "url.path(): " << url.path() << ", thumb_dir: "<< thumb_dir.path() << ", imageDir: "<< imageDir.path() << endl; if ( imageDir.exists() && file.open(IO_WriteOnly) ) { QTextStream stream(&file); stream.setEncoding(QTextStream::Locale); createHead(stream); createBody(stream, sourceDirName, subDirList, imageDir, url, imageFormat); //ugly file.close(); return !m_cancelled; } else { KMessageBox::sorry(m_part->widget(),i18n("Couldn't open file: %1").arg(url.path(+1))); return false; } }
void TestAusmt::initTestCase() { // Dirs QDir srcDir (QStandardPaths::writableLocation(QStandardPaths::TempLocation)); if (!srcDir.exists(AUSMTSRC_SUBDIR)) { QVERIFY(srcDir.mkdir(AUSMTSRC_SUBDIR)); } QVERIFY(srcDir.cd(AUSMTSRC_SUBDIR)); GET_DIR; GET_VAR_DIR; GET_FILES_DIR; GET_PATCHES_DIR; // Dump AUSMT into src dir QDir ausmtResDir (":/ausmtsrc/"); foreach (const QString &fileName, ausmtResDir.entryList(QDir::Files)) { QFile file (ausmtResDir.absoluteFilePath(fileName)); if (srcDir.exists(fileName)) { QVERIFY(QFileInfo(srcDir.absoluteFilePath(fileName)).isFile()); QVERIFY(srcDir.remove(fileName)); } QVERIFY(file.copy(srcDir.absoluteFilePath(fileName))); } QDir ausmtTestResDir (":/ausmtsrc-test/"); foreach (const QString &fileName, ausmtTestResDir.entryList(QDir::Files)) { QFile file (ausmtTestResDir.absoluteFilePath(fileName)); if (srcDir.exists(fileName)) { QVERIFY(QFileInfo(srcDir.absoluteFilePath(fileName)).isFile()); QVERIFY(srcDir.remove(fileName)); } QVERIFY(file.copy(srcDir.absoluteFilePath(fileName))); } // Make a better constants_root.sh QFile constantsRoot (srcDir.absoluteFilePath(CONSTANTS_ROOT_SH)); QVERIFY(constantsRoot.open(QIODevice::WriteOnly)); QTextStream constantsRootStream (&constantsRoot); constantsRootStream << QString("AUSMT_VAR_DIR=%1\n").arg(varDir.absolutePath()); constantsRootStream << QString("PATCH_ROOT_DIR=%1\n").arg(patchesDir.absolutePath()); constantsRootStream << QString("FILES_DIR=%1\n").arg(filesDir.absolutePath()); constantsRootStream << QString("NOTIFY_WRAPPER_EXEC=echo\n"); constantsRoot.close(); // Build AUSMT QString buildName = srcDir.absoluteFilePath(BUILD_SH); QFile build (buildName); QVERIFY(build.exists()); QVERIFY(build.setPermissions(QFileDevice::ReadUser | QFileDevice::WriteUser | QFileDevice::ExeUser)); QProcess buildProcess; buildProcess.setWorkingDirectory(srcDir.absolutePath()); buildProcess.start(PYTHON, QStringList() << buildName); buildProcess.waitForFinished(-1); QCOMPARE(buildProcess.exitCode(), 0); foreach (const QString &fileName, dir.entryList(QDir::Files)) { QFile file (dir.absoluteFilePath(fileName)); QVERIFY(file.setPermissions(QFileDevice::ReadUser | QFileDevice::WriteUser | QFileDevice::ExeUser)); } // Remove src QVERIFY(srcDir.removeRecursively()); // Prepare patches preparePatches(); }
int QgsSOAPRequestHandler::setUrlToFile( QImage* img ) { QString uri; QFile theFile; QDir tmpDir; QgsDebugMsg( "Entering." ); if ( findOutHostAddress( uri ) != 0 ) { return 1; } #ifdef Q_OS_WIN if ( !QFile::exists( QDir::currentPath() + "/tmp" ) ) { QDir::current().mkdir( "tmp" ); } tmpDir = QDir( QDir::currentPath() + "/tmp" ); #else // Q_OS_WIN tmpDir = QDir( "/tmp" ); #endif QgsDebugMsg( "Path to tmpDir is: " + tmpDir.absolutePath() ); //create a random folder under /tmp with map.jpg/png in it //and return the link to the client srand( time( nullptr ) ); int randomNumber = rand(); QString folderName = QString::number( randomNumber ); if ( !QFile::exists( tmpDir.absolutePath() + "/mas_tmp" ) ) { QgsDebugMsg( "Trying to create mas_tmp folder" ); if ( !tmpDir.mkdir( "mas_tmp" ) ) { return 2; } } QDir tmpMasDir( tmpDir.absolutePath() + "/mas_tmp" ); if ( !tmpMasDir.mkdir( folderName ) ) { QgsDebugMsg( "Trying to create random folder" ); return 3; } QgsDebugMsg( "Temp. folder is: " + tmpMasDir.absolutePath() + "/" + folderName ); if ( mFormat == "JPG" ) { theFile.setFileName( tmpMasDir.absolutePath() + "/" + folderName + "/map.jpg" ); uri.append( "/mas_tmp/" + folderName + "/map.jpg" ); } else if ( mFormat == "PNG" ) { theFile.setFileName( tmpMasDir.absolutePath() + "/" + folderName + "/map.png" ); uri.append( "/mas_tmp/" + folderName + "/map.png" ); } if ( !theFile.open( QIODevice::WriteOnly ) ) { QgsDebugMsg( "Error, could not open file" ); return 4; } if ( !img->save( &theFile, mFormat.toLocal8Bit().data(), -1 ) ) { QgsDebugMsg( "Error, could not save image" ); return 5; } QDomDocument xmlResponse; QDomElement envelopeElement = xmlResponse.createElementNS( "http://schemas.xmlsoap.org/soap/envelope/", "Envelope" ); xmlResponse.appendChild( envelopeElement ); QDomElement bodyElement = xmlResponse.createElementNS( "http://schemas.xmlsoap.org/soap/envelope/", "Body" ); envelopeElement.appendChild( bodyElement ); QDomElement getMapResponseElement = xmlResponse.createElementNS( "http://www.eu-orchestra.org/services/ms", "getMapResponse" ); QDomElement ahrefElement = xmlResponse.createElement( "a" ); ahrefElement.setAttribute( "href", uri ); //QString href("<a href=\""+uri+"\">"+uri+"</a>"); QDomText uriNode = xmlResponse.createTextNode( uri ); ahrefElement.appendChild( uriNode ); //getMapResponseElement.appendChild(uriNode); getMapResponseElement.appendChild( ahrefElement ); bodyElement.appendChild( getMapResponseElement ); QByteArray xmlByteArray = xmlResponse.toByteArray(); setHttpResponse( &xmlByteArray, "text/xml" ); return 0; }
void setupDirectory(const QDir &dir) { if (!dir.mkdir("bin")) abort(); if (!dir.mkdir("doc")) abort(); if (!dir.mkdir("examples")) abort(); if (!dir.mkdir("imports")) abort(); if (!dir.mkdir("include")) abort(); if (!dir.mkdir("lib")) abort(); if (!dir.mkdir("lib/cmake")) abort(); if (!dir.mkdir("lib/pkgconfig")) abort(); if (!dir.mkdir("mkspecs")) abort(); if (!dir.mkdir("phrasebooks")) abort(); if (!dir.mkdir("plugins")) abort(); if (!dir.mkdir("qml")) abort(); if (!dir.mkdir("translations")) abort(); }
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
int QvvMainWindow::deleteItems( int current_only ) { QDir trashdir; QString trash_can = trashdir.homePath(); trash_can += "/.qvv4_trash_can"; if( ! trashdir.exists( trash_can ) ) trashdir.mkdir( trash_can ); if( ! trashdir.exists( trash_can ) ) { statusBar()->showMessage( tr( "Error: Cannot find/create trash can path:" ) + " " + trash_can ); return -1; } QList<QTreeWidgetItem *> selected; if( current_only ) selected.append( tree->currentItem() ); else selected = tree->selectedItems(); int sel_count = selected.count(); if( sel_count < 1 ) { statusBar()->showMessage( tr( "Error: No files selected for delete" ) ); return -1; }; QvvConfirmDeleteDialog *confirm = new QvvConfirmDeleteDialog; confirm->move( x() + ( ( width() - confirm->width() ) / 2 ), y() + ( ( height() - confirm->height() ) / 2) ); confirm->setWindowTitle( sel_count > 1 ? tr( "Delete multiple files: " ) + sel_count + tr( "?" ) : tr( "Delete one file?" ) ); int yes_to_all = 0; int not_moved = 0; int moved_ok_count = 0; QTreeWidgetItem *item; for( int i = 0; i < sel_count; i++ ) { item = selected[i]; if( item->text( 0 ) == ITEM_TYPE_DIR ) continue; QString file_name = cdir.absolutePath() + "/" + item->text( 1 ); if( ! yes_to_all ) { QImage im; im.load( file_name ); im = im.scaled( QSize( 256, 256 ), Qt::KeepAspectRatio ); QPixmap pm( 256, 256 ); pm = pm.fromImage( im ); confirm->cd.file_name->setText( item->text( 1 ) ); confirm->cd.pixmap->setPixmap( pm ); //confirm->cd.buttonBox->button( QDialogButtonBox::YesToAll )->setEnabled( sel_count > 1 ); confirm->exec(); //qDebug() << "RESBUTTON: " << QVariant( confirm->activated_button ).toString(); if( confirm->activated_button == QDialogButtonBox::NoButton ) break; if( confirm->activated_button == QDialogButtonBox::Cancel ) break; if( confirm->activated_button == QDialogButtonBox::No ) continue; if( confirm->activated_button == QDialogButtonBox::YesToAll ) yes_to_all = 1; } //qDebug() << "DELETE YES: " << file_name << " RESBUTTON: " << QVariant( confirm->activated_button ).toString(); QString path_hash = QVariant( QCryptographicHash::hash( cdir.absolutePath().toAscii(), QCryptographicHash::Sha1 ).toHex() ).toString(); QString trash_file_name = trash_can + "/" + path_hash + "." + item->text( 1 ); int moved_ok = 0; if( trashdir.exists( trash_file_name ) ) QFile::remove( trash_file_name ); if( trashdir.rename( file_name, trash_file_name ) ) { moved_ok = 1; } else if( QFile::copy( file_name, trash_file_name ) ) { QFile::remove( file_name ); moved_ok = 1; } else { not_moved++; } if( moved_ok ) { tree->takeTopLevelItem( tree->indexOfTopLevelItem( item ) ); moved_ok_count++; } //qDebug() << "DELETE FILE: " << file_name; //qDebug() << "TRASH FILE: " << trash_file_name; //qDebug() << "--------------------------------------------------"; } delete confirm; return moved_ok_count; };
/** reads the configuration file .cuterc*/ void readConfig() { QDir dir = QDir::home(); if( !dir.cd(".cute") ){ dir.cd(".cute"); QFileInfo fi(dir, ".cute"); if(fi.exists()){ if(fi.isDir()) QMessageBox::warning(qApp->mainWidget(), "CUTE", "Cannot cd into .cute"); else QMessageBox::warning(qApp->mainWidget(), "CUTE", "Cannot create directory"); } else{ QMessageBox::information(qApp->mainWidget(), "CUTE", "Creating ~/.cute directory"); if(!dir.mkdir(".cute")) QMessageBox::information(qApp->mainWidget(), "CUTE", "Could not create ~/.cute directory"); else{ dir.cd(".cute"); if(!dir.mkdir("scripts")) QMessageBox::information(qApp->mainWidget(), "CUTE", "Could not create ~/.cute/scripts directory"); if(!dir.mkdir("macros")) QMessageBox::information(qApp->mainWidget(), "CUTE", "Could not create ~/.cute/macros directory"); if(!dir.mkdir("sessions")) QMessageBox::information(qApp->mainWidget(), "CUTE", "Could not create ~/.cute/sessions directory"); } } } // if cute version >= 0.1.6 langs dir is required if( !QDir(QDir::homeDirPath()+QDir::separator()+".cute"+QDir::separator()+"langs").exists() ) { QDir destDir = QDir::home(); destDir.cd(".cute"); destDir.mkdir("langs"); destDir.cd("langs"); QDir srcDir(LANG_DIR); QString data; QStringList dirList = srcDir.entryList(); for( int i = 2; i < dirList.count(); i++) if( QFileInfo(srcDir.absPath()+QDir::separator()+dirList[i]).isFile()) { QFile srcFile(srcDir.absPath()+QDir::separator()+dirList[i]); QFile destFile(destDir.absPath()+QDir::separator()+dirList[i]); if(destFile.exists()) continue; QTextStream destStream(&destFile); QTextStream srcStream(&srcFile); srcFile.open(IO_ReadOnly); destFile.open(IO_WriteOnly); data = srcStream.read(); destStream << data; srcFile.close(); destFile.close(); } } QFile file(QDir::homeDirPath()+"/.cuterc"); if(!file.exists()){ QMessageBox::information(qApp->mainWidget(), "CUTE", "Creating ~/.cuterc"); file.open(IO_ReadOnly); file.close(); return; } //FILE *c_file = fopen("/home/heiko/.cuterc", "r"); //PyRun_SimpleFile(c_file, ".cuterc"); QString const_cmd("execfile(\".cuterc\")\n"); dir = QDir::current(); QDir::setCurrent( QDir::homeDirPath() ); char *cmd = new char[1024]; strcpy(cmd, const_cmd.latin1()); PyRun_SimpleString(cmd); // read language config files QDir langDir = QDir(QDir::homeDirPath()+QDir::separator()+".cute"+QDir::separator()+"langs"); QStringList langEntryList = langDir.entryList(); QString langFile; for( int i = 2; i < langEntryList.count(); i++ ){ QString langFile = langDir.absPath()+QDir::separator()+langEntryList[i]; QFileInfo fi(langDir, langFile); if(fi.isFile()){ langFile = QString("execfile(\"")+langFile+QString("\")\n"); char *cmd = strdup(langFile); PyRun_SimpleString( cmd ); } } QDir::setCurrent( dir.absPath() ); }
void IconView::HandleImport(void) { QFileInfo path; QDir importdir; // Makes import directory samba/windows friendly (no colon) QString idirname = m_currDir + "/" + MythDate::current().toString("yyyy-MM-dd_hh-mm-ss"); importdir.mkdir(idirname); importdir.setPath(idirname); for (QStringList::const_iterator it = m_paths.begin(); it != m_paths.end(); ++it) { path.setFile(*it); if (path.isDir() && path.isReadable()) { ImportFromDir(*it, importdir.absolutePath()); } else if (path.isFile() && path.isExecutable()) { if (m_allowImportScripts) { QString cmd = *it + " " + importdir.absolutePath(); MythScreenStack *popupStack = GetMythMainWindow()->GetStack("popup stack"); MythUIBusyDialog *busy = new MythUIBusyDialog(tr("Importing images from camera. Please wait..."), popupStack, "importbusydialog"); if (busy->Create()) { popupStack->AddScreen(busy, false); } else { delete busy; busy = NULL; } ImportThread *import = new ImportThread(cmd); import->start(); while (!import->isFinished()) { usleep(500); qApp->processEvents(); } delete import; if (busy) busy->Close(); } else { ShowOkPopup(tr("Found an import script (%1) but running them has been disabled in the settings!") .arg(*it)); importdir.rmdir(importdir.absolutePath()); return; } } else { LOG(VB_GENERAL, LOG_ERR, LOC + QString("Could not read or execute %1").arg(*it)); ShowOkPopup(tr("Could not read or execute %1").arg(*it)); } } importdir.setFilter(QDir::Files | QDir::Readable | QDir::NoDotAndDotDot); importdir.refresh(); if (importdir.count() == 0) { ShowOkPopup(tr("Nothing found to import")); importdir.rmdir(importdir.absolutePath()); return; } else ShowOkPopup(tr("Found %n image(s)", "", importdir.count())); LoadDirectory(m_currDir); }
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; }
Application::Application(int &argc, char **argv) : QApplication(argc,argv) { QTranslator *main_translator=nullptr, *plugin_translator=nullptr; QFile ui_style(GlobalAttributes::TMPL_CONFIGURATIONS_DIR + GlobalAttributes::DIR_SEPARATOR + GlobalAttributes::UI_STYLE_CONF + GlobalAttributes::CONFIGURATION_EXT); QString plugin_name, plug_lang_dir, plug_lang_file; QStringList dir_list; QDir dir; //Creating the initial user's configuration createUserConfiguration(); //Changing the current working dir to the executable's directory in QDir::setCurrent(this->applicationDirPath()); //Adding paths which executable will find plugins and it's dependecies this->addLibraryPath(this->applicationDirPath()); this->addLibraryPath(GlobalAttributes::PLUGINS_DIR); //Try to create plugins dir if it does not exists if(!dir.exists(GlobalAttributes::PLUGINS_DIR)) { if(!dir.mkdir(GlobalAttributes::PLUGINS_DIR)) { Messagebox msg; msg.show(Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(GlobalAttributes::PLUGINS_DIR), ERR_FILE_DIR_NOT_WRITTEN,__PRETTY_FUNCTION__,__FILE__,__LINE__)); } } //Check if the temporary dir exists, if not, creates it. if(!dir.exists(GlobalAttributes::TEMPORARY_DIR)) { if(!dir.mkdir(GlobalAttributes::TEMPORARY_DIR)) { Messagebox msg; msg.show(Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(GlobalAttributes::TEMPORARY_DIR), ERR_FILE_DIR_NOT_WRITTEN, __PRETTY_FUNCTION__,__FILE__,__LINE__)); } } //Tries to load the main ui translation according to the system's locale main_translator=new QTranslator; main_translator->load(QLocale::system().name(), GlobalAttributes::LANGUAGES_DIR); this->installTranslator(main_translator); //Trying to load plugins translations dir_list=QDir(GlobalAttributes::PLUGINS_DIR + GlobalAttributes::DIR_SEPARATOR, QString("*"), QDir::Name, QDir::AllDirs | QDir::NoDotAndDotDot).entryList(); while(!dir_list.isEmpty()) { plugin_name=dir_list.front(); dir_list.pop_front(); //Configure the path to "lang" subdir at current plugin directory plug_lang_dir=GlobalAttributes::PLUGINS_DIR + GlobalAttributes::DIR_SEPARATOR + plugin_name + GlobalAttributes::DIR_SEPARATOR + QString("lang") + GlobalAttributes::DIR_SEPARATOR; plug_lang_file=plugin_name + QString(".") + QLocale::system().name(); //Check if the .qm file exists for the current plugin. If so create and install a translator if(QFileInfo(plug_lang_dir + plug_lang_file + QString(".qm")).exists()) { plugin_translator=new QTranslator; plugin_translator->load(plug_lang_file, plug_lang_dir); this->installTranslator(plugin_translator); } } //Loading app style sheet ui_style.open(QFile::ReadOnly); //Raises an error if ui style is not found if(!ui_style.isOpen()) { Messagebox msg; msg.show(Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED).arg(ui_style.fileName()), ERR_FILE_DIR_NOT_ACCESSED,__PRETTY_FUNCTION__,__FILE__,__LINE__)); } else this->setStyleSheet(ui_style.readAll()); }
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; }
BootSelectionDialog::BootSelectionDialog(const QString &defaultPartition, QWidget *parent) : QDialog(parent), _countdown(OS_SELECTION_TIMEOUT+1), ui(new Ui::BootSelectionDialog) { setWindowFlags(Qt::Window | Qt::CustomizeWindowHint | Qt::WindowTitleHint); ui->setupUi(this); QRect s = QApplication::desktop()->screenGeometry(); if (s.height() < 500) resize(s.width()-10, s.height()-100); QDir dir; dir.mkdir("/settings"); if (QProcess::execute("mount -o remount,ro /settings") != 0 && QProcess::execute("mount -t ext4 -o ro " SETTINGS_PARTITION " /settings") != 0) { QMessageBox::critical(this, tr("Cannot display boot menu"), tr("Error mounting settings partition")); return; } /* Also mount /dev/mmcblk0p1 as it may contain icons we need */ if (QProcess::execute("mount -t vfat -o ro /dev/mmcblk0p1 /mnt") != 0) { /* Not fatal if this fails */ } QVariantList installed_os = Json::loadFromFile("/settings/installed_os.json").toList(); QSize currentsize = ui->list->iconSize(); foreach (QVariant v, installed_os) { QVariantMap m = v.toMap(); QString iconfilename = m.value("icon").toString(); QIcon icon; if (!iconfilename.isEmpty() && QFile::exists(iconfilename)) { icon = QIcon(iconfilename); QList<QSize> avs = icon.availableSizes(); if (avs.isEmpty()) { /* Icon file corrupt */ icon = QIcon(); } else { QSize iconsize = avs.first(); if (iconsize.width() > currentsize.width() || iconsize.height() > currentsize.height()) { /* Make all icons as large as the largest icon we have */ currentsize = QSize(qMax(iconsize.width(), currentsize.width()),qMax(iconsize.height(), currentsize.height())); ui->list->setIconSize(currentsize); } } } if (canBootOs(m.value("name").toString(), m)) { QListWidgetItem *item = new QListWidgetItem(icon, m.value("name").toString()+"\n"+m.value("description").toString(), ui->list); item->setData(Qt::UserRole, m); } }
//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; }
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 }
bool FlpImport::tryZIPImport( trackContainer * _tc ) { // see if the file is a zip file closeFile(); const QFile &thefile = file(); int err = 0; struct zip *zfile = zip_open(qPrintable(thefile.fileName()), 0, &err); if( zfile == NULL ) { if( err == ZIP_ER_NOZIP ) { printf("flp import (zip): not a valid zip file\n"); } else if( err == ZIP_ER_OPEN ) { printf("flp import (zip): error opening file\n"); } else if( err == ZIP_ER_READ || err == ZIP_ER_SEEK ) { printf("flp import (zip): error reading file\n"); } else { printf("flp import (zip): unknown error opening zip file\n"); } return false; } // valid zip file // get temporary directory QString tmpName; { QTemporaryFile qtmp; if( qtmp.open() ) { tmpName = qtmp.fileName(); } else { zip_close(zfile); printf("flp import (zip): error getting temporary folder\n"); return false; } } QDir tmpDir = QDir::temp(); tmpDir.mkdir(tmpName); tmpDir.cd(tmpName); // unzip everything to the temp folder int buf_size = getpagesize(); char buf[buf_size]; int numFiles = zip_get_num_files(zfile); int i; bool foundFLP = false; QString flpFile = ""; for( i=0; i<numFiles; ++i ) { const char* fileName = zip_get_name(zfile, i, 0); if( fileName != NULL ) { struct zip_file *unzipFile = zip_fopen_index(zfile, i, 0); if( unzipFile != NULL ) { // we have a handle to read, now get a handle to the outfile QFile out(tmpDir.absolutePath() + QDir::separator() + fileName); out.open(QIODevice::WriteOnly); // ok we have handles on both, now do buffered writing bool readErr = false; while(true) { // read into buffer int numRead = zip_fread(unzipFile, buf, buf_size); if( numRead == -1 ) { readErr = true; printf("flp import (zip): error while reading %s " "from zip file\n", fileName); break; } out.write( buf, numRead ); if( numRead < buf_size ) break; } // we successfully read this file, check if it is // the .flp file QString qFileName(fileName); if( qFileName.endsWith(".flp") ) { foundFLP = true; flpFile = out.fileName(); } // clean up out.close(); zip_fclose(unzipFile); } else { printf("flp import (zip): unable to get %s out of %s\n", fileName, qPrintable(thefile.fileName()) ); } } } zip_close(zfile); // make sure there was a .flp file in the archive if( ! foundFLP ) { printf("flp import (zip): no .flp file found in archive\n"); return false; } // use the flp_import plugin to load the .flp file // which was extracted to the temp dir setFile(flpFile); m_fileBase = QFileInfo( flpFile ).path(); return tryFLPImport( _tc ); }
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(); }
QGeoMappingManagerEngineGoogle::QGeoMappingManagerEngineGoogle(const QMap<QString, QVariant> ¶meters, QGeoServiceProvider::Error *error, QString *errorString) : QGeoTiledMappingManagerEngine(parameters), m_parameters(parameters), m_nam(NULL) { QNetworkDiskCache *cache = NULL; Q_UNUSED(error) Q_UNUSED(errorString) setTileSize(QSize(256, 256)); setMinimumZoomLevel(0.0); setMaximumZoomLevel(17.0); QList<QGraphicsGeoMap::MapType> types; types << QGraphicsGeoMap::StreetMap; types << QGraphicsGeoMap::SatelliteMapDay; setSupportedMapTypes(types); QList<QGraphicsGeoMap::ConnectivityMode> modes; modes << QGraphicsGeoMap::OnlineMode; setSupportedConnectivityModes(modes); QList<QString> keys = m_parameters.keys(); if (keys.contains("mapping.networkaccessmanager")) { QNetworkAccessManager *nam; nam = (QNetworkAccessManager *)m_parameters .value("mapping.networkaccessmanager").value<void *>(); if (nam) m_nam = nam; } if (!m_nam) { m_nam = new QNetworkAccessManager(this); cache = new QNetworkDiskCache(this); } if (cache) { QDir dir = QDir::temp(); dir.mkdir("maptiles-google"); dir.cd("maptiles-google"); cache->setCacheDirectory(dir.path()); } if (keys.contains("mapping.proxy")) { QString proxy = m_parameters.value("mapping.proxy").toString(); if (!proxy.isEmpty()) m_nam->setProxy(parseProxy(proxy)); } if (cache && keys.contains("mapping.cache.directory")) { QString cacheDir = m_parameters.value("mapping.cache.directory").toString(); if (!cacheDir.isEmpty()) cache->setCacheDirectory(cacheDir); } if (cache && keys.contains("mapping.cache.size")) { bool ok = false; qint64 cacheSize = m_parameters.value("mapping.cache.size").toString().toLongLong(&ok); if (ok) cache->setMaximumCacheSize(cacheSize); } if (cache) m_nam->setCache(cache); }
void CrashHandler::attemptCrashsave() { QDir crashSave; crashSave.setCurrent(AppPathManager::userAppDir()); /* * For case if crash happened while ... attempt to load crashed files! * This avoids looping crashes because backup files are causing crash too! */ if(crashSave.exists("__crashsave")) { LogCriticalNC("We are detected that crash has been occouped on attempt to load or initialize backup files. Backup directory has been renamed into \"__crashsave_danger\"."); LogCriticalNC("Please attach all files in that directory and, if possible, additional contents (custom images, sounds, musics, configs and scripts) while reporting this crash."); QDir dupeDir(AppPathManager::userAppDir() + "/__crashsave_danger"); if(dupeDir.exists()) dupeDir.removeRecursively(); crashSave.rename("__crashsave", "__crashsave_danger"); return; } crashSave.mkdir("__crashsave"); crashSave.cd("__crashsave"); int untitledCounter = 0; MainWindow *mw = MainWinConnect::pMainWin; if(!mw) return; QList<QMdiSubWindow *> listOfAllSubWindows = mw->allEditWins(); for(QMdiSubWindow *subWin : listOfAllSubWindows) { if(mw->activeChildWindow(subWin) == MainWindow::WND_Level) { LevelEdit *lvledit = mw->activeLvlEditWin(subWin); if(!lvledit) continue; QString fName = lvledit->currentFile(); if(lvledit->isUntitled()) fName = QString("Untitled_Crash") + QString::number(untitledCounter++) + QString(".lvlx"); else fName = fName.section("/", -1) + QString(".lvlx"); LevelData &lvl = lvledit->LvlData; lvl.metaData.crash.used = true; lvl.metaData.crash.untitled = lvl.meta.untitled; lvl.metaData.crash.modifyed = lvl.meta.modified; lvl.metaData.crash.strictModeSMBX64 = lvl.meta.smbx64strict; lvl.metaData.crash.fmtID = lvl.meta.RecentFormat; lvl.metaData.crash.fmtVer = lvl.meta.RecentFormatVersion; lvl.metaData.crash.filename = lvl.meta.filename; lvl.metaData.crash.path = lvl.meta.path; lvl.metaData.crash.fullPath = lvledit->curFile; //Forcely save data into PGE-X format lvl.meta.RecentFormat = LevelData::PGEX; lvledit->saveFile(crashSave.absoluteFilePath(fName), false); } else if(mw->activeChildWindow(subWin) == MainWindow::WND_NpcTxt) { NpcEdit *npcedit = mw->activeNpcEditWin(subWin); if(!npcedit) continue; QString fName = npcedit->currentFile(); if(npcedit->isUntitled()) fName = QString("Untitled_Crash") + QString::number(untitledCounter++) + QString(".txt"); else fName = fName.section("/", -1); npcedit->saveFile(crashSave.absoluteFilePath(fName), false); } else if(mw->activeChildWindow(subWin) == MainWindow::WND_World) { WorldEdit *worldedit = mw->activeWldEditWin(subWin); if(!worldedit) continue; QString fName = worldedit->currentFile(); if(worldedit->isUntitled()) fName = QString("Untitled_Crash") + QString::number(untitledCounter++) + QString(".wldx"); else fName = fName.section("/", -1) + QString(".wldx"); WorldData &wld = worldedit->WldData; wld.metaData.crash.used = true; wld.metaData.crash.untitled = wld.meta.untitled; wld.metaData.crash.modifyed = wld.meta.modified; wld.metaData.crash.strictModeSMBX64 = wld.meta.smbx64strict; wld.metaData.crash.fmtID = wld.meta.RecentFormat; wld.metaData.crash.fmtVer = wld.meta.RecentFormatVersion; wld.metaData.crash.filename = wld.meta.filename; wld.metaData.crash.path = wld.meta.path; wld.metaData.crash.fullPath = worldedit->curFile; //Forcely save data into PGE-X format wld.meta.RecentFormat = WorldData::PGEX; worldedit->saveFile(crashSave.absoluteFilePath(fName), false); } } }