<commit_before>#include <boost/python.hpp>
#include <boost/cstdint.hpp>

#include <Magick++/Include.h>

using namespace boost::python;

void __QuantumOperator()
{
#ifndef PGMAGICK_LIB_IMAGEMAGICK
    enum_< Magick::QuantumOperator >("QuantumOperator")
        .value("AddQuantumOp", Magick::AddQuantumOp)
        .value("AndQuantumOp", Magick::AndQuantumOp)
#ifdef PGMAGICK_LIB_GRAPHICSMAGICK_1_3_x
        .value("AssignQuantumOp", Magick::AssignQuantumOp)
#endif
        .value("DivideQuantumOp", Magick::DivideQuantumOp)
        .value("LShiftQuantumOp", Magick::LShiftQuantumOp)
        .value("MultiplyQuantumOp)", Magick::MultiplyQuantumOp)
        .value("OrQuantumOp", Magick::OrQuantumOp)
        .value("RShiftQuantumOp", Magick::RShiftQuantumOp)
        .value("SubtractQuantumOp", Magick::SubtractQuantumOp)
#ifdef PGMAGICK_LIB_GRAPHICSMAGICK_1_3_x
        .value("ThresholdQuantumOp", Magick::ThresholdQuantumOp)
        .value("ThresholdBlackQuantumOp", Magick::ThresholdBlackQuantumOp)
        .value("ThresholdWhiteQuantumOp", Magick::ThresholdWhiteQuantumOp)
#endif
        .value("XorQuantumOp", Magick::XorQuantumOp)
#ifdef PGMAGICK_LIB_GRAPHICSMAGICK_1_3_x
        .value("NoiseGaussianQuantumOp", Magick::NoiseGaussianQuantumOp)
        .value("NoiseImpulseQuantumOp", Magick::NoiseImpulseQuantumOp)
        .value("NoiseLaplacianQuantumOp", Magick::NoiseLaplacianQuantumOp)
        .value("NoiseMultiplicativeQuantumOp", Magick::NoiseMultiplicativeQuantumOp)
        .value("NoisePoissonQuantumOp", Magick::NoisePoissonQuantumOp)
        .value("NoiseUniformQuantumOp", Magick::NoiseUniformQuantumOp)
        .value("NegateQuantumOp", Magick::NegateQuantumOp)
        .value("GammaQuantumOp", Magick::GammaQuantumOp)
        .value("DepthQuantumOp", Magick::DepthQuantumOp)
        .value("LogQuantumOp", Magick::LogQuantumOp)
        .value("MaxQuantumOp", Magick::MaxQuantumOp)
        .value("MinQuantumOp", Magick::MinQuantumOp)
        .value("PowQuantumOp", Magick::PowQuantumOp)
#endif
#endif
    ;
}
<commit_msg>fix typo (oops..)<commit_after>#include <boost/python.hpp>
#include <boost/cstdint.hpp>

#include <Magick++/Include.h>

using namespace boost::python;

void __QuantumOperator()
{
#ifndef PGMAGICK_LIB_IMAGEMAGICK
    enum_< Magick::QuantumOperator >("QuantumOperator")
        .value("AddQuantumOp", Magick::AddQuantumOp)
        .value("AndQuantumOp", Magick::AndQuantumOp)
#ifdef PGMAGICK_LIB_GRAPHICSMAGICK_1_3_x
        .value("AssignQuantumOp", Magick::AssignQuantumOp)
#endif
        .value("DivideQuantumOp", Magick::DivideQuantumOp)
        .value("LShiftQuantumOp", Magick::LShiftQuantumOp)
        .value("MultiplyQuantumOp", Magick::MultiplyQuantumOp)
        .value("OrQuantumOp", Magick::OrQuantumOp)
        .value("RShiftQuantumOp", Magick::RShiftQuantumOp)
        .value("SubtractQuantumOp", Magick::SubtractQuantumOp)
#ifdef PGMAGICK_LIB_GRAPHICSMAGICK_1_3_x
        .value("ThresholdQuantumOp", Magick::ThresholdQuantumOp)
        .value("ThresholdBlackQuantumOp", Magick::ThresholdBlackQuantumOp)
        .value("ThresholdWhiteQuantumOp", Magick::ThresholdWhiteQuantumOp)
#endif
        .value("XorQuantumOp", Magick::XorQuantumOp)
#ifdef PGMAGICK_LIB_GRAPHICSMAGICK_1_3_x
        .value("NoiseGaussianQuantumOp", Magick::NoiseGaussianQuantumOp)
        .value("NoiseImpulseQuantumOp", Magick::NoiseImpulseQuantumOp)
        .value("NoiseLaplacianQuantumOp", Magick::NoiseLaplacianQuantumOp)
        .value("NoiseMultiplicativeQuantumOp", Magick::NoiseMultiplicativeQuantumOp)
        .value("NoisePoissonQuantumOp", Magick::NoisePoissonQuantumOp)
        .value("NoiseUniformQuantumOp", Magick::NoiseUniformQuantumOp)
        .value("NegateQuantumOp", Magick::NegateQuantumOp)
        .value("GammaQuantumOp", Magick::GammaQuantumOp)
        .value("DepthQuantumOp", Magick::DepthQuantumOp)
        .value("LogQuantumOp", Magick::LogQuantumOp)
        .value("MaxQuantumOp", Magick::MaxQuantumOp)
        .value("MinQuantumOp", Magick::MinQuantumOp)
        .value("PowQuantumOp", Magick::PowQuantumOp)
#endif
#endif
    ;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QtCore/QCoreApplication>

#include <qllcpsocket.h>
#include <qnearfieldmanager.h>
#include <qnearfieldtarget.h>
#include "qnfctestcommon.h"
#include "qnfctestutil.h"

QTM_USE_NAMESPACE

Q_DECLARE_METATYPE(QNearFieldTarget*)
Q_DECLARE_METATYPE(QLlcpSocket::Error);

class tst_qllcpsocketremote : public QObject
{
    Q_OBJECT

public:
    tst_qllcpsocketremote();

private Q_SLOTS:

    // ALERT Handshake required, do NOTchange the sequence of handshaking testcases.
    void testCase0();  // Intial handshake - work with  tst_qllcpsocketlocal testCase0
    void testCase1();   // handshake 1,2  - work with  tst_qllcpsocketlocal testCase1
    void testCase2();   // handshake 3   - work with  tst_qllcpsocketlocal testCase2

    void cleanupTest();

private:
     QNearFieldManager *m_nfcManager;
     QNearFieldTarget *m_target;
     QLlcpSocket *m_socket;
     quint8 m_port;
};

tst_qllcpsocketremote::tst_qllcpsocketremote()
{
    qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*");
    qRegisterMetaType<QNearFieldTarget *>("QLlcpSocket::Error");
}

/*!
 Description: Init test case for NFC LLCP connection-less mode socket - local peer

 TestScenario:
     Touch a NFC device with LLCP connection-less service actived

 TestExpectedResults:
     Signal of target detected has been found.
*/
void tst_qllcpsocketremote::testCase0()
{
    m_nfcManager = new QNearFieldManager;
    QSignalSpy targetDetectedSpy(m_nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)));
    m_nfcManager->startTargetDetection(QNearFieldTarget::AnyTarget);

    QString message("Remote wait touch");
    QNfcTestUtil::ShowMessage(message);
    QTRY_VERIFY(!targetDetectedSpy.isEmpty());

    m_target = targetDetectedSpy.at(targetDetectedSpy.count() - 1).at(0).value<QNearFieldTarget *>();
    QVERIFY(m_target!=NULL);
    QVERIFY(m_target->accessMethods() & QNearFieldTarget::LlcpAccess);

    m_port = 35;
    m_socket = new QLlcpSocket;
}

/*!
 Description:  Description: Receive the message and send the acknowledged identical message

 TestScenario: 1. Remote peer binds to local port
               2. Remote peer receives the message sending from the local peer
               3. Remote peer sends the echoed message to the local peer

 TestExpectedResults:
               1. Remote peer binds to local port successfully.
               2. The message has been received from remote peer.
               3. The message has be sent to local peer.
*/
void tst_qllcpsocketremote::testCase1()
{

    // STEP 1:  bind the local port for current socket
    QSignalSpy readyReadSpy(m_socket, SIGNAL(readyRead()));
    bool ret = m_socket->bind(m_port);
    QVERIFY(ret);

    QString message("handshake 1");
    QNfcTestUtil::ShowMessage(message);

    QTRY_VERIFY(readyReadSpy.count() == 1);
    QVERIFY(ret);

    // STEP 2: Receive data from the peer which send messages to
    QByteArray datagram;
    if (m_socket->hasPendingDatagrams())
    {
       datagram.resize(m_socket->pendingDatagramSize());
       qint64 readSize = m_socket->readDatagram(datagram.data(), datagram.size());
       QVERIFY(readSize != -1);
    }

    // STEP 3: Send the received message back to the intiated device.
    QSignalSpy errorSpy(m_socket, SIGNAL(error(QLlcpSocket::Error)));
    QSignalSpy bytesWrittenSpy(m_socket, SIGNAL(bytesWritten(qint64)));

    qint64 val = m_socket->writeDatagram(datagram,m_target, m_port);
    QVERIFY(val != -1);

    QTRY_VERIFY(bytesWrittenSpy.count() == 1);
    QList<QVariant> arguments = bytesWrittenSpy.takeFirst(); // take the first signal
    qint64 writtenSize  = arguments.at(0).value<qint64>();
    QVERIFY(writtenSize > 0);

    QString message2("handshake 2");
    QNfcTestUtil::ShowMessage(message2);

    // make sure the no error signal emitted
    QCOMPARE(errorSpy.count(), 0);
}

/*!
 Description: Unit test for NFC LLCP connection-less mode socket - remote peer (passive)

 TestScenario: 1. Remote peer binds to local port ( already done in testCase1)
               2. Remote peer  receive datagram twice
               3. Remote peer waitForReadyRead

 TestExpectedResults:
               1. Remote peer binds to local port successfully.
               2. Remote peer  receive datagram twice successfully
               3. waitForReadyRead return true as long as readyReadSpy not empty
*/
void tst_qllcpsocketremote::testCase2()
{
    QLlcpSocket localSocket;
    quint8 localPort = 38;
    QSignalSpy readyReadSpy(&localSocket, SIGNAL(readyRead()));
    bool ret = localSocket.bind(localPort);
    QVERIFY(ret);

    // STEP 1:  bind the local port for current socket
    QString expectedMessage1("testcase2 string str1");
    QString expectedMessage2("testcase2 string str2");

    QString boxMessage("handshake 3");
    QNfcTestUtil::ShowAutoMsg(boxMessage,&readyReadSpy);

    QTRY_VERIFY(readyReadSpy.count() == 1);

    QByteArray datagram;
    if (localSocket.hasPendingDatagrams())
    {
       datagram.resize(localSocket.pendingDatagramSize());
       qint64 readSize = localSocket.readDatagram(datagram.data(), datagram.size());
       QVERIFY(readSize != -1);
    }

    QString receivedMessage1 = datagram.data();
    qDebug() << "receivedMessage1: " << receivedMessage1;
    QVERIFY(expectedMessage1 == receivedMessage1);

    QTRY_VERIFY(readyReadSpy.count() == 2);

     QByteArray datagram2;
    if (localSocket.hasPendingDatagrams())
    {
       datagram2.resize(localSocket.pendingDatagramSize());
       qint64 readSize = localSocket.readDatagram(datagram2.data(), datagram2.size());
       QVERIFY(readSize != -1);
    }
    QString receivedMessage2 = datagram2.data();
    qDebug() << "receivedMessage2: " << receivedMessage2;
    QVERIFY(expectedMessage2 == receivedMessage2);

    const int Timeout = 10 * 1000;
    ret = localSocket.waitForReadyRead(Timeout);

    QVERIFY(ret == false);
 }

void tst_qllcpsocketremote::cleanupTest()
{
   delete m_nfcManager;
   delete m_socket;
}

QTEST_MAIN(tst_qllcpsocketremote);

#include "tst_qllcpsocketremote.moc"
<commit_msg>add auto dismiss support to llcp1<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QtCore/QCoreApplication>

#include <qllcpsocket.h>
#include <qnearfieldmanager.h>
#include <qnearfieldtarget.h>
#include "qnfctestcommon.h"
#include "qnfctestutil.h"

QTM_USE_NAMESPACE

Q_DECLARE_METATYPE(QNearFieldTarget*)
Q_DECLARE_METATYPE(QLlcpSocket::Error);

class tst_qllcpsocketremote : public QObject
{
    Q_OBJECT

public:
    tst_qllcpsocketremote();

private Q_SLOTS:

    // ALERT Handshake required, do NOTchange the sequence of handshaking testcases.
    void testCase0();  // Intial handshake - work with  tst_qllcpsocketlocal testCase0
    void testCase1();   // handshake 1,2  - work with  tst_qllcpsocketlocal testCase1
    void testCase2();   // handshake 3   - work with  tst_qllcpsocketlocal testCase2

    void cleanupTest();

private:
     QNearFieldManager *m_nfcManager;
     QNearFieldTarget *m_target;
     QLlcpSocket *m_socket;
     quint8 m_port;
};

tst_qllcpsocketremote::tst_qllcpsocketremote()
{
    qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*");
    qRegisterMetaType<QNearFieldTarget *>("QLlcpSocket::Error");
}

/*!
 Description: Init test case for NFC LLCP connection-less mode socket - local peer

 TestScenario:
     Touch a NFC device with LLCP connection-less service actived

 TestExpectedResults:
     Signal of target detected has been found.
*/
void tst_qllcpsocketremote::testCase0()
{
    m_nfcManager = new QNearFieldManager;
    QSignalSpy targetDetectedSpy(m_nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)));
    m_nfcManager->startTargetDetection(QNearFieldTarget::AnyTarget);

    QString message("Please touch a NFC device with llcp client enabled");
    QNfcTestUtil::ShowAutoMsg(message, &targetDetectedSpy);
    QTRY_VERIFY(!targetDetectedSpy.isEmpty());

    m_target = targetDetectedSpy.at(targetDetectedSpy.count() - 1).at(0).value<QNearFieldTarget *>();
    QVERIFY(m_target!=NULL);
    QVERIFY(m_target->accessMethods() & QNearFieldTarget::LlcpAccess);

    m_port = 35;
    m_socket = new QLlcpSocket;
}

/*!
 Description:  Description: Receive the message and send the acknowledged identical message

 TestScenario: 1. Remote peer binds to local port
               2. Remote peer receives the message sending from the local peer
               3. Remote peer sends the echoed message to the local peer

 TestExpectedResults:
               1. Remote peer binds to local port successfully.
               2. The message has been received from remote peer.
               3. The message has be sent to local peer.
*/
void tst_qllcpsocketremote::testCase1()
{

    // STEP 1:  bind the local port for current socket
    QSignalSpy readyReadSpy(m_socket, SIGNAL(readyRead()));
    bool ret = m_socket->bind(m_port);
    QVERIFY(ret);

    QString message("handshake 1");
    QNfcTestUtil::ShowAutoMsg(message, &readyReadSpy);

    QTRY_VERIFY(readyReadSpy.count() == 1);
    QVERIFY(ret);

    // STEP 2: Receive data from the peer which send messages to
    QByteArray datagram;
    if (m_socket->hasPendingDatagrams())
    {
       datagram.resize(m_socket->pendingDatagramSize());
       qint64 readSize = m_socket->readDatagram(datagram.data(), datagram.size());
       QVERIFY(readSize != -1);
    }

    // STEP 3: Send the received message back to the intiated device.
    QSignalSpy errorSpy(m_socket, SIGNAL(error(QLlcpSocket::Error)));
    QSignalSpy bytesWrittenSpy(m_socket, SIGNAL(bytesWritten(qint64)));

    qint64 val = m_socket->writeDatagram(datagram,m_target, m_port);
    QVERIFY(val != -1);

    QTRY_VERIFY(bytesWrittenSpy.count() == 1);
    QList<QVariant> arguments = bytesWrittenSpy.takeFirst(); // take the first signal
    qint64 writtenSize  = arguments.at(0).value<qint64>();
    QVERIFY(writtenSize > 0);

    QString message2("handshake 2");
    QNfcTestUtil::ShowAutoMsg(message2, 1 * 1000);

    // make sure the no error signal emitted
    QCOMPARE(errorSpy.count(), 0);
}

/*!
 Description: Unit test for NFC LLCP connection-less mode socket - remote peer (passive)

 TestScenario: 1. Remote peer binds to local port ( already done in testCase1)
               2. Remote peer  receive datagram twice
               3. Remote peer waitForReadyRead

 TestExpectedResults:
               1. Remote peer binds to local port successfully.
               2. Remote peer  receive datagram twice successfully
               3. waitForReadyRead return true as long as readyReadSpy not empty
*/
void tst_qllcpsocketremote::testCase2()
{
    QLlcpSocket localSocket;
    quint8 localPort = 38;
    QSignalSpy readyReadSpy(&localSocket, SIGNAL(readyRead()));
    bool ret = localSocket.bind(localPort);
    QVERIFY(ret);

    // STEP 1:  bind the local port for current socket
    QString expectedMessage1("testcase2 string str1");
    QString expectedMessage2("testcase2 string str2");

    QString boxMessage("handshake 3");
    QNfcTestUtil::ShowAutoMsg(boxMessage,&readyReadSpy);

    QTRY_VERIFY(readyReadSpy.count() == 1);

    QByteArray datagram;
    if (localSocket.hasPendingDatagrams())
    {
       datagram.resize(localSocket.pendingDatagramSize());
       qint64 readSize = localSocket.readDatagram(datagram.data(), datagram.size());
       QVERIFY(readSize != -1);
    }

    QString receivedMessage1 = datagram.data();
    qDebug() << "receivedMessage1: " << receivedMessage1;
    QVERIFY(expectedMessage1 == receivedMessage1);

    QTRY_VERIFY(readyReadSpy.count() == 2);

     QByteArray datagram2;
    if (localSocket.hasPendingDatagrams())
    {
       datagram2.resize(localSocket.pendingDatagramSize());
       qint64 readSize = localSocket.readDatagram(datagram2.data(), datagram2.size());
       QVERIFY(readSize != -1);
    }
    QString receivedMessage2 = datagram2.data();
    qDebug() << "receivedMessage2: " << receivedMessage2;
    QVERIFY(expectedMessage2 == receivedMessage2);

    const int Timeout = 10 * 1000;
    ret = localSocket.waitForReadyRead(Timeout);

    QVERIFY(ret == false);
 }

void tst_qllcpsocketremote::cleanupTest()
{
   delete m_nfcManager;
   delete m_socket;
}

QTEST_MAIN(tst_qllcpsocketremote);

#include "tst_qllcpsocketremote.moc"
<|endoftext|>


<commit_before>#include "overviewpage.h"
#include "ui_overviewpage.h"

#include "clientmodel.h"
#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>

#define DECORATION_SIZE 64
#define NUM_ITEMS 3

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();
        QVariant value = index.data(Qt::ForegroundRole);
        QColor foreground = option.palette.color(QPalette::Text);
        if(qVariantCanConvert<QColor>(value))
        {
            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),
    clientModel(0),
    walletModel(0),
    currentBalance(-1),
    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->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(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance)
{
    int unit = walletModel->getOptionsModel()->getDisplayUnit();
    currentBalance = balance;
    currentUnconfirmedBalance = unconfirmedBalance;
    currentImmatureBalance = immatureBalance;
    ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
    ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));
    ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, 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);
}

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->sort(TransactionTableModel::Status, Qt::DescendingOrder);

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

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

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

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

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

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

        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>overviewpage: make some code Qt5 compatible<commit_after>#include "overviewpage.h"
#include "ui_overviewpage.h"

#include "clientmodel.h"
#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>

#define DECORATION_SIZE 64
#define NUM_ITEMS 3

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();
        QVariant value = index.data(Qt::ForegroundRole);
        QColor foreground = option.palette.color(QPalette::Text);
        if(value.canConvert<QBrush>())
        {
            QBrush brush = qvariant_cast<QBrush>(value);
            foreground = brush.color();
        }

        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),
    clientModel(0),
    walletModel(0),
    currentBalance(-1),
    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->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(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance)
{
    int unit = walletModel->getOptionsModel()->getDisplayUnit();
    currentBalance = balance;
    currentUnconfirmedBalance = unconfirmedBalance;
    currentImmatureBalance = immatureBalance;
    ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
    ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));
    ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, 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);
}

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->sort(TransactionTableModel::Status, Qt::DescendingOrder);

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

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

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

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

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

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

        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>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2015] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_TIMESTAMP_HPP
#define REALM_TIMESTAMP_HPP

#include <stdint.h>
#include <ostream>
#include <realm/util/assert.hpp>

namespace realm {

struct Timestamp {
    Timestamp(int64_t seconds, uint32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false)
    {
        REALM_ASSERT_3(nanoseconds, <, nanoseconds_per_second);
    }
    Timestamp() : m_is_null(true) { }

    bool is_null() const { return m_is_null; }

    int64_t get_seconds() const noexcept
    {
        return m_seconds;
    }

    uint32_t get_nanoseconds() const noexcept
    {
        return m_nanoseconds;
    }

    void set_seconds(uint64_t seconds) noexcept
    {
        m_seconds = seconds;
    }

    void set_nanoseconds(uint32_t nanoseconds) noexcept
    {
        REALM_ASSERT_3(nanoseconds, <, nanoseconds_per_second);
        m_nanoseconds = nanoseconds;
    }

    // Note that nullability is handled by query system. These operators are only invoked for non-null dates.
    bool operator==(const Timestamp& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }
    bool operator!=(const Timestamp& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }
    bool operator>(const Timestamp& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }
    bool operator<(const Timestamp& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }
    bool operator<=(const Timestamp& rhs) const { return *this < rhs || *this == rhs; }
    bool operator>=(const Timestamp& rhs) const { return *this > rhs || *this == rhs; }
    Timestamp& operator=(const Timestamp& rhs) = default;

    template<class Ch, class Tr>
    friend std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& out, const Timestamp&);
    static constexpr uint32_t nanoseconds_per_second = 1000000000;

private:
    int64_t m_seconds;
    uint32_t m_nanoseconds;
    bool m_is_null;
};

template<class C, class T>
inline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const Timestamp& d)
{
    out << "Timestamp(" << d.m_seconds << ", " << d.m_nanoseconds << ")";
    return out;
}

} // namespace realm

#endif // REALM_TIMESTAMP_HPP
<commit_msg>Removed unused, unnecessary setters<commit_after>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2015] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_TIMESTAMP_HPP
#define REALM_TIMESTAMP_HPP

#include <stdint.h>
#include <ostream>
#include <realm/util/assert.hpp>

namespace realm {

struct Timestamp {
    Timestamp(int64_t seconds, uint32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false)
    {
        REALM_ASSERT_3(nanoseconds, <, nanoseconds_per_second);
    }
    Timestamp() : m_is_null(true) { }

    bool is_null() const { return m_is_null; }

    int64_t get_seconds() const noexcept
    {
        return m_seconds;
    }

    uint32_t get_nanoseconds() const noexcept
    {
        return m_nanoseconds;
    }

    // Note that nullability is handled by query system. These operators are only invoked for non-null dates.
    bool operator==(const Timestamp& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }
    bool operator!=(const Timestamp& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }
    bool operator>(const Timestamp& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }
    bool operator<(const Timestamp& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }
    bool operator<=(const Timestamp& rhs) const { return *this < rhs || *this == rhs; }
    bool operator>=(const Timestamp& rhs) const { return *this > rhs || *this == rhs; }
    Timestamp& operator=(const Timestamp& rhs) = default;

    template<class Ch, class Tr>
    friend std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& out, const Timestamp&);
    static constexpr uint32_t nanoseconds_per_second = 1000000000;

private:
    int64_t m_seconds;
    uint32_t m_nanoseconds;
    bool m_is_null;
};

template<class C, class T>
inline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const Timestamp& d)
{
    out << "Timestamp(" << d.m_seconds << ", " << d.m_nanoseconds << ")";
    return out;
}

} // namespace realm

#endif // REALM_TIMESTAMP_HPP
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * Copyright 2016 Realm Inc.
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 **************************************************************************/

#ifndef REALM_UTILITIES_HPP
#define REALM_UTILITIES_HPP

#include <cstdint>
#include <cstdlib>
#include <cstdlib> // size_t
#include <cstdio>
#include <algorithm>
#include <functional>

#ifdef _MSC_VER
#include <intrin.h>
#endif

#include <realm/util/features.h>
#include <realm/util/assert.hpp>
#include <realm/util/safe_int_ops.hpp>

// GCC defines __i386__ and __x86_64__
#if (defined(__X86__) || defined(__i386__) || defined(i386) || defined(_M_IX86) || defined(__386__) ||               \
     defined(__x86_64__) || defined(_M_X64))
#define REALM_X86_OR_X64
#define REALM_X86_OR_X64_TRUE true
#else
#define REALM_X86_OR_X64_TRUE false
#endif

// GCC defines __arm__
#ifdef __arm__
#define REALM_ARCH_ARM
#endif

#if defined _LP64 || defined __LP64__ || defined __64BIT__ || defined _ADDR64 || defined _WIN64 ||                   \
    defined __arch64__ || (defined(__WORDSIZE) && __WORDSIZE == 64) || (defined __sparc && defined __sparcv9) ||     \
    defined __x86_64 || defined __amd64 || defined __x86_64__ || defined _M_X64 || defined _M_IA64 ||                \
    defined __ia64 || defined __IA64__
#define REALM_PTR_64
#endif

#if defined(REALM_PTR_64) && defined(REALM_X86_OR_X64)
#define REALM_COMPILER_SSE // Compiler supports SSE 4.2 through __builtin_ accessors or back-end assembler
#define REALM_COMPILER_AVX
#endif

namespace realm {

using StringCompareCallback = std::function<bool(const char* string1, const char* string2)>;

extern signed char sse_support;
extern signed char avx_support;

template <int version>
REALM_FORCEINLINE bool sseavx()
{
    /*
    Return whether or not SSE 3.0 (if version = 30) or 4.2 (for version = 42) is supported. Return value
    is based on the CPUID instruction.

    sse_support = -1: No SSE support
    sse_support = 0: SSE3
    sse_support = 1: SSE42

    avx_support = -1: No AVX support
    avx_support = 0: AVX1 supported
    sse_support = 1: AVX2 supported (not yet implemented for detection in our cpuid_init(), todo)

    This lets us test very rapidly at runtime because we just need 1 compare instruction (with 0) to test both for
    SSE 3 and 4.2 by caller (compiler optimizes if calls are concecutive), and can decide branch with ja/jl/je because
    sse_support is signed type. Also, 0 requires no immediate operand. Same for AVX.

    We runtime-initialize sse_support in a constructor of a static variable which is not guaranteed to be called
    prior to cpu_sse(). So we compile-time initialize sse_support to -2 as fallback.
    */
    static_assert(version == 1 || version == 2 || version == 30 || version == 42,
                  "Only version == 1 (AVX), 2 (AVX2), 30 (SSE 3) and 42 (SSE 4.2) are supported for detection");
#ifdef REALM_COMPILER_SSE
    if (version == 30)
        return (sse_support >= 0);
    else if (version == 42)
        return (sse_support > 0); // faster than == 1 (0 requres no immediate operand)
    else if (version == 1)        // avx
        return (avx_support >= 0);
    else if (version == 2) // avx2
        return (avx_support > 0);
    else
        return false;
#else
    return false;
#endif
}

void cpuid_init();
void* round_up(void* p, size_t align);
void* round_down(void* p, size_t align);
size_t round_up(size_t p, size_t align);
size_t round_down(size_t p, size_t align);
void millisleep(unsigned long milliseconds);

#ifdef REALM_SLAB_ALLOC_TUNE
void process_mem_usage(double& vm_usage, double& resident_set);
#endif
// popcount
int fast_popcount32(int32_t x);
int fast_popcount64(int64_t x);
uint64_t fastrand(uint64_t max = 0xffffffffffffffffULL, bool is_seed = false);

// log2 - returns -1 if x==0, otherwise log2(x)
inline int log2(size_t x)
{
    if (x == 0)
        return -1;
#if defined(__GNUC__)
#ifdef REALM_PTR_64
    return 63 - __builtin_clzll(x); // returns int
#else
    return 31 - __builtin_clz(x); // returns int
#endif
#elif defined(_WIN32)
    unsigned long index = 0;
#ifdef REALM_PTR_64
    unsigned char c = _BitScanReverse64(&index, x); // outputs unsigned long
#else
    unsigned char c = _BitScanReverse(&index, x); // outputs unsigned long
#endif
    return static_cast<int>(index);
#else // not __GNUC__ and not _WIN32
    int r = 0;
    while (x >>= 1) {
        r++;
    }
    return r;
#endif
}

// Implementation:

// Safe cast from 64 to 32 bits on 32 bit architecture. Differs from to_ref() by not testing alignment and
// REF-bitflag.
inline size_t to_size_t(int_fast64_t v) noexcept
{
    REALM_ASSERT_DEBUG(!util::int_cast_has_overflow<size_t>(v));
    return size_t(v);
}

template <typename ReturnType, typename OriginalType>
ReturnType type_punning(OriginalType variable) noexcept
{
    union Both {
        OriginalType in;
        ReturnType out;
    };
    Both both;
    both.out = ReturnType(); // Clear all bits in case ReturnType is larger than OriginalType
    both.in = variable;
    return both.out;
}

// Also see the comments in Array::index_string()
enum FindRes {
    // Indicate that no results were found in the search
    FindRes_not_found,
    // Indicates a single result is found
    FindRes_single,
    // Indicates more than one result is found and they are stored in a column
    FindRes_column
};

enum IndexMethod {
    index_FindFirst,
    index_FindAll,
    index_FindAll_nocopy,
    index_FindAll_ins,
    index_Count,
};

// Combined result of the index_FindAll_nocopy operation. The column returned
// can contain results that are not matches but all matches are within the
// returned start_ndx and end_ndx.
struct InternalFindResult {
    // Reference to a IntegerColumn containing result rows, or a single row
    // value if the result is FindRes_single.
    size_t payload;
    // Offset into the result column to start at.
    size_t start_ndx;
    // Offset index in the result column to end at.
    size_t end_ndx;
};

// realm::is_any<T, U1, U2, U3, ...> ==
// std::is_same<T, U1>::value || std::is_same<T, U2>::value || std::is_same<T, U3>::value ...
template <typename... T>
struct is_any : std::false_type {
};

template <typename T, typename... Ts>
struct is_any<T, T, Ts...> : std::true_type {
};

template <typename T, typename U, typename... Ts>
struct is_any<T, U, Ts...> : is_any<T, Ts...> {
};

// Use realm::safe_equal() instead of std::equal() if one of the parameters can be a null pointer.
template <class InputIterator1, class InputIterator2>
bool safe_equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2)
{
#if defined(_MSC_VER)
    // VS has a special check in debug mode against passing a null pointer std::equal(); it will give a warning
    // at runtime if this is observed.
    // It's uncertain if this is allowed by the C++ standard. For details, see
    // http://stackoverflow.com/questions/19120779/is-char-p-0-stdequalp-p-p-well-defined-according-to-the-c-standard.
    // So we use a safe C++14 method instead that takes two range pairs.
    size_t len = last1 - first1;
    return std::equal(first1, last1, first2, first2 + len);
#else
    return std::equal(first1, last1, first2);
#endif
}

// Use realm::safe_copy_n() instead of std::copy_n() if one of the parameters can be a null pointer. See the
// explanation of safe_equal() above; same things apply.
template< class InputIt, class Size, class OutputIt>
OutputIt safe_copy_n(InputIt first, Size count, OutputIt result)
{
#if defined(_MSC_VER)
    // This loop and the method prototype is copy pasted
    // from "Possible implementation" on http://en.cppreference.com/w/cpp/algorithm/copy_n
    if (count > 0) {
        *result++ = *first;
        for (Size i = 1; i < count; ++i) {
            *result++ = *++first;
        }
    }
    return result;
#else
    return std::copy_n(first, count, result);
#endif
}

template <class T>
struct Wrap {
    Wrap(const T& v)
        : m_value(v)
    {
    }
    operator T() const
    {
        return m_value;
    }

private:
    T m_value;
};

// PlacementDelete is intended for use with std::unique_ptr when it holds an object allocated with
// placement new. It simply calls the object's destructor without freeing the memory.
struct PlacementDelete {
    template <class T>
    void operator()(T* v) const
    {
        v->~T();
    }
};

} // namespace realm

#endif // REALM_UTILITIES_HPP
<commit_msg>Remove the now superfluous index method `index_FindAll`.<commit_after>/*************************************************************************
 *
 * Copyright 2016 Realm Inc.
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 **************************************************************************/

#ifndef REALM_UTILITIES_HPP
#define REALM_UTILITIES_HPP

#include <cstdint>
#include <cstdlib>
#include <cstdlib> // size_t
#include <cstdio>
#include <algorithm>
#include <functional>

#ifdef _MSC_VER
#include <intrin.h>
#endif

#include <realm/util/features.h>
#include <realm/util/assert.hpp>
#include <realm/util/safe_int_ops.hpp>

// GCC defines __i386__ and __x86_64__
#if (defined(__X86__) || defined(__i386__) || defined(i386) || defined(_M_IX86) || defined(__386__) ||               \
     defined(__x86_64__) || defined(_M_X64))
#define REALM_X86_OR_X64
#define REALM_X86_OR_X64_TRUE true
#else
#define REALM_X86_OR_X64_TRUE false
#endif

// GCC defines __arm__
#ifdef __arm__
#define REALM_ARCH_ARM
#endif

#if defined _LP64 || defined __LP64__ || defined __64BIT__ || defined _ADDR64 || defined _WIN64 ||                   \
    defined __arch64__ || (defined(__WORDSIZE) && __WORDSIZE == 64) || (defined __sparc && defined __sparcv9) ||     \
    defined __x86_64 || defined __amd64 || defined __x86_64__ || defined _M_X64 || defined _M_IA64 ||                \
    defined __ia64 || defined __IA64__
#define REALM_PTR_64
#endif

#if defined(REALM_PTR_64) && defined(REALM_X86_OR_X64)
#define REALM_COMPILER_SSE // Compiler supports SSE 4.2 through __builtin_ accessors or back-end assembler
#define REALM_COMPILER_AVX
#endif

namespace realm {

using StringCompareCallback = std::function<bool(const char* string1, const char* string2)>;

extern signed char sse_support;
extern signed char avx_support;

template <int version>
REALM_FORCEINLINE bool sseavx()
{
    /*
    Return whether or not SSE 3.0 (if version = 30) or 4.2 (for version = 42) is supported. Return value
    is based on the CPUID instruction.

    sse_support = -1: No SSE support
    sse_support = 0: SSE3
    sse_support = 1: SSE42

    avx_support = -1: No AVX support
    avx_support = 0: AVX1 supported
    sse_support = 1: AVX2 supported (not yet implemented for detection in our cpuid_init(), todo)

    This lets us test very rapidly at runtime because we just need 1 compare instruction (with 0) to test both for
    SSE 3 and 4.2 by caller (compiler optimizes if calls are concecutive), and can decide branch with ja/jl/je because
    sse_support is signed type. Also, 0 requires no immediate operand. Same for AVX.

    We runtime-initialize sse_support in a constructor of a static variable which is not guaranteed to be called
    prior to cpu_sse(). So we compile-time initialize sse_support to -2 as fallback.
    */
    static_assert(version == 1 || version == 2 || version == 30 || version == 42,
                  "Only version == 1 (AVX), 2 (AVX2), 30 (SSE 3) and 42 (SSE 4.2) are supported for detection");
#ifdef REALM_COMPILER_SSE
    if (version == 30)
        return (sse_support >= 0);
    else if (version == 42)
        return (sse_support > 0); // faster than == 1 (0 requres no immediate operand)
    else if (version == 1)        // avx
        return (avx_support >= 0);
    else if (version == 2) // avx2
        return (avx_support > 0);
    else
        return false;
#else
    return false;
#endif
}

void cpuid_init();
void* round_up(void* p, size_t align);
void* round_down(void* p, size_t align);
size_t round_up(size_t p, size_t align);
size_t round_down(size_t p, size_t align);
void millisleep(unsigned long milliseconds);

#ifdef REALM_SLAB_ALLOC_TUNE
void process_mem_usage(double& vm_usage, double& resident_set);
#endif
// popcount
int fast_popcount32(int32_t x);
int fast_popcount64(int64_t x);
uint64_t fastrand(uint64_t max = 0xffffffffffffffffULL, bool is_seed = false);

// log2 - returns -1 if x==0, otherwise log2(x)
inline int log2(size_t x)
{
    if (x == 0)
        return -1;
#if defined(__GNUC__)
#ifdef REALM_PTR_64
    return 63 - __builtin_clzll(x); // returns int
#else
    return 31 - __builtin_clz(x); // returns int
#endif
#elif defined(_WIN32)
    unsigned long index = 0;
#ifdef REALM_PTR_64
    unsigned char c = _BitScanReverse64(&index, x); // outputs unsigned long
#else
    unsigned char c = _BitScanReverse(&index, x); // outputs unsigned long
#endif
    return static_cast<int>(index);
#else // not __GNUC__ and not _WIN32
    int r = 0;
    while (x >>= 1) {
        r++;
    }
    return r;
#endif
}

// Implementation:

// Safe cast from 64 to 32 bits on 32 bit architecture. Differs from to_ref() by not testing alignment and
// REF-bitflag.
inline size_t to_size_t(int_fast64_t v) noexcept
{
    REALM_ASSERT_DEBUG(!util::int_cast_has_overflow<size_t>(v));
    return size_t(v);
}

template <typename ReturnType, typename OriginalType>
ReturnType type_punning(OriginalType variable) noexcept
{
    union Both {
        OriginalType in;
        ReturnType out;
    };
    Both both;
    both.out = ReturnType(); // Clear all bits in case ReturnType is larger than OriginalType
    both.in = variable;
    return both.out;
}

// Also see the comments in Array::index_string()
enum FindRes {
    // Indicate that no results were found in the search
    FindRes_not_found,
    // Indicates a single result is found
    FindRes_single,
    // Indicates more than one result is found and they are stored in a column
    FindRes_column
};

enum IndexMethod {
    index_FindFirst,
    index_FindAll_nocopy,
    index_FindAll_ins,
    index_Count,
};

// Combined result of the index_FindAll_nocopy operation. The column returned
// can contain results that are not matches but all matches are within the
// returned start_ndx and end_ndx.
struct InternalFindResult {
    // Reference to a IntegerColumn containing result rows, or a single row
    // value if the result is FindRes_single.
    size_t payload;
    // Offset into the result column to start at.
    size_t start_ndx;
    // Offset index in the result column to end at.
    size_t end_ndx;
};

// realm::is_any<T, U1, U2, U3, ...> ==
// std::is_same<T, U1>::value || std::is_same<T, U2>::value || std::is_same<T, U3>::value ...
template <typename... T>
struct is_any : std::false_type {
};

template <typename T, typename... Ts>
struct is_any<T, T, Ts...> : std::true_type {
};

template <typename T, typename U, typename... Ts>
struct is_any<T, U, Ts...> : is_any<T, Ts...> {
};

// Use realm::safe_equal() instead of std::equal() if one of the parameters can be a null pointer.
template <class InputIterator1, class InputIterator2>
bool safe_equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2)
{
#if defined(_MSC_VER)
    // VS has a special check in debug mode against passing a null pointer std::equal(); it will give a warning
    // at runtime if this is observed.
    // It's uncertain if this is allowed by the C++ standard. For details, see
    // http://stackoverflow.com/questions/19120779/is-char-p-0-stdequalp-p-p-well-defined-according-to-the-c-standard.
    // So we use a safe C++14 method instead that takes two range pairs.
    size_t len = last1 - first1;
    return std::equal(first1, last1, first2, first2 + len);
#else
    return std::equal(first1, last1, first2);
#endif
}

// Use realm::safe_copy_n() instead of std::copy_n() if one of the parameters can be a null pointer. See the
// explanation of safe_equal() above; same things apply.
template< class InputIt, class Size, class OutputIt>
OutputIt safe_copy_n(InputIt first, Size count, OutputIt result)
{
#if defined(_MSC_VER)
    // This loop and the method prototype is copy pasted
    // from "Possible implementation" on http://en.cppreference.com/w/cpp/algorithm/copy_n
    if (count > 0) {
        *result++ = *first;
        for (Size i = 1; i < count; ++i) {
            *result++ = *++first;
        }
    }
    return result;
#else
    return std::copy_n(first, count, result);
#endif
}

template <class T>
struct Wrap {
    Wrap(const T& v)
        : m_value(v)
    {
    }
    operator T() const
    {
        return m_value;
    }

private:
    T m_value;
};

// PlacementDelete is intended for use with std::unique_ptr when it holds an object allocated with
// placement new. It simply calls the object's destructor without freeing the memory.
struct PlacementDelete {
    template <class T>
    void operator()(T* v) const
    {
        v->~T();
    }
};

} // namespace realm

#endif // REALM_UTILITIES_HPP
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdlib.h>

#include "debugger.h"
#include "jni_internal.h"
#include "JNIHelp.h"
#include "thread-inl.h"

#if defined(HAVE_PRCTL)
#include <sys/prctl.h>
#endif

namespace art {

static void EnableDebugger() {
  // To let a non-privileged gdbserver attach to this
  // process, we must set our dumpable flag.
  if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
    PLOG(ERROR) << "prctl(PR_SET_DUMPABLE) failed for pid " << getpid();
  }
  // We don't want core dumps, though, so set the core dump size to 0.
  rlimit rl;
  rl.rlim_cur = 0;
  rl.rlim_max = RLIM_INFINITY;
  if (setrlimit(RLIMIT_CORE, &rl) == -1) {
    PLOG(ERROR) << "setrlimit(RLIMIT_CORE) failed for pid " << getpid();
  }
}

static void EnableDebugFeatures(uint32_t debug_flags) {
  // Must match values in dalvik.system.Zygote.
  enum {
    DEBUG_ENABLE_DEBUGGER           = 1,
    DEBUG_ENABLE_CHECKJNI           = 1 << 1,
    DEBUG_ENABLE_ASSERT             = 1 << 2,
    DEBUG_ENABLE_SAFEMODE           = 1 << 3,
    DEBUG_ENABLE_JNI_LOGGING        = 1 << 4,
  };

  if ((debug_flags & DEBUG_ENABLE_CHECKJNI) != 0) {
    Runtime* runtime = Runtime::Current();
    JavaVMExt* vm = runtime->GetJavaVM();
    if (!vm->check_jni) {
      LOG(DEBUG) << "Late-enabling -Xcheck:jni";
      vm->SetCheckJniEnabled(true);
      // There's only one thread running at this point, so only one JNIEnv to fix up.
      Thread::Current()->GetJniEnv()->SetCheckJniEnabled(true);
    } else {
      LOG(DEBUG) << "Not late-enabling -Xcheck:jni (already on)";
    }
    debug_flags &= ~DEBUG_ENABLE_CHECKJNI;
  }

  if ((debug_flags & DEBUG_ENABLE_JNI_LOGGING) != 0) {
    gLogVerbosity.third_party_jni = true;
    debug_flags &= ~DEBUG_ENABLE_JNI_LOGGING;
  }

  Dbg::SetJdwpAllowed((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0);
  if ((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0) {
    EnableDebugger();
  }
  debug_flags &= ~DEBUG_ENABLE_DEBUGGER;

  // These two are for backwards compatibility with Dalvik.
  debug_flags &= ~DEBUG_ENABLE_ASSERT;
  debug_flags &= ~DEBUG_ENABLE_SAFEMODE;

  if (debug_flags != 0) {
    LOG(ERROR) << StringPrintf("Unknown bits set in debug_flags: %#x", debug_flags);
  }
}

static jlong ZygoteHooks_nativePreFork(JNIEnv* env, jclass) {
  Runtime* runtime = Runtime::Current();
  CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
  if (!runtime->PreZygoteFork()) {
    LOG(FATAL) << "pre-fork heap failed";
  }

  // Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
  Thread* self = Thread::Current();
  return reinterpret_cast<jlong>(self);
}

static void ZygoteHooks_nativePostForkChild(JNIEnv* env, jclass, jlong token, jint debug_flags) {
  Thread* thread = reinterpret_cast<Thread*>(token);
  // Our system thread ID, etc, has changed so reset Thread state.
  thread->InitAfterFork();
  EnableDebugFeatures(debug_flags);
  Runtime::Current()->DidForkFromZygote();
}

static JNINativeMethod gMethods[] = {
  NATIVE_METHOD(ZygoteHooks, nativePreFork, "()J"),
  NATIVE_METHOD(ZygoteHooks, nativePostForkChild, "(JI)V"),
};

void register_dalvik_system_ZygoteHooks(JNIEnv* env) {
  REGISTER_NATIVE_METHODS("dalvik/system/ZygoteHooks");
}

}  // namespace art
<commit_msg>Include <sys/resource.h> for rlimit.<commit_after>/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdlib.h>

#include "debugger.h"
#include "jni_internal.h"
#include "JNIHelp.h"
#include "thread-inl.h"

#if defined(HAVE_PRCTL)
#include <sys/prctl.h>
#endif

#include <sys/resource.h>

namespace art {

static void EnableDebugger() {
  // To let a non-privileged gdbserver attach to this
  // process, we must set our dumpable flag.
  if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
    PLOG(ERROR) << "prctl(PR_SET_DUMPABLE) failed for pid " << getpid();
  }
  // We don't want core dumps, though, so set the core dump size to 0.
  rlimit rl;
  rl.rlim_cur = 0;
  rl.rlim_max = RLIM_INFINITY;
  if (setrlimit(RLIMIT_CORE, &rl) == -1) {
    PLOG(ERROR) << "setrlimit(RLIMIT_CORE) failed for pid " << getpid();
  }
}

static void EnableDebugFeatures(uint32_t debug_flags) {
  // Must match values in dalvik.system.Zygote.
  enum {
    DEBUG_ENABLE_DEBUGGER           = 1,
    DEBUG_ENABLE_CHECKJNI           = 1 << 1,
    DEBUG_ENABLE_ASSERT             = 1 << 2,
    DEBUG_ENABLE_SAFEMODE           = 1 << 3,
    DEBUG_ENABLE_JNI_LOGGING        = 1 << 4,
  };

  if ((debug_flags & DEBUG_ENABLE_CHECKJNI) != 0) {
    Runtime* runtime = Runtime::Current();
    JavaVMExt* vm = runtime->GetJavaVM();
    if (!vm->check_jni) {
      LOG(DEBUG) << "Late-enabling -Xcheck:jni";
      vm->SetCheckJniEnabled(true);
      // There's only one thread running at this point, so only one JNIEnv to fix up.
      Thread::Current()->GetJniEnv()->SetCheckJniEnabled(true);
    } else {
      LOG(DEBUG) << "Not late-enabling -Xcheck:jni (already on)";
    }
    debug_flags &= ~DEBUG_ENABLE_CHECKJNI;
  }

  if ((debug_flags & DEBUG_ENABLE_JNI_LOGGING) != 0) {
    gLogVerbosity.third_party_jni = true;
    debug_flags &= ~DEBUG_ENABLE_JNI_LOGGING;
  }

  Dbg::SetJdwpAllowed((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0);
  if ((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0) {
    EnableDebugger();
  }
  debug_flags &= ~DEBUG_ENABLE_DEBUGGER;

  // These two are for backwards compatibility with Dalvik.
  debug_flags &= ~DEBUG_ENABLE_ASSERT;
  debug_flags &= ~DEBUG_ENABLE_SAFEMODE;

  if (debug_flags != 0) {
    LOG(ERROR) << StringPrintf("Unknown bits set in debug_flags: %#x", debug_flags);
  }
}

static jlong ZygoteHooks_nativePreFork(JNIEnv* env, jclass) {
  Runtime* runtime = Runtime::Current();
  CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
  if (!runtime->PreZygoteFork()) {
    LOG(FATAL) << "pre-fork heap failed";
  }

  // Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
  Thread* self = Thread::Current();
  return reinterpret_cast<jlong>(self);
}

static void ZygoteHooks_nativePostForkChild(JNIEnv* env, jclass, jlong token, jint debug_flags) {
  Thread* thread = reinterpret_cast<Thread*>(token);
  // Our system thread ID, etc, has changed so reset Thread state.
  thread->InitAfterFork();
  EnableDebugFeatures(debug_flags);
  Runtime::Current()->DidForkFromZygote();
}

static JNINativeMethod gMethods[] = {
  NATIVE_METHOD(ZygoteHooks, nativePreFork, "()J"),
  NATIVE_METHOD(ZygoteHooks, nativePostForkChild, "(JI)V"),
};

void register_dalvik_system_ZygoteHooks(JNIEnv* env) {
  REGISTER_NATIVE_METHODS("dalvik/system/ZygoteHooks");
}

}  // namespace art
<|endoftext|>


<commit_before>#include <iostream>
#include "list.hpp"
#include "circular_list.hpp"
#include "single_list.hpp"
#include "stack_by_list.hpp"

int main()
{
//    ch10::list::single_list_ring<int> l;
//    l.insert(99);
//    l.insert(98);
//    l.insert(9);
//    l.insert(1);
//    l.remove(l.begin());
//    auto ptr = l.search(90);

//    std::cout << l ;
    ch10::list::stack_by_list<int> stk;

//    stk.enqueue(1);

//    stk.enqueue(2);

//    stk.enqueue(3);

//    stk.dequeue();

//    stk.print();
    for(int i = 0; i != 10; ++i)
    {
        stk.enqueue(i);
    }

    for(int i = 0; i != 10; ++i)
    {
        std::cout << stk.dequeue() << std::endl;
    }

    return 0;
}

<commit_msg>refreshed 	modified:   ch10/main.cpp<commit_after>#include <iostream>
#include "list.hpp"
#include "circular_list.hpp"
#include "single_list.hpp"
#include "stack_by_list.hpp"

int main()
{

    return 0;
}

<|endoftext|>


<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* 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., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "oxygenpanedengine.h"

#include <cassert>

namespace Oxygen
{

    //_____________________________________________________________
    PanedEngine::PanedEngine( Animations* parent ):
        BaseEngine( parent ),
        _verticalCursorLoaded( false ),
        _horizontalCursorLoaded( false ),
        _verticalCursor( 0L ),
        _horizontalCursor( 0L )
     {}

    //_____________________________________________________________
    PanedEngine::~PanedEngine( void )
    {
        if( _verticalCursor ) gdk_cursor_destroy( _verticalCursor );
        if( _horizontalCursor ) gdk_cursor_destroy( _horizontalCursor );
    }

    //_____________________________________________________________
    bool PanedEngine::registerWidget( GtkWidget* widget )
    {

        // make sure it is not already registered
        if( _data.find( widget ) != _data.end() ) return false;

        if( GTK_IS_VPANED( widget ) )
        {
            if( !_verticalCursorLoaded )
            {

                assert( !_verticalCursor );

                // get display
                GdkDisplay *display( gdk_display_get_default () );
                _verticalCursor = gdk_cursor_new_from_name( display, "col-resize" );
                _verticalCursorLoaded = true;

            }

            if( _verticalCursor )
            {
                GdkWindow* window(  gtk_paned_get_handle_window( GTK_PANED( widget ) ) );
                gdk_window_set_cursor( window, _verticalCursor );
            }

            _data.insert( widget );
            return true;

        } else if( GTK_IS_HPANED( widget ) ) {

            if( !_horizontalCursorLoaded )
            {

                assert( !_horizontalCursor );

                // get display
                GdkDisplay *display( gdk_display_get_default () );
                _horizontalCursor = gdk_cursor_new_from_name( display, "row-resize" );
                _horizontalCursorLoaded = true;

            }

            if( _horizontalCursor )
            {
                GdkWindow* window(  gtk_paned_get_handle_window( GTK_PANED( widget ) ) );
                gdk_window_set_cursor( window, _horizontalCursor );
            }

            _data.insert( widget );
            return true;

        }

        return false;

    }
}
<commit_msg>gdk_cursor_destroy -> gdk_cursor_unref<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* 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., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "oxygenpanedengine.h"

#include <cassert>

namespace Oxygen
{

    //_____________________________________________________________
    PanedEngine::PanedEngine( Animations* parent ):
        BaseEngine( parent ),
        _verticalCursorLoaded( false ),
        _horizontalCursorLoaded( false ),
        _verticalCursor( 0L ),
        _horizontalCursor( 0L )
     {}

    //_____________________________________________________________
    PanedEngine::~PanedEngine( void )
    {
        if( _verticalCursor ) gdk_cursor_unref( _verticalCursor );
        if( _horizontalCursor ) gdk_cursor_unref( _horizontalCursor );
    }

    //_____________________________________________________________
    bool PanedEngine::registerWidget( GtkWidget* widget )
    {

        // make sure it is not already registered
        if( _data.find( widget ) != _data.end() ) return false;

        if( GTK_IS_VPANED( widget ) )
        {
            if( !_verticalCursorLoaded )
            {

                assert( !_verticalCursor );

                // get display
                GdkDisplay *display( gdk_display_get_default () );
                _verticalCursor = gdk_cursor_new_from_name( display, "col-resize" );
                _verticalCursorLoaded = true;

            }

            if( _verticalCursor )
            {
                GdkWindow* window(  gtk_paned_get_handle_window( GTK_PANED( widget ) ) );
                gdk_window_set_cursor( window, _verticalCursor );
            }

            _data.insert( widget );
            return true;

        } else if( GTK_IS_HPANED( widget ) ) {

            if( !_horizontalCursorLoaded )
            {

                assert( !_horizontalCursor );

                // get display
                GdkDisplay *display( gdk_display_get_default () );
                _horizontalCursor = gdk_cursor_new_from_name( display, "row-resize" );
                _horizontalCursorLoaded = true;

            }

            if( _horizontalCursor )
            {
                GdkWindow* window(  gtk_paned_get_handle_window( GTK_PANED( widget ) ) );
                gdk_window_set_cursor( window, _horizontalCursor );
            }

            _data.insert( widget );
            return true;

        }

        return false;

    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TitleToolBox.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 06:35:43 $
 *
 *  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
 *
 ************************************************************************/

#include "TitleToolBox.hxx"

#include "res_bmp.hrc"

#ifndef _SV_BITMAP_HXX
#include <vcl/bitmap.hxx>
#endif
#ifndef _SV_BITMAPEX_HXX
#include <vcl/bitmapex.hxx>
#endif
#ifndef _SDRESID_HXX
#include "sdresid.hxx"
#endif
#include <rtl/ustring.hxx>

namespace sd { namespace toolpanel {

TitleToolBox::TitleToolBox (::Window* pParent, WinBits nStyle )
    : ToolBox( pParent, nStyle )
{
    lastSize = -1;

    Bitmap aBitmap (SdResId (BMP_CLOSE_DOC));
    Bitmap aBitmapHC (SdResId (BMP_CLOSE_DOC_H));
    Bitmap aTriangleRight (SdResId (BMP_TRIANGLE_RIGHT));
    Bitmap aTriangleDown (SdResId (BMP_TRIANGLE_DOWN));

    maImage = Image (aBitmap, Color (COL_LIGHTMAGENTA));
    maImageHC = Image (aBitmapHC, Color (BMP_COLOR_HIGHCONTRAST));
    maTriangleRight = Image (aTriangleRight, Color (COL_LIGHTMAGENTA));
    maTriangleDown = Image (aTriangleDown, Color (COL_LIGHTMAGENTA));

    SetOutStyle (TOOLBOX_STYLE_FLAT);
    SetBackground (Wallpaper (
        GetSettings().GetStyleSettings().GetDialogColor()));
}

void TitleToolBox::AddItem (ToolBoxId aId)
{
    switch (aId)
    {
        case TBID_PANEL_MENU:
            InsertItem (TBID_PANEL_MENU,
                String::CreateFromAscii ("Panel"),
                TIB_DROPDOWN);
            break;

        case TBID_DOCUMENT_CLOSE:
            InsertItem (TBID_DOCUMENT_CLOSE,
                GetSettings().GetStyleSettings().GetMenuBarColor().IsDark()
                ? maImageHC : maImage, 0 );
            break;

        case TBID_TRIANGLE_RIGHT:
            InsertItem (TBID_TRIANGLE_RIGHT,
                maTriangleRight, 0);
            break;

        case TBID_TRIANGLE_DOWN:
            InsertItem (TBID_TRIANGLE_DOWN,
                maTriangleDown, 0);
            break;

        case TBID_TEST:
            InsertItem (TBID_TEST,
                String::CreateFromAscii ("Test"),
                TIB_DROPDOWN);
            break;
    }
}

void TitleToolBox::DataChanged (const DataChangedEvent& rDCEvt)
{
    Window::DataChanged (rDCEvt);

    if (rDCEvt.GetFlags() & SETTINGS_STYLE)
    {
        SetBackground (
            Wallpaper (GetSettings().GetStyleSettings().GetDialogColor()));
    }
}

} } // end of namespace ::sd::toolbox
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.282); FILE MERGED 2006/09/01 17:37:23 kaib 1.3.282.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TitleToolBox.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 19:16:06 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "TitleToolBox.hxx"

#include "res_bmp.hrc"

#ifndef _SV_BITMAP_HXX
#include <vcl/bitmap.hxx>
#endif
#ifndef _SV_BITMAPEX_HXX
#include <vcl/bitmapex.hxx>
#endif
#ifndef _SDRESID_HXX
#include "sdresid.hxx"
#endif
#include <rtl/ustring.hxx>

namespace sd { namespace toolpanel {

TitleToolBox::TitleToolBox (::Window* pParent, WinBits nStyle )
    : ToolBox( pParent, nStyle )
{
    lastSize = -1;

    Bitmap aBitmap (SdResId (BMP_CLOSE_DOC));
    Bitmap aBitmapHC (SdResId (BMP_CLOSE_DOC_H));
    Bitmap aTriangleRight (SdResId (BMP_TRIANGLE_RIGHT));
    Bitmap aTriangleDown (SdResId (BMP_TRIANGLE_DOWN));

    maImage = Image (aBitmap, Color (COL_LIGHTMAGENTA));
    maImageHC = Image (aBitmapHC, Color (BMP_COLOR_HIGHCONTRAST));
    maTriangleRight = Image (aTriangleRight, Color (COL_LIGHTMAGENTA));
    maTriangleDown = Image (aTriangleDown, Color (COL_LIGHTMAGENTA));

    SetOutStyle (TOOLBOX_STYLE_FLAT);
    SetBackground (Wallpaper (
        GetSettings().GetStyleSettings().GetDialogColor()));
}

void TitleToolBox::AddItem (ToolBoxId aId)
{
    switch (aId)
    {
        case TBID_PANEL_MENU:
            InsertItem (TBID_PANEL_MENU,
                String::CreateFromAscii ("Panel"),
                TIB_DROPDOWN);
            break;

        case TBID_DOCUMENT_CLOSE:
            InsertItem (TBID_DOCUMENT_CLOSE,
                GetSettings().GetStyleSettings().GetMenuBarColor().IsDark()
                ? maImageHC : maImage, 0 );
            break;

        case TBID_TRIANGLE_RIGHT:
            InsertItem (TBID_TRIANGLE_RIGHT,
                maTriangleRight, 0);
            break;

        case TBID_TRIANGLE_DOWN:
            InsertItem (TBID_TRIANGLE_DOWN,
                maTriangleDown, 0);
            break;

        case TBID_TEST:
            InsertItem (TBID_TEST,
                String::CreateFromAscii ("Test"),
                TIB_DROPDOWN);
            break;
    }
}

void TitleToolBox::DataChanged (const DataChangedEvent& rDCEvt)
{
    Window::DataChanged (rDCEvt);

    if (rDCEvt.GetFlags() & SETTINGS_STYLE)
    {
        SetBackground (
            Wallpaper (GetSettings().GetStyleSettings().GetDialogColor()));
    }
}

} } // end of namespace ::sd::toolbox
<|endoftext|>


<commit_before>
class Date {
	int d, m, y;

	public:
	void init(int dd, int mm, int yy);
	Date(int dd, int mm, int yy);
	void add_year(int n);
	void add_month(int n);
	void add_day(int n);
	int day() const { return d; }
	int month() const { return m; }
	int year() const { return y; }
};

void f() {
	Date today(16, 10, 1996);
	today.init(16, 10, 1996);
	Date my_birthday(29, 7, 1985);

	Date tomorrow = today;
	tomorrow.add_day(1);

	Date d1 = today;
	Date d2(today);
}

void f2(Date &d, const Date &cd) {
	int i = d.day();
	d.add_year(1);

	i = cd.day();
	// cd.add_year(1); // Error

	return;
}

int main() {
	return 0;
}

void Date::init(int dd, int mm, int yy) {
	d = dd;
	m = mm;
	y = yy;
}

Date::Date(int dd, int mm, int yy) {
	d = dd;
	m = mm;
	y = yy;
}

void Date::add_day(int n) {
	d += n;
}

void Date::add_year(int n) {
	y += n;
}
<commit_msg>Added mutable examples from 16.2.9.3<commit_after>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

class Date {
	int d, m, y;
	mutable bool cache_valid;
	mutable string cache;

	void compute_cache_value() const;

	public:
	void init(int dd, int mm, int yy);
	Date(int dd, int mm, int yy);
	void add_year(int n);
	void add_month(int n);
	void add_day(int n);
	int day() const { return d; }
	int month() const { return m; }
	int year() const { return y; }
	string string_rep() const;
};

void Date::compute_cache_value() const {
	char tmp[20];
	sprintf(tmp, "%04d-%02d-%02d", y, m, d);
	string tmpstr(tmp);
	cache = tmpstr;
	cache_valid = true;
	return;
}

string Date::string_rep() const {
	if (!cache_valid) {
		compute_cache_value();
	}
	return cache;
}

void f() {
	Date today(16, 10, 1996);
	cout << today.string_rep() << endl;
	today.init(16, 10, 1996);
	Date my_birthday(29, 7, 1985);
	cout << my_birthday.string_rep() << endl;

	Date tomorrow = today;
	tomorrow.add_day(1);

	Date d1 = today;
	Date d2(today);
}

void f2(Date &d, const Date &cd) {
	int i = d.day();
	d.add_year(1);

	i = cd.day();
	// cd.add_year(1); // Error

	return;
}

int main() {
	f();
	return 0;
}

void Date::init(int dd, int mm, int yy) {
	d = dd;
	m = mm;
	y = yy;
}

Date::Date(int dd, int mm, int yy) :
	cache_valid(false),
	cache("")
{
	d = dd;
	m = mm;
	y = yy;
}

void Date::add_day(int n) {
	d += n;
}

void Date::add_year(int n) {
	y += n;
}
<|endoftext|>