<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ImpressViewShellBase.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-03 16:26:19 $
 *
 *  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 "precompiled_sd.hxx"

#include "ImpressViewShellBase.hxx"

#include "DrawDocShell.hxx"
#ifndef SD_RESID_HXX
#include "sdresid.hxx"
#endif
#include "strings.hrc"
#include "app.hrc"
#include "framework/FrameworkHelper.hxx"
#include "framework/ImpressModule.hxx"
#include "MasterPageObserver.hxx"

#ifndef _SFXREQUEST_HXX
#include <sfx2/request.hxx>
#endif

namespace sd {

TYPEINIT1(ImpressViewShellBase, ViewShellBase);

// We have to expand the SFX_IMPL_VIEWFACTORY macro to call LateInit() after a
// new ImpressViewShellBase object has been constructed.

/*
SFX_IMPL_VIEWFACTORY(ImpressViewShellBase, SdResId(STR_DEFAULTVIEW))
{
    SFX_VIEW_REGISTRATION(DrawDocShell);
}
*/
SfxViewFactory* ImpressViewShellBase::pFactory;
SfxViewShell* __EXPORT ImpressViewShellBase::CreateInstance (
    SfxViewFrame *pFrame, SfxViewShell *pOldView)
{
    ImpressViewShellBase* pBase = new ImpressViewShellBase(pFrame, pOldView);
    pBase->LateInit(::rtl::OUString());
    return pBase;
}
void ImpressViewShellBase::RegisterFactory( USHORT nPrio )
{
    pFactory = new SfxViewFactory(
        &CreateInstance,&InitFactory,nPrio,SdResId(STR_DEFAULTVIEW));
    InitFactory();
}
void ImpressViewShellBase::InitFactory()
{
    SFX_VIEW_REGISTRATION(DrawDocShell);
}

ImpressViewShellBase::ImpressViewShellBase (
    SfxViewFrame* _pFrame,
    SfxViewShell* pOldShell)
    : ViewShellBase (_pFrame, pOldShell)
{
    MasterPageObserver::Instance().RegisterDocument (*GetDocShell()->GetDoc());
}

ImpressViewShellBase::~ImpressViewShellBase (void)
{
    MasterPageObserver::Instance().UnregisterDocument (*GetDocShell()->GetDoc());
}

void ImpressViewShellBase::Execute (SfxRequest& rRequest)
{
    USHORT nSlotId = rRequest.GetSlot();

    switch (nSlotId)
    {
        case SID_LEFT_PANE_DRAW:
            // Prevent a Draw-only slots from being executed.
            rRequest.Cancel();
            break;

        default:
            // The remaining requests are forwarded to our base class.
            ViewShellBase::Execute(rRequest);
            break;
    }
}

void ImpressViewShellBase::InitializeFramework (void)
{
    ::com::sun::star::uno::Reference<com::sun::star::frame::XController>
        xController (GetController());
    sd::framework::ImpressModule::Initialize(xController);
}

} // end of namespace sd

<commit_msg>INTEGRATION: CWS changefileheader (1.2.234); FILE MERGED 2008/04/01 15:36:19 thb 1.2.234.3: #i85898# Stripping all external header guards 2008/04/01 12:39:31 thb 1.2.234.2: #i85898# Stripping all external header guards 2008/03/31 13:59:10 rt 1.2.234.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ImpressViewShellBase.cxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "precompiled_sd.hxx"

#include "ImpressViewShellBase.hxx"

#include "DrawDocShell.hxx"
#include "sdresid.hxx"
#include "strings.hrc"
#include "app.hrc"
#include "framework/FrameworkHelper.hxx"
#include "framework/ImpressModule.hxx"
#include "MasterPageObserver.hxx"
#include <sfx2/request.hxx>

namespace sd {

TYPEINIT1(ImpressViewShellBase, ViewShellBase);

// We have to expand the SFX_IMPL_VIEWFACTORY macro to call LateInit() after a
// new ImpressViewShellBase object has been constructed.

/*
SFX_IMPL_VIEWFACTORY(ImpressViewShellBase, SdResId(STR_DEFAULTVIEW))
{
    SFX_VIEW_REGISTRATION(DrawDocShell);
}
*/
SfxViewFactory* ImpressViewShellBase::pFactory;
SfxViewShell* __EXPORT ImpressViewShellBase::CreateInstance (
    SfxViewFrame *pFrame, SfxViewShell *pOldView)
{
    ImpressViewShellBase* pBase = new ImpressViewShellBase(pFrame, pOldView);
    pBase->LateInit(::rtl::OUString());
    return pBase;
}
void ImpressViewShellBase::RegisterFactory( USHORT nPrio )
{
    pFactory = new SfxViewFactory(
        &CreateInstance,&InitFactory,nPrio,SdResId(STR_DEFAULTVIEW));
    InitFactory();
}
void ImpressViewShellBase::InitFactory()
{
    SFX_VIEW_REGISTRATION(DrawDocShell);
}

ImpressViewShellBase::ImpressViewShellBase (
    SfxViewFrame* _pFrame,
    SfxViewShell* pOldShell)
    : ViewShellBase (_pFrame, pOldShell)
{
    MasterPageObserver::Instance().RegisterDocument (*GetDocShell()->GetDoc());
}

ImpressViewShellBase::~ImpressViewShellBase (void)
{
    MasterPageObserver::Instance().UnregisterDocument (*GetDocShell()->GetDoc());
}

void ImpressViewShellBase::Execute (SfxRequest& rRequest)
{
    USHORT nSlotId = rRequest.GetSlot();

    switch (nSlotId)
    {
        case SID_LEFT_PANE_DRAW:
            // Prevent a Draw-only slots from being executed.
            rRequest.Cancel();
            break;

        default:
            // The remaining requests are forwarded to our base class.
            ViewShellBase::Execute(rRequest);
            break;
    }
}

void ImpressViewShellBase::InitializeFramework (void)
{
    ::com::sun::star::uno::Reference<com::sun::star::frame::XController>
        xController (GetController());
    sd::framework::ImpressModule::Initialize(xController);
}

} // end of namespace sd

<|endoftext|>


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

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

#include "navcoinunits.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "transactionfilterproxy.h"
#include "transactiontablemodel.h"
#include "walletmodel.h"
#include "walletframe.h"
#include "askpassphrasedialog.h"
#include "util.h"

#include <QAbstractItemDelegate>
#include <QPainter>

#define DECORATION_SIZE 17
#define NUM_ITEMS 5

class TxViewDelegate : public QAbstractItemDelegate
{
    Q_OBJECT
public:
    TxViewDelegate(const PlatformStyle *platformStyle):
        QAbstractItemDelegate(), unit(NavCoinUnits::NAV),
        platformStyle(platformStyle)
    {

    }

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

        QIcon icon = qvariant_cast<QIcon>(index.data(TransactionTableModel::RawDecorationRole));
        QRect mainRect = option.rect;
        QRect decorationRect(mainRect.left(), mainRect.top()+DECORATION_SIZE, DECORATION_SIZE, DECORATION_SIZE);
        int xspace = DECORATION_SIZE + 6;
        int ypad = 1;
        int halfheight = (mainRect.height() - 3*ypad - 4)/3 ;
        QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, 150, DECORATION_SIZE);
        QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad, 300, DECORATION_SIZE);
        QRect dateRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight*2, 150, DECORATION_SIZE);
        icon = platformStyle->SingleColorIcon(icon);
        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);

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

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

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

        painter->setPen(COLOR_BAREADDRESS);
        painter->drawText(dateRect, 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*2.9 + 4);
    }

    int unit;
    const PlatformStyle *platformStyle;

};
#include "overviewpage.moc"

OverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OverviewPage),
    clientModel(0),
    walletModel(0),
    currentBalance(-1),
    currentUnconfirmedBalance(-1),
    currentStakingBalance(-1),
    currentColdStakingBalance(-1),
    currentImmatureBalance(-1),
    currentWatchOnlyBalance(-1),
    currentWatchUnconfBalance(-1),
    currentWatchImmatureBalance(-1),
    txdelegate(new TxViewDelegate(platformStyle)),
    filter(0)
{
    ui->setupUi(this);

    // use a SingleColorIcon for the "out of sync warning" icon
    QIcon icon = platformStyle->SingleColorIcon(":/icons/warning");
    icon.addPixmap(icon.pixmap(QSize(64,64), QIcon::Normal), QIcon::Disabled); // also set the disabled icon because we are using a disabled QPushButton to work around missing HiDPI support of QLabel (https://bugreports.qt.io/browse/QTBUG-42503)
    ui->labelWalletStatus->setIcon(icon);

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

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

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

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

void OverviewPage::showLockStaking(bool status)
{
    ui->unlockStakingButton->setVisible(status);
}

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

void OverviewPage::setStakingStats(QString day, QString week, QString month)
{
    ui->label24hStakingStats->setText(day);
    ui->label7dStakingStats->setText(week);
    ui->label30dStakingStats->setText(month);
}

void OverviewPage::setVotingStatus(QString text)
{
    ui->votingStatusLabel->setText(text);
}

void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& stakingBalance, const CAmount& immatureBalance,
                              const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance,
                              const CAmount& coldStakingBalance)
{
    int unit = walletModel->getOptionsModel()->getDisplayUnit();
    currentBalance = balance;
    currentUnconfirmedBalance = unconfirmedBalance;
    currentStakingBalance = stakingBalance;
    currentColdStakingBalance = coldStakingBalance;
    currentImmatureBalance = immatureBalance;
    currentWatchOnlyBalance = watchOnlyBalance;
    currentWatchUnconfBalance = watchUnconfBalance;
    currentWatchImmatureBalance = watchImmatureBalance;
    ui->labelBalance->setText(NavCoinUnits::formatWithUnit(unit, balance, false, NavCoinUnits::separatorAlways));
    ui->labelUnconfirmed->setText(NavCoinUnits::formatWithUnit(unit, unconfirmedBalance, false, NavCoinUnits::separatorAlways));
    ui->labelStaking->setText(NavCoinUnits::formatWithUnit(unit, stakingBalance, false, NavCoinUnits::separatorAlways));
    ui->labelColdStaking->setText(NavCoinUnits::formatWithUnit(unit, coldStakingBalance, false, NavCoinUnits::separatorAlways));
    ui->labelImmature->setText(NavCoinUnits::formatWithUnit(unit, immatureBalance, false, NavCoinUnits::separatorAlways));
    ui->labelTotal->setText(NavCoinUnits::formatWithUnit(unit, balance + unconfirmedBalance + stakingBalance, false, NavCoinUnits::separatorAlways));

    bool showStaking = stakingBalance != 0;

    ui->labelStaking->setVisible(showStaking);
    ui->labelStakingText->setVisible(showStaking);

    bool showColdStaking = coldStakingBalance != 0;

    ui->labelColdStaking->setVisible(showColdStaking);
    ui->labelColdStakingText->setVisible(showColdStaking);

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

    // for symmetry reasons also show immature label when the watch-only one is shown
    ui->labelImmature->setVisible(false);
    ui->labelImmatureText->setVisible(false);
}

// show/hide watch-only labels
void OverviewPage::updateWatchOnlyLabels(bool showWatchOnly)
{

}

void OverviewPage::setStakingStatus(QString text)
{
    ui->stakingStatusLabel->setText(text);
};

void OverviewPage::setStatusTitleBlocks(QString text)
{
    ui->statusTitleBlocks->setText(text);
}

void OverviewPage::setStatusTitleConnections(QString text)
{
    ui->statusTitleConnections->setText(text);

}

void OverviewPage::setStatusTitle(QString text)
{
    ui->statusTitle->setText(text);
}

void OverviewPage::showStatusTitleConnections(){
    ui->statusTitleConnections->show();
};
void OverviewPage::hideStatusTitleConnections(){
    ui->statusTitleConnections->hide();
};
void OverviewPage::showStatusTitleBlocks(){
    ui->statusTitleBlocks->show();
};
void OverviewPage::hideStatusTitleBlocks(){
    ui->statusTitleBlocks->hide();
};

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

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

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

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

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

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

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

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

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

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

void OverviewPage::unlockWalletStaking()
{
    if(!walletModel)
        return;
    // Unlock wallet when requested by wallet model
    if (walletModel->getEncryptionStatus() == WalletModel::Locked)
    {
        AskPassphraseDialog dlg(AskPassphraseDialog::UnlockStaking, this);
        dlg.setModel(walletModel);
        dlg.exec();
    }
}

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

using namespace boost;
using namespace std;

struct StakePeriodRange_T {
    int64_t Start;
    int64_t End;
    int64_t Total;
    int Count;
    string Name;
};

typedef vector<StakePeriodRange_T> vStakePeriodRange_T;

extern vStakePeriodRange_T PrepareRangeForStakeReport();
extern int GetsStakeSubTotal(vStakePeriodRange_T& aRange);

void OverviewPage::updateStakeReport(bool fImmediate=false)
{
    static vStakePeriodRange_T aRange;
    int nItemCounted=0;

    if (fImmediate) nLastReportUpdate = 0;

    if (this->isHidden())
        return;

    int64_t nTook = GetTimeMillis();

    // Skip report recalc if not immediate or before 5 minutes from last
    if (GetTime() - nLastReportUpdate > 300)
    {

        aRange = PrepareRangeForStakeReport();

        // get subtotal calc
        nItemCounted = GetsStakeSubTotal(aRange);

        nLastReportUpdate = GetTime();

        nTook = GetTimeMillis() - nTook;

    }

    int64_t nTook2 = GetTimeMillis();

    int i=30;

    int unit = walletModel->getOptionsModel()->getDisplayUnit();

    ui->label24hStakingStats->setText(NavCoinUnits::formatWithUnit(unit, aRange[i++].Total, false, NavCoinUnits::separatorAlways));
    ui->label7dStakingStats->setText(NavCoinUnits::formatWithUnit(unit, aRange[i++].Total, false, NavCoinUnits::separatorAlways));
    ui->label30dStakingStats->setText(NavCoinUnits::formatWithUnit(unit, aRange[i++].Total, false, NavCoinUnits::separatorAlways));

}

void OverviewPage::updateStakeReportbalanceChanged(qint64, qint64, qint64, qint64, qint64, qint64, qint64)
{
    OverviewPage::updateStakeReportNow();
}

void OverviewPage::updateStakeReportNow()
{
    updateStakeReport(true);
}
<commit_msg>unused var<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

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

#include "navcoinunits.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "transactionfilterproxy.h"
#include "transactiontablemodel.h"
#include "walletmodel.h"
#include "walletframe.h"
#include "askpassphrasedialog.h"
#include "util.h"

#include <QAbstractItemDelegate>
#include <QPainter>

#define DECORATION_SIZE 17
#define NUM_ITEMS 5

class TxViewDelegate : public QAbstractItemDelegate
{
    Q_OBJECT
public:
    TxViewDelegate(const PlatformStyle *platformStyle):
        QAbstractItemDelegate(), unit(NavCoinUnits::NAV),
        platformStyle(platformStyle)
    {

    }

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

        QIcon icon = qvariant_cast<QIcon>(index.data(TransactionTableModel::RawDecorationRole));
        QRect mainRect = option.rect;
        QRect decorationRect(mainRect.left(), mainRect.top()+DECORATION_SIZE, DECORATION_SIZE, DECORATION_SIZE);
        int xspace = DECORATION_SIZE + 6;
        int ypad = 1;
        int halfheight = (mainRect.height() - 3*ypad - 4)/3 ;
        QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, 150, DECORATION_SIZE);
        QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad, 300, DECORATION_SIZE);
        QRect dateRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight*2, 150, DECORATION_SIZE);
        icon = platformStyle->SingleColorIcon(icon);
        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);

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

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

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

        painter->setPen(COLOR_BAREADDRESS);
        painter->drawText(dateRect, 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*2.9 + 4);
    }

    int unit;
    const PlatformStyle *platformStyle;

};
#include "overviewpage.moc"

OverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OverviewPage),
    clientModel(0),
    walletModel(0),
    currentBalance(-1),
    currentUnconfirmedBalance(-1),
    currentStakingBalance(-1),
    currentColdStakingBalance(-1),
    currentImmatureBalance(-1),
    currentWatchOnlyBalance(-1),
    currentWatchUnconfBalance(-1),
    currentWatchImmatureBalance(-1),
    txdelegate(new TxViewDelegate(platformStyle)),
    filter(0)
{
    ui->setupUi(this);

    // use a SingleColorIcon for the "out of sync warning" icon
    QIcon icon = platformStyle->SingleColorIcon(":/icons/warning");
    icon.addPixmap(icon.pixmap(QSize(64,64), QIcon::Normal), QIcon::Disabled); // also set the disabled icon because we are using a disabled QPushButton to work around missing HiDPI support of QLabel (https://bugreports.qt.io/browse/QTBUG-42503)
    ui->labelWalletStatus->setIcon(icon);

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

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

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

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

void OverviewPage::showLockStaking(bool status)
{
    ui->unlockStakingButton->setVisible(status);
}

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

void OverviewPage::setStakingStats(QString day, QString week, QString month)
{
    ui->label24hStakingStats->setText(day);
    ui->label7dStakingStats->setText(week);
    ui->label30dStakingStats->setText(month);
}

void OverviewPage::setVotingStatus(QString text)
{
    ui->votingStatusLabel->setText(text);
}

void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& stakingBalance, const CAmount& immatureBalance,
                              const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance,
                              const CAmount& coldStakingBalance)
{
    int unit = walletModel->getOptionsModel()->getDisplayUnit();
    currentBalance = balance;
    currentUnconfirmedBalance = unconfirmedBalance;
    currentStakingBalance = stakingBalance;
    currentColdStakingBalance = coldStakingBalance;
    currentImmatureBalance = immatureBalance;
    currentWatchOnlyBalance = watchOnlyBalance;
    currentWatchUnconfBalance = watchUnconfBalance;
    currentWatchImmatureBalance = watchImmatureBalance;
    ui->labelBalance->setText(NavCoinUnits::formatWithUnit(unit, balance, false, NavCoinUnits::separatorAlways));
    ui->labelUnconfirmed->setText(NavCoinUnits::formatWithUnit(unit, unconfirmedBalance, false, NavCoinUnits::separatorAlways));
    ui->labelStaking->setText(NavCoinUnits::formatWithUnit(unit, stakingBalance, false, NavCoinUnits::separatorAlways));
    ui->labelColdStaking->setText(NavCoinUnits::formatWithUnit(unit, coldStakingBalance, false, NavCoinUnits::separatorAlways));
    ui->labelImmature->setText(NavCoinUnits::formatWithUnit(unit, immatureBalance, false, NavCoinUnits::separatorAlways));
    ui->labelTotal->setText(NavCoinUnits::formatWithUnit(unit, balance + unconfirmedBalance + stakingBalance, false, NavCoinUnits::separatorAlways));

    bool showStaking = stakingBalance != 0;

    ui->labelStaking->setVisible(showStaking);
    ui->labelStakingText->setVisible(showStaking);

    bool showColdStaking = coldStakingBalance != 0;

    ui->labelColdStaking->setVisible(showColdStaking);
    ui->labelColdStakingText->setVisible(showColdStaking);

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

    // for symmetry reasons also show immature label when the watch-only one is shown
    ui->labelImmature->setVisible(false);
    ui->labelImmatureText->setVisible(false);
}

// show/hide watch-only labels
void OverviewPage::updateWatchOnlyLabels(bool showWatchOnly)
{

}

void OverviewPage::setStakingStatus(QString text)
{
    ui->stakingStatusLabel->setText(text);
};

void OverviewPage::setStatusTitleBlocks(QString text)
{
    ui->statusTitleBlocks->setText(text);
}

void OverviewPage::setStatusTitleConnections(QString text)
{
    ui->statusTitleConnections->setText(text);

}

void OverviewPage::setStatusTitle(QString text)
{
    ui->statusTitle->setText(text);
}

void OverviewPage::showStatusTitleConnections(){
    ui->statusTitleConnections->show();
};
void OverviewPage::hideStatusTitleConnections(){
    ui->statusTitleConnections->hide();
};
void OverviewPage::showStatusTitleBlocks(){
    ui->statusTitleBlocks->show();
};
void OverviewPage::hideStatusTitleBlocks(){
    ui->statusTitleBlocks->hide();
};

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

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

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

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

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

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

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

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

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

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

void OverviewPage::unlockWalletStaking()
{
    if(!walletModel)
        return;
    // Unlock wallet when requested by wallet model
    if (walletModel->getEncryptionStatus() == WalletModel::Locked)
    {
        AskPassphraseDialog dlg(AskPassphraseDialog::UnlockStaking, this);
        dlg.setModel(walletModel);
        dlg.exec();
    }
}

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

using namespace boost;
using namespace std;

struct StakePeriodRange_T {
    int64_t Start;
    int64_t End;
    int64_t Total;
    int Count;
    string Name;
};

typedef vector<StakePeriodRange_T> vStakePeriodRange_T;

extern vStakePeriodRange_T PrepareRangeForStakeReport();
extern int GetsStakeSubTotal(vStakePeriodRange_T& aRange);

void OverviewPage::updateStakeReport(bool fImmediate=false)
{
    static vStakePeriodRange_T aRange;
    int nItemCounted=0;

    if (fImmediate) nLastReportUpdate = 0;

    if (this->isHidden())
        return;

    int64_t nTook = GetTimeMillis();

    // Skip report recalc if not immediate or before 5 minutes from last
    if (GetTime() - nLastReportUpdate > 300)
    {

        aRange = PrepareRangeForStakeReport();

        // get subtotal calc
        nItemCounted = GetsStakeSubTotal(aRange);

        nLastReportUpdate = GetTime();

        nTook = GetTimeMillis() - nTook;

    }

    //int64_t nTook2 = GetTimeMillis();

    int i=30;

    int unit = walletModel->getOptionsModel()->getDisplayUnit();

    ui->label24hStakingStats->setText(NavCoinUnits::formatWithUnit(unit, aRange[i++].Total, false, NavCoinUnits::separatorAlways));
    ui->label7dStakingStats->setText(NavCoinUnits::formatWithUnit(unit, aRange[i++].Total, false, NavCoinUnits::separatorAlways));
    ui->label30dStakingStats->setText(NavCoinUnits::formatWithUnit(unit, aRange[i++].Total, false, NavCoinUnits::separatorAlways));

}

void OverviewPage::updateStakeReportbalanceChanged(qint64, qint64, qint64, qint64, qint64, qint64, qint64)
{
    OverviewPage::updateStakeReportNow();
}

void OverviewPage::updateStakeReportNow()
{
    updateStakeReport(true);
}
<|endoftext|>


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

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <qt/splashscreen.h>

#include <clientversion.h>
#include <interfaces/handler.h>
#include <interfaces/node.h>
#include <interfaces/wallet.h>
#include <qt/guiutil.h>
#include <qt/networkstyle.h>
#include <util/system.h>
#include <util/translation.h>

#include <QApplication>
#include <QCloseEvent>
#include <QPainter>
#include <QRadialGradient>
#include <QScreen>

SplashScreen::SplashScreen(const NetworkStyle *networkStyle)
    : QWidget(nullptr), curAlignment(0) {
    // set reference point, paddings
    int paddingRight = 50;
    int paddingTop = 50;
    int titleVersionVSpace = 17;
    int titleCopyrightVSpace = 40;

    float fontFactor = 1.0;
    float devicePixelRatio = 1.0;
    devicePixelRatio =
        static_cast<QGuiApplication *>(QCoreApplication::instance())
            ->devicePixelRatio();

    // define text to place
    QString titleText = PACKAGE_NAME;
    QString versionText =
        QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText = QString::fromUtf8(
        CopyrightHolders(strprintf("\xc2\xA9 %u-%u ", 2009, COPYRIGHT_YEAR))
            .c_str());
    QString titleAddText = networkStyle->getTitleAddText();

    QString font = QApplication::font().toString();

    // create a bitmap according to device pixelratio
    QSize splashSize(634 * devicePixelRatio, 320 * devicePixelRatio);
    pixmap = QPixmap(splashSize);

    // change to HiDPI if it makes sense
    pixmap.setDevicePixelRatio(devicePixelRatio);

    QPainter pixPaint(&pixmap);
    pixPaint.setPen(QColor(100, 100, 100));

    // draw a slightly radial gradient
    QRadialGradient gradient(QPoint(0, 0),
                             splashSize.width() / devicePixelRatio);
    gradient.setColorAt(0, Qt::white);
    gradient.setColorAt(1, QColor(247, 247, 247));
    QRect rGradient(QPoint(0, 0), splashSize);
    pixPaint.fillRect(rGradient, gradient);

    // draw the bitcoin icon, expected size of PNG: 1024x1024
    QRect rectIcon(QPoint(-10, -100), QSize(430, 430));

    const QSize requiredSize(1024, 1024);
    QPixmap icon(networkStyle->getAppIcon().pixmap(requiredSize));

    pixPaint.drawPixmap(rectIcon, icon);

    // check font size and drawing with
    pixPaint.setFont(QFont(font, 33 * fontFactor));
    QFontMetrics fm = pixPaint.fontMetrics();
    int titleTextWidth = GUIUtil::TextWidth(fm, titleText);
    if (titleTextWidth > 176) {
        fontFactor = fontFactor * 176 / titleTextWidth;
    }

    pixPaint.setFont(QFont(font, 33 * fontFactor));
    fm = pixPaint.fontMetrics();
    titleTextWidth = GUIUtil::TextWidth(fm, titleText);
    pixPaint.drawText(pixmap.width() / devicePixelRatio - titleTextWidth -
                          paddingRight,
                      paddingTop, titleText);

    pixPaint.setFont(QFont(font, 15 * fontFactor));

    // if the version string is too long, reduce size
    fm = pixPaint.fontMetrics();
    int versionTextWidth = GUIUtil::TextWidth(fm, titleText);
    if (versionTextWidth > titleTextWidth + paddingRight - 10) {
        pixPaint.setFont(QFont(font, 10 * fontFactor));
        titleVersionVSpace -= 5;
    }
    pixPaint.drawText(pixmap.width() / devicePixelRatio - titleTextWidth -
                          paddingRight + 2,
                      paddingTop + titleVersionVSpace, versionText);

    // draw copyright stuff
    {
        pixPaint.setFont(QFont(font, 10 * fontFactor));
        const int x =
            pixmap.width() / devicePixelRatio - titleTextWidth - paddingRight;
        const int y = paddingTop + titleCopyrightVSpace;
        QRect copyrightRect(x, y, pixmap.width() - x - paddingRight,
                            pixmap.height() - y);
        pixPaint.drawText(copyrightRect,
                          Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap,
                          copyrightText);
    }

    // draw additional text if special network
    if (!titleAddText.isEmpty()) {
        QFont boldFont = QFont(font, 10 * fontFactor);
        boldFont.setWeight(QFont::Bold);
        pixPaint.setFont(boldFont);
        fm = pixPaint.fontMetrics();
        int titleAddTextWidth = GUIUtil::TextWidth(fm, titleAddText);
        pixPaint.drawText(pixmap.width() / devicePixelRatio -
                              titleAddTextWidth - 10,
                          15, titleAddText);
    }

    pixPaint.end();

    // Set window title
    setWindowTitle(titleText + " " + titleAddText);

    // Resize window and move to center of desktop, disallow resizing
    QRect r(QPoint(), QSize(pixmap.size().width() / devicePixelRatio,
                            pixmap.size().height() / devicePixelRatio));
    resize(r.size());
    setFixedSize(r.size());
    move(QGuiApplication::primaryScreen()->geometry().center() - r.center());

    installEventFilter(this);
}

SplashScreen::~SplashScreen() {
    if (m_node) {
        unsubscribeFromCoreSignals();
    }
}

void SplashScreen::setNode(interfaces::Node &node) {
    assert(!m_node);
    m_node = &node;
    subscribeToCoreSignals();
    if (m_shutdown) {
        m_node->startShutdown();
    }
}

void SplashScreen::shutdown() {
    m_shutdown = true;
    if (m_node) {
        m_node->startShutdown();
    }
}

bool SplashScreen::eventFilter(QObject *obj, QEvent *ev) {
    if (ev->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(ev);
        if (keyEvent->text()[0] == 'q') {
            shutdown();
        }
    }
    return QObject::eventFilter(obj, ev);
}

void SplashScreen::finish() {
    /* If the window is minimized, hide() will be ignored. */
    /* Make sure we de-minimize the splashscreen window before hiding */
    if (isMinimized()) {
        showNormal();
    }
    hide();
    // No more need for this
    deleteLater();
}

static void InitMessage(SplashScreen *splash, const std::string &message) {
    bool invoked = QMetaObject::invokeMethod(
        splash, "showMessage", Qt::QueuedConnection,
        Q_ARG(QString, QString::fromStdString(message)),
        Q_ARG(int, Qt::AlignBottom | Qt::AlignHCenter),
        Q_ARG(QColor, QColor(55, 55, 55)));
    assert(invoked);
}

static void ShowProgress(SplashScreen *splash, const std::string &title,
                         int nProgress, bool resume_possible) {
    InitMessage(
        splash,
        title + std::string("\n") +
            (resume_possible
                 ? _("(press q to shutdown and continue later)").translated
                 : _("press q to shutdown").translated) +
            strprintf("\n%d", nProgress) + "%");
}
#ifdef ENABLE_WALLET
void SplashScreen::ConnectWallet(std::unique_ptr<interfaces::Wallet> wallet) {
    m_connected_wallet_handlers.emplace_back(wallet->handleShowProgress(
        std::bind(ShowProgress, this, std::placeholders::_1,
                  std::placeholders::_2, false)));
    m_connected_wallets.emplace_back(std::move(wallet));
}
#endif

void SplashScreen::subscribeToCoreSignals() {
    // Connect signals to client
    m_handler_init_message = m_node->handleInitMessage(
        std::bind(InitMessage, this, std::placeholders::_1));
    m_handler_show_progress = m_node->handleShowProgress(
        std::bind(ShowProgress, this, std::placeholders::_1,
                  std::placeholders::_2, std::placeholders::_3));
#ifdef ENABLE_WALLET
    m_handler_load_wallet = m_node->handleLoadWallet(
        [this](std::unique_ptr<interfaces::Wallet> wallet) {
            ConnectWallet(std::move(wallet));
        });
#endif
}

void SplashScreen::unsubscribeFromCoreSignals() {
    // Disconnect signals from client
    m_handler_init_message->disconnect();
    m_handler_show_progress->disconnect();
    for (const auto &handler : m_connected_wallet_handlers) {
        handler->disconnect();
    }
    m_connected_wallet_handlers.clear();
    m_connected_wallets.clear();
}

void SplashScreen::showMessage(const QString &message, int alignment,
                               const QColor &color) {
    curMessage = message;
    curAlignment = alignment;
    curColor = color;
    update();
}

void SplashScreen::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    painter.drawPixmap(0, 0, pixmap);
    QRect r = rect().adjusted(5, 5, -5, -5);
    painter.setPen(curColor);
    painter.drawText(r, curAlignment, curMessage);
}

void SplashScreen::closeEvent(QCloseEvent *event) {
    // allows an "emergency" shutdown during startup
    shutdown();
    event->ignore();
}
<commit_msg>qt: Fix deprecated QCharRef usage<commit_after>// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <qt/splashscreen.h>

#include <clientversion.h>
#include <interfaces/handler.h>
#include <interfaces/node.h>
#include <interfaces/wallet.h>
#include <qt/guiutil.h>
#include <qt/networkstyle.h>
#include <util/system.h>
#include <util/translation.h>

#include <QApplication>
#include <QCloseEvent>
#include <QPainter>
#include <QRadialGradient>
#include <QScreen>

SplashScreen::SplashScreen(const NetworkStyle *networkStyle)
    : QWidget(nullptr), curAlignment(0) {
    // set reference point, paddings
    int paddingRight = 50;
    int paddingTop = 50;
    int titleVersionVSpace = 17;
    int titleCopyrightVSpace = 40;

    float fontFactor = 1.0;
    float devicePixelRatio = 1.0;
    devicePixelRatio =
        static_cast<QGuiApplication *>(QCoreApplication::instance())
            ->devicePixelRatio();

    // define text to place
    QString titleText = PACKAGE_NAME;
    QString versionText =
        QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText = QString::fromUtf8(
        CopyrightHolders(strprintf("\xc2\xA9 %u-%u ", 2009, COPYRIGHT_YEAR))
            .c_str());
    QString titleAddText = networkStyle->getTitleAddText();

    QString font = QApplication::font().toString();

    // create a bitmap according to device pixelratio
    QSize splashSize(634 * devicePixelRatio, 320 * devicePixelRatio);
    pixmap = QPixmap(splashSize);

    // change to HiDPI if it makes sense
    pixmap.setDevicePixelRatio(devicePixelRatio);

    QPainter pixPaint(&pixmap);
    pixPaint.setPen(QColor(100, 100, 100));

    // draw a slightly radial gradient
    QRadialGradient gradient(QPoint(0, 0),
                             splashSize.width() / devicePixelRatio);
    gradient.setColorAt(0, Qt::white);
    gradient.setColorAt(1, QColor(247, 247, 247));
    QRect rGradient(QPoint(0, 0), splashSize);
    pixPaint.fillRect(rGradient, gradient);

    // draw the bitcoin icon, expected size of PNG: 1024x1024
    QRect rectIcon(QPoint(-10, -100), QSize(430, 430));

    const QSize requiredSize(1024, 1024);
    QPixmap icon(networkStyle->getAppIcon().pixmap(requiredSize));

    pixPaint.drawPixmap(rectIcon, icon);

    // check font size and drawing with
    pixPaint.setFont(QFont(font, 33 * fontFactor));
    QFontMetrics fm = pixPaint.fontMetrics();
    int titleTextWidth = GUIUtil::TextWidth(fm, titleText);
    if (titleTextWidth > 176) {
        fontFactor = fontFactor * 176 / titleTextWidth;
    }

    pixPaint.setFont(QFont(font, 33 * fontFactor));
    fm = pixPaint.fontMetrics();
    titleTextWidth = GUIUtil::TextWidth(fm, titleText);
    pixPaint.drawText(pixmap.width() / devicePixelRatio - titleTextWidth -
                          paddingRight,
                      paddingTop, titleText);

    pixPaint.setFont(QFont(font, 15 * fontFactor));

    // if the version string is too long, reduce size
    fm = pixPaint.fontMetrics();
    int versionTextWidth = GUIUtil::TextWidth(fm, titleText);
    if (versionTextWidth > titleTextWidth + paddingRight - 10) {
        pixPaint.setFont(QFont(font, 10 * fontFactor));
        titleVersionVSpace -= 5;
    }
    pixPaint.drawText(pixmap.width() / devicePixelRatio - titleTextWidth -
                          paddingRight + 2,
                      paddingTop + titleVersionVSpace, versionText);

    // draw copyright stuff
    {
        pixPaint.setFont(QFont(font, 10 * fontFactor));
        const int x =
            pixmap.width() / devicePixelRatio - titleTextWidth - paddingRight;
        const int y = paddingTop + titleCopyrightVSpace;
        QRect copyrightRect(x, y, pixmap.width() - x - paddingRight,
                            pixmap.height() - y);
        pixPaint.drawText(copyrightRect,
                          Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap,
                          copyrightText);
    }

    // draw additional text if special network
    if (!titleAddText.isEmpty()) {
        QFont boldFont = QFont(font, 10 * fontFactor);
        boldFont.setWeight(QFont::Bold);
        pixPaint.setFont(boldFont);
        fm = pixPaint.fontMetrics();
        int titleAddTextWidth = GUIUtil::TextWidth(fm, titleAddText);
        pixPaint.drawText(pixmap.width() / devicePixelRatio -
                              titleAddTextWidth - 10,
                          15, titleAddText);
    }

    pixPaint.end();

    // Set window title
    setWindowTitle(titleText + " " + titleAddText);

    // Resize window and move to center of desktop, disallow resizing
    QRect r(QPoint(), QSize(pixmap.size().width() / devicePixelRatio,
                            pixmap.size().height() / devicePixelRatio));
    resize(r.size());
    setFixedSize(r.size());
    move(QGuiApplication::primaryScreen()->geometry().center() - r.center());

    installEventFilter(this);
}

SplashScreen::~SplashScreen() {
    if (m_node) {
        unsubscribeFromCoreSignals();
    }
}

void SplashScreen::setNode(interfaces::Node &node) {
    assert(!m_node);
    m_node = &node;
    subscribeToCoreSignals();
    if (m_shutdown) {
        m_node->startShutdown();
    }
}

void SplashScreen::shutdown() {
    m_shutdown = true;
    if (m_node) {
        m_node->startShutdown();
    }
}

bool SplashScreen::eventFilter(QObject *obj, QEvent *ev) {
    if (ev->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(ev);
        if (keyEvent->key() == Qt::Key_Q) {
            shutdown();
        }
    }
    return QObject::eventFilter(obj, ev);
}

void SplashScreen::finish() {
    /* If the window is minimized, hide() will be ignored. */
    /* Make sure we de-minimize the splashscreen window before hiding */
    if (isMinimized()) {
        showNormal();
    }
    hide();
    // No more need for this
    deleteLater();
}

static void InitMessage(SplashScreen *splash, const std::string &message) {
    bool invoked = QMetaObject::invokeMethod(
        splash, "showMessage", Qt::QueuedConnection,
        Q_ARG(QString, QString::fromStdString(message)),
        Q_ARG(int, Qt::AlignBottom | Qt::AlignHCenter),
        Q_ARG(QColor, QColor(55, 55, 55)));
    assert(invoked);
}

static void ShowProgress(SplashScreen *splash, const std::string &title,
                         int nProgress, bool resume_possible) {
    InitMessage(
        splash,
        title + std::string("\n") +
            (resume_possible
                 ? _("(press q to shutdown and continue later)").translated
                 : _("press q to shutdown").translated) +
            strprintf("\n%d", nProgress) + "%");
}
#ifdef ENABLE_WALLET
void SplashScreen::ConnectWallet(std::unique_ptr<interfaces::Wallet> wallet) {
    m_connected_wallet_handlers.emplace_back(wallet->handleShowProgress(
        std::bind(ShowProgress, this, std::placeholders::_1,
                  std::placeholders::_2, false)));
    m_connected_wallets.emplace_back(std::move(wallet));
}
#endif

void SplashScreen::subscribeToCoreSignals() {
    // Connect signals to client
    m_handler_init_message = m_node->handleInitMessage(
        std::bind(InitMessage, this, std::placeholders::_1));
    m_handler_show_progress = m_node->handleShowProgress(
        std::bind(ShowProgress, this, std::placeholders::_1,
                  std::placeholders::_2, std::placeholders::_3));
#ifdef ENABLE_WALLET
    m_handler_load_wallet = m_node->handleLoadWallet(
        [this](std::unique_ptr<interfaces::Wallet> wallet) {
            ConnectWallet(std::move(wallet));
        });
#endif
}

void SplashScreen::unsubscribeFromCoreSignals() {
    // Disconnect signals from client
    m_handler_init_message->disconnect();
    m_handler_show_progress->disconnect();
    for (const auto &handler : m_connected_wallet_handlers) {
        handler->disconnect();
    }
    m_connected_wallet_handlers.clear();
    m_connected_wallets.clear();
}

void SplashScreen::showMessage(const QString &message, int alignment,
                               const QColor &color) {
    curMessage = message;
    curAlignment = alignment;
    curColor = color;
    update();
}

void SplashScreen::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    painter.drawPixmap(0, 0, pixmap);
    QRect r = rect().adjusted(5, 5, -5, -5);
    painter.setPen(curColor);
    painter.drawText(r, curAlignment, curMessage);
}

void SplashScreen::closeEvent(QCloseEvent *event) {
    // allows an "emergency" shutdown during startup
    shutdown();
    event->ignore();
}
<|endoftext|>


<commit_before>//===- lib/Driver/Driver.cpp - Linker Driver Emulator ---------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Driver/Driver.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/InputFiles.h"
#include "lld/Core/Resolver.h"
#include "lld/Core/PassManager.h"
#include "lld/ReaderWriter/Reader.h"
#include "lld/ReaderWriter/Writer.h"

#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"

namespace lld {

/// This is where the link is actually performed.
bool Driver::link(const TargetInfo &targetInfo, raw_ostream &diagnostics) {
  // Honor -mllvm
  if (!targetInfo.llvmOptions().empty()) {
    unsigned numArgs = targetInfo.llvmOptions().size();
    const char **args = new const char*[numArgs + 2];
    args[0] = "lld (LLVM option parsing)";
    for (unsigned i = 0; i != numArgs; ++i)
      args[i + 1] = targetInfo.llvmOptions()[i];
    args[numArgs + 1] = 0;
    llvm::cl::ParseCommandLineOptions(numArgs + 1, args);
  }

  // Read inputs
  InputFiles inputs;
  for (const auto &input : targetInfo.inputFiles()) {
    std::vector<std::unique_ptr<File>> files;
    if (targetInfo.logInputFiles())
      llvm::outs() << input.getPath() << "\n";

    error_code ec = targetInfo.readFile(input.getPath(), files);
    if (ec) {
      diagnostics   << "Failed to read file: " << input.getPath() << ": "
                    << ec.message() << "\n";
      return true;
    }
    inputs.appendFiles(files);
  }

  // Give target a chance to add files.
  targetInfo.addImplicitFiles(inputs);

  // assign an ordinal to each file so sort() can preserve command line order
  inputs.assignFileOrdinals();

  // Do core linking.
  Resolver resolver(targetInfo, inputs);
  if (resolver.resolve()) {
    if (!targetInfo.allowRemainingUndefines())
      return true;
  }
  MutableFile &merged = resolver.resultFile();

  // Run passes on linked atoms.
  PassManager pm;
  targetInfo.addPasses(pm);
  pm.runOnFile(merged);

  // Give linked atoms to Writer to generate output file.
  if (error_code ec = targetInfo.writeFile(merged)) {
    diagnostics << "Failed to write file '" << targetInfo.outputPath()
                << "': " << ec.message() << "\n";
    return true;
  }

  return false;
}

} // namespace

<commit_msg>[Driver] Parallelize reading initial object files.<commit_after>//===- lib/Driver/Driver.cpp - Linker Driver Emulator ---------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Driver/Driver.h"

#include "lld/Core/LLVM.h"
#include "lld/Core/InputFiles.h"
#include "lld/Core/PassManager.h"
#include "lld/Core/Parallel.h"
#include "lld/Core/Resolver.h"
#include "lld/ReaderWriter/Reader.h"
#include "lld/ReaderWriter/Writer.h"

#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"

namespace lld {

/// This is where the link is actually performed.
bool Driver::link(const TargetInfo &targetInfo, raw_ostream &diagnostics) {
  // Honor -mllvm
  if (!targetInfo.llvmOptions().empty()) {
    unsigned numArgs = targetInfo.llvmOptions().size();
    const char **args = new const char*[numArgs + 2];
    args[0] = "lld (LLVM option parsing)";
    for (unsigned i = 0; i != numArgs; ++i)
      args[i + 1] = targetInfo.llvmOptions()[i];
    args[numArgs + 1] = 0;
    llvm::cl::ParseCommandLineOptions(numArgs + 1, args);
  }

  // Read inputs
  std::vector<std::vector<std::unique_ptr<File>>> files(
      targetInfo.inputFiles().size());
  size_t index = 0;
  std::atomic<bool> fail(false);
  TaskGroup tg;
  for (const auto &input : targetInfo.inputFiles()) {
    if (targetInfo.logInputFiles())
      llvm::outs() << input.getPath() << "\n";

    tg.spawn([&, index] {
      if (error_code ec = targetInfo.readFile(input.getPath(), files[index])) {
        diagnostics << "Failed to read file: " << input.getPath()
                    << ": " << ec.message() << "\n";
        fail = true;
        return;
      }
    });
    ++index;
  }
  tg.sync();

  if (fail)
    return true;

  InputFiles inputs;
  for (auto &f : files)
    inputs.appendFiles(f);

  // Give target a chance to add files.
  targetInfo.addImplicitFiles(inputs);

  // assign an ordinal to each file so sort() can preserve command line order
  inputs.assignFileOrdinals();

  // Do core linking.
  Resolver resolver(targetInfo, inputs);
  if (resolver.resolve()) {
    if (!targetInfo.allowRemainingUndefines())
      return true;
  }
  MutableFile &merged = resolver.resultFile();

  // Run passes on linked atoms.
  PassManager pm;
  targetInfo.addPasses(pm);
  pm.runOnFile(merged);

  // Give linked atoms to Writer to generate output file.
  if (error_code ec = targetInfo.writeFile(merged)) {
    diagnostics << "Failed to write file '" << targetInfo.outputPath()
                << "': " << ec.message() << "\n";
    return true;
  }

  return false;
}

} // namespace

<|endoftext|>


<commit_before>/* ozmhelper_main.cpp

Copyright (c) 2014, Nikolaj Schlej. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution.  The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

*/
#include <QCoreApplication>
#include <QString>
#include <QStringList>
#include <iostream>
#include <string.h>
#include <stdio.h>

#include "ozmhelper.h"

QString version = "v0.1";
QString appname = "OZMHelper";

void usageDsdt2Bios()
{
    printf("dsdt2bios command\n"
            " usage:\n"
            "\t%s --dsdt2bios -i AmiBoardInfo.bin -d DSDT.aml -o outputdir\n\n"
            " parameters:\n" \
            "\t-i, --input\t\tInput file (AmiBoardInfo)\n"
            "\t-d, --dsdt\t\tDSDT.aml file\n"
            "\t-o, --out [dir]\t\tOutput directory\n"
            "\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}

void usageFfsConvert()
{
    printf("ffsconvert command\n"
            " usage:\n"
            "\t%s --ffsconvert -o outputdir -i ffsdir\n\n"
            " parameters:\n"
            "\t-i, --input\t\tInput directory\n"
            "\t-o, --out [dir]\t\tOutput directory\n"
            "\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}

void usageOzmCreate()
{
    printf("ozmcreate command\n" \
            " usage:\n"
            "\t%s --ozmcreate -k kextdir -f ffsdir -d DSDT.aml -o outputdir -i BIOS.ROM\n\n"
            " parameters:\n"
            "\t-k, --kext [dir]\t\tKEXT directory\n"
            "\t-f, --ffs [dir]\t\tFFS directory (OZM files)\n"
            "\t-d, --dsdt [file]\t\tDSDT.aml file\n"
            "\t-i, --input\t\tInput file\n"
            "\t-o, --out [dir]\t\tOutput directory\n"
            "\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}

void usageOzmExtract()
{
    printf("ozmextract command\n"
            " usage:\n"
            "\t%s --ozmextract -o outputdir -i OZM.ROM\n\n"
            " parameters:\n"
            "\t-i, --input\t\tInput file\n"
            "\t-o, --out [dir]\t\tOutput directory\n"
            "\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}

void usageDSDTExtract()
{
    printf("dsdtextract command\n"
            " usage:\n"
            "\t%s --dsdtextract -o outputdir -i OZMBIOS_or_BIOS.ROM\n\n"
            " parameters:\n"
            "\t-i, --input\t\tInput file\n"
            "\t-o, --out [dir]\t\tOutput directory\n"
            "\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}

void usageGeneral()
{
    printf("Usage:\n" \
            "\t%s [COMMAND] [PARAMETERS...]\n\n"
            "Available commands:\n"
            "\t--dsdtextract\t\tExtracts DSDT from BIOS\n"
            "\t--ozmextract\t\tExtracts Ozmosis files (ffs) from BIOS\n"
            "\t--ozmcreate\t\tPatches Original BIOS with Ozmosis\n"
            "\t--ffsconvert\t\tConverts kext-directories to FFS\n"
            "\t--dsdt2bios\t\tInjects (bigger) DSDT into AmiBoardInfo\n"
            "\t--help, -h\t\tPrint this\n\n",qPrintable(appname));
}

void versionInfo()
{
    printf("%s - %s\n",qPrintable(appname), qPrintable(version));
}

void usageAll()
{
    usageGeneral();
    usageDSDTExtract();
    usageOzmExtract();
    usageOzmCreate();
    usageFfsConvert();
    usageDsdt2Bios();
}

int main(int argc, char *argv[])
{
    bool help = false;
    bool dsdtextract = false;
    bool ozmextract = false;
    bool ozmcreate = false;
    bool ffsconvert = false;
    bool dsdt2bios = false;
    QString inputpath = "";
    QString output = "";
    QString ffsdir = "";
    QString kextdir = "";
    QString dsdtfile = "";

    QCoreApplication a(argc, argv);
    a.setOrganizationName("CodeRush");
    a.setOrganizationDomain("coderush.me");
    a.setApplicationName("OZMHelper");

    OZMHelper w;
    UINT8 result = ERR_SUCCESS;

    if (argc == 1) {
        usageGeneral();
        printf("ERROR: No options supplied!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    //
    // Parse command line
    //
    argc --;
    argv ++;

    if ((strcasecmp(argv[0], "-h") == 0) || (strcasecmp(argv[0], "--help") == 0)) {
        usageAll();
        return ERR_SUCCESS;
    }

    if (strcasecmp(argv[0], "--version") == 0) {
        versionInfo();
        return ERR_SUCCESS;
    }

    while (argc > 0) {

        if (strcasecmp(argv[0], "--dsdtextract") == 0) {
            dsdtextract = true;
            argc --;
            argv ++;
            continue;
        }

        if (strcasecmp(argv[0], "--ozmextract") == 0) {
            ozmextract = true;
            argc --;
            argv ++;
            continue;
        }

        if (strcasecmp(argv[0], "--ozmcreate") == 0) {
            ozmcreate = true;
            argc --;
            argv ++;
            continue;
        }

        if (strcasecmp(argv[0], "--ffsconvert") == 0) {
            ffsconvert = true;
            argc --;
            argv ++;
            continue;
        }

        if (strcasecmp(argv[0], "--dsdt2bios") == 0) {
            ffsconvert = true;
            argc --;
            argv ++;
            continue;
        }

        if ((strcasecmp(argv[0], "-f") == 0) || (strcasecmp(argv[0], "--ffs") == 0)) {
            if (argv[1] == NULL || argv[1][0] == '-') {
                printf("Invalid option value\n"
                       "Input FFS directory is missing for -f option\n");
                goto fail;
            }
            ffsdir = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        }

        if ((strcasecmp(argv[0], "-k") == 0) || (strcasecmp(argv[0], "--kext") == 0)) {
            if (argv[1] == NULL || argv[1][0] == '-') {
                printf("Invalid option value\n"
                       "Input KEXT directory is missing for -k option\n");
                goto fail;
            }
            kextdir = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        }

        if ((strcasecmp(argv[0], "-d") == 0) || (strcasecmp(argv[0], "--dsdt") == 0)) {
            if (argv[1] == NULL || argv[1][0] == '-') {
                printf("Invalid option value\n"
                       "Input DSDT.aml file is missing for -d option\n");
                goto fail;
            }
            dsdtfile = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        }

        if ((strcasecmp(argv[0], "-i") == 0) || (strcasecmp(argv[0], "--input") == 0)) {
            if (argv[1] == NULL || argv[1][0] == '-') {
                printf("Invalid option value\n"
                       "Input file/dir is missing for -i option\n");
                goto fail;
            }
            inputpath = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        }

        if ((strcasecmp(argv[0], "-o") == 0) || (strcasecmp(argv[0], "--out") == 0)) {
            if (argv[1] == NULL || argv[1][0] == '-') {
                printf("Invalid option value\n"
                       "Output directory is missing for -o option\n");
                goto fail;
            }
            output = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        }

        if ((strcasecmp(argv[0], "-h") == 0) || (strcasecmp(argv[0], "--help") == 0)) {
            help = true;
            argc --;
            argv ++;
            continue;
        }

        printf("Unknown option: %s\n", argv[0]);

fail:
        printf("Exiting!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    int cmds = dsdtextract + ozmextract + ozmcreate + ffsconvert;

    if (help) {
        if (cmds > 1)
            usageAll();
        else if (dsdtextract)
            usageDSDTExtract();
        else if (ozmextract)
            usageOzmExtract();
        else if (ozmcreate)
            usageOzmCreate();
        else if (ffsconvert)
            usageFfsConvert();
        else if (dsdt2bios)
            usageDsdt2Bios();
        else
            usageAll();

        return ERR_SUCCESS;
    }

    if (cmds == 0) {
        printf("ERROR: No command supplied!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }
    else if (cmds > 1) {
        printf("ERROR: More than one command supplied, only one is allowed!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    if (inputpath.isEmpty()) {
        printf("ERROR: No input file/dir specified!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    if (output.isEmpty()) {
        printf("ERROR: No output dir specified!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    if(ozmcreate && kextdir.isEmpty())
        printf("Warning: No KEXT-dir given! Injecting only Ozmosis files!\n");

    if (ozmcreate && (ffsdir.isEmpty()||dsdtfile.isEmpty())) {
        printf("ERROR: No FFS directory or DSDT.aml file supplied!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    if (dsdt2bios && dsdtfile.isEmpty()) {
        printf("ERROR: No DSDT.aml file supplied!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    if (dsdtextract)
        result = w.DSDTExtract(inputpath, output);
    else if (ozmextract)
        result = w.OZMExtract(inputpath, output);
    else if (ozmcreate)
        result = w.OZMCreate(inputpath, output, ffsdir, kextdir, dsdtfile);
    else if (ffsconvert)
        result = w.FFSConvert(inputpath, output);
    else if (dsdt2bios)
        result = w.DSDT2Bios(inputpath, dsdtfile, output);

    printf("Program exited %s!\n", result ? "with errors" : "successfully");
    if(result)
        printf("Status: %i\n", result);

    return result;
}
<commit_msg>oops.. again -_-<commit_after>/* ozmhelper_main.cpp

Copyright (c) 2014, Nikolaj Schlej. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution.  The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

*/
#include <QCoreApplication>
#include <QString>
#include <QStringList>
#include <iostream>
#include <string.h>
#include <stdio.h>

#include "ozmhelper.h"

QString version = "v0.1";
QString appname = "OZMHelper";

void usageDsdt2Bios()
{
    printf("dsdt2bios command\n"
            " usage:\n"
            "\t%s --dsdt2bios -i AmiBoardInfo.bin -d DSDT.aml -o outputdir\n\n"
            " parameters:\n" \
            "\t-i, --input\t\tInput file (AmiBoardInfo)\n"
            "\t-d, --dsdt\t\tDSDT.aml file\n"
            "\t-o, --out [dir]\t\tOutput directory\n"
            "\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}

void usageFfsConvert()
{
    printf("ffsconvert command\n"
            " usage:\n"
            "\t%s --ffsconvert -o outputdir -i ffsdir\n\n"
            " parameters:\n"
            "\t-i, --input\t\tInput directory\n"
            "\t-o, --out [dir]\t\tOutput directory\n"
            "\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}

void usageOzmCreate()
{
    printf("ozmcreate command\n" \
            " usage:\n"
            "\t%s --ozmcreate -k kextdir -f ffsdir -d DSDT.aml -o outputdir -i BIOS.ROM\n\n"
            " parameters:\n"
            "\t-k, --kext [dir]\t\tKEXT directory\n"
            "\t-f, --ffs [dir]\t\tFFS directory (OZM files)\n"
            "\t-d, --dsdt [file]\t\tDSDT.aml file\n"
            "\t-i, --input\t\tInput file\n"
            "\t-o, --out [dir]\t\tOutput directory\n"
            "\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}

void usageOzmExtract()
{
    printf("ozmextract command\n"
            " usage:\n"
            "\t%s --ozmextract -o outputdir -i OZM.ROM\n\n"
            " parameters:\n"
            "\t-i, --input\t\tInput file\n"
            "\t-o, --out [dir]\t\tOutput directory\n"
            "\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}

void usageDSDTExtract()
{
    printf("dsdtextract command\n"
            " usage:\n"
            "\t%s --dsdtextract -o outputdir -i OZMBIOS_or_BIOS.ROM\n\n"
            " parameters:\n"
            "\t-i, --input\t\tInput file\n"
            "\t-o, --out [dir]\t\tOutput directory\n"
            "\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}

void usageGeneral()
{
    printf("Usage:\n" \
            "\t%s [COMMAND] [PARAMETERS...]\n\n"
            "Available commands:\n"
            "\t--dsdtextract\t\tExtracts DSDT from BIOS\n"
            "\t--ozmextract\t\tExtracts Ozmosis files (ffs) from BIOS\n"
            "\t--ozmcreate\t\tPatches Original BIOS with Ozmosis\n"
            "\t--ffsconvert\t\tConverts kext-directories to FFS\n"
            "\t--dsdt2bios\t\tInjects (bigger) DSDT into AmiBoardInfo\n"
            "\t--help, -h\t\tPrint this\n\n",qPrintable(appname));
}

void versionInfo()
{
    printf("%s - %s\n",qPrintable(appname), qPrintable(version));
}

void usageAll()
{
    usageGeneral();
    usageDSDTExtract();
    usageOzmExtract();
    usageOzmCreate();
    usageFfsConvert();
    usageDsdt2Bios();
}

int main(int argc, char *argv[])
{
    bool help = false;
    bool dsdtextract = false;
    bool ozmextract = false;
    bool ozmcreate = false;
    bool ffsconvert = false;
    bool dsdt2bios = false;
    QString inputpath = "";
    QString output = "";
    QString ffsdir = "";
    QString kextdir = "";
    QString dsdtfile = "";

    QCoreApplication a(argc, argv);
    a.setOrganizationName("CodeRush");
    a.setOrganizationDomain("coderush.me");
    a.setApplicationName("OZMHelper");

    OZMHelper w;
    UINT8 result = ERR_SUCCESS;

    if (argc == 1) {
        usageGeneral();
        printf("ERROR: No options supplied!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    //
    // Parse command line
    //
    argc --;
    argv ++;

    if ((strcasecmp(argv[0], "-h") == 0) || (strcasecmp(argv[0], "--help") == 0)) {
        usageAll();
        return ERR_SUCCESS;
    }

    if (strcasecmp(argv[0], "--version") == 0) {
        versionInfo();
        return ERR_SUCCESS;
    }

    while (argc > 0) {

        if (strcasecmp(argv[0], "--dsdtextract") == 0) {
            dsdtextract = true;
            argc --;
            argv ++;
            continue;
        }

        if (strcasecmp(argv[0], "--ozmextract") == 0) {
            ozmextract = true;
            argc --;
            argv ++;
            continue;
        }

        if (strcasecmp(argv[0], "--ozmcreate") == 0) {
            ozmcreate = true;
            argc --;
            argv ++;
            continue;
        }

        if (strcasecmp(argv[0], "--ffsconvert") == 0) {
            ffsconvert = true;
            argc --;
            argv ++;
            continue;
        }

        if (strcasecmp(argv[0], "--dsdt2bios") == 0) {
            dsdt2bios = true;
            argc --;
            argv ++;
            continue;
        }

        if ((strcasecmp(argv[0], "-f") == 0) || (strcasecmp(argv[0], "--ffs") == 0)) {
            if (argv[1] == NULL || argv[1][0] == '-') {
                printf("Invalid option value\n"
                       "Input FFS directory is missing for -f option\n");
                goto fail;
            }
            ffsdir = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        }

        if ((strcasecmp(argv[0], "-k") == 0) || (strcasecmp(argv[0], "--kext") == 0)) {
            if (argv[1] == NULL || argv[1][0] == '-') {
                printf("Invalid option value\n"
                       "Input KEXT directory is missing for -k option\n");
                goto fail;
            }
            kextdir = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        }

        if ((strcasecmp(argv[0], "-d") == 0) || (strcasecmp(argv[0], "--dsdt") == 0)) {
            if (argv[1] == NULL || argv[1][0] == '-') {
                printf("Invalid option value\n"
                       "Input DSDT.aml file is missing for -d option\n");
                goto fail;
            }
            dsdtfile = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        }

        if ((strcasecmp(argv[0], "-i") == 0) || (strcasecmp(argv[0], "--input") == 0)) {
            if (argv[1] == NULL || argv[1][0] == '-') {
                printf("Invalid option value\n"
                       "Input file/dir is missing for -i option\n");
                goto fail;
            }
            inputpath = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        }

        if ((strcasecmp(argv[0], "-o") == 0) || (strcasecmp(argv[0], "--out") == 0)) {
            if (argv[1] == NULL || argv[1][0] == '-') {
                printf("Invalid option value\n"
                       "Output directory is missing for -o option\n");
                goto fail;
            }
            output = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        }

        if ((strcasecmp(argv[0], "-h") == 0) || (strcasecmp(argv[0], "--help") == 0)) {
            help = true;
            argc --;
            argv ++;
            continue;
        }

        printf("Unknown option: %s\n", argv[0]);

fail:
        printf("Exiting!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    int cmds = dsdtextract + ozmextract + ozmcreate + ffsconvert;

    if (help) {
        if (cmds > 1)
            usageAll();
        else if (dsdtextract)
            usageDSDTExtract();
        else if (ozmextract)
            usageOzmExtract();
        else if (ozmcreate)
            usageOzmCreate();
        else if (ffsconvert)
            usageFfsConvert();
        else if (dsdt2bios)
            usageDsdt2Bios();
        else
            usageAll();

        return ERR_SUCCESS;
    }

    if (cmds == 0) {
        printf("ERROR: No command supplied!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }
    else if (cmds > 1) {
        printf("ERROR: More than one command supplied, only one is allowed!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    if (inputpath.isEmpty()) {
        printf("ERROR: No input file/dir specified!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    if (output.isEmpty()) {
        printf("ERROR: No output dir specified!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    if(ozmcreate && kextdir.isEmpty())
        printf("Warning: No KEXT-dir given! Injecting only Ozmosis files!\n");

    if (ozmcreate && (ffsdir.isEmpty()||dsdtfile.isEmpty())) {
        printf("ERROR: No FFS directory or DSDT.aml file supplied!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    if (dsdt2bios && dsdtfile.isEmpty()) {
        printf("ERROR: No DSDT.aml file supplied!\n");
        return ERR_GENERIC_CALL_NOT_SUPPORTED;
    }

    if (dsdtextract)
        result = w.DSDTExtract(inputpath, output);
    else if (ozmextract)
        result = w.OZMExtract(inputpath, output);
    else if (ozmcreate)
        result = w.OZMCreate(inputpath, output, ffsdir, kextdir, dsdtfile);
    else if (ffsconvert)
        result = w.FFSConvert(inputpath, output);
    else if (dsdt2bios)
        result = w.DSDT2Bios(inputpath, dsdtfile, output);

    printf("Program exited %s!\n", result ? "with errors" : "successfully");
    if(result)
        printf("Status: %i\n", result);

    return result;
}
<|endoftext|>


<commit_before>/*************************************
** Tsunagari Tile Engine            **
** main.cpp                         **
** Copyright 2016-2017 Paul Merrill **
*************************************/

// **********
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// **********

#include <fcntl.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <algorithm>
#include <mutex>
#include <unordered_set>

#include "os/os.h"
#include "pack/pack-file.h"
#include "pack/pool.h"
#include "pack/walker.h"
#include "pack/ui.h"
#include "util/move.h"
#include "util/optional.h"
#include "util/unique.h"

const char* exe = nullptr;

static void usage() {
    fprintf(stderr, "usage: %s create <output-archive> [input-file]...\n", exe);
    fprintf(stderr, "       %s list <input-archive>\n", exe);
    fprintf(stderr, "       %s extract <input-archive>\n", exe);
}

struct CreateArchiveContext {
    Unique<PackWriter> pack;
    std::mutex packMutex;
};

static void slurp(const std::string& path, uint64_t* size, void** data) {
    *size = getFileSize(path);
    *data = new char*[*size];
    FILE* f = fopen(path.c_str(), "r");
    fread(*data, *size, 1, f);
    fclose(f);
}

static void addFile(CreateArchiveContext& ctx, std::string path) {
    uiShowAddingFile(path);

    uint64_t size;
    void* data;
    slurp(path, &size, &data);

    std::lock_guard<std::mutex> guard(ctx.packMutex);
    ctx.pack->addBlob(move_(path), size, data);
}

template<typename Iterator>
static bool createArchive(const std::string& archivePath,
                          Iterator inputsBegin,
                          Iterator inputsEnd) {
    CreateArchiveContext ctx;
    ctx.pack = PackWriter::make();

    vector<std::string> paths;
    for (; inputsBegin != inputsEnd; ++inputsBegin) {
        paths.emplace_back(*inputsBegin);
    }

    walk(move_(paths), [&](std::string path) {
        addFile(ctx, move_(path));
    });

    uiShowWritingArchive(archivePath);

    return ctx.pack->writeToFile(archivePath);
}

static bool listArchive(const std::string& archivePath) {
    Unique<PackReader> pack = PackReader::fromFile(archivePath);

    if (pack) {
        for (PackReader::BlobIndex i = 0; i < pack->size(); i++) {
            std::string blobPath = pack->getBlobPath(i);
            uint64_t blobSize = pack->getBlobSize(i);

            uiShowListingEntry(blobPath, blobSize);
        }
        return true;
    } else {
        fprintf(stderr, "%s: %s: not found\n", exe, archivePath.c_str());
        return false;
    }
}

static Optional<std::string> getParentPath(const std::string& path) {
    auto sep = path.find_last_of('/');
    if (sep == path.npos) {
        return Optional<std::string>();
    } else {
        return Optional<std::string>(path.substr(0, sep));
    }
}

static void createDirs(const std::string& path) {
    Optional<std::string> parentPath = getParentPath(path);
    if (parentPath) {
        // Make sure parentPath's parent exists.
        createDirs(*parentPath);

        makeDirectory(*parentPath);
    }
}

static void putFile(const std::string& path, uint64_t size, void* data) {
    createDirs(path);

    int fd = open(path.c_str(), O_WRONLY | O_NONBLOCK | O_CREAT | O_TRUNC | O_CLOEXEC, 0777);
    write(fd, data, size);
}

static bool extractArchive(const std::string& archivePath) {
    Unique<PackReader> pack = PackReader::fromFile(archivePath);

    if (pack) {
        vector<PackReader::BlobIndex> blobIndicies;
        for (PackReader::BlobIndex i = 0; i < pack->size(); i++) {
            blobIndicies.push_back(i);
        }

        vector<void*> blobDatas = pack->getBlobDatas(blobIndicies);

        Unique<Pool> pool(Pool::makePool("extract", 1));

        for (PackReader::BlobIndex i = 0; i < pack->size(); i++) {
            std::string blobPath = pack->getBlobPath(i);
            uint64_t blobSize = pack->getBlobSize(i);
            void* blobData = blobDatas[i];

            pool->schedule([=] {
                uiShowExtractingFile(blobPath, blobSize);

                putFile(blobPath, blobSize, blobData);
            });
        }

        return true;
    } else {
        fprintf(stderr, "%s: %s: not found\n", exe, archivePath.c_str());
        return false;
    }
}

int main(int argc, char* argv[]) {
    exe = strrchr(argv[0], dirSeparator);
    if (exe) {
        exe += 1;
    } else {
        exe = argv[0];
    }

    if (argc == 1) {
        usage();
        return 0;
    }
    if (argc == 2) {
        usage();
        return 1;
    }

    std::string command = argv[1];
    vector<std::string> args;

    for (int i = 2; i < argc; i++) {
        args.push_back(argv[i]);
    }

    int exitCode;

    if (command == "create") {
        return createArchive(args[0], args.begin() + 1, args.end()) ? 0 : 1;
    } else if (command == "list") {
        if (argc != 3) {
            usage();
            return 1;
        }

        exitCode = listArchive(args[0]) ? 0 : 1;
    } else if (command == "extract") {
        if (argc != 3) {
            usage();
            return 1;
        }

        exitCode = extractArchive(args[0]) ? 0 : 1;
    } else {
        usage();
        return 1;
    }

    return exitCode;
}
<commit_msg>pack: Buffer output on 'list' command<commit_after>/*************************************
** Tsunagari Tile Engine            **
** main.cpp                         **
** Copyright 2016-2017 Paul Merrill **
*************************************/

// **********
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// **********

#include <fcntl.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <algorithm>
#include <mutex>
#include <unordered_set>

#include "os/os.h"
#include "pack/pack-file.h"
#include "pack/pool.h"
#include "pack/walker.h"
#include "pack/ui.h"
#include "util/move.h"
#include "util/optional.h"
#include "util/unique.h"

const char* exe = nullptr;

static void usage() {
    fprintf(stderr, "usage: %s create <output-archive> [input-file]...\n", exe);
    fprintf(stderr, "       %s list <input-archive>\n", exe);
    fprintf(stderr, "       %s extract <input-archive>\n", exe);
}

struct CreateArchiveContext {
    Unique<PackWriter> pack;
    std::mutex packMutex;
};

static void slurp(const std::string& path, uint64_t* size, void** data) {
    *size = getFileSize(path);
    *data = new char*[*size];
    FILE* f = fopen(path.c_str(), "r");
    fread(*data, *size, 1, f);
    fclose(f);
}

static void addFile(CreateArchiveContext& ctx, std::string path) {
    uiShowAddingFile(path);

    uint64_t size;
    void* data;
    slurp(path, &size, &data);

    std::lock_guard<std::mutex> guard(ctx.packMutex);
    ctx.pack->addBlob(move_(path), size, data);
}

template<typename Iterator>
static bool createArchive(const std::string& archivePath,
                          Iterator inputsBegin,
                          Iterator inputsEnd) {
    CreateArchiveContext ctx;
    ctx.pack = PackWriter::make();

    vector<std::string> paths;
    for (; inputsBegin != inputsEnd; ++inputsBegin) {
        paths.emplace_back(*inputsBegin);
    }

    walk(move_(paths), [&](std::string path) {
        addFile(ctx, move_(path));
    });

    uiShowWritingArchive(archivePath);

    return ctx.pack->writeToFile(archivePath);
}

static bool listArchive(const std::string& archivePath) {
    Unique<PackReader> pack = PackReader::fromFile(archivePath);

    if (pack) {
        std::string output;

        for (PackReader::BlobIndex i = 0; i < pack->size(); i++) {
            std::string blobPath = pack->getBlobPath(i);
            uint64_t blobSize = pack->getBlobSize(i);

            output.append(blobPath);
            output.append(": ");
            output.append(std::to_string(blobSize));
            output.append(" bytes\n");
        }
        printf("%s", output.c_str());
        return true;
    } else {
        fprintf(stderr, "%s: %s: not found\n", exe, archivePath.c_str());
        return false;
    }
}

static Optional<std::string> getParentPath(const std::string& path) {
    auto sep = path.find_last_of('/');
    if (sep == path.npos) {
        return Optional<std::string>();
    } else {
        return Optional<std::string>(path.substr(0, sep));
    }
}

static void createDirs(const std::string& path) {
    Optional<std::string> parentPath = getParentPath(path);
    if (parentPath) {
        // Make sure parentPath's parent exists.
        createDirs(*parentPath);

        makeDirectory(*parentPath);
    }
}

static void putFile(const std::string& path, uint64_t size, void* data) {
    createDirs(path);

    int fd = open(path.c_str(), O_WRONLY | O_NONBLOCK | O_CREAT | O_TRUNC | O_CLOEXEC, 0777);
    write(fd, data, size);
}

static bool extractArchive(const std::string& archivePath) {
    Unique<PackReader> pack = PackReader::fromFile(archivePath);

    if (pack) {
        vector<PackReader::BlobIndex> blobIndicies;
        for (PackReader::BlobIndex i = 0; i < pack->size(); i++) {
            blobIndicies.push_back(i);
        }

        vector<void*> blobDatas = pack->getBlobDatas(blobIndicies);

        Unique<Pool> pool(Pool::makePool("extract", 1));

        for (PackReader::BlobIndex i = 0; i < pack->size(); i++) {
            std::string blobPath = pack->getBlobPath(i);
            uint64_t blobSize = pack->getBlobSize(i);
            void* blobData = blobDatas[i];

            pool->schedule([=] {
                uiShowExtractingFile(blobPath, blobSize);

                putFile(blobPath, blobSize, blobData);
            });
        }

        return true;
    } else {
        fprintf(stderr, "%s: %s: not found\n", exe, archivePath.c_str());
        return false;
    }
}

int main(int argc, char* argv[]) {
    exe = strrchr(argv[0], dirSeparator);
    if (exe) {
        exe += 1;
    } else {
        exe = argv[0];
    }

    if (argc == 1) {
        usage();
        return 0;
    }
    if (argc == 2) {
        usage();
        return 1;
    }

    std::string command = argv[1];
    vector<std::string> args;

    for (int i = 2; i < argc; i++) {
        args.push_back(argv[i]);
    }

    int exitCode;

    if (command == "create") {
        return createArchive(args[0], args.begin() + 1, args.end()) ? 0 : 1;
    } else if (command == "list") {
        if (argc != 3) {
            usage();
            return 1;
        }

        exitCode = listArchive(args[0]) ? 0 : 1;
    } else if (command == "extract") {
        if (argc != 3) {
            usage();
            return 1;
        }

        exitCode = extractArchive(args[0]) ? 0 : 1;
    } else {
        usage();
        return 1;
    }

    return exitCode;
}
<|endoftext|>