<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "bitcoin-config.h"
#endif

#include "optionsmodel.h"

#include "bitcoinunits.h"
#include "guiutil.h"

#include "init.h"
#include "main.h"
#include "net.h"
#include "txdb.h" // for -dbcache defaults
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif

#include <QNetworkProxy>
#include <QSettings>
#include <QStringList>

OptionsModel::OptionsModel(QObject *parent) :
    QAbstractListModel(parent)
{
    Init();
}

void OptionsModel::addOverriddenOption(const std::string &option)
{
    strOverriddenByCommandLine += QString::fromStdString(option) + "=" + QString::fromStdString(mapArgs[option]) + " ";
}

// 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", BitcoinUnits::BTC);
    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)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("nTransactionFee"))
        settings.setValue("nTransactionFee", DEFAULT_TRANSACTION_FEE);
    nTransactionFee = 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

    // 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()))
        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();
}

void OptionsModel::Reset()
{
    QSettings settings;

    // Remove all entries from our QSettings object
    settings.clear();

    // default setting for OptionsModel::StartAtStartup - disabled
    if (GUIUtil::GetStartOnSystemStartup())
        GUIUtil::SetStartOnSystemStartup(false);
}

int OptionsModel::rowCount(const QModelIndex & parent) const
{
    return OptionIDRowCount;
}

// read QSettings values and return them
QVariant OptionsModel::data(const QModelIndex & index, int role) const
{
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            return GUIUtil::GetStartOnSystemStartup();
        case MinimizeToTray:
            return fMinimizeToTray;
        case MapPortUPnP:
#ifdef USE_UPNP
            return settings.value("fUseUPnP");
#else
            return false;
#endif
        case MinimizeOnClose:
            return fMinimizeOnClose;

        // default proxy
        case ProxyUse:
            return settings.value("fUseProxy", false);
        case ProxyIP: {
            // contains IP at index 0 and port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            return strlIpPort.at(0);
        }
        case ProxyPort: {
            // contains IP at index 0 and port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            return strlIpPort.at(1);
        }
        case ProxySocksVersion:
            return settings.value("nSocksVersion", 5);

#ifdef ENABLE_WALLET
        case Fee:
            // Attention: Init() is called before nTransactionFee is set in AppInit2()!
            // To ensure we can change the fee on-the-fly update our QSetting when
            // opening OptionsDialog, which queries Fee via the mapper.
            if (nTransactionFee != settings.value("nTransactionFee").toLongLong())
                settings.setValue("nTransactionFee", (qint64)nTransactionFee);
            // Todo: Consider to revert back to use just nTransactionFee here, if we don't want
            // -paytxfee to update our QSettings!
            return settings.value("nTransactionFee");
        case SpendZeroConfChange:
            return settings.value("bSpendZeroConfChange");
#endif
        case DisplayUnit:
            return nDisplayUnit;
        case DisplayAddresses:
            return bDisplayAddresses;
        case ThirdPartyTxUrls:
            return strThirdPartyTxUrls;
        case Language:
            return settings.value("language");
        case CoinControlFeatures:
            return fCoinControlFeatures;
        case DatabaseCache:
            return settings.value("nDatabaseCache");
        case ThreadsScriptVerif:
            return settings.value("nThreadsScriptVerif");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// 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 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);
            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;
}

bool OptionsModel::getProxySettings(QNetworkProxy& proxy) const
{
    // Directly query current base proxy, because
    // GUI settings can be overridden with -proxy.
    proxyType curProxy;
    if (GetProxy(NET_IPV4, curProxy)) {
        if (curProxy.second == 5) {
            proxy.setType(QNetworkProxy::Socks5Proxy);
            proxy.setHostName(QString::fromStdString(curProxy.first.ToStringIP()));
            proxy.setPort(curProxy.first.GetPort());

            return true;
        }
        else
            return false;
    }
    else
        proxy.setType(QNetworkProxy::NoProxy);

    return true;
}

void OptionsModel::setRestartRequired(bool fRequired)
{
    QSettings settings;
    return settings.setValue("fRestartRequired", fRequired);
}

bool OptionsModel::isRestartRequired()
{
    QSettings settings;
    return settings.value("fRestartRequired", false).toBool();
}
<commit_msg>qt: fix compile issue in Qt GUI<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "bitcoin-config.h"
#endif

#include "optionsmodel.h"

#include "bitcoinunits.h"
#include "guiutil.h"

#include "init.h"
#include "main.h"
#include "net.h"
#include "txdb.h" // for -dbcache defaults
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif

#include <QNetworkProxy>
#include <QSettings>
#include <QStringList>

OptionsModel::OptionsModel(QObject *parent) :
    QAbstractListModel(parent)
{
    Init();
}

void OptionsModel::addOverriddenOption(const std::string &option)
{
    strOverriddenByCommandLine += QString::fromStdString(option) + "=" + QString::fromStdString(mapArgs[option]) + " ";
}

// 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", BitcoinUnits::BTC);
    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)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("nTransactionFee"))
        settings.setValue("nTransactionFee", (qint64)DEFAULT_TRANSACTION_FEE);
    nTransactionFee = 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

    // 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()))
        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();
}

void OptionsModel::Reset()
{
    QSettings settings;

    // Remove all entries from our QSettings object
    settings.clear();

    // default setting for OptionsModel::StartAtStartup - disabled
    if (GUIUtil::GetStartOnSystemStartup())
        GUIUtil::SetStartOnSystemStartup(false);
}

int OptionsModel::rowCount(const QModelIndex & parent) const
{
    return OptionIDRowCount;
}

// read QSettings values and return them
QVariant OptionsModel::data(const QModelIndex & index, int role) const
{
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            return GUIUtil::GetStartOnSystemStartup();
        case MinimizeToTray:
            return fMinimizeToTray;
        case MapPortUPnP:
#ifdef USE_UPNP
            return settings.value("fUseUPnP");
#else
            return false;
#endif
        case MinimizeOnClose:
            return fMinimizeOnClose;

        // default proxy
        case ProxyUse:
            return settings.value("fUseProxy", false);
        case ProxyIP: {
            // contains IP at index 0 and port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            return strlIpPort.at(0);
        }
        case ProxyPort: {
            // contains IP at index 0 and port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            return strlIpPort.at(1);
        }
        case ProxySocksVersion:
            return settings.value("nSocksVersion", 5);

#ifdef ENABLE_WALLET
        case Fee:
            // Attention: Init() is called before nTransactionFee is set in AppInit2()!
            // To ensure we can change the fee on-the-fly update our QSetting when
            // opening OptionsDialog, which queries Fee via the mapper.
            if (nTransactionFee != settings.value("nTransactionFee").toLongLong())
                settings.setValue("nTransactionFee", (qint64)nTransactionFee);
            // Todo: Consider to revert back to use just nTransactionFee here, if we don't want
            // -paytxfee to update our QSettings!
            return settings.value("nTransactionFee");
        case SpendZeroConfChange:
            return settings.value("bSpendZeroConfChange");
#endif
        case DisplayUnit:
            return nDisplayUnit;
        case DisplayAddresses:
            return bDisplayAddresses;
        case ThirdPartyTxUrls:
            return strThirdPartyTxUrls;
        case Language:
            return settings.value("language");
        case CoinControlFeatures:
            return fCoinControlFeatures;
        case DatabaseCache:
            return settings.value("nDatabaseCache");
        case ThreadsScriptVerif:
            return settings.value("nThreadsScriptVerif");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// 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 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);
            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;
}

bool OptionsModel::getProxySettings(QNetworkProxy& proxy) const
{
    // Directly query current base proxy, because
    // GUI settings can be overridden with -proxy.
    proxyType curProxy;
    if (GetProxy(NET_IPV4, curProxy)) {
        if (curProxy.second == 5) {
            proxy.setType(QNetworkProxy::Socks5Proxy);
            proxy.setHostName(QString::fromStdString(curProxy.first.ToStringIP()));
            proxy.setPort(curProxy.first.GetPort());

            return true;
        }
        else
            return false;
    }
    else
        proxy.setType(QNetworkProxy::NoProxy);

    return true;
}

void OptionsModel::setRestartRequired(bool fRequired)
{
    QSettings settings;
    return settings.setValue("fRestartRequired", fRequired);
}

bool OptionsModel::isRestartRequired()
{
    QSettings settings;
    return settings.value("fRestartRequired", false).toBool();
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>

using namespace std;

#include "LibUtilities/Foundations/Foundations.hpp"
#include <LibUtilities/BasicUtils/NekManager.hpp>
#include <LibUtilities/Foundations/Points.h>
#include <LibUtilities/Foundations/GaussPoints.h>
#include <LibUtilities/Foundations/PolyEPoints.h>
#include <LibUtilities/Foundations/Basis.h>
#include <LibUtilities/Foundations/NodalTriFekete.h>
#include <LibUtilities/Foundations/ManagerAccess.h>

using namespace Nektar;
using namespace Nektar::LibUtilities;

// Quintic polynomial
long double polyFunc(long double x) {
    return  (((3.0*x*x - 5.0)*x + 1.0)*x - 2.0)*x + 3.0;
}

// Derivative of the Quintic polynomial
long double derivativePolyFunc(long double x) {
    return ((15.0*x*x - 15.0)*x   + 2.0)*x - 2.0;
}

// A Fourier function that integrates to 0 with the Trapezoidal rule
long double fourierFunc(long double x, int N) {
    long double z = M_PI*(x + 1.0);
    return (cos(N/2.0*z) + sin((N/2.0 - 2.0)*z))/M_PI;
}

// Derivative of the Fourier function above
long double derivativeFourierFunc(long double x, int N) {
    long double z = M_PI*(x + 1.0);
    long double a = (N-4.0)/2.0;
    long double b = N/2.0;
    return M_PI*M_PI*(a*cos(a*z) - b*sin(b*z));
}

long double function(long double x, int N, PointsType type) {
    long double y = 0;
    if( type == eFourierEvenlySpaced) {
        y = fourierFunc(x,N);
    } else {
        y = polyFunc(x);
    }
    return y;
}

long double derivativeFunction(long double x, int N, PointsType type){
    long double yDerivative = 0;
    if(type == eFourierEvenlySpaced){
         yDerivative = derivativeFourierFunc(x, N);
    } else {
         yDerivative = derivativePolyFunc(x);
    }
    return yDerivative;
}

long double integrationFunction(int nPts, PointsType type){
   long double integral = 0;
   switch(type){
       case  eFourierEvenlySpaced:
          integral = 0;
       break;
       default:
          integral = (long double)20.0/3.0;
   }
   return integral;
}

long double integrandWeightFunction(long double x, PointsType type){
    long double weight = 1;

    switch(type) {
        case eGaussGaussChebyshev:
        case eGaussRadauMChebyshev:
        case eGaussRadauPChebyshev:
        case eGaussLobattoChebyshev:
            weight = 1.0 / sqrt(1.0 - x*x);
        break;

        case eGaussRadauMAlpha0Beta1:
            // weight = 1.0 + x; // ?
        break;

        case eGaussRadauMAlpha0Beta2:
            // weight = (1.0 + x)*(1.0 + x); // ?
        break;

        default:
            weight = 1.0;
    }
    return weight;
}
// This routine projects a polynomial or trigonmetric functions which
// has energy in all modes of the expansions and report an error.

int main(int argc, char *argv[]) {

    // Argument check: Display a help message if the count is wrong
    if(argc != 3) {
        cerr << "Usage: FoundationDemo Points1D-Type nPts" << endl;

        cerr << "Where type is an integer value which dictates the basis as:\n";
        for(int i=0; i<SIZE_PointsType; ++i) {
            cerr << setw(30) << PointsTypeMap[i] << " = " << i << endl;
        }

        cerr << "Note type = 13, 14, and 15 are for two dimensional bases" << endl;
        cerr << "\nExample: FoundationDemo 5 6" << endl;
        cerr << "\n\t Tests GaussGaussChebyshev on 6 points" << endl;

        return 1; // Aborts main() function
    }

    // Read in the type for the points from the caller
    PointsType pointsType = (PointsType) atoi(argv[1]);
    if(pointsType == eNoPointsType) {
        cerr << "pointsType = " << pointsType << endl;
        cerr << "PointsTypeMap["<<pointsType<<"] = " << PointsTypeMap[pointsType] << endl;
        ErrorUtil::Error(ErrorUtil::efatal,__FILE__, __LINE__,
                         "No Points Type requested" );
    }

    // Read in the number of points at which the function will be evaluated
    int nPts = atoi(argv[2]);

    // Show the set up to the user
    cout << "Points type:               " << PointsTypeMap[pointsType] << endl;
    cout << "Number of points:          " << nPts << endl;

    // Display the example test function to the user
    if( pointsType == eFourierEvenlySpaced ) {
        cout << "Trigonometric function:    ";
        cout << "f(x) = (cos(N/2.0*z) + sin((N/2.0 - 2.0)*z))/M_PI, where z = M_PI*(x + 1.0)" << endl;
    } else {
        cout << "Quintic polynomial:        ";
        cout << "p(x) = (((3.0*x*x - 5.0)*x + 1.0)*x - 2.0)*x + 3.0" << endl;
    }

    // Obtain a reference to a Points object via an appropriate PointsKey object
    PointsKey key(nPts, pointsType);
    const ptr<Points<NekDouble> > points = PointsManager()[key];

    // Get the abscissas and their matching quadrature weights
    SharedArray<const NekDouble> z, w;
    points->GetZW(z,w);

    // Evaluate the example function at the z[i] points in the interval [-1,1].
    // This generates the data samples, which we store in the y vector and use later
    // during interpolation/integration/differentiation
    SharedArray<NekDouble> y(nPts);
    for(int i = 0; i < nPts; ++i) {
        y[i] = function( z[i], nPts, pointsType );
    }

     // /////////////////////////////////////////////////////////
    //                     Interpolation                      //
   // /////////////////////////////////////////////////////////

    // Generate a list of interpolating nodes
    int nNodes = 2*nPts; // Number of interpolating nodes
    const ptr<Points<NekDouble> > nodes = PointsManager()[PointsKey(nNodes, pointsType)];
    SharedArray<const NekDouble> zNode = nodes->GetZ();

    // Get the interpolation matrix I
    // Note that I is 2N rows by N columns
    const Points<NekDouble>::MatrixSharedPtrType Iptr = points->GetI(nNodes, zNode);
    const NekMatrix<NekDouble> & I = *Iptr;

    // Interpolate the data values in the y vector using the interpolation matrix I
    SharedArray<NekDouble> u(I.GetRows());
    for(int i = 0; i < I.GetRows(); ++i) {
        u[i] = 0;
        for(int j = 0; j < I.GetColumns(); ++j) {
            u[i] += I(i,j) * y[j];
        }
    }

    // Display the original samples
    cout << setprecision(3);
    cout << "\nOriginal data: \nx      = ";
    for(int i = 0; i < nPts; ++i) {
        cout << setw(6) << z[i] << " ";
    }
    cout << "\ny      = ";
    for(int i = 0; i < nPts; ++i) {
        cout << setw(6) << y[i] << " ";
    }

    // Display the interpolated data
    cout << "\n\n\n              **** Interpolation ****";
    cout << "\n\nResults of interpolation with " << PointsTypeMap[pointsType] << ":";
    cout << "\ninterp = ";
    for(int i = 0; i < nNodes; ++i) {
        cout << setw(6) << u[i] << " ";
    }

    // Determine the exact solutions
    cout << "\nexact  = ";
    for(int i = 0; i < nNodes; ++i) {
        cout << setw(6) << function(zNode[i], nPts, pointsType) << " ";
    }

    // Display the pointwise error
    cout << setprecision(1);
    cout << "\nerror  = ";
    long double Linf = 0, RMS = 0;
    for(int i = 0; i < I.GetRows(); ++i) {
        //long double exact = function(zNode[i], nNodes, pointsType);
        long double exact = function(zNode[i], nPts, pointsType);
        long double error = exact - u[i];
        Linf = fmax(Linf, fabs(error));
        RMS += error*error;
        long double epsilon = 1e-2;
        if( fabs(exact) > epsilon ) {
            error /= exact;
        }
        cout << setw(6) << error << " ";
    }
    RMS = sqrt(RMS) / I.GetRows();
    cout << setprecision(6);
    cout << "\nLinf   = " << setw(6) << Linf;
    cout << "\nRMS    = " << setw(6) << RMS << endl;

    // Show the interpolation matrix
    cout << "\nI = \n";
    for(int i = 0; i < I.GetRows(); ++i) {
        cout << "     ";
        for(int j = 0; j < I.GetColumns(); ++j) {
            printf("% 5.3f  ", I(i,j));
        }
        cout << "\n";
    }

      // /////////////////////////////////////////////////////////
     //                     Derivation                         //
    // /////////////////////////////////////////////////////////

    // Get the derivation matrix D
    // Note that, unlike I, D is N rows by N columns
    const Points<NekDouble>::MatrixSharedPtrType Dptr = points->GetD();
    const NekMatrix<NekDouble> & D = *Dptr;

    // Differentiate the data values in the y vector using the derivative matrix D
    SharedArray<NekDouble> v(nPts);
    for(int i = 0; i < D.GetRows(); ++i) {
        v[i] = 0;
        for(int j = 0; j < D.GetColumns(); ++j) {
            v[i] += D(i,j) * y[j];
        }
    }

    // Display the derivative approximations
    cout << "\n\n\n              **** Differentiation ****" << setprecision(3);
    cout << "\n\nResults of differentiation with " << PointsTypeMap[pointsType] << ":";
    cout << "\nderived = ";
    for(int i = 0; i < nPts; ++i) {
        cout << setw(6) << v[i] << " ";
    }

    // Determine the exact solutions
    cout << "\nexact   = ";
    for(int i = 0; i < nPts; ++i) {
        cout << setw(6) << derivativeFunction(z[i], nPts, pointsType) << " ";
    }

    // Display the pointwise error
    cout << setprecision(1);
    cout << "\nerror   = ";
    Linf = 0, RMS = 0;
    for(int i = 0; i < nPts; ++i) {
        long double exact = derivativeFunction(z[i], nPts, pointsType);
        long double error = exact - v[i];
        Linf = fmax(Linf, fabs(error));
        RMS += error*error;

        long double epsilon = 1e-2;
        if( fabs(exact) > epsilon ) {
            error /= exact;
        }
        cout << setw(6) << error << " ";
    }

    // Display the global error
    RMS = sqrt(RMS) / I.GetRows();
    cout << setprecision(6);
    cout << "\nLinf    = " << setw(6) << Linf;
    cout << "\nRMS     = " << setw(6) << RMS << endl;

    // Show the derivation matrix
    cout << "\nD = \n";
    for(int i = 0; i < D.GetRows(); ++i) {
        cout << "     ";
        for(int j = 0; j < D.GetColumns(); ++j) {
            printf("% 5.3f  ", D(i,j));
        }
        cout << "\n";
    }

      // /////////////////////////////////////////////////////////
     //                     Integration                        //
    // /////////////////////////////////////////////////////////

    // Integrate the function by approximating the integral as a weighted
    // linear combination of function evaluations at the z[i] points: y[i] = f(z[i])
    long double numericalIntegration = 0.0;
    for(int i = 0; i < nPts; ++i) {
        numericalIntegration += w[i] * y[i] / integrandWeightFunction(z[i], pointsType);
    }

    // Display the integral approximation
    cout << "\n\n\n              **** Integration ****" << setprecision(6);
    cout << "\n\nResults of integration with " << PointsTypeMap[pointsType] << ":";
    cout << "\nnumerical integral  = " << setw(12) << numericalIntegration;

    // Determine the exact solutions
    cout << "\nexact               = " << setw(12) << integrationFunction(nPts, pointsType);

    // Display the error
    cout << "\nerror               = ";
    {
        long double exact = integrationFunction(nPts, pointsType);
        long double error = exact - numericalIntegration;
        long double epsilon = 1e-2;
        if( fabs(exact) > epsilon ) {
            error /= exact;
        }
        cout << setw(12) << error;
    }

    // Show the weights
    cout << "\nquatdrature weights =      " << setprecision(3);
    for(int i = 0; i < nPts; ++i) {
        cout << setw(7) << w[i] << " ";
    }
    cout << endl;

}

<commit_msg>Fixed new changes of SharedArray stuff<commit_after>#include <iostream>
#include <iomanip>
#include <iosfwd>
#include <cmath>
#include <limits>

using namespace std;

#include "LibUtilities/Foundations/Foundations.hpp"
#include <LibUtilities/Foundations/Points.h>
#include <LibUtilities/Foundations/PolyEPoints.h>

using namespace Nektar;
using namespace Nektar::LibUtilities;

// Quintic polynomial
long double polyFunc(long double x)
{
    return  (((3.0*x*x - 5.0)*x + 1.0)*x - 2.0)*x + 3.0;
}

// Derivative of the Quintic polynomial
long double derivativePolyFunc(long double x)
{
    return ((15.0*x*x - 15.0)*x   + 2.0)*x - 2.0;
}

// A Fourier function that integrates to 0 with the Trapezoidal rule
long double fourierFunc(long double x, int N)
{
    long double z = M_PI*(x + 1.0);
    return (cos(N/2.0*z) + sin((N/2.0 - 2.0)*z))/M_PI;
}

// Derivative of the Fourier function above
long double derivativeFourierFunc(long double x, int N)
{
    long double z = M_PI*(x + 1.0);
    long double a = (N-4.0)/2.0;
    long double b = N/2.0;
    return M_PI*M_PI*(a*cos(a*z) - b*sin(b*z));
}

long double function(long double x, int N, PointsType type)
{
    long double y = 0;
    if( type == eFourierEvenlySpaced)
    {
        y = fourierFunc(x,N);
    } else
    {
        y = polyFunc(x);
    }
    return y;
}

long double derivativeFunction(long double x, int N, PointsType type)
{
    long double yDerivative = 0;
    if(type == eFourierEvenlySpaced)
    {
         yDerivative = derivativeFourierFunc(x, N);
    }
    else
    {
         yDerivative = derivativePolyFunc(x);
    }
    return yDerivative;
}

long double integrationFunction(int nPts, PointsType type)
{
   long double integral = 0;
   switch(type)
   {
       case  eFourierEvenlySpaced:
          integral = 0;
       break;
       default:
          integral = (long double)20.0/3.0;
   }
   return integral;
}

long double integrandWeightFunction(long double x, PointsType type)
{
    long double weight = 1;

    switch(type)
    {
        case eGaussGaussChebyshev:
        case eGaussRadauMChebyshev:
        case eGaussRadauPChebyshev:
        case eGaussLobattoChebyshev:
            weight = 1.0 / sqrt(1.0 - x*x);
        break;

        case eGaussRadauMAlpha0Beta1:
            // weight = 1.0 + x; // ?
        break;

        case eGaussRadauMAlpha0Beta2:
            // weight = (1.0 + x)*(1.0 + x); // ?
        break;

        default:
            weight = 1.0;
    }
    return weight;
}
// This routine projects a polynomial or trigonmetric functions which
// has energy in all modes of the expansions and report an error.

int main(int argc, char *argv[])
{

    // Argument check: Display a help message if the count is wrong
    if(argc != 3)
    {
        cerr << "Usage: FoundationDemo Points1D-Type nPts" << endl;

        cerr << "Where type is an integer value which dictates the basis as:\n";
        for(int i=0; i<SIZE_PointsType; ++i) {
            cerr << setw(30) << PointsTypeMap[i] << " = " << i << endl;
        }

        cerr << "Note type = 13, 14, and 15 are for two dimensional bases" << endl;
        cerr << "\nExample: FoundationDemo 5 6" << endl;
        cerr << "\n\t Tests GaussGaussChebyshev on 6 points" << endl;

        return 1; // Aborts main() function
    }

    // Read in the type for the points from the caller
    PointsType pointsType = (PointsType) atoi(argv[1]);
    if(pointsType == eNoPointsType)
    {
        cerr << "pointsType = " << pointsType << endl;
        cerr << "PointsTypeMap["<<pointsType<<"] = " << PointsTypeMap[pointsType] << endl;
        ErrorUtil::Error(ErrorUtil::efatal,__FILE__, __LINE__,
                  "No Points Type requested",0);
    }

    // Read in the number of points at which the function will be evaluated
    int nPts = atoi(argv[2]);

    // Show the set up to the user
    cout << "Points type:               " << PointsTypeMap[pointsType] << endl;
    cout << "Number of points:          " << nPts << endl;

    // Display the example test function to the user
    if( pointsType == eFourierEvenlySpaced )
    {
        cout << "Trigonometric function:    ";
        cout << "f(x) = (cos(N/2.0*z) + sin((N/2.0 - 2.0)*z))/M_PI, where z = M_PI*(x + 1.0)" << endl;
    }
    else
    {
        cout << "Quintic polynomial:        ";
        cout << "p(x) = (((3.0*x*x - 5.0)*x + 1.0)*x - 2.0)*x + 3.0" << endl;
    }

    // Obtain a reference to a Points object via an appropriate PointsKey object
    PointsKey key(nPts, pointsType);
    boost::shared_ptr<Points<NekDouble> > points = PointsManager()[key];
    //const ptr<Points<NekDouble> > points = PointsManager()[key];

    // Get the abscissas and their matching quadrature weights
   //    SharedArray<const NekDouble> z, w;
    ConstArray<OneD, NekDouble> z, w;
    points->GetZW(z,w);

    // Evaluate the example function at the z[i] points in the interval [-1,1].
    // This generates the data samples, which we store in the y vector and use later
    // during interpolation/integration/differentiation
    //    SharedArray<NekDouble> y(nPts);
    Array<OneD, NekDouble> y(nPts);
    for(int i = 0; i < nPts; ++i)
    {
        y[i] = function( z[i], nPts, pointsType );
    }

     // /////////////////////////////////////////////////////////
    //                     Interpolation                      //
   // /////////////////////////////////////////////////////////

    // Generate a list of interpolating nodes
    int nNodes = 2*nPts; // Number of interpolating nodes
    boost::shared_ptr<Points<NekDouble> > nodes = PointsManager()[PointsKey(nNodes, pointsType)];
   // const ptr<Points<NekDouble> > nodes = PointsManager()[PointsKey(nNodes, pointsType)];
    //SharedArray<const NekDouble> zNode = nodes->GetZ();
    ConstArray<OneD, NekDouble> zNode = nodes->GetZ();

    // Get the interpolation matrix I
    // Note that I is 2N rows by N columns
     const Points<NekDouble>::MatrixSharedPtrType Iptr = points->GetI(nNodes,zNode);
//     const Points<NekDouble>::MatrixSharedPtrType Iptr = points->GetI(nNodes, zNode);
    const NekMatrix<NekDouble> & I = *Iptr;

    // Interpolate the data values in the y vector using the interpolation matrix I
//     SharedArray<NekDouble> u(I.GetRows());
    Array<OneD, NekDouble> u(I.GetRows());
    for(int i = 0; i < int(I.GetRows()); ++i)
    {
        u[i] = 0;
        for(int j = 0; j < int(I.GetColumns()); ++j)
        {
            u[i] += I(i,j) * y[j];
        }
    }

    // Display the original samples
    cout << setprecision(3);
    cout << "\nOriginal data: \nx      = ";
    for(int i = 0; i < nPts; ++i)
    {
        cout << setw(6) << z[i] << " ";
    }
    cout << "\ny      = ";
    for(int i = 0; i < nPts; ++i)
    {
        cout << setw(6) << y[i] << " ";
    }

    // Display the interpolated data
    cout << "\n\n\n              **** Interpolation ****";
    cout << "\n\nResults of interpolation with " << PointsTypeMap[pointsType] << ":";
    cout << "\ninterp = ";
    for(int i = 0; i < nNodes; ++i)
    {
        cout << setw(6) << u[i] << " ";
    }

    // Determine the exact solutions
    cout << "\nexact  = ";
    for(int i = 0; i < nNodes; ++i)
    {
        cout << setw(6) << function(zNode[i], nPts, pointsType) << " ";
    }

    // Display the pointwise error
    cout << setprecision(1);
    cout << "\nerror  = ";
    long double Linf = 0, RMS = 0;
    for(int i = 0; i < int(I.GetRows()); ++i)
    {
        //long double exact = function(zNode[i], nNodes, pointsType);
        long double exact = function(zNode[i], nPts, pointsType);
        long double error = exact - u[i];
        Linf = max(Linf, fabs(error));
        RMS += error*error;
        long double epsilon = 1e-2;
        if( fabs(exact) > epsilon )
        {
            error /= exact;
        }
        cout << setw(6) << error << " ";
    }
    RMS = sqrt(RMS) / int(I.GetRows());
    cout << setprecision(6);
    cout << "\nLinf   = " << setw(6) << Linf;
    cout << "\nRMS    = " << setw(6) << RMS << endl;

    // Show the interpolation matrix
    cout << "\nI = \n";
    for(int i = 0; i < int(I.GetRows()); ++i)
    {
        cout << "     ";
        for(int j = 0; j < int(I.GetColumns()); ++j)
        {
            printf("% 5.3f  ", I(i,j));
        }
        cout << "\n";
    }

      // /////////////////////////////////////////////////////////
     //                     Derivation                         //
    // /////////////////////////////////////////////////////////

    // Get the derivation matrix D
    // Note that, unlike I, D is N rows by N columns
    const Points<NekDouble>::MatrixSharedPtrType Dptr = points->GetD();
    const NekMatrix<NekDouble> & D = *Dptr;

    // Differentiate the data values in the y vector using the derivative matrix D
    Array<OneD, NekDouble> v(nPts);
    for(int i = 0; i < int(D.GetRows()); ++i)
    {
        v[i] = 0;
        for(int j = 0; j < int(D.GetColumns()); ++j)
        {
            v[i] += D(i,j) * y[j];
        }
    }

    // Display the derivative approximations
    cout << "\n\n\n              **** Differentiation ****" << setprecision(3);
    cout << "\n\nResults of differentiation with " << PointsTypeMap[pointsType] << ":";
    cout << "\nderived = ";
    for(int i = 0; i < nPts; ++i)
    {
        cout << setw(6) << v[i] << " ";
    }

    // Determine the exact solutions
    cout << "\nexact   = ";
    for(int i = 0; i < nPts; ++i)
    {
        cout << setw(6) << derivativeFunction(z[i], nPts, pointsType) << " ";
    }

    // Display the pointwise error
    cout << setprecision(1);
    cout << "\nerror   = ";
    Linf = 0, RMS = 0;
    for(int i = 0; i < nPts; ++i)
    {
        long double exact = derivativeFunction(z[i], nPts, pointsType);
        long double error = exact - v[i];
        Linf = max(Linf, fabs(error));
        RMS += error*error;

        long double epsilon = 1e-2;
        if( fabs(exact) > epsilon )
        {
            error /= exact;
        }
        cout << setw(6) << error << " ";
    }

    // Display the global error
    RMS = sqrt(RMS) / I.GetRows();
    cout << setprecision(6);
    cout << "\nLinf    = " << setw(6) << Linf;
    cout << "\nRMS     = " << setw(6) << RMS << endl;

    // Show the derivation matrix
    cout << "\nD = \n";
    for(int i = 0; i < int(D.GetRows()); ++i)
    {
        cout << "     ";
        for(int j = 0; j < int(D.GetColumns()); ++j)
        {
            printf("% 5.3f  ", D(i,j));
        }
        cout << "\n";
    }

      // /////////////////////////////////////////////////////////
     //                     Integration                        //
    // /////////////////////////////////////////////////////////

    // Integrate the function by approximating the integral as a weighted
    // linear combination of function evaluations at the z[i] points: y[i] = f(z[i])
    long double numericalIntegration = 0.0;
    for(int i = 0; i < nPts; ++i)
    {
        numericalIntegration += w[i] * y[i] / integrandWeightFunction(z[i], pointsType);
    }

    // Display the integral approximation
    cout << "\n\n\n              **** Integration ****" << setprecision(6);
    cout << "\n\nResults of integration with " << PointsTypeMap[pointsType] << ":";
    cout << "\nnumerical integral  = " << setw(12) << numericalIntegration;

    // Determine the exact solutions
    cout << "\nexact               = " << setw(12) << integrationFunction(nPts, pointsType);

    // Display the error
    cout << "\nerror               = ";
    {
        long double exact = integrationFunction(nPts, pointsType);
        long double error = exact - numericalIntegration;
        long double epsilon = 1e-2;
        if( fabs(exact) > epsilon )
        {
            error /= exact;
        }
        cout << setw(12) << error;
    }

    // Show the weights
    cout << "\nquatdrature weights =      " << setprecision(3);
    for(int i = 0; i < nPts; ++i)
    {
        cout << setw(7) << w[i] << " ";
    }
    cout << endl;

}

<|endoftext|>


<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "overviewpage.h"
#include "ui_overviewpage.h"

#include "bitcoinunits.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "init.h"
#include "obfuscation.h"
#include "obfuscationconfig.h"
#include "optionsmodel.h"
#include "transactionfilterproxy.h"
#include "transactiontablemodel.h"
#include "walletmodel.h"

#include <QAbstractItemDelegate>
#include <QPainter>
#include <QSettings>
#include <QTimer>

#define DECORATION_SIZE 48
#define ICON_OFFSET 16
#define NUM_ITEMS 5

class TxViewDelegate : public QAbstractItemDelegate
{
    Q_OBJECT
public:
    TxViewDelegate() : QAbstractItemDelegate(), unit(BitcoinUnits::PIV)
    {
    }

    inline void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
    {
        painter->save();

        QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
        QRect mainRect = option.rect;
        mainRect.moveLeft(ICON_OFFSET);
        QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
        int xspace = DECORATION_SIZE + 8;
        int ypad = 6;
        int halfheight = (mainRect.height() - 2 * ypad) / 2;
        QRect amountRect(mainRect.left() + xspace, mainRect.top() + ypad, mainRect.width() - xspace - ICON_OFFSET, halfheight);
        QRect addressRect(mainRect.left() + xspace, mainRect.top() + ypad + halfheight, mainRect.width() - xspace, halfheight);
        icon.paint(painter, decorationRect);

        QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
        QString address = index.data(Qt::DisplayRole).toString();
        qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
        bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();
        QVariant value = index.data(Qt::ForegroundRole);
        QColor foreground = COLOR_BLACK;
        if (value.canConvert<QBrush>()) {
            QBrush brush = qvariant_cast<QBrush>(value);
            foreground = brush.color();
        }

        painter->setPen(foreground);
        QRect boundingRect;
        painter->drawText(addressRect, Qt::AlignLeft | Qt::AlignVCenter, address, &boundingRect);

        if (index.data(TransactionTableModel::WatchonlyRole).toBool()) {
            QIcon iconWatchonly = qvariant_cast<QIcon>(index.data(TransactionTableModel::WatchonlyDecorationRole));
            QRect watchonlyRect(boundingRect.right() + 5, mainRect.top() + ypad + halfheight, 16, halfheight);
            iconWatchonly.paint(painter, watchonlyRect);
        }

        if (amount < 0) {
            foreground = COLOR_NEGATIVE;
        } else if (!confirmed) {
            foreground = COLOR_UNCONFIRMED;
        } else {
            foreground = COLOR_BLACK;
        }
        painter->setPen(foreground);
        QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true, BitcoinUnits::separatorAlways);
        if (!confirmed) {
            amountText = QString("[") + amountText + QString("]");
        }
        painter->drawText(amountRect, Qt::AlignRight | Qt::AlignVCenter, amountText);

        painter->setPen(COLOR_BLACK);
        painter->drawText(amountRect, Qt::AlignLeft | Qt::AlignVCenter, GUIUtil::dateTimeStr(date));

        painter->restore();
    }

    inline QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
    {
        return QSize(DECORATION_SIZE, DECORATION_SIZE);
    }

    int unit;
};
#include "overviewpage.moc"

OverviewPage::OverviewPage(QWidget* parent) : QWidget(parent),
                                              ui(new Ui::OverviewPage),
                                              clientModel(0),
                                              walletModel(0),
                                              currentBalance(-1),
                                              currentUnconfirmedBalance(-1),
                                              currentImmatureBalance(-1),
                                              currentZerocoinBalance(-1),
                                              currentWatchOnlyBalance(-1),
                                              currentWatchUnconfBalance(-1),
                                              currentWatchImmatureBalance(-1),
                                              txdelegate(new TxViewDelegate()),
                                              filter(0)
{
    nDisplayUnit = 0; // just make sure it's not unitialized
    ui->setupUi(this);

    // Recent transactions
    ui->listTransactions->setItemDelegate(txdelegate);
    ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
    ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
    ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);

    connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));

    // init "out of sync" warning labels
    ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
    ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");

    // start with displaying the "out of sync" warnings
    showOutOfSyncWarning(true);
}

void OverviewPage::handleTransactionClicked(const QModelIndex& index)
{
    if (filter)
        emit transactionClicked(filter->mapToSource(index));
}

OverviewPage::~OverviewPage()
{
    if (!fLiteMode && !fMasterNode) disconnect(timer, SIGNAL(timeout()), this, SLOT(obfuScationStatus()));
    delete ui;
}

void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& zerocoinBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance)
{
    currentBalance = balance;
    currentUnconfirmedBalance = unconfirmedBalance;
    currentImmatureBalance = immatureBalance;
    currentZerocoinBalance = zerocoinBalance;
    currentWatchOnlyBalance = watchOnlyBalance;
    currentWatchUnconfBalance = watchUnconfBalance;
    currentWatchImmatureBalance = watchImmatureBalance;

    ui->labelBalance->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance - immatureBalance, false, BitcoinUnits::separatorAlways));
    ui->labelzBalance->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, zerocoinBalance, false, BitcoinUnits::separatorAlways));
    ui->labelUnconfirmed->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, unconfirmedBalance, false, BitcoinUnits::separatorAlways));
    ui->labelImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, immatureBalance, false, BitcoinUnits::separatorAlways));
    ui->labelTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance + unconfirmedBalance, false, BitcoinUnits::separatorAlways));

    ui->labelWatchAvailable->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchOnlyBalance, false, BitcoinUnits::separatorAlways));
    ui->labelWatchPending->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchUnconfBalance, false, BitcoinUnits::separatorAlways));
    ui->labelWatchImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchImmatureBalance, false, BitcoinUnits::separatorAlways));
    ui->labelWatchTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchOnlyBalance + watchUnconfBalance + watchImmatureBalance, false, BitcoinUnits::separatorAlways));

    // only show immature (newly mined) balance if it's non-zero, so as not to complicate things
    // for the non-mining users
    bool showImmature = immatureBalance != 0;
    bool showWatchOnlyImmature = watchImmatureBalance != 0;

    // for symmetry reasons also show immature label when the watch-only one is shown
    ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature);
    ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature);
    ui->labelWatchImmature->setVisible(showWatchOnlyImmature); // show watch-only immature balance

    static int cachedTxLocks = 0;

    if (cachedTxLocks != nCompleteTXLocks) {
        cachedTxLocks = nCompleteTXLocks;
        ui->listTransactions->update();
    }
}

// show/hide watch-only labels
void OverviewPage::updateWatchOnlyLabels(bool showWatchOnly)
{
    ui->labelSpendable->setVisible(showWatchOnly);      // show spendable label (only when watch-only is active)
    ui->labelWatchonly->setVisible(showWatchOnly);      // show watch-only label
    ui->lineWatchBalance->setVisible(showWatchOnly);    // show watch-only balance separator line
    ui->labelWatchAvailable->setVisible(showWatchOnly); // show watch-only available balance
    ui->labelWatchPending->setVisible(showWatchOnly);   // show watch-only pending balance
    ui->labelWatchTotal->setVisible(showWatchOnly);     // show watch-only total balance

    if (!showWatchOnly) {
        ui->labelWatchImmature->hide();
    } else {
        ui->labelBalance->setIndent(20);
        ui->labelUnconfirmed->setIndent(20);
        ui->labelImmature->setIndent(20);
        ui->labelTotal->setIndent(20);
    }
}

void OverviewPage::setClientModel(ClientModel* model)
{
    this->clientModel = model;
    if (model) {
        // Show warning if this is a prerelease version
        connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));
        updateAlerts(model->getStatusBarWarnings());
    }
}

void OverviewPage::setWalletModel(WalletModel* model)
{
    this->walletModel = model;
    if (model && model->getOptionsModel()) {
        // Set up transaction list
        filter = new TransactionFilterProxy();
        filter->setSourceModel(model->getTransactionTableModel());
        filter->setLimit(NUM_ITEMS);
        filter->setDynamicSortFilter(true);
        filter->setSortRole(Qt::EditRole);
        filter->setShowInactive(false);
        filter->sort(TransactionTableModel::Date, Qt::DescendingOrder);

        ui->listTransactions->setModel(filter);
        ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);

        // Keep up to date with wallet
        setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getZerocoinBalance(),
            model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());
        connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)));

        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));

        updateWatchOnlyLabels(model->haveWatchOnly());
        connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool)));
    }

    // update the display unit, to not use the default ("PIV")
    updateDisplayUnit();
}

void OverviewPage::updateDisplayUnit()
{
    if (walletModel && walletModel->getOptionsModel()) {
        nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit();
        if (currentBalance != -1)
            setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentZerocoinBalance,
                currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance);

        // Update txdelegate->unit with the current unit
        txdelegate->unit = nDisplayUnit;

        ui->listTransactions->update();
    }
}

void OverviewPage::updateAlerts(const QString& warnings)
{
    this->ui->labelAlerts->setVisible(!warnings.isEmpty());
    this->ui->labelAlerts->setText(warnings);
}

void OverviewPage::showOutOfSyncWarning(bool fShow)
{
    ui->labelWalletStatus->setVisible(fShow);
    ui->labelTransactionsStatus->setVisible(fShow);
}
<commit_msg>Fix segfault on exit<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "overviewpage.h"
#include "ui_overviewpage.h"

#include "bitcoinunits.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "init.h"
#include "obfuscation.h"
#include "obfuscationconfig.h"
#include "optionsmodel.h"
#include "transactionfilterproxy.h"
#include "transactiontablemodel.h"
#include "walletmodel.h"

#include <QAbstractItemDelegate>
#include <QPainter>
#include <QSettings>
#include <QTimer>

#define DECORATION_SIZE 48
#define ICON_OFFSET 16
#define NUM_ITEMS 5

class TxViewDelegate : public QAbstractItemDelegate
{
    Q_OBJECT
public:
    TxViewDelegate() : QAbstractItemDelegate(), unit(BitcoinUnits::PIV)
    {
    }

    inline void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
    {
        painter->save();

        QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
        QRect mainRect = option.rect;
        mainRect.moveLeft(ICON_OFFSET);
        QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
        int xspace = DECORATION_SIZE + 8;
        int ypad = 6;
        int halfheight = (mainRect.height() - 2 * ypad) / 2;
        QRect amountRect(mainRect.left() + xspace, mainRect.top() + ypad, mainRect.width() - xspace - ICON_OFFSET, halfheight);
        QRect addressRect(mainRect.left() + xspace, mainRect.top() + ypad + halfheight, mainRect.width() - xspace, halfheight);
        icon.paint(painter, decorationRect);

        QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
        QString address = index.data(Qt::DisplayRole).toString();
        qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
        bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();
        QVariant value = index.data(Qt::ForegroundRole);
        QColor foreground = COLOR_BLACK;
        if (value.canConvert<QBrush>()) {
            QBrush brush = qvariant_cast<QBrush>(value);
            foreground = brush.color();
        }

        painter->setPen(foreground);
        QRect boundingRect;
        painter->drawText(addressRect, Qt::AlignLeft | Qt::AlignVCenter, address, &boundingRect);

        if (index.data(TransactionTableModel::WatchonlyRole).toBool()) {
            QIcon iconWatchonly = qvariant_cast<QIcon>(index.data(TransactionTableModel::WatchonlyDecorationRole));
            QRect watchonlyRect(boundingRect.right() + 5, mainRect.top() + ypad + halfheight, 16, halfheight);
            iconWatchonly.paint(painter, watchonlyRect);
        }

        if (amount < 0) {
            foreground = COLOR_NEGATIVE;
        } else if (!confirmed) {
            foreground = COLOR_UNCONFIRMED;
        } else {
            foreground = COLOR_BLACK;
        }
        painter->setPen(foreground);
        QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true, BitcoinUnits::separatorAlways);
        if (!confirmed) {
            amountText = QString("[") + amountText + QString("]");
        }
        painter->drawText(amountRect, Qt::AlignRight | Qt::AlignVCenter, amountText);

        painter->setPen(COLOR_BLACK);
        painter->drawText(amountRect, Qt::AlignLeft | Qt::AlignVCenter, GUIUtil::dateTimeStr(date));

        painter->restore();
    }

    inline QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
    {
        return QSize(DECORATION_SIZE, DECORATION_SIZE);
    }

    int unit;
};
#include "overviewpage.moc"

OverviewPage::OverviewPage(QWidget* parent) : QWidget(parent),
                                              ui(new Ui::OverviewPage),
                                              clientModel(0),
                                              walletModel(0),
                                              currentBalance(-1),
                                              currentUnconfirmedBalance(-1),
                                              currentImmatureBalance(-1),
                                              currentZerocoinBalance(-1),
                                              currentWatchOnlyBalance(-1),
                                              currentWatchUnconfBalance(-1),
                                              currentWatchImmatureBalance(-1),
                                              txdelegate(new TxViewDelegate()),
                                              filter(0)
{
    nDisplayUnit = 0; // just make sure it's not unitialized
    ui->setupUi(this);

    // Recent transactions
    ui->listTransactions->setItemDelegate(txdelegate);
    ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
    ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
    ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);

    connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));

    // init "out of sync" warning labels
    ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
    ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");

    // start with displaying the "out of sync" warnings
    showOutOfSyncWarning(true);
}

void OverviewPage::handleTransactionClicked(const QModelIndex& index)
{
    if (filter)
        emit transactionClicked(filter->mapToSource(index));
}

OverviewPage::~OverviewPage()
{
    delete ui;
}

void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& zerocoinBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance)
{
    currentBalance = balance;
    currentUnconfirmedBalance = unconfirmedBalance;
    currentImmatureBalance = immatureBalance;
    currentZerocoinBalance = zerocoinBalance;
    currentWatchOnlyBalance = watchOnlyBalance;
    currentWatchUnconfBalance = watchUnconfBalance;
    currentWatchImmatureBalance = watchImmatureBalance;

    ui->labelBalance->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance - immatureBalance, false, BitcoinUnits::separatorAlways));
    ui->labelzBalance->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, zerocoinBalance, false, BitcoinUnits::separatorAlways));
    ui->labelUnconfirmed->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, unconfirmedBalance, false, BitcoinUnits::separatorAlways));
    ui->labelImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, immatureBalance, false, BitcoinUnits::separatorAlways));
    ui->labelTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance + unconfirmedBalance, false, BitcoinUnits::separatorAlways));

    ui->labelWatchAvailable->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchOnlyBalance, false, BitcoinUnits::separatorAlways));
    ui->labelWatchPending->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchUnconfBalance, false, BitcoinUnits::separatorAlways));
    ui->labelWatchImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchImmatureBalance, false, BitcoinUnits::separatorAlways));
    ui->labelWatchTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchOnlyBalance + watchUnconfBalance + watchImmatureBalance, false, BitcoinUnits::separatorAlways));

    // only show immature (newly mined) balance if it's non-zero, so as not to complicate things
    // for the non-mining users
    bool showImmature = immatureBalance != 0;
    bool showWatchOnlyImmature = watchImmatureBalance != 0;

    // for symmetry reasons also show immature label when the watch-only one is shown
    ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature);
    ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature);
    ui->labelWatchImmature->setVisible(showWatchOnlyImmature); // show watch-only immature balance

    static int cachedTxLocks = 0;

    if (cachedTxLocks != nCompleteTXLocks) {
        cachedTxLocks = nCompleteTXLocks;
        ui->listTransactions->update();
    }
}

// show/hide watch-only labels
void OverviewPage::updateWatchOnlyLabels(bool showWatchOnly)
{
    ui->labelSpendable->setVisible(showWatchOnly);      // show spendable label (only when watch-only is active)
    ui->labelWatchonly->setVisible(showWatchOnly);      // show watch-only label
    ui->lineWatchBalance->setVisible(showWatchOnly);    // show watch-only balance separator line
    ui->labelWatchAvailable->setVisible(showWatchOnly); // show watch-only available balance
    ui->labelWatchPending->setVisible(showWatchOnly);   // show watch-only pending balance
    ui->labelWatchTotal->setVisible(showWatchOnly);     // show watch-only total balance

    if (!showWatchOnly) {
        ui->labelWatchImmature->hide();
    } else {
        ui->labelBalance->setIndent(20);
        ui->labelUnconfirmed->setIndent(20);
        ui->labelImmature->setIndent(20);
        ui->labelTotal->setIndent(20);
    }
}

void OverviewPage::setClientModel(ClientModel* model)
{
    this->clientModel = model;
    if (model) {
        // Show warning if this is a prerelease version
        connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));
        updateAlerts(model->getStatusBarWarnings());
    }
}

void OverviewPage::setWalletModel(WalletModel* model)
{
    this->walletModel = model;
    if (model && model->getOptionsModel()) {
        // Set up transaction list
        filter = new TransactionFilterProxy();
        filter->setSourceModel(model->getTransactionTableModel());
        filter->setLimit(NUM_ITEMS);
        filter->setDynamicSortFilter(true);
        filter->setSortRole(Qt::EditRole);
        filter->setShowInactive(false);
        filter->sort(TransactionTableModel::Date, Qt::DescendingOrder);

        ui->listTransactions->setModel(filter);
        ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);

        // Keep up to date with wallet
        setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getZerocoinBalance(),
            model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());
        connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)));

        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));

        updateWatchOnlyLabels(model->haveWatchOnly());
        connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool)));
    }

    // update the display unit, to not use the default ("PIV")
    updateDisplayUnit();
}

void OverviewPage::updateDisplayUnit()
{
    if (walletModel && walletModel->getOptionsModel()) {
        nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit();
        if (currentBalance != -1)
            setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentZerocoinBalance,
                currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance);

        // Update txdelegate->unit with the current unit
        txdelegate->unit = nDisplayUnit;

        ui->listTransactions->update();
    }
}

void OverviewPage::updateAlerts(const QString& warnings)
{
    this->ui->labelAlerts->setVisible(!warnings.isEmpty());
    this->ui->labelAlerts->setText(warnings);
}

void OverviewPage::showOutOfSyncWarning(bool fShow)
{
    ui->labelWalletStatus->setVisible(fShow);
    ui->labelTransactionsStatus->setVisible(fShow);
}
<|endoftext|>


<commit_before>

#include <QWidget>
#include <QListView>

#include "overviewpage.h"
#include "ui_overviewpage.h"

#ifndef Q_MOC_RUN
#include "main.h"
#endif
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "optionsmodel.h"
#include "transactiontablemodel.h"
#include "transactionfilterproxy.h"
#include "guiutil.h"
#include "guiconstants.h"

#include <QAbstractItemDelegate>
#include <QPainter>

#ifdef WIN32
#include <QAxObject>
#include "../global_objects.hpp"
#include "../global_objects_noui.hpp"
#endif

#define DECORATION_SIZE 64

class TxViewDelegate : public QAbstractItemDelegate
{
    Q_OBJECT
public:
    TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC)
    {

    }

    inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
                      const QModelIndex &index ) const
    {
        painter->save();

        QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
        QRect mainRect = option.rect;
        QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
        int xspace = DECORATION_SIZE + 8;
        int ypad = 6;
        int halfheight = (mainRect.height() - 2*ypad)/2;
        QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);
        QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);
        icon.paint(painter, decorationRect);

        QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
        QString address = index.data(Qt::DisplayRole).toString();
        qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
        bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();

		//QColor foreground = option.palette.color(QPalette::Text);
		//R Halford: 11-28-2013:
		QColor foreground = QColor(200, 0, 0);

        QVariant value = index.data(Qt::ForegroundRole);
        //QColor foreground = option.palette.color(QPalette::Text);
        if(value.canConvert(QMetaType::QColor))
        {
            foreground = qvariant_cast<QColor>(value);
        }

        painter->setPen(foreground);
        painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);

        if(amount < 0)
        {
            foreground = COLOR_NEGATIVE;
        }
        else if(!confirmed)
        {
            foreground = COLOR_UNCONFIRMED;
        }
        else
        {
            foreground = option.palette.color(QPalette::Text);
        }
        painter->setPen(foreground);
        QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);
        if(!confirmed)
        {
            amountText = QString("[") + amountText + QString("]");
        }
        painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);

        painter->setPen(option.palette.color(QPalette::Text));
        painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));

        painter->restore();
    }

    inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        return QSize(DECORATION_SIZE, DECORATION_SIZE);
    }

    int unit;

};
#include "overviewpage.moc"

OverviewPage::OverviewPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OverviewPage),
    currentBalance(-1),
    currentStake(0),
    currentUnconfirmedBalance(-1),
    currentImmatureBalance(-1),
    txdelegate(new TxViewDelegate()),
    filter(0)
{
    ui->setupUi(this);

    // Recent transactions
    ui->listTransactions->setItemDelegate(txdelegate);
    ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
    ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);
    updateTransactions();

    connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));

    // init "out of sync" warning labels
    ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
    ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");

    // start with displaying the "out of sync" warnings
    showOutOfSyncWarning(true);
}

void OverviewPage::handleTransactionClicked(const QModelIndex &index)
{
	OverviewPage::UpdateBoincUtilization();

    if(filter)
        emit transactionClicked(filter->mapToSource(index));
}

void OverviewPage::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    updateTransactions();
}

void OverviewPage::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    updateTransactions();
}

void OverviewPage::updateTransactions()
{
    if(filter)
    {
        // Show the maximum number of transactions the transaction list widget
        // can hold without overflowing.
        const size_t itemHeight = DECORATION_SIZE + ui->listTransactions->spacing();
        const size_t contentsHeight = ui->listTransactions->height();
        const size_t numItems = contentsHeight / itemHeight;
        filter->setLimit(numItems);
        ui->listTransactions->update();
    }
}

OverviewPage::~OverviewPage()
{
    delete ui;
}

void OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)
{
    int unit = model->getOptionsModel()->getDisplayUnit();
    currentBalance = balance;
    currentStake = stake;
    currentUnconfirmedBalance = unconfirmedBalance;
    currentImmatureBalance = immatureBalance;
    ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
    ui->labelStake->setText(BitcoinUnits::formatWithUnit(unit, stake));
    ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));
    ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));
    ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, balance + stake + unconfirmedBalance + immatureBalance));

    // only show immature (newly mined) balance if it's non-zero, so as not to complicate things
    // for the non-mining users
    bool showImmature = immatureBalance != 0;
    ui->labelImmature->setVisible(showImmature);
    ui->labelImmatureText->setVisible(showImmature);
	OverviewPage::UpdateBoincUtilization();

}

void OverviewPage::UpdateBoincUtilization()
{
    LOCK(GlobalStatusStruct.lock);
    ui->labelBlocks->setText(QString::fromUtf8(GlobalStatusStruct.blocks.c_str()));
    ui->labelDifficulty->setText(QString::fromUtf8(GlobalStatusStruct.difficulty.c_str()));
    ui->labelNetWeight->setText(QString::fromUtf8(GlobalStatusStruct.netWeight.c_str()));
    ui->labelCoinWeight->setText(QString::fromUtf8(GlobalStatusStruct.coinWeight.c_str()));
    ui->labelMagnitude->setText(QString::fromUtf8(GlobalStatusStruct.magnitude.c_str()));
    ui->labelProject->setText(QString::fromUtf8(GlobalStatusStruct.project.c_str()));
    ui->labelCpid->setText(QString::fromUtf8(GlobalStatusStruct.cpid.c_str()));
    ui->labelStatus->setText(QString::fromUtf8(GlobalStatusStruct.status.c_str()));
    ui->labelPoll->setText(QString::fromUtf8(GlobalStatusStruct.poll.c_str()).replace(QChar('_'),QChar(' '), Qt::CaseSensitive));
    ui->labelErrors->setText(QString::fromUtf8(GlobalStatusStruct.errors.c_str()));
}

void OverviewPage::setModel(WalletModel *model)
{
    this->model = model;
    if(model && model->getOptionsModel())
    {
        // Set up transaction list
        filter = new TransactionFilterProxy();
        filter->setSourceModel(model->getTransactionTableModel());
        filter->setDynamicSortFilter(true);
        filter->setSortRole(Qt::EditRole);
        filter->setShowInactive(false);
        filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);

        ui->listTransactions->setModel(filter);
        ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);

        // Keep up to date with wallet
        setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());
        connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));

        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
        UpdateBoincUtilization();
    }

    // update the display unit, to not use the default ("BTC")
    updateDisplayUnit();
}

void OverviewPage::updateDisplayUnit()
{
    if(model && model->getOptionsModel())
    {
        if(currentBalance != -1)
            setBalance(currentBalance, model->getStake(), currentUnconfirmedBalance, currentImmatureBalance);

        // Update txdelegate->unit with the current unit
        txdelegate->unit = model->getOptionsModel()->getDisplayUnit();

        ui->listTransactions->update();
    }
}

void OverviewPage::showOutOfSyncWarning(bool fShow)
{
    ui->labelWalletStatus->setVisible(fShow);
    ui->labelTransactionsStatus->setVisible(fShow);
	OverviewPage::UpdateBoincUtilization();
}

void OverviewPage::updateglobalstatus()
{

	OverviewPage::UpdateBoincUtilization();
}

<commit_msg>Change QVariant cast check.<commit_after>

#include <QWidget>
#include <QListView>

#include "overviewpage.h"
#include "ui_overviewpage.h"

#ifndef Q_MOC_RUN
#include "main.h"
#endif
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "optionsmodel.h"
#include "transactiontablemodel.h"
#include "transactionfilterproxy.h"
#include "guiutil.h"
#include "guiconstants.h"

#include <QAbstractItemDelegate>
#include <QPainter>

#ifdef WIN32
#include <QAxObject>
#include "../global_objects.hpp"
#include "../global_objects_noui.hpp"
#endif

#define DECORATION_SIZE 64

class TxViewDelegate : public QAbstractItemDelegate
{
    Q_OBJECT
public:
    TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC)
    {

    }

    inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
                      const QModelIndex &index ) const
    {
        painter->save();

        QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
        QRect mainRect = option.rect;
        QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
        int xspace = DECORATION_SIZE + 8;
        int ypad = 6;
        int halfheight = (mainRect.height() - 2*ypad)/2;
        QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);
        QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);
        icon.paint(painter, decorationRect);

        QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
        QString address = index.data(Qt::DisplayRole).toString();
        qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
        bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();

		QColor foreground = QColor(200, 0, 0);
        QVariant value = index.data(Qt::ForegroundRole);
        if(value.canConvert<QColor>())
        {
            foreground = qvariant_cast<QColor>(value);
        }

        painter->setPen(foreground);
        painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);

        if(amount < 0)
        {
            foreground = COLOR_NEGATIVE;
        }
        else if(!confirmed)
        {
            foreground = COLOR_UNCONFIRMED;
        }
        else
        {
            foreground = option.palette.color(QPalette::Text);
        }
        painter->setPen(foreground);
        QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);
        if(!confirmed)
        {
            amountText = QString("[") + amountText + QString("]");
        }
        painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);

        painter->setPen(option.palette.color(QPalette::Text));
        painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));

        painter->restore();
    }

    inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        return QSize(DECORATION_SIZE, DECORATION_SIZE);
    }

    int unit;

};
#include "overviewpage.moc"

OverviewPage::OverviewPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OverviewPage),
    currentBalance(-1),
    currentStake(0),
    currentUnconfirmedBalance(-1),
    currentImmatureBalance(-1),
    txdelegate(new TxViewDelegate()),
    filter(0)
{
    ui->setupUi(this);

    // Recent transactions
    ui->listTransactions->setItemDelegate(txdelegate);
    ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
    ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);
    updateTransactions();

    connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));

    // init "out of sync" warning labels
    ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
    ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");

    // start with displaying the "out of sync" warnings
    showOutOfSyncWarning(true);
}

void OverviewPage::handleTransactionClicked(const QModelIndex &index)
{
	OverviewPage::UpdateBoincUtilization();

    if(filter)
        emit transactionClicked(filter->mapToSource(index));
}

void OverviewPage::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    updateTransactions();
}

void OverviewPage::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    updateTransactions();
}

void OverviewPage::updateTransactions()
{
    if(filter)
    {
        // Show the maximum number of transactions the transaction list widget
        // can hold without overflowing.
        const size_t itemHeight = DECORATION_SIZE + ui->listTransactions->spacing();
        const size_t contentsHeight = ui->listTransactions->height();
        const size_t numItems = contentsHeight / itemHeight;
        filter->setLimit(numItems);
        ui->listTransactions->update();
    }
}

OverviewPage::~OverviewPage()
{
    delete ui;
}

void OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)
{
    int unit = model->getOptionsModel()->getDisplayUnit();
    currentBalance = balance;
    currentStake = stake;
    currentUnconfirmedBalance = unconfirmedBalance;
    currentImmatureBalance = immatureBalance;
    ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
    ui->labelStake->setText(BitcoinUnits::formatWithUnit(unit, stake));
    ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));
    ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));
    ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, balance + stake + unconfirmedBalance + immatureBalance));

    // only show immature (newly mined) balance if it's non-zero, so as not to complicate things
    // for the non-mining users
    bool showImmature = immatureBalance != 0;
    ui->labelImmature->setVisible(showImmature);
    ui->labelImmatureText->setVisible(showImmature);
	OverviewPage::UpdateBoincUtilization();

}

void OverviewPage::UpdateBoincUtilization()
{
    LOCK(GlobalStatusStruct.lock);
    ui->labelBlocks->setText(QString::fromUtf8(GlobalStatusStruct.blocks.c_str()));
    ui->labelDifficulty->setText(QString::fromUtf8(GlobalStatusStruct.difficulty.c_str()));
    ui->labelNetWeight->setText(QString::fromUtf8(GlobalStatusStruct.netWeight.c_str()));
    ui->labelCoinWeight->setText(QString::fromUtf8(GlobalStatusStruct.coinWeight.c_str()));
    ui->labelMagnitude->setText(QString::fromUtf8(GlobalStatusStruct.magnitude.c_str()));
    ui->labelProject->setText(QString::fromUtf8(GlobalStatusStruct.project.c_str()));
    ui->labelCpid->setText(QString::fromUtf8(GlobalStatusStruct.cpid.c_str()));
    ui->labelStatus->setText(QString::fromUtf8(GlobalStatusStruct.status.c_str()));
    ui->labelPoll->setText(QString::fromUtf8(GlobalStatusStruct.poll.c_str()).replace(QChar('_'),QChar(' '), Qt::CaseSensitive));
    ui->labelErrors->setText(QString::fromUtf8(GlobalStatusStruct.errors.c_str()));
}

void OverviewPage::setModel(WalletModel *model)
{
    this->model = model;
    if(model && model->getOptionsModel())
    {
        // Set up transaction list
        filter = new TransactionFilterProxy();
        filter->setSourceModel(model->getTransactionTableModel());
        filter->setDynamicSortFilter(true);
        filter->setSortRole(Qt::EditRole);
        filter->setShowInactive(false);
        filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);

        ui->listTransactions->setModel(filter);
        ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);

        // Keep up to date with wallet
        setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());
        connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));

        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
        UpdateBoincUtilization();
    }

    // update the display unit, to not use the default ("BTC")
    updateDisplayUnit();
}

void OverviewPage::updateDisplayUnit()
{
    if(model && model->getOptionsModel())
    {
        if(currentBalance != -1)
            setBalance(currentBalance, model->getStake(), currentUnconfirmedBalance, currentImmatureBalance);

        // Update txdelegate->unit with the current unit
        txdelegate->unit = model->getOptionsModel()->getDisplayUnit();

        ui->listTransactions->update();
    }
}

void OverviewPage::showOutOfSyncWarning(bool fShow)
{
    ui->labelWalletStatus->setVisible(fShow);
    ui->labelTransactionsStatus->setVisible(fShow);
	OverviewPage::UpdateBoincUtilization();
}

void OverviewPage::updateglobalstatus()
{

	OverviewPage::UpdateBoincUtilization();
}

<|endoftext|>