<commit_before>#include "network_chooser.h"
#include "libcmm_net_restriction.h"

#include <map>
using std::make_pair;

NetworkChooser*
NetworkChooser::create(int redundancy_strategy_type)
{
    switch (redundancy_strategy_type) {
    case CELLULAR_ONLY:
        return new PreferredNetwork(NET_TYPE_THREEG);
    case WIFI_PREFERRED:
        return new PreferredNetwork(NET_TYPE_WIFI);
    case INTNW_NEVER_REDUNDANT:
    case INTNW_REDUNDANT:
    case ALWAYS_REDUNDANT:
        return new LabelMatcher;
    default:
        assert(0);
    }
}

PreferredNetwork::PreferredNetwork(int preferred_type_)
{
    preferred_type = preferred_type_;
}

void
PreferredNetwork::reset()
{
    has_match = false;
}

void
PreferredNetwork::consider(struct net_interface local_iface,
                           struct net_interface remote_iface)
{
    if (!has_match || matches_type(preferred_type, local_iface, remote_iface)) {
        has_match = true;
        local = local_iface;
        remote = remote_iface;
    }
}

bool
PreferredNetwork::choose_networks(u_long send_label,
                                  struct net_interface& local_iface,
                                  struct net_interface& remote_iface)
{
    assert(has_match);
    local_iface = local;
    remote_iface = remote;
}

void
LabelMatcher::consider(struct net_interface local_iface,
                       struct net_interface remote_iface)
{
    u_long bw, RTT;
    if (!NetStats::get_estimate(local_iface, remote_iface, NET_STATS_BW_UP, bw)) {
        bw = iface_bandwidth(local_iface, remote_iface);
    }
    if (iface_bandwidth(local_iface, remote_iface) == 0) {
        // special-case this, since the estimate won't
        // ever reflect when this happens
        bw = 0;
    }

    if (!NetStats::get_estimate(local_iface, remote_iface, NET_STATS_LATENCY, RTT)) {
        RTT = iface_RTT(local_iface, remote_iface);
    } else {
        RTT = RTT * 2;
    }

    if (bw > max_bw) {
        max_bw = bw;
        max_bw_iface_pair = make_pair(local_iface, remote_iface);
    }
    if (RTT < min_RTT) {
        min_RTT = RTT;
        min_RTT_iface_pair = make_pair(local_iface, remote_iface);
    }

    // we have a match after we've considered at least one.
    has_match = true;

    if (matches_type(NET_TYPE_WIFI, local_iface, remote_iface)) {
        wifi_pair = make_pair(local_iface, remote_iface);
        has_wifi_match = true;
    }
    if (matches_type(NET_TYPE_THREEG, local_iface, remote_iface)) {
        threeg_pair = make_pair(local_iface, remote_iface);
        has_threeg_match = true;
    }
}

bool
LabelMatcher::choose_networks(u_long send_label,
                              struct net_interface& local_iface,
                              struct net_interface& remote_iface)
{
    if (!has_match) {
        return false;
    }

    // first, check net type restriction labels, since they take precedence
    if (send_label & CMM_LABEL_WIFI_ONLY) {
        if (!has_wifi_match) {
            return false;
        }

        local_iface = wifi_pair.first;
        remote_iface = wifi_pair.second;
        return true;
    } else if (send_label & CMM_LABEL_THREEG_ONLY) {
        if (!has_threeg_match) {
            return false;
        }

        local_iface = threeg_pair.first;
        remote_iface = threeg_pair.second;
        return true;
    }
    // else: no net type restriction; carry on with other label matching

    const u_long LABELMASK_FGBG = CMM_LABEL_ONDEMAND | CMM_LABEL_BACKGROUND;

    // TODO: try to check based on the actual size
    if (send_label & CMM_LABEL_SMALL &&
        min_RTT < ULONG_MAX) {
        local_iface = min_RTT_iface_pair.first;
        remote_iface = min_RTT_iface_pair.second;
        return true;
    } else if (send_label & CMM_LABEL_LARGE) {
        local_iface = max_bw_iface_pair.first;
        remote_iface = max_bw_iface_pair.second;
        return true;
    } else if (send_label & CMM_LABEL_ONDEMAND ||
               !(send_label & LABELMASK_FGBG)) {
        local_iface = min_RTT_iface_pair.first;
        remote_iface = min_RTT_iface_pair.second;
        return true;
    } else if (send_label & CMM_LABEL_BACKGROUND ||
               send_label == 0) {
        local_iface = max_bw_iface_pair.first;
        remote_iface = max_bw_iface_pair.second;
        return true;
    } else {
        local_iface = max_bw_iface_pair.first;
        remote_iface = max_bw_iface_pair.second;
        return true;
    }
    return false;
}
<commit_msg>Compile fix that somehow wasn't caught for Android??<commit_after>#include "network_chooser.h"
#include "libcmm_net_restriction.h"

#include <map>
using std::make_pair;

NetworkChooser*
NetworkChooser::create(int redundancy_strategy_type)
{
    switch (redundancy_strategy_type) {
    case CELLULAR_ONLY:
        return new PreferredNetwork(NET_TYPE_THREEG);
    case WIFI_PREFERRED:
        return new PreferredNetwork(NET_TYPE_WIFI);
    case INTNW_NEVER_REDUNDANT:
    case INTNW_REDUNDANT:
    case ALWAYS_REDUNDANT:
        return new LabelMatcher;
    default:
        assert(0);
    }
}

PreferredNetwork::PreferredNetwork(int preferred_type_)
{
    preferred_type = preferred_type_;
}

void
PreferredNetwork::reset()
{
    has_match = false;
}

void
PreferredNetwork::consider(struct net_interface local_iface,
                           struct net_interface remote_iface)
{
    if (!has_match || matches_type(preferred_type, local_iface, remote_iface)) {
        has_match = true;
        local = local_iface;
        remote = remote_iface;
    }
}

bool
PreferredNetwork::choose_networks(u_long send_label,
                                  struct net_interface& local_iface,
                                  struct net_interface& remote_iface)
{
    if (!has_match) {
        return false;
    }
    local_iface = local;
    remote_iface = remote;
    return true;
}

void
LabelMatcher::consider(struct net_interface local_iface,
                       struct net_interface remote_iface)
{
    u_long bw, RTT;
    if (!NetStats::get_estimate(local_iface, remote_iface, NET_STATS_BW_UP, bw)) {
        bw = iface_bandwidth(local_iface, remote_iface);
    }
    if (iface_bandwidth(local_iface, remote_iface) == 0) {
        // special-case this, since the estimate won't
        // ever reflect when this happens
        bw = 0;
    }

    if (!NetStats::get_estimate(local_iface, remote_iface, NET_STATS_LATENCY, RTT)) {
        RTT = iface_RTT(local_iface, remote_iface);
    } else {
        RTT = RTT * 2;
    }

    if (bw > max_bw) {
        max_bw = bw;
        max_bw_iface_pair = make_pair(local_iface, remote_iface);
    }
    if (RTT < min_RTT) {
        min_RTT = RTT;
        min_RTT_iface_pair = make_pair(local_iface, remote_iface);
    }

    // we have a match after we've considered at least one.
    has_match = true;

    if (matches_type(NET_TYPE_WIFI, local_iface, remote_iface)) {
        wifi_pair = make_pair(local_iface, remote_iface);
        has_wifi_match = true;
    }
    if (matches_type(NET_TYPE_THREEG, local_iface, remote_iface)) {
        threeg_pair = make_pair(local_iface, remote_iface);
        has_threeg_match = true;
    }
}

bool
LabelMatcher::choose_networks(u_long send_label,
                              struct net_interface& local_iface,
                              struct net_interface& remote_iface)
{
    if (!has_match) {
        return false;
    }

    // first, check net type restriction labels, since they take precedence
    if (send_label & CMM_LABEL_WIFI_ONLY) {
        if (!has_wifi_match) {
            return false;
        }

        local_iface = wifi_pair.first;
        remote_iface = wifi_pair.second;
        return true;
    } else if (send_label & CMM_LABEL_THREEG_ONLY) {
        if (!has_threeg_match) {
            return false;
        }

        local_iface = threeg_pair.first;
        remote_iface = threeg_pair.second;
        return true;
    }
    // else: no net type restriction; carry on with other label matching

    const u_long LABELMASK_FGBG = CMM_LABEL_ONDEMAND | CMM_LABEL_BACKGROUND;

    // TODO: try to check based on the actual size
    if (send_label & CMM_LABEL_SMALL &&
        min_RTT < ULONG_MAX) {
        local_iface = min_RTT_iface_pair.first;
        remote_iface = min_RTT_iface_pair.second;
        return true;
    } else if (send_label & CMM_LABEL_LARGE) {
        local_iface = max_bw_iface_pair.first;
        remote_iface = max_bw_iface_pair.second;
        return true;
    } else if (send_label & CMM_LABEL_ONDEMAND ||
               !(send_label & LABELMASK_FGBG)) {
        local_iface = min_RTT_iface_pair.first;
        remote_iface = min_RTT_iface_pair.second;
        return true;
    } else if (send_label & CMM_LABEL_BACKGROUND ||
               send_label == 0) {
        local_iface = max_bw_iface_pair.first;
        remote_iface = max_bw_iface_pair.second;
        return true;
    } else {
        local_iface = max_bw_iface_pair.first;
        remote_iface = max_bw_iface_pair.second;
        return true;
    }
    return false;
}
<|endoftext|>


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

#include "walletview.h"

#include "addressbookpage.h"
#include "askpassphrasedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "overviewpage.h"
#include "receivecoinsdialog.h"
#include "sendcoinsdialog.h"
#include "signverifymessagedialog.h"
#include "transactiontablemodel.h"
#include "transactionview.h"
#include "walletmodel.h"
#include "utilitydialog.h"

#include "ui_interface.h"

#include <QAction>
#include <QActionGroup>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QProgressDialog>
#include <QPushButton>
#include <QVBoxLayout>

WalletView::WalletView(QWidget *parent):
    QStackedWidget(parent),
    clientModel(0),
    walletModel(0)
{
    // Create tabs
    overviewPage = new OverviewPage();

    transactionsPage = new QWidget(this);
    QVBoxLayout *vbox = new QVBoxLayout();
    QHBoxLayout *hbox_buttons = new QHBoxLayout();
    transactionView = new TransactionView(this);
    vbox->addWidget(transactionView);
    QPushButton *exportButton = new QPushButton(tr("&Export"), this);
    exportButton->setToolTip(tr("Export the data in the current tab to a file"));
#ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
    exportButton->setIcon(QIcon(":/icons/export"));
#endif
    hbox_buttons->addStretch();
    hbox_buttons->addWidget(exportButton);
    vbox->addLayout(hbox_buttons);
    transactionsPage->setLayout(vbox);

    receiveCoinsPage = new ReceiveCoinsDialog();
    sendCoinsPage = new SendCoinsDialog();

    addWidget(overviewPage);
    addWidget(transactionsPage);
    addWidget(receiveCoinsPage);
    addWidget(sendCoinsPage);

    // Clicking on a transaction on the overview pre-selects the transaction on the transaction history page
    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));

    // Double-clicking on a transaction on the transaction history page shows details
    connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));

    // Clicking on "Export" allows to export the transaction list
    connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked()));

    // Pass through messages from sendCoinsPage
    connect(sendCoinsPage, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
    // Pass through messages from transactionView
    connect(transactionView, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
}

WalletView::~WalletView()
{
}

void WalletView::setBitcoinGUI(BitcoinGUI *gui)
{
    if (gui)
    {
        // Clicking on a transaction on the overview page simply sends you to transaction history page
        connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), gui, SLOT(gotoHistoryPage()));

        // Receive and report messages
        connect(this, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int)));

        // Pass through encryption status changed signals
        connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int)));

        // Pass through transaction notifications
        connect(this, SIGNAL(incomingTransaction(QString,int,qint64,QString,QString)), gui, SLOT(incomingTransaction(QString,int,qint64,QString,QString)));
    }
}

void WalletView::setClientModel(ClientModel *clientModel)
{
    this->clientModel = clientModel;

    overviewPage->setClientModel(clientModel);
}

void WalletView::setWalletModel(WalletModel *walletModel)
{
    this->walletModel = walletModel;

    // Put transaction list in tabs
    transactionView->setModel(walletModel);
    overviewPage->setWalletModel(walletModel);
    receiveCoinsPage->setModel(walletModel);
    sendCoinsPage->setModel(walletModel);

    if (walletModel)
    {
        // Receive and pass through messages from wallet model
        connect(walletModel, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));

        // Handle changes in encryption status
        connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int)));
        updateEncryptionStatus();

        // Balloon pop-up for new transaction
        connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
                this, SLOT(processNewTransaction(QModelIndex,int,int)));

        // Ask for passphrase if needed
        connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));

        // Show progress dialog
        connect(walletModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int)));
    }
}

void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/)
{
    // Prevent balloon-spam when initial block download is in progress
    if (!walletModel || !clientModel || clientModel->inInitialBlockDownload())
        return;

    TransactionTableModel *ttm = walletModel->getTransactionTableModel();
    if (!ttm || ttm->processingQueuedTransactions())
        return;

    QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString();
    qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong();
    QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString();
    QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString();

    emit incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address);
}

void WalletView::gotoOverviewPage()
{
    setCurrentWidget(overviewPage);
}

void WalletView::gotoHistoryPage()
{
    setCurrentWidget(transactionsPage);
}

void WalletView::gotoReceiveCoinsPage()
{
    setCurrentWidget(receiveCoinsPage);
}

void WalletView::gotoSendCoinsPage(QString addr)
{
    setCurrentWidget(sendCoinsPage);

    if (!addr.isEmpty())
        sendCoinsPage->setAddress(addr);
}

void WalletView::gotoSignMessageTab(QString addr)
{
    // calls show() in showTab_SM()
    SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this);
    signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose);
    signVerifyMessageDialog->setModel(walletModel);
    signVerifyMessageDialog->showTab_SM(true);

    if (!addr.isEmpty())
        signVerifyMessageDialog->setAddress_SM(addr);
}

void WalletView::gotoVerifyMessageTab(QString addr)
{
    // calls show() in showTab_VM()
    SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this);
    signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose);
    signVerifyMessageDialog->setModel(walletModel);
    signVerifyMessageDialog->showTab_VM(true);

    if (!addr.isEmpty())
        signVerifyMessageDialog->setAddress_VM(addr);
}

bool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient)
{
    return sendCoinsPage->handlePaymentRequest(recipient);
}

void WalletView::showOutOfSyncWarning(bool fShow)
{
    overviewPage->showOutOfSyncWarning(fShow);
}

void WalletView::updateEncryptionStatus()
{
    emit encryptionStatusChanged(walletModel->getEncryptionStatus());
}

void WalletView::encryptWallet(bool status)
{
    if(!walletModel)
        return;
    AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this);
    dlg.setModel(walletModel);
    dlg.exec();

    updateEncryptionStatus();
}

void WalletView::backupWallet()
{
    QString filename = GUIUtil::getSaveFileName(this,
        tr("Backup Wallet"), QString(),
        tr("Wallet Data (*.dat)"), NULL);

    if (filename.isEmpty())
        return;

    if (!walletModel->backupWallet(filename)) {
        emit message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename),
            CClientUIInterface::MSG_ERROR);
        }
    else {
        emit message(tr("Backup Successful"), tr("The wallet data was successfully saved to %1.").arg(filename),
            CClientUIInterface::MSG_INFORMATION);
    }
}

void WalletView::changePassphrase()
{
    AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
    dlg.setModel(walletModel);
    dlg.exec();
}

void WalletView::unlockWallet()
{
    if(!walletModel)
        return;
    // Unlock wallet when requested by wallet model

    if (walletModel->getEncryptionStatus() == WalletModel::Locked || walletModel->getEncryptionStatus() == WalletModel::UnlockedForAnonymizationOnly)
    {
        AskPassphraseDialog dlg(AskPassphraseDialog::UnlockAnonymize, this);
        dlg.setModel(walletModel);
        dlg.exec();
    }
}

void WalletView::lockWallet()
{
    if(!walletModel)
        return;

    walletModel->setWalletLocked(true);
}

void WalletView::usedSendingAddresses()
{
    if(!walletModel)
        return;
    AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab, this);
    dlg->setAttribute(Qt::WA_DeleteOnClose);
    dlg->setModel(walletModel->getAddressTableModel());
    dlg->show();
}

void WalletView::usedReceivingAddresses()
{
    if(!walletModel)
        return;
    AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this);
    dlg->setAttribute(Qt::WA_DeleteOnClose);
    dlg->setModel(walletModel->getAddressTableModel());
    dlg->show();
}

void WalletView::showProgress(const QString &title, int nProgress)
{
    if (nProgress == 0)
    {
        progressDialog = new QProgressDialog(title, "", 0, 100);
        progressDialog->setWindowModality(Qt::ApplicationModal);
        progressDialog->setMinimumDuration(0);
        progressDialog->setCancelButton(0);
        progressDialog->setAutoClose(false);
        progressDialog->setValue(0);
    }
    else if (nProgress == 100)
    {
        if (progressDialog)
        {
            progressDialog->close();
            progressDialog->deleteLater();
        }
    }
    else if (progressDialog)
        progressDialog->setValue(nProgress);
}
void WalletView::printPaperWallets()
{
    if(!walletModel)
        return;

    PaperWalletDialog dlg(this);
    dlg.setModel(walletModel);
    dlg.exec();
}
<commit_msg>Dash Fork Update Show sum of selected transactions in 'Transactions'-tab<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "walletview.h"

#include "addressbookpage.h"
#include "askpassphrasedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "overviewpage.h"
#include "receivecoinsdialog.h"
#include "sendcoinsdialog.h"
#include "signverifymessagedialog.h"
#include "transactiontablemodel.h"
#include "transactionview.h"
#include "walletmodel.h"
#include "utilitydialog.h"

#include "ui_interface.h"

#include <QAction>
#include <QActionGroup>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QLabel>
#include <QProgressDialog>
#include <QPushButton>
#include <QVBoxLayout>

WalletView::WalletView(QWidget *parent):
    QStackedWidget(parent),
    clientModel(0),
    walletModel(0)
{
    // Create tabs
    overviewPage = new OverviewPage();

    transactionsPage = new QWidget(this);
    QVBoxLayout *vbox = new QVBoxLayout();
    QHBoxLayout *hbox_buttons = new QHBoxLayout();
    transactionView = new TransactionView(this);
    vbox->addWidget(transactionView);
    QPushButton *exportButton = new QPushButton(tr("&Export"), this);
    exportButton->setToolTip(tr("Export the data in the current tab to a file"));
#ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
    exportButton->setIcon(QIcon(":/icons/export"));
#endif
    hbox_buttons->addStretch();

    // Sum of selected transactions
    QLabel *transactionSumLabel = new QLabel(); // Label
    transactionSumLabel->setText("Selected amount: ");
    hbox_buttons->addWidget(transactionSumLabel);

    transactionSum = new QLabel(); // Amount
    transactionSum->setMinimumSize(200, 8);
    transactionSum->setTextInteractionFlags(Qt::TextSelectableByMouse);
    hbox_buttons->addWidget(transactionSum);

    hbox_buttons->addWidget(exportButton);
    vbox->addLayout(hbox_buttons);
    transactionsPage->setLayout(vbox);

    receiveCoinsPage = new ReceiveCoinsDialog();
    sendCoinsPage = new SendCoinsDialog();

    addWidget(overviewPage);
    addWidget(transactionsPage);
    addWidget(receiveCoinsPage);
    addWidget(sendCoinsPage);

    // Clicking on a transaction on the overview pre-selects the transaction on the transaction history page
    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));

    // Double-clicking on a transaction on the transaction history page shows details
    connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));

    // Update wallet with sum of selected transactions
    connect(transactionView, SIGNAL(trxAmount(QString)), this, SLOT(trxAmount(QString)));

    // Clicking on "Export" allows to export the transaction list
    connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked()));

    // Pass through messages from sendCoinsPage
    connect(sendCoinsPage, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
    // Pass through messages from transactionView
    connect(transactionView, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
}

WalletView::~WalletView()
{
}

void WalletView::setBitcoinGUI(BitcoinGUI *gui)
{
    if (gui)
    {
        // Clicking on a transaction on the overview page simply sends you to transaction history page
        connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), gui, SLOT(gotoHistoryPage()));

        // Receive and report messages
        connect(this, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int)));

        // Pass through encryption status changed signals
        connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int)));

        // Pass through transaction notifications
        connect(this, SIGNAL(incomingTransaction(QString,int,qint64,QString,QString)), gui, SLOT(incomingTransaction(QString,int,qint64,QString,QString)));
    }
}

void WalletView::setClientModel(ClientModel *clientModel)
{
    this->clientModel = clientModel;

    overviewPage->setClientModel(clientModel);
}

void WalletView::setWalletModel(WalletModel *walletModel)
{
    this->walletModel = walletModel;

    // Put transaction list in tabs
    transactionView->setModel(walletModel);
    overviewPage->setWalletModel(walletModel);
    receiveCoinsPage->setModel(walletModel);
    sendCoinsPage->setModel(walletModel);

    if (walletModel)
    {
        // Receive and pass through messages from wallet model
        connect(walletModel, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));

        // Handle changes in encryption status
        connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int)));
        updateEncryptionStatus();

        // Balloon pop-up for new transaction
        connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
                this, SLOT(processNewTransaction(QModelIndex,int,int)));

        // Ask for passphrase if needed
        connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));

        // Show progress dialog
        connect(walletModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int)));
    }
}

void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/)
{
    // Prevent balloon-spam when initial block download is in progress
    if (!walletModel || !clientModel || clientModel->inInitialBlockDownload())
        return;

    TransactionTableModel *ttm = walletModel->getTransactionTableModel();
    if (!ttm || ttm->processingQueuedTransactions())
        return;

    QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString();
    qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong();
    QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString();
    QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString();

    emit incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address);
}

void WalletView::gotoOverviewPage()
{
    setCurrentWidget(overviewPage);
}

void WalletView::gotoHistoryPage()
{
    setCurrentWidget(transactionsPage);
}

void WalletView::gotoReceiveCoinsPage()
{
    setCurrentWidget(receiveCoinsPage);
}

void WalletView::gotoSendCoinsPage(QString addr)
{
    setCurrentWidget(sendCoinsPage);

    if (!addr.isEmpty())
        sendCoinsPage->setAddress(addr);
}

void WalletView::gotoSignMessageTab(QString addr)
{
    // calls show() in showTab_SM()
    SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this);
    signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose);
    signVerifyMessageDialog->setModel(walletModel);
    signVerifyMessageDialog->showTab_SM(true);

    if (!addr.isEmpty())
        signVerifyMessageDialog->setAddress_SM(addr);
}

void WalletView::gotoVerifyMessageTab(QString addr)
{
    // calls show() in showTab_VM()
    SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this);
    signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose);
    signVerifyMessageDialog->setModel(walletModel);
    signVerifyMessageDialog->showTab_VM(true);

    if (!addr.isEmpty())
        signVerifyMessageDialog->setAddress_VM(addr);
}

bool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient)
{
    return sendCoinsPage->handlePaymentRequest(recipient);
}

void WalletView::showOutOfSyncWarning(bool fShow)
{
    overviewPage->showOutOfSyncWarning(fShow);
}

void WalletView::updateEncryptionStatus()
{
    emit encryptionStatusChanged(walletModel->getEncryptionStatus());
}

void WalletView::encryptWallet(bool status)
{
    if(!walletModel)
        return;
    AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this);
    dlg.setModel(walletModel);
    dlg.exec();

    updateEncryptionStatus();
}

void WalletView::backupWallet()
{
    QString filename = GUIUtil::getSaveFileName(this,
        tr("Backup Wallet"), QString(),
        tr("Wallet Data (*.dat)"), NULL);

    if (filename.isEmpty())
        return;

    if (!walletModel->backupWallet(filename)) {
        emit message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename),
            CClientUIInterface::MSG_ERROR);
        }
    else {
        emit message(tr("Backup Successful"), tr("The wallet data was successfully saved to %1.").arg(filename),
            CClientUIInterface::MSG_INFORMATION);
    }
}

void WalletView::changePassphrase()
{
    AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
    dlg.setModel(walletModel);
    dlg.exec();
}

void WalletView::unlockWallet()
{
    if(!walletModel)
        return;
    // Unlock wallet when requested by wallet model

    if (walletModel->getEncryptionStatus() == WalletModel::Locked || walletModel->getEncryptionStatus() == WalletModel::UnlockedForAnonymizationOnly)
    {
        AskPassphraseDialog dlg(AskPassphraseDialog::UnlockAnonymize, this);
        dlg.setModel(walletModel);
        dlg.exec();
    }
}

void WalletView::lockWallet()
{
    if(!walletModel)
        return;

    walletModel->setWalletLocked(true);
}

void WalletView::usedSendingAddresses()
{
    if(!walletModel)
        return;
    AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab, this);
    dlg->setAttribute(Qt::WA_DeleteOnClose);
    dlg->setModel(walletModel->getAddressTableModel());
    dlg->show();
}

void WalletView::usedReceivingAddresses()
{
    if(!walletModel)
        return;
    AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this);
    dlg->setAttribute(Qt::WA_DeleteOnClose);
    dlg->setModel(walletModel->getAddressTableModel());
    dlg->show();
}

void WalletView::showProgress(const QString &title, int nProgress)
{
    if (nProgress == 0)
    {
        progressDialog = new QProgressDialog(title, "", 0, 100);
        progressDialog->setWindowModality(Qt::ApplicationModal);
        progressDialog->setMinimumDuration(0);
        progressDialog->setCancelButton(0);
        progressDialog->setAutoClose(false);
        progressDialog->setValue(0);
    }
    else if (nProgress == 100)
    {
        if (progressDialog)
        {
            progressDialog->close();
            progressDialog->deleteLater();
        }
    }
    else if (progressDialog)
        progressDialog->setValue(nProgress);
}

/** Update wallet with the sum of the selected transactions */
void WalletView::trxAmount(QString amount)
{
    transactionSum->setText(amount);
}

void WalletView::printPaperWallets()
{
    if(!walletModel)
        return;

    PaperWalletDialog dlg(this);
    dlg.setModel(walletModel);
    dlg.exec();
}
<|endoftext|>


<commit_before>#include "generated/cpp/ApplicationBase.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "common/RhoFilePath.h"

#ifdef RHODES_EMULATOR
#define RHO_APPS_DIR ""
#else
#define RHO_APPS_DIR "apps/"
#endif

extern "C" void rho_sys_app_exit();

namespace rho {

using namespace apiGenerator;
using namespace common;

class CApplicationImpl: public CApplicationSingletonBase
{
public:

    CApplicationImpl(): CApplicationSingletonBase(){}

    virtual void getAppBundleFolder(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"app/") );
    }

    virtual void getAppsBundleFolder(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR) );
    }

    virtual void getUserFolder(rho::apiGenerator::CMethodResult& oResult)
    {
#ifdef OS_MACOSX
        oResult.set( CFilePath::join( rho_native_rhouserpath(), RHO_APPS_DIR) );
#else
        oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR) );
#endif
    }

    virtual void getConfigPath(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( RHOCONF().getConfFilePath() );
    }

    virtual void getModelsManifestPath(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"app_manifest.txt") );
    }

    virtual void getDatabaseBlobFolder(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR"/db/db-files") );
    }

    virtual void getPublicFolder(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"public") );
    }

    virtual void getStartURI(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( RHOCONF().getString("start_path") );
    }

    virtual void setStartURI( const rho::String& startURI, rho::apiGenerator::CMethodResult& oResult)
    {
        RHOCONF().setString("start_path", startURI, false );
    }

    virtual void getSettingsPageURI(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( RHOCONF().getString("options_path") );
    }

    virtual void setSettingsPageURI( const rho::String& settingsPageURI, rho::apiGenerator::CMethodResult& oResult)
    {
        RHOCONF().setString("options_path", settingsPageURI, false );
    }

    virtual void getSplash(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( RHOCONF().getString("splash_screen") );
    }

    virtual void getVersion(rho::apiGenerator::CMethodResult& oResult)
    {
       oResult.set( RHOCONF().getString("app_version") );
    }

    virtual void getTitle(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( RHOCONF().getString("title_text") );
    }

    virtual void setTitle( const rho::String& title, rho::apiGenerator::CMethodResult& oResult)
    {
        RHOCONF().setString("title_text", title, false);
    }

    virtual void getName(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( RHODESAPP().getAppName() );
    }

    virtual void getBadLinkURI(rho::apiGenerator::CMethodResult& oResult)
    {
        //TODO: getBadLinkURI
    }

    virtual void setBadLinkURI( const rho::String& badLinkURI, rho::apiGenerator::CMethodResult& oResult)
    {
        //TODO: setBadLinkURI
    }

    virtual void modelFolderPath( const rho::String& name, rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"app/" + name + "/") );
    }

    virtual void databaseFilePath( const rho::String& partitionName, rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR"db/syncdb" + partitionName + ".sqlite") );
    }

    virtual void expandDatabaseBlobFilePath( const rho::String& relativePath, rho::apiGenerator::CMethodResult& oResult)
    {
        if ( String_startsWith(relativePath, "file://") )
            oResult.set(relativePath);
        else
        {
            String dbRootFolder = CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR);
            oResult.set( CFilePath::join( dbRootFolder, relativePath ) );
        }
    }

    virtual void quit(rho::apiGenerator::CMethodResult& oResult)
    {
        rho_sys_app_exit();
    }

    virtual void minimize(rho::apiGenerator::CMethodResult& oResult)
    {
        RHODESAPP().getExtManager().minimizeApp();
    }

    virtual void restore(rho::apiGenerator::CMethodResult& oResult)
    {
        RHODESAPP().getExtManager().restoreApp();
    }

    virtual void setActivationNotify(rho::apiGenerator::CMethodResult& oResult)
    {
        //TODO: setActivationNotify
    }

    virtual void getRhoPlatformVersion(rho::apiGenerator::CMethodResult& oResult)
    {
        //TODO: setActivationNotify
    }
};

////////////////////////////////////////////////////////////////////////

class CApplicationFactory: public CApplicationFactoryBase
{
public:
    ~CApplicationFactory(){}

    IApplicationSingleton* createModuleSingleton()
    {
        return new CApplicationImpl();
    }
};

}

extern "C" void Init_Application()
{
    rho::CApplicationFactory::setInstance( new rho::CApplicationFactory() );
    rho::Init_Application_API();

    RHODESAPP().getExtManager().requireRubyFile("RhoApplicationApi");
}
<commit_msg>rhosim: fix database access<commit_after>#include "generated/cpp/ApplicationBase.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "common/RhoFilePath.h"

#ifdef RHODES_EMULATOR
#define RHO_APPS_DIR ""
#else
#define RHO_APPS_DIR "apps/"
#endif

extern "C" void rho_sys_app_exit();

namespace rho {

using namespace apiGenerator;
using namespace common;

class CApplicationImpl: public CApplicationSingletonBase
{
public:

    CApplicationImpl(): CApplicationSingletonBase(){}

    virtual void getAppBundleFolder(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"app/") );
    }

    virtual void getAppsBundleFolder(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR) );
    }

    virtual void getUserFolder(rho::apiGenerator::CMethodResult& oResult)
    {
#ifdef OS_MACOSX
        oResult.set( CFilePath::join( rho_native_rhouserpath(), RHO_APPS_DIR) );
#else
        oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR) );
#endif
    }

    virtual void getConfigPath(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( RHOCONF().getConfFilePath() );
    }

    virtual void getModelsManifestPath(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"app_manifest.txt") );
    }

    virtual void getDatabaseBlobFolder(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR"/db/db-files") );
    }

    virtual void getPublicFolder(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"public") );
    }

    virtual void getStartURI(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( RHOCONF().getString("start_path") );
    }

    virtual void setStartURI( const rho::String& startURI, rho::apiGenerator::CMethodResult& oResult)
    {
        RHOCONF().setString("start_path", startURI, false );
    }

    virtual void getSettingsPageURI(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( RHOCONF().getString("options_path") );
    }

    virtual void setSettingsPageURI( const rho::String& settingsPageURI, rho::apiGenerator::CMethodResult& oResult)
    {
        RHOCONF().setString("options_path", settingsPageURI, false );
    }

    virtual void getSplash(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( RHOCONF().getString("splash_screen") );
    }

    virtual void getVersion(rho::apiGenerator::CMethodResult& oResult)
    {
       oResult.set( RHOCONF().getString("app_version") );
    }

    virtual void getTitle(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( RHOCONF().getString("title_text") );
    }

    virtual void setTitle( const rho::String& title, rho::apiGenerator::CMethodResult& oResult)
    {
        RHOCONF().setString("title_text", title, false);
    }

    virtual void getName(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( RHODESAPP().getAppName() );
    }

    virtual void getBadLinkURI(rho::apiGenerator::CMethodResult& oResult)
    {
        //TODO: getBadLinkURI
    }

    virtual void setBadLinkURI( const rho::String& badLinkURI, rho::apiGenerator::CMethodResult& oResult)
    {
        //TODO: setBadLinkURI
    }

    virtual void modelFolderPath( const rho::String& name, rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"app/" + name + "/") );
    }

    virtual void databaseFilePath( const rho::String& partitionName, rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR"/db/syncdb" + partitionName + ".sqlite") );
    }

    virtual void expandDatabaseBlobFilePath( const rho::String& relativePath, rho::apiGenerator::CMethodResult& oResult)
    {
        if ( String_startsWith(relativePath, "file://") )
            oResult.set(relativePath);
        else
        {
            String dbRootFolder = CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR);
            oResult.set( CFilePath::join( dbRootFolder, relativePath ) );
        }
    }

    virtual void quit(rho::apiGenerator::CMethodResult& oResult)
    {
        rho_sys_app_exit();
    }

    virtual void minimize(rho::apiGenerator::CMethodResult& oResult)
    {
        RHODESAPP().getExtManager().minimizeApp();
    }

    virtual void restore(rho::apiGenerator::CMethodResult& oResult)
    {
        RHODESAPP().getExtManager().restoreApp();
    }

    virtual void setActivationNotify(rho::apiGenerator::CMethodResult& oResult)
    {
        //TODO: setActivationNotify
    }

    virtual void getRhoPlatformVersion(rho::apiGenerator::CMethodResult& oResult)
    {
        //TODO: setActivationNotify
    }
};

////////////////////////////////////////////////////////////////////////

class CApplicationFactory: public CApplicationFactoryBase
{
public:
    ~CApplicationFactory(){}

    IApplicationSingleton* createModuleSingleton()
    {
        return new CApplicationImpl();
    }
};

}

extern "C" void Init_Application()
{
    rho::CApplicationFactory::setInstance( new rho::CApplicationFactory() );
    rho::Init_Application_API();

    RHODESAPP().getExtManager().requireRubyFile("RhoApplicationApi");
}
<|endoftext|>


<commit_before>
#ifndef __aspeller_leditdist_hh__
#define __aspeller_leditdist_hh__

#include "weights.hpp"

namespace aspeller {

  // limit_edit_distance finds the shortest edit distance but will
  // stop and return a number at least as large as LARGE_NUM if it has
  // to do more edits than a set limit.
  // Note that this does NOT bean than the score returned <= limit*w.max
  // as sub vs submarine will return 6*(cost of insertion) no matter what
  // the limit is.
  // The edit distance is
  // (cost of swap)(# of swaps) + (cost of deletion)(# of deletions)
  //   + (cost of insertion)(# of insertions)
  //   + (cost of substitutions)(# of substitutions)

  // Preconditions:
  //  (limit+1)*w.min < limit*w.max
  //  limit <= 5 (use edit_distance if n > 5)

  // The running time is asymptotically bounded above by
  // (3^l)*n where l is the limit and n is the maxium of strlen(a),strlen(b)
  // Based ob my informal tests however the n does not really matter
  // and the running time is more like (3^l).

  // limit_edit_distance, based on my informal tests, turns out to be
  // faster than edit_dist for l < 5.  For l == 5 it is about the
  // smaller for short strings (<= 5) and less than for longer strings

  // limit2_edit_distance(a,b,w) = limit_edit_distance(a,b,2,w)
  //  but is roughly 2/3's faster

  struct EditDist {
    int          score;
    const char * stopped_at;
    EditDist() {}
    EditDist(int s, const char * p)
      : score(s), stopped_at(p) {}
    operator int () const {return score;}
  };

  static const int LARGE_NUM = 0xFFFFF;
  // this needs to be SMALLER than INT_MAX since it may be incremented
  // a few times

  int limit_edit_distance(const char * a, const char * b, int limit,
			  const EditDistanceWeights & w
			  = EditDistanceWeights());

  EditDist limit1_edit_distance(const char * a, const char * b,
				const EditDistanceWeights & w
				= EditDistanceWeights());

  EditDist limit2_edit_distance(const char * a, const char * b,
				const EditDistanceWeights & w
				= EditDistanceWeights());

}

#endif
<commit_msg>Fixed typos in comments<commit_after>
#ifndef __aspeller_leditdist_hh__
#define __aspeller_leditdist_hh__

#include "weights.hpp"

namespace aspeller {

  // limit_edit_distance finds the shortest edit distance but will
  // stop and return a number at least as large as LARGE_NUM if it has
  // to do more edits than a set limit.
  // Note that this does NOT mean that the score returned is <= limit*w.max
  // as "sub" vs "submarine" will return 6*(cost of insertion) no matter what
  // the limit is.
  // The edit distance is
  // (cost of swap)(# of swaps) + (cost of deletion)(# of deletions)
  //   + (cost of insertion)(# of insertions)
  //   + (cost of substitutions)(# of substitutions)

  // Preconditions:
  //  (limit+1)*w.min < limit*w.max
  //  limit <= 5 (use edit_distance if limit > 5)
  // where w.min and w.max is the minimum and maximum cost of an edit
  // respectfully.

  // The running time is asymptotically bounded above by
  // (3^l)*n where l is the limit and n is the maxium of strlen(a),strlen(b)
  // Based on my informal tests, however, the n does not really matter
  // and the running time is more like (3^l).

  // limit_edit_distance, based on my informal tests, turns out to be
  // faster than edit_dist for l < 5.  For l == 5 it is about the
  // smaller for short strings (<= 5) and less than for longer strings

  // limit2_edit_distance(a,b,w) = limit_edit_distance(a,b,2,w)
  // but is roughly 2/3's faster

  struct EditDist {
    int          score;
    const char * stopped_at;
    EditDist() {}
    EditDist(int s, const char * p)
      : score(s), stopped_at(p) {}
    operator int () const {return score;}
  };

  static const int LARGE_NUM = 0xFFFFF;
  // this needs to be SMALLER than INT_MAX since it may be incremented
  // a few times

  int limit_edit_distance(const char * a, const char * b, int limit,
			  const EditDistanceWeights & w
			  = EditDistanceWeights());

  EditDist limit1_edit_distance(const char * a, const char * b,
				const EditDistanceWeights & w
				= EditDistanceWeights());

  EditDist limit2_edit_distance(const char * a, const char * b,
				const EditDistanceWeights & w
				= EditDistanceWeights());

}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: SQLException.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2004-07-30 15:11:34 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_
#include "java/sql/SQLException.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif

using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
//  using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//**************************************************************
//************ Class: java.sql.SQLException
//**************************************************************
java_sql_SQLException::java_sql_SQLException( const java_sql_SQLException_BASE& _rException,const Reference< XInterface> & _rContext)
    : starsdbc::SQLException(   _rException.getMessage(),
                                _rContext,
                                _rException.getSQLState(),
                                _rException.getErrorCode(),
                                makeAny(_rException.getNextException())
                            )
{
}

java_sql_SQLException_BASE::java_sql_SQLException_BASE( JNIEnv * pEnv, jobject myObj ) : java_lang_Exception( pEnv, myObj )
{
}

jclass java_sql_SQLException_BASE::theClass = 0;

java_sql_SQLException_BASE::~java_sql_SQLException_BASE()
{}

jclass java_sql_SQLException_BASE::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass("java/sql/SQLException");
        OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
        if(!tempClass)
        {
            t.pEnv->ExceptionDescribe();
            t.pEnv->ExceptionClear();
        }
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_sql_SQLException_BASE::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

starsdbc::SQLException java_sql_SQLException_BASE::getNextException()  const
{
    jobject out = NULL;
    SDBThreadAttach t;
    if( t.pEnv ){

        // temporaere Variable initialisieren
        char * cSignature = "()Ljava/sql/Exception;";
        char * cMethodName = "getNextException";
        // Java-Call absetzen
        jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    if( out )
    {
        java_sql_SQLException_BASE  warn_base(t.pEnv,out);
        return (starsdbc::SQLException)java_sql_SQLException(warn_base,0);
    }

    return starsdbc::SQLException();
}

::rtl::OUString java_sql_SQLException_BASE::getSQLState() const
{
    jstring out = (jstring)NULL;
    SDBThreadAttach t;
    ::rtl::OUString aStr;
    if( t.pEnv ){

        // temporaere Variable initialisieren
        char * cSignature = "()Ljava/lang/String;";
        char * cMethodName = "getSQLState";
        // Java-Call absetzen
        jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            out = (jstring) t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
            if(out)
                aStr = JavaString2String(t.pEnv,out);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return aStr;
}
sal_Int32 java_sql_SQLException_BASE::getErrorCode() const
{
    jint out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
    if( t.pEnv ){

        // temporaere Variable initialisieren
        char * cSignature = "()I";
        char * cMethodName = "getErrorCode";
        // Java-Call absetzen
        jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            out = t.pEnv->CallIntMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
        } //mID
    } //t.pEnv
    return (sal_Int32)out;
}

<commit_msg>INTEGRATION: CWS hsqldb (1.6.6); FILE MERGED 2004/09/10 12:45:04 oj 1.6.6.1: #i33348# code optimizing<commit_after>/*************************************************************************
 *
 *  $RCSfile: SQLException.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2004-11-09 12:14:18 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_
#include "java/sql/SQLException.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif

using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
//  using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//**************************************************************
//************ Class: java.sql.SQLException
//**************************************************************
java_sql_SQLException::java_sql_SQLException( const java_sql_SQLException_BASE& _rException,const Reference< XInterface> & _rContext)
    : starsdbc::SQLException(   _rException.getMessage(),
                                _rContext,
                                _rException.getSQLState(),
                                _rException.getErrorCode(),
                                makeAny(_rException.getNextException())
                            )
{
}

java_sql_SQLException_BASE::java_sql_SQLException_BASE( JNIEnv * pEnv, jobject myObj ) : java_lang_Exception( pEnv, myObj )
{
}

jclass java_sql_SQLException_BASE::theClass = 0;

java_sql_SQLException_BASE::~java_sql_SQLException_BASE()
{}

jclass java_sql_SQLException_BASE::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass("java/sql/SQLException");
        OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
        if(!tempClass)
        {
            t.pEnv->ExceptionDescribe();
            t.pEnv->ExceptionClear();
        }
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_sql_SQLException_BASE::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

starsdbc::SQLException java_sql_SQLException_BASE::getNextException()  const
{
    jobject out = NULL;
    SDBThreadAttach t;
    if( t.pEnv ){

        // temporaere Variable initialisieren
        static char * cSignature = "()Ljava/sql/Exception;";
        static char * cMethodName = "getNextException";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    if( out )
    {
        java_sql_SQLException_BASE  warn_base(t.pEnv,out);
        return (starsdbc::SQLException)java_sql_SQLException(warn_base,0);
    }

    return starsdbc::SQLException();
}

::rtl::OUString java_sql_SQLException_BASE::getSQLState() const
{
    SDBThreadAttach t;
    ::rtl::OUString aStr;
    if( t.pEnv ){

        // temporaere Variable initialisieren
        static char * cSignature = "()Ljava/lang/String;";
        static char * cMethodName = "getSQLState";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            jstring out = (jstring) t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
            aStr = JavaString2String(t.pEnv,out);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return aStr;
}
sal_Int32 java_sql_SQLException_BASE::getErrorCode() const
{
    jint out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
    if( t.pEnv ){

        // temporaere Variable initialisieren
        static char * cSignature = "()I";
        static char * cMethodName = "getErrorCode";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            out = t.pEnv->CallIntMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
        } //mID
    } //t.pEnv
    return (sal_Int32)out;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: SQLException.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-16 17:30:01 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_
#include "java/sql/SQLException.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif

using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
//  using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//**************************************************************
//************ Class: java.sql.SQLException
//**************************************************************
java_sql_SQLException::java_sql_SQLException( const java_sql_SQLException_BASE& _rException,const Reference< XInterface> & _rContext)
    : starsdbc::SQLException(   _rException.getMessage(),
                                _rContext,
                                _rException.getSQLState(),
                                _rException.getErrorCode(),
                                makeAny(_rException.getNextException())
                            )
{
}

java_sql_SQLException_BASE::java_sql_SQLException_BASE( JNIEnv * pEnv, jobject myObj ) : java_lang_Exception( pEnv, myObj )
{
}

jclass java_sql_SQLException_BASE::theClass = 0;

java_sql_SQLException_BASE::~java_sql_SQLException_BASE()
{}

jclass java_sql_SQLException_BASE::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass("java/sql/SQLException");
        OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
        if(!tempClass)
        {
            t.pEnv->ExceptionDescribe();
            t.pEnv->ExceptionClear();
        }
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_sql_SQLException_BASE::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

starsdbc::SQLException java_sql_SQLException_BASE::getNextException()  const
{
    jobject out = NULL;
    SDBThreadAttach t;
    if( t.pEnv ){

        // temporaere Variable initialisieren
        static char * cSignature = "()Ljava/sql/Exception;";
        static char * cMethodName = "getNextException";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    if( out )
    {
        java_sql_SQLException_BASE  warn_base(t.pEnv,out);
        return (starsdbc::SQLException)java_sql_SQLException(warn_base,0);
    }

    return starsdbc::SQLException();
}

::rtl::OUString java_sql_SQLException_BASE::getSQLState() const
{
    SDBThreadAttach t;
    ::rtl::OUString aStr;
    if( t.pEnv ){

        // temporaere Variable initialisieren
        static char * cSignature = "()Ljava/lang/String;";
        static char * cMethodName = "getSQLState";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            jstring out = (jstring) t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
            aStr = JavaString2String(t.pEnv,out);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return aStr;
}
sal_Int32 java_sql_SQLException_BASE::getErrorCode() const
{
    jint out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv ){

        // temporaere Variable initialisieren
        static char * cSignature = "()I";
        static char * cMethodName = "getErrorCode";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            out = t.pEnv->CallIntMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
        } //mID
    } //t.pEnv
    return (sal_Int32)out;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.8.78); FILE MERGED 2005/09/05 17:24:15 rt 1.8.78.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SQLException.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:12:32 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_
#include "java/sql/SQLException.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif

using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
//  using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//**************************************************************
//************ Class: java.sql.SQLException
//**************************************************************
java_sql_SQLException::java_sql_SQLException( const java_sql_SQLException_BASE& _rException,const Reference< XInterface> & _rContext)
    : starsdbc::SQLException(   _rException.getMessage(),
                                _rContext,
                                _rException.getSQLState(),
                                _rException.getErrorCode(),
                                makeAny(_rException.getNextException())
                            )
{
}

java_sql_SQLException_BASE::java_sql_SQLException_BASE( JNIEnv * pEnv, jobject myObj ) : java_lang_Exception( pEnv, myObj )
{
}

jclass java_sql_SQLException_BASE::theClass = 0;

java_sql_SQLException_BASE::~java_sql_SQLException_BASE()
{}

jclass java_sql_SQLException_BASE::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass("java/sql/SQLException");
        OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
        if(!tempClass)
        {
            t.pEnv->ExceptionDescribe();
            t.pEnv->ExceptionClear();
        }
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_sql_SQLException_BASE::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

starsdbc::SQLException java_sql_SQLException_BASE::getNextException()  const
{
    jobject out = NULL;
    SDBThreadAttach t;
    if( t.pEnv ){

        // temporaere Variable initialisieren
        static char * cSignature = "()Ljava/sql/Exception;";
        static char * cMethodName = "getNextException";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    if( out )
    {
        java_sql_SQLException_BASE  warn_base(t.pEnv,out);
        return (starsdbc::SQLException)java_sql_SQLException(warn_base,0);
    }

    return starsdbc::SQLException();
}

::rtl::OUString java_sql_SQLException_BASE::getSQLState() const
{
    SDBThreadAttach t;
    ::rtl::OUString aStr;
    if( t.pEnv ){

        // temporaere Variable initialisieren
        static char * cSignature = "()Ljava/lang/String;";
        static char * cMethodName = "getSQLState";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            jstring out = (jstring) t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
            aStr = JavaString2String(t.pEnv,out);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return aStr;
}
sal_Int32 java_sql_SQLException_BASE::getErrorCode() const
{
    jint out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv ){

        // temporaere Variable initialisieren
        static char * cSignature = "()I";
        static char * cMethodName = "getErrorCode";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            out = t.pEnv->CallIntMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
        } //mID
    } //t.pEnv
    return (sal_Int32)out;
}

<|endoftext|>


<commit_before>#ifndef DIPLOMA_ROOT_SET_HPP
#define DIPLOMA_ROOT_SET_HPP

#include <algorithm>
#include <forward_list>

#include <libprecisegc/details/allocators/object_pool.hpp>
#include <libprecisegc/details/allocators/stl_adapter.hpp>
#include <libprecisegc/details/ptrs/gc_untyped_ptr.hpp>
#include <libprecisegc/details/utils/utility.hpp>
#include <libprecisegc/details/gc_unsafe_scope.h>
#include <libprecisegc/details/types.hpp>

namespace precisegc { namespace details {

template <typename T>
class stack_map : private utils::noncopyable, private utils::nonmovable
{
public:
    stack_map() = default;

    void insert(T elem)
    {
        gc_unsafe_scope unsafe_scope;
        m_list.push_front(elem);
    }

    void remove(T elem)
    {
        gc_unsafe_scope unsafe_scope;
        remove_first(elem);
    }

    bool contains(T elem)
    {
        gc_unsafe_scope unsafe_scope;
        return std::find(m_list.begin(), m_list.end(), elem) != m_list.end();
    }

    template <typename Functor>
    void trace(Functor& f) const
    {
        std::for_each(m_list.begin(), m_list.end(), f);
    }

    template <typename Functor>
    void trace(const Functor& f) const
    {
        std::for_each(m_list.begin(), m_list.end(), f);
    }
private:
    void remove_first(T elem)
    {
        auto it = m_list.before_begin();
        auto next = std::next(it);
        auto last = m_list.end();
        while (next != last && *next != elem) {
            it = next;
            ++next;
        }
        if (next != last) {
            m_list.erase_after(it);
        }
    }

    std::forward_list<T, allocators::stl_adapter<T, allocators::object_pool>> m_list;
};

typedef stack_map<ptrs::gc_untyped_ptr*> root_stack_map;
typedef stack_map<byte*> pin_stack_map;

}}

#endif //DIPLOMA_ROOT_SET_HPP
<commit_msg>separate pool for every stack_map<commit_after>#ifndef DIPLOMA_ROOT_SET_HPP
#define DIPLOMA_ROOT_SET_HPP

#include <algorithm>
#include <forward_list>

#include <boost/iterator/iterator_facade.hpp>

#include <libprecisegc/details/allocators/intrusive_list_allocator.hpp>
#include <libprecisegc/details/allocators/freelist_pool_chunk.hpp>
#include <libprecisegc/details/allocators/default_allocator.hpp>
#include <libprecisegc/details/ptrs/gc_untyped_ptr.hpp>
#include <libprecisegc/details/utils/utility.hpp>
#include <libprecisegc/details/gc_unsafe_scope.h>
#include <libprecisegc/details/types.hpp>

namespace precisegc { namespace details {

template <typename T>
class stack_map : private utils::noncopyable, private utils::nonmovable
{
public:
    stack_map()
        : m_head(nullptr)
    {};

    void insert(T elem)
    {
        gc_unsafe_scope unsafe_scope;
        push_front(elem);
    }

    void remove(T elem)
    {
        gc_unsafe_scope unsafe_scope;
        remove_first(elem);
    }

    bool contains(T elem)
    {
        gc_unsafe_scope unsafe_scope;
        return std::find(begin(), end(), elem) != end();
    }

    template <typename Functor>
    void trace(Functor& f) const
    {
        std::for_each(begin(), end(), f);
    }

    template <typename Functor>
    void trace(const Functor& f) const
    {
        std::for_each(begin(), end(), f);
    }
private:
    struct node
    {
        T m_value;
        node* m_next;
    };

    class iterator: public boost::iterator_facade<
              iterator
            , const T
            , boost::forward_traversal_tag
    >
    {
    public:
        iterator(node* pnode) noexcept
            : m_pnode(pnode)
        {}

        iterator(const iterator&) noexcept = default;
        iterator(iterator&&) noexcept = default;

        iterator& operator=(const iterator&) noexcept = default;
        iterator& operator=(iterator&&) noexcept = default;

        const T* operator->() const
        {
            return &m_pnode->m_value;
        }
    private:
        friend class stack_map;
        friend class boost::iterator_core_access;

        const T& dereference() const
        {
            return m_pnode->m_value;
        }

        void increment() noexcept
        {
            m_pnode = m_pnode->m_next;
        }

        bool equal(const iterator& other) const noexcept
        {
            return m_pnode == other.m_pnode;
        }

        node* m_pnode;
    };

    iterator begin() const
    {
        return iterator(m_head);
    }

    iterator end() const
    {
        return iterator(nullptr);
    }

    void push_front(T elem)
    {
        node* pnode = create_node(elem);
        pnode->m_next = m_head;
        m_head = pnode;
    }

    void remove_first(T elem)
    {
        assert(m_head);
        if (m_head->m_value == elem) {
            node* tmp = m_head;
            m_head = m_head->m_next;
            destroy_node(tmp);
            return;
        }
        node* it = m_head;
        node* next = it->m_next;
        while (next && next->m_value != elem) {
            it = next;
            next = next->m_next;
        }
        if (next) {
            it->m_next = next->m_next;
            destroy_node(next);
        }
    }

    node* create_node(T elem)
    {
        node* pnode = reinterpret_cast<node*>(m_pool.allocate(sizeof(node)));
        pnode->m_value = elem;
        return pnode;
    }

    void destroy_node(node* pnode)
    {
        m_pool.deallocate(reinterpret_cast<byte*>(pnode), sizeof(node));
    }

    typedef allocators::intrusive_list_allocator<
            allocators::freelist_pool_chunk, allocators::default_allocator
        > object_pool_t;

    node* m_head;
    object_pool_t m_pool;
};

typedef stack_map<ptrs::gc_untyped_ptr*> root_stack_map;
typedef stack_map<byte*> pin_stack_map;

}}

#endif //DIPLOMA_ROOT_SET_HPP
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2006-2016  Music Technology Group - Universitat Pompeu Fabra
 *
 * This file is part of Essentia
 *
 * Essentia is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation (FSF), either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * version 3 along with this program.  If not, see http://www.gnu.org/licenses/
 */

#include "chordsdetectionbeats.h"
#include "essentiamath.h"

using namespace std;

namespace essentia {
namespace standard {

const char* ChordsDetectionBeats::name = "ChordsDetectionBeats";
const char* ChordsDetectionBeats::category = "Tonal";
const char* ChordsDetectionBeats::description = DOC("This algorithm estimates chords using pitch profile classes on segments between beats. It is similar to ChordsDetection algorithm, but the chords are estimated on audio segments between each pair of consecutive beats.\n"
"\n"
"Quality: experimental (algorithm needs evaluation)\n"
"\n"
"References:\n"
"  [1] E. Gómez, \"Tonal Description of Polyphonic Audio for Music Content\n"
"  Processing,\" INFORMS Journal on Computing, vol. 18, no. 3, pp. 294–304,\n"
"  2006.\n\n"
"  [2] D. Temperley, \"What's key for key? The Krumhansl-Schmuckler\n"
"  key-finding algorithm reconsidered\", Music Perception vol. 17, no. 1,\n"
"  pp. 65-100, 1999.");

void ChordsDetectionBeats::configure() {
  _sampleRate = parameter("sampleRate").toReal();
  _hopSize = parameter("hopSize").toInt();
}

void ChordsDetectionBeats::compute() {
  const vector<vector<Real> >& hpcp = _pcp.get();
  vector<string>& chords = _chords.get();
  vector<Real>& strength = _strength.get();
  const vector<Real>& ticks = _ticks.get();

  string key;
  string scale;
  Real keyStrength;
  Real firstToSecondRelativeStrength;

  if(ticks.size() < 2) {
    throw EssentiaException("Ticks vector should contain at least 2 elements.");
  }

  chords.reserve(ticks.size() - 1);
  strength.reserve(ticks.size() - 1);

  for (int i=0; i < (int)ticks.size()-1; ++i) {

    Real diffTicks = ticks[i+1] - ticks[i];
    int numFramesTick = int((diffTicks * _sampleRate) / _hopSize);
    int frameStart = int((ticks[i] * _sampleRate) / _hopSize);
    int frameEnd = frameStart + numFramesTick-1;

    if (frameEnd > (int)hpcp.size()-1) break;

    vector<Real> hpcpMedian = medianFrames(hpcp, frameStart, frameEnd);
    normalize(hpcpMedian);

    _chordsAlgo->input("pcp").set(hpcpMedian);
    _chordsAlgo->output("key").set(key);
    _chordsAlgo->output("scale").set(scale);
    _chordsAlgo->output("strength").set(keyStrength);
    _chordsAlgo->output("firstToSecondRelativeStrength").set(firstToSecondRelativeStrength);
    _chordsAlgo->compute();

    if (scale == "minor") {
      chords.push_back(key + 'm');
    }
    else {
      chords.push_back(key);
    }

    strength.push_back(keyStrength);
  }
}

} // namespace standard
} // namespace essentia
<commit_msg>Fixing bug in frames bound calculation in chordsdetectionbeats.<commit_after>/*
 * Copyright (C) 2006-2016  Music Technology Group - Universitat Pompeu Fabra
 *
 * This file is part of Essentia
 *
 * Essentia is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation (FSF), either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * version 3 along with this program.  If not, see http://www.gnu.org/licenses/
 */

#include "chordsdetectionbeats.h"
#include "essentiamath.h"

using namespace std;

namespace essentia {
namespace standard {

const char* ChordsDetectionBeats::name = "ChordsDetectionBeats";
const char* ChordsDetectionBeats::category = "Tonal";
const char* ChordsDetectionBeats::description = DOC("This algorithm estimates chords using pitch profile classes on segments between beats. It is similar to ChordsDetection algorithm, but the chords are estimated on audio segments between each pair of consecutive beats.\n"
"\n"
"Quality: experimental (algorithm needs evaluation)\n"
"\n"
"References:\n"
"  [1] E. Gómez, \"Tonal Description of Polyphonic Audio for Music Content\n"
"  Processing,\" INFORMS Journal on Computing, vol. 18, no. 3, pp. 294–304,\n"
"  2006.\n\n"
"  [2] D. Temperley, \"What's key for key? The Krumhansl-Schmuckler\n"
"  key-finding algorithm reconsidered\", Music Perception vol. 17, no. 1,\n"
"  pp. 65-100, 1999.");

void ChordsDetectionBeats::configure() {
  _sampleRate = parameter("sampleRate").toReal();
  _hopSize = parameter("hopSize").toInt();
}

void ChordsDetectionBeats::compute() {
  const vector<vector<Real> >& hpcp = _pcp.get();
  vector<string>& chords = _chords.get();
  vector<Real>& strength = _strength.get();
  const vector<Real>& ticks = _ticks.get();

  string key;
  string scale;
  Real keyStrength;
  Real firstToSecondRelativeStrength;

  if(ticks.size() < 2) {
    throw EssentiaException("Ticks vector should contain at least 2 elements.");
  }

  chords.reserve(ticks.size() - 1);
  strength.reserve(ticks.size() - 1);

  for (int i=0; i < (int)ticks.size()-1; ++i) {

    Real diffTicks = ticks[i+1] - ticks[i];
    int numFramesTick = int((diffTicks * _sampleRate) / _hopSize);
    int frameStart = int((ticks[i] * _sampleRate) / _hopSize);
    int frameEnd = frameStart + numFramesTick-1;
    // Could happen if beats are unrealistically close.
    if (frameStart >= frameEnd)
      frameEnd = frameStart + 1;

    if (frameEnd > (int)hpcp.size()-1) break;
    vector<Real> hpcpMedian = medianFrames(hpcp, frameStart, frameEnd);
    normalize(hpcpMedian);

    _chordsAlgo->input("pcp").set(hpcpMedian);
    _chordsAlgo->output("key").set(key);
    _chordsAlgo->output("scale").set(scale);
    _chordsAlgo->output("strength").set(keyStrength);
    _chordsAlgo->output("firstToSecondRelativeStrength").set(firstToSecondRelativeStrength);
    _chordsAlgo->compute();

    if (scale == "minor") {
      chords.push_back(key + 'm');
    }
    else {
      chords.push_back(key);
    }

    strength.push_back(keyStrength);
  }
}

} // namespace standard
} // namespace essentia
<|endoftext|>