SendCoinsDialog::SendCoinsDialog(QWidget* parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), clientModel(0), model(0), fNewRecipientAllowed(true), fFeeMinimized(true) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this); addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString&)), this, SLOT(coinControlChangeEdited(const QString&))); // UTXO Splitter connect(ui->splitBlockCheckBox, SIGNAL(stateChanged(int)), this, SLOT(splitBlockChecked(int))); connect(ui->splitBlockLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(splitBlockLineEditChanged(const QString&))); // Exsolution specific QSettings settings; if (!settings.contains("bUseDarKsend")) settings.setValue("bUseDarKsend", false); if (!settings.contains("bUseInstantX")) settings.setValue("bUseInstantX", false); bool useDarKsend = settings.value("bUseDarKsend").toBool(); bool useInstantX = settings.value("bUseInstantX").toBool(); if (fLiteMode) { ui->checkUseDarksend->setChecked(false); ui->checkUseDarksend->setVisible(false); ui->checkInstantX->setVisible(false); CoinControlDialog::coinControl->useDarKsend = false; CoinControlDialog::coinControl->useInstantX = false; } else { ui->checkUseDarksend->setChecked(useDarKsend); ui->checkInstantX->setChecked(useInstantX); CoinControlDialog::coinControl->useDarKsend = useDarKsend; CoinControlDialog::coinControl->useInstantX = useInstantX; } connect(ui->checkUseDarksend, SIGNAL(stateChanged(int)), this, SLOT(updateDisplayUnit())); connect(ui->checkInstantX, SIGNAL(stateChanged(int)), this, SLOT(updateInstantX())); // Coin Control: clipboard actions QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction* clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction* clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction* clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction* clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction* clipboardLowOutputAction = new QAction(tr("Copy dust"), this); QAction* clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // init transaction fee section if (!settings.contains("fFeeSectionMinimized")) settings.setValue("fFeeSectionMinimized", true); if (!settings.contains("nFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility settings.setValue("nFeeRadio", 1); // custom if (!settings.contains("nFeeRadio")) settings.setValue("nFeeRadio", 0); // recommended if (!settings.contains("nCustomFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility settings.setValue("nCustomFeeRadio", 1); // total at least if (!settings.contains("nCustomFeeRadio")) settings.setValue("nCustomFeeRadio", 0); // per kilobyte if (!settings.contains("nSmartFeeSliderPosition")) settings.setValue("nSmartFeeSliderPosition", 0); if (!settings.contains("nTransactionFee")) settings.setValue("nTransactionFee", (qint64)DEFAULT_TRANSACTION_FEE); if (!settings.contains("fPayOnlyMinFee")) settings.setValue("fPayOnlyMinFee", false); if (!settings.contains("fSendFreeTransactions")) settings.setValue("fSendFreeTransactions", false); ui->groupFee->setId(ui->radioSmartFee, 0); ui->groupFee->setId(ui->radioCustomFee, 1); ui->groupFee->button((int)std::max(0, std::min(1, settings.value("nFeeRadio").toInt())))->setChecked(true); ui->groupCustomFee->setId(ui->radioCustomPerKilobyte, 0); ui->groupCustomFee->setId(ui->radioCustomAtLeast, 1); ui->groupCustomFee->button((int)std::max(0, std::min(1, settings.value("nCustomFeeRadio").toInt())))->setChecked(true); ui->sliderSmartFee->setValue(settings.value("nSmartFeeSliderPosition").toInt()); ui->customFee->setValue(settings.value("nTransactionFee").toLongLong()); ui->checkBoxMinimumFee->setChecked(settings.value("fPayOnlyMinFee").toBool()); ui->checkBoxFreeTx->setChecked(settings.value("fSendFreeTransactions").toBool()); minimizeFeeSection(settings.value("fFeeSectionMinimized").toBool()); }
CoinControlDialog::CoinControlDialog(QWidget *parent) : QDialog(parent), ui(new Ui::CoinControlDialog), model(0) { ui->setupUi(this); // context menu actions QAction *copyAddressAction = new QAction(tr("Copy address"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this // context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(copyTransactionHashAction); contextMenu->addSeparator(); contextMenu->addAction(lockAction); contextMenu->addAction(unlockAction); // context menu signals connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint))); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash())); connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin())); connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin())); // clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // toggle tree/list mode connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool))); connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool))); // click on checkbox connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int))); // click on header #if QT_VERSION < 0x050000 ui->treeWidget->header()->setClickable(true); #else ui->treeWidget->header()->setSectionsClickable(true); #endif connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int))); // ok button connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*))); // (un)select all connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked())); // change coin control first column label due Qt4 bug. // see https://github.com/bitcoin/bitcoin/issues/5716 ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString()); ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84); ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100); ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170); ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 290); ui->treeWidget->setColumnWidth(COLUMN_DATE, 110); ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100); ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100); ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transacton hash in this column, but don't show it ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but don't show it ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true); // store amount int64 in this column, but don't show it ui->treeWidget->setColumnHidden(COLUMN_PRIORITY_INT64, true); // store priority int64 in this column, but don't show it ui->treeWidget->setColumnHidden(COLUMN_DATE_INT64, true); // store date int64 in this column, but don't show it // default view is sorted by amount desc sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder); // restore list mode and sortorder as a convenience feature QSettings settings; if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool()) ui->radioTreeMode->click(); if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder")) sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt())); }
int main( int argc, char *argv[] ) { QgsDebugMsg( QString( "Starting qgis main" ) ); #ifdef WIN32 // Windows #ifdef _MSC_VER _set_fmode( _O_BINARY ); #else //MinGW _fmode = _O_BINARY; #endif // _MSC_VER #endif // WIN32 // Set up the custom qWarning/qDebug custom handler #ifndef ANDROID qInstallMsgHandler( myMessageOutput ); #endif #if (defined(linux) && !defined(ANDROID)) || defined(__FreeBSD__) signal( SIGQUIT, qgisCrash ); signal( SIGILL, qgisCrash ); signal( SIGFPE, qgisCrash ); signal( SIGSEGV, qgisCrash ); signal( SIGBUS, qgisCrash ); signal( SIGSYS, qgisCrash ); signal( SIGTRAP, qgisCrash ); signal( SIGXCPU, qgisCrash ); signal( SIGXFSZ, qgisCrash ); #endif #ifdef Q_OS_WIN SetUnhandledExceptionFilter( QgisApp::qgisCrashDump ); #endif // initialize random number seed srand( time( NULL ) ); ///////////////////////////////////////////////////////////////// // Command line options 'behaviour' flag setup //////////////////////////////////////////////////////////////// // // Parse the command line arguments, looking to see if the user has asked for any // special behaviours. Any remaining non command arguments will be kept aside to // be passed as a list of layers and / or a project that should be loaded. // // This behaviour is used to load the app, snapshot the map, // save the image to disk and then exit QString mySnapshotFileName = ""; int mySnapshotWidth = 800; int mySnapshotHeight = 600; bool myHideSplash = false; #if defined(ANDROID) QgsDebugMsg( QString( "Android: Splash hidden" ) ); myHideSplash = true; #endif bool myRestorePlugins = true; bool myCustomization = true; // This behaviour will set initial extent of map canvas, but only if // there are no command line arguments. This gives a usable map // extent when qgis starts with no layers loaded. When layers are // loaded, we let the layers define the initial extent. QString myInitialExtent = ""; if ( argc == 1 ) myInitialExtent = "-1,-1,1,1"; // This behaviour will allow you to force the use of a translation file // which is useful for testing QString myTranslationCode; // The user can specify a path which will override the default path of custom // user settings (~/.qgis) and it will be used for QSettings INI file QString configpath; QString optionpath; QString pythonfile; QString customizationfile; #if defined(ANDROID) QgsDebugMsg( QString( "Android: All params stripped" ) );// Param %1" ).arg( argv[0] ) ); //put all QGIS settings in the same place configpath = QgsApplication::qgisSettingsDirPath(); QgsDebugMsg( QString( "Android: configpath set to %1" ).arg( configpath ) ); #endif QStringList args; if ( !bundleclicked( argc, argv ) ) { // Build a local QCoreApplication from arguments. This way, arguments are correctly parsed from their native locale // It will use QString::fromLocal8Bit( argv ) under Unix and GetCommandLine() under Windows. QCoreApplication coreApp( argc, argv ); args = QCoreApplication::arguments(); for ( int i = 1; i < args.size(); ++i ) { QString arg = args[i]; if ( arg == "--help" || arg == "-?" ) { usage( args[0].toStdString() ); return 2; } else if ( arg == "--nologo" || arg == "-n" ) { myHideSplash = true; } else if ( arg == "--noplugins" || arg == "-P" ) { myRestorePlugins = false; } else if ( arg == "--nocustomization" || arg == "-C" ) { myCustomization = false; } else if ( i + 1 < argc && ( arg == "--snapshot" || arg == "-s" ) ) { mySnapshotFileName = QDir::convertSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == "--width" || arg == "-w" ) ) { mySnapshotWidth = QString( args[++i] ).toInt(); } else if ( i + 1 < argc && ( arg == "--height" || arg == "-h" ) ) { mySnapshotHeight = QString( args[++i] ).toInt(); } else if ( i + 1 < argc && ( arg == "--lang" || arg == "-l" ) ) { myTranslationCode = args[++i]; } else if ( i + 1 < argc && ( arg == "--project" || arg == "-p" ) ) { myProjectFileName = QDir::convertSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == "--extent" || arg == "-e" ) ) { myInitialExtent = args[++i]; } else if ( i + 1 < argc && ( arg == "--optionspath" || arg == "-o" ) ) { optionpath = QDir::convertSeparators( QDir( args[++i] ).absolutePath() ); } else if ( i + 1 < argc && ( arg == "--configpath" || arg == "-c" ) ) { configpath = QDir::convertSeparators( QDir( args[++i] ).absolutePath() ); } else if ( i + 1 < argc && ( arg == "--code" || arg == "-f" ) ) { pythonfile = QDir::convertSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == "--customizationfile" || arg == "-z" ) ) { customizationfile = QDir::convertSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } else { myFileList.append( QDir::convertSeparators( QFileInfo( args[i] ).absoluteFilePath() ) ); } } } ///////////////////////////////////////////////////////////////////// // If no --project was specified, parse the args to look for a // // .qgs file and set myProjectFileName to it. This allows loading // // of a project file by clicking on it in various desktop managers // // where an appropriate mime-type has been set up. // ///////////////////////////////////////////////////////////////////// if ( myProjectFileName.isEmpty() ) { // check for a .qgs for ( int i = 0; i < args.size(); i++ ) { QString arg = QDir::convertSeparators( QFileInfo( args[i] ).absoluteFilePath() ); if ( arg.contains( ".qgs" ) ) { myProjectFileName = arg; break; } } } ///////////////////////////////////////////////////////////////////// // Now we have the handlers for the different behaviours... //////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // Initialise the application and the translation stuff ///////////////////////////////////////////////////////////////////// #ifdef Q_WS_X11 bool myUseGuiFlag = getenv( "DISPLAY" ) != 0; #else bool myUseGuiFlag = true; #endif if ( !myUseGuiFlag ) { std::cerr << QObject::tr( "QGIS starting in non-interactive mode not supported.\n" "You are seeing this message most likely because you " "have no DISPLAY environment variable set.\n" ).toUtf8().constData(); exit( 1 ); //exit for now until a version of qgis is capabable of running non interactive } if ( !optionpath.isEmpty() || !configpath.isEmpty() ) { // tell QSettings to use INI format and save the file in custom config path QSettings::setDefaultFormat( QSettings::IniFormat ); QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, optionpath.isEmpty() ? configpath : optionpath ); } // GUI customization is enabled according to settings (loaded when instance is created) // we force disabled here if --nocustomization argument is used if ( !myCustomization ) { QgsCustomization::instance()->setEnabled( false ); } QgsApplication myApp( argc, argv, myUseGuiFlag, configpath ); // (if Windows/Mac, use icon from resource) #if !defined(Q_WS_WIN) && !defined(Q_WS_MAC) myApp.setWindowIcon( QIcon( QgsApplication::iconsPath() + "qgis-icon-60x60.png" ) ); #endif // // Set up the QSettings environment must be done after qapp is created QCoreApplication::setOrganizationName( "QGIS" ); QCoreApplication::setOrganizationDomain( "qgis.org" ); QCoreApplication::setApplicationName( "QGIS2" ); QCoreApplication::setAttribute( Qt::AA_DontShowIconsInMenus, false ); QSettings* customizationsettings; if ( !optionpath.isEmpty() || !configpath.isEmpty() ) { // tell QSettings to use INI format and save the file in custom config path QSettings::setDefaultFormat( QSettings::IniFormat ); QString path = optionpath.isEmpty() ? configpath : optionpath; QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, path ); customizationsettings = new QSettings( QSettings::IniFormat, QSettings::UserScope, "QGIS", "QGISCUSTOMIZATION2" ); } else { customizationsettings = new QSettings( "QGIS", "QGISCUSTOMIZATION2" ); } // Using the customizationfile option always overrides the option and config path options. if ( !customizationfile.isEmpty() ) { customizationsettings = new QSettings( customizationfile, QSettings::IniFormat ); QgsCustomization::instance()->setEnabled( true ); } // Load and set possible default customization, must be done afterQgsApplication init and QSettings ( QCoreApplication ) init QgsCustomization::instance()->setSettings( customizationsettings ); QgsCustomization::instance()->loadDefault(); #ifdef Q_OS_MACX // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH // is not already defined, use the GDAL plugins in the application bundle. QString gdalPlugins( QCoreApplication::applicationDirPath().append( "/lib/gdalplugins" ) ); if ( QFile::exists( gdalPlugins ) && !getenv( "GDAL_DRIVER_PATH" ) ) { setenv( "GDAL_DRIVER_PATH", gdalPlugins.toUtf8(), 1 ); } #endif QSettings mySettings; // update any saved setting for older themes to new default 'gis' theme (2013-04-15) if ( mySettings.contains( "/Themes" ) ) { QString theme = mySettings.value( "/Themes", "default" ).toString(); if ( theme == QString( "gis" ) || theme == QString( "classic" ) || theme == QString( "nkids" ) ) { mySettings.setValue( "/Themes", QString( "default" ) ); } } // custom environment variables QMap<QString, QString> systemEnvVars = QgsApplication::systemEnvVars(); bool useCustomVars = mySettings.value( "qgis/customEnvVarsUse", QVariant( false ) ).toBool(); if ( useCustomVars ) { QStringList customVarsList = mySettings.value( "qgis/customEnvVars", "" ).toStringList(); if ( !customVarsList.isEmpty() ) { foreach ( const QString &varStr, customVarsList ) { int pos = varStr.indexOf( QLatin1Char( '|' ) ); if ( pos == -1 ) continue; QString envVarApply = varStr.left( pos ); QString varStrNameValue = varStr.mid( pos + 1 ); pos = varStrNameValue.indexOf( QLatin1Char( '=' ) ); if ( pos == -1 ) continue; QString envVarName = varStrNameValue.left( pos ); QString envVarValue = varStrNameValue.mid( pos + 1 ); if ( systemEnvVars.contains( envVarName ) ) { if ( envVarApply == "prepend" ) { envVarValue += systemEnvVars.value( envVarName ); } else if ( envVarApply == "append" ) { envVarValue = systemEnvVars.value( envVarName ) + envVarValue; } } if ( systemEnvVars.contains( envVarName ) && envVarApply == "unset" ) { #ifdef Q_WS_WIN putenv( envVarName.toUtf8().constData() ); #else unsetenv( envVarName.toUtf8().constData() ); #endif } else { #ifdef Q_WS_WIN if ( envVarApply != "undefined" || !getenv( envVarName.toUtf8().constData() ) ) putenv( QString( "%1=%2" ).arg( envVarName ).arg( envVarValue ).toUtf8().constData() ); #else setenv( envVarName.toUtf8().constData(), envVarValue.toUtf8().constData(), envVarApply == "undefined" ? 0 : 1 ); #endif } } }
// write QSettings values bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role) { bool successful = true; /* set to false on parse error */ if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: successful = GUIUtil::SetStartOnSystemStartup(value.toBool()); break; case MinimizeToTray: fMinimizeToTray = value.toBool(); settings.setValue("fMinimizeToTray", fMinimizeToTray); break; case MapPortUPnP: // core option - can be changed on-the-fly settings.setValue("fUseUPnP", value.toBool()); MapPort(value.toBool()); break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); settings.setValue("fMinimizeOnClose", fMinimizeOnClose); break; // default proxy case ProxyUse: if (settings.value("fUseProxy") != value) { settings.setValue("fUseProxy", value.toBool()); setRestartRequired(true); } break; case ProxyIP: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed IP if (!settings.contains("addrProxy") || strlIpPort.at(0) != value.toString()) { // construct new value from new IP and current port QString strNewValue = value.toString() + ":" + strlIpPort.at(1); settings.setValue("addrProxy", strNewValue); setRestartRequired(true); } } break; case ProxyPort: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed port if (!settings.contains("addrProxy") || strlIpPort.at(1) != value.toString()) { // construct new value from current IP and new port QString strNewValue = strlIpPort.at(0) + ":" + value.toString(); settings.setValue("addrProxy", strNewValue); setRestartRequired(true); } } break; // separate Tor proxy case ProxyUseTor: if (settings.value("fUseSeparateProxyTor") != value) { settings.setValue("fUseSeparateProxyTor", value.toBool()); setRestartRequired(true); } break; case ProxyIPTor: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed IP if (!settings.contains("addrSeparateProxyTor") || strlIpPort.at(0) != value.toString()) { // construct new value from new IP and current port QString strNewValue = value.toString() + ":" + strlIpPort.at(1); settings.setValue("addrSeparateProxyTor", strNewValue); setRestartRequired(true); } } break; case ProxyPortTor: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed port if (!settings.contains("addrSeparateProxyTor") || strlIpPort.at(1) != value.toString()) { // construct new value from current IP and new port QString strNewValue = strlIpPort.at(0) + ":" + value.toString(); settings.setValue("addrSeparateProxyTor", strNewValue); setRestartRequired(true); } } break; #ifdef ENABLE_WALLET case SpendZeroConfChange: if (settings.value("bSpendZeroConfChange") != value) { settings.setValue("bSpendZeroConfChange", value); setRestartRequired(true); } break; #endif case DisplayUnit: setDisplayUnit(value); break; case ThirdPartyTxUrls: if (strThirdPartyTxUrls != value.toString()) { strThirdPartyTxUrls = value.toString(); settings.setValue("strThirdPartyTxUrls", strThirdPartyTxUrls); setRestartRequired(true); } break; case Language: if (settings.value("language") != value) { settings.setValue("language", value); setRestartRequired(true); } break; case CoinControlFeatures: fCoinControlFeatures = value.toBool(); settings.setValue("fCoinControlFeatures", fCoinControlFeatures); Q_EMIT coinControlFeaturesChanged(fCoinControlFeatures); break; case DatabaseCache: if (settings.value("nDatabaseCache") != value) { settings.setValue("nDatabaseCache", value); setRestartRequired(true); } break; case ThreadsScriptVerif: if (settings.value("nThreadsScriptVerif") != value) { settings.setValue("nThreadsScriptVerif", value); setRestartRequired(true); } break; case Listen: if (settings.value("fListen") != value) { settings.setValue("fListen", value); setRestartRequired(true); } break; case BlockSizeAcceptLimit: { int32_t valueBytes = round(value.toDouble() * 1e6); if (settings.value("blockSizeAcceptLimitBytes") != valueBytes) { settings.setValue("blockSizeAcceptLimitBytes", valueBytes); setRestartRequired(true); } } break; default: break; } } Q_EMIT dataChanged(index, index); return successful; }
bool QgsNewSpatialiteLayerDialog::createDb() { QSettings settings; int ret; sqlite3 *sqlite_handle; char *errMsg = NULL; if ( mDatabaseComboBox->currentText().isEmpty() ) return false; QFile newDb( mDatabaseComboBox->currentText() ); if ( !newDb.exists() ) { QgsDebugMsg( "creating a new db" ); QFileInfo fullPath = QFileInfo( mDatabaseComboBox->currentText() ); QDir path = fullPath.dir(); QgsDebugMsg( QString( "making this dir: %1" ).arg( path.absolutePath() ) ); // Must be sure there is destination directory ~/.qgis QDir().mkpath( path.absolutePath( ) ); // creating/opening the new database QString dbPath = newDb.fileName(); spatialite_init( 0 ); ret = sqlite3_open_v2( dbPath.toUtf8().constData(), &sqlite_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL ); if ( ret ) { // an error occurred QString errCause = tr( "Could not create a new database\n" ); errCause += QString::fromUtf8( sqlite3_errmsg( sqlite_handle ) ); sqlite3_close( sqlite_handle ); QMessageBox::warning( 0, tr( "SpatiaLite Database" ), errCause ); pbnFindSRID->setEnabled( false ); return false; } // activating Foreign Key constraints ret = sqlite3_exec( sqlite_handle, "PRAGMA foreign_keys = 1", NULL, 0, &errMsg ); if ( ret != SQLITE_OK ) { QMessageBox::warning( 0, tr( "SpatiaLite Database" ), tr( "Unable to activate FOREIGN_KEY constraints" ) ); sqlite3_free( errMsg ); sqlite3_close( sqlite_handle ); pbnFindSRID->setEnabled( false ); return false; } initializeSpatialMetadata( sqlite_handle ); // all done: closing the DB connection sqlite3_close( sqlite_handle ); } QFileInfo fi( newDb ); if ( !fi.exists() ) { pbnFindSRID->setEnabled( false ); return false; } QString key = "/SpatiaLite/connections/" + fi.fileName() + "/sqlitepath"; if ( !settings.contains( key ) ) { settings.setValue( "/SpatiaLite/connections/selected", fi.fileName() + tr( "@" ) + fi.canonicalFilePath() ); settings.setValue( key, fi.canonicalFilePath() ); QMessageBox::information( 0, tr( "SpatiaLite Database" ), tr( "Registered new database!" ) ); } pbnFindSRID->setEnabled( true ); return true; }
void DiveLogExportDialog::on_buttonBox_accepted() { QString filename; QString stylesheet; QSettings settings; QString lastDir = QDir::homePath(); settings.beginGroup("FileDialog"); if (settings.contains("LastDir")) { if (QDir::setCurrent(settings.value("LastDir").toString())) { lastDir = settings.value("LastDir").toString(); } } settings.endGroup(); switch (ui->tabWidget->currentIndex()) { case 0: if (ui->exportUDDF->isChecked()) { stylesheet = "uddf-export.xslt"; filename = QFileDialog::getSaveFileName(this, tr("Export UDDF file as"), lastDir, tr("UDDF files (*.uddf *.UDDF)")); } else if (ui->exportCSV->isChecked()) { stylesheet = "xml2csv.xslt"; filename = QFileDialog::getSaveFileName(this, tr("Export CSV file as"), lastDir, tr("CSV files (*.csv *.CSV)")); } else if (ui->exportCSVDetails->isChecked()) { stylesheet = "xml2manualcsv.xslt"; filename = QFileDialog::getSaveFileName(this, tr("Export CSV file as"), lastDir, tr("CSV files (*.csv *.CSV)")); } else if (ui->exportDivelogs->isChecked()) { DivelogsDeWebServices::instance()->prepareDivesForUpload(ui->exportSelected->isChecked()); } else if (ui->exportDiveshare->isChecked()) { DiveShareExportDialog::instance()->prepareDivesForUpload(ui->exportSelected->isChecked()); } else if (ui->exportWorldMap->isChecked()) { filename = QFileDialog::getSaveFileName(this, tr("Export world map"), lastDir, tr("HTML files (*.html)")); if (!filename.isNull() && !filename.isEmpty()) export_worldmap_HTML(filename.toUtf8().data(), ui->exportSelected->isChecked()); } else if (ui->exportSubsurfaceXML->isChecked()) { filename = QFileDialog::getSaveFileName(this, tr("Export Subsurface XML"), lastDir, tr("XML files (*.xml *.ssrf)")); if (!filename.isNull() && !filename.isEmpty()) { if (!filename.contains('.')) filename.append(".ssrf"); QByteArray bt = QFile::encodeName(filename); save_dives_logic(bt.data(), ui->exportSelected->isChecked()); } } else if (ui->exportImageDepths->isChecked()) { filename = QFileDialog::getSaveFileName(this, tr("Save image depths"), lastDir); if (!filename.isNull() && !filename.isEmpty()) export_depths(filename.toUtf8().data(), ui->exportSelected->isChecked()); } break; case 1: filename = QFileDialog::getSaveFileName(this, tr("Export HTML files as"), lastDir, tr("HTML files (*.html)")); if (!filename.isNull() && !filename.isEmpty()) exportHtmlInit(filename); break; } if (!filename.isNull() && !filename.isEmpty()) { // remember the last export path QFileInfo fileInfo(filename); settings.beginGroup("FileDialog"); settings.setValue("LastDir", fileInfo.dir().path()); settings.endGroup(); // the non XSLT exports are called directly above, the XSLT based ons are called here if (!stylesheet.isEmpty()) { future = QtConcurrent::run(export_dives_xslt, filename.toUtf8(), ui->exportSelected->isChecked(), ui->CSVUnits_2->currentIndex(), stylesheet.toUtf8()); MainWindow::instance()->getNotificationWidget()->showNotification(tr("Please wait, exporting..."), KMessageWidget::Information); MainWindow::instance()->getNotificationWidget()->setFuture(future); } } }
// write QSettings values bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role) { bool successful = true; /* set to false on parse error */ if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: successful = GUIUtil::SetStartOnSystemStartup(value.toBool()); break; case HideTrayIcon: fHideTrayIcon = value.toBool(); settings.setValue("fHideTrayIcon", fHideTrayIcon); Q_EMIT hideTrayIconChanged(fHideTrayIcon); break; case MinimizeToTray: fMinimizeToTray = value.toBool(); settings.setValue("fMinimizeToTray", fMinimizeToTray); break; case MapPortUPnP: // core option - can be changed on-the-fly settings.setValue("fUseUPnP", value.toBool()); MapPort(value.toBool()); break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); settings.setValue("fMinimizeOnClose", fMinimizeOnClose); break; // default proxy case ProxyUse: if (settings.value("fUseProxy") != value) { settings.setValue("fUseProxy", value.toBool()); setRestartRequired(true); } break; case ProxyIP: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed IP if (!settings.contains("addrProxy") || strlIpPort.at(0) != value.toString()) { // construct new value from new IP and current port QString strNewValue = value.toString() + ":" + strlIpPort.at(1); settings.setValue("addrProxy", strNewValue); setRestartRequired(true); } } break; case ProxyPort: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed port if (!settings.contains("addrProxy") || strlIpPort.at(1) != value.toString()) { // construct new value from current IP and new port QString strNewValue = strlIpPort.at(0) + ":" + value.toString(); settings.setValue("addrProxy", strNewValue); setRestartRequired(true); } } break; // separate Tor proxy case ProxyUseTor: if (settings.value("fUseSeparateProxyTor") != value) { settings.setValue("fUseSeparateProxyTor", value.toBool()); setRestartRequired(true); } break; case ProxyIPTor: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed IP if (!settings.contains("addrSeparateProxyTor") || strlIpPort.at(0) != value.toString()) { // construct new value from new IP and current port QString strNewValue = value.toString() + ":" + strlIpPort.at(1); settings.setValue("addrSeparateProxyTor", strNewValue); setRestartRequired(true); } } break; case ProxyPortTor: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed port if (!settings.contains("addrSeparateProxyTor") || strlIpPort.at(1) != value.toString()) { // construct new value from current IP and new port QString strNewValue = strlIpPort.at(0) + ":" + value.toString(); settings.setValue("addrSeparateProxyTor", strNewValue); setRestartRequired(true); } } break; #ifdef ENABLE_WALLET case SpendZeroConfChange: if (settings.value("bSpendZeroConfChange") != value) { settings.setValue("bSpendZeroConfChange", value); setRestartRequired(true); } break; case ShowMasternodesTab: if (settings.value("fShowMasternodesTab") != value) { settings.setValue("fShowMasternodesTab", value); setRestartRequired(true); } break; case ShowAdvancedPSUI: fShowAdvancedPSUI = value.toBool(); settings.setValue("fShowAdvancedPSUI", fShowAdvancedPSUI); Q_EMIT advancedPSUIChanged(fShowAdvancedPSUI); break; case LowKeysWarning: settings.setValue("fLowKeysWarning", value); break; case PrivateSendRounds: if (settings.value("nPrivateSendRounds") != value) { privateSendClient.nPrivateSendRounds = value.toInt(); settings.setValue("nPrivateSendRounds", privateSendClient.nPrivateSendRounds); Q_EMIT privateSendRoundsChanged(); } break; case PrivateSendAmount: if (settings.value("nPrivateSendAmount") != value) { privateSendClient.nPrivateSendAmount = value.toInt(); settings.setValue("nPrivateSendAmount", privateSendClient.nPrivateSendAmount); Q_EMIT privateSentAmountChanged(); } break; case PrivateSendMultiSession: if (settings.value("fPrivateSendMultiSession") != value) { privateSendClient.fPrivateSendMultiSession = value.toBool(); settings.setValue("fPrivateSendMultiSession", privateSendClient.fPrivateSendMultiSession); } break; #endif case DisplayUnit: setDisplayUnit(value); break; case ThirdPartyTxUrls: if (strThirdPartyTxUrls != value.toString()) { strThirdPartyTxUrls = value.toString(); settings.setValue("strThirdPartyTxUrls", strThirdPartyTxUrls); setRestartRequired(true); } break; case Digits: if (settings.value("digits") != value) { settings.setValue("digits", value); setRestartRequired(true); } break; case Theme: if (settings.value("theme") != value) { settings.setValue("theme", value); setRestartRequired(true); } break; case Language: if (settings.value("language") != value) { settings.setValue("language", value); setRestartRequired(true); } break; case CoinControlFeatures: fCoinControlFeatures = value.toBool(); settings.setValue("fCoinControlFeatures", fCoinControlFeatures); Q_EMIT coinControlFeaturesChanged(fCoinControlFeatures); break; case DatabaseCache: if (settings.value("nDatabaseCache") != value) { settings.setValue("nDatabaseCache", value); setRestartRequired(true); } break; case ThreadsScriptVerif: if (settings.value("nThreadsScriptVerif") != value) { settings.setValue("nThreadsScriptVerif", value); setRestartRequired(true); } break; case Listen: if (settings.value("fListen") != value) { settings.setValue("fListen", value); setRestartRequired(true); } break; default: break; } } Q_EMIT dataChanged(index, index); return successful; }
int main( int argc, char *argv[] ) { QgsDebugMsg( QString( "Starting qgis main" ) ); #ifdef WIN32 // Windows #ifdef _MSC_VER _set_fmode( _O_BINARY ); #else //MinGW _fmode = _O_BINARY; #endif // _MSC_VER #endif // WIN32 #if defined(linux) && !defined(ANDROID) // Set up the custom qWarning/qDebug custom handler qInstallMsgHandler( myMessageOutput ); signal( SIGQUIT, qgisCrash ); signal( SIGILL, qgisCrash ); signal( SIGFPE, qgisCrash ); signal( SIGSEGV, qgisCrash ); signal( SIGBUS, qgisCrash ); signal( SIGSYS, qgisCrash ); signal( SIGTRAP, qgisCrash ); signal( SIGXCPU, qgisCrash ); signal( SIGXFSZ, qgisCrash ); #endif #ifdef Q_OS_WIN SetUnhandledExceptionFilter( qgisCrashDump ); #endif // initialize random number seed srand( time( NULL ) ); ///////////////////////////////////////////////////////////////// // Command line options 'behaviour' flag setup //////////////////////////////////////////////////////////////// // // Parse the command line arguments, looking to see if the user has asked for any // special behaviours. Any remaining non command arguments will be kept aside to // be passed as a list of layers and / or a project that should be loaded. // // This behaviour is used to load the app, snapshot the map, // save the image to disk and then exit QString mySnapshotFileName = ""; int mySnapshotWidth = 800; int mySnapshotHeight = 600; bool myHideSplash = false; #if defined(ANDROID) QgsDebugMsg( QString( "Android: Splash hidden" ) ); myHideSplash = true; #endif bool myRestorePlugins = true; bool myCustomization = true; // This behaviour will set initial extent of map canvas, but only if // there are no command line arguments. This gives a usable map // extent when qgis starts with no layers loaded. When layers are // loaded, we let the layers define the initial extent. QString myInitialExtent = ""; if ( argc == 1 ) myInitialExtent = "-1,-1,1,1"; // This behaviour will allow you to force the use of a translation file // which is useful for testing QString myTranslationCode; // The user can specify a path which will override the default path of custom // user settings (~/.qgis) and it will be used for QSettings INI file QString configpath; QString optionpath; QString pythonfile; QString customizationfile; #if defined(ANDROID) QgsDebugMsg( QString( "Android: All params stripped" ) );// Param %1" ).arg( argv[0] ) ); //put all QGIS settings in the same place configpath = QgsApplication::qgisSettingsPath(); QgsDebugMsg( QString( "Android: configpath set to %1" ).arg( configpath ) ); #elif defined(Q_WS_WIN) for ( int i = 1; i < argc; i++ ) { QString arg = argv[i]; if ( arg == "--help" || arg == "-?" ) { usage( argv[0] ); return 2; } else if ( arg == "-nologo" || arg == "-n" ) { myHideSplash = true; } else if ( arg == "--noplugins" || arg == "-P" ) { myRestorePlugins = false; } else if ( arg == "--nocustomization" || arg == "-C" ) { myCustomization = false; } else if ( i + 1 < argc && ( arg == "--snapshot" || arg == "-s" ) ) { mySnapshotFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == "--width" || arg == "-w" ) ) { mySnapshotWidth = QString( argv[++i] ).toInt(); } else if ( i + 1 < argc && ( arg == "--height" || arg == "-h" ) ) { mySnapshotHeight = QString( argv[++i] ).toInt(); } else if ( i + 1 < argc && ( arg == "--lang" || arg == "-l" ) ) { myTranslationCode = argv[++i]; } else if ( i + 1 < argc && ( arg == "--project" || arg == "-p" ) ) { myProjectFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == "--extent" || arg == "-e" ) ) { myInitialExtent = argv[++i]; } else if ( i + 1 < argc && ( arg == "--optionspath" || arg == "-o" ) ) { optionpath = argv[++i]; } else if ( i + 1 < argc && ( arg == "--configpath" || arg == "-c" ) ) { configpath = argv[++i]; } else if ( i + 1 < argc && ( arg == "--code" || arg == "-f" ) ) { pythonfile = argv[++i]; } else if ( i + 1 < argc && ( arg == "--customizationfile" || arg == "-z" ) ) { customizationfile = argv[++i]; } else { myFileList.append( QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[i] ) ).absoluteFilePath() ) ); } } #else if ( !bundleclicked( argc, argv ) ) { //////////////////////////////////////////////////////////////// // Use the GNU Getopts utility to parse cli arguments // Invokes ctor `GetOpt (int argc, char **argv, char *optstring);' /////////////////////////////////////////////////////////////// int optionChar; while ( 1 ) { static struct option long_options[] = { /* These options set a flag. */ {"help", no_argument, 0, '?'}, {"nologo", no_argument, 0, 'n'}, {"noplugins", no_argument, 0, 'P'}, {"nocustomization", no_argument, 0, 'C'}, /* These options don't set a flag. * We distinguish them by their indices. */ {"snapshot", required_argument, 0, 's'}, {"width", required_argument, 0, 'w'}, {"height", required_argument, 0, 'h'}, {"lang", required_argument, 0, 'l'}, {"project", required_argument, 0, 'p'}, {"extent", required_argument, 0, 'e'}, {"optionspath", required_argument, 0, 'o'}, {"configpath", required_argument, 0, 'c'}, {"customizationfile", required_argument, 0, 'z'}, {"code", required_argument, 0, 'f'}, {"android", required_argument, 0, 'a'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; optionChar = getopt_long( argc, argv, "swhlpeoc", long_options, &option_index ); QgsDebugMsg( QString( "Qgis main Debug" ) + optionChar ); /* Detect the end of the options. */ if ( optionChar == -1 ) break; switch ( optionChar ) { case 0: /* If this option set a flag, do nothing else now. */ if ( long_options[option_index].flag != 0 ) break; printf( "option %s", long_options[option_index].name ); if ( optarg ) printf( " with arg %s", optarg ); printf( "\n" ); break; case 's': mySnapshotFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() ); break; case 'w': mySnapshotWidth = QString( optarg ).toInt(); break; case 'h': mySnapshotHeight = QString( optarg ).toInt(); break; case 'n': myHideSplash = true; break; case 'l': myTranslationCode = optarg; break; case 'p': myProjectFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() ); break; case 'P': myRestorePlugins = false; break; case 'C': myCustomization = false; break; case 'e': myInitialExtent = optarg; break; case 'o': optionpath = optarg; break; case 'c': configpath = optarg; break; case 'f': pythonfile = optarg; break; case 'z': customizationfile = optarg; break; case '?': usage( argv[0] ); return 2; // XXX need standard exit codes break; default: QgsDebugMsg( QString( "%1: getopt returned character code %2" ).arg( argv[0] ).arg( optionChar ) ); return 1; // XXX need standard exit codes } } // Add any remaining args to the file list - we will attempt to load them // as layers in the map view further down.... QgsDebugMsg( QString( "Files specified on command line: %1" ).arg( optind ) ); if ( optind < argc ) { while ( optind < argc ) { #ifdef QGISDEBUG int idx = optind; QgsDebugMsg( QString( "%1: %2" ).arg( idx ).arg( argv[idx] ) ); #endif myFileList.append( QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[optind++] ) ).absoluteFilePath() ) ); } } } #endif ///////////////////////////////////////////////////////////////////// // Now we have the handlers for the different behaviours... //////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // Initialise the application and the translation stuff ///////////////////////////////////////////////////////////////////// #ifdef Q_WS_X11 bool myUseGuiFlag = getenv( "DISPLAY" ) != 0; #else bool myUseGuiFlag = true; #endif if ( !myUseGuiFlag ) { std::cerr << QObject::tr( "QGIS starting in non-interactive mode not supported.\n" "You are seeing this message most likely because you " "have no DISPLAY environment variable set.\n" ).toUtf8().constData(); exit( 1 ); //exit for now until a version of qgis is capabable of running non interactive } if ( !optionpath.isEmpty() || !configpath.isEmpty() ) { // tell QSettings to use INI format and save the file in custom config path QSettings::setDefaultFormat( QSettings::IniFormat ); QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, optionpath.isEmpty() ? configpath : optionpath ); } // GUI customization is enabled according to settings (loaded when instance is created) // we force disabled here if --nocustomization argument is used if ( !myCustomization ) { QgsCustomization::instance()->setEnabled( false ); } QgsApplication myApp( argc, argv, myUseGuiFlag, configpath ); // (if Windows/Mac, use icon from resource) #if !defined(Q_WS_WIN) && !defined(Q_WS_MAC) myApp.setWindowIcon( QPixmap( qgis_xpm ) ); // Linux #endif // // Set up the QSettings environment must be done after qapp is created QCoreApplication::setOrganizationName( "QGIS" ); QCoreApplication::setOrganizationDomain( "qgis.org" ); QCoreApplication::setApplicationName( "QGIS2" ); QCoreApplication::setAttribute( Qt::AA_DontShowIconsInMenus, false ); QSettings* customizationsettings; if ( !optionpath.isEmpty() || !configpath.isEmpty() ) { // tell QSettings to use INI format and save the file in custom config path QSettings::setDefaultFormat( QSettings::IniFormat ); QString path = optionpath.isEmpty() ? configpath : optionpath; QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, path ); customizationsettings = new QSettings( QSettings::IniFormat, QSettings::UserScope, "QGIS", "QGISCUSTOMIZATION2" ); } else { customizationsettings = new QSettings( "QGIS", "QGISCUSTOMIZATION2" ); } // Using the customizationfile option always overrides the option and config path options. if ( !customizationfile.isEmpty() ) { customizationsettings = new QSettings( customizationfile, QSettings::IniFormat ); QgsCustomization::instance()->setEnabled( true ); } // Load and set possible default customization, must be done afterQgsApplication init and QSettings ( QCoreApplication ) init QgsCustomization::instance()->setSettings( customizationsettings ); QgsCustomization::instance()->loadDefault(); #ifdef Q_OS_MACX // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH // is not already defined, use the GDAL plugins in the application bundle. QString gdalPlugins( QCoreApplication::applicationDirPath().append( "/lib/gdalplugins" ) ); if ( QFile::exists( gdalPlugins ) && !getenv( "GDAL_DRIVER_PATH" ) ) { setenv( "GDAL_DRIVER_PATH", gdalPlugins.toUtf8(), 1 ); } #endif QSettings mySettings; // update any saved setting for older themes to new default 'gis' theme (2013-04-15) if ( mySettings.contains( "/Themes" ) ) { QString theme = mySettings.value( "/Themes", "default" ).toString(); if ( theme == QString( "gis" ) || theme == QString( "classic" ) || theme == QString( "nkids" ) ) { mySettings.setValue( "/Themes", QString( "default" ) ); } } // custom environment variables QMap<QString, QString> systemEnvVars = QgsApplication::systemEnvVars(); bool useCustomVars = mySettings.value( "qgis/customEnvVarsUse", QVariant( false ) ).toBool(); if ( useCustomVars ) { QStringList customVarsList = mySettings.value( "qgis/customEnvVars", "" ).toStringList(); if ( !customVarsList.isEmpty() ) { foreach ( const QString &varStr, customVarsList ) { int pos = varStr.indexOf( QLatin1Char( '|' ) ); if ( pos == -1 ) continue; QString envVarApply = varStr.left( pos ); QString varStrNameValue = varStr.mid( pos + 1 ); pos = varStrNameValue.indexOf( QLatin1Char( '=' ) ); if ( pos == -1 ) continue; QString envVarName = varStrNameValue.left( pos ); QString envVarValue = varStrNameValue.mid( pos + 1 ); if ( systemEnvVars.contains( envVarName ) ) { if ( envVarApply == "prepend" ) { envVarValue += systemEnvVars.value( envVarName ); } else if ( envVarApply == "append" ) { envVarValue = systemEnvVars.value( envVarName ) + envVarValue; } } if ( systemEnvVars.contains( envVarName ) && envVarApply == "unset" ) { #ifdef Q_WS_WIN putenv( envVarName.toUtf8().constData() ); #else unsetenv( envVarName.toUtf8().constData() ); #endif } else { #ifdef Q_WS_WIN if ( envVarApply != "undefined" || !getenv( envVarName.toUtf8().constData() ) ) putenv( QString( "%1=%2" ).arg( envVarName ).arg( envVarValue ).toUtf8().constData() ); #else setenv( envVarName.toUtf8().constData(), envVarValue.toUtf8().constData(), envVarApply == "undefined" ? 0 : 1 ); #endif } } }
void KTorrentImportPage::handleAccepted () { QString filename = Ui_.FileLocation_->text (); if (!CheckValidity (filename)) return; Entity e = Util::MakeEntity (QUrl::fromLocalFile (filename), QString (), FromUserInitiated, "x-leechcraft/bittorrent-import"); if (Ui_.ImportSettings_->checkState () == Qt::Checked) { QSettings settings (filename, QSettings::IniFormat); if (settings.status () == QSettings::NoError) { QMap<QString, QVariant> additional; settings.beginGroup ("downloads"); if (settings.contains ("completedDir")) additional ["CompletedDir"] = settings.value ("completedDir"); if (settings.contains ("dhtPort")) additional ["DHTPort"] = settings.value ("dhtPort"); if (settings.contains ("dhtSupport")) additional ["DHTSupport"] = settings.value ("dhtSupport"); if (settings.contains ("lastSaveDir")) additional ["LastSaveDir"] = settings.value ("lastSaveDir"); if (settings.contains ("oldTorrentsImported")) additional ["OldTorrentsImported"] = settings.value ("oldTorrentsImported"); if (settings.contains ("saveDir")) additional ["SaveDir"] = settings.value ("saveDir"); if (settings.contains ("TempDir")) { additional ["TempDir"] = settings.value ("TempDir"); QDir tempDir (settings.value ("TempDir").toString ()); if (tempDir.exists () && tempDir.isReadable ()) { QFileInfoList torrentsDir = tempDir.entryInfoList (QStringList ("tor"), QDir::Dirs | QDir::Readable, QDir::Unsorted); QList<QVariant> list; for (int i = 0; i < torrentsDir.size (); ++i) { QMap<QString, QVariant> map; GetTorrentSettings (torrentsDir.at (i).absoluteFilePath (), map); list << map; } additional ["BitTorrentImportTorrents"] = list; } } else { additional ["TempDir"] = "~/.kde/share/apps/ktorrent"; // TODO later } if (settings.contains ("TorrentCopyDir")) additional ["TorrentCopyDir"] = settings.value ("torrentCopyDir"); settings.endGroup (); e.Additional_ ["BitTorrent/SettingsImportData"] = additional; e.Additional_ ["UserVisibleName"] = tr ("KTorrent settings"); } else QMessageBox::critical (this, "LeechCraft", tr ("Could not access or parse KTorrent settings.")); } SendEntity (e); }
void CCuteCom::readSettings() { WRITE_ERROR_LOGGER() QSettings settings; m_hardwareCb->setChecked(settings.value("/cutecom/HardwareHandshake", false).toBool()); m_softwareCb->setChecked(settings.value("/cutecom/SoftwareHandshake", false).toBool()); m_readCb->setChecked(settings.value("/cutecom/OpenForReading", true).toBool()); m_writeCb->setChecked(settings.value("/cutecom/OpenForWriting", true).toBool()); m_applyCb->setChecked(!settings.value("/cutecom/DontApplySettings", false).toBool()); enableSettingWidgets(m_applyCb->isChecked()); int defaultBaud = settings.value("/cutecom/Baud", -1).toInt(); if (defaultBaud != -1) { m_baudCb->setCurrentIndex(defaultBaud); } m_dataBitsCb->setCurrentIndex(settings.value("/cutecom/Databits", 3).toInt()); m_parityCb->setCurrentIndex(settings.value("/cutecom/Parity", 0).toInt()); m_stopCb->setCurrentIndex(settings.value("/cutecom/Stopbits", 0).toInt()); m_protoPb->setCurrentIndex(settings.value("/cutecom/Protocol", 0).toInt()); m_inputModeCb->setCurrentIndex(settings.value("/cutecom/LineMode", 0).toInt()); m_hexOutputCb->setChecked(settings.value("/cutecom/HexOutput", false).toBool()); m_charDelaySb->setValue(settings.value("/cutecom/CharDelay", 1).toInt()); m_sendFileDialogStartDir=settings.value("/cutecom/SendFileDialogStartDir", QDir::homePath()).toString(); m_logFileLe->setText(settings.value("/cutecom/LogFileName", QDir::homePath()+"/cutecom.log").toString()); m_logAppendCb->setCurrentIndex(settings.value("/cutecom/AppendToLogFile", 0).toInt()); int x=settings.value("/cutecom/width", -1).toInt(); int y=settings.value("/cutecom/height", -1).toInt(); if ((x>100) && (y>100)) { resize(x,y); } bool entryFound = settings.contains("/cutecom/AllDevices"); QStringList devices=settings.value("/cutecom/AllDevices").toStringList(); if (!entryFound) { devices<<"/dev/ttyS0"<<"/dev/ttyS1"<<"/dev/ttyS2"<<"/dev/ttyS3"; } m_deviceCb->insertItems(0, devices); int indexOfCurrentDevice = devices.indexOf(settings.value("/cutecom/CurrentDevice", "/dev/ttyS0").toString()); // fprintf(stderr, "currentDEev: -%s - index: %d\n", settings.value("/cutecom/CurrentDevice", "/dev/ttyS0").toString().toLatin1().constData(), indexOfCurrentDevice); if (indexOfCurrentDevice!=-1) { m_deviceCb->setCurrentIndex(indexOfCurrentDevice); } QStringList history=settings.value("/cutecom/History").toStringList(); if (!history.empty()) { m_oldCmdsLb->addItems(history); m_oldCmdsLb->setCurrentRow(m_oldCmdsLb->count()-1); m_oldCmdsLb->scrollToItem(m_oldCmdsLb->currentItem()); m_oldCmdsLb->clearSelection(); } }
QgsPgNewConnection::QgsPgNewConnection( QWidget *parent, const QString& connName, Qt::WindowFlags fl ) : QDialog( parent, fl ), mOriginalConnName( connName ) , mAuthConfigSelect( nullptr ) { setupUi( this ); cbxSSLmode->addItem( tr( "disable" ), QgsDataSourceURI::SSLdisable ); cbxSSLmode->addItem( tr( "allow" ), QgsDataSourceURI::SSLallow ); cbxSSLmode->addItem( tr( "prefer" ), QgsDataSourceURI::SSLprefer ); cbxSSLmode->addItem( tr( "require" ), QgsDataSourceURI::SSLrequire ); mAuthConfigSelect = new QgsAuthConfigSelect( this, "postgres" ); tabAuthentication->insertTab( 1, mAuthConfigSelect, tr( "Configurations" ) ); if ( !connName.isEmpty() ) { // populate the dialog with the information stored for the connection // populate the fields with the stored setting parameters QSettings settings; QString key = "/PostgreSQL/connections/" + connName; txtService->setText( settings.value( key + "/service" ).toString() ); txtHost->setText( settings.value( key + "/host" ).toString() ); QString port = settings.value( key + "/port" ).toString(); if ( port.length() == 0 ) { port = "5432"; } txtPort->setText( port ); txtDatabase->setText( settings.value( key + "/database" ).toString() ); cb_publicSchemaOnly->setChecked( settings.value( key + "/publicOnly", false ).toBool() ); cb_geometryColumnsOnly->setChecked( settings.value( key + "/geometryColumnsOnly", true ).toBool() ); cb_dontResolveType->setChecked( settings.value( key + "/dontResolveType", false ).toBool() ); cb_allowGeometrylessTables->setChecked( settings.value( key + "/allowGeometrylessTables", false ).toBool() ); // Ensure that cb_publicSchemaOnly is set correctly on_cb_geometryColumnsOnly_clicked(); cb_useEstimatedMetadata->setChecked( settings.value( key + "/estimatedMetadata", false ).toBool() ); cbxSSLmode->setCurrentIndex( cbxSSLmode->findData( settings.value( key + "/sslmode", QgsDataSourceURI::SSLprefer ).toInt() ) ); if ( settings.value( key + "/saveUsername" ).toString() == "true" ) { txtUsername->setText( settings.value( key + "/username" ).toString() ); chkStoreUsername->setChecked( true ); } if ( settings.value( key + "/savePassword" ).toString() == "true" ) { txtPassword->setText( settings.value( key + "/password" ).toString() ); chkStorePassword->setChecked( true ); } // Old save setting if ( settings.contains( key + "/save" ) ) { txtUsername->setText( settings.value( key + "/username" ).toString() ); chkStoreUsername->setChecked( !txtUsername->text().isEmpty() ); if ( settings.value( key + "/save" ).toString() == "true" ) txtPassword->setText( settings.value( key + "/password" ).toString() ); chkStorePassword->setChecked( true ); } QString authcfg = settings.value( key + "/authcfg" ).toString(); mAuthConfigSelect->setConfigId( authcfg ); if ( !authcfg.isEmpty() ) { tabAuthentication->setCurrentIndex( tabAuthentication->indexOf( mAuthConfigSelect ) ); } txtName->setText( connName ); } }
bool ccGui::ParamStruct::isInPersistentSettings(QString paramName) const { QSettings settings; settings.beginGroup("OpenGL"); return settings.contains(paramName); }
SendCoinsDialog::SendCoinsDialog(const PlatformStyle *platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), clientModel(0), model(0), fNewRecipientAllowed(true), fFeeMinimized(true), platformStyle(platformStyle) { ui->setupUi(this); if (!platformStyle->getImagesOnButtons()) { ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); } else { ui->addButton->setIcon(platformStyle->SingleColorIcon(":/icons/add")); ui->clearButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); ui->sendButton->setIcon(platformStyle->SingleColorIcon(":/icons/send")); } GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this); addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // init transaction fee section QSettings settings; if (!settings.contains("fFeeSectionMinimized")) settings.setValue("fFeeSectionMinimized", true); if (!settings.contains("nFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility settings.setValue("nFeeRadio", 1); // custom if (!settings.contains("nFeeRadio")) settings.setValue("nFeeRadio", 0); // recommended if (!settings.contains("nCustomFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility settings.setValue("nCustomFeeRadio", 1); // total at least if (!settings.contains("nCustomFeeRadio")) settings.setValue("nCustomFeeRadio", 0); // per kilobyte if (!settings.contains("nSmartFeeSliderPosition")) settings.setValue("nSmartFeeSliderPosition", 0); if (!settings.contains("nTransactionFee")) settings.setValue("nTransactionFee", (qint64)DEFAULT_TRANSACTION_FEE); if (!settings.contains("fPayOnlyMinFee")) settings.setValue("fPayOnlyMinFee", false); if (!settings.contains("fSendFreeTransactions")) settings.setValue("fSendFreeTransactions", false); ui->groupFee->setId(ui->radioSmartFee, 0); ui->groupFee->setId(ui->radioCustomFee, 1); ui->groupFee->button((int)std::max(0, std::min(1, settings.value("nFeeRadio").toInt())))->setChecked(true); ui->groupCustomFee->setId(ui->radioCustomPerKilobyte, 0); ui->groupCustomFee->setId(ui->radioCustomAtLeast, 1); ui->groupCustomFee->button((int)std::max(0, std::min(1, settings.value("nCustomFeeRadio").toInt())))->setChecked(true); ui->sliderSmartFee->setValue(settings.value("nSmartFeeSliderPosition").toInt()); ui->customFee->setValue(settings.value("nTransactionFee").toLongLong()); ui->checkBoxMinimumFee->setChecked(settings.value("fPayOnlyMinFee").toBool()); ui->checkBoxFreeTx->setChecked(settings.value("fSendFreeTransactions").toBool()); minimizeFeeSection(settings.value("fFeeSectionMinimized").toBool()); }
// Writes all missing QSettings with their default values void OptionsModel::Init() { QSettings settings; // Ensure restart flag is unset on client startup setRestartRequired(false); // These are Qt-only settings: // Window if (!settings.contains("fMinimizeToTray")) settings.setValue("fMinimizeToTray", false); fMinimizeToTray = settings.value("fMinimizeToTray").toBool(); if (!settings.contains("fMinimizeOnClose")) settings.setValue("fMinimizeOnClose", false); fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool(); // Display if (!settings.contains("nDisplayUnit")) settings.setValue("nDisplayUnit", BitcreditUnits::CRE); nDisplayUnit = settings.value("nDisplayUnit").toInt(); if (!settings.contains("bDisplayAddresses")) settings.setValue("bDisplayAddresses", false); bDisplayAddresses = settings.value("bDisplayAddresses", false).toBool(); if (!settings.contains("strThirdPartyTxUrls")) settings.setValue("strThirdPartyTxUrls", ""); strThirdPartyTxUrls = settings.value("strThirdPartyTxUrls", "").toString(); if (!settings.contains("fCoinControlFeatures")) settings.setValue("fCoinControlFeatures", false); fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool(); // These are shared with the core or have a command-line parameter // and we want command-line parameters to overwrite the GUI settings. // // If setting doesn't exist create it with defaults. // // If SoftSetArg() or SoftSetBoolArg() return false we were overridden // by command-line and show this in the UI. // Main if (!settings.contains("nDatabaseCache")) settings.setValue("nDatabaseCache", (qint64)bitcredit_nDefaultDbCache); if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString())) addOverriddenOption("-dbcache"); if (!settings.contains("nThreadsScriptVerif")) settings.setValue("nThreadsScriptVerif", BITCREDIT_DEFAULT_SCRIPTCHECK_THREADS); if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString())) addOverriddenOption("-par"); // Wallet #ifdef ENABLE_WALLET if (!settings.contains("nTransactionFee")) settings.setValue("nTransactionFee", (qint64)CREDITS_DEFAULT_TRANSACTION_FEE); credits_payTxFee = CFeeRate(settings.value("nTransactionFee").toLongLong()); // if -paytxfee is set, this will be overridden later in init.cpp if (mapArgs.count("-paytxfee")) addOverriddenOption("-paytxfee"); if (!settings.contains("bSpendZeroConfChange")) settings.setValue("bSpendZeroConfChange", true); if (!SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool())) addOverriddenOption("-spendzeroconfchange"); #endif #ifdef ENABLE_WALLET if (!settings.contains("bitcoin_nTransactionFee")) settings.setValue("bitcoin_nTransactionFee", (qint64)BITCOIN_DEFAULT_TRANSACTION_FEE); bitcoin_payTxFee = CFeeRate(settings.value("nTransactionFee").toLongLong()); // if -paytxfee is set, this will be overridden later in init.cpp if (mapArgs.count("-bitcoin_paytxfee")) addOverriddenOption("-bitcoin_paytxfee"); if (!settings.contains("bitcoin_bSpendZeroConfChange")) settings.setValue("bitcoin_bSpendZeroConfChange", true); if (!SoftSetBoolArg("-bitcoin_spendzeroconfchange", settings.value("bitcoin_bSpendZeroConfChange").toBool())) addOverriddenOption("-bitcoin_spendzeroconfchange"); #endif // Network if (!settings.contains("fUseUPnP")) settings.setValue("fUseUPnP", DEFAULT_UPNP); if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool())) addOverriddenOption("-upnp"); if (!settings.contains("fUseProxy")) settings.setValue("fUseProxy", false); if (!settings.contains("addrProxy")) settings.setValue("addrProxy", "127.0.0.1:9050"); // Only try to set -proxy, if user has enabled fUseProxy if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString())) addOverriddenOption("-proxy"); if (!settings.contains("nSocksVersion")) settings.setValue("nSocksVersion", 5); // Only try to set -socks, if user has enabled fUseProxy if (settings.value("fUseProxy").toBool() && !SoftSetArg("-socks", settings.value("nSocksVersion").toString().toStdString())) addOverriddenOption("-socks"); // Display if (!settings.contains("language")) settings.setValue("language", ""); if (!SoftSetArg("-lang", settings.value("language").toString().toStdString())) addOverriddenOption("-lang"); language = settings.value("language").toString(); }
QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* parent, QgsMapCanvas *canvas ) : QWidget( parent ) , mMapCanvas( canvas ) { mLayer = layer; if ( !layer ) { return; } setupUi( this ); // get rid of annoying outer focus rect on Mac mDiagramOptionsListWidget->setAttribute( Qt::WA_MacShowFocusRect, false ); mDiagramTypeComboBox->blockSignals( true ); QPixmap pix = QgsApplication::getThemePixmap( "diagramNone" ); mDiagramTypeComboBox->addItem( pix, tr( "No diagrams" ), "None" ); pix = QgsApplication::getThemePixmap( "pie-chart" ); mDiagramTypeComboBox->addItem( pix, tr( "Pie chart" ), DIAGRAM_NAME_PIE ); pix = QgsApplication::getThemePixmap( "text" ); mDiagramTypeComboBox->addItem( pix, tr( "Text diagram" ), DIAGRAM_NAME_TEXT ); pix = QgsApplication::getThemePixmap( "histogram" ); mDiagramTypeComboBox->addItem( pix, tr( "Histogram" ), DIAGRAM_NAME_HISTOGRAM ); mDiagramTypeComboBox->blockSignals( false ); mScaleRangeWidget->setMapCanvas( QgisApp::instance()->mapCanvas() ); mSizeFieldExpressionWidget->registerGetExpressionContextCallback( &_getExpressionContext, mLayer ); mBackgroundColorButton->setColorDialogTitle( tr( "Select background color" ) ); mBackgroundColorButton->setAllowAlpha( true ); mBackgroundColorButton->setContext( "symbology" ); mBackgroundColorButton->setShowNoColor( true ); mBackgroundColorButton->setNoColorString( tr( "Transparent background" ) ); mDiagramPenColorButton->setColorDialogTitle( tr( "Select pen color" ) ); mDiagramPenColorButton->setAllowAlpha( true ); mDiagramPenColorButton->setContext( "symbology" ); mDiagramPenColorButton->setShowNoColor( true ); mDiagramPenColorButton->setNoColorString( tr( "Transparent outline" ) ); mMaxValueSpinBox->setShowClearButton( false ); mDiagramUnitComboBox->setUnits( QgsSymbolV2::OutputUnitList() << QgsSymbolV2::MM << QgsSymbolV2::MapUnit << QgsSymbolV2::Pixel ); mDiagramLineUnitComboBox->setUnits( QgsSymbolV2::OutputUnitList() << QgsSymbolV2::MM << QgsSymbolV2::MapUnit << QgsSymbolV2::Pixel ); QGis::GeometryType layerType = layer->geometryType(); if ( layerType == QGis::UnknownGeometry || layerType == QGis::NoGeometry ) { mDiagramTypeComboBox->setEnabled( false ); mDiagramFrame->setEnabled( false ); } //insert placement options mPlacementComboBox->blockSignals( true ); switch ( layerType ) { case QGis::Point: mPlacementComboBox->addItem( tr( "Around Point" ), QgsDiagramLayerSettings::AroundPoint ); mPlacementComboBox->addItem( tr( "Over Point" ), QgsDiagramLayerSettings::OverPoint ); mLinePlacementFrame->setVisible( false ); break; case QGis::Line: mPlacementComboBox->addItem( tr( "Around Line" ), QgsDiagramLayerSettings::Line ); mPlacementComboBox->addItem( tr( "Over Line" ), QgsDiagramLayerSettings::Horizontal ); mLinePlacementFrame->setVisible( true ); break; case QGis::Polygon: mPlacementComboBox->addItem( tr( "Around Centroid" ), QgsDiagramLayerSettings::AroundPoint ); mPlacementComboBox->addItem( tr( "Over Centroid" ), QgsDiagramLayerSettings::OverPoint ); mPlacementComboBox->addItem( tr( "Perimeter" ), QgsDiagramLayerSettings::Line ); mPlacementComboBox->addItem( tr( "Inside Polygon" ), QgsDiagramLayerSettings::Horizontal ); mLinePlacementFrame->setVisible( false ); break; default: break; } mPlacementComboBox->blockSignals( false ); mLabelPlacementComboBox->addItem( tr( "Height" ), QgsDiagramSettings::Height ); mLabelPlacementComboBox->addItem( tr( "x-height" ), QgsDiagramSettings::XHeight ); mScaleDependencyComboBox->addItem( tr( "Area" ), true ); mScaleDependencyComboBox->addItem( tr( "Diameter" ), false ); mDataDefinedXComboBox->addItem( tr( "None" ), -1 ); mDataDefinedYComboBox->addItem( tr( "None" ), -1 ); mAngleOffsetComboBox->addItem( tr( "Top" ), 90 * 16 ); mAngleOffsetComboBox->addItem( tr( "Right" ), 0 ); mAngleOffsetComboBox->addItem( tr( "Bottom" ), 270 * 16 ); mAngleOffsetComboBox->addItem( tr( "Left" ), 180 * 16 ); mDataDefinedVisibilityComboBox->addItem( tr( "None" ), -1 ); QSettings settings; // reset horiz strech of left side of options splitter (set to 1 for previewing in Qt Designer) QSizePolicy policy( mDiagramOptionsListFrame->sizePolicy() ); policy.setHorizontalStretch( 0 ); mDiagramOptionsListFrame->setSizePolicy( policy ); if ( !settings.contains( QString( "/Windows/Diagrams/OptionsSplitState" ) ) ) { // set left list widget width on intial showing QList<int> splitsizes; splitsizes << 115; mDiagramOptionsSplitter->setSizes( splitsizes ); } // restore dialog, splitters and current tab mDiagramOptionsSplitter->restoreState( settings.value( QString( "/Windows/Diagrams/OptionsSplitState" ) ).toByteArray() ); mDiagramOptionsListWidget->setCurrentRow( settings.value( QString( "/Windows/Diagrams/Tab" ), 0 ).toInt() ); // field combo and expression button mSizeFieldExpressionWidget->setLayer( mLayer ); QgsDistanceArea myDa; myDa.setSourceCrs( mLayer->crs().srsid() ); myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); mSizeFieldExpressionWidget->setGeomCalculator( myDa ); //insert all attributes into the combo boxes const QgsFields& layerFields = layer->fields(); for ( int idx = 0; idx < layerFields.count(); ++idx ) { QTreeWidgetItem *newItem = new QTreeWidgetItem( mAttributesTreeWidget ); QString name = QString( "\"%1\"" ).arg( layerFields[idx].name() ); newItem->setText( 0, name ); newItem->setData( 0, Qt::UserRole, name ); newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled ); mDataDefinedXComboBox->addItem( layerFields[idx].name(), idx ); mDataDefinedYComboBox->addItem( layerFields[idx].name(), idx ); mDataDefinedVisibilityComboBox->addItem( layerFields[idx].name(), idx ); } const QgsDiagramRendererV2* dr = layer->diagramRenderer(); if ( !dr ) //no diagram renderer yet, insert reasonable default { mDiagramTypeComboBox->blockSignals( true ); mDiagramTypeComboBox->setCurrentIndex( 0 ); mDiagramTypeComboBox->blockSignals( false ); mFixedSizeRadio->setChecked( true ); mDiagramUnitComboBox->setUnit( QgsSymbolV2::MM ); mDiagramLineUnitComboBox->setUnit( QgsSymbolV2::MM ); mLabelPlacementComboBox->setCurrentIndex( mLabelPlacementComboBox->findText( tr( "x-height" ) ) ); mDiagramSizeSpinBox->setEnabled( true ); mDiagramSizeSpinBox->setValue( 15 ); mLinearScaleFrame->setEnabled( false ); mIncreaseMinimumSizeSpinBox->setEnabled( false ); mIncreaseMinimumSizeLabel->setEnabled( false ); mBarWidthSpinBox->setValue( 5 ); mScaleVisibilityGroupBox->setChecked( layer->hasScaleBasedVisibility() ); mScaleRangeWidget->setScaleRange( 1.0 / layer->maximumScale(), 1.0 / layer->minimumScale() ); // caution: layer uses scale denoms, widget uses true scales mShowAllCheckBox->setChecked( true ); mDataDefinedVisibilityGroupBox->setChecked( false ); switch ( layerType ) { case QGis::Point: mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( QgsDiagramLayerSettings::AroundPoint ) ); break; case QGis::Line: mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( QgsDiagramLayerSettings::Line ) ); chkLineAbove->setChecked( true ); chkLineBelow->setChecked( false ); chkLineOn->setChecked( false ); chkLineOrientationDependent->setChecked( false ); break; case QGis::Polygon: mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( QgsDiagramLayerSettings::AroundPoint ) ); break; case QGis::UnknownGeometry: case QGis::NoGeometry: break; } mBackgroundColorButton->setColor( QColor( 255, 255, 255, 255 ) ); //force a refresh of widget status to match diagram type on_mDiagramTypeComboBox_currentIndexChanged( mDiagramTypeComboBox->currentIndex() ); } else // already a diagram renderer present { //single category renderer or interpolated one? if ( dr->rendererName() == "SingleCategory" ) { mFixedSizeRadio->setChecked( true ); } else { mAttributeBasedScalingRadio->setChecked( true ); } mDiagramSizeSpinBox->setEnabled( mFixedSizeRadio->isChecked() ); mLinearScaleFrame->setEnabled( mAttributeBasedScalingRadio->isChecked() ); //assume single category or linearly interpolated diagram renderer for now QList<QgsDiagramSettings> settingList = dr->diagramSettings(); if ( !settingList.isEmpty() ) { mDiagramFrame->setEnabled( settingList.at( 0 ).enabled ); mDiagramFont = settingList.at( 0 ).font; QSizeF size = settingList.at( 0 ).size; mBackgroundColorButton->setColor( settingList.at( 0 ).backgroundColor ); mTransparencySpinBox->setValue( settingList.at( 0 ).transparency * 100.0 / 255.0 ); mTransparencySlider->setValue( mTransparencySpinBox->value() ); mDiagramPenColorButton->setColor( settingList.at( 0 ).penColor ); mPenWidthSpinBox->setValue( settingList.at( 0 ).penWidth ); mDiagramSizeSpinBox->setValue(( size.width() + size.height() ) / 2.0 ); // caution: layer uses scale denoms, widget uses true scales mScaleRangeWidget->setScaleRange( 1.0 / ( settingList.at( 0 ).maxScaleDenominator > 0 ? settingList.at( 0 ).maxScaleDenominator : layer->maximumScale() ), 1.0 / ( settingList.at( 0 ).minScaleDenominator > 0 ? settingList.at( 0 ).minScaleDenominator : layer->minimumScale() ) ); mScaleVisibilityGroupBox->setChecked( settingList.at( 0 ).scaleBasedVisibility ); mDiagramUnitComboBox->setUnit( settingList.at( 0 ).sizeType ); mDiagramUnitComboBox->setMapUnitScale( settingList.at( 0 ).sizeScale ); mDiagramLineUnitComboBox->setUnit( settingList.at( 0 ).lineSizeUnit ); mDiagramLineUnitComboBox->setMapUnitScale( settingList.at( 0 ).lineSizeScale ); if ( settingList.at( 0 ).labelPlacementMethod == QgsDiagramSettings::Height ) { mLabelPlacementComboBox->setCurrentIndex( 0 ); } else { mLabelPlacementComboBox->setCurrentIndex( 1 ); } mAngleOffsetComboBox->setCurrentIndex( mAngleOffsetComboBox->findData( settingList.at( 0 ).angleOffset ) ); mOrientationLeftButton->setProperty( "direction", QgsDiagramSettings::Left ); mOrientationRightButton->setProperty( "direction", QgsDiagramSettings::Right ); mOrientationUpButton->setProperty( "direction", QgsDiagramSettings::Up ); mOrientationDownButton->setProperty( "direction", QgsDiagramSettings::Down ); switch ( settingList.at( 0 ).diagramOrientation ) { case QgsDiagramSettings::Left: mOrientationLeftButton->setChecked( true ); break; case QgsDiagramSettings::Right: mOrientationRightButton->setChecked( true ); break; case QgsDiagramSettings::Up: mOrientationUpButton->setChecked( true ); break; case QgsDiagramSettings::Down: mOrientationDownButton->setChecked( true ); break; } mBarWidthSpinBox->setValue( settingList.at( 0 ).barWidth ); mIncreaseSmallDiagramsCheck->setChecked( settingList.at( 0 ).minimumSize != 0 ); mIncreaseMinimumSizeSpinBox->setEnabled( mIncreaseSmallDiagramsCheck->isChecked() ); mIncreaseMinimumSizeLabel->setEnabled( mIncreaseSmallDiagramsCheck->isChecked() ); mIncreaseMinimumSizeSpinBox->setValue( settingList.at( 0 ).minimumSize ); if ( settingList.at( 0 ).scaleByArea ) { mScaleDependencyComboBox->setCurrentIndex( 0 ); } else { mScaleDependencyComboBox->setCurrentIndex( 1 ); } QList< QColor > categoryColors = settingList.at( 0 ).categoryColors; QList< QString > categoryAttributes = settingList.at( 0 ).categoryAttributes; QList< QString > categoryLabels = settingList.at( 0 ).categoryLabels; QList< QString >::const_iterator catIt = categoryAttributes.constBegin(); QList< QColor >::const_iterator coIt = categoryColors.constBegin(); QList< QString >::const_iterator labIt = categoryLabels.constBegin(); for ( ; catIt != categoryAttributes.constEnd(); ++catIt, ++coIt, ++labIt ) { QTreeWidgetItem *newItem = new QTreeWidgetItem( mDiagramAttributesTreeWidget ); newItem->setText( 0, *catIt ); newItem->setData( 0, Qt::UserRole, *catIt ); newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled ); QColor col( *coIt ); col.setAlpha( 255 ); newItem->setBackground( 1, QBrush( col ) ); newItem->setText( 2, *labIt ); newItem->setFlags( newItem->flags() | Qt::ItemIsEditable ); } } if ( dr->rendererName() == "LinearlyInterpolated" ) { const QgsLinearlyInterpolatedDiagramRenderer* lidr = dynamic_cast<const QgsLinearlyInterpolatedDiagramRenderer*>( dr ); if ( lidr ) { mDiagramSizeSpinBox->setEnabled( false ); mLinearScaleFrame->setEnabled( true ); mMaxValueSpinBox->setValue( lidr->upperValue() ); mSizeSpinBox->setValue(( lidr->upperSize().width() + lidr->upperSize().height() ) / 2 ); if ( lidr->classificationAttributeIsExpression() ) { mSizeFieldExpressionWidget->setField( lidr->classificationAttributeExpression() ); } else { mSizeFieldExpressionWidget->setField( mLayer->fields().at( lidr->classificationAttribute() ).name() ); } } } const QgsDiagramLayerSettings *dls = layer->diagramLayerSettings(); if ( dls ) { mDiagramDistanceSpinBox->setValue( dls->distance() ); mPrioritySlider->setValue( dls->getPriority() ); mZIndexSpinBox->setValue( dls->getZIndex() ); mDataDefinedXComboBox->setCurrentIndex( mDataDefinedXComboBox->findData( dls->xPosColumn ) ); mDataDefinedYComboBox->setCurrentIndex( mDataDefinedYComboBox->findData( dls->yPosColumn ) ); if ( dls->xPosColumn != -1 || dls->yPosColumn != -1 ) { mDataDefinedPositionGroupBox->setChecked( true ); } mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( dls->getPlacement() ) ); chkLineAbove->setChecked( dls->linePlacementFlags() & QgsDiagramLayerSettings::AboveLine ); chkLineBelow->setChecked( dls->linePlacementFlags() & QgsDiagramLayerSettings::BelowLine ); chkLineOn->setChecked( dls->linePlacementFlags() & QgsDiagramLayerSettings::OnLine ); if ( !( dls->linePlacementFlags() & QgsDiagramLayerSettings::MapOrientation ) ) chkLineOrientationDependent->setChecked( true ); mShowAllCheckBox->setChecked( dls->showAllDiagrams() ); mDataDefinedVisibilityComboBox->setCurrentIndex( mDataDefinedVisibilityComboBox->findData( dls->showColumn ) ); if ( dls->showColumn != -1 ) { mDataDefinedVisibilityGroupBox->setChecked( true ); } } if ( dr->diagram() ) { mDiagramType = dr->diagram()->diagramName(); mDiagramTypeComboBox->blockSignals( true ); mDiagramTypeComboBox->setCurrentIndex( settingList.at( 0 ).enabled ? mDiagramTypeComboBox->findData( mDiagramType ) : 0 ); mDiagramTypeComboBox->blockSignals( false ); //force a refresh of widget status to match diagram type on_mDiagramTypeComboBox_currentIndexChanged( mDiagramTypeComboBox->currentIndex() ); if ( mDiagramTypeComboBox->currentIndex() == -1 ) { QMessageBox::warning( this, tr( "Unknown diagram type." ), tr( "The diagram type '%1' is unknown. A default type is selected for you." ).arg( mDiagramType ), QMessageBox::Ok ); mDiagramTypeComboBox->setCurrentIndex( mDiagramTypeComboBox->findData( DIAGRAM_NAME_PIE ) ); } } } // if ( !dr ) connect( mAddAttributeExpression, SIGNAL( clicked() ), this, SLOT( showAddAttributeExpressionDialog() ) ); connect( mTransparencySlider, SIGNAL( valueChanged( int ) ), mTransparencySpinBox, SLOT( setValue( int ) ) ); connect( mTransparencySpinBox, SIGNAL( valueChanged( int ) ), mTransparencySlider, SLOT( setValue( int ) ) ); }
QtAsteriskDesktopMain::QtAsteriskDesktopMain(QWidget *parent) : QMainWindow(parent), ui(new Ui::QtAsteriskDesktopMain) { _instance = this; _skipEvents.append("VarSet"); _skipEvents.append("Newexten"); _phoneFeatures = NULL; ui->setupUi(this); _chanMap = new QMap<QString, AstChannel*>(); _parkedMap = new QMap<QString, AstParkedCall*>(); _callMap = new QMap<QString, AdmCallWidget*>(); _extensionMap = new QMap<QString, AdmExtensionWidget *>(); _mySipPeerMap = new QMap<QString, AstSipPeer*>(); _sipPeerMap = new QMap<QString, AstSipPeer*>(); _showSipPeerActionId = new QMap<QString, AstSipPeer*>(); _extensionStateActionId = new QMap<QString, AstSipPeer*>(); _loginActionId = QString(); _sipPeersActionId = QString(); _statusIcon = new StatusIcon(this); ui->statusBar->addPermanentWidget(_statusIcon); /*Connect the Menu Actions*/ connect(ui->_actionExit, SIGNAL(triggered()), this, SLOT(sExit())); connect(ui->_actionPreferences, SIGNAL(triggered()), this, SLOT(sPreferences())); connect(ui->_actionPhoneFeatures, SIGNAL(triggered()), this, SLOT(sPhoneFeatures())); _ami = new AsteriskManager(this); connect( _ami, SIGNAL(connected()), this, SLOT(asteriskConnected()) ); connect(_ami, SIGNAL(disconnected()), this, SLOT(asteriskDisconnected()) ); connect(_ami, SIGNAL(responseSent(AsteriskManager::Response,QVariantMap,QString)), this, SLOT(asteriskResponseSent(AsteriskManager::Response,QVariantMap,QString)) ); connect(_ami, SIGNAL(eventGenerated(AsteriskManager::Event,QVariantMap)), this, SLOT(asteriskEventGenerated(AsteriskManager::Event,QVariantMap)) ); QSettings settings; settings.beginGroup("AMI"); if(settings.contains(AmiPref::getName(AmiPref::host)) && settings.contains(AmiPref::getName(AmiPref::port))) { bool valid = false; QString host = settings.value(AmiPref::getName(AmiPref::host)).toString(); uint port = settings.value(AmiPref::getName(AmiPref::port)).toUInt(&valid); if(valid) { _ami->connectToHost(host, port); bool connected = _ami->waitForConnected(60000); qDebug() << "connected: " << connected; qDebug() << _ami->socketType(); qDebug() << _ami->peerName(); qDebug() << _ami->peerAddress().toIPv4Address(); qDebug() << _ami->peerPort(); if(!connected) { qDebug() << _ami->errorString(); _ami->connectToHost(host, port); bool connected = _ami->waitForConnected(60000); qDebug() << "connected: " << connected; qDebug() << _ami->socketType(); qDebug() << _ami->peerName(); qDebug() << _ami->peerAddress().toIPv4Address(); qDebug() << _ami->peerPort(); if(!connected) { qDebug() << _ami->errorString(); } } } else asteriskDisconnected(); } else asteriskDisconnected(); settings.endGroup(); if(settings.contains("DEVICES/default")) { AstChanParts cp(settings.value("DEVICES/default").toString()); if(cp.isValid()) { ui->_extStatus->setExten(cp.getExten()); } } }
// Writes all missing QSettings with their default values void OptionsModel::Init() { QSettings settings; // Ensure restart flag is unset on client startup setRestartRequired(false); // These are Qt-only settings: // Window if (!settings.contains("fMinimizeToTray")) settings.setValue("fMinimizeToTray", false); fMinimizeToTray = settings.value("fMinimizeToTray").toBool(); if (!settings.contains("fMinimizeOnClose")) settings.setValue("fMinimizeOnClose", false); fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool(); // Display if (!settings.contains("nDisplayUnit")) settings.setValue("nDisplayUnit", AstroCoinUnits::BTC); nDisplayUnit = settings.value("nDisplayUnit").toInt(); if (!settings.contains("bDisplayAddresses")) settings.setValue("bDisplayAddresses", false); bDisplayAddresses = settings.value("bDisplayAddresses", false).toBool(); if (!settings.contains("fCoinControlFeatures")) settings.setValue("fCoinControlFeatures", false); fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool(); // These are shared with the core or have a command-line parameter // and we want command-line parameters to overwrite the GUI settings. // // If setting doesn't exist create it with defaults. // // If SoftSetArg() or SoftSetBoolArg() return false we were overridden // by command-line and show this in the UI. // Main #ifdef ENABLE_WALLET if (!settings.contains("nTransactionFee")) settings.setValue("nTransactionFee", 0); nTransactionFee = settings.value("nTransactionFee").toLongLong(); // if -paytxfee is set, this will be overridden later in init.cpp if (mapArgs.count("-paytxfee")) strOverriddenByCommandLine += "-paytxfee "; if (!settings.contains("bSpendZeroConfChange")) settings.setValue("bSpendZeroConfChange", true); if (!SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool())) strOverriddenByCommandLine += "-spendzeroconfchange "; #endif if (!settings.contains("nDatabaseCache")) settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache); if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString())) strOverriddenByCommandLine += "-dbcache "; if (!settings.contains("nThreadsScriptVerif")) settings.setValue("nThreadsScriptVerif", 0); if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString())) strOverriddenByCommandLine += "-par "; // Network if (!settings.contains("fUseUPnP")) #ifdef USE_UPNP settings.setValue("fUseUPnP", true); #else settings.setValue("fUseUPnP", false); #endif if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool())) strOverriddenByCommandLine += "-upnp "; if (!settings.contains("fUseProxy")) settings.setValue("fUseProxy", false); if (!settings.contains("addrProxy")) settings.setValue("addrProxy", "127.0.0.1:9050"); // Only try to set -proxy, if user has enabled fUseProxy if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString())) strOverriddenByCommandLine += "-proxy "; if (!settings.contains("nSocksVersion")) settings.setValue("nSocksVersion", 5); // Only try to set -socks, if user has enabled fUseProxy if (settings.value("fUseProxy").toBool() && !SoftSetArg("-socks", settings.value("nSocksVersion").toString().toStdString())) strOverriddenByCommandLine += "-socks "; // Display if (!settings.contains("language")) settings.setValue("language", ""); if (!SoftSetArg("-lang", settings.value("language").toString().toStdString())) strOverriddenByCommandLine += "-lang"; language = settings.value("language").toString(); }
void MainWindow::setupWidgets() { // ligne à supprimer lorsque la doc util sera disponible actionUserManual->setVisible(false); aboutDial = new AboutDialog(this); confDial = new ConfigDialog(this); logDial = LogDialog::instance(); searchDialog = new SearchDialog(this); //printDialog = new QPrintDialog(this); QAction *a; recentActions.clear(); for(int i=0; i<10; i++) { a = new QAction(this); a->setVisible(false); connect(a, SIGNAL(triggered()), this, SLOT(openRecent())); recentActions << a; } menuRecent_files->addActions(recentActions); menuRecent_files->addSeparator(); menuRecent_files->addAction(actionClearRecent); actionPlugins->setVisible(false); actionMap[AbstractTabWidget::Copy] = actionCopy; actionMap[AbstractTabWidget::Cut] = actionCut; actionMap[AbstractTabWidget::Paste] = actionPaste; actionMap[AbstractTabWidget::Print] = actionPrint; actionMap[AbstractTabWidget::Redo] = actionRedo; actionMap[AbstractTabWidget::Save] = actionSaveQuery; actionMap[AbstractTabWidget::SaveAs] = actionSaveQueryAs; actionMap[AbstractTabWidget::Search] = actionSearch; actionMap[AbstractTabWidget::SelectAll] = actionSelect_all; actionMap[AbstractTabWidget::Undo] = actionUndo; QSettings s; s.beginGroup("mainwindow"); if(s.contains("size")) resize(s.value("size").toSize()); if(s.contains("position")) move(s.value("position").toPoint()); if(s.value("maximized", false).toBool()) setWindowState(Qt::WindowMaximized); // removeDockWidget(dockWidget); int corner = s.value("maindock_area", 1).toInt(); switch (corner) { case 1: addDockWidget(Qt::LeftDockWidgetArea, dockWidget); break; case 2: addDockWidget(Qt::RightDockWidgetArea, dockWidget); break; case 4: addDockWidget(Qt::TopDockWidgetArea, dockWidget); break; case 8: addDockWidget(Qt::BottomDockWidgetArea, dockWidget); break; } if (s.contains("maindock_size")) { dockWidget->resize(s.value("maindock_size").toSize()); } queriesStatusLabel = new QLabel("", this); QMainWindow::statusBar()->addPermanentWidget(queriesStatusLabel); tooltipButton->setChecked(s.value("tooltips", true).toBool()); tooltipFrame->setVisible(s.value("tooltips", true).toBool()); s.endGroup(); int count = s.beginReadArray("recentfiles"); recentFiles.clear(); for(int i=0; i<count && i<10; i++) { s.setArrayIndex(i); recentFiles << s.value("entry").toString(); } s.endArray(); refreshRecent(); #if defined(Q_WS_X11) QString lang = QLocale::system().name().left(2).toLower(); QString url = QString(QString(PREFIX) + "/share/dbmaster/index_%1.html") .arg(lang); if(!QFile::exists(url)) url = QString(QString(PREFIX) + "/share/dbmaster/index_en.html"); textBrowser->setSource(url); #endif #if defined(Q_WS_WIN) QString lang = QLocale::system().name().left(2).toLower(); QString url = QString("share\\index_%1.html").arg(lang); if(!QFile::exists(url)) url = QString("share\\index_en.html"); textBrowser->setSource(url); #endif #if QT_VERSION >= 0x040500 // ensures compatibility with Qt 4.4 tabWidget->setMovable(true); tabWidget->setTabsClosable(true); // actionCloseTab->setVisible(false); mainToolBar->removeAction(actionCloseTab); #endif // loading icons from current theme actionAbout->setIcon( IconManager::get("help-about")); actionAddDb->setIcon( IconManager::get("db_add")); actionClearRecent->setIcon( IconManager::get("edit-clear")); actionCloseTab->setIcon( IconManager::get("window-close")); actionCopy->setIcon( IconManager::get("edit-copy")); actionCut->setIcon( IconManager::get("edit-cut")); actionExit->setIcon( IconManager::get("application-exit")); actionNewQuery->setIcon( IconManager::get("document-new")); actionOpenQuery->setIcon( IconManager::get("document-open")); actionPaste->setIcon( IconManager::get("edit-paste")); actionPreferences->setIcon( IconManager::get("preferences")); actionPrint->setIcon( IconManager::get("document-print")); actionRedo->setIcon( IconManager::get("edit-redo")); actionSaveQuery->setIcon( IconManager::get("document-save")); actionSaveQueryAs->setIcon( IconManager::get("document-save-as")); actionSearch->setIcon( IconManager::get("edit-find")); actionUndo->setIcon( IconManager::get("edit-undo")); tooltipButton->setIcon( IconManager::get("help-faq")); tabWidget->setTabIcon(0, IconManager::get("go-home")); }
void QMLManager::syncLoadFromCloud() { QSettings s; QString cloudMarker = QLatin1Literal("loadFromCloud") + QString(prefs.cloud_storage_email); m_loadFromCloud = s.contains(cloudMarker) && s.value(cloudMarker).toBool(); }
void UpdateManager::requestReceived() { bool haveNewVersion = false; QMessageBox msgbox; QString msgTitle = tr("Check for updates."); QString msgText = "<h3>" + tr("Subsurface was unable to check for updates.") + "</h3>"; QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender()); if (reply->error() != QNetworkReply::NoError) { //Network Error msgText = msgText + "<br/><b>" + tr("The following error occurred:") + "</b><br/>" + reply->errorString() + "<br/><br/><b>" + tr("Please check your internet connection.") + "</b>"; } else { //No network error QString responseBody(reply->readAll()); QString responseLink; if (responseBody.contains('"')) responseLink = responseBody.split("\"").at(1); msgbox.setIcon(QMessageBox::Information); if (responseBody == "OK") { msgText = tr("You are using the latest version of Subsurface."); } else if (responseBody.startsWith("[\"http")) { haveNewVersion = true; msgText = tr("A new version of Subsurface is available.<br/>Click on:<br/><a href=\"%1\">%1</a><br/> to download it.") .arg(responseLink); } else if (responseBody.startsWith("Latest version")) { // the webservice backend doesn't localize - but it's easy enough to just replace the // strings that it is likely to send back haveNewVersion = true; msgText = QString("<b>") + tr("A new version of Subsurface is available.") + QString("</b><br/><br/>") + tr("Latest version is %1, please check %2 our download page %3 for information in how to update.") .arg(responseLink).arg("<a href=\"http://subsurface-divelog.org/download\">").arg("</a>"); } else { // the webservice backend doesn't localize - but it's easy enough to just replace the // strings that it is likely to send back if (!responseBody.contains("latest development") && !responseBody.contains("newer") && !responseBody.contains("beta", Qt::CaseInsensitive)) haveNewVersion = true; if (responseBody.contains("Newest release version is ")) responseBody.replace("Newest release version is ", tr("Newest release version is ")); msgText = tr("The server returned the following information:").append("<br/><br/>").append(responseBody); msgbox.setIcon(QMessageBox::Warning); } } #ifndef SUBSURFACE_MOBILE if (haveNewVersion || !isAutomaticCheck) { msgbox.setWindowTitle(msgTitle); msgbox.setWindowIcon(QIcon(":/subsurface-icon")); msgbox.setText(msgText); msgbox.setTextFormat(Qt::RichText); msgbox.exec(); } if (isAutomaticCheck) { QSettings settings; settings.beginGroup("UpdateManager"); if (!settings.contains("DontCheckForUpdates")) { // we allow an opt out of future checks QMessageBox response(MainWindow::instance()); QString message = tr("Subsurface is checking every two weeks if a new version is available. If you don't want Subsurface to continue checking, please click Decline."); response.addButton(tr("Decline"), QMessageBox::RejectRole); response.addButton(tr("Accept"), QMessageBox::AcceptRole); response.setText(message); response.setWindowTitle(tr("Automatic check for updates")); response.setIcon(QMessageBox::Question); response.setWindowModality(Qt::WindowModal); int ret = response.exec(); if (ret == QMessageBox::Accepted) settings.setValue("DontCheckForUpdates", "FALSE"); else settings.setValue("DontCheckForUpdates", "TRUE"); } } #endif }
// Writes all missing QSettings with their default values void OptionsModel::Init(bool resetSettings) { if (resetSettings) Reset(); this->resetSettings = resetSettings; QSettings settings; // Ensure restart flag is unset on client startup setRestartRequired(false); // These are Qt-only settings: // Window if (!settings.contains("fHideTrayIcon")) settings.setValue("fHideTrayIcon", false); fHideTrayIcon = settings.value("fHideTrayIcon").toBool(); Q_EMIT hideTrayIconChanged(fHideTrayIcon); if (!settings.contains("fMinimizeToTray")) settings.setValue("fMinimizeToTray", false); fMinimizeToTray = settings.value("fMinimizeToTray").toBool() && !fHideTrayIcon; if (!settings.contains("fMinimizeOnClose")) settings.setValue("fMinimizeOnClose", false); fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool(); // Display if (!settings.contains("nDisplayUnit")) settings.setValue("nDisplayUnit", BitcoinUnits::DASH); nDisplayUnit = settings.value("nDisplayUnit").toInt(); if (!settings.contains("strThirdPartyTxUrls")) settings.setValue("strThirdPartyTxUrls", ""); strThirdPartyTxUrls = settings.value("strThirdPartyTxUrls", "").toString(); if (!settings.contains("fCoinControlFeatures")) settings.setValue("fCoinControlFeatures", false); fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool(); if (!settings.contains("digits")) settings.setValue("digits", "2"); if (!settings.contains("theme")) settings.setValue("theme", ""); if (!settings.contains("fShowMasternodesTab")) settings.setValue("fShowMasternodesTab", masternodeConfig.getCount()); if (!settings.contains("fShowAdvancedPSUI")) settings.setValue("fShowAdvancedPSUI", false); fShowAdvancedPSUI = settings.value("fShowAdvancedPSUI", false).toBool(); if (!settings.contains("fLowKeysWarning")) settings.setValue("fLowKeysWarning", true); // These are shared with the core or have a command-line parameter // and we want command-line parameters to overwrite the GUI settings. // // If setting doesn't exist create it with defaults. // // If SoftSetArg() or SoftSetBoolArg() return false we were overridden // by command-line and show this in the UI. // Main if (!settings.contains("nDatabaseCache")) settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache); if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString())) addOverriddenOption("-dbcache"); if (!settings.contains("nThreadsScriptVerif")) settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS); if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString())) addOverriddenOption("-par"); // Wallet #ifdef ENABLE_WALLET if (!settings.contains("bSpendZeroConfChange")) settings.setValue("bSpendZeroConfChange", true); if (!SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool())) addOverriddenOption("-spendzeroconfchange"); // PrivateSend if (!settings.contains("nPrivateSendRounds")) settings.setValue("nPrivateSendRounds", DEFAULT_PRIVATESEND_ROUNDS); if (!SoftSetArg("-privatesendrounds", settings.value("nPrivateSendRounds").toString().toStdString())) addOverriddenOption("-privatesendrounds"); privateSendClient.nPrivateSendRounds = settings.value("nPrivateSendRounds").toInt(); if (!settings.contains("nPrivateSendAmount")) { // for migration from old settings if (!settings.contains("nAnonymizeDashAmount")) settings.setValue("nPrivateSendAmount", DEFAULT_PRIVATESEND_AMOUNT); else settings.setValue("nPrivateSendAmount", settings.value("nAnonymizeDashAmount").toInt()); } if (!SoftSetArg("-privatesendamount", settings.value("nPrivateSendAmount").toString().toStdString())) addOverriddenOption("-privatesendamount"); privateSendClient.nPrivateSendAmount = settings.value("nPrivateSendAmount").toInt(); if (!settings.contains("fPrivateSendMultiSession")) settings.setValue("fPrivateSendMultiSession", DEFAULT_PRIVATESEND_MULTISESSION); if (!SoftSetBoolArg("-privatesendmultisession", settings.value("fPrivateSendMultiSession").toBool())) addOverriddenOption("-privatesendmultisession"); privateSendClient.fPrivateSendMultiSession = settings.value("fPrivateSendMultiSession").toBool(); #endif // Network if (!settings.contains("fUseUPnP")) settings.setValue("fUseUPnP", DEFAULT_UPNP); if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool())) addOverriddenOption("-upnp"); if (!settings.contains("fListen")) settings.setValue("fListen", DEFAULT_LISTEN); if (!SoftSetBoolArg("-listen", settings.value("fListen").toBool())) addOverriddenOption("-listen"); if (!settings.contains("fUseProxy")) settings.setValue("fUseProxy", false); if (!settings.contains("addrProxy")) settings.setValue("addrProxy", "127.0.0.1:9050"); // Only try to set -proxy, if user has enabled fUseProxy if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString())) addOverriddenOption("-proxy"); else if(!settings.value("fUseProxy").toBool() && !GetArg("-proxy", "").empty()) addOverriddenOption("-proxy"); if (!settings.contains("fUseSeparateProxyTor")) settings.setValue("fUseSeparateProxyTor", false); if (!settings.contains("addrSeparateProxyTor")) settings.setValue("addrSeparateProxyTor", "127.0.0.1:9050"); // Only try to set -onion, if user has enabled fUseSeparateProxyTor if (settings.value("fUseSeparateProxyTor").toBool() && !SoftSetArg("-onion", settings.value("addrSeparateProxyTor").toString().toStdString())) addOverriddenOption("-onion"); else if(!settings.value("fUseSeparateProxyTor").toBool() && !GetArg("-onion", "").empty()) addOverriddenOption("-onion"); // Display if (!settings.contains("language")) settings.setValue("language", ""); if (!SoftSetArg("-lang", settings.value("language").toString().toStdString())) addOverriddenOption("-lang"); language = settings.value("language").toString(); }
void QgsNewHttpConnection::accept() { QSettings settings; QString key = mBaseKey + txtName->text(); QString credentialsKey = "/Qgis/" + mCredentialsBaseKey + '/' + txtName->text(); // warn if entry was renamed to an existing connection if (( mOriginalConnName.isNull() || mOriginalConnName.compare( txtName->text(), Qt::CaseInsensitive ) != 0 ) && settings.contains( key + "/url" ) && QMessageBox::question( this, tr( "Save connection" ), tr( "Should the existing connection %1 be overwritten?" ).arg( txtName->text() ), QMessageBox::Ok | QMessageBox::Cancel ) == QMessageBox::Cancel ) { return; } if ( !txtPassword->text().isEmpty() && QMessageBox::question( this, tr( "Saving passwords" ), tr( "WARNING: You have entered a password. It will be stored in plain text in your project files and in your home directory on Unix-like systems, or in your user profile on Windows. If you do not want this to happen, please press the Cancel button.\nNote: giving the password is optional. It will be requested interactivly, when needed." ), QMessageBox::Ok | QMessageBox::Cancel ) == QMessageBox::Cancel ) { return; } // on rename delete original entry first if ( !mOriginalConnName.isNull() && mOriginalConnName != key ) { settings.remove( mBaseKey + mOriginalConnName ); settings.remove( "/Qgis/" + mCredentialsBaseKey + '/' + mOriginalConnName ); settings.sync(); } QUrl url( txtUrl->text().trimmed() ); const QList< QPair<QByteArray, QByteArray> > &items = url.encodedQueryItems(); QHash< QString, QPair<QByteArray, QByteArray> > params; for ( QList< QPair<QByteArray, QByteArray> >::const_iterator it = items.constBegin(); it != items.constEnd(); ++it ) { params.insert( QString( it->first ).toUpper(), *it ); } if ( params["SERVICE"].second.toUpper() == "WMS" || params["SERVICE"].second.toUpper() == "WFS" || params["SERVICE"].second.toUpper() == "WCS" ) { url.removeEncodedQueryItem( params["SERVICE"].first ); url.removeEncodedQueryItem( params["REQUEST"].first ); url.removeEncodedQueryItem( params["FORMAT"].first ); } if ( url.encodedPath().isEmpty() ) { url.setEncodedPath( "/" ); } settings.setValue( key + "/url", url.toString() ); if ( mBaseKey == "/Qgis/connections-wms/" || mBaseKey == "/Qgis/connections-wcs/" || mBaseKey == "/Qgis/connections-wfs/" ) { settings.setValue( key + "/ignoreAxisOrientation", cbxIgnoreAxisOrientation->isChecked() ); settings.setValue( key + "/invertAxisOrientation", cbxInvertAxisOrientation->isChecked() ); } if ( mBaseKey == "/Qgis/connections-wms/" || mBaseKey == "/Qgis/connections-wcs/" ) { settings.setValue( key + "/ignoreGetMapURI", cbxIgnoreGetMapURI->isChecked() ); settings.setValue( key + "/smoothPixmapTransform", cbxSmoothPixmapTransform->isChecked() ); int dpiMode = 0; switch ( cmbDpiMode->currentIndex() ) { case 0: // all => QGIS|UMN|GeoServer dpiMode = 7; break; case 1: // off dpiMode = 0; break; case 2: // QGIS dpiMode = 1; break; case 3: // UMN dpiMode = 2; break; case 4: // GeoServer dpiMode = 4; break; } settings.setValue( key + "/dpiMode", dpiMode ); } if ( mBaseKey == "/Qgis/connections-wms/" ) { settings.setValue( key + "/ignoreGetFeatureInfoURI", cbxIgnoreGetFeatureInfoURI->isChecked() ); } if ( mBaseKey == "/Qgis/connections-wfs/" ) { QString version = "auto"; switch ( cmbVersion->currentIndex() ) { case 0: version = "auto"; break; case 1: version = "1.0.0"; break; case 2: version = "1.1.0"; break; case 3: version = "2.0.0"; break; } settings.setValue( key + "/version", version ); settings.setValue( key + "/maxnumfeatures", txtMaxNumFeatures->text() ); } settings.setValue( key + "/referer", txtReferer->text() ); settings.setValue( credentialsKey + "/username", txtUserName->text() ); settings.setValue( credentialsKey + "/password", txtPassword->text() ); settings.setValue( credentialsKey + "/authcfg", mAuthConfigSelect->configId() ); settings.setValue( mBaseKey + "/selected", txtName->text() ); QDialog::accept(); }
// Writes all missing QSettings with their default values void OptionsModel::Init(bool resetSettings) { if (resetSettings) Reset(); QSettings settings; // Ensure restart flag is unset on client startup setRestartRequired(false); // These are Qt-only settings: // Window if (!settings.contains("fMinimizeToTray")) settings.setValue("fMinimizeToTray", false); fMinimizeToTray = settings.value("fMinimizeToTray").toBool(); if (!settings.contains("fMinimizeOnClose")) settings.setValue("fMinimizeOnClose", false); fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool(); // Display if (!settings.contains("nDisplayUnit")) settings.setValue("nDisplayUnit", BitcoinUnits::BTC); nDisplayUnit = settings.value("nDisplayUnit").toInt(); if (!settings.contains("strThirdPartyTxUrls")) settings.setValue("strThirdPartyTxUrls", ""); strThirdPartyTxUrls = settings.value("strThirdPartyTxUrls", "").toString(); if (!settings.contains("fCoinControlFeatures")) settings.setValue("fCoinControlFeatures", false); fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool(); // These are shared with the core or have a command-line parameter // and we want command-line parameters to overwrite the GUI settings. // // If setting doesn't exist create it with defaults. // // If SoftSetArg() or SoftSetBoolArg() return false we were overridden // by command-line and show this in the UI. // Main if (!settings.contains("nDatabaseCache")) settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache); if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString())) addOverriddenOption("-dbcache"); if (!settings.contains("nThreadsScriptVerif")) settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS); if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString())) addOverriddenOption("-par"); if (!settings.contains("blockSizeAcceptLimitBytes")) settings.setValue("blockSizeAcceptLimitBytes", DEFAULT_BLOCK_ACCEPT_SIZE); if (mapArgs.count("-blocksizeacceptlimit")) addOverriddenOption("-blocksizeacceptlimit"); else if (mapArgs.count("-blocksizeacceptlimitbytes")) addOverriddenOption("-blocksizeacceptlimitbytes"); else if (mapArgs.count("-excessiveblocksize")) addOverriddenOption("-excessiveblocksize"); else { QVariant limit = settings.value("blockSizeAcceptLimitBytes"); if (Application::uahfChainState() != Application::UAHFDisabled) { bool ok; int value = settings.value("blockSizeAcceptLimitBytes").toInt(&ok); if (ok && value < 8000000) limit = QVariant(8000000); } SoftSetArg("-blocksizeacceptlimitbytes", limit.toString().toStdString()); } // Wallet #ifdef ENABLE_WALLET if (!settings.contains("bSpendZeroConfChange")) settings.setValue("bSpendZeroConfChange", true); if (!SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool())) addOverriddenOption("-spendzeroconfchange"); #endif // Network if (!settings.contains("fUseUPnP")) settings.setValue("fUseUPnP", DEFAULT_UPNP); if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool())) addOverriddenOption("-upnp"); if (!settings.contains("fListen")) settings.setValue("fListen", DEFAULT_LISTEN); if (!SoftSetBoolArg("-listen", settings.value("fListen").toBool())) addOverriddenOption("-listen"); if (!settings.contains("fUseProxy")) settings.setValue("fUseProxy", false); if (!settings.contains("addrProxy")) settings.setValue("addrProxy", "127.0.0.1:9050"); // Only try to set -proxy, if user has enabled fUseProxy if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString())) addOverriddenOption("-proxy"); else if(!settings.value("fUseProxy").toBool() && !GetArg("-proxy", "").empty()) addOverriddenOption("-proxy"); if (!settings.contains("fUseSeparateProxyTor")) settings.setValue("fUseSeparateProxyTor", false); if (!settings.contains("addrSeparateProxyTor")) settings.setValue("addrSeparateProxyTor", "127.0.0.1:9050"); // Only try to set -onion, if user has enabled fUseSeparateProxyTor if (settings.value("fUseSeparateProxyTor").toBool() && !SoftSetArg("-onion", settings.value("addrSeparateProxyTor").toString().toStdString())) addOverriddenOption("-onion"); else if(!settings.value("fUseSeparateProxyTor").toBool() && !GetArg("-onion", "").empty()) addOverriddenOption("-onion"); // Display if (!settings.contains("language")) settings.setValue("language", ""); if (!SoftSetArg("-lang", settings.value("language").toString().toStdString())) addOverriddenOption("-lang"); language = settings.value("language").toString(); }
windowManager::windowManager() : originalImageColorCount_(0), projectFilename_(QString()), hideWindows_(false) { const QString chooserText(tr("Color Chooser (1/4)")); const QString compareText(tr("Color compare (2/4)")); const QString squareText(tr("Square compare (3/4)")); const QString patternText(tr("Pattern (4/4)")); colorChooserAction_ = new QAction(QIcon(":colorChooser.png"), chooserText, this); colorCompareAction_ = new QAction(QIcon(":colorCompare.png"), compareText, this); squareWindowAction_ = new QAction(QIcon(":square.png"), squareText, this); patternWindowAction_ = new QAction(QIcon(":pattern.png"), patternText, this); activeColorChooserAction_ = new QAction(QIcon(":colorChooser_active.png"), chooserText, this); activeColorCompareAction_ = new QAction(QIcon(":colorCompare_active.png"), compareText, this); activeSquareWindowAction_ = new QAction(QIcon(":square_active.png"), squareText, this); activePatternWindowAction_ = new QAction(QIcon(":pattern_active.png"), patternText, this); colorChooserAction_->setEnabled(false); colorChooserAction_->setShortcut(QKeySequence(QString(tr("Ctrl+1")))); colorCompareAction_->setEnabled(false); colorCompareAction_->setShortcut(QKeySequence(QString(tr("Ctrl+2")))); squareWindowAction_->setEnabled(false); squareWindowAction_->setShortcut(QKeySequence(QString(tr("Ctrl+3")))); patternWindowAction_->setEnabled(false); patternWindowAction_->setShortcut(QKeySequence(QString(tr("Ctrl+4")))); windowMenu_ = new QMenu(tr("&Windows")); connect(windowMenu_, SIGNAL(triggered(QAction*)), this, SLOT(displayActionWindow(QAction*))); windowMenu_->addAction(colorChooserAction_); windowMenu_->addSeparator(); windowMenu_->addAction(colorCompareAction_); windowMenu_->addSeparator(); windowMenu_->addAction(squareWindowAction_); windowMenu_->addSeparator(); windowMenu_->addAction(patternWindowAction_); autoShowQuickHelp_ = new QAction(tr("Auto display Quick Help windows"), this); autoShowQuickHelp_->setCheckable(true); // restore the autoShowQuickHelp_ setting if it exists const QSettings settings("cstitch", "cstitch"); if (settings.contains("auto_show_quick_help")) { const bool checked = settings.value("auto_show_quick_help").toBool(); autoShowQuickHelp_->setChecked(checked); } else { autoShowQuickHelp_->setChecked(true); } // make this connection _after_ the initial checkbox has been set or // else quickHelp will be called on a non-existent active window! connect(autoShowQuickHelp_, SIGNAL(toggled(bool )), this, SLOT(autoShowQuickHelp(bool ))); }
void OptionsModel::Init() { QSettings settings; // These are Qt-only settings: nDisplayUnit = settings.value("nDisplayUnit", DarkSilkUnits::DRKSLK).toInt(); fMinimizeToTray = settings.value("fMinimizeToTray", false).toBool(); fMinimizeOnClose = settings.value("fMinimizeOnClose", false).toBool(); fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool(); nTransactionFee = settings.value("nTransactionFee").toLongLong(); nReserveBalance = settings.value("nReserveBalance").toLongLong(); language = settings.value("language", "").toString(); fUseBlackTheme = settings.value("fUseBlackTheme", true).toBool(); if (!settings.contains("nSandstormRounds")) settings.setValue("nSandstormRounds", 2); if (!settings.contains("nAnonymizeDarkSilkAmount")) settings.setValue("nAnonymizeDarkSilkAmount", 1000); nSandstormRounds = settings.value("nSandstormRounds").toLongLong(); nAnonymizeDarkSilkAmount = settings.value("nAnonymizeDarkSilkAmount").toLongLong(); // These are shared with core DarkSilk; we want // command-line options to override the GUI settings: if (settings.contains("fUseUPnP")) SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()); if (settings.contains("addrProxy") && settings.value("fUseProxy").toBool()) SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString()); if (!language.isEmpty()) SoftSetArg("-lang", language.toStdString()); if (settings.contains("nSandstormRounds")) SoftSetArg("-sandstormrounds", settings.value("nSandstormRounds").toString().toStdString()); if (settings.contains("nAnonymizeDarkSilkAmount")) SoftSetArg("-anonymizedarksilkamount", settings.value("nAnonymizeDarkSilkAmount").toString().toStdString()); #ifdef USE_NATIVE_I2P ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME); if (settings.value("useI2POnly", false).toBool()) { mapArgs["-onlynet"] = NATIVE_I2P_NET_STRING; std::vector<std::string>& onlyNets = mapMultiArgs["-onlynet"]; if (std::find(onlyNets.begin(), onlyNets.end(), NATIVE_I2P_NET_STRING) == onlyNets.end()) onlyNets.push_back(NATIVE_I2P_NET_STRING); } if (settings.contains("samhost")) SoftSetArg(I2P_SAM_HOST_PARAM, settings.value("samhost").toString().toStdString()); if (settings.contains("samport")) SoftSetArg(I2P_SAM_PORT_PARAM, settings.value("samport").toString().toStdString()); if (settings.contains("sessionName")) SoftSetArg(I2P_SESSION_NAME_PARAM, settings.value("sessionName").toString().toStdString()); i2pInboundQuantity = settings.value(SAM_NAME_INBOUND_QUANTITY , SAM_DEFAULT_INBOUND_QUANTITY ).toInt(); i2pInboundLength = settings.value(SAM_NAME_INBOUND_LENGTH , SAM_DEFAULT_INBOUND_LENGTH ).toInt(); i2pInboundLengthVariance = settings.value(SAM_NAME_INBOUND_LENGTHVARIANCE , SAM_DEFAULT_INBOUND_LENGTHVARIANCE ).toInt(); i2pInboundBackupQuantity = settings.value(SAM_NAME_INBOUND_BACKUPQUANTITY , SAM_DEFAULT_INBOUND_BACKUPQUANTITY ).toInt(); i2pInboundAllowZeroHop = settings.value(SAM_NAME_INBOUND_ALLOWZEROHOP , SAM_DEFAULT_INBOUND_ALLOWZEROHOP ).toBool(); i2pInboundIPRestriction = settings.value(SAM_NAME_INBOUND_IPRESTRICTION , SAM_DEFAULT_INBOUND_IPRESTRICTION ).toInt(); i2pOutboundQuantity = settings.value(SAM_NAME_OUTBOUND_QUANTITY , SAM_DEFAULT_OUTBOUND_QUANTITY ).toInt(); i2pOutboundLength = settings.value(SAM_NAME_OUTBOUND_LENGTH , SAM_DEFAULT_OUTBOUND_LENGTH ).toInt(); i2pOutboundLengthVariance = settings.value(SAM_NAME_OUTBOUND_LENGTHVARIANCE, SAM_DEFAULT_OUTBOUND_LENGTHVARIANCE).toInt(); i2pOutboundBackupQuantity = settings.value(SAM_NAME_OUTBOUND_BACKUPQUANTITY, SAM_DEFAULT_OUTBOUND_BACKUPQUANTITY).toInt(); i2pOutboundAllowZeroHop = settings.value(SAM_NAME_OUTBOUND_ALLOWZEROHOP , SAM_DEFAULT_OUTBOUND_ALLOWZEROHOP ).toBool(); i2pOutboundIPRestriction = settings.value(SAM_NAME_OUTBOUND_IPRESTRICTION , SAM_DEFAULT_OUTBOUND_IPRESTRICTION ).toInt(); i2pOutboundPriority = settings.value(SAM_NAME_OUTBOUND_PRIORITY , SAM_DEFAULT_OUTBOUND_PRIORITY ).toInt(); std::string i2pOptionsTemp; FormatI2POptionsString(i2pOptionsTemp, SAM_NAME_INBOUND_QUANTITY , std::make_pair(settings.contains(SAM_NAME_INBOUND_QUANTITY ), i2pInboundQuantity)); FormatI2POptionsString(i2pOptionsTemp, SAM_NAME_INBOUND_LENGTH , std::make_pair(settings.contains(SAM_NAME_INBOUND_LENGTH ), i2pInboundLength)); FormatI2POptionsString(i2pOptionsTemp, SAM_NAME_INBOUND_LENGTHVARIANCE , std::make_pair(settings.contains(SAM_NAME_INBOUND_LENGTHVARIANCE ), i2pInboundLengthVariance)); FormatI2POptionsString(i2pOptionsTemp, SAM_NAME_INBOUND_BACKUPQUANTITY , std::make_pair(settings.contains(SAM_NAME_INBOUND_BACKUPQUANTITY ), i2pInboundBackupQuantity)); FormatI2POptionsString(i2pOptionsTemp, SAM_NAME_INBOUND_ALLOWZEROHOP , std::make_pair(settings.contains(SAM_NAME_INBOUND_ALLOWZEROHOP ), i2pInboundAllowZeroHop)); FormatI2POptionsString(i2pOptionsTemp, SAM_NAME_INBOUND_IPRESTRICTION , std::make_pair(settings.contains(SAM_NAME_INBOUND_IPRESTRICTION ), i2pInboundIPRestriction)); FormatI2POptionsString(i2pOptionsTemp, SAM_NAME_OUTBOUND_QUANTITY , std::make_pair(settings.contains(SAM_NAME_OUTBOUND_QUANTITY ), i2pOutboundQuantity)); FormatI2POptionsString(i2pOptionsTemp, SAM_NAME_OUTBOUND_LENGTH , std::make_pair(settings.contains(SAM_NAME_OUTBOUND_LENGTH ), i2pOutboundLength)); FormatI2POptionsString(i2pOptionsTemp, SAM_NAME_OUTBOUND_LENGTHVARIANCE, std::make_pair(settings.contains(SAM_NAME_OUTBOUND_LENGTHVARIANCE), i2pOutboundLengthVariance)); FormatI2POptionsString(i2pOptionsTemp, SAM_NAME_OUTBOUND_BACKUPQUANTITY, std::make_pair(settings.contains(SAM_NAME_OUTBOUND_BACKUPQUANTITY), i2pOutboundBackupQuantity)); FormatI2POptionsString(i2pOptionsTemp, SAM_NAME_OUTBOUND_ALLOWZEROHOP , std::make_pair(settings.contains(SAM_NAME_OUTBOUND_ALLOWZEROHOP ), i2pOutboundAllowZeroHop)); FormatI2POptionsString(i2pOptionsTemp, SAM_NAME_OUTBOUND_IPRESTRICTION , std::make_pair(settings.contains(SAM_NAME_OUTBOUND_IPRESTRICTION ), i2pOutboundIPRestriction)); FormatI2POptionsString(i2pOptionsTemp, SAM_NAME_OUTBOUND_PRIORITY , std::make_pair(settings.contains(SAM_NAME_OUTBOUND_PRIORITY ), i2pOutboundPriority)); if (!i2pOptionsTemp.empty()) SoftSetArg(I2P_SAM_I2P_OPTIONS_PARAM, i2pOptionsTemp); i2pOptions = QString::fromStdString(i2pOptionsTemp); #endif }
// Writes all missing QSettings with their default values void OptionsModel::Init(bool resetSettings) { if (resetSettings) Reset(); checkAndMigrate(); QSettings settings; // Ensure restart flag is unset on client startup setRestartRequired(false); // These are Qt-only settings: // Window if (!settings.contains("fHideTrayIcon")) settings.setValue("fHideTrayIcon", false); fHideTrayIcon = settings.value("fHideTrayIcon").toBool(); Q_EMIT hideTrayIconChanged(fHideTrayIcon); if (!settings.contains("fMinimizeToTray")) settings.setValue("fMinimizeToTray", false); fMinimizeToTray = settings.value("fMinimizeToTray").toBool() && !fHideTrayIcon; if (!settings.contains("fMinimizeOnClose")) settings.setValue("fMinimizeOnClose", false); fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool(); // Display if (!settings.contains("nDisplayUnit")) settings.setValue("nDisplayUnit", BitcoinUnits::BTC); nDisplayUnit = settings.value("nDisplayUnit").toInt(); if (!settings.contains("strThirdPartyTxUrls")) settings.setValue("strThirdPartyTxUrls", ""); strThirdPartyTxUrls = settings.value("strThirdPartyTxUrls", "").toString(); if (!settings.contains("fCoinControlFeatures")) settings.setValue("fCoinControlFeatures", false); fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool(); // These are shared with the core or have a command-line parameter // and we want command-line parameters to overwrite the GUI settings. // // If setting doesn't exist create it with defaults. // // If gArgs.SoftSetArg() or gArgs.SoftSetBoolArg() return false we were overridden // by command-line and show this in the UI. // Main if (!settings.contains("nDatabaseCache")) settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache); if (!gArgs.SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString())) addOverriddenOption("-dbcache"); if (!settings.contains("nThreadsScriptVerif")) settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS); if (!gArgs.SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString())) addOverriddenOption("-par"); if (!settings.contains("strDataDir")) settings.setValue("strDataDir", Intro::getDefaultDataDirectory()); // Wallet #ifdef ENABLE_WALLET if (!settings.contains("bSpendZeroConfChange")) settings.setValue("bSpendZeroConfChange", true); if (!gArgs.SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool())) addOverriddenOption("-spendzeroconfchange"); #endif // Network if (!settings.contains("fUseUPnP")) settings.setValue("fUseUPnP", DEFAULT_UPNP); if (!gArgs.SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool())) addOverriddenOption("-upnp"); if (!settings.contains("fListen")) settings.setValue("fListen", DEFAULT_LISTEN); if (!gArgs.SoftSetBoolArg("-listen", settings.value("fListen").toBool())) addOverriddenOption("-listen"); if (!settings.contains("fUseProxy")) settings.setValue("fUseProxy", false); if (!settings.contains("addrProxy")) settings.setValue("addrProxy", "127.0.0.1:9050"); // Only try to set -proxy, if user has enabled fUseProxy if (settings.value("fUseProxy").toBool() && !gArgs.SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString())) addOverriddenOption("-proxy"); else if(!settings.value("fUseProxy").toBool() && !gArgs.GetArg("-proxy", "").empty()) addOverriddenOption("-proxy"); if (!settings.contains("fUseSeparateProxyTor")) settings.setValue("fUseSeparateProxyTor", false); if (!settings.contains("addrSeparateProxyTor")) settings.setValue("addrSeparateProxyTor", "127.0.0.1:9050"); // Only try to set -onion, if user has enabled fUseSeparateProxyTor if (settings.value("fUseSeparateProxyTor").toBool() && !gArgs.SoftSetArg("-onion", settings.value("addrSeparateProxyTor").toString().toStdString())) addOverriddenOption("-onion"); else if(!settings.value("fUseSeparateProxyTor").toBool() && !gArgs.GetArg("-onion", "").empty()) addOverriddenOption("-onion"); // Display if (!settings.contains("language")) settings.setValue("language", ""); if (!gArgs.SoftSetArg("-lang", settings.value("language").toString().toStdString())) addOverriddenOption("-lang"); language = settings.value("language").toString(); }
PrivacyDialog::PrivacyDialog(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowCloseButtonHint), ui(new Ui::PrivacyDialog), walletModel(0), currentBalance(-1), fDenomsMinimized(true) { nDisplayUnit = 0; // just make sure it's not unitialized ui->setupUi(this); // "Spending 999999 xION ought to be enough for anybody." - Bill Gates, 2017 ui->xIONpayAmount->setValidator( new QDoubleValidator(0.0, 38600000.0, 20, this) ); ui->labelMintAmountValue->setValidator( new QIntValidator(0, 999999, this) ); // Default texts for (mini-) coincontrol ui->labelCoinControlQuantity->setText (tr("Coins automatically selected")); ui->labelCoinControlAmount->setText (tr("Coins automatically selected")); ui->labelxIONSyncStatus->setText("(" + tr("out of sync") + ")"); // Sunken frame for minting messages ui->TEMintStatus->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); ui->TEMintStatus->setLineWidth (2); ui->TEMintStatus->setMidLineWidth (2); ui->TEMintStatus->setPlainText(tr("Mint Status: Okay")); // Coin Control signals connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); // Coin Control: clipboard actions QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); // Denomination labels ui->labelzDenom1Text->setText(tr("Denom. with value <b>1</b>:")); ui->labelzDenom2Text->setText(tr("Denom. with value <b>5</b>:")); ui->labelzDenom3Text->setText(tr("Denom. with value <b>10</b>:")); ui->labelzDenom4Text->setText(tr("Denom. with value <b>50</b>:")); ui->labelzDenom5Text->setText(tr("Denom. with value <b>100</b>:")); ui->labelzDenom6Text->setText(tr("Denom. with value <b>500</b>:")); ui->labelzDenom7Text->setText(tr("Denom. with value <b>1000</b>:")); ui->labelzDenom8Text->setText(tr("Denom. with value <b>5000</b>:")); // AutoMint status ui->label_AutoMintStatus->setText(tr("AutoMint Status:")); // Global Supply labels ui->labelZsupplyText1->setText(tr("Denom. <b>1</b>:")); ui->labelZsupplyText5->setText(tr("Denom. <b>5</b>:")); ui->labelZsupplyText10->setText(tr("Denom. <b>10</b>:")); ui->labelZsupplyText50->setText(tr("Denom. <b>50</b>:")); ui->labelZsupplyText100->setText(tr("Denom. <b>100</b>:")); ui->labelZsupplyText500->setText(tr("Denom. <b>500</b>:")); ui->labelZsupplyText1000->setText(tr("Denom. <b>1000</b>:")); ui->labelZsupplyText5000->setText(tr("Denom. <b>5000</b>:")); // ION settings QSettings settings; if (!settings.contains("nSecurityLevel")){ nSecurityLevel = 42; settings.setValue("nSecurityLevel", nSecurityLevel); } else{ nSecurityLevel = settings.value("nSecurityLevel").toInt(); } if (!settings.contains("fMinimizeChange")){ fMinimizeChange = false; settings.setValue("fMinimizeChange", fMinimizeChange); } else{ fMinimizeChange = settings.value("fMinimizeChange").toBool(); } ui->checkBoxMinimizeChange->setChecked(fMinimizeChange); // Start with displaying the "out of sync" warnings showOutOfSyncWarning(true); // Hide those placeholder elements needed for CoinControl interaction ui->WarningLabel->hide(); // Explanatory text visible in QT-Creator ui->dummyHideWidget->hide(); // Dummy widget with elements to hide // Set labels/buttons depending on SPORK_16 status updateSPORK16Status(); // init Denoms section if(!settings.contains("fDenomsSectionMinimized")) settings.setValue("fDenomsSectionMinimized", true); minimizeDenomsSection(settings.value("fDenomsSectionMinimized").toBool()); }
/*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <QSettings> #include <QFileDialog> #include <QMessageBox> #include <QInputDialog> #include <QTextCodec> #include "qgslogger.h" #include "qgsopenvectorlayerdialog.h" #include "qgsvectordataprovider.h" #include <ogr_api.h> #include "qgsproviderregistry.h" #include "qgsnewogrconnection.h" #include "qgsogrhelperfunctions.h" #include "qgscontexthelp.h" QgsOpenVectorLayerDialog::QgsOpenVectorLayerDialog( QWidget* parent, Qt::WFlags fl ) : QDialog( parent, fl ) { setupUi( this ); cmbDatabaseTypes->blockSignals( true ); cmbConnections->blockSignals( true ); radioSrcFile->setChecked( true ); mDataSourceType = "file"; //set encoding cmbEncodings->addItems( QgsVectorDataProvider::availableEncodings() ); QSettings settings; QString enc = settings.value( "/UI/encoding", "System" ).toString(); restoreGeometry( settings.value( "/Windows/OpenVectorLayer/geometry" ).toByteArray() ); // The specified decoding is added if not existing alread, and then set current. // This should select it. int encindex = cmbEncodings->findText( enc ); if ( encindex < 0 ) { cmbEncodings->insertItem( 0, enc ); encindex = 0; } cmbEncodings->setCurrentIndex( encindex ); //add database drivers mVectorFileFilter = QgsProviderRegistry::instance()->fileVectorFilters(); QgsDebugMsg( "Database drivers :" + QgsProviderRegistry::instance()->databaseDrivers() ); QStringList dbDrivers = QgsProviderRegistry::instance()->databaseDrivers().split( ";" ); for ( int i = 0; i < dbDrivers.count(); i++ ) { QString dbDriver = dbDrivers.at( i ); if (( !dbDriver.isEmpty() ) && ( !dbDriver.isNull() ) ) cmbDatabaseTypes->addItem( dbDriver.split( "," ).at( 0 ) ); } //add directory drivers QStringList dirDrivers = QgsProviderRegistry::instance()->directoryDrivers().split( ";" ); for ( int i = 0; i < dirDrivers.count(); i++ ) { QString dirDriver = dirDrivers.at( i ); if (( !dirDriver.isEmpty() ) && ( !dirDriver.isNull() ) ) cmbDirectoryTypes->addItem( dirDriver.split( "," ).at( 0 ) ); } //add protocol drivers QStringList proDrivers = QgsProviderRegistry::instance()->protocolDrivers().split( ";" ); for ( int i = 0; i < proDrivers.count(); i++ ) { QString proDriver = proDrivers.at( i ); if (( !proDriver.isEmpty() ) && ( !proDriver.isNull() ) ) cmbProtocolTypes->addItem( proDriver.split( "," ).at( 0 ) ); } cmbDatabaseTypes->blockSignals( false ); cmbConnections->blockSignals( false ); } QgsOpenVectorLayerDialog::~QgsOpenVectorLayerDialog() { QSettings settings; settings.setValue( "/Windows/OpenVectorLayer/geometry", saveGeometry() ); } QStringList QgsOpenVectorLayerDialog::openFile() { QStringList selectedFiles; QgsDebugMsg( "Vector file filters: " + mVectorFileFilter ); QString enc = encoding(); QString title = tr( "Open an OGR Supported Vector Layer" ); QgisGui::openFilesRememberingFilter( "lastVectorFileFilter", mVectorFileFilter, selectedFiles, enc, title ); return selectedFiles; } QString QgsOpenVectorLayerDialog::openDirectory() { QSettings settings; bool haveLastUsedDir = settings.contains( "/UI/LastUsedDirectory" ); QString lastUsedDir = settings.value( "/UI/LastUsedDirectory", QVariant() ).toString(); if ( !haveLastUsedDir ) lastUsedDir = ""; QString path = QFileDialog::getExistingDirectory( this, tr( "Open Directory" ), lastUsedDir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks ); settings.setValue( "/UI/LastUsedDirectory", path ); //process path if it is grass if ( cmbDirectoryTypes->currentText() == "Grass Vector" ) { #ifdef WIN32 //replace backslashes with forward slashes path.replace( "\\", "/" ); #endif path = path + "/head"; } return path; } QStringList QgsOpenVectorLayerDialog::dataSources() { return mDataSources; } QString QgsOpenVectorLayerDialog::encoding() { return cmbEncodings->currentText(); } QString QgsOpenVectorLayerDialog::dataSourceType() { return mDataSourceType; } void QgsOpenVectorLayerDialog::addNewConnection() { QgsNewOgrConnection *nc = new QgsNewOgrConnection( this ); nc->exec(); delete nc; populateConnectionList(); } void QgsOpenVectorLayerDialog::editConnection() { QgsNewOgrConnection *nc = new QgsNewOgrConnection( this, cmbDatabaseTypes->currentText(), cmbConnections->currentText() ); nc->exec(); delete nc; populateConnectionList(); } void QgsOpenVectorLayerDialog::deleteConnection() { QSettings settings; QString key = "/" + cmbDatabaseTypes->currentText() + "/connections/" + cmbConnections->currentText(); QString msg = tr( "Are you sure you want to remove the %1 connection and all associated settings?" ) .arg( cmbConnections->currentText() ); QMessageBox::StandardButton result = QMessageBox::information( this, tr( "Confirm Delete" ), msg, QMessageBox::Ok | QMessageBox::Cancel ); if ( result == QMessageBox::Ok ) { settings.remove( key + "/host" ); settings.remove( key + "/database" ); settings.remove( key + "/username" ); settings.remove( key + "/password" ); settings.remove( key + "/port" ); settings.remove( key + "/save" ); settings.remove( key ); cmbConnections->removeItem( cmbConnections->currentIndex() ); // populateConnectionList(); setConnectionListPosition(); } } void QgsOpenVectorLayerDialog::populateConnectionList() { QSettings settings; settings.beginGroup( "/" + cmbDatabaseTypes->currentText() + "/connections" ); QStringList keys = settings.childGroups(); QStringList::Iterator it = keys.begin(); cmbConnections->clear(); while ( it != keys.end() ) { cmbConnections->addItem( *it ); ++it; } settings.endGroup(); setConnectionListPosition(); } void QgsOpenVectorLayerDialog::setConnectionListPosition() { QSettings settings; // If possible, set the item currently displayed database QString toSelect = settings.value( "/" + cmbDatabaseTypes->currentText() + "/connections/selected" ).toString(); // Does toSelect exist in cmbConnections? bool set = false; for ( int i = 0; i < cmbConnections->count(); ++i ) if ( cmbConnections->itemText( i ) == toSelect ) { cmbConnections->setCurrentIndex( i ); set = true; break; } // If we couldn't find the stored item, but there are some, // default to the last item (this makes some sense when deleting // items as it allows the user to repeatidly click on delete to // remove a whole lot of items). if ( !set && cmbConnections->count() > 0 ) { // If toSelect is null, then the selected connection wasn't found // by QSettings, which probably means that this is the first time // the user has used qgis with database connections, so default to // the first in the list of connetions. Otherwise default to the last. if ( toSelect.isNull() ) cmbConnections->setCurrentIndex( 0 ); else cmbConnections->setCurrentIndex( cmbConnections->count() - 1 ); } } void QgsOpenVectorLayerDialog::setConnectionTypeListPosition() { QSettings settings; QString toSelect = settings.value( "/ogr/connections/selectedtype" ).toString(); for ( int i = 0; i < cmbDatabaseTypes->count(); ++i ) if ( cmbDatabaseTypes->itemText( i ) == toSelect ) { cmbDatabaseTypes->setCurrentIndex( i ); break; } } void QgsOpenVectorLayerDialog::setSelectedConnectionType() { QSettings settings; QString baseKey = "/ogr/connections/"; settings.setValue( baseKey + "selectedtype", cmbDatabaseTypes->currentText() ); QgsDebugMsg( "Setting selected type to" + cmbDatabaseTypes->currentText() ); } void QgsOpenVectorLayerDialog::setSelectedConnection() { QSettings settings; settings.setValue( "/" + cmbDatabaseTypes->currentText() + "/connections/selected", cmbConnections->currentText() ); QgsDebugMsg( "Setting selected connection to " + cmbConnections->currentText() ); } void QgsOpenVectorLayerDialog::on_buttonSelectSrc_clicked() { if ( radioSrcFile->isChecked() ) { inputSrcDataset->setText( openFile().join( ";" ) ); } else if ( radioSrcDirectory->isChecked() ) { inputSrcDataset->setText( openDirectory() ); } else if ( !radioSrcDatabase->isChecked() ) { Q_ASSERT( !"SHOULD NEVER GET HERE" ); } } //********************auto connected slots *****************/ void QgsOpenVectorLayerDialog::accept() { QSettings settings; QgsDebugMsg( "dialog button accepted" ); mDataSources.clear(); if ( radioSrcDatabase->isChecked() ) { if ( !settings.contains( "/" + cmbDatabaseTypes->currentText() + "/connections/" + cmbConnections->currentText() + "/host" ) ) { QMessageBox::information( this, tr( "Add vector layer" ), tr( "No database selected." ) ); return; } QString baseKey = "/" + cmbDatabaseTypes->currentText() + "/connections/"; baseKey += cmbConnections->currentText(); QString host = settings.value( baseKey + "/host" ).toString(); QString database = settings.value( baseKey + "/database" ).toString(); QString port = settings.value( baseKey + "/port" ).toString(); QString user = settings.value( baseKey + "/username" ).toString(); QString pass = settings.value( baseKey + "/password" ).toString(); bool makeConnection = false; if ( pass.isEmpty() ) { pass = QInputDialog::getText( this, tr( "Password for " ) + user, tr( "Please enter your password:"******"Add vector layer" ), tr( "No protocol URI entered." ) ); return; } mDataSources << createProtocolURI( cmbProtocolTypes->currentText(), protocolURI->text() ); } else if ( radioSrcFile->isChecked() ) { if ( inputSrcDataset->text().isEmpty() ) { QMessageBox::information( this, tr( "Add vector layer" ), tr( "No layers selected." ) ); return; } mDataSources << inputSrcDataset->text().split( ";" ); } else if ( radioSrcDirectory->isChecked() ) { if ( inputSrcDataset->text().isEmpty() ) { QMessageBox::information( this, tr( "Add vector layer" ), tr( "No directory selected." ) ); return; } mDataSources << inputSrcDataset->text(); } // Save the used encoding settings.setValue( "/UI/encoding", encoding() ); QDialog::accept(); }
// write QSettings values bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role) { bool successful = true; /* set to false on parse error */ if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: successful = GUIUtil::SetStartOnSystemStartup(value.toBool()); break; case MinimizeToTray: fMinimizeToTray = value.toBool(); settings.setValue("fMinimizeToTray", fMinimizeToTray); break; case MapPortUPnP: // core option - can be changed on-the-fly settings.setValue("fUseUPnP", value.toBool()); MapPort(value.toBool()); break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); settings.setValue("fMinimizeOnClose", fMinimizeOnClose); break; // default proxy case ProxyUse: if (settings.value("fUseProxy") != value) { settings.setValue("fUseProxy", value.toBool()); setRestartRequired(true); } break; case ProxyIP: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed IP if (!settings.contains("addrProxy") || strlIpPort.at(0) != value.toString()) { // construct new value from new IP and current port QString strNewValue = value.toString() + ":" + strlIpPort.at(1); settings.setValue("addrProxy", strNewValue); setRestartRequired(true); } } break; case ProxyPort: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed port if (!settings.contains("addrProxy") || strlIpPort.at(1) != value.toString()) { // construct new value from current IP and new port QString strNewValue = strlIpPort.at(0) + ":" + value.toString(); settings.setValue("addrProxy", strNewValue); setRestartRequired(true); } } break; case ProxySocksVersion: { if (settings.value("nSocksVersion") != value) { settings.setValue("nSocksVersion", value.toInt()); setRestartRequired(true); } } break; #ifdef ENABLE_WALLET case Fee: // core option - can be changed on-the-fly // Todo: Add is valid check and warn via message, if not nTransactionFee = value.toLongLong(); settings.setValue("nTransactionFee", (qint64)nTransactionFee); emit transactionFeeChanged(nTransactionFee); break; case SpendZeroConfChange: if (settings.value("bSpendZeroConfChange") != value) { settings.setValue("bSpendZeroConfChange", value); setRestartRequired(true); } break; #endif case DisplayUnit: nDisplayUnit = value.toInt(); settings.setValue("nDisplayUnit", nDisplayUnit); emit displayUnitChanged(nDisplayUnit); break; case DisplayAddresses: bDisplayAddresses = value.toBool(); settings.setValue("bDisplayAddresses", bDisplayAddresses); break; case Language: if (settings.value("language") != value) { settings.setValue("language", value); setRestartRequired(true); } break; case CoinControlFeatures: fCoinControlFeatures = value.toBool(); settings.setValue("fCoinControlFeatures", fCoinControlFeatures); emit coinControlFeaturesChanged(fCoinControlFeatures); break; case DatabaseCache: if (settings.value("nDatabaseCache") != value) { settings.setValue("nDatabaseCache", value); setRestartRequired(true); } break; case ThreadsScriptVerif: if (settings.value("nThreadsScriptVerif") != value) { settings.setValue("nThreadsScriptVerif", value); setRestartRequired(true); } break; default: break; } } emit dataChanged(index, index); return successful; }
/// \brief Read the settings from the last session or another file. /// \param fileName Optional filename to load the settings from an ini file. /// \return 0 on success, negative on error. int DsoSettings::load(const QString &fileName) { // Use main configuration if the fileName wasn't set QSettings *settingsLoader; if(fileName.isEmpty()) settingsLoader = new QSettings(this); else { settingsLoader = new QSettings(fileName, QSettings::IniFormat, this); } if(settingsLoader->status() != QSettings::NoError) return -settingsLoader->status(); // Main window layout and other general options settingsLoader->beginGroup("options"); settingsLoader->beginGroup("window"); // Docking windows and toolbars settingsLoader->beginGroup("docks"); QList<DsoSettingsOptionsWindowPanel *> docks; docks.append(&(this->options.window.dock.horizontal)); docks.append(&(this->options.window.dock.spectrum)); docks.append(&(this->options.window.dock.trigger)); docks.append(&(this->options.window.dock.voltage)); QStringList dockNames; dockNames << "horizontal" << "spectrum" << "trigger" << "voltage"; for(int dockId = 0; dockId < docks.size(); ++dockId) { settingsLoader->beginGroup(dockNames[dockId]); if(settingsLoader->contains("floating")) docks[dockId]->floating = settingsLoader->value("floating").toBool(); if(settingsLoader->contains("position")) docks[dockId]->position = settingsLoader->value("position").toPoint(); if(settingsLoader->contains("visible")) docks[dockId]->visible = settingsLoader->value("visible").toBool(); settingsLoader->endGroup(); } settingsLoader->endGroup(); settingsLoader->beginGroup("toolbars"); QList<DsoSettingsOptionsWindowPanel *> toolbars; toolbars.append(&(this->options.window.toolbar.file)); toolbars.append(&(this->options.window.toolbar.oscilloscope)); toolbars.append(&(this->options.window.toolbar.view)); QStringList toolbarNames; toolbarNames << "file" << "oscilloscope" << "view"; for(int toolbarId = 0; toolbarId < toolbars.size(); ++toolbarId) { settingsLoader->beginGroup(toolbarNames[toolbarId]); if(settingsLoader->contains("floating")) toolbars[toolbarId]->floating = settingsLoader->value("floating").toBool(); if(settingsLoader->contains("position")) toolbars[toolbarId]->position = settingsLoader->value("position").toPoint(); if(settingsLoader->contains("visible")) toolbars[toolbarId]->visible = settingsLoader->value("visible").toBool(); settingsLoader->endGroup(); } settingsLoader->endGroup(); // Main window if(settingsLoader->contains("pos")) this->options.window.position = settingsLoader->value("pos").toPoint(); if(settingsLoader->contains("size")) this->options.window.size = settingsLoader->value("size").toSize(); settingsLoader->endGroup(); // General options if(settingsLoader->contains("alwaysSave")) this->options.alwaysSave = settingsLoader->value("alwaysSave").toBool(); if(settingsLoader->contains("imageSize")) this->options.imageSize = settingsLoader->value("imageSize").toSize(); settingsLoader->endGroup(); // Oszilloskope settings settingsLoader->beginGroup("scope"); // Horizontal axis settingsLoader->beginGroup("horizontal"); if(settingsLoader->contains("format")) this->scope.horizontal.format = (Dso::GraphFormat) settingsLoader->value("format").toInt(); if(settingsLoader->contains("frequencybase")) this->scope.horizontal.frequencybase = settingsLoader->value("frequencybase").toDouble(); for(int marker = 0; marker < 2; ++marker) { QString name; name = QString("marker%1").arg(marker); if(settingsLoader->contains(name)) this->scope.horizontal.marker[marker] = settingsLoader->value(name).toDouble(); } if(settingsLoader->contains("timebase")) this->scope.horizontal.timebase = settingsLoader->value("timebase").toDouble(); if(settingsLoader->contains("recordLength")) this->scope.horizontal.recordLength = settingsLoader->value("recordLength").toUInt(); if(settingsLoader->contains("samplerate")) this->scope.horizontal.samplerate = settingsLoader->value("samplerate").toDouble(); if(settingsLoader->contains("samplerateSet")) this->scope.horizontal.samplerateSet = settingsLoader->value("samplerateSet").toBool(); settingsLoader->endGroup(); // Trigger settingsLoader->beginGroup("trigger"); if(settingsLoader->contains("filter")) this->scope.trigger.filter = settingsLoader->value("filter").toBool(); if(settingsLoader->contains("mode")) this->scope.trigger.mode = (Dso::TriggerMode) settingsLoader->value("mode").toInt(); if(settingsLoader->contains("position")) this->scope.trigger.position = settingsLoader->value("position").toDouble(); if(settingsLoader->contains("slope")) this->scope.trigger.slope = (Dso::Slope) settingsLoader->value("slope").toInt(); if(settingsLoader->contains("source")) this->scope.trigger.source = settingsLoader->value("source").toInt(); if(settingsLoader->contains("special")) this->scope.trigger.special = settingsLoader->value("special").toInt(); settingsLoader->endGroup(); // Spectrum for(int channel = 0; channel < this->scope.spectrum.count(); ++channel) { settingsLoader->beginGroup(QString("spectrum%1").arg(channel)); if(settingsLoader->contains("magnitude")) this->scope.spectrum[channel].magnitude = settingsLoader->value("magnitude").toDouble(); if(settingsLoader->contains("offset")) this->scope.spectrum[channel].offset = settingsLoader->value("offset").toDouble(); if(settingsLoader->contains("used")) this->scope.spectrum[channel].used = settingsLoader->value("used").toBool(); settingsLoader->endGroup(); } // Vertical axis for(int channel = 0; channel < this->scope.voltage.count(); ++channel) { settingsLoader->beginGroup(QString("vertical%1").arg(channel)); if(settingsLoader->contains("gain")) this->scope.voltage[channel].gain = settingsLoader->value("gain").toDouble(); if(settingsLoader->contains("misc")) this->scope.voltage[channel].misc = settingsLoader->value("misc").toInt(); if(settingsLoader->contains("offset")) this->scope.voltage[channel].offset = settingsLoader->value("offset").toDouble(); if(settingsLoader->contains("trigger")) this->scope.voltage[channel].trigger = settingsLoader->value("trigger").toDouble(); if(settingsLoader->contains("used")) this->scope.voltage[channel].used = settingsLoader->value("used").toBool(); settingsLoader->endGroup(); } if(settingsLoader->contains("spectrumLimit")) this->scope.spectrumLimit = settingsLoader->value("spectrumLimit").toDouble(); if(settingsLoader->contains("spectrumReference")) this->scope.spectrumReference = settingsLoader->value("spectrumReference").toDouble(); if(settingsLoader->contains("spectrumWindow")) this->scope.spectrumWindow = (Dso::WindowFunction) settingsLoader->value("spectrumWindow").toInt(); settingsLoader->endGroup(); // View settingsLoader->beginGroup("view"); // Colors settingsLoader->beginGroup("color"); DsoSettingsColorValues *colors; for(int mode = 0; mode < 2; ++mode) { if(mode == 0) { colors = &this->view.color.screen; settingsLoader->beginGroup("screen"); } else { colors = &this->view.color.print; settingsLoader->beginGroup("print"); } if(settingsLoader->contains("axes")) colors->axes = settingsLoader->value("axes").value<QColor>(); if(settingsLoader->contains("background")) colors->background = settingsLoader->value("background").value<QColor>(); if(settingsLoader->contains("border")) colors->border = settingsLoader->value("border").value<QColor>(); if(settingsLoader->contains("grid")) colors->grid = settingsLoader->value("grid").value<QColor>(); if(settingsLoader->contains("markers")) colors->markers = settingsLoader->value("markers").value<QColor>(); for(int channel = 0; channel < this->scope.spectrum.count(); ++channel) { QString key = QString("spectrum%1").arg(channel); if(settingsLoader->contains(key)) colors->spectrum[channel] = settingsLoader->value(key).value<QColor>(); } if(settingsLoader->contains("text")) colors->text = settingsLoader->value("text").value<QColor>(); for(int channel = 0; channel < this->scope.voltage.count(); ++channel) { QString key = QString("voltage%1").arg(channel); if(settingsLoader->contains(key)) colors->voltage[channel] = settingsLoader->value(key).value<QColor>(); } settingsLoader->endGroup(); } settingsLoader->endGroup(); // Other view settings if(settingsLoader->contains("digitalPhosphor")) this->view.digitalPhosphor = settingsLoader->value("digitalPhosphor").toBool(); if(settingsLoader->contains("interpolation")) this->view.interpolation = (Dso::InterpolationMode) settingsLoader->value("interpolation").toInt(); if(settingsLoader->contains("screenColorImages")) this->view.screenColorImages = (Dso::InterpolationMode) settingsLoader->value("screenColorImages").toBool(); if(settingsLoader->contains("zoom")) this->view.zoom = (Dso::InterpolationMode) settingsLoader->value("zoom").toBool(); settingsLoader->endGroup(); delete settingsLoader; return 0; }