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

#include "qt/pivx/receivewidget.h"
#include "qt/pivx/forms/ui_receivewidget.h"
#include "qt/pivx/requestdialog.h"
#include "qt/pivx/addnewcontactdialog.h"
#include "qt/pivx/qtutils.h"
#include "qt/pivx/myaddressrow.h"
#include "qt/pivx/furlistrow.h"
#include "qt/pivx/addressholder.h"
#include "walletmodel.h"
#include "guiutil.h"
#include "pairresult.h"

#include <QModelIndex>
#include <QColor>
#include <QDateTime>

#define DECORATION_SIZE 70
#define NUM_ITEMS 3

ReceiveWidget::ReceiveWidget(PIVXGUI* parent) :
    PWidget(parent),
    ui(new Ui::ReceiveWidget)
{
    ui->setupUi(this);
    this->setStyleSheet(parent->styleSheet());

    delegate = new FurAbstractListItemDelegate(
                DECORATION_SIZE,
                new AddressHolder(isLightTheme()),
                this
                );

    // Containers
    setCssProperty(ui->left, "container");
    ui->left->setContentsMargins(20,20,20,20);
    setCssProperty(ui->right, "container-right");
    ui->right->setContentsMargins(0,9,0,0);

    // Title
    setCssTitleScreen(ui->labelTitle);
    setCssSubtitleScreen(ui->labelSubtitle1);

    // Address
    setCssProperty(ui->labelAddress, "label-address-box");

    /* Button Group */
    setCssProperty(ui->pushLeft, "btn-check-left");
    setCssProperty(ui->pushRight, "btn-check-right");
    setCssSubtitleScreen(ui->labelSubtitle2);
    ui->labelSubtitle2->setContentsMargins(0,2,4,0);

    setCssSubtitleScreen(ui->labelDate);
    setCssSubtitleScreen(ui->labelLabel);

    // Options
    ui->btnMyAddresses->setTitleClassAndText("btn-title-grey", tr("My Addresses"));
    ui->btnMyAddresses->setSubTitleClassAndText("text-subtitle", tr("List your own addresses"));
    ui->btnMyAddresses->layout()->setMargin(0);
    ui->btnMyAddresses->setRightIconClass("ic-arrow");

    ui->btnRequest->setTitleClassAndText("btn-title-grey", tr("Create Request"));
    ui->btnRequest->setSubTitleClassAndText("text-subtitle", tr("Request payment with a fixed amount"));
    ui->btnRequest->layout()->setMargin(0);

    ui->pushButtonLabel->setLayoutDirection(Qt::RightToLeft);
    setCssProperty(ui->pushButtonLabel, "btn-secundary-label");

    ui->pushButtonNewAddress->setLayoutDirection(Qt::RightToLeft);
    setCssProperty(ui->pushButtonNewAddress, "btn-secundary-new-address");

    ui->pushButtonCopy->setLayoutDirection(Qt::RightToLeft);
    setCssProperty(ui->pushButtonCopy, "btn-secundary-copy");

    // List Addresses
    setCssProperty(ui->listViewAddress, "container");
    ui->listViewAddress->setItemDelegate(delegate);
    ui->listViewAddress->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
    ui->listViewAddress->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
    ui->listViewAddress->setAttribute(Qt::WA_MacShowFocusRect, false);
    ui->listViewAddress->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->listViewAddress->setUniformItemSizes(true);

    spacer = new QSpacerItem(40, 20, QSizePolicy::Maximum, QSizePolicy::Expanding);
    ui->btnMyAddresses->setChecked(true);
    ui->container_right->addItem(spacer);
    ui->listViewAddress->setVisible(false);

    // Sort Controls
    SortEdit* lineEdit = new SortEdit(ui->comboBoxSort);
    connect(lineEdit, &SortEdit::Mouse_Pressed, [this](){ui->comboBoxSort->showPopup();});
    connect(ui->comboBoxSort, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ReceiveWidget::onSortChanged);
    SortEdit* lineEditOrder = new SortEdit(ui->comboBoxSortOrder);
    connect(lineEditOrder, &SortEdit::Mouse_Pressed, [this](){ui->comboBoxSortOrder->showPopup();});
    connect(ui->comboBoxSortOrder, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ReceiveWidget::onSortOrderChanged);
    fillAddressSortControls(lineEdit, lineEditOrder, ui->comboBoxSort, ui->comboBoxSortOrder);
    ui->sortWidget->setVisible(false);

    // Connect
    connect(ui->pushButtonLabel, &QPushButton::clicked, this, &ReceiveWidget::onLabelClicked);
    connect(ui->pushButtonCopy, &QPushButton::clicked, this, &ReceiveWidget::onCopyClicked);
    connect(ui->pushButtonNewAddress, &QPushButton::clicked, this, &ReceiveWidget::onNewAddressClicked);
    connect(ui->listViewAddress, &QListView::clicked, this, &ReceiveWidget::handleAddressClicked);
    connect(ui->btnRequest, &OptionButton::clicked, this, &ReceiveWidget::onRequestClicked);
    connect(ui->btnMyAddresses, &OptionButton::clicked, this, &ReceiveWidget::onMyAddressesClicked);

    ui->pushLeft->setChecked(true);
    connect(ui->pushLeft, &QPushButton::clicked, [this](){onTransparentSelected(true);});
    connect(ui->pushRight,  &QPushButton::clicked, [this](){onTransparentSelected(false);});
}

void ReceiveWidget::loadWalletModel()
{
    if (walletModel) {
        this->addressTableModel = walletModel->getAddressTableModel();
        this->filter = new AddressFilterProxyModel(AddressTableModel::Receive, this);
        this->filter->setSourceModel(addressTableModel);
        this->filter->sort(sortType, sortOrder);
        ui->listViewAddress->setModel(this->filter);
        ui->listViewAddress->setModelColumn(AddressTableModel::Address);

        if (!info) info = new SendCoinsRecipient();
        refreshView();

        // data change
        connect(this->addressTableModel, &AddressTableModel::dataChanged, [this](const QModelIndex& tl, const QModelIndex& br){ refreshView(tl, br); });
    }
}

void ReceiveWidget::refreshView(const QModelIndex& tl, const QModelIndex& br)
{
    const QModelIndex& index = tl.sibling(tl.row(), AddressTableModel::Address);
    return refreshView(index.data(Qt::DisplayRole).toString());
}

void ReceiveWidget::refreshView(QString refreshAddress)
{
    try {
        QString latestAddress = (refreshAddress.isEmpty()) ? this->addressTableModel->getAddressToShow(shieldedMode) : refreshAddress;

        if (latestAddress.isEmpty()) {
            // Check for generation errors
            ui->labelQrImg->setText(tr("No available address, try unlocking the wallet"));
            inform(tr("Error generating address"));
            return;
        }

        QString addressToShow = latestAddress;
        int64_t time = walletModel->getKeyCreationTime(latestAddress.toStdString());
        if (shieldedMode) {
            addressToShow = addressToShow.left(20) + "..." + addressToShow.right(19);
        }

        ui->labelAddress->setText(addressToShow);
        ui->labelDate->setText(GUIUtil::dateTimeStr(QDateTime::fromTime_t(static_cast<uint>(time))));
        updateQr(latestAddress);
        updateLabel();
    } catch (const std::runtime_error& error) {
        ui->labelQrImg->setText(tr("No available address, try unlocking the wallet"));
        inform(tr("Error generating address"));
    }
}

void ReceiveWidget::updateLabel()
{
    if (!info->address.isEmpty()) {
        // Check if address label exists
        QString label = addressTableModel->labelForAddress(info->address);
        if (!label.isEmpty()) {
            ui->labelLabel->setVisible(true);
            ui->labelLabel->setText(label);
            ui->pushButtonLabel->setText(tr("Edit Label"));
        } else {
            ui->labelLabel->setVisible(false);
        }
    }
}

void ReceiveWidget::updateQr(QString& address)
{
    info->address = address;
    QString uri = GUIUtil::formatBitcoinURI(*info);
    ui->labelQrImg->setText("");

    QString error;
    QColor qrColor("#382d4d");
    QPixmap pixmap = encodeToQr(uri, error, qrColor);
    if (!pixmap.isNull()) {
        qrImage = &pixmap;
        ui->labelQrImg->setPixmap(qrImage->scaled(ui->labelQrImg->width(), ui->labelQrImg->height()));
    } else {
        ui->labelQrImg->setText(!error.isEmpty() ? error : "Error encoding address");
    }
}

void ReceiveWidget::handleAddressClicked(const QModelIndex &index)
{
    QModelIndex rIndex = filter->mapToSource(index);
    refreshView(rIndex.data(Qt::DisplayRole).toString());
}

void ReceiveWidget::onLabelClicked()
{
    if (walletModel && !isShowingDialog) {
        isShowingDialog = true;
        showHideOp(true);
        AddNewContactDialog *dialog = new AddNewContactDialog(window);
        dialog->setTexts(tr("Edit Address Label"));
        dialog->setData(info->address, addressTableModel->labelForAddress(info->address));
        if (openDialogWithOpaqueBackgroundY(dialog, window, 3.5, 6)) {
            QString label = dialog->getLabel();
            const CWDestination address = Standard::DecodeDestination(info->address.toUtf8().constData());
            if (!label.isEmpty() && walletModel->updateAddressBookLabels(
                    address,
                    label.toUtf8().constData(),
                    AddressBook::AddressBookPurpose::RECEIVE
            )
                    ) {
                // update label status (icon color)
                updateLabel();
                inform(tr("Address label saved"));
            } else {
                inform(tr("Error storing address label"));
            }
        }
        isShowingDialog = false;
    }
}

void ReceiveWidget::onNewAddressClicked()
{
    try {
        WalletModel::UnlockContext ctx(walletModel->requestUnlock());
        if (!ctx.isValid()) {
            // Unlock wallet was cancelled
            inform(tr("Cannot create new address, wallet locked"));
            return;
        }

        QString strAddress;
        PairResult r(false);
        if (!shieldedMode) {
            Destination address;
            r = walletModel->getNewAddress(address, "");
            strAddress = QString::fromStdString(address.ToString());
        } else {
            r = walletModel->getNewShieldedAddress(strAddress, "");
        }

        // Check validity
        if (!r.result) {
            inform(r.status->c_str());
            return;
        }

        refreshView(strAddress);
        inform(tr("New address created"));
    } catch (const std::runtime_error& error) {
        // Error generating address
        inform("Error generating address");
    }
}

void ReceiveWidget::onCopyClicked()
{
    GUIUtil::setClipboard(info->address);
    inform(tr("Address copied"));
}

void ReceiveWidget::onRequestClicked()
{
    showAddressGenerationDialog(true);
}

void ReceiveWidget::showAddressGenerationDialog(bool isPaymentRequest)
{
    if (walletModel && !isShowingDialog) {
        WalletModel::UnlockContext ctx(walletModel->requestUnlock());
        if (!ctx.isValid()) {
            // Unlock wallet was cancelled
            inform(tr("Cannot perform operation, wallet locked"));
            return;
        }
        isShowingDialog = true;
        showHideOp(true);
        RequestDialog *dialog = new RequestDialog(window);
        dialog->setWalletModel(walletModel);
        dialog->setPaymentRequest(isPaymentRequest);
        openDialogWithOpaqueBackgroundY(dialog, window, 3.5, 12);
        if (dialog->res == 1) {
            inform(tr("URI copied to clipboard"));
        } else if (dialog->res == 2) {
            inform(tr("Address copied to clipboard"));
        }
        dialog->deleteLater();
        isShowingDialog = false;
    }
}

void ReceiveWidget::onMyAddressesClicked()
{
    bool isVisible = ui->listViewAddress->isVisible();
    if (!isVisible) {
        ui->btnMyAddresses->setRightIconClass("btn-dropdown", true);
        ui->listViewAddress->setVisible(true);
        ui->sortWidget->setVisible(true);
        ui->container_right->removeItem(spacer);
        ui->listViewAddress->update();
    } else {
        ui->btnMyAddresses->setRightIconClass("ic-arrow", true);
        ui->container_right->addItem(spacer);
        ui->listViewAddress->setVisible(false);
        ui->sortWidget->setVisible(false);
    }
}

void ReceiveWidget::onSortChanged(int idx)
{
    sortType = (AddressTableModel::ColumnIndex) ui->comboBoxSort->itemData(idx).toInt();
    sortAddresses();
}

void ReceiveWidget::onSortOrderChanged(int idx)
{
    sortOrder = (Qt::SortOrder) ui->comboBoxSortOrder->itemData(idx).toInt();
    sortAddresses();
}

void ReceiveWidget::sortAddresses()
{
    if (this->filter)
        this->filter->sort(sortType, sortOrder);
}

void ReceiveWidget::onTransparentSelected(bool transparentSelected)
{
    shieldedMode = !transparentSelected;
    refreshView();
    this->filter->setType(shieldedMode ? AddressTableModel::ShieldedReceive : AddressTableModel::Receive);
};

void ReceiveWidget::changeTheme(bool isLightTheme, QString& theme)
{
    static_cast<AddressHolder*>(this->delegate->getRowFactory())->isLightTheme = isLightTheme;
}

ReceiveWidget::~ReceiveWidget()
{
    delete ui;
}
<commit_msg>[GUI] receive widget, fix missing style for no available address notification.<commit_after>// Copyright (c) 2019-2020 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "qt/pivx/receivewidget.h"
#include "qt/pivx/forms/ui_receivewidget.h"
#include "qt/pivx/requestdialog.h"
#include "qt/pivx/addnewcontactdialog.h"
#include "qt/pivx/qtutils.h"
#include "qt/pivx/myaddressrow.h"
#include "qt/pivx/furlistrow.h"
#include "qt/pivx/addressholder.h"
#include "walletmodel.h"
#include "guiutil.h"
#include "pairresult.h"

#include <QModelIndex>
#include <QColor>
#include <QDateTime>

#define DECORATION_SIZE 70
#define NUM_ITEMS 3

ReceiveWidget::ReceiveWidget(PIVXGUI* parent) :
    PWidget(parent),
    ui(new Ui::ReceiveWidget)
{
    ui->setupUi(this);
    this->setStyleSheet(parent->styleSheet());

    delegate = new FurAbstractListItemDelegate(
                DECORATION_SIZE,
                new AddressHolder(isLightTheme()),
                this
                );

    // Containers
    setCssProperty(ui->left, "container");
    ui->left->setContentsMargins(20,20,20,20);
    setCssProperty(ui->right, "container-right");
    ui->right->setContentsMargins(0,9,0,0);

    // Title
    setCssTitleScreen(ui->labelTitle);
    setCssSubtitleScreen(ui->labelSubtitle1);

    // Address
    setCssProperty(ui->labelAddress, "label-address-box");

    /* Button Group */
    setCssProperty(ui->pushLeft, "btn-check-left");
    setCssProperty(ui->pushRight, "btn-check-right");
    setCssSubtitleScreen(ui->labelSubtitle2);
    ui->labelSubtitle2->setContentsMargins(0,2,4,0);

    setCssSubtitleScreen(ui->labelDate);
    setCssSubtitleScreen(ui->labelLabel);

    // Options
    ui->btnMyAddresses->setTitleClassAndText("btn-title-grey", tr("My Addresses"));
    ui->btnMyAddresses->setSubTitleClassAndText("text-subtitle", tr("List your own addresses"));
    ui->btnMyAddresses->layout()->setMargin(0);
    ui->btnMyAddresses->setRightIconClass("ic-arrow");

    ui->btnRequest->setTitleClassAndText("btn-title-grey", tr("Create Request"));
    ui->btnRequest->setSubTitleClassAndText("text-subtitle", tr("Request payment with a fixed amount"));
    ui->btnRequest->layout()->setMargin(0);

    ui->pushButtonLabel->setLayoutDirection(Qt::RightToLeft);
    setCssProperty(ui->pushButtonLabel, "btn-secundary-label");

    ui->pushButtonNewAddress->setLayoutDirection(Qt::RightToLeft);
    setCssProperty(ui->pushButtonNewAddress, "btn-secundary-new-address");

    ui->pushButtonCopy->setLayoutDirection(Qt::RightToLeft);
    setCssProperty(ui->pushButtonCopy, "btn-secundary-copy");

    setCssProperty(ui->labelQrImg, "text-subtitle");

    // List Addresses
    setCssProperty(ui->listViewAddress, "container");
    ui->listViewAddress->setItemDelegate(delegate);
    ui->listViewAddress->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
    ui->listViewAddress->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
    ui->listViewAddress->setAttribute(Qt::WA_MacShowFocusRect, false);
    ui->listViewAddress->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->listViewAddress->setUniformItemSizes(true);

    spacer = new QSpacerItem(40, 20, QSizePolicy::Maximum, QSizePolicy::Expanding);
    ui->btnMyAddresses->setChecked(true);
    ui->container_right->addItem(spacer);
    ui->listViewAddress->setVisible(false);

    // Sort Controls
    SortEdit* lineEdit = new SortEdit(ui->comboBoxSort);
    connect(lineEdit, &SortEdit::Mouse_Pressed, [this](){ui->comboBoxSort->showPopup();});
    connect(ui->comboBoxSort, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ReceiveWidget::onSortChanged);
    SortEdit* lineEditOrder = new SortEdit(ui->comboBoxSortOrder);
    connect(lineEditOrder, &SortEdit::Mouse_Pressed, [this](){ui->comboBoxSortOrder->showPopup();});
    connect(ui->comboBoxSortOrder, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ReceiveWidget::onSortOrderChanged);
    fillAddressSortControls(lineEdit, lineEditOrder, ui->comboBoxSort, ui->comboBoxSortOrder);
    ui->sortWidget->setVisible(false);

    // Connect
    connect(ui->pushButtonLabel, &QPushButton::clicked, this, &ReceiveWidget::onLabelClicked);
    connect(ui->pushButtonCopy, &QPushButton::clicked, this, &ReceiveWidget::onCopyClicked);
    connect(ui->pushButtonNewAddress, &QPushButton::clicked, this, &ReceiveWidget::onNewAddressClicked);
    connect(ui->listViewAddress, &QListView::clicked, this, &ReceiveWidget::handleAddressClicked);
    connect(ui->btnRequest, &OptionButton::clicked, this, &ReceiveWidget::onRequestClicked);
    connect(ui->btnMyAddresses, &OptionButton::clicked, this, &ReceiveWidget::onMyAddressesClicked);

    ui->pushLeft->setChecked(true);
    connect(ui->pushLeft, &QPushButton::clicked, [this](){onTransparentSelected(true);});
    connect(ui->pushRight,  &QPushButton::clicked, [this](){onTransparentSelected(false);});
}

void ReceiveWidget::loadWalletModel()
{
    if (walletModel) {
        this->addressTableModel = walletModel->getAddressTableModel();
        this->filter = new AddressFilterProxyModel(AddressTableModel::Receive, this);
        this->filter->setSourceModel(addressTableModel);
        this->filter->sort(sortType, sortOrder);
        ui->listViewAddress->setModel(this->filter);
        ui->listViewAddress->setModelColumn(AddressTableModel::Address);

        if (!info) info = new SendCoinsRecipient();
        refreshView();

        // data change
        connect(this->addressTableModel, &AddressTableModel::dataChanged, [this](const QModelIndex& tl, const QModelIndex& br){ refreshView(tl, br); });
    }
}

void ReceiveWidget::refreshView(const QModelIndex& tl, const QModelIndex& br)
{
    const QModelIndex& index = tl.sibling(tl.row(), AddressTableModel::Address);
    return refreshView(index.data(Qt::DisplayRole).toString());
}

void ReceiveWidget::refreshView(QString refreshAddress)
{
    try {
        QString latestAddress = (refreshAddress.isEmpty()) ? this->addressTableModel->getAddressToShow(shieldedMode) : refreshAddress;

        if (latestAddress.isEmpty()) {
            // Check for generation errors
            ui->labelQrImg->setText(tr("No available address\ntry unlocking the wallet"));
            inform(tr("Error generating address"));
            return;
        }

        QString addressToShow = latestAddress;
        int64_t time = walletModel->getKeyCreationTime(latestAddress.toStdString());
        if (shieldedMode) {
            addressToShow = addressToShow.left(20) + "..." + addressToShow.right(19);
        }

        ui->labelAddress->setText(addressToShow);
        ui->labelDate->setText(GUIUtil::dateTimeStr(QDateTime::fromTime_t(static_cast<uint>(time))));
        updateQr(latestAddress);
        updateLabel();
    } catch (const std::runtime_error& error) {
        ui->labelQrImg->setText(tr("No available address\ntry unlocking the wallet"));
        inform(tr("Error generating address"));
    }
}

void ReceiveWidget::updateLabel()
{
    if (!info->address.isEmpty()) {
        // Check if address label exists
        QString label = addressTableModel->labelForAddress(info->address);
        if (!label.isEmpty()) {
            ui->labelLabel->setVisible(true);
            ui->labelLabel->setText(label);
            ui->pushButtonLabel->setText(tr("Edit Label"));
        } else {
            ui->labelLabel->setVisible(false);
        }
    }
}

void ReceiveWidget::updateQr(QString& address)
{
    info->address = address;
    QString uri = GUIUtil::formatBitcoinURI(*info);
    ui->labelQrImg->setText("");

    QString error;
    QColor qrColor("#382d4d");
    QPixmap pixmap = encodeToQr(uri, error, qrColor);
    if (!pixmap.isNull()) {
        qrImage = &pixmap;
        ui->labelQrImg->setPixmap(qrImage->scaled(ui->labelQrImg->width(), ui->labelQrImg->height()));
    } else {
        ui->labelQrImg->setText(!error.isEmpty() ? error : "Error encoding address");
    }
}

void ReceiveWidget::handleAddressClicked(const QModelIndex &index)
{
    QModelIndex rIndex = filter->mapToSource(index);
    refreshView(rIndex.data(Qt::DisplayRole).toString());
}

void ReceiveWidget::onLabelClicked()
{
    if (walletModel && !isShowingDialog) {
        isShowingDialog = true;
        showHideOp(true);
        AddNewContactDialog *dialog = new AddNewContactDialog(window);
        dialog->setTexts(tr("Edit Address Label"));
        dialog->setData(info->address, addressTableModel->labelForAddress(info->address));
        if (openDialogWithOpaqueBackgroundY(dialog, window, 3.5, 6)) {
            QString label = dialog->getLabel();
            const CWDestination address = Standard::DecodeDestination(info->address.toUtf8().constData());
            if (!label.isEmpty() && walletModel->updateAddressBookLabels(
                    address,
                    label.toUtf8().constData(),
                    AddressBook::AddressBookPurpose::RECEIVE
            )
                    ) {
                // update label status (icon color)
                updateLabel();
                inform(tr("Address label saved"));
            } else {
                inform(tr("Error storing address label"));
            }
        }
        isShowingDialog = false;
    }
}

void ReceiveWidget::onNewAddressClicked()
{
    try {
        WalletModel::UnlockContext ctx(walletModel->requestUnlock());
        if (!ctx.isValid()) {
            // Unlock wallet was cancelled
            inform(tr("Cannot create new address, wallet locked"));
            return;
        }

        QString strAddress;
        PairResult r(false);
        if (!shieldedMode) {
            Destination address;
            r = walletModel->getNewAddress(address, "");
            strAddress = QString::fromStdString(address.ToString());
        } else {
            r = walletModel->getNewShieldedAddress(strAddress, "");
        }

        // Check validity
        if (!r.result) {
            inform(r.status->c_str());
            return;
        }

        refreshView(strAddress);
        inform(tr("New address created"));
    } catch (const std::runtime_error& error) {
        // Error generating address
        inform("Error generating address");
    }
}

void ReceiveWidget::onCopyClicked()
{
    GUIUtil::setClipboard(info->address);
    inform(tr("Address copied"));
}

void ReceiveWidget::onRequestClicked()
{
    showAddressGenerationDialog(true);
}

void ReceiveWidget::showAddressGenerationDialog(bool isPaymentRequest)
{
    if (walletModel && !isShowingDialog) {
        WalletModel::UnlockContext ctx(walletModel->requestUnlock());
        if (!ctx.isValid()) {
            // Unlock wallet was cancelled
            inform(tr("Cannot perform operation, wallet locked"));
            return;
        }
        isShowingDialog = true;
        showHideOp(true);
        RequestDialog *dialog = new RequestDialog(window);
        dialog->setWalletModel(walletModel);
        dialog->setPaymentRequest(isPaymentRequest);
        openDialogWithOpaqueBackgroundY(dialog, window, 3.5, 12);
        if (dialog->res == 1) {
            inform(tr("URI copied to clipboard"));
        } else if (dialog->res == 2) {
            inform(tr("Address copied to clipboard"));
        }
        dialog->deleteLater();
        isShowingDialog = false;
    }
}

void ReceiveWidget::onMyAddressesClicked()
{
    bool isVisible = ui->listViewAddress->isVisible();
    if (!isVisible) {
        ui->btnMyAddresses->setRightIconClass("btn-dropdown", true);
        ui->listViewAddress->setVisible(true);
        ui->sortWidget->setVisible(true);
        ui->container_right->removeItem(spacer);
        ui->listViewAddress->update();
    } else {
        ui->btnMyAddresses->setRightIconClass("ic-arrow", true);
        ui->container_right->addItem(spacer);
        ui->listViewAddress->setVisible(false);
        ui->sortWidget->setVisible(false);
    }
}

void ReceiveWidget::onSortChanged(int idx)
{
    sortType = (AddressTableModel::ColumnIndex) ui->comboBoxSort->itemData(idx).toInt();
    sortAddresses();
}

void ReceiveWidget::onSortOrderChanged(int idx)
{
    sortOrder = (Qt::SortOrder) ui->comboBoxSortOrder->itemData(idx).toInt();
    sortAddresses();
}

void ReceiveWidget::sortAddresses()
{
    if (this->filter)
        this->filter->sort(sortType, sortOrder);
}

void ReceiveWidget::onTransparentSelected(bool transparentSelected)
{
    shieldedMode = !transparentSelected;
    refreshView();
    this->filter->setType(shieldedMode ? AddressTableModel::ShieldedReceive : AddressTableModel::Receive);
};

void ReceiveWidget::changeTheme(bool isLightTheme, QString& theme)
{
    static_cast<AddressHolder*>(this->delegate->getRowFactory())->isLightTheme = isLightTheme;
}

ReceiveWidget::~ReceiveWidget()
{
    delete ui;
}
<|endoftext|>


<commit_before>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2012 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

/***********************************************************************************************************************
 * SimpleTest.cpp
 *
 *  Created on: May 11, 2012
 *      Author: Dimitar Asenov
 **********************************************************************************************************************/

#include "contractslibrary.h"
#include "SelfTest/src/SelfTestSuite.h"

namespace ContractsLibrary {

TEST(ContractsLibrary, SimpleTest)
{
	CHECK_INT_EQUAL(1,1);
}

}
<commit_msg>Create a basic test case scenario for Code Contracts <commit_after>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2012 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

/***********************************************************************************************************************
 * SimpleTest.cpp
 *
 *  Created on: May 11, 2012
 *      Author: Dimitar Asenov
 **********************************************************************************************************************/

#include "contractslibrary.h"
#include "SelfTest/src/SelfTestSuite.h"

#include "OOModel/src/allOOModelNodes.h"
#include "ModelBase/src/Model.h"

#include "VisualizationBase/src/VisualizationManager.h"
#include "VisualizationBase/src/Scene.h"
#include "VisualizationBase/src/views/MainView.h"
#include "VisualizationBase/src/renderer/ModelRenderer.h"
#include "VisualizationBase/src/items/VExtendable.h"
#include "VisualizationBase/src/items/VText.h"
#include "VisualizationBase/src/items/VList.h"
#include "VisualizationBase/src/node_extensions/Position.h"
#include "VisualizationBase/src/items/RootItem.h"

#include "OOInteraction/src/expression_editor/OOExpressionBuilder.h"

using namespace OOModel;
using namespace Visualization;
using namespace OOInteraction;

namespace ContractsLibrary {

Library* createContractsLibrary()
{
	Library* lib = new Library();
	lib->setName("CodeContracts");
	Class* contract = new Class();
	lib->classes()->append(contract);
	contract->setName("Contract");

	Method* req = new Method();
	req->setName("Requires");
	contract->methods()->append(req);
	req->setVisibility(Visibility::PUBLIC);
	req->setStorageSpecifier(StorageSpecifier::CLASS_VARIABLE);
	auto *fa = new FormalArgument();
	fa->setTypeExpression(new PrimitiveTypeExpression(PrimitiveType::BOOLEAN));
	fa->setName("precondition");
	req->arguments()->append(fa);

	Method* ens = new Method();
	ens->setName("Ensures");
	contract->methods()->append(ens);
	ens->setVisibility(Visibility::PUBLIC);
	ens->setStorageSpecifier(StorageSpecifier::CLASS_VARIABLE);
	fa = new FormalArgument();
	fa->setTypeExpression(new PrimitiveTypeExpression(PrimitiveType::BOOLEAN));
	fa->setName("postcondition");
	ens->arguments()->append(fa);

	// Set positions
	lib->extension<Position>()->setX(540);
	contract->extension<Position>()->setY(0);
	req->extension<Position>()->setY(0);
	ens->extension<Position>()->setY(60);

	return lib;
}

Class* createBaseClass()
{
	Class* car = new Class();
	car->setName("Car");
	car->setVisibility(Visibility::PUBLIC);

	auto *fuel = new Field();
	fuel->setName("fuel");
	fuel->setTypeExpression(new PrimitiveTypeExpression(PrimitiveType::INT));
	fuel->setVisibility(Visibility::PUBLIC);
	car->fields()->append(fuel);

	auto *travel = new Method();
	travel->setName("travel");
	travel->setVisibility(Visibility::PUBLIC);
	car->methods()->append(travel);
	auto *fa = new FormalArgument();
	fa->setTypeExpression(new PrimitiveTypeExpression(PrimitiveType::INT));
	fa->setName("numPassengers");
	travel->arguments()->append(fa);

	travel->items()->append(new ExpressionStatement( OOExpressionBuilder::getOOExpression(
			"CodeContracts.Contract.Requires(fuel>0)")));

	travel->items()->append(new ExpressionStatement( OOExpressionBuilder::getOOExpression(
			"CodeContracts.Contract.Requires(numPassengers>0)")));

	return car;
}

Class* createDerivedClass()
{
	Class* car = new Class();
	car->setName("SelfDrivingCar");
	car->setVisibility(Visibility::PUBLIC);
	car->baseClasses()->append(new ReferenceExpression("Car"));

	auto *travel = new Method();
	travel->setName("travel");
	travel->setVisibility(Visibility::PUBLIC);
	car->methods()->append(travel);
	auto *fa = new FormalArgument();
	fa->setTypeExpression(new PrimitiveTypeExpression(PrimitiveType::INT));
	fa->setName("numPassengers");
	travel->arguments()->append(fa);

	travel->items()->append(new ExpressionStatement( OOExpressionBuilder::getOOExpression(
			"CodeContracts.Contract.Requires(numPassengers>=0)")));

	car->extension<Position>()->setY(160);

	return car;
}

TEST(ContractsLibrary, ContractsLibraryTest)
{
	CHECK_INT_EQUAL(1,1);

	Scene* scene = new Scene();

	////////////////////////////////////////////////// Create Model
	Model::Model* model = new Model::Model();
	Project* prj = nullptr;

	// Create project
	prj = dynamic_cast<Project*> (model->createRoot("Project"));
	model->beginModification(prj, "build simple java library and a hello world app");
	prj->setName("HelloWorld");
	prj->libraries()->append(createContractsLibrary());
	prj->classes()->append( createBaseClass());
	prj->classes()->append( createDerivedClass() );
	model->endModification();

	scene->addTopLevelItem( new RootItem(prj));
	scene->scheduleUpdate();
	scene->listenToModel(model);

	// Create view
	MainView* view = new MainView(scene);

	CHECK_CONDITION(view != nullptr);
}

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 EEnginE 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.
 *
 */

#pragma once

#include "defines.hpp"
#include "vkuDevice.hpp"
#include <mutex>

namespace e_engine {

class vkuSwapChain final {
  struct Config {
    bool     preferMailBoxPresetMode      = true;
    bool     prefereNonTearingPresentMode = true;
    VkFormat preferedSurfaceFormat        = VK_FORMAT_B8G8R8A8_UNORM;
  };

  struct SwapChainImg {
    VkImage     img;
    VkImageView iv;
  };

  class LockAndResult {
    typedef std::unique_lock<std::mutex> LOCK;

   private:
    LOCK     vLock;
    uint32_t vImg;
    VkResult vRes;

   public:
    LockAndResult() = delete;
    LockAndResult(LOCK _l, uint64_t _img) : vLock(std::move(_l)), vImg(_img), vRes(VK_SUCCESS) {}
    LockAndResult(LOCK _l, VkResult _res) : vLock(std::move(_l)), vImg(UINT32_MAX), vRes(_res) {}

    LockAndResult(LockAndResult const &) = delete;
    LockAndResult(LockAndResult &&)      = default;
    LockAndResult &operator=(const LockAndResult &) = delete;
    LockAndResult &operator=(LockAndResult &&) = default;

    inline uint32_t getNextImage() const noexcept { return vImg; }
    inline VkResult getError() const noexcept { return vRes; }
    inline uint32_t operator*() const noexcept { return vImg; }

    inline bool operator!() const noexcept { return vRes != VK_SUCCESS; }
    inline explicit operator bool() const noexcept { return vRes == VK_SUCCESS; }
  };

 private:
  VkSwapchainKHR vSwapChain = VK_NULL_HANDLE;
  VkSurfaceKHR   vSurface   = VK_NULL_HANDLE;
  vkuDevicePTR   vDevice    = nullptr;

  std::vector<VkImage>     vSwapchainImages;
  std::vector<VkImageView> vSwapchainViews;

  VkSurfaceFormatKHR vSwapchainFormat;

  std::mutex vSwapChainCreateMutex;

  Config cfg;

 public:
  vkuSwapChain() = default;
  ~vkuSwapChain();

  vkuSwapChain(vkuSwapChain const &) = delete;
  vkuSwapChain(vkuSwapChain &&)      = delete;
  vkuSwapChain &operator=(const vkuSwapChain &) = delete;
  vkuSwapChain &operator=(vkuSwapChain &&) = delete;

  LockAndResult init(vkuDevicePTR _device, VkSurfaceKHR _surface);
  void destroy();

  LockAndResult acquireNextImage(VkSemaphore _semaphore = VK_NULL_HANDLE,
                                 VkFence     _fence     = VK_NULL_HANDLE,
                                 uint64_t    _timeout   = UINT64_MAX);

  inline VkSwapchainKHR     get() const noexcept { return vSwapChain; }
  inline VkSurfaceFormatKHR getFormat() const noexcept { return vSwapchainFormat; }
  inline vkuDevicePTR       getDevice() const noexcept { return vDevice; }
  inline Config             getConfig() const noexcept { return cfg; }
  inline bool               isCreated() const noexcept { return vSwapChain != VK_NULL_HANDLE; }

  inline uint32_t getNumImages() const noexcept { return static_cast<uint32_t>(vSwapchainImages.size()); }
  std::vector<vkuSwapChain::SwapChainImg> getImages() const noexcept;

  inline VkSwapchainKHR operator*() const noexcept { return vSwapChain; }

  inline bool operator!() const noexcept { return !isCreated(); }
  inline explicit operator bool() const noexcept { return isCreated(); }
};
}
<commit_msg>Fixed clang compiler warning<commit_after>/*
 * Copyright (C) 2017 EEnginE 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.
 *
 */

#pragma once

#include "defines.hpp"
#include "vkuDevice.hpp"
#include <mutex>

namespace e_engine {

class vkuSwapChain final {
  struct Config {
    bool     preferMailBoxPresetMode      = true;
    bool     prefereNonTearingPresentMode = true;
    VkFormat preferedSurfaceFormat        = VK_FORMAT_B8G8R8A8_UNORM;
  };

  struct SwapChainImg {
    VkImage     img;
    VkImageView iv;
  };

  class LockAndResult {
    typedef std::unique_lock<std::mutex> LOCK;

   private:
    LOCK     vLock;
    uint32_t vImg;
    VkResult vRes;

   public:
    LockAndResult() = delete;
    LockAndResult(LOCK _l, uint32_t _img) : vLock(std::move(_l)), vImg(_img), vRes(VK_SUCCESS) {}
    LockAndResult(LOCK _l, VkResult _res) : vLock(std::move(_l)), vImg(UINT32_MAX), vRes(_res) {}

    LockAndResult(LockAndResult const &) = delete;
    LockAndResult(LockAndResult &&)      = default;
    LockAndResult &operator=(const LockAndResult &) = delete;
    LockAndResult &operator=(LockAndResult &&) = default;

    inline uint32_t getNextImage() const noexcept { return vImg; }
    inline VkResult getError() const noexcept { return vRes; }
    inline uint32_t operator*() const noexcept { return vImg; }

    inline bool operator!() const noexcept { return vRes != VK_SUCCESS; }
    inline explicit operator bool() const noexcept { return vRes == VK_SUCCESS; }
  };

 private:
  VkSwapchainKHR vSwapChain = VK_NULL_HANDLE;
  VkSurfaceKHR   vSurface   = VK_NULL_HANDLE;
  vkuDevicePTR   vDevice    = nullptr;

  std::vector<VkImage>     vSwapchainImages;
  std::vector<VkImageView> vSwapchainViews;

  VkSurfaceFormatKHR vSwapchainFormat;

  std::mutex vSwapChainCreateMutex;

  Config cfg;

 public:
  vkuSwapChain() = default;
  ~vkuSwapChain();

  vkuSwapChain(vkuSwapChain const &) = delete;
  vkuSwapChain(vkuSwapChain &&)      = delete;
  vkuSwapChain &operator=(const vkuSwapChain &) = delete;
  vkuSwapChain &operator=(vkuSwapChain &&) = delete;

  LockAndResult init(vkuDevicePTR _device, VkSurfaceKHR _surface);
  void destroy();

  LockAndResult acquireNextImage(VkSemaphore _semaphore = VK_NULL_HANDLE,
                                 VkFence     _fence     = VK_NULL_HANDLE,
                                 uint64_t    _timeout   = UINT64_MAX);

  inline VkSwapchainKHR     get() const noexcept { return vSwapChain; }
  inline VkSurfaceFormatKHR getFormat() const noexcept { return vSwapchainFormat; }
  inline vkuDevicePTR       getDevice() const noexcept { return vDevice; }
  inline Config             getConfig() const noexcept { return cfg; }
  inline bool               isCreated() const noexcept { return vSwapChain != VK_NULL_HANDLE; }

  inline uint32_t getNumImages() const noexcept { return static_cast<uint32_t>(vSwapchainImages.size()); }
  std::vector<vkuSwapChain::SwapChainImg> getImages() const noexcept;

  inline VkSwapchainKHR operator*() const noexcept { return vSwapChain; }

  inline bool operator!() const noexcept { return !isCreated(); }
  inline explicit operator bool() const noexcept { return isCreated(); }
};
}
<|endoftext|>


<commit_before>/*
    Copyright 2012 <copyright holder> <email>

    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 "manager.hpp"

#include <boost/filesystem.hpp>
#include <ctime>

#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>

using namespace bithorded;
using namespace bithorded::cache;

namespace fs = boost::filesystem;

namespace bithorded {
	namespace cache {
		log4cplus::Logger log = log4cplus::Logger::getInstance("source");
	}
}

CacheManager::CacheManager(boost::asio::io_service& ioSvc,
                           bithorded::router::Router& router,
                           const boost::filesystem::path& baseDir, intmax_t size) :
	bithorded::store::AssetStore(baseDir),
	_baseDir(baseDir),
	_ioSvc(ioSvc),
	_router(router),
	_maxSize(size)
{
	if (!baseDir.empty())
		AssetStore::openOrCreate();
}

IAsset::Ptr CacheManager::openAsset(const boost::filesystem::path& assetPath)
{
	return boost::make_shared<CachedAsset>(assetPath);
}

IAsset::Ptr CacheManager::openAsset(const bithorde::BindRead& req)
{
	auto stored = boost::dynamic_pointer_cast<CachedAsset>(bithorded::store::AssetStore::openAsset(req));
	if (stored && (stored->status == bithorde::Status::SUCCESS)) {
		return stored;
	} else {
		auto upstream = _router.findAsset(req);
		if (auto upstream_ = boost::dynamic_pointer_cast<router::ForwardedAsset>(upstream))
			return boost::make_shared<CachingAsset>(*this, upstream_, stored);
		else
			return upstream;
	}
}

CachedAsset::Ptr CacheManager::prepareUpload(uint64_t size)
{
	if ((!_baseDir.empty()) && makeRoom(size)) {
		fs::path assetFolder(AssetStore::newAssetDir());

		try {
			auto asset = boost::make_shared<CachedAsset>(assetFolder,size);
			asset->statusChange.connect(boost::bind(&CacheManager::linkAsset, this, CachedAsset::WeakPtr(asset)));
			return asset;
		} catch (const std::ios::failure& e) {
			LOG4CPLUS_ERROR(log, "Failed to create " << assetFolder << " for upload. Purging...");
			AssetStore::removeAsset(assetFolder);
			return CachedAsset::Ptr();
		}
	} else {
		return CachedAsset::Ptr();
	}
}

IAsset::Ptr CacheManager::findAsset(const bithorde::BindRead& req)
{
	return AssetSessions::findAsset(req);
}

bool CacheManager::makeRoom(uint64_t size)
{
	while ((store::AssetStore::size()+size) > _maxSize) {
		auto looser = pickLooser();
		if (looser.empty())
			return false;
		else
			AssetStore::removeAsset(looser);
	}
	return true;
}

fs::path CacheManager::pickLooser() {
	// TODO: update mtime on access (support both FIFO and LRU?)
	fs::path looser;
	std::time_t oldest=-1;
	fs::directory_iterator end;
	for (auto iter=AssetStore::assetIterator(); iter != end; iter++) {
		auto age = fs::last_write_time(iter->path());
		if ((oldest == -1) || (age < oldest)) {
			oldest = age;
			looser = iter->path();
		}
	}

	return looser;
}

void CacheManager::linkAsset(CachedAsset::WeakPtr asset_)
{
	auto asset = asset_.lock();
	BitHordeIds ids;
	if (asset && asset->getIds(ids)) {
		std::cerr << "Linking" << std::endl;
		const char *data_path = (asset->folder()/"data").c_str();
		lutimes(data_path, NULL);

		AssetStore::link(ids, asset);
	}
}

<commit_msg>[bithorded/cache/manager]Fix debug-linking-message.<commit_after>/*
    Copyright 2012 <copyright holder> <email>

    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 "manager.hpp"

#include <boost/filesystem.hpp>
#include <ctime>

#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>

using namespace bithorded;
using namespace bithorded::cache;

namespace fs = boost::filesystem;

namespace bithorded {
	namespace cache {
		log4cplus::Logger log = log4cplus::Logger::getInstance("cache");
	}
}

CacheManager::CacheManager(boost::asio::io_service& ioSvc,
                           bithorded::router::Router& router,
                           const boost::filesystem::path& baseDir, intmax_t size) :
	bithorded::store::AssetStore(baseDir),
	_baseDir(baseDir),
	_ioSvc(ioSvc),
	_router(router),
	_maxSize(size)
{
	if (!baseDir.empty())
		AssetStore::openOrCreate();
}

IAsset::Ptr CacheManager::openAsset(const boost::filesystem::path& assetPath)
{
	return boost::make_shared<CachedAsset>(assetPath);
}

IAsset::Ptr CacheManager::openAsset(const bithorde::BindRead& req)
{
	auto stored = boost::dynamic_pointer_cast<CachedAsset>(bithorded::store::AssetStore::openAsset(req));
	if (stored && (stored->status == bithorde::Status::SUCCESS)) {
		return stored;
	} else {
		auto upstream = _router.findAsset(req);
		if (auto upstream_ = boost::dynamic_pointer_cast<router::ForwardedAsset>(upstream))
			return boost::make_shared<CachingAsset>(*this, upstream_, stored);
		else
			return upstream;
	}
}

CachedAsset::Ptr CacheManager::prepareUpload(uint64_t size)
{
	if ((!_baseDir.empty()) && makeRoom(size)) {
		fs::path assetFolder(AssetStore::newAssetDir());

		try {
			auto asset = boost::make_shared<CachedAsset>(assetFolder,size);
			asset->statusChange.connect(boost::bind(&CacheManager::linkAsset, this, CachedAsset::WeakPtr(asset)));
			return asset;
		} catch (const std::ios::failure& e) {
			LOG4CPLUS_ERROR(log, "Failed to create " << assetFolder << " for upload. Purging...");
			AssetStore::removeAsset(assetFolder);
			return CachedAsset::Ptr();
		}
	} else {
		return CachedAsset::Ptr();
	}
}

IAsset::Ptr CacheManager::findAsset(const bithorde::BindRead& req)
{
	return AssetSessions::findAsset(req);
}

bool CacheManager::makeRoom(uint64_t size)
{
	while ((store::AssetStore::size()+size) > _maxSize) {
		auto looser = pickLooser();
		if (looser.empty())
			return false;
		else
			AssetStore::removeAsset(looser);
	}
	return true;
}

fs::path CacheManager::pickLooser() {
	// TODO: update mtime on access (support both FIFO and LRU?)
	fs::path looser;
	std::time_t oldest=-1;
	fs::directory_iterator end;
	for (auto iter=AssetStore::assetIterator(); iter != end; iter++) {
		auto age = fs::last_write_time(iter->path());
		if ((oldest == -1) || (age < oldest)) {
			oldest = age;
			looser = iter->path();
		}
	}

	return looser;
}

void CacheManager::linkAsset(CachedAsset::WeakPtr asset_)
{
	auto asset = asset_.lock();
	BitHordeIds ids;
	if (asset && asset->getIds(ids)) {
		LOG4CPLUS_DEBUG(log, "Linking " << ids << " to " << asset->folder());
		const char *data_path = (asset->folder()/"data").c_str();
		lutimes(data_path, NULL);

		AssetStore::link(ids, asset);
	}
}

<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkPointSet.h"
#include <mitkOperation.h>
#include <mitkOperationActor.h>
#include <mitkPointOperation.h>
#include "mitkInteractionConst.h"
#include <mitkXMLWriter.h>
#include <mitkXMLReader.h>
#include <mitkPointSetWriter.h>
#include <mitkPointSetReader.h>

#include "mitkRenderWindow.h"//*\todo remove later, when update ok!

//##ModelId=3F0177E901BD
mitk::PointSet::PointSet()
{
  m_ItkData = DataType::New();
  PointDataContainer::Pointer pointData = PointDataContainer::New();
  m_ItkData->SetPointData(pointData);
  m_Geometry3D->Initialize();
}

//##ModelId=3F0177E901BE
mitk::PointSet::~PointSet()
{}

//##ModelId=3F0177E901C1
int mitk::PointSet::GetSize()
{
  return m_ItkData->GetNumberOfPoints();
}

//##ModelId=3F0177E901CC
mitk::PointSet::DataType::Pointer mitk::PointSet::GetPointSet() const
{
  return m_ItkData;
}

//##ModelId=3F0177E901DE
//##Documentation
//##@brief searches a point in the list with a given precision
int mitk::PointSet::SearchPoint(Point3D point, float distance )
{
//out is the point which is checked to be the searched point
  PointType out;
  out.Fill(0);

  //searching the first point in the Set, that is +- distance far away from the given point
  unsigned int i;
  PointsContainer::Iterator it, end;
  end = m_ItkData->GetPoints()->End();
  int bestIndex=-1;
  distance = distance*distance;
  ScalarType bestDist=distance;
  ScalarType dist, tmp;
 	for (it = m_ItkData->GetPoints()->Begin(), i=0; it != end; ++it, ++i)
	{
    bool ok = m_ItkData->GetPoints()->GetElementIfIndexExists(it->Index(), &out);
    if (!ok)
      return -1;
    else
    if (point == out)//if totaly equal
      return it->Index();

    //distance calculation
    tmp=out[0]-point[0]; dist  = tmp*tmp;
    tmp=out[1]-point[1]; dist += tmp*tmp;
    tmp=out[2]-point[2]; dist += tmp*tmp;
    if(dist<bestDist)
    {
      bestIndex = it->Index();
      bestDist  = dist;
    }
	}
	return bestIndex;
}

//##ModelId=3F0177E901CE
//##Documentation
//##@brief check if index exists. If it doesn't exist, then return 0,0,0
mitk::PointSet::PointType mitk::PointSet::GetPoint(int position) const
{
  PointType out;
  out.Fill(0);

  if (m_ItkData->GetPoints()->IndexExists(position))
  {
    m_ItkData->GetPoint(position, &out);
    return out;
  }
  else
    return out;
}

bool mitk::PointSet::IndexExists(int position)
{
  return m_ItkData->GetPoints()->IndexExists(position);
}

//##ModelId=3F0177E901DC
bool mitk::PointSet::GetSelectInfo(int position)
{
  if (m_ItkData->GetPoints()->IndexExists(position))
	{
    PointDataType pointData = {0, false, PTUNDEFINED};
    m_ItkData->GetPointData(position, &pointData);
    return pointData.selected;
	}
	else
		return false;
}

//##ModelId=3F05B07B0147
const int mitk::PointSet::GetNumberOfSelected()
{
  int numberOfSelected = 0;
  for (PointDataIterator it = m_ItkData->GetPointData()->Begin(); it != m_ItkData->GetPointData()->End(); it++)
  {
    if (it->Value().selected == true)
      numberOfSelected++;
  }
  return numberOfSelected;
}

int mitk::PointSet::SearchSelectedPoint()
{
  for (PointDataIterator it = m_ItkData->GetPointData()->Begin(); it != m_ItkData->GetPointData()->End(); it++)
  {
    if (it->Value().selected == true)
      return it->Index();
  }
  return -1;
}

//##ModelId=3F0177E901BF
//##Documentation
//## @brief executes the given Operation
void mitk::PointSet::ExecuteOperation(Operation* operation)
{

	switch (operation->GetOperationType())
	{
	case OpNOTHING:
		break;
	case OpINSERT://inserts the point at the given position and selects it.
		{
      mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

      int position = pointOp->GetIndex();

      PointType pt;
      pt.CastFrom(pointOp->GetPoint());

      m_ItkData->GetPoints()->InsertElement(position, pt);

      PointDataType pointData = {pointOp->GetIndex(), pointOp->GetSelected(), pointOp->GetPointType()};
      m_ItkData->GetPointData()->InsertElement(position, pointData);
      this->Modified();
      ((const itk::Object*)this)->InvokeEvent( NewPointEvent() );
		}
		break;
	case OpMOVE://moves the point given by index
		{
      mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

			PointType pt;
      pt.CastFrom(pointOp->GetPoint());
      m_ItkData->SetPoint(pointOp->GetIndex(), pt);
      this->Modified();
		}
		break;
	case OpREMOVE://removes the point at given by position
		{
      mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

      m_ItkData->GetPoints()->DeleteIndex((unsigned)pointOp->GetIndex());
      m_ItkData->GetPointData()->DeleteIndex((unsigned)pointOp->GetIndex());
      this->Modified();
     ((const itk::Object*)this)->InvokeEvent( RemovedPointEvent() );
		}
		break;
  case OpSELECTPOINT://select the given point
		{
      mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

      PointDataType pointData = {0, false, PTUNDEFINED};
      m_ItkData->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.selected = true;
      m_ItkData->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
		}
		break;
	case OpDESELECTPOINT://unselect the given point
		{
      mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

      PointDataType pointData = {0, false, PTUNDEFINED};
      m_ItkData->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.selected = false;
      m_ItkData->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
		}
		break;
  case OpSETPOINTTYPE:
    {
      mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_ItkData->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.pointSpec = pointOp->GetPointType();
      m_ItkData->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;
	default:
    itkWarningMacro("mitkPointSet could not understrand the operation. Please check!");
		break;
	}

  //to tell the mappers, that the data is modifierd and has to be updated
  //only call modified if anything is done, so call in cases
	//this->Modified();

  mitk::OperationEndEvent endevent(operation);
  ((const itk::Object*)this)->InvokeEvent(endevent);

  mitk::RenderWindow::UpdateAllInstances(); //*todo has to be done here, cause of update-pipeline not working yet
}

//##ModelId=3F0177E901EE
void mitk::PointSet::UpdateOutputInformation()
{
  if ( this->GetSource( ) )
  {
      this->GetSource( )->UpdateOutputInformation( );
  }
  const DataType::BoundingBoxType *bb = m_ItkData->GetBoundingBox();
  BoundingBox::BoundsArrayType itkBounds = bb->GetBounds();
  float mitkBounds[6];

  //for assignment see Geometry3d::SetBounds(const float bounds)
  mitkBounds[0] = itkBounds[0];
  mitkBounds[1] = itkBounds[1];
  mitkBounds[2] = itkBounds[2];
  mitkBounds[3] = itkBounds[3];
  mitkBounds[4] = itkBounds[4];
  mitkBounds[5] = itkBounds[5];

  m_Geometry3D->SetBounds(mitkBounds);
}

//##ModelId=3F0177E901FB
void mitk::PointSet::SetRequestedRegionToLargestPossibleRegion()
{
}
//##ModelId=3F0177E901FD
bool mitk::PointSet::RequestedRegionIsOutsideOfTheBufferedRegion()
{
    return false;
}
//##ModelId=3F0177E901FF
bool mitk::PointSet::VerifyRequestedRegion()
{
    return true;
}
//##ModelId=3F0177E9020B
void mitk::PointSet::SetRequestedRegion(itk::DataObject*)
{
}

bool mitk::PointSet::WriteXMLData( XMLWriter& xmlWriter )
{
  std::string fileName = xmlWriter.GetNewFilenameAndSubFolder();
  fileName += ".mps";
  xmlWriter.WriteProperty( XMLReader::FILENAME, fileName.c_str() );
  PointSetWriter::Pointer writer = PointSetWriter::New();
  writer->SetFileName( fileName.c_str() );
  writer->SetInput( this );
  writer->Update();
  return true;
}

bool mitk::PointSet::ReadXMLData( XMLReader& xmlReader )
{
  std::string fileName;
  xmlReader.GetAttribute( XMLReader::FILENAME, fileName );

  if ( fileName.empty() )
    return false;

  PointSetReader::Pointer reader = PointSetReader::New();
  reader->SetFileName( fileName.c_str() );
  reader->Update();
  m_ItkData = dynamic_cast<DataType*>( reader->GetOutput() );

  if ( m_ItkData.IsNull() )
    return false;

  return true;
}
<commit_msg>store and load MITK-Projects using the XML-reader and write functions<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkPointSet.h"
#include <mitkOperation.h>
#include <mitkOperationActor.h>
#include <mitkPointOperation.h>
#include "mitkInteractionConst.h"
#include <mitkXMLWriter.h>
#include <mitkXMLReader.h>
#include <mitkPointSetWriter.h>
#include <mitkPointSetReader.h>

#include "mitkRenderWindow.h"//*\todo remove later, when update ok!

//##ModelId=3F0177E901BD
mitk::PointSet::PointSet()
{
  m_ItkData = DataType::New();
  PointDataContainer::Pointer pointData = PointDataContainer::New();
  m_ItkData->SetPointData(pointData);
  m_Geometry3D->Initialize();
}

//##ModelId=3F0177E901BE
mitk::PointSet::~PointSet()
{}

//##ModelId=3F0177E901C1
int mitk::PointSet::GetSize()
{
  return m_ItkData->GetNumberOfPoints();
}

//##ModelId=3F0177E901CC
mitk::PointSet::DataType::Pointer mitk::PointSet::GetPointSet() const
{
  return m_ItkData;
}

//##ModelId=3F0177E901DE
//##Documentation
//##@brief searches a point in the list with a given precision
int mitk::PointSet::SearchPoint(Point3D point, float distance )
{
//out is the point which is checked to be the searched point
  PointType out;
  out.Fill(0);

  //searching the first point in the Set, that is +- distance far away from the given point
  unsigned int i;
  PointsContainer::Iterator it, end;
  end = m_ItkData->GetPoints()->End();
  int bestIndex=-1;
  distance = distance*distance;
  ScalarType bestDist=distance;
  ScalarType dist, tmp;
 	for (it = m_ItkData->GetPoints()->Begin(), i=0; it != end; ++it, ++i)
	{
    bool ok = m_ItkData->GetPoints()->GetElementIfIndexExists(it->Index(), &out);
    if (!ok)
      return -1;
    else
    if (point == out)//if totaly equal
      return it->Index();

    //distance calculation
    tmp=out[0]-point[0]; dist  = tmp*tmp;
    tmp=out[1]-point[1]; dist += tmp*tmp;
    tmp=out[2]-point[2]; dist += tmp*tmp;
    if(dist<bestDist)
    {
      bestIndex = it->Index();
      bestDist  = dist;
    }
	}
	return bestIndex;
}

//##ModelId=3F0177E901CE
//##Documentation
//##@brief check if index exists. If it doesn't exist, then return 0,0,0
mitk::PointSet::PointType mitk::PointSet::GetPoint(int position) const
{
  PointType out;
  out.Fill(0);

  if (m_ItkData->GetPoints()->IndexExists(position))
  {
    m_ItkData->GetPoint(position, &out);
    return out;
  }
  else
    return out;
}

bool mitk::PointSet::IndexExists(int position)
{
  return m_ItkData->GetPoints()->IndexExists(position);
}

//##ModelId=3F0177E901DC
bool mitk::PointSet::GetSelectInfo(int position)
{
  if (m_ItkData->GetPoints()->IndexExists(position))
	{
    PointDataType pointData = {0, false, PTUNDEFINED};
    m_ItkData->GetPointData(position, &pointData);
    return pointData.selected;
	}
	else
		return false;
}

//##ModelId=3F05B07B0147
const int mitk::PointSet::GetNumberOfSelected()
{
  int numberOfSelected = 0;
  for (PointDataIterator it = m_ItkData->GetPointData()->Begin(); it != m_ItkData->GetPointData()->End(); it++)
  {
    if (it->Value().selected == true)
      numberOfSelected++;
  }
  return numberOfSelected;
}

int mitk::PointSet::SearchSelectedPoint()
{
  for (PointDataIterator it = m_ItkData->GetPointData()->Begin(); it != m_ItkData->GetPointData()->End(); it++)
  {
    if (it->Value().selected == true)
      return it->Index();
  }
  return -1;
}

//##ModelId=3F0177E901BF
//##Documentation
//## @brief executes the given Operation
void mitk::PointSet::ExecuteOperation(Operation* operation)
{

	switch (operation->GetOperationType())
	{
	case OpNOTHING:
		break;
	case OpINSERT://inserts the point at the given position and selects it.
		{
      mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

      int position = pointOp->GetIndex();

      PointType pt;
      pt.CastFrom(pointOp->GetPoint());

      m_ItkData->GetPoints()->InsertElement(position, pt);

      PointDataType pointData = {pointOp->GetIndex(), pointOp->GetSelected(), pointOp->GetPointType()};
      m_ItkData->GetPointData()->InsertElement(position, pointData);
      this->Modified();
      ((const itk::Object*)this)->InvokeEvent( NewPointEvent() );
		}
		break;
	case OpMOVE://moves the point given by index
		{
      mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

			PointType pt;
      pt.CastFrom(pointOp->GetPoint());
      m_ItkData->SetPoint(pointOp->GetIndex(), pt);
      this->Modified();
		}
		break;
	case OpREMOVE://removes the point at given by position
		{
      mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

      m_ItkData->GetPoints()->DeleteIndex((unsigned)pointOp->GetIndex());
      m_ItkData->GetPointData()->DeleteIndex((unsigned)pointOp->GetIndex());
      this->Modified();
     ((const itk::Object*)this)->InvokeEvent( RemovedPointEvent() );
		}
		break;
  case OpSELECTPOINT://select the given point
		{
      mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

      PointDataType pointData = {0, false, PTUNDEFINED};
      m_ItkData->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.selected = true;
      m_ItkData->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
		}
		break;
	case OpDESELECTPOINT://unselect the given point
		{
      mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

      PointDataType pointData = {0, false, PTUNDEFINED};
      m_ItkData->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.selected = false;
      m_ItkData->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
		}
		break;
  case OpSETPOINTTYPE:
    {
      mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_ItkData->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.pointSpec = pointOp->GetPointType();
      m_ItkData->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;
	default:
    itkWarningMacro("mitkPointSet could not understrand the operation. Please check!");
		break;
	}

  //to tell the mappers, that the data is modifierd and has to be updated
  //only call modified if anything is done, so call in cases
	//this->Modified();

  mitk::OperationEndEvent endevent(operation);
  ((const itk::Object*)this)->InvokeEvent(endevent);

  mitk::RenderWindow::UpdateAllInstances(); //*todo has to be done here, cause of update-pipeline not working yet
}

//##ModelId=3F0177E901EE
void mitk::PointSet::UpdateOutputInformation()
{
  if ( this->GetSource( ) )
  {
      this->GetSource( )->UpdateOutputInformation( );
  }
  const DataType::BoundingBoxType *bb = m_ItkData->GetBoundingBox();
  BoundingBox::BoundsArrayType itkBounds = bb->GetBounds();
  float mitkBounds[6];

  //for assignment see Geometry3d::SetBounds(const float bounds)
  mitkBounds[0] = itkBounds[0];
  mitkBounds[1] = itkBounds[1];
  mitkBounds[2] = itkBounds[2];
  mitkBounds[3] = itkBounds[3];
  mitkBounds[4] = itkBounds[4];
  mitkBounds[5] = itkBounds[5];

  m_Geometry3D->SetBounds(mitkBounds);
}

//##ModelId=3F0177E901FB
void mitk::PointSet::SetRequestedRegionToLargestPossibleRegion()
{
}
//##ModelId=3F0177E901FD
bool mitk::PointSet::RequestedRegionIsOutsideOfTheBufferedRegion()
{
    return false;
}
//##ModelId=3F0177E901FF
bool mitk::PointSet::VerifyRequestedRegion()
{
    return true;
}
//##ModelId=3F0177E9020B
void mitk::PointSet::SetRequestedRegion(itk::DataObject*)
{
}

bool mitk::PointSet::WriteXMLData( XMLWriter& xmlWriter )
{
  BaseData::WriteXMLData( xmlWriter );
  std::string fileName = xmlWriter.GetNewFilenameAndSubFolder();
  fileName += ".mps";
  xmlWriter.WriteProperty( XMLReader::FILENAME, fileName.c_str() );
  PointSetWriter::Pointer writer = PointSetWriter::New();
  writer->SetFileName( fileName.c_str() );
  writer->SetInput( this );
  writer->Update();
  return true;
}

bool mitk::PointSet::ReadXMLData( XMLReader& xmlReader )
{
  BaseData::ReadXMLData( xmlReader );

  std::string fileName;
  xmlReader.GetAttribute( XMLReader::FILENAME, fileName );

  if ( fileName.empty() )
    return false;

  PointSetReader::Pointer reader = PointSetReader::New();
  reader->SetFileName( fileName.c_str() );
  reader->Update();
  m_ItkData = dynamic_cast<DataType*>( reader->GetOutput() );

  if ( m_ItkData.IsNull() )
    return false;

  return true;
}
<|endoftext|>


<commit_before>#include "mitkImageMapper2D.h"
//#include "mitkRenderWindow.h"
#include "widget.h"
#include "picimage.h"
#include "pic2vtk.h"
#include "PlaneGeometry.h"
#include "BaseRenderer.h"
#include "DataTreeNode.h"

#include "mitkLookupTableProperty.h"
#include "mitkBoolProperty.h"
#include "mitkLevelWindowProperty.h"

#include "mitkRenderWindow.h"
#include "mitkAbstractTransformGeometry.h"

#include <vtkImageReslice.h>
#include <vtkTransform.h>
#include <vtkMatrix4x4.h>
#include <vtkLookupTable.h>

int mitk::ImageMapper2D::numRenderer = 0;

mitk::ImageMapper2D::ImageMapper2D() : m_SliceSelector(NULL)
{
  // Modify superclass default values, can be overridden by subclasses
  this->SetNumberOfRequiredInputs(1);

  m_SliceSelector = ImageSliceSelector::New();
  m_Reslicer = vtkImageReslice::New();

}

//##ModelId=3E32DCF60043
mitk::ImageMapper2D::~ImageMapper2D()
{
  //@FIXME: durch die folgende Zeile sollte doch wohl der desctructor von RendererInfo aufgerufen werden. Das passiert aber nie. Deshalb wird bei der Programm-Beendung auch das iilImage und damit die textur nicht rechtzeitig freigegeben und das Programm crashed.
  m_RendererInfo.clear();
}

//##ModelId=3E3D834B003A
void mitk::ImageMapper2D::GenerateData()
{

}

void mitk::ImageMapper2D::Paint(mitk::BaseRenderer * renderer)
{
  if(IsVisible(renderer)==false) return;

  RendererInfo& renderinfo=m_RendererInfo[renderer];
  iilPicImage*& image = renderinfo.m_iilImage;

  Update(renderer);

  const mitk::DisplayGeometry* displayGeometry = renderer->GetDisplayGeometry();

  Vector2D oldtopLeft=displayGeometry->GetOriginInUnits();
  Vector2D oldbottomRight=displayGeometry->GetOriginInUnits()+displayGeometry->GetSizeInUnits();

  Vector2D topLeft;
  Vector2D bottomRight;
  topLeft=displayGeometry->GetOriginInDisplayUnits();
  bottomRight=topLeft+displayGeometry->GetSizeInDisplayUnits();

  displayGeometry->DisplayToMM(topLeft, topLeft); topLeft.x*=renderinfo.m_PixelsPerMM.x;  topLeft.y*=renderinfo.m_PixelsPerMM.y;
  displayGeometry->DisplayToMM(bottomRight, bottomRight); bottomRight.x*=renderinfo.m_PixelsPerMM.x;  bottomRight.y*=renderinfo.m_PixelsPerMM.y;

  //test - small differences noticed for unisotropic datasets.
  if((Vector2D(oldtopLeft-topLeft).length()>0.1) || (Vector2D(oldbottomRight-bottomRight).length()>0.1))
  {
    bottomRight*=1.0;
  }

  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();
  gluOrtho2D(topLeft.x, bottomRight.x, topLeft.y, bottomRight.y );
  glMatrixMode( GL_MODELVIEW );

  GLdouble eqn0[4] = {0.0, 1.0, 0.0, 0.0};
  GLdouble eqn1[4] = {1.0, 0.0, 0.0, 0.0};
  GLdouble eqn2[4] = {-1.0, 0.0 , 0.0, image->width()};
  GLdouble eqn3[4] = {0, -1.0, 0.0, image->height() };

  glClipPlane (GL_CLIP_PLANE0, eqn0);
  glEnable (GL_CLIP_PLANE0);
  glClipPlane (GL_CLIP_PLANE1, eqn1);
  glEnable (GL_CLIP_PLANE1);
  glClipPlane (GL_CLIP_PLANE2, eqn2);
  glEnable (GL_CLIP_PLANE2);
  glClipPlane (GL_CLIP_PLANE3, eqn3);
  glEnable (GL_CLIP_PLANE3);

  image->display(renderer->GetRenderWindow());

  glDisable (GL_CLIP_PLANE0);
  glDisable (GL_CLIP_PLANE1);
  glDisable (GL_CLIP_PLANE2);
  glDisable (GL_CLIP_PLANE3);

  glPushMatrix ();
  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();
  gluOrtho2D(0, displayGeometry->GetDisplayWidth(), 0, displayGeometry->GetDisplayHeight() );
  glMatrixMode( GL_MODELVIEW );
  glPopMatrix ();
}

//##ModelId=3E3D834B0008
const mitk::ImageMapper2D::InputImageType *mitk::ImageMapper2D::GetInput(void)
{
  if (this->GetNumberOfInputs() < 1)
  {
    return 0;
  }

  return static_cast<const mitk::ImageMapper2D::InputImageType * >
    ( GetData() );
}

//##ModelId=3E6E83B00343
int mitk::ImageMapper2D::GetAssociatedChannelNr(mitk::BaseRenderer *renderer)
{
  RendererInfo& renderinfo=m_RendererInfo[renderer];
  if(renderinfo.m_RendererId < 0)
    renderinfo.m_RendererId = ImageMapper2D::numRenderer++;

  return renderinfo.m_RendererId;
}

//##ModelId=3E8607D20380
void mitk::ImageMapper2D::GenerateOutputInformation()
{
  mitk::Image::Pointer output = this->GetOutput();
  mitk::PixelType pt(typeid(int));
  unsigned int dim[]={256,256};
  output->Initialize(mitk::PixelType(typeid(short int)), 2, dim, 10);
}

//##ModelId=3ED932B00140
void mitk::ImageMapper2D::GenerateData(mitk::BaseRenderer *renderer)
{
  RendererInfo& renderinfo=m_RendererInfo[renderer];

  iilPicImage*& image = renderinfo.m_iilImage;

  mitk::Image::Pointer input  = const_cast<mitk::ImageMapper2D::InputImageType *>(this->GetInput());

  if(image!= NULL)
  {
    delete image;
    image = NULL;
  }

  if(renderinfo.m_Pic)
  {
    ipPicFree(renderinfo.m_Pic);
    renderinfo.m_Pic = NULL;
  }

  if(renderinfo.m_RendererId < 0)
    renderinfo.m_RendererId = ImageMapper2D::numRenderer++;

  if(input.IsNotNull())
  {
    vtkImageData* inputData = input->GetVtkImageData();
    const PlaneView* planeview=NULL;

    const Geometry2D* worldgeometry = renderer->GetWorldGeometry();

    if(dynamic_cast<const PlaneGeometry *>(worldgeometry)!=NULL)
    {
      planeview=&dynamic_cast<const PlaneGeometry *>(worldgeometry)->GetPlaneView();
      m_Reslicer->SetResliceTransform(NULL);
    }
    else
      if(dynamic_cast<const AbstractTransformGeometry *>(worldgeometry)!=NULL)
      {
        const AbstractTransformGeometry *abstractGeometry=dynamic_cast<const AbstractTransformGeometry *>(worldgeometry);
        planeview=&abstractGeometry->GetPlaneView();
        m_Reslicer->SetResliceTransform(abstractGeometry->GetVtkAbstractTransform());
        //m_Reslicer->DebugOn();
      }
      else
        return;

    assert(planeview!=NULL);
    assert(planeview->normal.length()>0.1);

    vtkMatrix4x4* geometry = vtkMatrix4x4::New();
    geometry->Identity();

    m_Reslicer->SetInput(inputData);
    m_Reslicer->SetOutputDimensionality(2);
    m_Reslicer->SetOutputOrigin(0,0,0);

    m_Reslicer->SetBackgroundLevel(-1024);

    int width, height;
    width=worldgeometry->GetWidthInUnits();
    height=worldgeometry->GetHeightInUnits();
    renderinfo.m_PixelsPerMM.set(planeview->getLengthOfOrientation1()/width, planeview->getLengthOfOrientation2()/height);

    m_Reslicer->SetOutputSpacing(renderinfo.m_PixelsPerMM.x, renderinfo.m_PixelsPerMM.y, 1.0);
    m_Reslicer->SetOutputExtent(0.0, width-1, 0.0, height-1, 0.0, 1.0);

    double origin[3];
    origin[0]=planeview->point.x;
    origin[1]=planeview->point.y;
    origin[2]=planeview->point.z;

    m_Reslicer->SetResliceAxes(geometry);
    m_Reslicer->SetResliceAxesOrigin(origin);
    //        m_Reslicer->SetInterpolationModeToLinear();
    double cosines[9];
    Vector3f orient1 = planeview->getOrientation1();
    orient1.normalize();

    Vector3f orient2 = planeview->getOrientation2();
    orient2.normalize();

    // Richtung der X-Achse der Ergebnisschicht im Volumen,
    cosines[0]=orient1.x;
    cosines[1]=orient1.y;
    cosines[2]=orient1.z;

    //Richtung der Y-Achse der Ergebnisschicht im Volumen
    cosines[3]=orient2.x;
    cosines[4]=orient2.y;
    cosines[5]=orient2.z;

    // Schichtfolge/Projektionsrichtung
    cosines[6]= planeview->normal.x;
    cosines[7]= planeview->normal.y;
    cosines[8]= planeview->normal.z;
    m_Reslicer->SetResliceAxesDirectionCosines(cosines);

    m_Reslicer->Update();

    vtkImageData* vtkoutput = m_Reslicer->GetOutput();

    assert(vtkoutput);

    //	std::cout << vtkoutput <<std::endl;
    ipPicDescriptor* pic = Pic2vtk::convert(vtkoutput);
    assert(pic);
    if(pic->dim==1)
    {
      pic->dim=2;
      pic->n[1]=1;
    }
    assert(pic->dim == 2);

    renderinfo.m_Pic = pic;

    //std::cout << "Pic dimensions:" << pic->dim << std::endl;

    image = new iilPicImage(NULL, "ll", 512);

    ApplyProperties(renderer);
//   image->setImage(pic, iilImage::INTENSITY_ALPHA);
	  image->setImage(pic, m_iilMode);
    image->setInterpolation(true);
    image->setRegion(0,0,pic->n[0],pic->n[1]);

    mitk::Image::Pointer output = this->GetOutput();

    //if(renderinfo.m_RendererId < 10)
    //	output->SetPicSlice(pic,0,0,renderinfo.m_RendererId);
    output->Modified();
    renderinfo.m_LastUpdateTime=output->GetMTime();
  }
  return;
}

void mitk::ImageMapper2D::GenerateAllData()
{
  std::map<mitk::BaseRenderer*,RendererInfo>::iterator it=m_RendererInfo.begin();
  for(;it!=m_RendererInfo.end();++it)
    Update(it->first);
}

void mitk::ImageMapper2D::ApplyProperties(mitk::BaseRenderer* renderer)
{
  RendererInfo& renderinfo=m_RendererInfo[renderer];
  iilPicImage*& image = renderinfo.m_iilImage;

  assert(image != NULL);

  float rgba[4]={1.0f,1.0f,1.0f,1.0f};
  // check for color prop and use it for rendering if it exists
  GetColor(rgba, renderer);
  // check for opacity prop and use it for rendering if it exists
  GetOpacity(rgba[3], renderer);

  mitk::LevelWindow levelWindow;
  // check for level window prop and use it for display if it exists
  GetLevelWindow(levelWindow, renderer);

  mitk::LookupTableProperty::Pointer LookupTable;
  LookupTable = dynamic_cast<mitk::LookupTableProperty*>(this->GetDataTreeNode()->GetProperty("LookupTable").GetPointer());
	if (LookupTable.IsNull() )
	{
		m_iilMode = iilImage::INTENSITY_ALPHA;
	  image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]);
	}
	else {
		m_iilMode = iilImage::COLOR_ALPHA;
		image->setColors(LookupTable->GetLookupTable().GetRawLookupTable());
	}

  mitk::BoolProperty::Pointer binary;
  binary = dynamic_cast<mitk::BoolProperty*>(this->GetDataTreeNode()->GetProperty("binary").GetPointer());

  mitk::LevelWindowProperty::Pointer overwriteLevelWindow;
  overwriteLevelWindow = dynamic_cast<mitk::LevelWindowProperty*>(this->GetDataTreeNode()->GetProperty("levelWindow").GetPointer());

  if (binary.IsNotNull() )
  {
    image->setExtrema(0, 1);
  }
  else if (overwriteLevelWindow.IsNotNull() )
  {
    image->setExtrema(overwriteLevelWindow->GetLevelWindow().GetMin(), overwriteLevelWindow->GetLevelWindow().GetMax());
  }
  else
  {
  // set the properties
    image->setExtrema(levelWindow.GetMin(), levelWindow.GetMax());
  }
//  image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]);
}

void mitk::ImageMapper2D::Update(mitk::BaseRenderer* renderer)
{

  RendererInfo& renderinfo=m_RendererInfo[renderer];
  DataTreeNode* node=GetDataTreeNode();
  iilPicImage*& image = renderinfo.m_iilImage;

  if(
      (image == NULL) ||
      (renderinfo.m_RendererId < 0) ||
      (renderinfo.m_LastUpdateTime < node->GetMTime())
    )
    GenerateData(renderer);
  else
  if(
      (renderinfo.m_LastUpdateTime < renderer->GetWorldGeometry()->GetMTime())
      //&&
      //(renderinfo.m_LastUpdateTime < renderer->GetMTime())
    )
    GenerateData(renderer);
  else
  if(
      (renderinfo.m_LastUpdateTime < node->GetPropertyList()->GetMTime()) ||
      (renderinfo.m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime())
    )
  {
    ApplyProperties(renderer);
    // since we have checked that nothing important has changed, we can set m_LastUpdateTime
    // to the current time
    mitk::Image::Pointer output = this->GetOutput();
    output->Modified();
    renderinfo.m_LastUpdateTime=output->GetMTime();
  }
}
<commit_msg>fixed update problem<commit_after>#include "mitkImageMapper2D.h"
//#include "mitkRenderWindow.h"
#include "widget.h"
#include "picimage.h"
#include "pic2vtk.h"
#include "PlaneGeometry.h"
#include "BaseRenderer.h"
#include "DataTreeNode.h"

#include "mitkLookupTableProperty.h"
#include "mitkBoolProperty.h"
#include "mitkLevelWindowProperty.h"

#include "mitkRenderWindow.h"
#include "mitkAbstractTransformGeometry.h"

#include <vtkImageReslice.h>
#include <vtkTransform.h>
#include <vtkMatrix4x4.h>
#include <vtkLookupTable.h>

int mitk::ImageMapper2D::numRenderer = 0;

mitk::ImageMapper2D::ImageMapper2D() : m_SliceSelector(NULL)
{
  // Modify superclass default values, can be overridden by subclasses
  this->SetNumberOfRequiredInputs(1);

  m_SliceSelector = ImageSliceSelector::New();
  m_Reslicer = vtkImageReslice::New();

}

//##ModelId=3E32DCF60043
mitk::ImageMapper2D::~ImageMapper2D()
{
  //@FIXME: durch die folgende Zeile sollte doch wohl der desctructor von RendererInfo aufgerufen werden. Das passiert aber nie. Deshalb wird bei der Programm-Beendung auch das iilImage und damit die textur nicht rechtzeitig freigegeben und das Programm crashed.
  m_RendererInfo.clear();
}

//##ModelId=3E3D834B003A
void mitk::ImageMapper2D::GenerateData()
{

}

void mitk::ImageMapper2D::Paint(mitk::BaseRenderer * renderer)
{
  if(IsVisible(renderer)==false) return;

  RendererInfo& renderinfo=m_RendererInfo[renderer];
  iilPicImage*& image = renderinfo.m_iilImage;

  Update(renderer);

  const mitk::DisplayGeometry* displayGeometry = renderer->GetDisplayGeometry();

  Vector2D oldtopLeft=displayGeometry->GetOriginInUnits();
  Vector2D oldbottomRight=displayGeometry->GetOriginInUnits()+displayGeometry->GetSizeInUnits();

  Vector2D topLeft;
  Vector2D bottomRight;
  topLeft=displayGeometry->GetOriginInDisplayUnits();
  bottomRight=topLeft+displayGeometry->GetSizeInDisplayUnits();

  displayGeometry->DisplayToMM(topLeft, topLeft); topLeft.x*=renderinfo.m_PixelsPerMM.x;  topLeft.y*=renderinfo.m_PixelsPerMM.y;
  displayGeometry->DisplayToMM(bottomRight, bottomRight); bottomRight.x*=renderinfo.m_PixelsPerMM.x;  bottomRight.y*=renderinfo.m_PixelsPerMM.y;

  //test - small differences noticed for unisotropic datasets.
  if((Vector2D(oldtopLeft-topLeft).length()>0.1) || (Vector2D(oldbottomRight-bottomRight).length()>0.1))
  {
    bottomRight*=1.0;
  }

  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();
  gluOrtho2D(topLeft.x, bottomRight.x, topLeft.y, bottomRight.y );
  glMatrixMode( GL_MODELVIEW );

  GLdouble eqn0[4] = {0.0, 1.0, 0.0, 0.0};
  GLdouble eqn1[4] = {1.0, 0.0, 0.0, 0.0};
  GLdouble eqn2[4] = {-1.0, 0.0 , 0.0, image->width()};
  GLdouble eqn3[4] = {0, -1.0, 0.0, image->height() };

  glClipPlane (GL_CLIP_PLANE0, eqn0);
  glEnable (GL_CLIP_PLANE0);
  glClipPlane (GL_CLIP_PLANE1, eqn1);
  glEnable (GL_CLIP_PLANE1);
  glClipPlane (GL_CLIP_PLANE2, eqn2);
  glEnable (GL_CLIP_PLANE2);
  glClipPlane (GL_CLIP_PLANE3, eqn3);
  glEnable (GL_CLIP_PLANE3);

  image->display(renderer->GetRenderWindow());

  glDisable (GL_CLIP_PLANE0);
  glDisable (GL_CLIP_PLANE1);
  glDisable (GL_CLIP_PLANE2);
  glDisable (GL_CLIP_PLANE3);

  glPushMatrix ();
  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();
  gluOrtho2D(0, displayGeometry->GetDisplayWidth(), 0, displayGeometry->GetDisplayHeight() );
  glMatrixMode( GL_MODELVIEW );
  glPopMatrix ();
}

//##ModelId=3E3D834B0008
const mitk::ImageMapper2D::InputImageType *mitk::ImageMapper2D::GetInput(void)
{
  if (this->GetNumberOfInputs() < 1)
  {
    return 0;
  }

  return static_cast<const mitk::ImageMapper2D::InputImageType * >
    ( GetData() );
}

//##ModelId=3E6E83B00343
int mitk::ImageMapper2D::GetAssociatedChannelNr(mitk::BaseRenderer *renderer)
{
  RendererInfo& renderinfo=m_RendererInfo[renderer];
  if(renderinfo.m_RendererId < 0)
    renderinfo.m_RendererId = ImageMapper2D::numRenderer++;

  return renderinfo.m_RendererId;
}

//##ModelId=3E8607D20380
void mitk::ImageMapper2D::GenerateOutputInformation()
{
  mitk::Image::Pointer output = this->GetOutput();
  mitk::PixelType pt(typeid(int));
  unsigned int dim[]={256,256};
  output->Initialize(mitk::PixelType(typeid(short int)), 2, dim, 10);
}

//##ModelId=3ED932B00140
void mitk::ImageMapper2D::GenerateData(mitk::BaseRenderer *renderer)
{
  RendererInfo& renderinfo=m_RendererInfo[renderer];

  iilPicImage*& image = renderinfo.m_iilImage;

  mitk::Image::Pointer input  = const_cast<mitk::ImageMapper2D::InputImageType *>(this->GetInput());

  if(image!= NULL)
  {
    delete image;
    image = NULL;
  }

  if(renderinfo.m_Pic)
  {
    ipPicFree(renderinfo.m_Pic);
    renderinfo.m_Pic = NULL;
  }

  if(renderinfo.m_RendererId < 0)
    renderinfo.m_RendererId = ImageMapper2D::numRenderer++;

  if(input.IsNotNull())
  {
    vtkImageData* inputData = input->GetVtkImageData();
    const PlaneView* planeview=NULL;

    const Geometry2D* worldgeometry = renderer->GetWorldGeometry();

    if(dynamic_cast<const PlaneGeometry *>(worldgeometry)!=NULL)
    {
      planeview=&dynamic_cast<const PlaneGeometry *>(worldgeometry)->GetPlaneView();
      m_Reslicer->SetResliceTransform(NULL);
    }
    else
      if(dynamic_cast<const AbstractTransformGeometry *>(worldgeometry)!=NULL)
      {
        const AbstractTransformGeometry *abstractGeometry=dynamic_cast<const AbstractTransformGeometry *>(worldgeometry);
        planeview=&abstractGeometry->GetPlaneView();
        m_Reslicer->SetResliceTransform(abstractGeometry->GetVtkAbstractTransform());
        //m_Reslicer->DebugOn();
      }
      else
        return;

    assert(planeview!=NULL);
    assert(planeview->normal.length()>0.1);

    vtkMatrix4x4* geometry = vtkMatrix4x4::New();
    geometry->Identity();

    m_Reslicer->SetInput(inputData);
    m_Reslicer->SetOutputDimensionality(2);
    m_Reslicer->SetOutputOrigin(0,0,0);

    m_Reslicer->SetBackgroundLevel(-1024);

    int width, height;
    width=worldgeometry->GetWidthInUnits();
    height=worldgeometry->GetHeightInUnits();
    renderinfo.m_PixelsPerMM.set(planeview->getLengthOfOrientation1()/width, planeview->getLengthOfOrientation2()/height);

    m_Reslicer->SetOutputSpacing(renderinfo.m_PixelsPerMM.x, renderinfo.m_PixelsPerMM.y, 1.0);
    m_Reslicer->SetOutputExtent(0.0, width-1, 0.0, height-1, 0.0, 1.0);

    double origin[3];
    origin[0]=planeview->point.x;
    origin[1]=planeview->point.y;
    origin[2]=planeview->point.z;

    m_Reslicer->SetResliceAxes(geometry);
    m_Reslicer->SetResliceAxesOrigin(origin);
    //        m_Reslicer->SetInterpolationModeToLinear();
    double cosines[9];
    Vector3f orient1 = planeview->getOrientation1();
    orient1.normalize();

    Vector3f orient2 = planeview->getOrientation2();
    orient2.normalize();

    // Richtung der X-Achse der Ergebnisschicht im Volumen,
    cosines[0]=orient1.x;
    cosines[1]=orient1.y;
    cosines[2]=orient1.z;

    //Richtung der Y-Achse der Ergebnisschicht im Volumen
    cosines[3]=orient2.x;
    cosines[4]=orient2.y;
    cosines[5]=orient2.z;

    // Schichtfolge/Projektionsrichtung
    cosines[6]= planeview->normal.x;
    cosines[7]= planeview->normal.y;
    cosines[8]= planeview->normal.z;
    m_Reslicer->SetResliceAxesDirectionCosines(cosines);

    m_Reslicer->Update();

    vtkImageData* vtkoutput = m_Reslicer->GetOutput();

    assert(vtkoutput);

    //	std::cout << vtkoutput <<std::endl;
    ipPicDescriptor* pic = Pic2vtk::convert(vtkoutput);
    assert(pic);
    if(pic->dim==1)
    {
      pic->dim=2;
      pic->n[1]=1;
    }
    assert(pic->dim == 2);

    renderinfo.m_Pic = pic;

    //std::cout << "Pic dimensions:" << pic->dim << std::endl;

    image = new iilPicImage(NULL, "ll", 512);

    ApplyProperties(renderer);
//   image->setImage(pic, iilImage::INTENSITY_ALPHA);
	  image->setImage(pic, m_iilMode);
    image->setInterpolation(true);
    image->setRegion(0,0,pic->n[0],pic->n[1]);

    mitk::Image::Pointer output = this->GetOutput();

    //if(renderinfo.m_RendererId < 10)
    //	output->SetPicSlice(pic,0,0,renderinfo.m_RendererId);
    output->Modified();
    renderinfo.m_LastUpdateTime=output->GetMTime();
  }
  return;
}

void mitk::ImageMapper2D::GenerateAllData()
{
  std::map<mitk::BaseRenderer*,RendererInfo>::iterator it=m_RendererInfo.begin();
  for(;it!=m_RendererInfo.end();++it)
    Update(it->first);
}

void mitk::ImageMapper2D::ApplyProperties(mitk::BaseRenderer* renderer)
{
  RendererInfo& renderinfo=m_RendererInfo[renderer];
  iilPicImage*& image = renderinfo.m_iilImage;

  assert(image != NULL);

  float rgba[4]={1.0f,1.0f,1.0f,1.0f};
  // check for color prop and use it for rendering if it exists
  GetColor(rgba, renderer);
  // check for opacity prop and use it for rendering if it exists
  GetOpacity(rgba[3], renderer);

  mitk::LevelWindow levelWindow;
  // check for level window prop and use it for display if it exists
  GetLevelWindow(levelWindow, renderer);

  mitk::LookupTableProperty::Pointer LookupTable;
  LookupTable = dynamic_cast<mitk::LookupTableProperty*>(this->GetDataTreeNode()->GetProperty("LookupTable").GetPointer());
	if (LookupTable.IsNull() )
	{
		m_iilMode = iilImage::INTENSITY_ALPHA;
	  image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]);
	}
	else {
		m_iilMode = iilImage::COLOR_ALPHA;
		image->setColors(LookupTable->GetLookupTable().GetRawLookupTable());
	}

  mitk::BoolProperty::Pointer binary;
  binary = dynamic_cast<mitk::BoolProperty*>(this->GetDataTreeNode()->GetProperty("binary").GetPointer());

  mitk::LevelWindowProperty::Pointer overwriteLevelWindow;
  overwriteLevelWindow = dynamic_cast<mitk::LevelWindowProperty*>(this->GetDataTreeNode()->GetProperty("levelWindow").GetPointer());

  if (binary.IsNotNull() )
  {
    image->setExtrema(0, 1);
  }
  else if (overwriteLevelWindow.IsNotNull() )
  {
    image->setExtrema(overwriteLevelWindow->GetLevelWindow().GetMin(), overwriteLevelWindow->GetLevelWindow().GetMax());
  }
  else
  {
  // set the properties
    image->setExtrema(levelWindow.GetMin(), levelWindow.GetMax());
  }
//  image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]);
}

void mitk::ImageMapper2D::Update(mitk::BaseRenderer* renderer)
{

  RendererInfo& renderinfo=m_RendererInfo[renderer];
  DataTreeNode* node=GetDataTreeNode();
  iilPicImage*& image = renderinfo.m_iilImage;

  if(
      (image == NULL) ||
      (renderinfo.m_RendererId < 0) ||
      (renderinfo.m_LastUpdateTime < node->GetMTime()) ||
      (renderinfo.m_LastUpdateTime < renderer->GetMTime())
    )
    GenerateData(renderer);
  else
  if(
      (renderinfo.m_LastUpdateTime < renderer->GetWorldGeometry()->GetMTime())
      //&&
      //(renderinfo.m_LastUpdateTime < renderer->GetMTime())
    )
    GenerateData(renderer);
  else
  if(
      (renderinfo.m_LastUpdateTime < node->GetPropertyList()->GetMTime()) ||
      (renderinfo.m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime())
    )
  {
    ApplyProperties(renderer);
    // since we have checked that nothing important has changed, we can set m_LastUpdateTime
    // to the current time
    mitk::Image::Pointer output = this->GetOutput();
    output->Modified();
    renderinfo.m_LastUpdateTime=output->GetMTime();
  }
}
<|endoftext|>