text
stringlengths 54
60.6k
|
|---|
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinamountfield.h"
#include "qvaluecombobox.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QDoubleSpinBox>
#include <QApplication>
#include <qmath.h> // for qPow()
BitcoinAmountField::BitcoinAmountField(QWidget *parent):
QWidget(parent), amount(0), currentUnit(-1)
{
amount = new QDoubleSpinBox(this);
amount->setLocale(QLocale::c());
amount->setDecimals(8);
amount->installEventFilter(this);
amount->setMaximumWidth(170);
amount->setSingleStep(0.001);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(amount);
unit = new QValueComboBox(this);
unit->setModel(new BitcoinUnits(this));
layout->addWidget(unit);
layout->addStretch(1);
layout->setContentsMargins(0,0,0,0);
setLayout(layout);
setFocusPolicy(Qt::TabFocus);
setFocusProxy(amount);
// If one if the widgets changes, the combined content changes as well
connect(amount, SIGNAL(valueChanged(QString)), this, SIGNAL(textChanged()));
connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int)));
// Set default based on configuration
unitChanged(unit->currentIndex());
}
void BitcoinAmountField::setText(const QString &text)
{
if (text.isEmpty())
amount->clear();
else
amount->setValue(text.toDouble());
}
void BitcoinAmountField::clear()
{
amount->clear();
unit->setCurrentIndex(0);
}
bool BitcoinAmountField::validate()
{
bool valid = true;
if (amount->value() == 0.0)
valid = false;
if (valid && !BitcoinUnits::parse(currentUnit, text(), 0))
valid = false;
setValid(valid);
return valid;
}
void BitcoinAmountField::setValid(bool valid)
{
if (valid)
amount->setStyleSheet("");
else
amount->setStyleSheet(STYLE_INVALID);
}
QString BitcoinAmountField::text() const
{
if (amount->text().isEmpty())
return QString();
else
return amount->text();
}
bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::FocusIn)
{
// Clear invalid flag on focus
setValid(true);
}
else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Comma)
{
// Translate a comma into a period
QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count());
QApplication::sendEvent(object, &periodKeyEvent);
return true;
}
}
return QWidget::eventFilter(object, event);
}
QWidget *BitcoinAmountField::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, amount);
return amount;
}
qint64 BitcoinAmountField::value(bool *valid_out) const
{
qint64 val_out = 0;
bool valid = BitcoinUnits::parse(currentUnit, text(), &val_out);
if(valid_out)
{
*valid_out = valid;
}
return val_out;
}
void BitcoinAmountField::setValue(qint64 value)
{
setText(BitcoinUnits::format(currentUnit, value));
}
void BitcoinAmountField::unitChanged(int idx)
{
// Use description tooltip for current unit for the combobox
unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString());
// Determine new unit ID
int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt();
// Parse current value and convert to new unit
bool valid = false;
qint64 currentValue = value(&valid);
currentUnit = newUnit;
// Set max length after retrieving the value, to prevent truncation
amount->setDecimals(BitcoinUnits::decimals(currentUnit));
amount->setMaximum(qPow(10, BitcoinUnits::amountDigits(currentUnit)) - qPow(10, -amount->decimals()));
if(currentUnit == BitcoinUnits::uBTC)
amount->setSingleStep(0.01);
else
amount->setSingleStep(0.001);
if(valid)
{
// If value was valid, re-place it in the widget with the new unit
setValue(currentValue);
}
else
{
// If current value is invalid, just clear field
setText("");
}
setValid(true);
}
void BitcoinAmountField::setDisplayUnit(int newUnit)
{
unit->setValue(newUnit);
}
<commit_msg>Fix bug in Qt wallet when parsing large amount in Reddcoin URI.<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinamountfield.h"
#include "util.h"
#include "qvaluecombobox.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QDoubleSpinBox>
#include <QApplication>
#include <qmath.h> // for qPow()
BitcoinAmountField::BitcoinAmountField(QWidget *parent):
QWidget(parent), amount(0), currentUnit(-1)
{
amount = new QDoubleSpinBox(this);
amount->setLocale(QLocale::c());
amount->setDecimals(8);
amount->installEventFilter(this);
amount->setMaximumWidth(170);
amount->setSingleStep(0.001);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(amount);
unit = new QValueComboBox(this);
unit->setModel(new BitcoinUnits(this));
layout->addWidget(unit);
layout->addStretch(1);
layout->setContentsMargins(0,0,0,0);
setLayout(layout);
setFocusPolicy(Qt::TabFocus);
setFocusProxy(amount);
// If one if the widgets changes, the combined content changes as well
connect(amount, SIGNAL(valueChanged(QString)), this, SIGNAL(textChanged()));
connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int)));
// Set default based on configuration
unitChanged(unit->currentIndex());
}
void BitcoinAmountField::setText(const QString &text)
{
if (text.isEmpty())
{
amount->clear();
}
else
{
// remove the space delimiter for every 3 digits
QString value = text;
amount->setValue(value.replace(" ", "").toDouble());
}
}
void BitcoinAmountField::clear()
{
amount->clear();
unit->setCurrentIndex(0);
}
bool BitcoinAmountField::validate()
{
bool valid = true;
if (amount->value() == 0.0)
valid = false;
if (valid && !BitcoinUnits::parse(currentUnit, text(), 0))
valid = false;
setValid(valid);
return valid;
}
void BitcoinAmountField::setValid(bool valid)
{
if (valid)
amount->setStyleSheet("");
else
amount->setStyleSheet(STYLE_INVALID);
}
QString BitcoinAmountField::text() const
{
if (amount->text().isEmpty())
return QString();
else
return amount->text();
}
bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::FocusIn)
{
// Clear invalid flag on focus
setValid(true);
}
else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Comma)
{
// Translate a comma into a period
QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count());
QApplication::sendEvent(object, &periodKeyEvent);
return true;
}
}
return QWidget::eventFilter(object, event);
}
QWidget *BitcoinAmountField::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, amount);
return amount;
}
qint64 BitcoinAmountField::value(bool *valid_out) const
{
qint64 val_out = 0;
bool valid = BitcoinUnits::parse(currentUnit, text(), &val_out);
if(valid_out)
{
*valid_out = valid;
}
return val_out;
}
void BitcoinAmountField::setValue(qint64 value)
{
setText(BitcoinUnits::format(currentUnit, value));
}
void BitcoinAmountField::unitChanged(int idx)
{
// Use description tooltip for current unit for the combobox
unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString());
// Determine new unit ID
int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt();
// Parse current value and convert to new unit
bool valid = false;
qint64 currentValue = value(&valid);
currentUnit = newUnit;
// Set max length after retrieving the value, to prevent truncation
amount->setDecimals(BitcoinUnits::decimals(currentUnit));
amount->setMaximum(qPow(10, BitcoinUnits::amountDigits(currentUnit)) - qPow(10, -amount->decimals()));
if(currentUnit == BitcoinUnits::uBTC)
amount->setSingleStep(0.01);
else
amount->setSingleStep(0.001);
if(valid)
{
// If value was valid, re-place it in the widget with the new unit
setValue(currentValue);
}
else
{
// If current value is invalid, just clear field
setText("");
}
setValid(true);
}
void BitcoinAmountField::setDisplayUnit(int newUnit)
{
unit->setValue(newUnit);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "receivecoinsdialog.h"
#include "ui_receivecoinsdialog.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "receivefreezedialog.h"
#include "receiverequestdialog.h"
#include "recentrequeststablemodel.h"
#include "unlimited.h"
ReceiveFreezeDialog *freezeDialog;
#include <QAction>
#include <QCheckBox>
#include <QCursor>
#include <QItemSelection>
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
ReceiveCoinsDialog::ReceiveCoinsDialog(const PlatformStyle *platformStyle, QWidget *parent)
: QDialog(parent), ui(new Ui::ReceiveCoinsDialog), model(0), platformStyle(platformStyle)
{
ui->setupUi(this);
if (!platformStyle->getImagesOnButtons())
{
ui->clearButton->setIcon(QIcon());
ui->receiveButton->setIcon(QIcon());
ui->showRequestButton->setIcon(QIcon());
ui->removeRequestButton->setIcon(QIcon());
}
else
{
ui->clearButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
ui->receiveButton->setIcon(platformStyle->SingleColorIcon(":/icons/receiving_addresses"));
ui->showRequestButton->setIcon(platformStyle->SingleColorIcon(":/icons/edit"));
ui->removeRequestButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
}
// context menu actions
QAction *copyAddressAction = new QAction(tr("Copy address"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyMessageAction = new QAction(tr("Copy message"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
// context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyMessageAction);
contextMenu->addAction(copyAmountAction);
// context menu signals
connect(ui->recentRequestsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(copyMessage()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// initialize freeze
nFreezeLockTime = CScriptNum(0);
}
void ReceiveCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
if (model && model->getOptionsModel())
{
model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder);
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateDisplayUnit();
QTableView *tableView = ui->recentRequestsView;
tableView->verticalHeader()->hide();
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
tableView->setModel(model->getRecentRequestsTableModel());
tableView->setAlternatingRowColors(true);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::ContiguousSelection);
tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH);
connect(tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this,
SLOT(recentRequestsView_selectionChanged(QItemSelection, QItemSelection)));
// Last 2 columns are set by the columnResizingFixer, when the table geometry is ready.
columnResizingFixer =
new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH);
}
}
ReceiveCoinsDialog::~ReceiveCoinsDialog() { delete ui; }
void ReceiveCoinsDialog::clear()
{
ui->reqAmount->clear();
ui->reqLabel->setText("");
ui->reqMessage->setText("");
ui->reuseAddress->setChecked(false);
ui->freezeCheck->setChecked(false);
ui->freezeCheck->setText("Coin &Freeze");
nFreezeLockTime = CScriptNum(0);
freezeDialog = NULL;
updateDisplayUnit();
}
void ReceiveCoinsDialog::reject() { clear(); }
void ReceiveCoinsDialog::accept() { clear(); }
void ReceiveCoinsDialog::updateDisplayUnit()
{
if (model && model->getOptionsModel())
{
ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
void ReceiveCoinsDialog::on_freezeDialog_hide()
{
freezeDialog->getFreezeLockTime(nFreezeLockTime);
if (nFreezeLockTime == 0)
{
// user cancelled freeze
ui->freezeCheck->setChecked(false);
ui->freezeCheck->setText("Coin Freeze");
}
else
{
// user selected freeze
ui->freezeCheck->setChecked(true);
QString freezeLabel;
if (nFreezeLockTime.getint64() < LOCKTIME_THRESHOLD)
{
uint64_t height = GetBlockchainHeight();
uint64_t freezeHeight = nFreezeLockTime.getint();
uint64_t approxTimeMs =
((freezeHeight - height) * 10 * 60 * 1000) + QDateTime::currentDateTime().toMSecsSinceEpoch();
freezeLabel = (QString)("block: ") + QString::number(freezeHeight) + (QString)(" (approximately: ") +
QDateTime::fromMSecsSinceEpoch(approxTimeMs).date().toString() + ")";
}
else
freezeLabel =
QDateTime::fromMSecsSinceEpoch(nFreezeLockTime.getint64() * 1000).toString("yyyy/MM/dd hh:mm");
ui->freezeCheck->setText("Coin freeze until " + freezeLabel);
}
}
void ReceiveCoinsDialog::on_freezeCheck_clicked()
{
if (ui->freezeCheck->isChecked()) // If the user clicked on coin freeze, bring up the freeze dialog box
{
if (!freezeDialog)
{
freezeDialog = new ReceiveFreezeDialog(this);
freezeDialog->setModel(model->getOptionsModel());
}
freezeDialog->show();
}
else // if the user unchecked, then hide the freeze dialog if its still showing
{
if (freezeDialog)
freezeDialog->hide();
}
}
void ReceiveCoinsDialog::on_receiveButton_clicked()
{
if (!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel())
return;
QString address;
QString label = ui->reqLabel->text();
QString sFreezeLockTime = "";
if (ui->reuseAddress->isChecked())
{
/* Choose existing receiving address */
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
address = dlg.getReturnValue();
if (label.isEmpty()) /* If no label provided, use the previously used label */
{
label = model->getAddressTableModel()->labelForAddress(address);
}
}
else
{
return;
}
}
else
{
/* Generate new receiving address and add to the address table */
address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", CScriptNum(0));
// only use coin freeze if the freeze value is valid and the check box is still set
if ((nFreezeLockTime > 0) && (ui->freezeCheck) && (ui->freezeCheck->isChecked()))
{
/* Generate the freeze redeemScript and add to the address table.
* The address variable needs to show the freeze P2SH public key */
address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", nFreezeLockTime);
sFreezeLockTime = model->getAddressTableModel()->labelForFreeze(address);
}
}
SendCoinsRecipient info(address, label, ui->reqAmount->value(), ui->reqMessage->text(), sFreezeLockTime, "");
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setModel(model->getOptionsModel());
dialog->setInfo(info);
dialog->show();
clear();
/* Store request for later reference */
model->getRecentRequestsTableModel()->addNewRequest(info);
}
void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &index)
{
const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel();
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setModel(model->getOptionsModel());
dialog->setInfo(submodel->entry(index.row()).recipient);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
void ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection &selected,
const QItemSelection &deselected)
{
// Enable Show/Remove buttons only if anything is selected.
bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty();
ui->showRequestButton->setEnabled(enable);
ui->removeRequestButton->setEnabled(enable);
}
void ReceiveCoinsDialog::on_showRequestButton_clicked()
{
if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
Q_FOREACH (const QModelIndex &index, selection)
{
on_recentRequestsView_doubleClicked(index);
}
}
void ReceiveCoinsDialog::on_removeRequestButton_clicked()
{
if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if (selection.empty())
return;
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent());
}
// We override the virtual resizeEvent of the QWidget to adjust tables column
// sizes as the tables width is proportional to the dialogs width.
void ReceiveCoinsDialog::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message);
}
void ReceiveCoinsDialog::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Return)
{
// press return -> submit form
if (ui->reqLabel->hasFocus() || ui->reqAmount->hasFocus() || ui->reqMessage->hasFocus())
{
event->ignore();
on_receiveButton_clicked();
return;
}
}
this->QDialog::keyPressEvent(event);
}
// copy column of selected row to clipboard
void ReceiveCoinsDialog::copyColumnToClipboard(int column)
{
if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if (selection.empty())
return;
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
GUIUtil::setClipboard(model->getRecentRequestsTableModel()
->data(firstIndex.child(firstIndex.row(), column), Qt::EditRole)
.toString());
}
// context menu
void ReceiveCoinsDialog::showMenu(const QPoint &point)
{
if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if (selection.empty())
return;
contextMenu->exec(QCursor::pos());
}
// context menu action: copy address
void ReceiveCoinsDialog::copyAddress() { copyColumnToClipboard(RecentRequestsTableModel::Address); }
// context menu action: copy label
void ReceiveCoinsDialog::copyLabel() { copyColumnToClipboard(RecentRequestsTableModel::Label); }
// context menu action: copy message
void ReceiveCoinsDialog::copyMessage() { copyColumnToClipboard(RecentRequestsTableModel::Message); }
// context menu action: copy amount
void ReceiveCoinsDialog::copyAmount() { copyColumnToClipboard(RecentRequestsTableModel::Amount); }
<commit_msg>Bug Fix for Coin Freeze when making payment request (#875)<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "receivecoinsdialog.h"
#include "ui_receivecoinsdialog.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "receivefreezedialog.h"
#include "receiverequestdialog.h"
#include "recentrequeststablemodel.h"
#include "unlimited.h"
ReceiveFreezeDialog *freezeDialog;
#include <QAction>
#include <QCheckBox>
#include <QCursor>
#include <QItemSelection>
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
ReceiveCoinsDialog::ReceiveCoinsDialog(const PlatformStyle *platformStyle, QWidget *parent)
: QDialog(parent), ui(new Ui::ReceiveCoinsDialog), model(0), platformStyle(platformStyle)
{
ui->setupUi(this);
if (!platformStyle->getImagesOnButtons())
{
ui->clearButton->setIcon(QIcon());
ui->receiveButton->setIcon(QIcon());
ui->showRequestButton->setIcon(QIcon());
ui->removeRequestButton->setIcon(QIcon());
}
else
{
ui->clearButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
ui->receiveButton->setIcon(platformStyle->SingleColorIcon(":/icons/receiving_addresses"));
ui->showRequestButton->setIcon(platformStyle->SingleColorIcon(":/icons/edit"));
ui->removeRequestButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
}
// context menu actions
QAction *copyAddressAction = new QAction(tr("Copy address"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyMessageAction = new QAction(tr("Copy message"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
// context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyMessageAction);
contextMenu->addAction(copyAmountAction);
// context menu signals
connect(ui->recentRequestsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(copyMessage()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// initialize freeze
nFreezeLockTime = CScriptNum(0);
}
void ReceiveCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
if (model && model->getOptionsModel())
{
model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder);
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateDisplayUnit();
QTableView *tableView = ui->recentRequestsView;
tableView->verticalHeader()->hide();
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
tableView->setModel(model->getRecentRequestsTableModel());
tableView->setAlternatingRowColors(true);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::ContiguousSelection);
tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH);
connect(tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this,
SLOT(recentRequestsView_selectionChanged(QItemSelection, QItemSelection)));
// Last 2 columns are set by the columnResizingFixer, when the table geometry is ready.
columnResizingFixer =
new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH);
}
}
ReceiveCoinsDialog::~ReceiveCoinsDialog() { delete ui; }
void ReceiveCoinsDialog::clear()
{
ui->reqAmount->clear();
ui->reqLabel->setText("");
ui->reqMessage->setText("");
ui->reuseAddress->setChecked(false);
ui->freezeCheck->setChecked(false);
ui->freezeCheck->setText("Coin &Freeze");
nFreezeLockTime = CScriptNum(0);
freezeDialog = NULL;
updateDisplayUnit();
}
void ReceiveCoinsDialog::reject() { clear(); }
void ReceiveCoinsDialog::accept() { clear(); }
void ReceiveCoinsDialog::updateDisplayUnit()
{
if (model && model->getOptionsModel())
{
ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
void ReceiveCoinsDialog::on_freezeDialog_hide()
{
freezeDialog->getFreezeLockTime(nFreezeLockTime);
if (nFreezeLockTime == 0)
{
// user cancelled freeze
ui->freezeCheck->setChecked(false);
ui->freezeCheck->setText("Coin Freeze");
}
else
{
// user selected freeze
ui->freezeCheck->setChecked(true);
QString freezeLabel;
if (nFreezeLockTime.getint64() < LOCKTIME_THRESHOLD)
{
uint64_t height = GetBlockchainHeight();
uint64_t freezeHeight = nFreezeLockTime.getint();
uint64_t approxTimeMs =
((freezeHeight - height) * 10 * 60 * 1000) + QDateTime::currentDateTime().toMSecsSinceEpoch();
freezeLabel = (QString)("block: ") + QString::number(freezeHeight) + (QString)(" (approximately: ") +
QDateTime::fromMSecsSinceEpoch(approxTimeMs).date().toString() + ")";
}
else
freezeLabel =
QDateTime::fromMSecsSinceEpoch(nFreezeLockTime.getint64() * 1000).toString("yyyy/MM/dd hh:mm");
ui->freezeCheck->setText("Coin freeze until " + freezeLabel);
}
}
void ReceiveCoinsDialog::on_freezeCheck_clicked()
{
if (ui->freezeCheck->isChecked()) // If the user clicked on coin freeze, bring up the freeze dialog box
{
if (!freezeDialog)
{
freezeDialog = new ReceiveFreezeDialog(this);
freezeDialog->setModel(model->getOptionsModel());
}
freezeDialog->show();
}
else // if the user unchecked, then hide the freeze dialog if its still showing
{
if (freezeDialog)
freezeDialog->hide();
}
}
void ReceiveCoinsDialog::on_receiveButton_clicked()
{
if (!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel())
return;
QString address;
QString label = ui->reqLabel->text();
QString sFreezeLockTime = "";
if (ui->reuseAddress->isChecked())
{
/* Choose existing receiving address */
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
address = dlg.getReturnValue();
if (label.isEmpty()) /* If no label provided, use the previously used label */
{
label = model->getAddressTableModel()->labelForAddress(address);
}
}
else
{
return;
}
}
else
{
// only use coin freeze if the freeze value is valid and the check box is still set
if ((nFreezeLockTime > 0) && (ui->freezeCheck) && (ui->freezeCheck->isChecked()))
{
/* Generate the freeze redeemScript and add to the address table.
* The address variable needs to show the freeze P2SH public key */
address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", nFreezeLockTime);
sFreezeLockTime = model->getAddressTableModel()->labelForFreeze(address);
}
else
{
/* Generate new receiving address and add to the address table */
address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", CScriptNum(0));
}
}
SendCoinsRecipient info(address, label, ui->reqAmount->value(), ui->reqMessage->text(), sFreezeLockTime, "");
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setModel(model->getOptionsModel());
dialog->setInfo(info);
dialog->show();
clear();
/* Store request for later reference */
model->getRecentRequestsTableModel()->addNewRequest(info);
}
void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &index)
{
const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel();
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setModel(model->getOptionsModel());
dialog->setInfo(submodel->entry(index.row()).recipient);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
void ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection &selected,
const QItemSelection &deselected)
{
// Enable Show/Remove buttons only if anything is selected.
bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty();
ui->showRequestButton->setEnabled(enable);
ui->removeRequestButton->setEnabled(enable);
}
void ReceiveCoinsDialog::on_showRequestButton_clicked()
{
if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
Q_FOREACH (const QModelIndex &index, selection)
{
on_recentRequestsView_doubleClicked(index);
}
}
void ReceiveCoinsDialog::on_removeRequestButton_clicked()
{
if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if (selection.empty())
return;
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent());
}
// We override the virtual resizeEvent of the QWidget to adjust tables column
// sizes as the tables width is proportional to the dialogs width.
void ReceiveCoinsDialog::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message);
}
void ReceiveCoinsDialog::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Return)
{
// press return -> submit form
if (ui->reqLabel->hasFocus() || ui->reqAmount->hasFocus() || ui->reqMessage->hasFocus())
{
event->ignore();
on_receiveButton_clicked();
return;
}
}
this->QDialog::keyPressEvent(event);
}
// copy column of selected row to clipboard
void ReceiveCoinsDialog::copyColumnToClipboard(int column)
{
if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if (selection.empty())
return;
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
GUIUtil::setClipboard(model->getRecentRequestsTableModel()
->data(firstIndex.child(firstIndex.row(), column), Qt::EditRole)
.toString());
}
// context menu
void ReceiveCoinsDialog::showMenu(const QPoint &point)
{
if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if (selection.empty())
return;
contextMenu->exec(QCursor::pos());
}
// context menu action: copy address
void ReceiveCoinsDialog::copyAddress() { copyColumnToClipboard(RecentRequestsTableModel::Address); }
// context menu action: copy label
void ReceiveCoinsDialog::copyLabel() { copyColumnToClipboard(RecentRequestsTableModel::Label); }
// context menu action: copy message
void ReceiveCoinsDialog::copyMessage() { copyColumnToClipboard(RecentRequestsTableModel::Message); }
// context menu action: copy amount
void ReceiveCoinsDialog::copyAmount() { copyColumnToClipboard(RecentRequestsTableModel::Amount); }
<|endoftext|>
|
<commit_before>#include "sendmessagesdialog.h"
#include "ui_sendmessagesdialog.h"
//#include "init.h"
#include "walletmodel.h"
#include "messagemodel.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "sendmessagesentry.h"
//#include "guiutil.h"
#include <QMessageBox>
#include <QLocale>
#include <QTextDocument>
#include <QScrollBar>
#include <QClipboard>
#include <QDataWidgetMapper>
SendMessagesDialog::SendMessagesDialog(Mode mode, Type type, QWidget *parent) :
QDialog(parent),
ui(new Ui::SendMessagesDialog),
model(0),
mode(mode),
type(type)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
if(mode == SendMessagesDialog::Encrypted)
ui->addressFrom->setPlaceholderText(tr("Enter a DarkCoin address (e.g. FECqNjwb99MC7nTHM1iQKpL9RGZAAiVPnz)"));
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(reject()));
fNewRecipientAllowed = true;
if(mode == SendMessagesDialog::Anonymous)
ui->frameAddressFrom->hide();
if(type == SendMessagesDialog::Page)
ui->closeButton->hide();
}
void SendMessagesDialog::setModel(MessageModel *model)
{
this->model = model;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendMessagesEntry *entry = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
entry->setModel(model);
}
}
void SendMessagesDialog::loadRow(int row)
{
if(model->data(model->index(row, model->Type, QModelIndex()), Qt::DisplayRole).toString() == MessageModel::Received)
ui->addressFrom->setText(model->data(model->index(row, model->ToAddress, QModelIndex()), Qt::DisplayRole).toString());
else
ui->addressFrom->setText(model->data(model->index(row, model->FromAddress, QModelIndex()), Qt::DisplayRole).toString());
for(int i = 0; i < ui->entries->count(); ++i)
{
SendMessagesEntry *entry = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
entry->loadRow(row);
}
}
bool SendMessagesDialog::checkMode(Mode mode)
{
return (mode == this->mode);
}
bool SendMessagesDialog::validate()
{
if(mode == SendMessagesDialog::Encrypted && ui->addressFrom->text() == "")
{
ui->addressFrom->setValid(false);
return false;
}
return true;
}
SendMessagesDialog::~SendMessagesDialog()
{
delete ui;
}
void SendMessagesDialog::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->addressFrom->setText(QApplication::clipboard()->text());
}
void SendMessagesDialog::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getWalletModel()->getAddressTableModel());
if(dlg.exec())
{
ui->addressFrom->setText(dlg.getReturnValue());
SendMessagesEntry *entry = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(0)->widget());
entry->setFocus();
// findChild( const QString "sentTo")->setFocus();
}
}
void SendMessagesDialog::on_sendButton_clicked()
{
QList<SendMessagesRecipient> recipients;
bool valid = true;
if(!model)
return;
valid = validate();
for(int i = 0; i < ui->entries->count(); ++i)
{
SendMessagesEntry *entry = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
recipients.append(entry->getValue());
else
valid = false;
}
}
if(!valid || recipients.isEmpty())
return;
// Format confirmation message
QStringList formatted;
foreach(const SendMessagesRecipient &rcp, recipients)
{
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(rcp.message, Qt::escape(rcp.label), rcp.address));
}
fNewRecipientAllowed = false;
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send messages"),
tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
MessageModel::StatusCode sendstatus;
if(mode == SendMessagesDialog::Anonymous)
sendstatus = model->sendMessages(recipients);
else
sendstatus = model->sendMessages(recipients, ui->addressFrom->text());
switch(sendstatus)
{
case MessageModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Message"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case MessageModel::InvalidMessage:
QMessageBox::warning(this, tr("Send Message"),
tr("The message can't be empty."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case MessageModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Message"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case MessageModel::MessageCreationFailed:
QMessageBox::warning(this, tr("Send Message"),
tr("Error: Message creation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case MessageModel::MessageCommitFailed:
QMessageBox::warning(this, tr("Send Message"),
tr("Error: The message was rejected."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case MessageModel::Aborted: // User aborted, nothing to do
break;
case MessageModel::FailedErrorShown: // Send failed, error message was displayed
break;
case MessageModel::OK:
accept();
break;
}
fNewRecipientAllowed = true;
}
void SendMessagesDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
delete ui->entries->takeAt(0)->widget();
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void SendMessagesDialog::reject()
{
if(type == SendMessagesDialog::Dialog)
done(1);
else
clear();
}
void SendMessagesDialog::accept()
{
if(type == SendMessagesDialog::Dialog)
done(0);
else
clear();
}
void SendMessagesDialog::done(int retval)
{
if(type == SendMessagesDialog::Dialog)
QDialog::done(retval);
else
clear();
}
SendMessagesEntry *SendMessagesDialog::addEntry()
{
SendMessagesEntry *entry = new SendMessagesEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendMessagesEntry*)), this, SLOT(removeEntry(SendMessagesEntry*)));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
QCoreApplication::instance()->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendMessagesDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
SendMessagesEntry *entry = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
entry->setRemoveEnabled(enabled);
}
setupTabChain(0);
}
void SendMessagesDialog::removeEntry(SendMessagesEntry* entry)
{
delete entry;
updateRemoveEnabled();
}
QWidget *SendMessagesDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendMessagesEntry *entry = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->addButton);
QWidget::setTabOrder(ui->addButton, ui->sendButton);
return ui->sendButton;
}
void SendMessagesDialog::pasteEntry(const SendMessagesRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendMessagesEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendMessagesEntry *first = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
entry = first;
}
if(!entry)
entry = addEntry();
entry->setValue(rv);
}
<commit_msg>Fixed sendmessagesdialog.cpp for Qt5<commit_after>#include "sendmessagesdialog.h"
#include "ui_sendmessagesdialog.h"
//#include "init.h"
#include "walletmodel.h"
#include "messagemodel.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "sendmessagesentry.h"
//#include "guiutil.h"
#include <QMessageBox>
#include <QLocale>
#include <QTextDocument>
#include <QScrollBar>
#include <QClipboard>
#include <QDataWidgetMapper>
SendMessagesDialog::SendMessagesDialog(Mode mode, Type type, QWidget *parent) :
QDialog(parent),
ui(new Ui::SendMessagesDialog),
model(0),
mode(mode),
type(type)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
if(mode == SendMessagesDialog::Encrypted)
ui->addressFrom->setPlaceholderText(tr("Enter a DarkCoin address (e.g. FECqNjwb99MC7nTHM1iQKpL9RGZAAiVPnz)"));
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(reject()));
fNewRecipientAllowed = true;
if(mode == SendMessagesDialog::Anonymous)
ui->frameAddressFrom->hide();
if(type == SendMessagesDialog::Page)
ui->closeButton->hide();
}
void SendMessagesDialog::setModel(MessageModel *model)
{
this->model = model;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendMessagesEntry *entry = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
entry->setModel(model);
}
}
void SendMessagesDialog::loadRow(int row)
{
if(model->data(model->index(row, model->Type, QModelIndex()), Qt::DisplayRole).toString() == MessageModel::Received)
ui->addressFrom->setText(model->data(model->index(row, model->ToAddress, QModelIndex()), Qt::DisplayRole).toString());
else
ui->addressFrom->setText(model->data(model->index(row, model->FromAddress, QModelIndex()), Qt::DisplayRole).toString());
for(int i = 0; i < ui->entries->count(); ++i)
{
SendMessagesEntry *entry = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
entry->loadRow(row);
}
}
bool SendMessagesDialog::checkMode(Mode mode)
{
return (mode == this->mode);
}
bool SendMessagesDialog::validate()
{
if(mode == SendMessagesDialog::Encrypted && ui->addressFrom->text() == "")
{
ui->addressFrom->setValid(false);
return false;
}
return true;
}
SendMessagesDialog::~SendMessagesDialog()
{
delete ui;
}
void SendMessagesDialog::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->addressFrom->setText(QApplication::clipboard()->text());
}
void SendMessagesDialog::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getWalletModel()->getAddressTableModel());
if(dlg.exec())
{
ui->addressFrom->setText(dlg.getReturnValue());
SendMessagesEntry *entry = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(0)->widget());
entry->setFocus();
// findChild( const QString "sentTo")->setFocus();
}
}
void SendMessagesDialog::on_sendButton_clicked()
{
QList<SendMessagesRecipient> recipients;
bool valid = true;
if(!model)
return;
valid = validate();
for(int i = 0; i < ui->entries->count(); ++i)
{
SendMessagesEntry *entry = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
recipients.append(entry->getValue());
else
valid = false;
}
}
if(!valid || recipients.isEmpty())
return;
// Format confirmation message
QStringList formatted;
foreach(const SendMessagesRecipient &rcp, recipients)
{
#if QT_VERSION < 0x050000
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(rcp.message, Qt::escape(rcp.label), rcp.address));
#else
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(rcp.message, rcp.label.toHtmlEscaped(), rcp.address));
#endif
}
fNewRecipientAllowed = false;
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send messages"),
tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
MessageModel::StatusCode sendstatus;
if(mode == SendMessagesDialog::Anonymous)
sendstatus = model->sendMessages(recipients);
else
sendstatus = model->sendMessages(recipients, ui->addressFrom->text());
switch(sendstatus)
{
case MessageModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Message"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case MessageModel::InvalidMessage:
QMessageBox::warning(this, tr("Send Message"),
tr("The message can't be empty."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case MessageModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Message"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case MessageModel::MessageCreationFailed:
QMessageBox::warning(this, tr("Send Message"),
tr("Error: Message creation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case MessageModel::MessageCommitFailed:
QMessageBox::warning(this, tr("Send Message"),
tr("Error: The message was rejected."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case MessageModel::Aborted: // User aborted, nothing to do
break;
case MessageModel::FailedErrorShown: // Send failed, error message was displayed
break;
case MessageModel::OK:
accept();
break;
}
fNewRecipientAllowed = true;
}
void SendMessagesDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
delete ui->entries->takeAt(0)->widget();
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void SendMessagesDialog::reject()
{
if(type == SendMessagesDialog::Dialog)
done(1);
else
clear();
}
void SendMessagesDialog::accept()
{
if(type == SendMessagesDialog::Dialog)
done(0);
else
clear();
}
void SendMessagesDialog::done(int retval)
{
if(type == SendMessagesDialog::Dialog)
QDialog::done(retval);
else
clear();
}
SendMessagesEntry *SendMessagesDialog::addEntry()
{
SendMessagesEntry *entry = new SendMessagesEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendMessagesEntry*)), this, SLOT(removeEntry(SendMessagesEntry*)));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
QCoreApplication::instance()->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendMessagesDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
SendMessagesEntry *entry = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
entry->setRemoveEnabled(enabled);
}
setupTabChain(0);
}
void SendMessagesDialog::removeEntry(SendMessagesEntry* entry)
{
delete entry;
updateRemoveEnabled();
}
QWidget *SendMessagesDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendMessagesEntry *entry = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->addButton);
QWidget::setTabOrder(ui->addButton, ui->sendButton);
return ui->sendButton;
}
void SendMessagesDialog::pasteEntry(const SendMessagesRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendMessagesEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendMessagesEntry *first = qobject_cast<SendMessagesEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
entry = first;
}
if(!entry)
entry = addEntry();
entry->setValue(rv);
}
<|endoftext|>
|
<commit_before>#include "trafficgraphwidget.h"
#include "clientmodel.h"
#include "optionsmodel.h"
#include <QPainter>
#include <QPainterPath>
#include <QColor>
#include <QTimer>
#include <cmath>
#define DESIRED_SAMPLES 800
#define XMARGIN 10
#define YMARGIN 10
TrafficGraphWidget::TrafficGraphWidget(QWidget *parent) :
QWidget(parent),
timer(0),
fMax(0.0f),
nMins(0),
vSamplesIn(),
vSamplesOut(),
nLastBytesIn(0),
nLastBytesOut(0),
clientModel(0)
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), SLOT(updateRates()));
}
void TrafficGraphWidget::setClientModel(ClientModel *model)
{
clientModel = model;
if(model) {
nLastBytesIn = model->getTotalBytesRecv();
nLastBytesOut = model->getTotalBytesSent();
}
}
int TrafficGraphWidget::getGraphRangeMins() const
{
return nMins;
}
void TrafficGraphWidget::paintPath(QPainterPath &path, QQueue<float> &samples)
{
int h = height() - YMARGIN * 2, w = width() - XMARGIN * 2;
int sampleCount = samples.size(), x = XMARGIN + w, y;
if(sampleCount > 0) {
path.moveTo(x, YMARGIN + h);
for(int i = 0; i < sampleCount; ++i) {
x = XMARGIN + w - w * i / DESIRED_SAMPLES;
y = YMARGIN + h - (int)(h * samples.at(i) / fMax);
path.lineTo(x, y);
}
path.lineTo(x, YMARGIN + h);
}
}
void TrafficGraphWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QColor background_color;
QColor axisCol;
// This is inelegant, but the easiest way to get the traffic graph to respect the stylesheets.
// Qt does not provide an easy way to use stylesheets with the low level QPainter class.
if (this->clientModel->getOptionsModel()->getCurrentStyle() == "dark")
{
background_color.setRgb(26, 38, 50);
axisCol.setRgb(174, 180, 182);
}
else
{
background_color.setRgb(235, 236, 238);
axisCol.setRgb(88, 92, 107);
}
painter.fillRect(rect(), background_color);
if(fMax <= 0.0f) return;
int h = height() - YMARGIN * 2;
painter.setPen(axisCol);
painter.drawLine(XMARGIN, YMARGIN + h, width() - XMARGIN, YMARGIN + h);
// decide what order of magnitude we are
int base = floor(log10(fMax));
float val = pow(10.0f, base);
// draw lines
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax, QString("%1 kB/s").arg(val));
for(float y = val; y < fMax; y += val) {
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
// if we drew 3 or fewer lines, break them up at the next lower order of magnitude
if(fMax / val <= 3.0f) {
axisCol = axisCol.darker();
val = pow(10.0f, base - 1);
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax, QString("%1 kB/s").arg(val));
int count = 1;
for(float y = val; y < fMax; y += val, count++) {
// don't overwrite lines drawn above
if(count % 10 == 0)
continue;
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
}
if(!vSamplesIn.empty()) {
QPainterPath p;
paintPath(p, vSamplesIn);
painter.fillPath(p, QColor(0, 255, 0, 128));
painter.setPen(Qt::green);
painter.drawPath(p);
}
if(!vSamplesOut.empty()) {
QPainterPath p;
paintPath(p, vSamplesOut);
painter.fillPath(p, QColor(255, 0, 0, 128));
painter.setPen(Qt::red);
painter.drawPath(p);
}
}
void TrafficGraphWidget::updateRates()
{
if(!clientModel) return;
quint64 bytesIn = clientModel->getTotalBytesRecv(),
bytesOut = clientModel->getTotalBytesSent();
float inRate = (bytesIn - nLastBytesIn) / 1024.0f * 1000 / timer->interval();
float outRate = (bytesOut - nLastBytesOut) / 1024.0f * 1000 / timer->interval();
vSamplesIn.push_front(inRate);
vSamplesOut.push_front(outRate);
nLastBytesIn = bytesIn;
nLastBytesOut = bytesOut;
while(vSamplesIn.size() > DESIRED_SAMPLES) {
vSamplesIn.pop_back();
}
while(vSamplesOut.size() > DESIRED_SAMPLES) {
vSamplesOut.pop_back();
}
float tmax = 0.0f;
foreach(float f, vSamplesIn) {
if(f > tmax) tmax = f;
}
foreach(float f, vSamplesOut) {
if(f > tmax) tmax = f;
}
fMax = tmax;
update();
}
void TrafficGraphWidget::setGraphRangeMins(int mins)
{
nMins = mins;
int msecsPerSample = nMins * 60 * 1000 / DESIRED_SAMPLES;
timer->stop();
timer->setInterval(msecsPerSample);
clear();
}
void TrafficGraphWidget::clear()
{
timer->stop();
vSamplesOut.clear();
vSamplesIn.clear();
fMax = 0.0f;
if(clientModel) {
nLastBytesIn = clientModel->getTotalBytesRecv();
nLastBytesOut = clientModel->getTotalBytesSent();
}
timer->start();
}
<commit_msg>Qt: Add antialiasing to traffic graph widget<commit_after>#include "trafficgraphwidget.h"
#include "clientmodel.h"
#include "optionsmodel.h"
#include <QPainter>
#include <QPainterPath>
#include <QColor>
#include <QTimer>
#include <cmath>
#define DESIRED_SAMPLES 800
#define XMARGIN 10
#define YMARGIN 10
TrafficGraphWidget::TrafficGraphWidget(QWidget *parent) :
QWidget(parent),
timer(0),
fMax(0.0f),
nMins(0),
vSamplesIn(),
vSamplesOut(),
nLastBytesIn(0),
nLastBytesOut(0),
clientModel(0)
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), SLOT(updateRates()));
}
void TrafficGraphWidget::setClientModel(ClientModel *model)
{
clientModel = model;
if(model) {
nLastBytesIn = model->getTotalBytesRecv();
nLastBytesOut = model->getTotalBytesSent();
}
}
int TrafficGraphWidget::getGraphRangeMins() const
{
return nMins;
}
void TrafficGraphWidget::paintPath(QPainterPath &path, QQueue<float> &samples)
{
int h = height() - YMARGIN * 2, w = width() - XMARGIN * 2;
int sampleCount = samples.size(), x = XMARGIN + w, y;
if(sampleCount > 0) {
path.moveTo(x, YMARGIN + h);
for(int i = 0; i < sampleCount; ++i) {
x = XMARGIN + w - w * i / DESIRED_SAMPLES;
y = YMARGIN + h - (int)(h * samples.at(i) / fMax);
path.lineTo(x, y);
}
path.lineTo(x, YMARGIN + h);
}
}
void TrafficGraphWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QColor background_color;
QColor axisCol;
// This is inelegant, but the easiest way to get the traffic graph to respect the stylesheets.
// Qt does not provide an easy way to use stylesheets with the low level QPainter class.
if (this->clientModel->getOptionsModel()->getCurrentStyle() == "dark")
{
background_color.setRgb(26, 38, 50);
axisCol.setRgb(174, 180, 182);
}
else
{
background_color.setRgb(235, 236, 238);
axisCol.setRgb(88, 92, 107);
}
painter.fillRect(rect(), background_color);
if(fMax <= 0.0f) return;
int h = height() - YMARGIN * 2;
painter.setPen(axisCol);
painter.drawLine(XMARGIN, YMARGIN + h, width() - XMARGIN, YMARGIN + h);
// decide what order of magnitude we are
int base = floor(log10(fMax));
float val = pow(10.0f, base);
// draw lines
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax, QString("%1 kB/s").arg(val));
for(float y = val; y < fMax; y += val) {
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
// if we drew 3 or fewer lines, break them up at the next lower order of magnitude
if(fMax / val <= 3.0f) {
axisCol = axisCol.darker();
val = pow(10.0f, base - 1);
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax, QString("%1 kB/s").arg(val));
int count = 1;
for(float y = val; y < fMax; y += val, count++) {
// don't overwrite lines drawn above
if(count % 10 == 0)
continue;
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
}
painter.setRenderHint(QPainter::Antialiasing);
if(!vSamplesIn.empty()) {
QPainterPath p;
paintPath(p, vSamplesIn);
painter.fillPath(p, QColor(0, 255, 0, 128));
painter.setPen(Qt::green);
painter.drawPath(p);
}
if(!vSamplesOut.empty()) {
QPainterPath p;
paintPath(p, vSamplesOut);
painter.fillPath(p, QColor(255, 0, 0, 128));
painter.setPen(Qt::red);
painter.drawPath(p);
}
}
void TrafficGraphWidget::updateRates()
{
if(!clientModel) return;
quint64 bytesIn = clientModel->getTotalBytesRecv(),
bytesOut = clientModel->getTotalBytesSent();
float inRate = (bytesIn - nLastBytesIn) / 1024.0f * 1000 / timer->interval();
float outRate = (bytesOut - nLastBytesOut) / 1024.0f * 1000 / timer->interval();
vSamplesIn.push_front(inRate);
vSamplesOut.push_front(outRate);
nLastBytesIn = bytesIn;
nLastBytesOut = bytesOut;
while(vSamplesIn.size() > DESIRED_SAMPLES) {
vSamplesIn.pop_back();
}
while(vSamplesOut.size() > DESIRED_SAMPLES) {
vSamplesOut.pop_back();
}
float tmax = 0.0f;
foreach(float f, vSamplesIn) {
if(f > tmax) tmax = f;
}
foreach(float f, vSamplesOut) {
if(f > tmax) tmax = f;
}
fMax = tmax;
update();
}
void TrafficGraphWidget::setGraphRangeMins(int mins)
{
nMins = mins;
int msecsPerSample = nMins * 60 * 1000 / DESIRED_SAMPLES;
timer->stop();
timer->setInterval(msecsPerSample);
clear();
}
void TrafficGraphWidget::clear()
{
timer->stop();
vSamplesOut.clear();
vSamplesIn.clear();
fMax = 0.0f;
if(clientModel) {
nLastBytesIn = clientModel->getTotalBytesRecv();
nLastBytesOut = clientModel->getTotalBytesSent();
}
timer->start();
}
<|endoftext|>
|
<commit_before>/**
* \file
* \brief Definitions of clocks for STM32L4
*
* \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef SOURCE_CHIP_STM32_STM32L4_INCLUDE_DISTORTOS_CHIP_CLOCKS_HPP_
#define SOURCE_CHIP_STM32_STM32L4_INCLUDE_DISTORTOS_CHIP_CLOCKS_HPP_
#include "distortos/distortosConfiguration.h"
#include <cstdint>
namespace distortos
{
namespace chip
{
/*---------------------------------------------------------------------------------------------------------------------+
| global constants
+---------------------------------------------------------------------------------------------------------------------*/
/// maximum allowed APB1 (low speed) frequency, Hz
constexpr uint32_t maxApb1Frequency {80000000};
/// maximum allowed APB2 (high speed) frequency, Hz
constexpr uint32_t maxApb2Frequency {80000000};
/// SYSCLK frequency, Hz
constexpr uint32_t sysclkFrequency {CONFIG_CHIP_STM32L4_RCC_SYSCLK_FREQUENCY};
/// AHB frequency, Hz
constexpr uint32_t ahbFrequency {sysclkFrequency / CONFIG_CHIP_STM32L4_RCC_HPRE};
/// APB1 frequency, Hz
constexpr uint32_t apb1Frequency {ahbFrequency / CONFIG_CHIP_STM32L4_RCC_PPRE1};
static_assert(apb1Frequency <= maxApb1Frequency, "Invalid APB1 (low speed) frequency!");
/// APB2 frequency, Hz
constexpr uint32_t apb2Frequency {ahbFrequency / CONFIG_CHIP_STM32L4_RCC_PPRE2};
static_assert(apb2Frequency <= maxApb2Frequency, "Invalid APB2 (high speed) frequency!");
} // namespace chip
} // namespace distortos
#endif // SOURCE_CHIP_STM32_STM32L4_INCLUDE_DISTORTOS_CHIP_CLOCKS_HPP_
<commit_msg>Extend STM32L4's clocks.hpp in preparation for clock configuration<commit_after>/**
* \file
* \brief Definitions of clocks for STM32L4
*
* \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef SOURCE_CHIP_STM32_STM32L4_INCLUDE_DISTORTOS_CHIP_CLOCKS_HPP_
#define SOURCE_CHIP_STM32_STM32L4_INCLUDE_DISTORTOS_CHIP_CLOCKS_HPP_
#include "distortos/distortosConfiguration.h"
#include <cstdint>
namespace distortos
{
namespace chip
{
/*---------------------------------------------------------------------------------------------------------------------+
| global constants
+---------------------------------------------------------------------------------------------------------------------*/
/// minimum allowed values for HSE frequency, Hz
/// [0] - "HSE Clock Bypass" disabled
/// [1] - "HSE Clock Bypass" enabled
constexpr uint32_t minHseFrequencies[2] {4000000, 1};
/// maximum allowed values for HSE frequency, Hz
/// [...][0] - voltage scaling range 1
/// [...][1] - voltage scaling range 2
/// [0][...] - "HSE Clock Bypass" disabled
/// [1][...] - "HSE Clock Bypass" enabled
constexpr uint32_t maxHseFrequencies[2][2]
{
{48000000, 48000000},
{48000000, 26000000},
};
/// HSI16 clock frequency, Hz
constexpr uint32_t hsi16Frequency {16000000};
/// MSI frequencies, Hz
/// [0] - range 0
/// [1] - range 1
/// [2] - range 2
/// [3] - range 3
/// [4] - range 4
/// [5] - range 5
/// [6] - range 6
/// [7] - range 7
/// [8] - range 8
/// [9] - range 9
/// [10] - range 10
/// [11] - range 11
constexpr uint32_t msiFrequencies[12]
{
100000,
200000,
400000,
800000,
1000000,
2000000,
4000000,
8000000,
16000000,
24000000,
32000000,
48000000,
};
/// minimum allowed value for VCO input frequency, Hz
constexpr uint32_t minVcoInFrequency {4000000};
/// maximum allowed value for VCO input frequency, Hz
constexpr uint32_t maxVcoInFrequency {16000000};
/// minimum allowed value for VCO output frequency, Hz
constexpr uint32_t minVcoOutFrequency {64000000};
/// maximum allowed values for VCO output frequency, Hz
/// [0] - voltage scaling range 1
/// [1] - voltage scaling range 2
constexpr uint32_t maxVcoOutFrequency[2] {344000000, 128000000};
/// minimum allowed value for PLL "P" output frequency, Hz
constexpr uint32_t minPllpOutFrequency {2064500};
/// maximum allowed values for PLL "P" output frequency, Hz
/// [0] - voltage scaling range 1
/// [1] - voltage scaling range 2
constexpr uint32_t maxPllpOutFrequencies[2] {80000000, 26000000};
/// minimum allowed value for PLL "Q" output frequency, Hz
constexpr uint32_t minPllqOutFrequency {8000000};
/// maximum allowed values for PLL "Q" output frequency, Hz
/// [0] - voltage scaling range 1
/// [1] - voltage scaling range 2
constexpr uint32_t maxPllqOutFrequencies[2] {80000000, 26000000};
/// minimum allowed value for PLL "R" output frequency, Hz
constexpr uint32_t minPllrOutFrequency {8000000};
/// maximum allowed values for PLL "R" output frequency, Hz
/// [0] - voltage scaling range 1
/// [1] - voltage scaling range 2
constexpr uint32_t maxPllrOutFrequencies[2] {80000000, 26000000};
/// maximum allowed values for SYSCLK frequency, Hz
/// [0] - voltage scaling range 1
/// [1] - voltage scaling range 2
constexpr uint32_t maxSysclkFrequencies[2] {80000000, 26000000};
/// maximum allowed values for AHB frequency, Hz
/// [0] - voltage scaling range 1
/// [1] - voltage scaling range 2
constexpr uint32_t maxAhbFrequencies[2] {80000000, 26000000};
/// maximum allowed values for APB1 (low speed) frequency, Hz
/// [0] - voltage scaling range 1
/// [1] - voltage scaling range 2
constexpr uint32_t maxApb1Frequencies[2] {80000000, 26000000};
/// maximum allowed values for APB2 (high speed) frequency, Hz
/// [0] - voltage scaling range 1
/// [1] - voltage scaling range 2
constexpr uint32_t maxApb2Frequencies[2] {80000000, 26000000};
#ifdef CONFIG_CHIP_STM32L4_STANDARD_CLOCK_CONFIGURATION_ENABLE
/// voltage scaling range index for arrays
constexpr uint8_t voltageScalingRangeIndex {CONFIG_CHIP_STM32L4_PWR_VOLTAGE_SCALING_RANGE - 1};
#ifdef CONFIG_CHIP_STM32L4_RCC_HSE_ENABLE
/// HSE frequency, Hz
constexpr uint32_t hseFrequency {CONFIG_CHIP_STM32L4_RCC_HSE_FREQUENCY};
/// HSE clock bypass
#ifdef CONFIG_CHIP_STM32L4_RCC_HSE_CLOCK_BYPASS
constexpr bool hseClockBypass {true};
#else // !def CONFIG_CHIP_STM32L4_RCC_HSE_CLOCK_BYPASS
constexpr bool hseClockBypass {false};
#endif // !def CONFIG_CHIP_STM32L4_RCC_HSE_CLOCK_BYPASS
static_assert(minHseFrequencies[hseClockBypass] <= hseFrequency &&
hseFrequency <= maxHseFrequencies[hseClockBypass][voltageScalingRangeIndex], "Invalid HSE frequency!");
#endif // def CONFIG_CHIP_STM32L4_RCC_HSE_ENABLE
#ifdef CONFIG_CHIP_STM32L4_RCC_MSI_ENABLE
/// MSI frequency, Hz
constexpr uint32_t msiFrequency {msiFrequencies[CONFIG_CHIP_STM32L4_RCC_MSI_RANGE]};
#endif // def CONFIG_CHIP_STM32L4_RCC_MSI_ENABLE
#ifdef CONFIG_CHIP_STM32L4_RCC_PLL_ENABLE
/// PLL input frequency, Hz
#if defined(CONFIG_CHIP_STM32L4_RCC_PLLSRC_HSE)
constexpr uint32_t pllInFrequency {hseFrequency};
#elif defined(CONFIG_CHIP_STM32L4_RCC_PLLSRC_HSI16)
constexpr uint32_t pllInFrequency {hsi16Frequency};
#elif defined(CONFIG_CHIP_STM32L4_RCC_PLLSRC_MSI)
constexpr uint32_t pllInFrequency {msiFrequency};
#endif // defined(CONFIG_CHIP_STM32L4_RCC_PLLSRC_MSI)
/// VCO input frequency, Hz
constexpr uint32_t vcoInFrequency {pllInFrequency / CONFIG_CHIP_STM32L4_RCC_PLLM};
static_assert(minVcoInFrequency <= vcoInFrequency && vcoInFrequency <= maxVcoInFrequency,
"Invalid VCO input frequency!");
/// VCO output frequency, Hz
constexpr uint32_t vcoOutFrequency {vcoInFrequency * CONFIG_CHIP_STM32L4_RCC_PLLN};
static_assert(minVcoOutFrequency <= vcoOutFrequency && vcoOutFrequency <= maxVcoOutFrequency[voltageScalingRangeIndex],
"Invalid VCO output frequency!");
/// PLL "P" output frequency, Hz
constexpr uint32_t pllpOutFrequency {vcoOutFrequency / CONFIG_CHIP_STM32L4_RCC_PLLP};
static_assert(minPllpOutFrequency <= pllpOutFrequency &&
pllpOutFrequency <= maxPllpOutFrequencies[voltageScalingRangeIndex], "Invalid PLL \"P\" output frequency!");
/// PLL "Q" output frequency, Hz
constexpr uint32_t pllqOutFrequency {vcoOutFrequency / CONFIG_CHIP_STM32L4_RCC_PLLQ};
static_assert(minPllqOutFrequency <= pllqOutFrequency &&
pllqOutFrequency <= maxPllqOutFrequencies[voltageScalingRangeIndex], "Invalid PLL \"Q\" output frequency!");
/// PLL "R" output frequency, Hz
constexpr uint32_t pllrOutFrequency {vcoOutFrequency / CONFIG_CHIP_STM32L4_RCC_PLLR};
static_assert(minPllrOutFrequency <= pllrOutFrequency &&
pllrOutFrequency <= maxPllrOutFrequencies[voltageScalingRangeIndex], "Invalid PLL \"R\" output frequency!");
#endif // def CONFIG_CHIP_STM32L4_RCC_PLL_ENABLE
/// SYSCLK frequency, Hz
#if defined(CONFIG_CHIP_STM32L4_RCC_SYSCLK_HSE)
constexpr uint32_t sysclkFrequency {hseFrequency};
#elif defined(CONFIG_CHIP_STM32L4_RCC_SYSCLK_HSI16)
constexpr uint32_t sysclkFrequency {hsi16Frequency};
#elif defined(CONFIG_CHIP_STM32L4_RCC_SYSCLK_MSI)
constexpr uint32_t sysclkFrequency {msiFrequency};
#elif defined(CONFIG_CHIP_STM32L4_RCC_SYSCLK_PLL)
constexpr uint32_t sysclkFrequency {pllrOutFrequency};
#else
#error "All SYSCLK sources disabled!"
#endif
#else // !def CONFIG_CHIP_STM32L4_STANDARD_CLOCK_CONFIGURATION_ENABLE
/// voltage scaling range index for arrays
constexpr uint8_t voltageScalingRangeIndex {0};
/// SYSCLK frequency, Hz
constexpr uint32_t sysclkFrequency {CONFIG_CHIP_STM32L4_RCC_SYSCLK_FREQUENCY};
#endif // !def CONFIG_CHIP_STM32L4_STANDARD_CLOCK_CONFIGURATION_ENABLE
static_assert(sysclkFrequency <= maxSysclkFrequencies[voltageScalingRangeIndex], "Invalid SYSCLK frequency!");
/// AHB frequency, Hz
constexpr uint32_t ahbFrequency {sysclkFrequency / CONFIG_CHIP_STM32L4_RCC_HPRE};
static_assert(ahbFrequency <= maxAhbFrequencies[voltageScalingRangeIndex], "Invalid AHB frequency!");
/// APB1 frequency, Hz
constexpr uint32_t apb1Frequency {ahbFrequency / CONFIG_CHIP_STM32L4_RCC_PPRE1};
static_assert(apb1Frequency <= maxApb1Frequencies[voltageScalingRangeIndex], "Invalid APB1 (low speed) frequency!");
/// APB2 frequency, Hz
constexpr uint32_t apb2Frequency {ahbFrequency / CONFIG_CHIP_STM32L4_RCC_PPRE2};
static_assert(apb2Frequency <= maxApb2Frequencies[voltageScalingRangeIndex], "Invalid APB2 (high speed) frequency!");
} // namespace chip
} // namespace distortos
#endif // SOURCE_CHIP_STM32_STM32L4_INCLUDE_DISTORTOS_CHIP_CLOCKS_HPP_
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2015] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_COLUMN_DATETIME_HPP
#define REALM_COLUMN_DATETIME_HPP
#include <realm/column.hpp>
namespace realm {
struct NewDate {
NewDate(int64_t seconds, int32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false) { }
NewDate(const null&) : m_is_null(true) { }
NewDate() : NewDate(null()) { }
bool is_null() const { return m_is_null; }
bool operator == (const NewDate& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }
bool operator != (const NewDate& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }
bool operator > (const NewDate& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }
bool operator < (const NewDate& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }
NewDate& operator = (const NewDate& rhs) = default;
int64_t m_seconds;
int32_t m_nanoseconds;
bool m_is_null;
};
class DateTimeColumn : public ColumnBase, public ColumnTemplate<NewDate> {
public:
DateTimeColumn();
/// Get the number of entries in this column. This operation is relatively
/// slow.
size_t size() const noexcept override;
/// Whether or not this column is nullable.
bool is_nullable() const noexcept override;
/// Whether or not the value at \a row_ndx is NULL. If the column is not
/// nullable, always returns false.
bool is_null(size_t row_ndx) const noexcept override;
/// Sets the value at \a row_ndx to be NULL.
/// \throw LogicError Thrown if this column is not nullable.
void set_null(size_t row_ndx) override;
void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override;
void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
bool broken_reciprocal_backlinks) override;
void move_last_row_over(size_t row_ndx, size_t prior_num_rows,
bool broken_reciprocal_backlinks) override;
void clear(size_t num_rows, bool broken_reciprocal_backlinks) override;
void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override;
void destroy() noexcept override;
StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override;
Allocator& get_alloc() const noexcept override;
/// Returns the 'ref' of the root array.
ref_type get_ref() const noexcept override;
MemRef get_mem() const noexcept override;
void replace_root_array(std::unique_ptr<Array> leaf) override;
MemRef clone_deep(Allocator& alloc) const override;
void detach() override;
bool is_attached() const noexcept override;
ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override;
void set_parent(ArrayParent*, size_t ndx_in_parent) noexcept override;
size_t get_ndx_in_parent() const noexcept override;
void set_ndx_in_parent(size_t ndx_in_parent) noexcept override;
void update_from_parent(size_t old_baseline) noexcept override;
void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override;
#ifdef REALM_DEBUG
void verify() const override;
void to_dot(std::ostream&, StringData title = StringData()) const override;
void do_dump_node_structure(std::ostream&, int level) const override;
void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override;
#endif
void add(const NewDate& ndt = NewDate{});
NewDate get(size_t row_ndx) const noexcept;
NewDate get_val(size_t row_ndx) const override;
void set(size_t row_ndx, const NewDate& ndt);
private:
IntNullColumn m_seconds;
IntegerColumn m_nanoseconds;
};
// Implementation
inline DateTimeColumn::DateTimeColumn() :
m_seconds(Allocator::get_default(), IntNullColumn::create(Allocator::get_default())),
m_nanoseconds(Allocator::get_default(), IntegerColumn::create(Allocator::get_default()))
{
}
/// Get the number of entries in this column. This operation is relatively
/// slow.
inline size_t DateTimeColumn::size() const noexcept
{
// FIXME: Consider debug asserts on the columns having the same size
return m_seconds.size();
}
/// Whether or not this column is nullable.
inline bool DateTimeColumn::is_nullable() const noexcept
{
return m_seconds.is_nullable();
}
/// Whether or not the value at \a row_ndx is NULL. If the column is not
/// nullable, always returns false.
inline bool DateTimeColumn::is_null(size_t row_ndx) const noexcept
{
return m_seconds.is_null(row_ndx);
}
/// Sets the value at \a row_ndx to be NULL.
/// \throw LogicError Thrown if this column is not nullable.
inline void DateTimeColumn::set_null(size_t row_ndx)
{
m_seconds.set_null(row_ndx);
}
inline void DateTimeColumn::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows,
bool nullable)
{
m_seconds.insert_rows(row_ndx, num_rows_to_insert, prior_num_rows, nullable);
m_nanoseconds.insert_rows(row_ndx, num_rows_to_insert, prior_num_rows, nullable);
}
inline void DateTimeColumn::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
bool broken_reciprocal_backlinks)
{
m_seconds.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, broken_reciprocal_backlinks);
m_nanoseconds.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, broken_reciprocal_backlinks);
}
inline void DateTimeColumn::move_last_row_over(size_t row_ndx, size_t prior_num_rows,
bool broken_reciprocal_backlinks)
{
m_seconds.move_last_row_over(row_ndx, prior_num_rows, broken_reciprocal_backlinks);
m_nanoseconds.move_last_row_over(row_ndx, prior_num_rows, broken_reciprocal_backlinks);
}
inline void DateTimeColumn::clear(size_t num_rows, bool broken_reciprocal_backlinks)
{
m_seconds.clear(num_rows, broken_reciprocal_backlinks);
m_nanoseconds.clear(num_rows, broken_reciprocal_backlinks);
}
inline void DateTimeColumn::swap_rows(size_t row_ndx_1, size_t row_ndx_2)
{
m_seconds.swap_rows(row_ndx_1, row_ndx_2);
m_nanoseconds.swap_rows(row_ndx_1, row_ndx_2);
}
inline void DateTimeColumn::destroy() noexcept
{
m_seconds.destroy();
m_nanoseconds.destroy();
}
inline StringData DateTimeColumn::get_index_data(size_t, StringIndex::StringConversionBuffer& /*buffer*/) const noexcept
{
// FIXME: Dummy implementation
return null();
}
inline Allocator& DateTimeColumn::get_alloc() const noexcept
{
// FIXME: Dummy implementation
return Allocator::get_default();
}
inline ref_type DateTimeColumn::get_ref() const noexcept
{
// FIXME: Dummy implementation
return 0;
}
inline MemRef DateTimeColumn::get_mem() const noexcept
{
// FIXME: Dummy implementation
return MemRef();
}
inline void DateTimeColumn::replace_root_array(std::unique_ptr<Array> /*leaf*/)
{
// FIXME: Dummy implementation
}
inline MemRef DateTimeColumn::clone_deep(Allocator& /*alloc*/) const
{
// FIXME: Dummy implementation
return MemRef();
}
inline void DateTimeColumn::detach()
{
m_seconds.detach();
m_nanoseconds.detach();
}
inline bool DateTimeColumn::is_attached() const noexcept
{
// FIXME: Assert on both columns having same attached state?
return m_seconds.is_attached();
}
inline ref_type DateTimeColumn::write(size_t /*slice_offset*/, size_t /*slice_size*/, size_t /*table_size*/,
_impl::OutputStream&) const
{
// FIXME: Dummy implementation
return 0;
}
inline void DateTimeColumn::set_parent(ArrayParent*, size_t /*ndx_in_parent*/) noexcept
{
// FIXME: Dummy implementation
}
inline size_t DateTimeColumn::get_ndx_in_parent() const noexcept
{
// FIXME: Dummy implementation
return 0;
}
inline void DateTimeColumn::set_ndx_in_parent(size_t /*ndx_in_parent*/) noexcept
{
// FIXME: Dummy implementation
}
inline void DateTimeColumn::update_from_parent(size_t /*old_baseline*/) noexcept
{
// FIXME: Dummy implementation
}
inline void DateTimeColumn::refresh_accessor_tree(size_t /*new_col_ndx*/, const Spec&)
{
// FIXME: Dummy implementation
}
#ifdef REALM_DEBUG
inline void DateTimeColumn::verify() const
{
// FIXME: Dummy implementation
}
inline void DateTimeColumn::to_dot(std::ostream&, StringData /*title*/) const
{
// FIXME: Dummy implementation
}
inline void DateTimeColumn::do_dump_node_structure(std::ostream&, int /*level*/) const
{
// FIXME: Dummy implementation
}
inline void DateTimeColumn::leaf_to_dot(MemRef, ArrayParent*, size_t /*ndx_in_parent*/, std::ostream&) const
{
// FIXME: Dummy implementation
}
#endif
inline void DateTimeColumn::add(const NewDate& ndt)
{
util::Optional<int64_t> seconds = ndt.is_null() ? util::none : util::make_optional(ndt.m_seconds);
int32_t nanoseconds = ndt.is_null() ? 0 : ndt.m_nanoseconds;
m_seconds.add(seconds);
m_nanoseconds.add(nanoseconds);
}
inline NewDate DateTimeColumn::get(size_t row_ndx) const noexcept
{
util::Optional<int64_t> seconds = m_seconds.get(row_ndx);
return seconds ? NewDate(*seconds, int32_t(m_nanoseconds.get(row_ndx))) : NewDate(null());
}
inline NewDate DateTimeColumn::get_val(size_t row_ndx) const
{
return get(row_ndx);
}
inline void DateTimeColumn::set(size_t row_ndx, const NewDate& ndt)
{
util::Optional<int64_t> seconds = ndt.is_null() ? util::none : util::make_optional(ndt.m_seconds);
int32_t nanoseconds = ndt.is_null() ? 0 : ndt.m_nanoseconds;
m_seconds.set(row_ndx, seconds);
m_nanoseconds.set(row_ndx, nanoseconds);
}
} // namespace realm
#endif // REALM_COLUMN_DATETIME_HPP
<commit_msg>Minor refactoring; extracted expression to variable<commit_after>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2015] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_COLUMN_DATETIME_HPP
#define REALM_COLUMN_DATETIME_HPP
#include <realm/column.hpp>
namespace realm {
struct NewDate {
NewDate(int64_t seconds, int32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false) { }
NewDate(const null&) : m_is_null(true) { }
NewDate() : NewDate(null()) { }
bool is_null() const { return m_is_null; }
bool operator == (const NewDate& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }
bool operator != (const NewDate& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }
bool operator > (const NewDate& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }
bool operator < (const NewDate& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }
NewDate& operator = (const NewDate& rhs) = default;
int64_t m_seconds;
int32_t m_nanoseconds;
bool m_is_null;
};
class DateTimeColumn : public ColumnBase, public ColumnTemplate<NewDate> {
public:
DateTimeColumn();
/// Get the number of entries in this column. This operation is relatively
/// slow.
size_t size() const noexcept override;
/// Whether or not this column is nullable.
bool is_nullable() const noexcept override;
/// Whether or not the value at \a row_ndx is NULL. If the column is not
/// nullable, always returns false.
bool is_null(size_t row_ndx) const noexcept override;
/// Sets the value at \a row_ndx to be NULL.
/// \throw LogicError Thrown if this column is not nullable.
void set_null(size_t row_ndx) override;
void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override;
void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
bool broken_reciprocal_backlinks) override;
void move_last_row_over(size_t row_ndx, size_t prior_num_rows,
bool broken_reciprocal_backlinks) override;
void clear(size_t num_rows, bool broken_reciprocal_backlinks) override;
void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override;
void destroy() noexcept override;
StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override;
Allocator& get_alloc() const noexcept override;
/// Returns the 'ref' of the root array.
ref_type get_ref() const noexcept override;
MemRef get_mem() const noexcept override;
void replace_root_array(std::unique_ptr<Array> leaf) override;
MemRef clone_deep(Allocator& alloc) const override;
void detach() override;
bool is_attached() const noexcept override;
ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override;
void set_parent(ArrayParent*, size_t ndx_in_parent) noexcept override;
size_t get_ndx_in_parent() const noexcept override;
void set_ndx_in_parent(size_t ndx_in_parent) noexcept override;
void update_from_parent(size_t old_baseline) noexcept override;
void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override;
#ifdef REALM_DEBUG
void verify() const override;
void to_dot(std::ostream&, StringData title = StringData()) const override;
void do_dump_node_structure(std::ostream&, int level) const override;
void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override;
#endif
void add(const NewDate& ndt = NewDate{});
NewDate get(size_t row_ndx) const noexcept;
NewDate get_val(size_t row_ndx) const override;
void set(size_t row_ndx, const NewDate& ndt);
private:
IntNullColumn m_seconds;
IntegerColumn m_nanoseconds;
};
// Implementation
inline DateTimeColumn::DateTimeColumn() :
m_seconds(Allocator::get_default(), IntNullColumn::create(Allocator::get_default())),
m_nanoseconds(Allocator::get_default(), IntegerColumn::create(Allocator::get_default()))
{
}
/// Get the number of entries in this column. This operation is relatively
/// slow.
inline size_t DateTimeColumn::size() const noexcept
{
// FIXME: Consider debug asserts on the columns having the same size
return m_seconds.size();
}
/// Whether or not this column is nullable.
inline bool DateTimeColumn::is_nullable() const noexcept
{
return m_seconds.is_nullable();
}
/// Whether or not the value at \a row_ndx is NULL. If the column is not
/// nullable, always returns false.
inline bool DateTimeColumn::is_null(size_t row_ndx) const noexcept
{
return m_seconds.is_null(row_ndx);
}
/// Sets the value at \a row_ndx to be NULL.
/// \throw LogicError Thrown if this column is not nullable.
inline void DateTimeColumn::set_null(size_t row_ndx)
{
m_seconds.set_null(row_ndx);
}
inline void DateTimeColumn::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows,
bool nullable)
{
m_seconds.insert_rows(row_ndx, num_rows_to_insert, prior_num_rows, nullable);
m_nanoseconds.insert_rows(row_ndx, num_rows_to_insert, prior_num_rows, nullable);
}
inline void DateTimeColumn::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
bool broken_reciprocal_backlinks)
{
m_seconds.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, broken_reciprocal_backlinks);
m_nanoseconds.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, broken_reciprocal_backlinks);
}
inline void DateTimeColumn::move_last_row_over(size_t row_ndx, size_t prior_num_rows,
bool broken_reciprocal_backlinks)
{
m_seconds.move_last_row_over(row_ndx, prior_num_rows, broken_reciprocal_backlinks);
m_nanoseconds.move_last_row_over(row_ndx, prior_num_rows, broken_reciprocal_backlinks);
}
inline void DateTimeColumn::clear(size_t num_rows, bool broken_reciprocal_backlinks)
{
m_seconds.clear(num_rows, broken_reciprocal_backlinks);
m_nanoseconds.clear(num_rows, broken_reciprocal_backlinks);
}
inline void DateTimeColumn::swap_rows(size_t row_ndx_1, size_t row_ndx_2)
{
m_seconds.swap_rows(row_ndx_1, row_ndx_2);
m_nanoseconds.swap_rows(row_ndx_1, row_ndx_2);
}
inline void DateTimeColumn::destroy() noexcept
{
m_seconds.destroy();
m_nanoseconds.destroy();
}
inline StringData DateTimeColumn::get_index_data(size_t, StringIndex::StringConversionBuffer& /*buffer*/) const noexcept
{
// FIXME: Dummy implementation
return null();
}
inline Allocator& DateTimeColumn::get_alloc() const noexcept
{
// FIXME: Dummy implementation
return Allocator::get_default();
}
inline ref_type DateTimeColumn::get_ref() const noexcept
{
// FIXME: Dummy implementation
return 0;
}
inline MemRef DateTimeColumn::get_mem() const noexcept
{
// FIXME: Dummy implementation
return MemRef();
}
inline void DateTimeColumn::replace_root_array(std::unique_ptr<Array> /*leaf*/)
{
// FIXME: Dummy implementation
}
inline MemRef DateTimeColumn::clone_deep(Allocator& /*alloc*/) const
{
// FIXME: Dummy implementation
return MemRef();
}
inline void DateTimeColumn::detach()
{
m_seconds.detach();
m_nanoseconds.detach();
}
inline bool DateTimeColumn::is_attached() const noexcept
{
// FIXME: Assert on both columns having same attached state?
return m_seconds.is_attached();
}
inline ref_type DateTimeColumn::write(size_t /*slice_offset*/, size_t /*slice_size*/, size_t /*table_size*/,
_impl::OutputStream&) const
{
// FIXME: Dummy implementation
return 0;
}
inline void DateTimeColumn::set_parent(ArrayParent*, size_t /*ndx_in_parent*/) noexcept
{
// FIXME: Dummy implementation
}
inline size_t DateTimeColumn::get_ndx_in_parent() const noexcept
{
// FIXME: Dummy implementation
return 0;
}
inline void DateTimeColumn::set_ndx_in_parent(size_t /*ndx_in_parent*/) noexcept
{
// FIXME: Dummy implementation
}
inline void DateTimeColumn::update_from_parent(size_t /*old_baseline*/) noexcept
{
// FIXME: Dummy implementation
}
inline void DateTimeColumn::refresh_accessor_tree(size_t /*new_col_ndx*/, const Spec&)
{
// FIXME: Dummy implementation
}
#ifdef REALM_DEBUG
inline void DateTimeColumn::verify() const
{
// FIXME: Dummy implementation
}
inline void DateTimeColumn::to_dot(std::ostream&, StringData /*title*/) const
{
// FIXME: Dummy implementation
}
inline void DateTimeColumn::do_dump_node_structure(std::ostream&, int /*level*/) const
{
// FIXME: Dummy implementation
}
inline void DateTimeColumn::leaf_to_dot(MemRef, ArrayParent*, size_t /*ndx_in_parent*/, std::ostream&) const
{
// FIXME: Dummy implementation
}
#endif
inline void DateTimeColumn::add(const NewDate& ndt)
{
bool is_null = ndt.is_null();
util::Optional<int64_t> seconds = is_null ? util::none : util::make_optional(ndt.m_seconds);
int32_t nanoseconds = is_null ? 0 : ndt.m_nanoseconds;
m_seconds.add(seconds);
m_nanoseconds.add(nanoseconds);
}
inline NewDate DateTimeColumn::get(size_t row_ndx) const noexcept
{
util::Optional<int64_t> seconds = m_seconds.get(row_ndx);
return seconds ? NewDate(*seconds, int32_t(m_nanoseconds.get(row_ndx))) : NewDate(null());
}
inline NewDate DateTimeColumn::get_val(size_t row_ndx) const
{
return get(row_ndx);
}
inline void DateTimeColumn::set(size_t row_ndx, const NewDate& ndt)
{
bool is_null = ndt.is_null();
util::Optional<int64_t> seconds = is_null ? util::none : util::make_optional(ndt.m_seconds);
int32_t nanoseconds = is_null ? 0 : ndt.m_nanoseconds;
m_seconds.set(row_ndx, seconds);
m_nanoseconds.set(row_ndx, nanoseconds);
}
} // namespace realm
#endif // REALM_COLUMN_DATETIME_HPP
<|endoftext|>
|
<commit_before>/*
@file is_transaction_safe
@Copyright Barrett Adair 2015-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE_HPP
#define BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE_HPP
#include <boost/callable_traits/detail/core.hpp>
namespace boost { namespace callable_traits {
//[ is_transaction_safe_hpp
/*`[section:ref_is_transaction_safe is_transaction_safe]
[heading Header]
``#include <boost/callable_traits/is_transaction_safe.hpp>``
[heading Definition]
*/
// inherits from either std::true_type or std::false_type
template<typename T>
struct is_transaction_safe;
//<-
template<typename T>
struct is_transaction_safe : detail::traits<
detail::shallow_decay<T>>::is_transaction_safe {
using type = typename detail::traits<
detail::shallow_decay<T>>::is_transaction_safe;
};
#ifdef BOOST_CLBL_TRTS_DISABLE_VARIABLE_TEMPLATES
template<typename T>
struct is_transaction_safe_v {
static_assert(std::is_same<T, detail::dummy>::value,
"Variable templates not supported on this compiler.");
};
#else
//->
// only available when variable templates are supported
template<typename T>
//<-
BOOST_CLBL_TRAITS_INLINE_VAR
//->
constexpr bool is_transaction_safe_v = //see below
//<-
detail::traits<detail::shallow_decay<T>>::is_transaction_safe::value;
#endif
}} // namespace boost::callable_traits
//->
/*`
[heading Constraints]
* none
*
[heading Behavior]
* `is_transaction_safe<T>::value` is `true` when either:
* `T` is a function type, function pointer type, function reference type, or member function pointer type where the function has a `transaction_safe` specifier
* `T` is a function object with a non-overloaded `operator()`, where the `operator()` has a `transaction_safe` specifier
* On compilers that support variable templates, `is_transaction_safe_v<T>` is equivalent to `is_transaction_safe<T>::value`.
[heading Input/Output Examples]
[table
[[`T`] [`is_transaction_safe_v<T>`]]
[[`int() const transaction_safe`] [`true`]]
[[`int(*)() transaction_safe`] [`true`]]
[[`int(&)() transaction_safe`] [`true`]]
[[`int(foo::* const)() transaction_safe`] [`true`]]
[[`int() const`] [`false`]]
[[`int() volatile`] [`false`]]
[[`int(foo::*)() const`] [`false`]]
[[`int() const`] [`false`]]
[[`int() volatile`] [`false`]]
[[`int() &`] [`false`]]
[[`int(*)()`] [`false`]]
[[`int`] [`false`]]
[[`int foo::*`] [`false`]]
[[`const int foo::*`] [`false`]]
]
[heading Example Program]
[import ../example/is_transaction_safe.cpp]
[is_transaction_safe]
[endsect]
*/
//]
#endif // #ifndef BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE_HPP
<commit_msg>Delete is_transaction_safe.hpp<commit_after><|endoftext|>
|
<commit_before>#include "connection.h"
#include "channel.cpp"
#ifndef SERVER_ROBOBO
#define SERVER_ROBOBO
Server::Server(std::string serverAddress, std::tr1::unordered_map<std::string, std::string> confVars, ModuleInterface* modFace) {
serverName = serverAddress;
serverConf = confVars;
moduleData = modFace;
std::istringstream portNumber (serverConf["port"]);
unsigned int port;
portNumber >> port;
serverConnection.connectServer(serverAddress, port);
sendLine("NICK " + serverConf["nick"]);
sendLine("USER " + serverConf["ident"] + " here " + serverAddress + " :" + serverConf["gecos"]);
handleData();
}
void Server::sendLine(std::string line) {
serverConnection.sendData(line);
std::cout << " -> " << line << std::endl;
moduleData->callHookOut(serverName, parseLine(line));
}
std::tr1::unordered_map<std::string, std::string> Server::getInfo() {
return serverConf;
}
std::tr1::unordered_map<char, char> Server::getPrefixes() {
return prefix;
}
std::vector<std::vector<char> > Server::getChanModes() {
return chanModes;
}
std::vector<char> Server::getChanTypes() {
return chanTypes;
}
void Server::resyncChannels() {
for (std::tr1::unordered_map<std::string, Channel>::iterator iter = inChannels.begin(); iter != inChannels.end(); iter++)
sendLine("NAMES " + iter->first);
}
void Server::handleData() {
std::string receivedLine = "";
std::vector<std::string> parsedLine;
while (true) {
receivedLine = serverConnection.receive();
std::cout << receivedLine << std::endl;
parsedLine = parseLine(receivedLine);
if (parsedLine.size() >= 1)
moduleData->callHook(serverName, parsedLine); // call module hooks for the received message
if (parsedLine[1] == "001") { // welcome to the network
if (serverConf["channels"] != "")
sendLine("JOIN " + serverConf["channels"]);
} else if (parsedLine[1] == "005") // server features
parse005(parsedLine);
else if (parsedLine[1] == "332") { // channel topic
for (std::tr1::unordered_map<std::string, Channel>::iterator it = inChannels.begin(); it != inChannels.end(); it++) {
if (it->first == parsedLine[3])
it->second.setTopic(parsedLine[4]);
}
} else if (parsedLine[1] == "353") { // NAMES reply
for (std::tr1::unordered_map<std::string, Channel>::iterator it = inChannels.begin(); it != inChannels.end(); it++) {
if (it->first == parsedLine[4])
it->second.parseNames(separateBySpace(parsedLine[5]));
}
} else if (parsedLine[1] == "366") { // end of NAMES reply
for (std::tr1::unordered_map<std::string, Channel>::iterator it = inChannels.begin(); it != inChannels.end(); it++) {
if (it->first == parsedLine[3])
it->second.numeric366();
}
} else if (parsedLine[1] == "MODE") {
bool addMode = true;
if (parsedLine[2] == serverConf["nick"]) { // if it's a user mode
for (unsigned int i = 0; i < parsedLine[3].size(); i++) {
if (parsedLine[3][i] == '+')
addMode = true;
else if (parsedLine[3][i] == '-')
addMode = false;
else {
if (addMode)
userModes.push_back(parsedLine[3][i]);
else {
for (std::vector<char>::iterator uModeIter = userModes.begin(); uModeIter != userModes.end(); uModeIter++) {
if (parsedLine[3][i] == *uModeIter) {
userModes.erase(uModeIter);
break;
}
}
}
}
}
} else { // it's a channel mode
int currParam = 4;
for (unsigned int i = 0; i < parsedLine[3].size(); i++) {
if (parsedLine[3][i] == '+')
addMode = true;
else if (parsedLine[3][i] == '-')
addMode = false;
else {
bool found = false;
int category;
for (unsigned int j = 0; j < chanModes[0].size(); j++) {
if (parsedLine[3][i] == chanModes[0][j]) {
found = true;
category = 0;
}
}
if (!found) {
for (unsigned int j = 0; j < chanModes[1].size(); j++) {
if (parsedLine[3][i] == chanModes[1][j]) {
found = true;
category = 1;
}
}
}
if (!found) {
for (unsigned int j = 0; j < chanModes[2].size(); j++) {
if (parsedLine[3][i] == chanModes[2][j]) {
found = true;
category = 2;
}
}
}
if (!found) {
for (unsigned int j = 0; j < chanModes[3].size(); j++) {
if (parsedLine[3][i] == chanModes[3][j]) {
found = true;
category = 3;
}
}
}
if (!found)
category = 4;
if (category == 0 || category == 1 || (category == 2 && addMode)) {
for (std::tr1::unordered_map<std::string, Channel>::iterator chanIter = inChannels.begin(); chanIter != inChannels.end(); chanIter++) {
if (chanIter->first == parsedLine[2])
chanIter->second.setMode(addMode, parsedLine[3][i], parsedLine[currParam++]);
}
} else {
for (std::tr1::unordered_map<std::string, Channel>::iterator chanIter = inChannels.begin(); chanIter != inChannels.end(); chanIter++) {
if (chanIter->first == parsedLine[2])
chanIter->second.setMode(addMode, parsedLine[3][i], "");
}
}
}
}
}
} else if (parsedLine[1] == "NICK" && serverConf["nick"] == separateNickFromFullHostmask(parsedLine[0].substr(1))) // bot's nick changed
serverConf["nick"] = parsedLine[2];
else if (parsedLine[1] == "JOIN" && serverConf["nick"] == separateNickFromFullHostmask(parsedLine[0].substr(1))) // bot joined a channel
inChannels.insert(std::pair<std::string, Channel> (parsedLine[2], Channel (this)));
else if (parsedLine[1] == "PART" && serverConf["nick"] == separateNickFromFullHostmask(parsedLine[0].substr(1)))
inChannels.erase(parsedLine[2]);
else if (parsedLine[1] == "QUIT" && serverConf["nick"] == separateNickFromFullHostmask(parsedLine[0].substr(1))) {
serverConnection.closeConnection();
break;
} else if (parsedLine[0] == "PING") // server ping
sendLine("PONG " + parsedLine[1]);
else if (parsedLine[0] == "ERROR") {
if (parsedLine[1].size() > 12) {
if (parsedLine[1].substr(0,12) == "Closing Link") {
serverConnection.closeConnection();
break;
}
}
}
}
}
void Server::parse005(std::vector<std::string> parsedLine) {
for (unsigned int i = 3; i < parsedLine.size(); i++) {
if (parsedLine[i] == "NAMESX") // RoBoBo supports NAMESX
sendLine("PROTOCTL NAMESX"); // NAMESX
if (parsedLine[i].size() > 8) { // Network name
if (parsedLine[i].substr(0,8) == "NETWORK=") // NETWORK=NameOfNetwork
network = parsedLine[i].substr(8);
}
if (parsedLine[i].size() > 7) { // Channel statuses
if (parsedLine[i].substr(0,7) == "PREFIX=") { // PREFIX=(qaohv)~&@%+
std::string data = parsedLine[i].substr(8);
std::string modes = data.substr(0, data.find_first_of(')'));
std::string chars = data.substr(data.find_first_of(')') + 1);
for (unsigned int i = 0; i < modes.size(); i++)
prefix.insert(std::pair<char, char> (modes[i], chars[i]));
}
}
if (parsedLine[i].size() > 10) { // Channel types
if (parsedLine[i].substr(0,10) == "CHANTYPES=") { // CHANTYPES=#&
std::string types = parsedLine[i].substr(10);
for (unsigned int i = 0; i < types.size(); i++)
chanTypes.push_back(types[i]);
}
}
if (parsedLine[i].size() > 10) { // Channel modes
if (parsedLine[i].substr(0,10) == "CHANMODES=") { // CHANMODES=Ibeg,k,FJLfjl,ABCGKMNOPQRSTcimnprst
std::string modeList = parsedLine[i].substr(10);
std::vector<char> currSet;
unsigned int i;
for (i = 0; i < modeList.size(); i++) { // list modes
if (modeList[i] == ',')
break;
currSet.push_back(modeList[i]);
}
chanModes.push_back(currSet);
currSet.clear();
for (i++; i < modeList.size(); i++) { // param for set and unset; increment i off comma before continuing
if (modeList[i] == ',')
break;
currSet.push_back(modeList[i]);
}
chanModes.push_back(currSet);
currSet.clear();
for (i++; i < modeList.size(); i++) { // param for set; increment i off comma
if (modeList[i] == ',')
break;
currSet.push_back(modeList[i]);
}
chanModes.push_back(currSet);
currSet.clear();
for (i++; i < modeList.size(); i++) // no param; increment i off comma
currSet.push_back(modeList[i]); // no more commas
chanModes.push_back(currSet);
}
}
}
}
std::vector<std::string> Server::parseLine(std::string unformattedLine) {
std::vector<std::string> parsedLine;
std::string linePart = "";
for (unsigned int i = 0; i < unformattedLine.size(); i++) {
if (unformattedLine[i] == ' ') {
parsedLine.push_back(linePart);
linePart = "";
continue;
}
if (i > 0) {
if (unformattedLine[i] == ':' && unformattedLine[i-1] == ' ') {
for (i++; i < unformattedLine.size(); i++)
linePart += unformattedLine[i];
parsedLine.push_back(linePart);
linePart = "";
break;
}
}
linePart += unformattedLine[i];
}
if (linePart != "")
parsedLine.push_back(linePart);
return parsedLine;
}
std::vector<std::string> Server::separateBySpace(std::string joinedLine) {
std::vector<std::string> words;
std::string wordPart;
for (unsigned int i = 0; i < joinedLine.size(); i++) {
if (joinedLine[i] == ' ') {
words.push_back(wordPart);
wordPart = "";
continue;
}
wordPart += joinedLine[i];
}
if (wordPart != "")
words.push_back(wordPart);
return words;
}
std::string Server::separateNickFromFullHostmask(std::string hostmask) {
return hostmask.substr(0, hostmask.find_first_of('!'));
}
#endif<commit_msg>Add kill message to reasons the bot's connection can close.<commit_after>#include "connection.h"
#include "channel.cpp"
#ifndef SERVER_ROBOBO
#define SERVER_ROBOBO
Server::Server(std::string serverAddress, std::tr1::unordered_map<std::string, std::string> confVars, ModuleInterface* modFace) {
serverName = serverAddress;
serverConf = confVars;
moduleData = modFace;
std::istringstream portNumber (serverConf["port"]);
unsigned int port;
portNumber >> port;
serverConnection.connectServer(serverAddress, port);
sendLine("NICK " + serverConf["nick"]);
sendLine("USER " + serverConf["ident"] + " here " + serverAddress + " :" + serverConf["gecos"]);
handleData();
}
void Server::sendLine(std::string line) {
serverConnection.sendData(line);
std::cout << " -> " << line << std::endl;
moduleData->callHookOut(serverName, parseLine(line));
}
std::tr1::unordered_map<std::string, std::string> Server::getInfo() {
return serverConf;
}
std::tr1::unordered_map<char, char> Server::getPrefixes() {
return prefix;
}
std::vector<std::vector<char> > Server::getChanModes() {
return chanModes;
}
std::vector<char> Server::getChanTypes() {
return chanTypes;
}
void Server::resyncChannels() {
for (std::tr1::unordered_map<std::string, Channel>::iterator iter = inChannels.begin(); iter != inChannels.end(); iter++)
sendLine("NAMES " + iter->first);
}
void Server::handleData() {
std::string receivedLine = "";
std::vector<std::string> parsedLine;
while (true) {
receivedLine = serverConnection.receive();
std::cout << receivedLine << std::endl;
parsedLine = parseLine(receivedLine);
if (parsedLine.size() >= 1)
moduleData->callHook(serverName, parsedLine); // call module hooks for the received message
if (parsedLine[1] == "001") { // welcome to the network
if (serverConf["channels"] != "")
sendLine("JOIN " + serverConf["channels"]);
} else if (parsedLine[1] == "005") // server features
parse005(parsedLine);
else if (parsedLine[1] == "332") { // channel topic
for (std::tr1::unordered_map<std::string, Channel>::iterator it = inChannels.begin(); it != inChannels.end(); it++) {
if (it->first == parsedLine[3])
it->second.setTopic(parsedLine[4]);
}
} else if (parsedLine[1] == "353") { // NAMES reply
for (std::tr1::unordered_map<std::string, Channel>::iterator it = inChannels.begin(); it != inChannels.end(); it++) {
if (it->first == parsedLine[4])
it->second.parseNames(separateBySpace(parsedLine[5]));
}
} else if (parsedLine[1] == "366") { // end of NAMES reply
for (std::tr1::unordered_map<std::string, Channel>::iterator it = inChannels.begin(); it != inChannels.end(); it++) {
if (it->first == parsedLine[3])
it->second.numeric366();
}
} else if (parsedLine[1] == "MODE") {
bool addMode = true;
if (parsedLine[2] == serverConf["nick"]) { // if it's a user mode
for (unsigned int i = 0; i < parsedLine[3].size(); i++) {
if (parsedLine[3][i] == '+')
addMode = true;
else if (parsedLine[3][i] == '-')
addMode = false;
else {
if (addMode)
userModes.push_back(parsedLine[3][i]);
else {
for (std::vector<char>::iterator uModeIter = userModes.begin(); uModeIter != userModes.end(); uModeIter++) {
if (parsedLine[3][i] == *uModeIter) {
userModes.erase(uModeIter);
break;
}
}
}
}
}
} else { // it's a channel mode
int currParam = 4;
for (unsigned int i = 0; i < parsedLine[3].size(); i++) {
if (parsedLine[3][i] == '+')
addMode = true;
else if (parsedLine[3][i] == '-')
addMode = false;
else {
bool found = false;
int category;
for (unsigned int j = 0; j < chanModes[0].size(); j++) {
if (parsedLine[3][i] == chanModes[0][j]) {
found = true;
category = 0;
}
}
if (!found) {
for (unsigned int j = 0; j < chanModes[1].size(); j++) {
if (parsedLine[3][i] == chanModes[1][j]) {
found = true;
category = 1;
}
}
}
if (!found) {
for (unsigned int j = 0; j < chanModes[2].size(); j++) {
if (parsedLine[3][i] == chanModes[2][j]) {
found = true;
category = 2;
}
}
}
if (!found) {
for (unsigned int j = 0; j < chanModes[3].size(); j++) {
if (parsedLine[3][i] == chanModes[3][j]) {
found = true;
category = 3;
}
}
}
if (!found)
category = 4;
if (category == 0 || category == 1 || (category == 2 && addMode)) {
for (std::tr1::unordered_map<std::string, Channel>::iterator chanIter = inChannels.begin(); chanIter != inChannels.end(); chanIter++) {
if (chanIter->first == parsedLine[2])
chanIter->second.setMode(addMode, parsedLine[3][i], parsedLine[currParam++]);
}
} else {
for (std::tr1::unordered_map<std::string, Channel>::iterator chanIter = inChannels.begin(); chanIter != inChannels.end(); chanIter++) {
if (chanIter->first == parsedLine[2])
chanIter->second.setMode(addMode, parsedLine[3][i], "");
}
}
}
}
}
} else if (parsedLine[1] == "NICK" && serverConf["nick"] == separateNickFromFullHostmask(parsedLine[0].substr(1))) // bot's nick changed
serverConf["nick"] = parsedLine[2];
else if (parsedLine[1] == "JOIN" && serverConf["nick"] == separateNickFromFullHostmask(parsedLine[0].substr(1))) // bot joined a channel
inChannels.insert(std::pair<std::string, Channel> (parsedLine[2], Channel (this)));
else if (parsedLine[1] == "PART" && serverConf["nick"] == separateNickFromFullHostmask(parsedLine[0].substr(1)))
inChannels.erase(parsedLine[2]);
else if (parsedLine[1] == "QUIT" && serverConf["nick"] == separateNickFromFullHostmask(parsedLine[0].substr(1))) {
serverConnection.closeConnection();
break;
} else if (parsedLine[1] == "KILL" && serverConf["nick"] == separateNickFromFullHostmask(parsedLine[0].substr(1))) {
serverConnection.closeConnection();
break;
} else if (parsedLine[0] == "PING") // server ping
sendLine("PONG " + parsedLine[1]);
else if (parsedLine[0] == "ERROR") {
if (parsedLine[1].size() > 12) {
if (parsedLine[1].substr(0,12) == "Closing Link") {
serverConnection.closeConnection();
break;
}
}
}
}
}
void Server::parse005(std::vector<std::string> parsedLine) {
for (unsigned int i = 3; i < parsedLine.size(); i++) {
if (parsedLine[i] == "NAMESX") // RoBoBo supports NAMESX
sendLine("PROTOCTL NAMESX"); // NAMESX
if (parsedLine[i].size() > 8) { // Network name
if (parsedLine[i].substr(0,8) == "NETWORK=") // NETWORK=NameOfNetwork
network = parsedLine[i].substr(8);
}
if (parsedLine[i].size() > 7) { // Channel statuses
if (parsedLine[i].substr(0,7) == "PREFIX=") { // PREFIX=(qaohv)~&@%+
std::string data = parsedLine[i].substr(8);
std::string modes = data.substr(0, data.find_first_of(')'));
std::string chars = data.substr(data.find_first_of(')') + 1);
for (unsigned int i = 0; i < modes.size(); i++)
prefix.insert(std::pair<char, char> (modes[i], chars[i]));
}
}
if (parsedLine[i].size() > 10) { // Channel types
if (parsedLine[i].substr(0,10) == "CHANTYPES=") { // CHANTYPES=#&
std::string types = parsedLine[i].substr(10);
for (unsigned int i = 0; i < types.size(); i++)
chanTypes.push_back(types[i]);
}
}
if (parsedLine[i].size() > 10) { // Channel modes
if (parsedLine[i].substr(0,10) == "CHANMODES=") { // CHANMODES=Ibeg,k,FJLfjl,ABCGKMNOPQRSTcimnprst
std::string modeList = parsedLine[i].substr(10);
std::vector<char> currSet;
unsigned int i;
for (i = 0; i < modeList.size(); i++) { // list modes
if (modeList[i] == ',')
break;
currSet.push_back(modeList[i]);
}
chanModes.push_back(currSet);
currSet.clear();
for (i++; i < modeList.size(); i++) { // param for set and unset; increment i off comma before continuing
if (modeList[i] == ',')
break;
currSet.push_back(modeList[i]);
}
chanModes.push_back(currSet);
currSet.clear();
for (i++; i < modeList.size(); i++) { // param for set; increment i off comma
if (modeList[i] == ',')
break;
currSet.push_back(modeList[i]);
}
chanModes.push_back(currSet);
currSet.clear();
for (i++; i < modeList.size(); i++) // no param; increment i off comma
currSet.push_back(modeList[i]); // no more commas
chanModes.push_back(currSet);
}
}
}
}
std::vector<std::string> Server::parseLine(std::string unformattedLine) {
std::vector<std::string> parsedLine;
std::string linePart = "";
for (unsigned int i = 0; i < unformattedLine.size(); i++) {
if (unformattedLine[i] == ' ') {
parsedLine.push_back(linePart);
linePart = "";
continue;
}
if (i > 0) {
if (unformattedLine[i] == ':' && unformattedLine[i-1] == ' ') {
for (i++; i < unformattedLine.size(); i++)
linePart += unformattedLine[i];
parsedLine.push_back(linePart);
linePart = "";
break;
}
}
linePart += unformattedLine[i];
}
if (linePart != "")
parsedLine.push_back(linePart);
return parsedLine;
}
std::vector<std::string> Server::separateBySpace(std::string joinedLine) {
std::vector<std::string> words;
std::string wordPart;
for (unsigned int i = 0; i < joinedLine.size(); i++) {
if (joinedLine[i] == ' ') {
words.push_back(wordPart);
wordPart = "";
continue;
}
wordPart += joinedLine[i];
}
if (wordPart != "")
words.push_back(wordPart);
return words;
}
std::string Server::separateNickFromFullHostmask(std::string hostmask) {
return hostmask.substr(0, hostmask.find_first_of('!'));
}
#endif<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2010, Image Engine Design Inc. 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 Image Engine Design nor the names of any
// other contributors to this software 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 OWNER 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.
//
//////////////////////////////////////////////////////////////////////////
#include "IECoreMaya/NumericTraits.h"
#include "IECoreMaya/ToMayaObjectConverter.h"
#include "IECoreMaya/FromMayaObjectConverter.h"
#include "IECoreMaya/TransformationMatrixParameterHandler.h"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/TransformationMatrix.h"
#include "maya/MFnCompoundAttribute.h"
#include "maya/MFnNumericAttribute.h"
#include "maya/MFnUnitAttribute.h"
using namespace IECoreMaya;
using namespace Imath;
// T & R should be kept first, to make iteration easier later on
// as they are the only two with special attribute types.
#define TRANSLATE_INDEX 0
#define ROTATE_INDEX 1
#define SCALE_INDEX 2
#define SHEAR_INDEX 3
#define SCALEPIVOT_INDEX 4
#define SCALEPIVOTTRANS_INDEX 5
#define ROTATEPIVOT_INDEX 6
#define ROTATEPIVOTTRANS_INDEX 7
// We keep this in an array to allow a bunch of tasks to be done in a loop later.
// The order here should correlate with the defines above.
template<typename T>
MString TransformationMatrixParameterHandler<T>::g_attributeNames[] = {
"translate",
"rotate",
"scale",
"shear",
"scalePivot",
"scalePivotTranslation",
"rotatePivot",
"rotatePivotTranslation"
};
static ParameterHandler::Description< TransformationMatrixParameterHandler<float> > floatRegistrar( IECore::TransformationMatrixfParameter::staticTypeId() );
static ParameterHandler::Description< TransformationMatrixParameterHandler<double> > doubleRegistrar( IECore::TransformationMatrixdParameter::staticTypeId() );
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::doUpdate( IECore::ConstParameterPtr parameter, MPlug &plug ) const
{
typename IECore::TypedParameter<IECore::TransformationMatrix<T> >::ConstPtr p = IECore::runTimeCast<const IECore::TypedParameter<IECore::TransformationMatrix<T> > >( parameter );
if( !p )
{
return MS::kFailure;
}
MObject attribute = plug.attribute();
MFnCompoundAttribute fnCAttr( attribute );
if( !fnCAttr.hasObj( attribute ) )
{
return MS::kFailure;
}
if( plug.numChildren() != 8 )
{
return MS::kFailure;
}
MStatus stat;
MPlug tmpPlug;
for( unsigned int i=0; i<8; i++ )
{
tmpPlug = plug.child( i, &stat );
// Verify the naming of the child plugs.
const MString name = tmpPlug.partialName();
const unsigned int len = name.length() - 1;
const unsigned int nlen = g_attributeNames[i].length() - 1;
const MString nameEnd = name.substringW( len - nlen, len );
if( !stat || nameEnd != g_attributeNames[i] )
{
return MS::kFailure;
}
MObject attr = tmpPlug.attribute();
fnCAttr.setObject( attr );
if( !fnCAttr.hasObj( attr ) )
{
return MS::kFailure;
}
}
IECore::TransformationMatrix<T> tMatrix = p->typedDefaultValue();
if( !setUnitVecDefaultValues( plug.child( TRANSLATE_INDEX ), tMatrix.translate ) )
return MS::kFailure;
if( !setUnitVecDefaultValues( plug.child( ROTATE_INDEX ), tMatrix.rotate ) )
return MS::kFailure;
if( !setVecDefaultValues( plug.child( SCALE_INDEX ), tMatrix.scale ) )
return MS::kFailure;
if( !setVecDefaultValues( plug.child( SHEAR_INDEX ), tMatrix.shear ) )
return MS::kFailure;
if( !setVecDefaultValues( plug.child( SCALEPIVOT_INDEX ), tMatrix.scalePivot ) )
return MS::kFailure;
if( !setVecDefaultValues( plug.child( SCALEPIVOTTRANS_INDEX ), tMatrix.scalePivotTranslation ) )
return MS::kFailure;
if( !setVecDefaultValues( plug.child( ROTATEPIVOT_INDEX ), tMatrix.rotatePivot ) )
return MS::kFailure;
if( !setVecDefaultValues( plug.child( ROTATEPIVOTTRANS_INDEX ), tMatrix.rotatePivotTranslation ) )
return MS::kFailure;
return finishUpdating( parameter, plug );
}
template<typename T>
MPlug TransformationMatrixParameterHandler<T>::doCreate( IECore::ConstParameterPtr parameter, const MString &plugName, MObject &node ) const
{
typename IECore::TypedParameter<IECore::TransformationMatrix<T> >::ConstPtr p = IECore::runTimeCast<const IECore::TypedParameter<IECore::TransformationMatrix<T> > >( parameter );
if( !p )
{
return MPlug();
}
MFnCompoundAttribute fnCAttr;
MObject attribute = fnCAttr.create( plugName, plugName );
MFnNumericAttribute fnNAttr;
MFnUnitAttribute fnUAttr;
// As TransformationMatrix embodies a fairly comprehensive rotation model, were going to be a little
// more basic here, and just supply a V3f rotation and pretend that the Quartonean isn't there.
///\todo Expose rotation order and rotationOrientation.
MObject p1 = fnUAttr.create( plugName + g_attributeNames[ TRANSLATE_INDEX ] + "0", plugName + g_attributeNames[ TRANSLATE_INDEX ] + "0", MFnUnitAttribute::kDistance );
MObject p2 = fnUAttr.create( plugName + g_attributeNames[ TRANSLATE_INDEX ] + "1", plugName + g_attributeNames[ TRANSLATE_INDEX ] + "1", MFnUnitAttribute::kDistance );
MObject p3 = fnUAttr.create( plugName + g_attributeNames[ TRANSLATE_INDEX ] + "2", plugName + g_attributeNames[ TRANSLATE_INDEX ] + "2", MFnUnitAttribute::kDistance );
fnCAttr.addChild( fnNAttr.create( plugName + g_attributeNames[ TRANSLATE_INDEX ], plugName + g_attributeNames[ TRANSLATE_INDEX ], p1, p2, p3 ) );
p1 = fnUAttr.create( plugName + g_attributeNames[ ROTATE_INDEX ] + "0", plugName + g_attributeNames[ ROTATE_INDEX ] + "0", MFnUnitAttribute::kAngle );
p2 = fnUAttr.create( plugName + g_attributeNames[ ROTATE_INDEX ] + "1", plugName + g_attributeNames[ ROTATE_INDEX ] + "1", MFnUnitAttribute::kAngle );
p3 = fnUAttr.create( plugName + g_attributeNames[ ROTATE_INDEX ] + "2", plugName + g_attributeNames[ ROTATE_INDEX ] + "2", MFnUnitAttribute::kAngle );
fnCAttr.addChild( fnNAttr.create( plugName + g_attributeNames[ ROTATE_INDEX ], plugName + g_attributeNames[ ROTATE_INDEX ], p1, p2, p3 ) );
for( unsigned int i=2; i<8; i++ )
{
fnCAttr.addChild( fnNAttr.create( plugName + g_attributeNames[i], plugName + g_attributeNames[i], NumericTraits<Imath::Vec3<T> >::dataType() ) );
}
MPlug result = finishCreating( parameter, attribute, node );
if( !doUpdate( parameter, result ) )
{
return MPlug(); // failure
}
if( !finishUpdating( parameter, result ) )
{
return MPlug(); // failure
}
return result;
}
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::doSetValue( IECore::ConstParameterPtr parameter, MPlug &plug ) const
{
typename IECore::TypedParameter<IECore::TransformationMatrix<T> >::ConstPtr p = IECore::runTimeCast<const IECore::TypedParameter<IECore::TransformationMatrix<T> > >( parameter );
if( !p )
{
return MS::kFailure;
}
IECore::TransformationMatrix<T> tMatrix = p->getTypedValue();
if( tMatrix.rotate.order() != Imath::Euler<T>::XYZ )
{
IECore::msg(
IECore::Msg::Error,
"TransformationMatrixParameterHandler::doSetValue",
"The rotation order of the parameter '"+parameter->name()+"' is not XYZ, unable to set value."
);
return MS::kFailure;
}
if( !setVecValues( plug.child( TRANSLATE_INDEX ), tMatrix.translate ) )
return MS::kFailure;
if( !setVecValues( plug.child( ROTATE_INDEX ), tMatrix.rotate ) )
return MS::kFailure;
if( !setVecValues( plug.child( SCALE_INDEX ), tMatrix.scale ) )
return MS::kFailure;
if( !setVecValues( plug.child( SHEAR_INDEX ), tMatrix.shear ) )
return MS::kFailure;
if( !setVecValues( plug.child( SCALEPIVOT_INDEX ), tMatrix.scalePivot ) )
return MS::kFailure;
if( !setVecValues( plug.child( SCALEPIVOTTRANS_INDEX ), tMatrix.scalePivotTranslation ) )
return MS::kFailure;
if( !setVecValues( plug.child( ROTATEPIVOT_INDEX ), tMatrix.rotatePivot ) )
return MS::kFailure;
if( !setVecValues( plug.child( ROTATEPIVOTTRANS_INDEX ), tMatrix.rotatePivotTranslation ) )
return MS::kFailure;
return MS::kSuccess;
}
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::doSetValue( const MPlug &plug, IECore::ParameterPtr parameter ) const
{
typename IECore::TypedParameter<IECore::TransformationMatrix<T> >::Ptr p = IECore::runTimeCast<IECore::TypedParameter<IECore::TransformationMatrix<T> > >( parameter );
if( !p )
{
return MS::kFailure;
}
IECore::TransformationMatrix<T> tMatrix = p->getTypedValue();
if( tMatrix.rotate.order() != Imath::Euler<T>::XYZ )
{
IECore::msg(
IECore::Msg::Error,
"TransformationMatrixParameterHandler::doSetValue",
"The rotation order of the parameter '"+parameter->name()+"' is not XYZ, unable to set value."
);
return MS::kFailure;
}
std::vector<Imath::Vec3<T> > v;
v.resize(8);
for( unsigned int i=0; i<8; i++ )
{
if( !getVecValues( plug.child(i), v[i] ) )
return MS::kFailure;
}
tMatrix.translate = v[ TRANSLATE_INDEX ];
tMatrix.rotate = Imath::Euler<T>(v[ ROTATE_INDEX ]);
tMatrix.scale = v[ SCALE_INDEX ];
tMatrix.shear = v[ SHEAR_INDEX ];
tMatrix.scalePivot = v[ SCALEPIVOT_INDEX ];
tMatrix.scalePivotTranslation = v[ SCALEPIVOTTRANS_INDEX ];
tMatrix.rotatePivot = v[ ROTATEPIVOT_INDEX ];
tMatrix.rotatePivotTranslation = v[ ROTATEPIVOTTRANS_INDEX ];
p->setTypedValue( tMatrix );
return MS::kSuccess;
}
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::setVecValues( MPlug vecPlug, Imath::Vec3<T> &values ) const
{
if( vecPlug.numChildren() != 3 )
{
return MS::kFailure;
}
for( unsigned int i=0; i<3; i++ )
{
if( !vecPlug.child(i).setValue( values[i] ) )
{
return MS::kFailure;
}
}
return MS::kSuccess;
}
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::getVecValues( MPlug vecPlug, Imath::Vec3<T> &values ) const
{
if( vecPlug.numChildren() != 3 )
{
return MS::kFailure;
}
for( unsigned int i=0; i<3; i++ )
{
if( !vecPlug.child(i).getValue( values[i] ) )
{
return MS::kFailure;
}
}
return MS::kSuccess;
}
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::setVecDefaultValues( MPlug vecPlug, Imath::Vec3<T> &defaultValue ) const
{
if( vecPlug.numChildren() != 3 )
{
return MS::kFailure;
}
MFnNumericAttribute fnN;
for( unsigned int i=0; i<3; i++ )
{
fnN.setObject( vecPlug.child(i).attribute() );
if( !fnN.setDefault( defaultValue[i] ) )
{
return MS::kFailure;
}
}
return MS::kSuccess;
}
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::setUnitVecDefaultValues( MPlug vecPlug, Imath::Vec3<T> &defaultValue ) const
{
if( vecPlug.numChildren() != 3 )
{
return MS::kFailure;
}
MFnUnitAttribute fnU;
for( unsigned int i=0; i<3; i++ )
{
fnU.setObject( vecPlug.child(i).attribute() );
if( !fnU.setDefault( defaultValue[i] ) )
{
return MS::kFailure;
}
}
return MS::kSuccess;
}
<commit_msg>Adding comment<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2010, Image Engine Design Inc. 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 Image Engine Design nor the names of any
// other contributors to this software 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 OWNER 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.
//
//////////////////////////////////////////////////////////////////////////
#include "IECoreMaya/NumericTraits.h"
#include "IECoreMaya/ToMayaObjectConverter.h"
#include "IECoreMaya/FromMayaObjectConverter.h"
#include "IECoreMaya/TransformationMatrixParameterHandler.h"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/TransformationMatrix.h"
#include "maya/MFnCompoundAttribute.h"
#include "maya/MFnNumericAttribute.h"
#include "maya/MFnUnitAttribute.h"
using namespace IECoreMaya;
using namespace Imath;
// T & R should be kept first, to make iteration easier later on
// as they are the only two with special attribute types.
#define TRANSLATE_INDEX 0
#define ROTATE_INDEX 1
#define SCALE_INDEX 2
#define SHEAR_INDEX 3
#define SCALEPIVOT_INDEX 4
#define SCALEPIVOTTRANS_INDEX 5
#define ROTATEPIVOT_INDEX 6
#define ROTATEPIVOTTRANS_INDEX 7
// We keep this in an array to allow a bunch of tasks to be done in a loop later.
// The order here should correlate with the defines above.
template<typename T>
MString TransformationMatrixParameterHandler<T>::g_attributeNames[] = {
"translate",
"rotate",
"scale",
"shear",
"scalePivot",
"scalePivotTranslation",
"rotatePivot",
"rotatePivotTranslation"
};
static ParameterHandler::Description< TransformationMatrixParameterHandler<float> > floatRegistrar( IECore::TransformationMatrixfParameter::staticTypeId() );
static ParameterHandler::Description< TransformationMatrixParameterHandler<double> > doubleRegistrar( IECore::TransformationMatrixdParameter::staticTypeId() );
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::doUpdate( IECore::ConstParameterPtr parameter, MPlug &plug ) const
{
typename IECore::TypedParameter<IECore::TransformationMatrix<T> >::ConstPtr p = IECore::runTimeCast<const IECore::TypedParameter<IECore::TransformationMatrix<T> > >( parameter );
if( !p )
{
return MS::kFailure;
}
MObject attribute = plug.attribute();
MFnCompoundAttribute fnCAttr( attribute );
if( !fnCAttr.hasObj( attribute ) )
{
return MS::kFailure;
}
if( plug.numChildren() != 8 )
{
return MS::kFailure;
}
MStatus stat;
MPlug tmpPlug;
for( unsigned int i=0; i<8; i++ )
{
tmpPlug = plug.child( i, &stat );
// Verify the naming of the child plugs.
const MString name = tmpPlug.partialName();
const unsigned int len = name.length() - 1;
const unsigned int nlen = g_attributeNames[i].length() - 1;
const MString nameEnd = name.substringW( len - nlen, len );
if( !stat || nameEnd != g_attributeNames[i] )
{
return MS::kFailure;
}
MObject attr = tmpPlug.attribute();
fnCAttr.setObject( attr );
if( !fnCAttr.hasObj( attr ) )
{
return MS::kFailure;
}
}
IECore::TransformationMatrix<T> tMatrix = p->typedDefaultValue();
if( !setUnitVecDefaultValues( plug.child( TRANSLATE_INDEX ), tMatrix.translate ) )
return MS::kFailure;
if( !setUnitVecDefaultValues( plug.child( ROTATE_INDEX ), tMatrix.rotate ) )
return MS::kFailure;
if( !setVecDefaultValues( plug.child( SCALE_INDEX ), tMatrix.scale ) )
return MS::kFailure;
if( !setVecDefaultValues( plug.child( SHEAR_INDEX ), tMatrix.shear ) )
return MS::kFailure;
if( !setVecDefaultValues( plug.child( SCALEPIVOT_INDEX ), tMatrix.scalePivot ) )
return MS::kFailure;
if( !setVecDefaultValues( plug.child( SCALEPIVOTTRANS_INDEX ), tMatrix.scalePivotTranslation ) )
return MS::kFailure;
if( !setVecDefaultValues( plug.child( ROTATEPIVOT_INDEX ), tMatrix.rotatePivot ) )
return MS::kFailure;
if( !setVecDefaultValues( plug.child( ROTATEPIVOTTRANS_INDEX ), tMatrix.rotatePivotTranslation ) )
return MS::kFailure;
return finishUpdating( parameter, plug );
}
template<typename T>
MPlug TransformationMatrixParameterHandler<T>::doCreate( IECore::ConstParameterPtr parameter, const MString &plugName, MObject &node ) const
{
typename IECore::TypedParameter<IECore::TransformationMatrix<T> >::ConstPtr p = IECore::runTimeCast<const IECore::TypedParameter<IECore::TransformationMatrix<T> > >( parameter );
if( !p )
{
return MPlug();
}
MFnCompoundAttribute fnCAttr;
MObject attribute = fnCAttr.create( plugName, plugName );
MFnNumericAttribute fnNAttr;
MFnUnitAttribute fnUAttr;
// As TransformationMatrix embodies a fairly comprehensive rotation model, were going to be a little
// more basic here, and just supply a V3f rotation and pretend that the Quartonean isn't there.
///\todo Expose rotation order and rotationOrientation.
// These use the '0', '1' and '2' child suffixes instead of 'X' 'Y' and 'Z' to match those created by fnNAttr.create() @ L188.
MObject p1 = fnUAttr.create( plugName + g_attributeNames[ TRANSLATE_INDEX ] + "0", plugName + g_attributeNames[ TRANSLATE_INDEX ] + "0", MFnUnitAttribute::kDistance );
MObject p2 = fnUAttr.create( plugName + g_attributeNames[ TRANSLATE_INDEX ] + "1", plugName + g_attributeNames[ TRANSLATE_INDEX ] + "1", MFnUnitAttribute::kDistance );
MObject p3 = fnUAttr.create( plugName + g_attributeNames[ TRANSLATE_INDEX ] + "2", plugName + g_attributeNames[ TRANSLATE_INDEX ] + "2", MFnUnitAttribute::kDistance );
fnCAttr.addChild( fnNAttr.create( plugName + g_attributeNames[ TRANSLATE_INDEX ], plugName + g_attributeNames[ TRANSLATE_INDEX ], p1, p2, p3 ) );
p1 = fnUAttr.create( plugName + g_attributeNames[ ROTATE_INDEX ] + "0", plugName + g_attributeNames[ ROTATE_INDEX ] + "0", MFnUnitAttribute::kAngle );
p2 = fnUAttr.create( plugName + g_attributeNames[ ROTATE_INDEX ] + "1", plugName + g_attributeNames[ ROTATE_INDEX ] + "1", MFnUnitAttribute::kAngle );
p3 = fnUAttr.create( plugName + g_attributeNames[ ROTATE_INDEX ] + "2", plugName + g_attributeNames[ ROTATE_INDEX ] + "2", MFnUnitAttribute::kAngle );
fnCAttr.addChild( fnNAttr.create( plugName + g_attributeNames[ ROTATE_INDEX ], plugName + g_attributeNames[ ROTATE_INDEX ], p1, p2, p3 ) );
for( unsigned int i=2; i<8; i++ )
{
fnCAttr.addChild( fnNAttr.create( plugName + g_attributeNames[i], plugName + g_attributeNames[i], NumericTraits<Imath::Vec3<T> >::dataType() ) );
}
MPlug result = finishCreating( parameter, attribute, node );
if( !doUpdate( parameter, result ) )
{
return MPlug(); // failure
}
if( !finishUpdating( parameter, result ) )
{
return MPlug(); // failure
}
return result;
}
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::doSetValue( IECore::ConstParameterPtr parameter, MPlug &plug ) const
{
typename IECore::TypedParameter<IECore::TransformationMatrix<T> >::ConstPtr p = IECore::runTimeCast<const IECore::TypedParameter<IECore::TransformationMatrix<T> > >( parameter );
if( !p )
{
return MS::kFailure;
}
IECore::TransformationMatrix<T> tMatrix = p->getTypedValue();
if( tMatrix.rotate.order() != Imath::Euler<T>::XYZ )
{
IECore::msg(
IECore::Msg::Error,
"TransformationMatrixParameterHandler::doSetValue",
"The rotation order of the parameter '"+parameter->name()+"' is not XYZ, unable to set value."
);
return MS::kFailure;
}
if( !setVecValues( plug.child( TRANSLATE_INDEX ), tMatrix.translate ) )
return MS::kFailure;
if( !setVecValues( plug.child( ROTATE_INDEX ), tMatrix.rotate ) )
return MS::kFailure;
if( !setVecValues( plug.child( SCALE_INDEX ), tMatrix.scale ) )
return MS::kFailure;
if( !setVecValues( plug.child( SHEAR_INDEX ), tMatrix.shear ) )
return MS::kFailure;
if( !setVecValues( plug.child( SCALEPIVOT_INDEX ), tMatrix.scalePivot ) )
return MS::kFailure;
if( !setVecValues( plug.child( SCALEPIVOTTRANS_INDEX ), tMatrix.scalePivotTranslation ) )
return MS::kFailure;
if( !setVecValues( plug.child( ROTATEPIVOT_INDEX ), tMatrix.rotatePivot ) )
return MS::kFailure;
if( !setVecValues( plug.child( ROTATEPIVOTTRANS_INDEX ), tMatrix.rotatePivotTranslation ) )
return MS::kFailure;
return MS::kSuccess;
}
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::doSetValue( const MPlug &plug, IECore::ParameterPtr parameter ) const
{
typename IECore::TypedParameter<IECore::TransformationMatrix<T> >::Ptr p = IECore::runTimeCast<IECore::TypedParameter<IECore::TransformationMatrix<T> > >( parameter );
if( !p )
{
return MS::kFailure;
}
IECore::TransformationMatrix<T> tMatrix = p->getTypedValue();
if( tMatrix.rotate.order() != Imath::Euler<T>::XYZ )
{
IECore::msg(
IECore::Msg::Error,
"TransformationMatrixParameterHandler::doSetValue",
"The rotation order of the parameter '"+parameter->name()+"' is not XYZ, unable to set value."
);
return MS::kFailure;
}
std::vector<Imath::Vec3<T> > v;
v.resize(8);
for( unsigned int i=0; i<8; i++ )
{
if( !getVecValues( plug.child(i), v[i] ) )
return MS::kFailure;
}
tMatrix.translate = v[ TRANSLATE_INDEX ];
tMatrix.rotate = Imath::Euler<T>(v[ ROTATE_INDEX ]);
tMatrix.scale = v[ SCALE_INDEX ];
tMatrix.shear = v[ SHEAR_INDEX ];
tMatrix.scalePivot = v[ SCALEPIVOT_INDEX ];
tMatrix.scalePivotTranslation = v[ SCALEPIVOTTRANS_INDEX ];
tMatrix.rotatePivot = v[ ROTATEPIVOT_INDEX ];
tMatrix.rotatePivotTranslation = v[ ROTATEPIVOTTRANS_INDEX ];
p->setTypedValue( tMatrix );
return MS::kSuccess;
}
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::setVecValues( MPlug vecPlug, Imath::Vec3<T> &values ) const
{
if( vecPlug.numChildren() != 3 )
{
return MS::kFailure;
}
for( unsigned int i=0; i<3; i++ )
{
if( !vecPlug.child(i).setValue( values[i] ) )
{
return MS::kFailure;
}
}
return MS::kSuccess;
}
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::getVecValues( MPlug vecPlug, Imath::Vec3<T> &values ) const
{
if( vecPlug.numChildren() != 3 )
{
return MS::kFailure;
}
for( unsigned int i=0; i<3; i++ )
{
if( !vecPlug.child(i).getValue( values[i] ) )
{
return MS::kFailure;
}
}
return MS::kSuccess;
}
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::setVecDefaultValues( MPlug vecPlug, Imath::Vec3<T> &defaultValue ) const
{
if( vecPlug.numChildren() != 3 )
{
return MS::kFailure;
}
MFnNumericAttribute fnN;
for( unsigned int i=0; i<3; i++ )
{
fnN.setObject( vecPlug.child(i).attribute() );
if( !fnN.setDefault( defaultValue[i] ) )
{
return MS::kFailure;
}
}
return MS::kSuccess;
}
template<typename T>
MStatus TransformationMatrixParameterHandler<T>::setUnitVecDefaultValues( MPlug vecPlug, Imath::Vec3<T> &defaultValue ) const
{
if( vecPlug.numChildren() != 3 )
{
return MS::kFailure;
}
MFnUnitAttribute fnU;
for( unsigned int i=0; i<3; i++ )
{
fnU.setObject( vecPlug.child(i).attribute() );
if( !fnU.setDefault( defaultValue[i] ) )
{
return MS::kFailure;
}
}
return MS::kSuccess;
}
<|endoftext|>
|
<commit_before>// RUN: %clang_cc1 -triple i686-pc-win32 -x c++ -O2 -disable-llvm-optzns -emit-llvm < %s | FileCheck %s
#define DLLEXPORT __declspec(dllexport)
void DLLEXPORT a();
// CHECK-DAG: declare dllexport void @"\01?a@@YAXXZ"()
inline void DLLEXPORT b() {}
// CHECK-DAG: define weak_odr dllexport void @"\01?b@@YAXXZ"()
template <typename T> void c() {}
template void DLLEXPORT c<int>();
// CHECK-DAG: define weak_odr dllexport void @"\01??$c@H@@YAXXZ"()
struct S {
void DLLEXPORT a() {}
// CHECK-DAG: define weak_odr dllexport x86_thiscallcc void @"\01?a@S@@QAEXXZ"
};
void user() {
// FIXME: dllexported functions must be emitted even if they're not referenced in this TU.
a();
b();
&S::a;
}
<commit_msg>test/CodeGenCXX/dllexport.cpp: we already correctly emit b() even when it's not used, because CodeGenModule::EmitGlobal consults ASTContext::DeclMustBeEmitted via CodeGenModule::MayDeferGeneration.<commit_after>// RUN: %clang_cc1 -triple i686-pc-win32 -x c++ -O2 -disable-llvm-optzns -emit-llvm < %s | FileCheck %s
#define DLLEXPORT __declspec(dllexport)
void DLLEXPORT a();
// CHECK-DAG: declare dllexport void @"\01?a@@YAXXZ"()
inline void DLLEXPORT b() {}
// CHECK-DAG: define weak_odr dllexport void @"\01?b@@YAXXZ"()
template <typename T> void c() {}
template void DLLEXPORT c<int>();
// CHECK-DAG: define weak_odr dllexport void @"\01??$c@H@@YAXXZ"()
struct S {
void DLLEXPORT a() {}
// CHECK-DAG: define weak_odr dllexport x86_thiscallcc void @"\01?a@S@@QAEXXZ"
};
void user() {
a();
// FIXME: dllexported methods must be emitted even if they're not referenced in this TU.
&S::a;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <sauce/sauce.h>
/**
* The purpose of this test is to enforce ansi c++ compatibility within the source.
*
* It does so by first pulling in all desired includes, instantiating templates and then asserting
* that it was compiled with -ansi.
*/
int main() {
#ifdef __STRICT_ANSI__
return 0;
#else
std::cerr << "This file was not compiled with -ansi." << std::endl;
return 1;
#endif
}
<commit_msg>Give the ansi checker something to do.<commit_after>#include <iostream>
#include <sauce/sauce.h>
/**
* The purpose of this test is to enforce ansi c++ compatibility within the source.
*
* It does so by first pulling in all desired includes, instantiating templates and then asserting
* that it was compiled with -ansi.
*/
using ::sauce::AbstractProvider;
using ::sauce::Binder;
using ::sauce::Injector;
using ::sauce::Modules;
using ::sauce::Named;
struct Animal {
virtual std::string says() = 0;
};
struct Cat: Animal {
std::string says() { return "Meow"; }
};
struct LieutenantShinysides {};
struct Fish: Animal {
std::string says() { return "Blub blub"; }
};
struct Meatloaf {};
struct Cow: Animal {
std::string says() { return "Moo"; }
};
struct CowProvider: AbstractProvider<Animal> {
Animal * provide() {
return new Cow();
}
void dispose(Animal * cow) {
delete cow;
}
};
struct Pond {
sauce::shared_ptr<Animal> animal;
Pond(sauce::shared_ptr<Animal> animal):
animal(animal) {}
};
void AnimalModule(Binder & binder) {
binder.bind<Animal>().to<Cat()>();
binder.bind<Animal>().named<LieutenantShinysides>().to<Fish()>();
binder.bind<Animal>().named<Meatloaf>().toProvider<CowProvider()>();
binder.bind<Pond>().to<Pond(Named<Animal, LieutenantShinysides>)>();
}
int main() {
sauce::shared_ptr<Injector> injector(Modules().add(&AnimalModule).createInjector());
#ifdef __STRICT_ANSI__
return 0;
#else
std::cerr << "This file was not compiled with -ansi." << std::endl;
return 1;
#endif
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2012 The WebM project authors. All Rights Reserved.
Use of this source code is governed by a BSD-style license
that can be found in the LICENSE file in the root of the source
tree. An additional intellectual property rights grant can be found
in the file PATENTS. All contributing project authors may
be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
namespace {
const int kMaxErrorFrames = 8;
const int kMaxDroppableFrames = 8;
class ErrorResilienceTest : public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWithParam<libvpx_test::TestMode> {
protected:
ErrorResilienceTest() : EncoderTest(GET_PARAM(0)),
psnr_(0.0),
nframes_(0),
mismatch_psnr_(0.0),
mismatch_nframes_(0),
encoding_mode_(GET_PARAM(1)) {
Reset();
}
virtual ~ErrorResilienceTest() {}
void Reset() {
error_nframes_ = 0;
droppable_nframes_ = 0;
}
virtual void SetUp() {
InitializeConfig();
SetMode(encoding_mode_);
}
virtual void BeginPassHook(unsigned int /*pass*/) {
psnr_ = 0.0;
nframes_ = 0;
mismatch_psnr_ = 0.0;
mismatch_nframes_ = 0;
}
virtual bool Continue() const {
return !HasFatalFailure() && !abort_;
}
virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
psnr_ += pkt->data.psnr.psnr[0];
nframes_++;
}
virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video) {
frame_flags_ &= ~(VP8_EFLAG_NO_UPD_LAST |
VP8_EFLAG_NO_UPD_GF |
VP8_EFLAG_NO_UPD_ARF);
if (droppable_nframes_ > 0 &&
(cfg_.g_pass == VPX_RC_LAST_PASS || cfg_.g_pass == VPX_RC_ONE_PASS)) {
for (unsigned int i = 0; i < droppable_nframes_; ++i) {
if (droppable_frames_[i] == nframes_) {
std::cout << " Encoding droppable frame: "
<< droppable_frames_[i] << "\n";
frame_flags_ |= (VP8_EFLAG_NO_UPD_LAST |
VP8_EFLAG_NO_UPD_GF |
VP8_EFLAG_NO_UPD_ARF);
return;
}
}
}
}
double GetAveragePsnr() const {
if (nframes_)
return psnr_ / nframes_;
return 0.0;
}
double GetAverageMismatchPsnr() const {
if (mismatch_nframes_)
return mismatch_psnr_ / mismatch_nframes_;
return 0.0;
}
virtual bool DoDecode() const {
if (error_nframes_ > 0 &&
(cfg_.g_pass == VPX_RC_LAST_PASS || cfg_.g_pass == VPX_RC_ONE_PASS)) {
for (unsigned int i = 0; i < error_nframes_; ++i) {
if (error_frames_[i] == nframes_ - 1) {
std::cout << " Skipping decoding frame: "
<< error_frames_[i] << "\n";
return 0;
}
}
}
return 1;
}
virtual void MismatchHook(const vpx_image_t *img1,
const vpx_image_t *img2) {
double mismatch_psnr = compute_psnr(img1, img2);
mismatch_psnr_ += mismatch_psnr;
++mismatch_nframes_;
// std::cout << "Mismatch frame psnr: " << mismatch_psnr << "\n";
}
void SetErrorFrames(int num, unsigned int *list) {
if (num > kMaxErrorFrames)
num = kMaxErrorFrames;
else if (num < 0)
num = 0;
error_nframes_ = num;
for (unsigned int i = 0; i < error_nframes_; ++i)
error_frames_[i] = list[i];
}
void SetDroppableFrames(int num, unsigned int *list) {
if (num > kMaxDroppableFrames)
num = kMaxDroppableFrames;
else if (num < 0)
num = 0;
droppable_nframes_ = num;
for (unsigned int i = 0; i < droppable_nframes_; ++i)
droppable_frames_[i] = list[i];
}
unsigned int GetMismatchFrames() {
return mismatch_nframes_;
}
private:
double psnr_;
unsigned int nframes_;
unsigned int error_nframes_;
unsigned int droppable_nframes_;
double mismatch_psnr_;
unsigned int mismatch_nframes_;
unsigned int error_frames_[kMaxErrorFrames];
unsigned int droppable_frames_[kMaxDroppableFrames];
libvpx_test::TestMode encoding_mode_;
};
TEST_P(ErrorResilienceTest, OnVersusOff) {
const vpx_rational timebase = { 33333333, 1000000000 };
cfg_.g_timebase = timebase;
cfg_.rc_target_bitrate = 2000;
cfg_.g_lag_in_frames = 25;
init_flags_ = VPX_CODEC_USE_PSNR;
libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
timebase.den, timebase.num, 0, 30);
// Error resilient mode OFF.
cfg_.g_error_resilient = 0;
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
const double psnr_resilience_off = GetAveragePsnr();
EXPECT_GT(psnr_resilience_off, 25.0);
// Error resilient mode ON.
cfg_.g_error_resilient = 1;
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
const double psnr_resilience_on = GetAveragePsnr();
EXPECT_GT(psnr_resilience_on, 25.0);
// Test that turning on error resilient mode hurts by 10% at most.
if (psnr_resilience_off > 0.0) {
const double psnr_ratio = psnr_resilience_on / psnr_resilience_off;
EXPECT_GE(psnr_ratio, 0.9);
EXPECT_LE(psnr_ratio, 1.1);
}
}
TEST_P(ErrorResilienceTest, DropFramesWithoutRecovery) {
const vpx_rational timebase = { 33333333, 1000000000 };
cfg_.g_timebase = timebase;
cfg_.rc_target_bitrate = 2000;
cfg_.g_lag_in_frames = 5;
init_flags_ = VPX_CODEC_USE_PSNR;
libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
timebase.den, timebase.num, 0, 30);
// Error resilient mode ON.
cfg_.g_error_resilient = 1;
// Set an arbitrary set of error frames same as droppable frames
unsigned int num_droppable_frames = 2;
unsigned int droppable_frame_list[] = {5, 16};
SetDroppableFrames(num_droppable_frames, droppable_frame_list);
SetErrorFrames(num_droppable_frames, droppable_frame_list);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
// Test that no mismatches have been found
std::cout << " Mismatch frames: "
<< GetMismatchFrames() << "\n";
EXPECT_EQ(GetMismatchFrames(), (unsigned int) 0);
// reset previously set error/droppable frames
Reset();
// Now set an arbitrary set of error frames that are non-droppable
unsigned int num_error_frames = 3;
unsigned int error_frame_list[] = {3, 10, 20};
SetErrorFrames(num_error_frames, error_frame_list);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
// Test that dropping an arbitrary set of inter frames does not hurt too much
// Note the Average Mismatch PSNR is the average of the PSNR between
// decoded frame and encoder's version of the same frame for all frames
// with mismatch.
const double psnr_resilience_mismatch = GetAverageMismatchPsnr();
std::cout << " Mismatch PSNR: "
<< psnr_resilience_mismatch << "\n";
EXPECT_GT(psnr_resilience_mismatch, 20.0);
}
VP8_INSTANTIATE_TEST_CASE(ErrorResilienceTest, ONE_PASS_TEST_MODES);
VP9_INSTANTIATE_TEST_CASE(ErrorResilienceTest, ONE_PASS_TEST_MODES);
} // namespace
<commit_msg>Tweak DropFramesWithoutRecovery params<commit_after>/*
Copyright (c) 2012 The WebM project authors. All Rights Reserved.
Use of this source code is governed by a BSD-style license
that can be found in the LICENSE file in the root of the source
tree. An additional intellectual property rights grant can be found
in the file PATENTS. All contributing project authors may
be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
namespace {
const int kMaxErrorFrames = 8;
const int kMaxDroppableFrames = 8;
class ErrorResilienceTest : public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWithParam<libvpx_test::TestMode> {
protected:
ErrorResilienceTest() : EncoderTest(GET_PARAM(0)),
psnr_(0.0),
nframes_(0),
mismatch_psnr_(0.0),
mismatch_nframes_(0),
encoding_mode_(GET_PARAM(1)) {
Reset();
}
virtual ~ErrorResilienceTest() {}
void Reset() {
error_nframes_ = 0;
droppable_nframes_ = 0;
}
virtual void SetUp() {
InitializeConfig();
SetMode(encoding_mode_);
}
virtual void BeginPassHook(unsigned int /*pass*/) {
psnr_ = 0.0;
nframes_ = 0;
mismatch_psnr_ = 0.0;
mismatch_nframes_ = 0;
}
virtual bool Continue() const {
return !HasFatalFailure() && !abort_;
}
virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
psnr_ += pkt->data.psnr.psnr[0];
nframes_++;
}
virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video) {
frame_flags_ &= ~(VP8_EFLAG_NO_UPD_LAST |
VP8_EFLAG_NO_UPD_GF |
VP8_EFLAG_NO_UPD_ARF);
if (droppable_nframes_ > 0 &&
(cfg_.g_pass == VPX_RC_LAST_PASS || cfg_.g_pass == VPX_RC_ONE_PASS)) {
for (unsigned int i = 0; i < droppable_nframes_; ++i) {
if (droppable_frames_[i] == nframes_) {
std::cout << " Encoding droppable frame: "
<< droppable_frames_[i] << "\n";
frame_flags_ |= (VP8_EFLAG_NO_UPD_LAST |
VP8_EFLAG_NO_UPD_GF |
VP8_EFLAG_NO_UPD_ARF);
return;
}
}
}
}
double GetAveragePsnr() const {
if (nframes_)
return psnr_ / nframes_;
return 0.0;
}
double GetAverageMismatchPsnr() const {
if (mismatch_nframes_)
return mismatch_psnr_ / mismatch_nframes_;
return 0.0;
}
virtual bool DoDecode() const {
if (error_nframes_ > 0 &&
(cfg_.g_pass == VPX_RC_LAST_PASS || cfg_.g_pass == VPX_RC_ONE_PASS)) {
for (unsigned int i = 0; i < error_nframes_; ++i) {
if (error_frames_[i] == nframes_ - 1) {
std::cout << " Skipping decoding frame: "
<< error_frames_[i] << "\n";
return 0;
}
}
}
return 1;
}
virtual void MismatchHook(const vpx_image_t *img1,
const vpx_image_t *img2) {
double mismatch_psnr = compute_psnr(img1, img2);
mismatch_psnr_ += mismatch_psnr;
++mismatch_nframes_;
// std::cout << "Mismatch frame psnr: " << mismatch_psnr << "\n";
}
void SetErrorFrames(int num, unsigned int *list) {
if (num > kMaxErrorFrames)
num = kMaxErrorFrames;
else if (num < 0)
num = 0;
error_nframes_ = num;
for (unsigned int i = 0; i < error_nframes_; ++i)
error_frames_[i] = list[i];
}
void SetDroppableFrames(int num, unsigned int *list) {
if (num > kMaxDroppableFrames)
num = kMaxDroppableFrames;
else if (num < 0)
num = 0;
droppable_nframes_ = num;
for (unsigned int i = 0; i < droppable_nframes_; ++i)
droppable_frames_[i] = list[i];
}
unsigned int GetMismatchFrames() {
return mismatch_nframes_;
}
private:
double psnr_;
unsigned int nframes_;
unsigned int error_nframes_;
unsigned int droppable_nframes_;
double mismatch_psnr_;
unsigned int mismatch_nframes_;
unsigned int error_frames_[kMaxErrorFrames];
unsigned int droppable_frames_[kMaxDroppableFrames];
libvpx_test::TestMode encoding_mode_;
};
TEST_P(ErrorResilienceTest, OnVersusOff) {
const vpx_rational timebase = { 33333333, 1000000000 };
cfg_.g_timebase = timebase;
cfg_.rc_target_bitrate = 2000;
cfg_.g_lag_in_frames = 25;
init_flags_ = VPX_CODEC_USE_PSNR;
libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
timebase.den, timebase.num, 0, 30);
// Error resilient mode OFF.
cfg_.g_error_resilient = 0;
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
const double psnr_resilience_off = GetAveragePsnr();
EXPECT_GT(psnr_resilience_off, 25.0);
// Error resilient mode ON.
cfg_.g_error_resilient = 1;
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
const double psnr_resilience_on = GetAveragePsnr();
EXPECT_GT(psnr_resilience_on, 25.0);
// Test that turning on error resilient mode hurts by 10% at most.
if (psnr_resilience_off > 0.0) {
const double psnr_ratio = psnr_resilience_on / psnr_resilience_off;
EXPECT_GE(psnr_ratio, 0.9);
EXPECT_LE(psnr_ratio, 1.1);
}
}
TEST_P(ErrorResilienceTest, DropFramesWithoutRecovery) {
const vpx_rational timebase = { 33333333, 1000000000 };
cfg_.g_timebase = timebase;
cfg_.rc_target_bitrate = 500;
init_flags_ = VPX_CODEC_USE_PSNR;
libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
timebase.den, timebase.num, 0, 30);
// Error resilient mode ON.
cfg_.g_error_resilient = 1;
// Set an arbitrary set of error frames same as droppable frames
unsigned int num_droppable_frames = 2;
unsigned int droppable_frame_list[] = {5, 16};
SetDroppableFrames(num_droppable_frames, droppable_frame_list);
SetErrorFrames(num_droppable_frames, droppable_frame_list);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
// Test that no mismatches have been found
std::cout << " Mismatch frames: "
<< GetMismatchFrames() << "\n";
EXPECT_EQ(GetMismatchFrames(), (unsigned int) 0);
// reset previously set error/droppable frames
Reset();
// Now set an arbitrary set of error frames that are non-droppable
unsigned int num_error_frames = 3;
unsigned int error_frame_list[] = {3, 10, 20};
SetErrorFrames(num_error_frames, error_frame_list);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
// Test that dropping an arbitrary set of inter frames does not hurt too much
// Note the Average Mismatch PSNR is the average of the PSNR between
// decoded frame and encoder's version of the same frame for all frames
// with mismatch.
const double psnr_resilience_mismatch = GetAverageMismatchPsnr();
std::cout << " Mismatch PSNR: "
<< psnr_resilience_mismatch << "\n";
EXPECT_GT(psnr_resilience_mismatch, 20.0);
}
VP8_INSTANTIATE_TEST_CASE(ErrorResilienceTest, ONE_PASS_TEST_MODES);
VP9_INSTANTIATE_TEST_CASE(ErrorResilienceTest, ONE_PASS_TEST_MODES);
} // namespace
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#ifndef _Stroika_Foundation_IO_Network_Transfer_Client_libcurl_inl_
#define _Stroika_Foundation_IO_Network_Transfer_Client_libcurl_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
CompileTimeFlagChecker_HEADER (Stroika::Foundation::IO::Network::Transfer, qHasFeature_LibCurl, qHasFeature_LibCurl);
namespace Stroika::Foundation::IO::Network::Transfer {
#if qHasFeature_LibCurl
class LibCurlException [[deprecated ("Since v2.1d18, use SystemErrorException{ hr, LibCurl_error_category () }")]] : public Execution::SystemErrorException<>
{
public:
using CURLcode = int; // tried directly to reference libcurl CURLcode but tricky cuz its an enum -- LGP 2012-05-08
public:
LibCurlException (CURLcode ccode);
public:
// throw Exception () type iff the status indicates a real exception code. This MAY not throw an exception of type LibCurlException,
// but MAY map to any other exception type
static void ThrowIfError (CURLcode status);
public:
nonvirtual CURLcode GetCode () const
{
return fCurlCode_;
}
private:
CURLcode fCurlCode_;
};
#endif
}
#endif /*_Stroika_Foundation_IO_Network_Transfer_Client_libcurl_inl_*/
<commit_msg>deprecated class typo<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#ifndef _Stroika_Foundation_IO_Network_Transfer_Client_libcurl_inl_
#define _Stroika_Foundation_IO_Network_Transfer_Client_libcurl_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
CompileTimeFlagChecker_HEADER (Stroika::Foundation::IO::Network::Transfer, qHasFeature_LibCurl, qHasFeature_LibCurl);
namespace Stroika::Foundation::IO::Network::Transfer {
#if qHasFeature_LibCurl
class [[deprecated ("Since v2.1d18, use SystemErrorException{ hr, LibCurl_error_category () }")]] LibCurlException : public Execution::SystemErrorException<>
{
public:
using CURLcode = int; // tried directly to reference libcurl CURLcode but tricky cuz its an enum -- LGP 2012-05-08
public:
LibCurlException (CURLcode ccode);
public:
// throw Exception () type iff the status indicates a real exception code. This MAY not throw an exception of type LibCurlException,
// but MAY map to any other exception type
static void ThrowIfError (CURLcode status);
public:
nonvirtual CURLcode GetCode () const
{
return fCurlCode_;
}
private:
CURLcode fCurlCode_;
};
#endif
}
#endif /*_Stroika_Foundation_IO_Network_Transfer_Client_libcurl_inl_*/
<|endoftext|>
|
<commit_before>#include "catch.hpp"
#include <iostream> // std::cout, std::endl
#include <exception> // std::bad_function_call, std::runtime_error
#include <thread> // std::thread, std::this_thread::yield
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
#include <functional> // std::function
/**
* The EventThreader class runs two threads simutaniously but not at the same
* time. The switching between threads is controlled by the EventThreader
* class. The two threads are the current thread (named the calling thread)
* and the second thread is spawned from a given function (event thread). The
* event thread is spawned and paused in the construction of the EventThreader
* class.
*
* Operation
* Only the calling thread will run until it requests that event thread is run.
* While one thread is running, it is guaranteed that the other is paused. On
* EventThreader construction, the event thead is paused. The event thread is
* invoked (and the calling thread paused) either with calls
* EventThreader::join() or EventThreader::switchToEventThread(). From the
* event thread, the calling thread can be invoked by a call to the event
* threads function parameter.
*
* The EventThreader takes one parameter on construction to be a functional
* object f of type void(void(void)). f will be the function run as the event
* thread. f's parameter is the function that invokes the event thread to
* pause, allowing the calling thread to continue.
*
* Every call to EventThreader::switchToEventThread() from the calling thread
* must be followed by a call EventThreader::switchToCallingThread() via
* calling the event theads functional parameter from the event thread.
*/
class EventThreader {
private:
std::condition_variable event_waiter, calling_waiter;
std::unique_lock<std::mutex>* event_lock, * calling_lock;
std::mutex mtx;
std::thread event_thread;
void switchToCallingThread();
bool request_end_of_event = false;
bool waiting_for_event = false;
std::function<void(void)> event_cleanup;
std::runtime_error* exception_from_the_event_thread;
public:
EventThreader(std::function<void (std::function<void (void)>)> func);
~EventThreader();
void switchToEventThread();
void join();
void setEventCleanup(std::function<void(void)>);
};
EventThreader::EventThreader(std::function<void (std::function<void (void)>)> func) {
exception_from_the_event_thread = nullptr;
calling_lock = new std::unique_lock<std::mutex>(mtx);
event_cleanup = [](){}; // empty function
auto event = [&](){
/* mtx force switch to calling - blocked by the mutex */
event_lock = new std::unique_lock<std::mutex>(mtx);
calling_waiter.notify_one();
event_waiter.wait(*event_lock);
std::this_thread::yield();
try {
func([&](){switchToCallingThread();});
if (waiting_for_event) { // the event has ended, but not ready to join
// rejoin the calling thread after dealing with this exception
calling_waiter.notify_one();
throw std::runtime_error("calling thread is not ready to join");
}
} catch (const std::runtime_error &e) {
/* report the exception to the calling thread */
exception_from_the_event_thread = new std::runtime_error(e);
}
delete event_lock;
event_cleanup();
};
event_thread = std::thread(event);
std::this_thread::yield();
calling_waiter.wait(*calling_lock);
std::this_thread::yield();
}
EventThreader::~EventThreader() {}
void EventThreader::switchToCallingThread() {
if (request_end_of_event) {
std::runtime_error err("calling thread requested join, cannot call switchToCallingThread()");
throw err;
}
/* switch to calling */
calling_waiter.notify_one();
std::this_thread::yield();
event_waiter.wait(*event_lock);
std::this_thread::yield();
/* back from calling */
}
void EventThreader::switchToEventThread() {
waiting_for_event = true;
/* switch to event */
event_waiter.notify_one();
std::this_thread::yield();
calling_waiter.wait(*calling_lock);
std::this_thread::yield();
/* back from event */
waiting_for_event = false;
}
void EventThreader::join() {
request_end_of_event = true;
delete calling_lock; // remove lock on this thread, allow event to run
event_waiter.notify_one();
std::this_thread::yield();
event_thread.join();
if (exception_from_the_event_thread != nullptr) {
/* an exception occured */
std::runtime_error e_copy(exception_from_the_event_thread->what());
delete exception_from_the_event_thread;
throw e_copy;
}
}
void EventThreader::setEventCleanup(std::function<void(void)> cleanup) {
event_cleanup = cleanup;
}
TEST_CASE( "EventThreader", "[EventThreader]" ) {
std::stringstream ss;
SECTION("Abitrary use") {
/* Example of most basic use */
auto f = [&ss](std::function<void(void)> switchToMainThread){
for(int i = 0; i < 100; i++) { ss << "*"; }
switchToMainThread();
for(int i = 0; i < 50; i++) { ss << "*"; }
switchToMainThread();
};
EventThreader et(f);
et.switchToEventThread();
for(int i = 0; i < 75; i++) { ss << "$"; }
et.switchToEventThread();
for(int i = 0; i < 25; i++) { ss << "$"; }
et.join();
/* Generate what the result should look like */
std::string requirement;
for(int i = 0; i < 100; i++) { requirement += "*"; }
for(int i = 0; i < 75; i++) { requirement += "$"; }
for(int i = 0; i < 50; i++) { requirement += "*"; }
for(int i = 0; i < 25; i++) { requirement += "$"; }
REQUIRE( requirement == ss.str());
}
SECTION("Empty event - no switch, most basic use") {
auto f = [&ss](std::function<void(void)> switchToMainThread){};
EventThreader et(f);
et.join();
REQUIRE( ss.str() == "" );
}
SECTION("Empty event - no switch, main prints a thing") {
auto f = [&ss](std::function<void(void)> switchToMainThread){};
EventThreader et(f);
ss << "here";
et.join();
REQUIRE( ss.str() == "here" );
}
SECTION("no switch to event") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
et.join();
REQUIRE( ss.str() == "f" );
}
SECTION("one switch to event - trigger exception with type std::runtime_error") {
REQUIRE_THROWS_AS([&ss](){
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
et.switchToEventThread();
et.join();
}, std::runtime_error);
REQUIRE( ss.str() == "f" );
}
SECTION("one switch to event - trigger exception with text") {
REQUIRE_THROWS_WITH([&ss](){
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
et.switchToEventThread();
et.join();
}, "calling thread is not ready to join");
}
SECTION("two switch to event - trigger exception with type std::runtime_error") {
REQUIRE_THROWS_AS([&ss](){
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
et.switchToEventThread();
et.switchToEventThread();
et.join();
}, std::runtime_error);
REQUIRE( ss.str() == "f" );
}
SECTION("two switch to event - trigger exception with text") {
REQUIRE_THROWS_WITH([&ss](){
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
et.switchToEventThread();
et.switchToEventThread();
et.join();
}, "calling thread is not ready to join");
}
SECTION("print order") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << 1;
switchToMainThread();
ss << 3;
switchToMainThread();
ss << 5;
switchToMainThread();
};
EventThreader et(f);
ss << 0;
et.switchToEventThread();
ss << 2;
et.switchToEventThread();
ss << 4;
et.switchToEventThread();
ss << 6;
et.join();
REQUIRE( ss.str() == "0123456" );
}
SECTION("no event switch to main") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "1";
ss << "2";
};
EventThreader et(f);
et.join();
REQUIRE( ss.str() == "12" );
}
SECTION("one event switch to main") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "1";
switchToMainThread();
ss << "2";
};
EventThreader et(f);
et.switchToEventThread();
et.join();
REQUIRE( ss.str() == "1" );
}
SECTION("premiture join with exception message") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
switchToMainThread();
switchToMainThread();
};
EventThreader et(f);
et.switchToEventThread();
REQUIRE_THROWS_WITH([&et](){
et.join();
}, "EventThreader attempted join but event thread is still running");
}
SECTION("EventThreader when event still running") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
switchToMainThread();
switchToMainThread();
};
EventThreader* et = new EventThreader(f);
et->switchToEventThread();
REQUIRE_THROWS_WITH([&et](){
delete et;
}, "EventThreader attempted deconstructor but event thread is still running");
}
}
<commit_msg>condensed some tests<commit_after>#include "catch.hpp"
#include <iostream> // std::cout, std::endl
#include <exception> // std::bad_function_call, std::runtime_error
#include <thread> // std::thread, std::this_thread::yield
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
#include <functional> // std::function
/**
* The EventThreader class runs two threads simutaniously but not at the same
* time. The switching between threads is controlled by the EventThreader
* class. The two threads are the current thread (named the calling thread)
* and the second thread is spawned from a given function (event thread). The
* event thread is spawned and paused in the construction of the EventThreader
* class.
*
* Operation
* Only the calling thread will run until it requests that event thread is run.
* While one thread is running, it is guaranteed that the other is paused. On
* EventThreader construction, the event thead is paused. The event thread is
* invoked (and the calling thread paused) either with calls
* EventThreader::join() or EventThreader::switchToEventThread(). From the
* event thread, the calling thread can be invoked by a call to the event
* threads function parameter.
*
* The EventThreader takes one parameter on construction to be a functional
* object f of type void(void(void)). f will be the function run as the event
* thread. f's parameter is the function that invokes the event thread to
* pause, allowing the calling thread to continue.
*
* Every call to EventThreader::switchToEventThread() from the calling thread
* must be followed by a call EventThreader::switchToCallingThread() via
* calling the event theads functional parameter from the event thread.
*/
class EventThreader {
private:
std::condition_variable event_waiter, calling_waiter;
std::unique_lock<std::mutex>* event_lock, * calling_lock;
std::mutex mtx;
std::thread event_thread;
void switchToCallingThread();
bool request_end_of_event = false;
bool waiting_for_event = false;
bool event_ended = false;
std::function<void(void)> event_cleanup;
std::runtime_error* exception_from_the_event_thread;
public:
EventThreader(std::function<void (std::function<void (void)>)> func);
~EventThreader();
void switchToEventThread();
void join();
void setEventCleanup(std::function<void(void)>);
};
EventThreader::EventThreader(std::function<void (std::function<void (void)>)> func) {
exception_from_the_event_thread = nullptr;
calling_lock = new std::unique_lock<std::mutex>(mtx);
event_cleanup = [](){}; // empty function
auto event = [&](){
/* mtx force switch to calling - blocked by the mutex */
event_lock = new std::unique_lock<std::mutex>(mtx);
calling_waiter.notify_one();
event_waiter.wait(*event_lock);
std::this_thread::yield();
try {
func([&](){switchToCallingThread();});
if (waiting_for_event) { // the event has ended, but not ready to join
// rejoin the calling thread after dealing with this exception
calling_waiter.notify_one();
throw std::runtime_error("calling thread is not ready to join");
}
} catch (const std::runtime_error &e) {
/* report the exception to the calling thread */
exception_from_the_event_thread = new std::runtime_error(e);
}
delete event_lock;
event_cleanup();
event_ended = true;
};
event_thread = std::thread(event);
std::this_thread::yield();
calling_waiter.wait(*calling_lock);
std::this_thread::yield();
}
EventThreader::~EventThreader() {}
void EventThreader::switchToCallingThread() {
if (request_end_of_event) {
std::runtime_error err("calling thread requested join, cannot call switchToCallingThread()");
throw err;
}
/* switch to calling */
calling_waiter.notify_one();
std::this_thread::yield();
event_waiter.wait(*event_lock);
std::this_thread::yield();
/* back from calling */
}
void EventThreader::switchToEventThread() {
if (event_ended) {
throw std::runtime_error("event thread ended, cannot switch to it");
}
waiting_for_event = true;
/* switch to event */
event_waiter.notify_one();
std::this_thread::yield();
calling_waiter.wait(*calling_lock);
std::this_thread::yield();
/* back from event */
waiting_for_event = false;
}
void EventThreader::join() {
request_end_of_event = true;
delete calling_lock; // remove lock on this thread, allow event to run
event_waiter.notify_one();
std::this_thread::yield();
event_thread.join();
if (exception_from_the_event_thread != nullptr) {
/* an exception occured */
std::runtime_error e_copy(exception_from_the_event_thread->what());
delete exception_from_the_event_thread;
throw e_copy;
}
}
void EventThreader::setEventCleanup(std::function<void(void)> cleanup) {
event_cleanup = cleanup;
}
TEST_CASE( "EventThreader", "[EventThreader]" ) {
std::stringstream ss;
SECTION("Abitrary use") {
/* Example of most basic use */
auto f = [&ss](std::function<void(void)> switchToMainThread){
for(int i = 0; i < 100; i++) { ss << "*"; }
switchToMainThread();
for(int i = 0; i < 50; i++) { ss << "*"; }
switchToMainThread();
};
EventThreader et(f);
et.switchToEventThread();
for(int i = 0; i < 75; i++) { ss << "$"; }
et.switchToEventThread();
for(int i = 0; i < 25; i++) { ss << "$"; }
et.join();
/* Generate what the result should look like */
std::string requirement;
for(int i = 0; i < 100; i++) { requirement += "*"; }
for(int i = 0; i < 75; i++) { requirement += "$"; }
for(int i = 0; i < 50; i++) { requirement += "*"; }
for(int i = 0; i < 25; i++) { requirement += "$"; }
REQUIRE( requirement == ss.str());
}
SECTION("Empty event - no switch, most basic use") {
auto f = [&ss](std::function<void(void)> switchToMainThread){};
EventThreader et(f);
et.join();
REQUIRE( ss.str() == "" );
}
SECTION("Empty event - no switch, main prints a thing") {
auto f = [&ss](std::function<void(void)> switchToMainThread){};
EventThreader et(f);
ss << "here";
et.join();
REQUIRE( ss.str() == "here" );
}
SECTION("event is run without switch") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
et.join();
REQUIRE( ss.str() == "f" );
}
SECTION("event is run at join (not asked to run before)") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
ss << "p";
et.join();
REQUIRE( ss.str() == "pf" );
}
SECTION("one switch to event without a switch to main") {
auto f = [&ss](){
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
et.switchToEventThread();
et.join();
};
REQUIRE_THROWS_AS(f(), std::runtime_error);
REQUIRE( ss.str() == "f" );
REQUIRE_THROWS_WITH(f(), "calling thread is not ready to join");
REQUIRE( ss.str() == "ff" );
}
SECTION("two switch to event - trigger exception with type std::runtime_error") {
REQUIRE_THROWS_AS([&ss](){
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
et.switchToEventThread();
et.switchToEventThread();
et.join();
}(), std::runtime_error);
REQUIRE( ss.str() == "f" );
}
SECTION("two switch to event - trigger exception with text") {
REQUIRE_THROWS_WITH([&ss](){
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
et.switchToEventThread();
et.switchToEventThread();
et.join();
}(), "event thread ended, cannot switch to it");
}
SECTION("print order") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << 1;
switchToMainThread();
ss << 3;
switchToMainThread();
ss << 5;
switchToMainThread();
};
EventThreader et(f);
ss << 0;
et.switchToEventThread();
ss << 2;
et.switchToEventThread();
ss << 4;
et.switchToEventThread();
ss << 6;
et.join();
REQUIRE( ss.str() == "0123456" );
}
SECTION("no event switch to main") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "1";
ss << "2";
};
EventThreader et(f);
et.join();
REQUIRE( ss.str() == "12" );
}
SECTION("one event switch to main") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "1";
switchToMainThread();
ss << "2";
};
EventThreader et(f);
et.switchToEventThread();
et.join();
REQUIRE( ss.str() == "1" );
}
SECTION("premiture join with exception message") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
switchToMainThread();
switchToMainThread();
};
EventThreader et(f);
et.switchToEventThread();
REQUIRE_THROWS_WITH([&et](){
et.join();
}, "EventThreader attempted join but event thread is still running");
}
SECTION("EventThreader when event still running") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
switchToMainThread();
switchToMainThread();
};
EventThreader* et = new EventThreader(f);
et->switchToEventThread();
REQUIRE_THROWS_WITH([&et](){
delete et;
}(), "EventThreader attempted deconstructor but event thread is still running");
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <string>
// Loriano: let's try Armadillo quick code
#include <armadillo>
#define ENTDIM 8
#define COORDIM (ENTDIM-2)
namespace
{
int numofline (const char * fname)
{
int number_of_lines = 0;
std::string line;
std::ifstream myfile(fname);
while (std::getline(myfile, line))
++number_of_lines;
myfile.close();
return number_of_lines;
}
}
int main (int argc, char ** argv)
{
if (argc != 2)
{
std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl;
return 1;
}
int num_of_line = numofline(argv[1]);
std::cout << "file has " << num_of_line << " line " << std::endl;
int num_of_ent = (num_of_line-1)/ENTDIM;
std::cout << " " << num_of_ent << " entries " << std::endl;
// non perfomante ma easy to go
double ** param_mtx = new double *[num_of_ent];
double ** coord_mtx = new double *[num_of_ent];
for (int i = 0; i < num_of_ent; ++i)
{
coord_mtx[i] = new double[3*COORDIM];
param_mtx[i] = new double[5];
}
// leggere file coordinate tracce simulate plus parametri
std::string line;
std::ifstream mytfp;
mytfp.open (argv[1], std::ios::in);
std::getline (mytfp, line);
//std::cout << line << std::endl;
for (int i = 0; i < num_of_ent; ++i)
{
int fake1, fake2;
mytfp >> fake1 >> fake2 ;
#ifdef DEBUG
std::cout << fake1 << " " << fake2 << std::endl;
#endif
for (int j = 0; j < COORDIM; ++j)
{
int a, b, c;
mytfp >> coord_mtx[i][j*3] >>
coord_mtx[i][j*3+1] >>
coord_mtx[i][j*3+2] >>
a >> b >> c;
}
mytfp >> param_mtx[i][0] >>
param_mtx[i][1] >>
param_mtx[i][2] >>
param_mtx[i][3] >>
param_mtx[i][4];
}
mytfp.close();
#ifdef DEBUG
for (int i = 0; i < num_of_ent; ++i)
{
for (int j = 0; j < COORDIM; ++j)
{
std::cout << coord_mtx[i][j*3] << " " <<
coord_mtx[i][j*3+1] << " " <<
coord_mtx[i][j*3+2] << std::endl;
}
std::cout << param_mtx[i][0] << " " <<
param_mtx[i][1] << " " <<
param_mtx[i][2] << " " <<
param_mtx[i][3] << " " <<
param_mtx[i][4] << std::endl;
}
#endif
double sum = 1.0e0;
double coordm[3*COORDIM] = {0.0e0};
double hc[3*COORDIM][3*COORDIM] = {0.0e0};
for (int l=0; l<num_of_ent; ++l)
{
sum += 1.0e0;
for (int i=0; i<(3*COORDIM); ++i)
coordm[i] += (coord_mtx[l][i]-coordm[i])/sum;
for (int i=0; i<(3*COORDIM); ++i)
{
for (int j=0; j<(3*COORDIM); ++j)
{
hc[i][j] += ((coord_mtx[l][i] - coordm[i])*
(coord_mtx[l][j] - coordm[j])-
(sum-1.0e0)*hc[i][j]/sum)/(sum-1.0e0);
}
}
}
for (int i=0; i<(3*COORDIM); ++i)
for (int j=i+1; j<(3*COORDIM); ++j)
if (hc[i][j] != hc[j][i])
std::cout << i << " " << j << " " <<
hc[i][j] << " ERROR" << std::endl;;
arma::mat hca = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);
for (int i=0; i<(3*COORDIM); ++i)
for (int j=0; j<(3*COORDIM); ++j)
hca(i,j) = hc[i][j];
arma::vec eigval;
arma::mat eigvec;
arma::eig_sym(eigval, eigvec, hca);
double totval = 0.0e0;
for (int i=0; i<(3*COORDIM); ++i)
totval += eigval(i);
int j = 1;
double totvar = 0.0e0;
for (int i=(3*COORDIM-1); i>=0; --i)
{
if (j <= 5)
totvar += 100.0e0*(eigval(i)/totval);
++j;
std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << std::endl;
}
std::cout << "5 eigenvalues: " << totvar << std::endl;
// documento Annovi
// calcolo matrice di correlazione traccie HC
// diagonalizzo HC e determino A, matrice 5 autovettori principali (5 componenti pricipali)
// A matrice rotazione che mi permette di calcolare la traslazione usando i paamtri di tracce
// simulate.
// documento ATLAS
// calcolare V e data V calcolare inversa V e quindi C, matrice di rotazione
// data C determinare il vettore di traslazione q
// c plus q costanti PCA
// write constants in a file
for (int i = 0; i < num_of_ent; ++i)
{
delete(coord_mtx[i]);
delete(param_mtx[i]);
}
delete(coord_mtx);
delete(param_mtx);
return 0;
}
<commit_msg>quick note (i.e. pseudocode like)<commit_after>#include <iostream>
#include <fstream>
#include <string>
// Loriano: let's try Armadillo quick code
#include <armadillo>
#define ENTDIM 8
#define COORDIM (ENTDIM-2)
namespace
{
int numofline (const char * fname)
{
int number_of_lines = 0;
std::string line;
std::ifstream myfile(fname);
while (std::getline(myfile, line))
++number_of_lines;
myfile.close();
return number_of_lines;
}
}
int main (int argc, char ** argv)
{
if (argc != 2)
{
std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl;
return 1;
}
int num_of_line = numofline(argv[1]);
std::cout << "file has " << num_of_line << " line " << std::endl;
int num_of_ent = (num_of_line-1)/ENTDIM;
std::cout << " " << num_of_ent << " entries " << std::endl;
// non perfomante ma easy to go
double ** param_mtx = new double *[num_of_ent];
double ** coord_mtx = new double *[num_of_ent];
for (int i = 0; i < num_of_ent; ++i)
{
coord_mtx[i] = new double[3*COORDIM];
param_mtx[i] = new double[5];
}
// leggere file coordinate tracce simulate plus parametri
std::string line;
std::ifstream mytfp;
mytfp.open (argv[1], std::ios::in);
std::getline (mytfp, line);
//std::cout << line << std::endl;
for (int i = 0; i < num_of_ent; ++i)
{
int fake1, fake2;
mytfp >> fake1 >> fake2 ;
#ifdef DEBUG
std::cout << fake1 << " " << fake2 << std::endl;
#endif
for (int j = 0; j < COORDIM; ++j)
{
int a, b, c;
mytfp >> coord_mtx[i][j*3] >>
coord_mtx[i][j*3+1] >>
coord_mtx[i][j*3+2] >>
a >> b >> c;
}
mytfp >> param_mtx[i][0] >>
param_mtx[i][1] >>
param_mtx[i][2] >>
param_mtx[i][3] >>
param_mtx[i][4];
}
mytfp.close();
#ifdef DEBUG
for (int i = 0; i < num_of_ent; ++i)
{
for (int j = 0; j < COORDIM; ++j)
{
std::cout << coord_mtx[i][j*3] << " " <<
coord_mtx[i][j*3+1] << " " <<
coord_mtx[i][j*3+2] << std::endl;
}
std::cout << param_mtx[i][0] << " " <<
param_mtx[i][1] << " " <<
param_mtx[i][2] << " " <<
param_mtx[i][3] << " " <<
param_mtx[i][4] << std::endl;
}
#endif
double sum = 1.0e0;
double coordm[3*COORDIM] = {0.0e0};
double hc[3*COORDIM][3*COORDIM] = {0.0e0};
for (int l=0; l<num_of_ent; ++l)
{
sum += 1.0e0;
for (int i=0; i<(3*COORDIM); ++i)
coordm[i] += (coord_mtx[l][i]-coordm[i])/sum;
for (int i=0; i<(3*COORDIM); ++i)
{
for (int j=0; j<(3*COORDIM); ++j)
{
hc[i][j] += ((coord_mtx[l][i] - coordm[i])*
(coord_mtx[l][j] - coordm[j])-
(sum-1.0e0)*hc[i][j]/sum)/(sum-1.0e0);
}
}
}
for (int i=0; i<(3*COORDIM); ++i)
for (int j=i+1; j<(3*COORDIM); ++j)
if (hc[i][j] != hc[j][i])
std::cout << i << " " << j << " " <<
hc[i][j] << " ERROR" << std::endl;;
arma::mat hca = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);
for (int i=0; i<(3*COORDIM); ++i)
for (int j=0; j<(3*COORDIM); ++j)
hca(i,j) = hc[i][j];
arma::vec eigval;
arma::mat eigvec;
arma::eig_sym(eigval, eigvec, hca);
double totval = 0.0e0;
for (int i=0; i<(3*COORDIM); ++i)
totval += eigval(i);
int j = 1;
double totvar = 0.0e0;
for (int i=(3*COORDIM-1); i>=0; --i)
{
if (j <= 5)
totvar += 100.0e0*(eigval(i)/totval);
++j;
std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << std::endl;
}
std::cout << "5 eigenvalues: " << totvar << std::endl;
arma::mat hcai = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);
hcai = hca.i();
std::cout << hca * hcai ;
// and so on ...
// documento Annovi
// calcolo matrice di correlazione traccie HC
// diagonalizzo HC e determino A, matrice 5 autovettori principali (5 componenti pricipali)
// A matrice rotazione che mi permette di calcolare la traslazione usando i paamtri di tracce
// simulate.
// documento ATLAS
// calcolare V e data V calcolare inversa V e quindi C, matrice di rotazione
// data C determinare il vettore di traslazione q
// c plus q costanti PCA
// write constants in a file
for (int i = 0; i < num_of_ent; ++i)
{
delete(coord_mtx[i]);
delete(param_mtx[i]);
}
delete(coord_mtx);
delete(param_mtx);
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>Planning: minor changes in path_reuse_decider<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE entry.
#include "chrome/browser/sync/util/extensions_activity_monitor.h"
#include "base/file_path.h"
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/extensions/extension_bookmarks_module.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/notification_service.h"
#include "testing/gtest/include/gtest/gtest.h"
using browser_sync::ExtensionsActivityMonitor;
namespace keys = extension_manifest_keys;
namespace {
const char* kTestExtensionPath1 = "c:\\testextension1";
const char* kTestExtensionPath2 = "c:\\testextension2";
const char* kTestExtensionVersion = "1.0.0.0";
const char* kTestExtensionName = "foo extension";
template <class FunctionType>
class BookmarkAPIEventTask : public Task {
public:
BookmarkAPIEventTask(FunctionType* t, Extension* e, size_t repeats,
base::WaitableEvent* done) :
extension_(e), function_(t), repeats_(repeats), done_(done) {}
virtual void Run() {
for (size_t i = 0; i < repeats_; i++) {
NotificationService::current()->Notify(
NotificationType::EXTENSION_BOOKMARKS_API_INVOKED,
Source<Extension>(extension_.get()),
Details<const BookmarksFunction>(function_.get()));
}
done_->Signal();
}
private:
scoped_ptr<Extension> extension_;
scoped_refptr<FunctionType> function_;
size_t repeats_;
base::WaitableEvent* done_;
DISALLOW_COPY_AND_ASSIGN(BookmarkAPIEventTask);
};
class BookmarkAPIEventGenerator {
public:
BookmarkAPIEventGenerator() {}
virtual ~BookmarkAPIEventGenerator() {}
template <class T>
void NewEvent(const std::string& extension_path,
T* bookmarks_function, size_t repeats) {
#if defined(OS_WIN)
FilePath path(UTF8ToWide(extension_path));
#elif defined(OS_POSIX)
FilePath path(extension_path);
#endif
Extension* extension = new Extension(path);
std::string error;
DictionaryValue input;
input.SetString(keys::kVersion, kTestExtensionVersion);
input.SetString(keys::kName, kTestExtensionName);
extension->InitFromValue(input, false, &error);
bookmarks_function->set_name(T::function_name());
base::WaitableEvent done_event(false, false);
ChromeThread::PostTask(ChromeThread::UI, FROM_HERE,
new BookmarkAPIEventTask<T>(bookmarks_function, extension,
repeats, &done_event));
done_event.Wait();
}
private:
DISALLOW_COPY_AND_ASSIGN(BookmarkAPIEventGenerator);
};
} // namespace
class DoUIThreadSetupTask : public Task {
public:
DoUIThreadSetupTask(NotificationService** service,
base::WaitableEvent* done)
: service_(service), signal_when_done_(done) {}
virtual ~DoUIThreadSetupTask() {}
virtual void Run() {
*service_ = new NotificationService();
signal_when_done_->Signal();
}
private:
NotificationService** service_;
base::WaitableEvent* signal_when_done_;
DISALLOW_COPY_AND_ASSIGN(DoUIThreadSetupTask);
};
class ExtensionsActivityMonitorTest : public testing::Test {
public:
ExtensionsActivityMonitorTest() : service_(NULL),
ui_thread_(ChromeThread::UI) { }
virtual ~ExtensionsActivityMonitorTest() {}
virtual void SetUp() {
ui_thread_.Start();
base::WaitableEvent service_created(false, false);
ui_thread_.message_loop()->PostTask(FROM_HERE,
new DoUIThreadSetupTask(&service_, &service_created));
service_created.Wait();
}
virtual void TearDown() {
ui_thread_.message_loop()->DeleteSoon(FROM_HERE, service_);
ui_thread_.Stop();
}
MessageLoop* ui_loop() { return ui_thread_.message_loop(); }
static std::string GetExtensionIdForPath(const std::string& extension_path) {
std::string error;
#if defined(OS_WIN)
FilePath path(UTF8ToWide(extension_path));
#elif defined(OS_POSIX)
FilePath path(extension_path);
#endif
Extension e(path);
DictionaryValue input;
input.SetString(keys::kVersion, kTestExtensionVersion);
input.SetString(keys::kName, kTestExtensionName);
e.InitFromValue(input, false, &error);
EXPECT_EQ("", error);
return e.id();
}
private:
NotificationService* service_;
ChromeThread ui_thread_;
};
TEST_F(ExtensionsActivityMonitorTest, Basic) {
ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor();
BookmarkAPIEventGenerator generator;
generator.NewEvent<RemoveBookmarkFunction>(kTestExtensionPath1,
new RemoveBookmarkFunction(), 1);
generator.NewEvent<MoveBookmarkFunction>(kTestExtensionPath1,
new MoveBookmarkFunction(), 1);
generator.NewEvent<UpdateBookmarkFunction>(kTestExtensionPath1,
new UpdateBookmarkFunction(), 2);
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 3);
generator.NewEvent<SearchBookmarksFunction>(kTestExtensionPath1,
new SearchBookmarksFunction(), 5);
const uint32 writes_by_extension1 = 1 + 1 + 2 + 3;
generator.NewEvent<RemoveTreeBookmarkFunction>(kTestExtensionPath2,
new RemoveTreeBookmarkFunction(), 8);
generator.NewEvent<GetBookmarkTreeFunction>(kTestExtensionPath2,
new GetBookmarkTreeFunction(), 13);
generator.NewEvent<GetBookmarkChildrenFunction>(kTestExtensionPath2,
new GetBookmarkChildrenFunction(), 21);
generator.NewEvent<GetBookmarksFunction>(kTestExtensionPath2,
new GetBookmarksFunction(), 33);
const uint32 writes_by_extension2 = 8;
ExtensionsActivityMonitor::Records results;
monitor->GetAndClearRecords(&results);
std::string id1 = GetExtensionIdForPath(kTestExtensionPath1);
std::string id2 = GetExtensionIdForPath(kTestExtensionPath2);
EXPECT_EQ(2U, results.size());
EXPECT_TRUE(results.end() != results.find(id1));
EXPECT_TRUE(results.end() != results.find(id2));
EXPECT_EQ(writes_by_extension1, results[id1].bookmark_write_count);
EXPECT_EQ(writes_by_extension2, results[id2].bookmark_write_count);
ui_loop()->DeleteSoon(FROM_HERE, monitor);
}
TEST_F(ExtensionsActivityMonitorTest, Put) {
ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor();
BookmarkAPIEventGenerator generator;
std::string id1 = GetExtensionIdForPath(kTestExtensionPath1);
std::string id2 = GetExtensionIdForPath(kTestExtensionPath2);
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 5);
generator.NewEvent<MoveBookmarkFunction>(kTestExtensionPath2,
new MoveBookmarkFunction(), 8);
ExtensionsActivityMonitor::Records results;
monitor->GetAndClearRecords(&results);
EXPECT_EQ(2U, results.size());
EXPECT_EQ(5U, results[id1].bookmark_write_count);
EXPECT_EQ(8U, results[id2].bookmark_write_count);
generator.NewEvent<GetBookmarksFunction>(kTestExtensionPath2,
new GetBookmarksFunction(), 3);
generator.NewEvent<UpdateBookmarkFunction>(kTestExtensionPath2,
new UpdateBookmarkFunction(), 2);
// Simulate a commit failure, which augments the active record set with the
// refugee records.
monitor->PutRecords(results);
ExtensionsActivityMonitor::Records new_records;
monitor->GetAndClearRecords(&new_records);
EXPECT_EQ(2U, results.size());
EXPECT_EQ(id1, new_records[id1].extension_id);
EXPECT_EQ(id2, new_records[id2].extension_id);
EXPECT_EQ(5U, new_records[id1].bookmark_write_count);
EXPECT_EQ(8U + 2U, new_records[id2].bookmark_write_count);
ui_loop()->DeleteSoon(FROM_HERE, monitor);
}
TEST_F(ExtensionsActivityMonitorTest, MultiGet) {
ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor();
BookmarkAPIEventGenerator generator;
std::string id1 = GetExtensionIdForPath(kTestExtensionPath1);
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 5);
ExtensionsActivityMonitor::Records results;
monitor->GetAndClearRecords(&results);
EXPECT_EQ(1U, results.size());
EXPECT_EQ(5U, results[id1].bookmark_write_count);
monitor->GetAndClearRecords(&results);
EXPECT_TRUE(results.empty());
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 3);
monitor->GetAndClearRecords(&results);
EXPECT_EQ(1U, results.size());
EXPECT_EQ(3U, results[id1].bookmark_write_count);
ui_loop()->DeleteSoon(FROM_HERE, monitor);
}
<commit_msg>Fix the extensions activity monitor test for POSIX (c:\? Really?)<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE entry.
#include "chrome/browser/sync/util/extensions_activity_monitor.h"
#include "base/file_path.h"
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/extensions/extension_bookmarks_module.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/notification_service.h"
#include "testing/gtest/include/gtest/gtest.h"
using browser_sync::ExtensionsActivityMonitor;
namespace keys = extension_manifest_keys;
namespace {
const FilePath::CharType kTestExtensionPath1[] =
#if defined(OS_POSIX)
FILE_PATH_LITERAL("/testextension1");
#elif defined(OS_WIN)
FILE_PATH_LITERAL("c:\\testextension1");
#endif
const FilePath::CharType kTestExtensionPath2[] =
#if defined(OS_POSIX)
FILE_PATH_LITERAL("/testextension2");
#elif defined(OS_WIN)
FILE_PATH_LITERAL("c:\\testextension2");
#endif
const char* kTestExtensionVersion = "1.0.0.0";
const char* kTestExtensionName = "foo extension";
template <class FunctionType>
class BookmarkAPIEventTask : public Task {
public:
BookmarkAPIEventTask(FunctionType* t, Extension* e, size_t repeats,
base::WaitableEvent* done) :
extension_(e), function_(t), repeats_(repeats), done_(done) {}
virtual void Run() {
for (size_t i = 0; i < repeats_; i++) {
NotificationService::current()->Notify(
NotificationType::EXTENSION_BOOKMARKS_API_INVOKED,
Source<Extension>(extension_.get()),
Details<const BookmarksFunction>(function_.get()));
}
done_->Signal();
}
private:
scoped_ptr<Extension> extension_;
scoped_refptr<FunctionType> function_;
size_t repeats_;
base::WaitableEvent* done_;
DISALLOW_COPY_AND_ASSIGN(BookmarkAPIEventTask);
};
class BookmarkAPIEventGenerator {
public:
BookmarkAPIEventGenerator() {}
virtual ~BookmarkAPIEventGenerator() {}
template <class T>
void NewEvent(const FilePath::StringType& extension_path,
T* bookmarks_function, size_t repeats) {
FilePath path(extension_path);
Extension* extension = new Extension(path);
std::string error;
DictionaryValue input;
input.SetString(keys::kVersion, kTestExtensionVersion);
input.SetString(keys::kName, kTestExtensionName);
extension->InitFromValue(input, false, &error);
bookmarks_function->set_name(T::function_name());
base::WaitableEvent done_event(false, false);
ChromeThread::PostTask(ChromeThread::UI, FROM_HERE,
new BookmarkAPIEventTask<T>(bookmarks_function, extension,
repeats, &done_event));
done_event.Wait();
}
private:
DISALLOW_COPY_AND_ASSIGN(BookmarkAPIEventGenerator);
};
} // namespace
class DoUIThreadSetupTask : public Task {
public:
DoUIThreadSetupTask(NotificationService** service,
base::WaitableEvent* done)
: service_(service), signal_when_done_(done) {}
virtual ~DoUIThreadSetupTask() {}
virtual void Run() {
*service_ = new NotificationService();
signal_when_done_->Signal();
}
private:
NotificationService** service_;
base::WaitableEvent* signal_when_done_;
DISALLOW_COPY_AND_ASSIGN(DoUIThreadSetupTask);
};
class ExtensionsActivityMonitorTest : public testing::Test {
public:
ExtensionsActivityMonitorTest() : service_(NULL),
ui_thread_(ChromeThread::UI) { }
virtual ~ExtensionsActivityMonitorTest() {}
virtual void SetUp() {
ui_thread_.Start();
base::WaitableEvent service_created(false, false);
ui_thread_.message_loop()->PostTask(FROM_HERE,
new DoUIThreadSetupTask(&service_, &service_created));
service_created.Wait();
}
virtual void TearDown() {
ui_thread_.message_loop()->DeleteSoon(FROM_HERE, service_);
ui_thread_.Stop();
}
MessageLoop* ui_loop() { return ui_thread_.message_loop(); }
static std::string GetExtensionIdForPath(
const FilePath::StringType& extension_path) {
std::string error;
FilePath path(extension_path);
Extension e(path);
DictionaryValue input;
input.SetString(keys::kVersion, kTestExtensionVersion);
input.SetString(keys::kName, kTestExtensionName);
e.InitFromValue(input, false, &error);
EXPECT_EQ("", error);
return e.id();
}
private:
NotificationService* service_;
ChromeThread ui_thread_;
};
TEST_F(ExtensionsActivityMonitorTest, Basic) {
ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor();
BookmarkAPIEventGenerator generator;
generator.NewEvent<RemoveBookmarkFunction>(kTestExtensionPath1,
new RemoveBookmarkFunction(), 1);
generator.NewEvent<MoveBookmarkFunction>(kTestExtensionPath1,
new MoveBookmarkFunction(), 1);
generator.NewEvent<UpdateBookmarkFunction>(kTestExtensionPath1,
new UpdateBookmarkFunction(), 2);
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 3);
generator.NewEvent<SearchBookmarksFunction>(kTestExtensionPath1,
new SearchBookmarksFunction(), 5);
const uint32 writes_by_extension1 = 1 + 1 + 2 + 3;
generator.NewEvent<RemoveTreeBookmarkFunction>(kTestExtensionPath2,
new RemoveTreeBookmarkFunction(), 8);
generator.NewEvent<GetBookmarkTreeFunction>(kTestExtensionPath2,
new GetBookmarkTreeFunction(), 13);
generator.NewEvent<GetBookmarkChildrenFunction>(kTestExtensionPath2,
new GetBookmarkChildrenFunction(), 21);
generator.NewEvent<GetBookmarksFunction>(kTestExtensionPath2,
new GetBookmarksFunction(), 33);
const uint32 writes_by_extension2 = 8;
ExtensionsActivityMonitor::Records results;
monitor->GetAndClearRecords(&results);
std::string id1 = GetExtensionIdForPath(kTestExtensionPath1);
std::string id2 = GetExtensionIdForPath(kTestExtensionPath2);
EXPECT_EQ(2U, results.size());
EXPECT_TRUE(results.end() != results.find(id1));
EXPECT_TRUE(results.end() != results.find(id2));
EXPECT_EQ(writes_by_extension1, results[id1].bookmark_write_count);
EXPECT_EQ(writes_by_extension2, results[id2].bookmark_write_count);
ui_loop()->DeleteSoon(FROM_HERE, monitor);
}
TEST_F(ExtensionsActivityMonitorTest, Put) {
ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor();
BookmarkAPIEventGenerator generator;
std::string id1 = GetExtensionIdForPath(kTestExtensionPath1);
std::string id2 = GetExtensionIdForPath(kTestExtensionPath2);
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 5);
generator.NewEvent<MoveBookmarkFunction>(kTestExtensionPath2,
new MoveBookmarkFunction(), 8);
ExtensionsActivityMonitor::Records results;
monitor->GetAndClearRecords(&results);
EXPECT_EQ(2U, results.size());
EXPECT_EQ(5U, results[id1].bookmark_write_count);
EXPECT_EQ(8U, results[id2].bookmark_write_count);
generator.NewEvent<GetBookmarksFunction>(kTestExtensionPath2,
new GetBookmarksFunction(), 3);
generator.NewEvent<UpdateBookmarkFunction>(kTestExtensionPath2,
new UpdateBookmarkFunction(), 2);
// Simulate a commit failure, which augments the active record set with the
// refugee records.
monitor->PutRecords(results);
ExtensionsActivityMonitor::Records new_records;
monitor->GetAndClearRecords(&new_records);
EXPECT_EQ(2U, results.size());
EXPECT_EQ(id1, new_records[id1].extension_id);
EXPECT_EQ(id2, new_records[id2].extension_id);
EXPECT_EQ(5U, new_records[id1].bookmark_write_count);
EXPECT_EQ(8U + 2U, new_records[id2].bookmark_write_count);
ui_loop()->DeleteSoon(FROM_HERE, monitor);
}
TEST_F(ExtensionsActivityMonitorTest, MultiGet) {
ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor();
BookmarkAPIEventGenerator generator;
std::string id1 = GetExtensionIdForPath(kTestExtensionPath1);
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 5);
ExtensionsActivityMonitor::Records results;
monitor->GetAndClearRecords(&results);
EXPECT_EQ(1U, results.size());
EXPECT_EQ(5U, results[id1].bookmark_write_count);
monitor->GetAndClearRecords(&results);
EXPECT_TRUE(results.empty());
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 3);
monitor->GetAndClearRecords(&results);
EXPECT_EQ(1U, results.size());
EXPECT_EQ(3U, results[id1].bookmark_write_count);
ui_loop()->DeleteSoon(FROM_HERE, monitor);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/views/browser_actions_container.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_action.h"
#include "chrome/common/extensions/extension_resource.h"
class BrowserActionsContainerTest : public ExtensionBrowserTest {
public:
BrowserActionsContainerTest() : browser_(NULL) {
}
virtual ~BrowserActionsContainerTest() {}
virtual Browser* CreateBrowser(Profile* profile) {
browser_ = InProcessBrowserTest::CreateBrowser(profile);
browser_actions_bar_.reset(new BrowserActionTestUtil(browser_));
return browser_;
}
Browser* browser() { return browser_; }
BrowserActionTestUtil* browser_actions_bar() {
return browser_actions_bar_.get();
}
// Make sure extension with index |extension_index| has an icon.
void EnsureExtensionHasIcon(int extension_index) {
if (!browser_actions_bar_->HasIcon(extension_index)) {
// The icon is loaded asynchronously and a notification is then sent to
// observers. So we wait on it.
browser_actions_bar_->WaitForBrowserActionUpdated(extension_index);
}
EXPECT_TRUE(browser_actions_bar()->HasIcon(extension_index));
}
private:
scoped_ptr<BrowserActionTestUtil> browser_actions_bar_;
Browser* browser_; // Weak.
};
// Test the basic functionality.
IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, Basic) {
BrowserActionsContainer::disable_animations_during_testing_ = true;
// Load an extension with no browser action.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("none")));
// This extension should not be in the model (has no browser action).
EXPECT_EQ(0, browser_actions_bar()->NumberOfBrowserActions());
// Load an extension with a browser action.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics")));
EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions());
EnsureExtensionHasIcon(0);
// Unload the extension.
std::string id = browser_actions_bar()->GetExtensionId(0);
UnloadExtension(id);
EXPECT_EQ(0, browser_actions_bar()->NumberOfBrowserActions());
}
// TODO(mpcomplete): http://code.google.com/p/chromium/issues/detail?id=38992
// Disabled, http://crbug.com/38992.
IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, DISABLED_Visibility) {
BrowserActionsContainer::disable_animations_during_testing_ = true;
// Load extension A (contains browser action).
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics")));
EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions());
EnsureExtensionHasIcon(0);
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
std::string idA = browser_actions_bar()->GetExtensionId(0);
// Load extension B (contains browser action).
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("add_popup")));
EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
EnsureExtensionHasIcon(0);
EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
std::string idB = browser_actions_bar()->GetExtensionId(1);
EXPECT_NE(idA, idB);
// Load extension C (contains browser action).
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup")));
EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions());
EnsureExtensionHasIcon(2);
EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions());
std::string idC = browser_actions_bar()->GetExtensionId(2);
// Change container to show only one action, rest in overflow: A, [B, C].
browser_actions_bar()->SetIconVisibilityCount(1);
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
// Disable extension A (should disappear). State becomes: B [C].
DisableExtension(idA);
EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idB, browser_actions_bar()->GetExtensionId(0));
// Enable A again. A should get its spot in the same location and the bar
// should not grow (chevron is showing). For details: http://crbug.com/35349.
// State becomes: A, [B, C].
EnableExtension(idA);
EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(0));
// Disable C (in overflow). State becomes: A, [B].
DisableExtension(idC);
EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(0));
// Enable C again. State becomes: A, [B, C].
EnableExtension(idC);
EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(0));
// Now we have 3 extensions. Make sure they are all visible. State: A, B, C.
browser_actions_bar()->SetIconVisibilityCount(3);
EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions());
// Disable extension A (should disappear). State becomes: B, C.
DisableExtension(idA);
EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idB, browser_actions_bar()->GetExtensionId(0));
// Disable extension B (should disappear). State becomes: C.
DisableExtension(idB);
EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idC, browser_actions_bar()->GetExtensionId(0));
// Enable B (makes B and C showing now). State becomes: B, C.
EnableExtension(idB);
EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idB, browser_actions_bar()->GetExtensionId(0));
// Enable A (makes A, B and C showing now). State becomes: B, C, A.
EnableExtension(idA);
EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(2));
}
IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, ForceHide) {
BrowserActionsContainer::disable_animations_during_testing_ = true;
// Load extension A (contains browser action).
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics")));
EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions());
EnsureExtensionHasIcon(0);
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
std::string idA = browser_actions_bar()->GetExtensionId(0);
// Force hide this browser action.
ExtensionsService* service = browser()->profile()->GetExtensionsService();
service->SetBrowserActionVisibility(service->GetExtensionById(idA, false),
false);
EXPECT_EQ(0, browser_actions_bar()->VisibleBrowserActions());
ReloadExtension(idA);
// The browser action should become visible again.
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
}
IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, TestCrash57536) {
std::cout << "Test starting\n" << std::flush;
ExtensionsService* service = browser()->profile()->GetExtensionsService();
const size_t size_before = service->extensions()->size();
std::cout << "Loading extension\n" << std::flush;
// Load extension A (contains browser action).
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("crash_57536")));
const Extension* extension = service->extensions()->at(size_before);
std::cout << "Creating bitmap\n" << std::flush;
// Create and cache and empty bitmap.
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config,
Extension::kBrowserActionIconMaxSize,
Extension::kBrowserActionIconMaxSize);
bitmap.allocPixels();
std::cout << "Set as cached image\n" << std::flush;
gfx::Size size(Extension::kBrowserActionIconMaxSize,
Extension::kBrowserActionIconMaxSize);
extension->SetCachedImage(
extension->GetResource(extension->browser_action()->default_icon_path()),
bitmap,
size);
std::cout << "Disabling extension\n" << std::flush;
DisableExtension(extension->id());
std::cout << "Enabling extension\n" << std::flush;
EnableExtension(extension->id());
std::cout << "Test ending\n" << std::flush;
}
<commit_msg>Reenable BrowserActionsContainerTest.Visibility with timing info, since I suspect the problem is that the test is just a bit too long for the timeout value we use.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/views/browser_actions_container.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_action.h"
#include "chrome/common/extensions/extension_resource.h"
class BrowserActionsContainerTest : public ExtensionBrowserTest {
public:
BrowserActionsContainerTest() : browser_(NULL) {
}
virtual ~BrowserActionsContainerTest() {}
virtual Browser* CreateBrowser(Profile* profile) {
browser_ = InProcessBrowserTest::CreateBrowser(profile);
browser_actions_bar_.reset(new BrowserActionTestUtil(browser_));
return browser_;
}
Browser* browser() { return browser_; }
BrowserActionTestUtil* browser_actions_bar() {
return browser_actions_bar_.get();
}
// Make sure extension with index |extension_index| has an icon.
void EnsureExtensionHasIcon(int extension_index) {
if (!browser_actions_bar_->HasIcon(extension_index)) {
// The icon is loaded asynchronously and a notification is then sent to
// observers. So we wait on it.
browser_actions_bar_->WaitForBrowserActionUpdated(extension_index);
}
EXPECT_TRUE(browser_actions_bar()->HasIcon(extension_index));
}
private:
scoped_ptr<BrowserActionTestUtil> browser_actions_bar_;
Browser* browser_; // Weak.
};
// Test the basic functionality.
IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, Basic) {
BrowserActionsContainer::disable_animations_during_testing_ = true;
// Load an extension with no browser action.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("none")));
// This extension should not be in the model (has no browser action).
EXPECT_EQ(0, browser_actions_bar()->NumberOfBrowserActions());
// Load an extension with a browser action.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics")));
EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions());
EnsureExtensionHasIcon(0);
// Unload the extension.
std::string id = browser_actions_bar()->GetExtensionId(0);
UnloadExtension(id);
EXPECT_EQ(0, browser_actions_bar()->NumberOfBrowserActions());
}
// TODO(mpcomplete): http://code.google.com/p/chromium/issues/detail?id=38992
IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, Visibility) {
BrowserActionsContainer::disable_animations_during_testing_ = true;
base::TimeTicks start_time = base::TimeTicks::Now();
// Load extension A (contains browser action).
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics")));
EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions());
EnsureExtensionHasIcon(0);
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
std::string idA = browser_actions_bar()->GetExtensionId(0);
LOG(INFO) << "Load extension A done : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
// Load extension B (contains browser action).
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("add_popup")));
EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
EnsureExtensionHasIcon(0);
EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
std::string idB = browser_actions_bar()->GetExtensionId(1);
LOG(INFO) << "Load extension B done : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
EXPECT_NE(idA, idB);
// Load extension C (contains browser action).
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup")));
EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions());
EnsureExtensionHasIcon(2);
EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions());
std::string idC = browser_actions_bar()->GetExtensionId(2);
LOG(INFO) << "Load extension C done : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
// Change container to show only one action, rest in overflow: A, [B, C].
browser_actions_bar()->SetIconVisibilityCount(1);
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
LOG(INFO) << "Icon visibility count 1: "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
// Disable extension A (should disappear). State becomes: B [C].
DisableExtension(idA);
EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idB, browser_actions_bar()->GetExtensionId(0));
LOG(INFO) << "Disable extension A : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
// Enable A again. A should get its spot in the same location and the bar
// should not grow (chevron is showing). For details: http://crbug.com/35349.
// State becomes: A, [B, C].
EnableExtension(idA);
EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(0));
LOG(INFO) << "Enable extension A : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
// Disable C (in overflow). State becomes: A, [B].
DisableExtension(idC);
EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(0));
LOG(INFO) << "Disable extension C : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
// Enable C again. State becomes: A, [B, C].
EnableExtension(idC);
EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(0));
LOG(INFO) << "Enable extension C : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
// Now we have 3 extensions. Make sure they are all visible. State: A, B, C.
browser_actions_bar()->SetIconVisibilityCount(3);
EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions());
LOG(INFO) << "Checkpoint : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
// Disable extension A (should disappear). State becomes: B, C.
DisableExtension(idA);
EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idB, browser_actions_bar()->GetExtensionId(0));
LOG(INFO) << "Disable extension A : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
// Disable extension B (should disappear). State becomes: C.
DisableExtension(idB);
EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idC, browser_actions_bar()->GetExtensionId(0));
LOG(INFO) << "Disable extension B : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
// Enable B (makes B and C showing now). State becomes: B, C.
EnableExtension(idB);
EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idB, browser_actions_bar()->GetExtensionId(0));
LOG(INFO) << "Enable extension B : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
// Enable A (makes A, B and C showing now). State becomes: B, C, A.
EnableExtension(idA);
EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(2));
LOG(INFO) << "Test complete : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
}
IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, ForceHide) {
BrowserActionsContainer::disable_animations_during_testing_ = true;
// Load extension A (contains browser action).
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics")));
EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions());
EnsureExtensionHasIcon(0);
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
std::string idA = browser_actions_bar()->GetExtensionId(0);
// Force hide this browser action.
ExtensionsService* service = browser()->profile()->GetExtensionsService();
service->SetBrowserActionVisibility(service->GetExtensionById(idA, false),
false);
EXPECT_EQ(0, browser_actions_bar()->VisibleBrowserActions());
ReloadExtension(idA);
// The browser action should become visible again.
EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
}
IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, TestCrash57536) {
LOG(INFO) << "Test starting\n" << std::flush;
ExtensionsService* service = browser()->profile()->GetExtensionsService();
const size_t size_before = service->extensions()->size();
LOG(INFO) << "Loading extension\n" << std::flush;
// Load extension A (contains browser action).
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("crash_57536")));
const Extension* extension = service->extensions()->at(size_before);
LOG(INFO) << "Creating bitmap\n" << std::flush;
// Create and cache and empty bitmap.
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config,
Extension::kBrowserActionIconMaxSize,
Extension::kBrowserActionIconMaxSize);
bitmap.allocPixels();
LOG(INFO) << "Set as cached image\n" << std::flush;
gfx::Size size(Extension::kBrowserActionIconMaxSize,
Extension::kBrowserActionIconMaxSize);
extension->SetCachedImage(
extension->GetResource(extension->browser_action()->default_icon_path()),
bitmap,
size);
LOG(INFO) << "Disabling extension\n" << std::flush;
DisableExtension(extension->id());
LOG(INFO) << "Enabling extension\n" << std::flush;
EnableExtension(extension->id());
LOG(INFO) << "Test ending\n" << std::flush;
}
<|endoftext|>
|
<commit_before>//
// "$Id$"
//
// Filename list routines for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2005 by Bill Spitzak and others.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library 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.
//
// Please report all bugs and problems on the following page:
//
// http://www.fltk.org/str.php
//
// Wrapper for scandir with const-correct function prototypes.
#include <FL/filename.H>
#include "flstring.h"
#include <stdlib.h>
// OTB Modifications
//#include <config.h>
#include "fltk-config.h"
extern "C" {
#ifndef HAVE_SCANDIR
int fl_scandir (const char *dir, dirent ***namelist,
int (*select)(dirent *),
int (*compar)(dirent **, dirent **));
# define scandir fl_scandir
#endif
}
int fl_alphasort(struct dirent **a, struct dirent **b) {
return strcmp((*a)->d_name, (*b)->d_name);
}
int fl_casealphasort(struct dirent **a, struct dirent **b) {
return strcasecmp((*a)->d_name, (*b)->d_name);
}
int fl_filename_list(const char *d, dirent ***list,
Fl_File_Sort_F *sort) {
#ifndef HAVE_SCANDIR
int n = scandir(d, list, 0, sort);
#elif defined(__hpux) || defined(__CYGWIN__)
// HP-UX, Cygwin define the comparison function like this:
int n = scandir(d, list, 0, (int(*)(const dirent **, const dirent **))sort);
#elif defined(__osf__)
// OSF, DU 4.0x
int n = scandir(d, list, 0, (int(*)(dirent **, dirent **))sort);
#elif defined(_AIX)
// AIX is almost standard...
int n = scandir(d, list, 0, (int(*)(void*, void*))sort);
#elif !defined(__sgi)
// The vast majority of UNIX systems want the sort function to have this
// prototype, most likely so that it can be passed to qsort without any
// changes:
int n = scandir(d, list, 0, (int(*)(const void*,const void*))sort);
#else
// This version is when we define our own scandir (WIN32 and perhaps
// some Unix systems) and apparently on IRIX:
int n = scandir(d, list, 0, sort);
#endif
#if defined(WIN32) && !defined(__CYGWIN__)
// we did this already during fl_scandir/win32
#else
// append a '/' to all filenames that are directories
int i, dirlen = strlen(d);
char *fullname = (char*)malloc(dirlen+FL_PATH_MAX+3); // Add enough extra for two /'s and a nul
// Use memcpy for speed since we already know the length of the string...
memcpy(fullname, d, dirlen+1);
char *name = fullname + dirlen;
if (name!=fullname && name[-1]!='/') *name++ = '/';
for (i=0; i<n; i++) {
dirent *de = (*list)[i];
int len = strlen(de->d_name);
if (de->d_name[len-1]=='/' || len>FL_PATH_MAX) continue;
// Use memcpy for speed since we already know the length of the string...
memcpy(name, de->d_name, len+1);
if (fl_filename_isdir(fullname)) {
(*list)[i] = de = (dirent*)realloc(de, de->d_name - (char*)de + len + 2);
char *dst = de->d_name + len;
*dst++ = '/';
*dst = 0;
}
}
free(fullname);
#endif
return n;
}
//
// End of "$Id$".
//
<commit_msg>COMP: fix FLTK compilation problem on open solaris<commit_after>//
// "$Id$"
//
// Filename list routines for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2005 by Bill Spitzak and others.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library 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.
//
// Please report all bugs and problems on the following page:
//
// http://www.fltk.org/str.php
//
// Wrapper for scandir with const-correct function prototypes.
#include <FL/filename.H>
#include "flstring.h"
#include <stdlib.h>
// OTB Modifications
//#include <config.h>
#include "fltk-config.h"
extern "C" {
#ifndef HAVE_SCANDIR
int fl_scandir (const char *dir, dirent ***namelist,
int (*select)(dirent *),
int (*compar)(dirent **, dirent **));
# define scandir fl_scandir
#endif
}
int fl_alphasort(struct dirent **a, struct dirent **b) {
return strcmp((*a)->d_name, (*b)->d_name);
}
int fl_casealphasort(struct dirent **a, struct dirent **b) {
return strcasecmp((*a)->d_name, (*b)->d_name);
}
int fl_filename_list(const char *d, dirent ***list,
Fl_File_Sort_F *sort) {
#ifndef HAVE_SCANDIR
int n = scandir(d, list, 0, sort);
#elif defined(__hpux) || defined(__CYGWIN__) || defined(sun)
// HP-UX, Cygwin define the comparison function like this:
int n = scandir(d, list, 0, (int(*)(const dirent **, const dirent **))sort);
#elif defined(__osf__)
// OSF, DU 4.0x
int n = scandir(d, list, 0, (int(*)(dirent **, dirent **))sort);
#elif defined(_AIX)
// AIX is almost standard...
int n = scandir(d, list, 0, (int(*)(void*, void*))sort);
#elif !defined(__sgi)
// The vast majority of UNIX systems want the sort function to have this
// prototype, most likely so that it can be passed to qsort without any
// changes:
int n = scandir(d, list, 0, (int(*)(const void*,const void*))sort);
#else
// This version is when we define our own scandir (WIN32 and perhaps
// some Unix systems) and apparently on IRIX:
int n = scandir(d, list, 0, sort);
#endif
#if defined(WIN32) && !defined(__CYGWIN__)
// we did this already during fl_scandir/win32
#else
// append a '/' to all filenames that are directories
int i, dirlen = strlen(d);
char *fullname = (char*)malloc(dirlen+FL_PATH_MAX+3); // Add enough extra for two /'s and a nul
// Use memcpy for speed since we already know the length of the string...
memcpy(fullname, d, dirlen+1);
char *name = fullname + dirlen;
if (name!=fullname && name[-1]!='/') *name++ = '/';
for (i=0; i<n; i++) {
dirent *de = (*list)[i];
int len = strlen(de->d_name);
if (de->d_name[len-1]=='/' || len>FL_PATH_MAX) continue;
// Use memcpy for speed since we already know the length of the string...
memcpy(name, de->d_name, len+1);
if (fl_filename_isdir(fullname)) {
(*list)[i] = de = (dirent*)realloc(de, de->d_name - (char*)de + len + 2);
char *dst = de->d_name + len;
*dst++ = '/';
*dst = 0;
}
}
free(fullname);
#endif
return n;
}
//
// End of "$Id$".
//
<|endoftext|>
|
<commit_before>/* Copyright (c) 2021 Dennis Wölfing
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* kernel/src/blockcache.cpp
* Cached block device.
*/
#include <errno.h>
#include <dennix/kernel/addressspace.h>
#include <dennix/kernel/blockcache.h>
#include <dennix/kernel/interrupts.h>
static void worker(void* device) {
BlockCacheDevice* dev = (BlockCacheDevice*) device;
dev->freeUnusedBlocks();
}
BlockCacheDevice::BlockCacheDevice(mode_t mode, dev_t dev)
: Vnode(mode | S_IFBLK, dev),
blocks(sizeof(blockBuffer) / sizeof(blockBuffer[0]), blockBuffer) {
cacheMutex = KTHREAD_MUTEX_INITIALIZER;
freeList = nullptr;
leastRecentlyUsed = nullptr;
mostRecentlyUsed = nullptr;
workerJob.func = worker;
workerJob.context = this;
}
bool BlockCacheDevice::isSeekable() {
return true;
}
void BlockCacheDevice::useBlock(Block* block) {
// Remove the block from its current location.
if (block->prevAccessed) {
block->prevAccessed->nextAccessed = block->nextAccessed;
} else if (block == leastRecentlyUsed) {
leastRecentlyUsed = block->nextAccessed;
}
if (block->nextAccessed) {
block->nextAccessed->prevAccessed = block->prevAccessed;
} else if (block == mostRecentlyUsed) {
mostRecentlyUsed = block->prevAccessed;
}
// Add the block as the most recently used.
block->prevAccessed = mostRecentlyUsed;
if (mostRecentlyUsed) {
mostRecentlyUsed->nextAccessed = block;
} else {
leastRecentlyUsed = block;
}
mostRecentlyUsed = block;
block->nextAccessed = nullptr;
}
ssize_t BlockCacheDevice::pread(void* buffer, size_t size, off_t offset,
int flags) {
if (size == 0) return 0;
if (offset < 0) {
errno = EINVAL;
return -1;
}
AutoLock lock(&mutex);
if (offset >= stats.st_size) return 0;
if ((off_t) size > stats.st_size - offset) {
size = stats.st_size - offset;
}
kthread_mutex_lock(&cacheMutex);
Block* allocatedBlock = nullptr;
ssize_t bytesRead = 0;
char* buf = (char*) buffer;
while (size > 0) {
uint64_t blockNumber = offset / PAGESIZE;
off_t blockOffset = blockNumber * PAGESIZE;
Block* block = blocks.get(blockNumber);
if (!block) {
if (!allocatedBlock) {
kthread_mutex_unlock(&cacheMutex);
paddr_t physicalAddress = allocateCache();
if (!physicalAddress) {
if (bytesRead) return bytesRead;
errno = ENOMEM;
return -1;
}
vaddr_t address = kernelSpace->mapPhysical(physicalAddress,
PAGESIZE, PROT_READ | PROT_WRITE);
if (!address) {
returnCache(physicalAddress);
if (bytesRead) return bytesRead;
errno = ENOMEM;
return -1;
}
allocatedBlock = new Block(address, blockNumber);
if (!allocatedBlock) {
kernelSpace->unmapPhysical(address, PAGESIZE);
returnCache(physicalAddress);
if (bytesRead) return bytesRead;
return -1;
}
kthread_mutex_lock(&cacheMutex);
}
block = blocks.get(blockNumber);
if (!block) {
size_t readSize = PAGESIZE;
if (unlikely(blockOffset + PAGESIZE > stats.st_size)) {
// The device ends before the end of the page.
readSize = stats.st_size - blockOffset;
}
if (!readUncached((void*) allocatedBlock->address, readSize,
blockOffset, flags)) {
if (!bytesRead) bytesRead = -1;
break;
}
block = allocatedBlock;
allocatedBlock = nullptr;
blocks.add(block);
}
}
useBlock(block);
size_t readSize = PAGESIZE - (offset & PAGE_MISALIGN);
if (readSize > size) readSize = size;
memcpy(buf + bytesRead, (char*) block->address +
(offset & PAGE_MISALIGN), readSize);
offset += readSize;
bytesRead += readSize;
size -= readSize;
}
kthread_mutex_unlock(&cacheMutex);
if (allocatedBlock) {
paddr_t physicalAddress = kernelSpace->getPhysicalAddress(
allocatedBlock->address);
kernelSpace->unmapPhysical(allocatedBlock->address, PAGESIZE);
returnCache(physicalAddress);
delete allocatedBlock;
}
return bytesRead;
}
ssize_t BlockCacheDevice::pwrite(const void* buffer, size_t size, off_t offset,
int flags) {
if (size == 0) return 0;
if (offset < 0) {
errno = EINVAL;
return -1;
}
AutoLock lock(&mutex);
if (offset >= stats.st_size) {
errno = ENOSPC;
return -1;
}
if ((off_t) size > stats.st_size - offset) {
size = stats.st_size - offset;
}
kthread_mutex_lock(&cacheMutex);
Block* allocatedBlock = nullptr;
ssize_t bytesWritten = 0;
const char* buf = (const char*) buffer;
while (size > 0) {
uint64_t blockNumber = offset / PAGESIZE;
off_t blockOffset = blockNumber * PAGESIZE;
Block* block = blocks.get(blockNumber);
if (!block) {
if (!allocatedBlock) {
kthread_mutex_unlock(&cacheMutex);
paddr_t physicalAddress = allocateCache();
if (!physicalAddress) {
if (bytesWritten) return bytesWritten;
errno = ENOMEM;
return -1;
}
vaddr_t address = kernelSpace->mapPhysical(physicalAddress,
PAGESIZE, PROT_READ | PROT_WRITE);
if (!address) {
returnCache(physicalAddress);
if (bytesWritten) return bytesWritten;
errno = ENOMEM;
return -1;
}
allocatedBlock = new Block(address, blockNumber);
if (!allocatedBlock) {
kernelSpace->unmapPhysical(address, PAGESIZE);
returnCache(physicalAddress);
if (bytesWritten) return bytesWritten;
return -1;
}
kthread_mutex_lock(&cacheMutex);
}
block = blocks.get(blockNumber);
if (!block) {
// Only read the block from the device if we are not overwriting
// it completely.
if (offset != blockOffset || size < PAGESIZE) {
size_t readSize = PAGESIZE;
if (unlikely(blockOffset + PAGESIZE > stats.st_size)) {
// The device ends before the end of the page.
readSize = stats.st_size - blockOffset;
}
if (!readUncached((void*) allocatedBlock->address, readSize,
blockOffset, flags)) {
if (!bytesWritten) bytesWritten = -1;
break;
}
}
block = allocatedBlock;
allocatedBlock = nullptr;
blocks.add(block);
}
}
useBlock(block);
size_t writeSize = PAGESIZE - (offset & PAGE_MISALIGN);
if (writeSize > size) writeSize = size;
memcpy((char*) block->address + (offset & PAGE_MISALIGN),
buf + bytesWritten, writeSize);
size_t writeOffset = offset & ~(stats.st_blksize - 1);
size_t writeLength = ALIGNUP(writeSize, stats.st_blksize);
if (!writeUncached((char*) block->address + (writeOffset &
PAGE_MISALIGN), writeLength, writeOffset, flags)) {
if (bytesWritten == 0) return -1;
return bytesWritten;
}
offset += writeSize;
bytesWritten += writeSize;
size -= writeSize;
}
kthread_mutex_unlock(&cacheMutex);
if (allocatedBlock) {
paddr_t physicalAddress = kernelSpace->getPhysicalAddress(
allocatedBlock->address);
kernelSpace->unmapPhysical(allocatedBlock->address, PAGESIZE);
returnCache(physicalAddress);
delete allocatedBlock;
}
return bytesWritten;
}
void BlockCacheDevice::freeUnusedBlocks() {
kthread_mutex_lock(&cacheMutex);
Block* block = freeList;
freeList = nullptr;
kthread_mutex_unlock(&cacheMutex);
while (block) {
kernelSpace->unmapPhysical(block->address, PAGESIZE);
Block* nextBlock = block->nextFree;
delete block;
block = nextBlock;
}
}
paddr_t BlockCacheDevice::reclaimCache() {
AutoLock lock(&cacheMutex);
Block* block = leastRecentlyUsed;
if (!block) return 0;
leastRecentlyUsed = block->nextAccessed;
if (leastRecentlyUsed) {
leastRecentlyUsed->prevAccessed = nullptr;
} else {
mostRecentlyUsed = nullptr;
}
blocks.remove(block->blockNumber);
block->nextFree = freeList;
freeList = block;
if (!block->nextFree) {
Interrupts::disable();
WorkerThread::addJob(&workerJob);
Interrupts::enable();
}
paddr_t physicalAddress = kernelSpace->getPhysicalAddress(block->address);
// We cannot unmap the block yet because the PMM is locked. This will be
// handled by the worker thread.
return physicalAddress;
}
BlockCacheDevice::Block::Block(vaddr_t address, uint64_t blockNumber) {
this->address = address;
this->blockNumber = blockNumber;
prevAccessed = nullptr;
nextAccessed = nullptr;
}
<commit_msg>Fix incorrect type in BlockCacheDevice::pwrite().<commit_after>/* Copyright (c) 2021 Dennis Wölfing
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* kernel/src/blockcache.cpp
* Cached block device.
*/
#include <errno.h>
#include <dennix/kernel/addressspace.h>
#include <dennix/kernel/blockcache.h>
#include <dennix/kernel/interrupts.h>
static void worker(void* device) {
BlockCacheDevice* dev = (BlockCacheDevice*) device;
dev->freeUnusedBlocks();
}
BlockCacheDevice::BlockCacheDevice(mode_t mode, dev_t dev)
: Vnode(mode | S_IFBLK, dev),
blocks(sizeof(blockBuffer) / sizeof(blockBuffer[0]), blockBuffer) {
cacheMutex = KTHREAD_MUTEX_INITIALIZER;
freeList = nullptr;
leastRecentlyUsed = nullptr;
mostRecentlyUsed = nullptr;
workerJob.func = worker;
workerJob.context = this;
}
bool BlockCacheDevice::isSeekable() {
return true;
}
void BlockCacheDevice::useBlock(Block* block) {
// Remove the block from its current location.
if (block->prevAccessed) {
block->prevAccessed->nextAccessed = block->nextAccessed;
} else if (block == leastRecentlyUsed) {
leastRecentlyUsed = block->nextAccessed;
}
if (block->nextAccessed) {
block->nextAccessed->prevAccessed = block->prevAccessed;
} else if (block == mostRecentlyUsed) {
mostRecentlyUsed = block->prevAccessed;
}
// Add the block as the most recently used.
block->prevAccessed = mostRecentlyUsed;
if (mostRecentlyUsed) {
mostRecentlyUsed->nextAccessed = block;
} else {
leastRecentlyUsed = block;
}
mostRecentlyUsed = block;
block->nextAccessed = nullptr;
}
ssize_t BlockCacheDevice::pread(void* buffer, size_t size, off_t offset,
int flags) {
if (size == 0) return 0;
if (offset < 0) {
errno = EINVAL;
return -1;
}
AutoLock lock(&mutex);
if (offset >= stats.st_size) return 0;
if ((off_t) size > stats.st_size - offset) {
size = stats.st_size - offset;
}
kthread_mutex_lock(&cacheMutex);
Block* allocatedBlock = nullptr;
ssize_t bytesRead = 0;
char* buf = (char*) buffer;
while (size > 0) {
uint64_t blockNumber = offset / PAGESIZE;
off_t blockOffset = blockNumber * PAGESIZE;
Block* block = blocks.get(blockNumber);
if (!block) {
if (!allocatedBlock) {
kthread_mutex_unlock(&cacheMutex);
paddr_t physicalAddress = allocateCache();
if (!physicalAddress) {
if (bytesRead) return bytesRead;
errno = ENOMEM;
return -1;
}
vaddr_t address = kernelSpace->mapPhysical(physicalAddress,
PAGESIZE, PROT_READ | PROT_WRITE);
if (!address) {
returnCache(physicalAddress);
if (bytesRead) return bytesRead;
errno = ENOMEM;
return -1;
}
allocatedBlock = new Block(address, blockNumber);
if (!allocatedBlock) {
kernelSpace->unmapPhysical(address, PAGESIZE);
returnCache(physicalAddress);
if (bytesRead) return bytesRead;
return -1;
}
kthread_mutex_lock(&cacheMutex);
}
block = blocks.get(blockNumber);
if (!block) {
size_t readSize = PAGESIZE;
if (unlikely(blockOffset + PAGESIZE > stats.st_size)) {
// The device ends before the end of the page.
readSize = stats.st_size - blockOffset;
}
if (!readUncached((void*) allocatedBlock->address, readSize,
blockOffset, flags)) {
if (!bytesRead) bytesRead = -1;
break;
}
block = allocatedBlock;
allocatedBlock = nullptr;
blocks.add(block);
}
}
useBlock(block);
size_t readSize = PAGESIZE - (offset & PAGE_MISALIGN);
if (readSize > size) readSize = size;
memcpy(buf + bytesRead, (char*) block->address +
(offset & PAGE_MISALIGN), readSize);
offset += readSize;
bytesRead += readSize;
size -= readSize;
}
kthread_mutex_unlock(&cacheMutex);
if (allocatedBlock) {
paddr_t physicalAddress = kernelSpace->getPhysicalAddress(
allocatedBlock->address);
kernelSpace->unmapPhysical(allocatedBlock->address, PAGESIZE);
returnCache(physicalAddress);
delete allocatedBlock;
}
return bytesRead;
}
ssize_t BlockCacheDevice::pwrite(const void* buffer, size_t size, off_t offset,
int flags) {
if (size == 0) return 0;
if (offset < 0) {
errno = EINVAL;
return -1;
}
AutoLock lock(&mutex);
if (offset >= stats.st_size) {
errno = ENOSPC;
return -1;
}
if ((off_t) size > stats.st_size - offset) {
size = stats.st_size - offset;
}
kthread_mutex_lock(&cacheMutex);
Block* allocatedBlock = nullptr;
ssize_t bytesWritten = 0;
const char* buf = (const char*) buffer;
while (size > 0) {
uint64_t blockNumber = offset / PAGESIZE;
off_t blockOffset = blockNumber * PAGESIZE;
Block* block = blocks.get(blockNumber);
if (!block) {
if (!allocatedBlock) {
kthread_mutex_unlock(&cacheMutex);
paddr_t physicalAddress = allocateCache();
if (!physicalAddress) {
if (bytesWritten) return bytesWritten;
errno = ENOMEM;
return -1;
}
vaddr_t address = kernelSpace->mapPhysical(physicalAddress,
PAGESIZE, PROT_READ | PROT_WRITE);
if (!address) {
returnCache(physicalAddress);
if (bytesWritten) return bytesWritten;
errno = ENOMEM;
return -1;
}
allocatedBlock = new Block(address, blockNumber);
if (!allocatedBlock) {
kernelSpace->unmapPhysical(address, PAGESIZE);
returnCache(physicalAddress);
if (bytesWritten) return bytesWritten;
return -1;
}
kthread_mutex_lock(&cacheMutex);
}
block = blocks.get(blockNumber);
if (!block) {
// Only read the block from the device if we are not overwriting
// it completely.
if (offset != blockOffset || size < PAGESIZE) {
size_t readSize = PAGESIZE;
if (unlikely(blockOffset + PAGESIZE > stats.st_size)) {
// The device ends before the end of the page.
readSize = stats.st_size - blockOffset;
}
if (!readUncached((void*) allocatedBlock->address, readSize,
blockOffset, flags)) {
if (!bytesWritten) bytesWritten = -1;
break;
}
}
block = allocatedBlock;
allocatedBlock = nullptr;
blocks.add(block);
}
}
useBlock(block);
size_t writeSize = PAGESIZE - (offset & PAGE_MISALIGN);
if (writeSize > size) writeSize = size;
memcpy((char*) block->address + (offset & PAGE_MISALIGN),
buf + bytesWritten, writeSize);
off_t writeOffset = offset & ~(stats.st_blksize - 1);
size_t writeLength = ALIGNUP(writeSize, stats.st_blksize);
if (!writeUncached((char*) block->address + (writeOffset &
PAGE_MISALIGN), writeLength, writeOffset, flags)) {
if (bytesWritten == 0) return -1;
return bytesWritten;
}
offset += writeSize;
bytesWritten += writeSize;
size -= writeSize;
}
kthread_mutex_unlock(&cacheMutex);
if (allocatedBlock) {
paddr_t physicalAddress = kernelSpace->getPhysicalAddress(
allocatedBlock->address);
kernelSpace->unmapPhysical(allocatedBlock->address, PAGESIZE);
returnCache(physicalAddress);
delete allocatedBlock;
}
return bytesWritten;
}
void BlockCacheDevice::freeUnusedBlocks() {
kthread_mutex_lock(&cacheMutex);
Block* block = freeList;
freeList = nullptr;
kthread_mutex_unlock(&cacheMutex);
while (block) {
kernelSpace->unmapPhysical(block->address, PAGESIZE);
Block* nextBlock = block->nextFree;
delete block;
block = nextBlock;
}
}
paddr_t BlockCacheDevice::reclaimCache() {
AutoLock lock(&cacheMutex);
Block* block = leastRecentlyUsed;
if (!block) return 0;
leastRecentlyUsed = block->nextAccessed;
if (leastRecentlyUsed) {
leastRecentlyUsed->prevAccessed = nullptr;
} else {
mostRecentlyUsed = nullptr;
}
blocks.remove(block->blockNumber);
block->nextFree = freeList;
freeList = block;
if (!block->nextFree) {
Interrupts::disable();
WorkerThread::addJob(&workerJob);
Interrupts::enable();
}
paddr_t physicalAddress = kernelSpace->getPhysicalAddress(block->address);
// We cannot unmap the block yet because the PMM is locked. This will be
// handled by the worker thread.
return physicalAddress;
}
BlockCacheDevice::Block::Block(vaddr_t address, uint64_t blockNumber) {
this->address = address;
this->blockNumber = blockNumber;
prevAccessed = nullptr;
nextAccessed = nullptr;
}
<|endoftext|>
|
<commit_before>//---------------------------- mapping_02.cc ---------------------------
// $Id: bem.cc 22693 2010-11-11 20:11:47Z kanschat $
// Version: $Name$
//
// Copyright (C) 2010, 2011 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- mapping_02.cc ---------------------------
// like _01, but use a quadratic mapping. since we now map line segments to
// curves, the normal vectors at different quadrature points should no longer
// be parallel
#include "../tests.h"
#include <base/quadrature_lib.h>
#include <grid/tria.h>
#include <grid/grid_generator.h>
#include <grid/tria_boundary_lib.h>
#include <grid/grid_out.h>
#include <grid/grid_tools.h>
#include <fe/fe_values.h>
#include <fe/fe_q.h>
#include <fe/mapping_q.h>
template <int dim>
void test (unsigned int degree)
{
Triangulation<dim-1, dim> mesh;
GridGenerator::hyper_cube(mesh);
QGauss<dim-1> quadrature(dim == 2 ? 3 : 2);
MappingQ<dim-1,dim> mapping(degree);
Point<dim> p;
// Try to project a point on the
// surface
for(unsigned int i=0; i<dim; ++i)
p[i] = .2;
Point<dim-1> q =
mapping.transform_real_to_unit_cell(mesh.begin_active(), p);
deallog << "Mapping Q("<< degree<< "): P: " << p
<< ", on unit: " << q << std::endl;
}
int main ()
{
std::ofstream logfile("mapping_03/output");
deallog.attach(logfile);
deallog.depth_console(0);
test<2> (1);
test<2> (2);
test<3> (1);
test<3> (2);
return 0;
}
<commit_msg>Make include path future proof.<commit_after>//---------------------------- mapping_02.cc ---------------------------
// $Id: bem.cc 22693 2010-11-11 20:11:47Z kanschat $
// Version: $Name$
//
// Copyright (C) 2010, 2011 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- mapping_02.cc ---------------------------
// like _01, but use a quadratic mapping. since we now map line segments to
// curves, the normal vectors at different quadrature points should no longer
// be parallel
#include "../tests.h"
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/tria_boundary_lib.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/fe/fe_values.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/fe/mapping_q.h>
template <int dim>
void test (unsigned int degree)
{
Triangulation<dim-1, dim> mesh;
GridGenerator::hyper_cube(mesh);
QGauss<dim-1> quadrature(dim == 2 ? 3 : 2);
MappingQ<dim-1,dim> mapping(degree);
Point<dim> p;
// Try to project a point on the
// surface
for(unsigned int i=0; i<dim; ++i)
p[i] = .2;
Point<dim-1> q =
mapping.transform_real_to_unit_cell(mesh.begin_active(), p);
deallog << "Mapping Q("<< degree<< "): P: " << p
<< ", on unit: " << q << std::endl;
}
int main ()
{
std::ofstream logfile("mapping_03/output");
deallog.attach(logfile);
deallog.depth_console(0);
test<2> (1);
test<2> (2);
test<3> (1);
test<3> (2);
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2011-2014 Intel Corporation. All rights reserved.
*
* 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "decodeinputavformat.h"
#include "common/common_def.h"
#include "common/log.h"
#include <Yami.h>
DecodeInputAvFormat::DecodeInputAvFormat()
:m_format(NULL),m_videoId(-1), m_codecId(AV_CODEC_ID_NONE), m_isEos(true)
{
av_register_all();
av_init_packet(&m_packet);
}
bool DecodeInputAvFormat::initInput(const char* fileName)
{
uint16_t width = 0, height = 0;
int ret = avformat_open_input(&m_format, fileName, NULL, NULL);
if (ret)
goto error;
uint32_t i;
for (i = 0; i < m_format->nb_streams; ++i) {
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 33, 100)
AVCodecParameters* codec = m_format->streams[i]->codecpar;
#else
AVCodecContext* codec = m_format->streams[i]->codec;
#endif
//VP9: width and height of the IVF header,VP8: width and height is zero
if (AVMEDIA_TYPE_VIDEO == codec->codec_type) {
width = codec->width;
height = codec->height;
break;
}
}
ret = avformat_find_stream_info(m_format, NULL);
if (ret < 0)
goto error;
for (i = 0; i < m_format->nb_streams; i++)
{
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 33, 100)
AVCodecParameters* codec = m_format->streams[i]->codecpar;
#else
AVCodecContext* codec = m_format->streams[i]->codec;
#endif
if (AVMEDIA_TYPE_VIDEO == codec->codec_type) {
m_codecId = codec->codec_id;
if (codec->extradata && codec->extradata_size)
m_codecData.append((char*)codec->extradata, codec->extradata_size);
m_videoId = i;
//VP9: display_width and display_height of the first frame
if (codec->width > width)
width = codec->width;
if (codec->height > height)
height = codec->height;
setResolution(width, height);
break;
}
}
if (i == m_format->nb_streams) {
ERROR("no video stream");
goto error;
}
m_isEos = false;
return true;
error:
if (m_format)
avformat_close_input(&m_format);
return false;
}
struct MimeEntry
{
AVCodecID id;
const char* mime;
};
static const MimeEntry MimeEntrys[] = {
AV_CODEC_ID_MPEG2VIDEO, YAMI_MIME_MPEG2,
AV_CODEC_ID_VP8, YAMI_MIME_VP8,
#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(54, 40, 0)
AV_CODEC_ID_VP9, YAMI_MIME_VP9,
#endif
AV_CODEC_ID_H264, YAMI_MIME_H264,
AV_CODEC_ID_H265, YAMI_MIME_H265,
AV_CODEC_ID_WMV3, YAMI_MIME_VC1,
AV_CODEC_ID_VC1, YAMI_MIME_VC1
};
const char * DecodeInputAvFormat::getMimeType()
{
for (size_t i = 0; i < N_ELEMENTS(MimeEntrys); i++) {
if (MimeEntrys[i].id == m_codecId)
return MimeEntrys[i].mime;
}
return "unknow";
}
bool DecodeInputAvFormat::getNextDecodeUnit(VideoDecodeBuffer &inputBuffer)
{
if (!m_format || m_isEos)
return false;
int ret;
while (1) {
//free old packet
av_packet_unref(&m_packet);
ret = av_read_frame(m_format, &m_packet);
if (ret) {
m_isEos = true;
return false;
}
if (m_packet.stream_index == m_videoId) {
memset(&inputBuffer, 0, sizeof(inputBuffer));
inputBuffer.data = m_packet.data;
inputBuffer.size = m_packet.size;
inputBuffer.timeStamp = m_packet.dts;
return true;
}
}
return false;
}
const string& DecodeInputAvFormat::getCodecData()
{
return m_codecData;
}
DecodeInputAvFormat::~DecodeInputAvFormat()
{
if (m_format) {
av_packet_unref(&m_packet);
avformat_close_input(&m_format);
}
}
<commit_msg>avformat: be compatible with all version ffmpeg<commit_after>/*
* Copyright (C) 2011-2014 Intel Corporation. All rights reserved.
*
* 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "decodeinputavformat.h"
#include "common/common_def.h"
#include "common/log.h"
#include <Yami.h>
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55, 39, 100)
#define av_packet_unref av_free_packet
#endif
DecodeInputAvFormat::DecodeInputAvFormat()
:m_format(NULL),m_videoId(-1), m_codecId(AV_CODEC_ID_NONE), m_isEos(true)
{
av_register_all();
av_init_packet(&m_packet);
}
bool DecodeInputAvFormat::initInput(const char* fileName)
{
uint16_t width = 0, height = 0;
int ret = avformat_open_input(&m_format, fileName, NULL, NULL);
if (ret)
goto error;
uint32_t i;
for (i = 0; i < m_format->nb_streams; ++i) {
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 33, 100)
AVCodecParameters* codec = m_format->streams[i]->codecpar;
#else
AVCodecContext* codec = m_format->streams[i]->codec;
#endif
//VP9: width and height of the IVF header,VP8: width and height is zero
if (AVMEDIA_TYPE_VIDEO == codec->codec_type) {
width = codec->width;
height = codec->height;
break;
}
}
ret = avformat_find_stream_info(m_format, NULL);
if (ret < 0)
goto error;
for (i = 0; i < m_format->nb_streams; i++)
{
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 33, 100)
AVCodecParameters* codec = m_format->streams[i]->codecpar;
#else
AVCodecContext* codec = m_format->streams[i]->codec;
#endif
if (AVMEDIA_TYPE_VIDEO == codec->codec_type) {
m_codecId = codec->codec_id;
if (codec->extradata && codec->extradata_size)
m_codecData.append((char*)codec->extradata, codec->extradata_size);
m_videoId = i;
//VP9: display_width and display_height of the first frame
if (codec->width > width)
width = codec->width;
if (codec->height > height)
height = codec->height;
setResolution(width, height);
break;
}
}
if (i == m_format->nb_streams) {
ERROR("no video stream");
goto error;
}
m_isEos = false;
return true;
error:
if (m_format)
avformat_close_input(&m_format);
return false;
}
struct MimeEntry
{
AVCodecID id;
const char* mime;
};
static const MimeEntry MimeEntrys[] = {
AV_CODEC_ID_MPEG2VIDEO, YAMI_MIME_MPEG2,
AV_CODEC_ID_VP8, YAMI_MIME_VP8,
#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(54, 40, 0)
AV_CODEC_ID_VP9, YAMI_MIME_VP9,
#endif
AV_CODEC_ID_H264, YAMI_MIME_H264,
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55, 39, 100)
AV_CODEC_ID_H265, YAMI_MIME_H265,
#endif
AV_CODEC_ID_WMV3, YAMI_MIME_VC1,
AV_CODEC_ID_VC1, YAMI_MIME_VC1
};
const char * DecodeInputAvFormat::getMimeType()
{
for (size_t i = 0; i < N_ELEMENTS(MimeEntrys); i++) {
if (MimeEntrys[i].id == m_codecId)
return MimeEntrys[i].mime;
}
return "unknow";
}
bool DecodeInputAvFormat::getNextDecodeUnit(VideoDecodeBuffer &inputBuffer)
{
if (!m_format || m_isEos)
return false;
int ret;
while (1) {
//free old packet
av_packet_unref(&m_packet);
ret = av_read_frame(m_format, &m_packet);
if (ret) {
m_isEos = true;
return false;
}
if (m_packet.stream_index == m_videoId) {
memset(&inputBuffer, 0, sizeof(inputBuffer));
inputBuffer.data = m_packet.data;
inputBuffer.size = m_packet.size;
inputBuffer.timeStamp = m_packet.dts;
return true;
}
}
return false;
}
const string& DecodeInputAvFormat::getCodecData()
{
return m_codecData;
}
DecodeInputAvFormat::~DecodeInputAvFormat()
{
if (m_format) {
av_packet_unref(&m_packet);
avformat_close_input(&m_format);
}
}
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "id.h"
#include "coreconstants.h"
#include "icontext.h"
#include <utils/qtcassert.h>
#include <QtCore/QHash>
namespace Core {
/*!
\class Core::Id
\brief The class Id encapsulates an identifier. It is used as a type-safe
helper class instead of a \c QString or \c QByteArray. The internal
representation of the id is assumed to be plain 7-bit-clean ASCII.
*/
static int lastUid = 0;
static QVector<QByteArray> stringFromId;
static QHash<QByteArray, int> idFromString;
static int theId(const QByteArray &ba)
{
QTC_CHECK(!ba.isEmpty());
int res = idFromString.value(ba);
if (res == 0) {
if (lastUid == 0)
stringFromId.append(QByteArray());
res = ++lastUid;
idFromString[ba] = res;
stringFromId.append(ba);
}
return res;
}
Id::Id(const char *name)
: m_id(theId(name))
{}
Id::Id(const QString &name)
: m_id(theId(name.toLatin1()))
{}
QByteArray Id::name() const
{
return stringFromId.at(m_id);
}
QString Id::toString() const
{
return QString::fromLatin1(stringFromId[m_id]);
}
Context::Context(const char *id, int offset)
{
d.append(Id(QLatin1String(id) + QString::number(offset)).uniqueIdentifier());
}
void Context::add(const char *id)
{
d.append(Id(id).uniqueIdentifier());
}
bool Context::contains(const char *id) const
{
return d.contains(Id(id).uniqueIdentifier());
}
} // namespace Core
<commit_msg>core: prevent allocations when looking up an existing Core::Id<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "id.h"
#include "coreconstants.h"
#include "icontext.h"
#include <utils/qtcassert.h>
#include <QtCore/QHash>
namespace Core {
/*!
\class Core::Id
\brief The class Id encapsulates an identifier. It is used as a type-safe
helper class instead of a \c QString or \c QByteArray. The internal
representation of the id is assumed to be plain 7-bit-clean ASCII.
*/
class StringHolder
{
public:
explicit StringHolder(const char *s)
: str(s)
{
n = strlen(s);
int m = n;
h = 0;
while (m--) {
h = (h << 4) + *s++;
h ^= (h & 0xf0000000) >> 23;
h &= 0x0fffffff;
}
}
int n;
const char *str;
uint h;
};
static bool operator==(const StringHolder &sh1, const StringHolder &sh2)
{
// sh.n is unlikely to discriminate better than the hash.
return sh1.h == sh2.h && strcmp(sh1.str, sh1.str) == 0;
}
static uint qHash(const StringHolder &sh)
{
return sh.h;
}
struct IdCache : public QHash<StringHolder, int>
{
#ifndef QTC_ALLOW_STATIC_LEAKS
~IdCache()
{
for (IdCache::iterator it = begin(); it != end(); ++it)
free(const_cast<char *>(it.key().str));
}
#endif
};
static int lastUid = 0;
static QVector<QByteArray> stringFromId;
static IdCache idFromString;
static int theId(const char *str)
{
QTC_ASSERT(str && *str, return 0);
StringHolder sh(str);
int res = idFromString.value(sh, 0);
if (res == 0) {
if (lastUid == 0)
stringFromId.append(QByteArray());
res = ++lastUid;
sh.str = strdup(sh.str);
idFromString[sh] = res;
stringFromId.append(QByteArray::fromRawData(sh.str, sh.n));
}
return res;
}
Id::Id(const char *name)
: m_id(theId(name))
{}
Id::Id(const QString &name)
: m_id(theId(name.toLatin1()))
{}
QByteArray Id::name() const
{
return stringFromId.at(m_id);
}
QString Id::toString() const
{
return QString::fromLatin1(stringFromId[m_id]);
}
Context::Context(const char *id, int offset)
{
d.append(Id(QLatin1String(id) + QString::number(offset)).uniqueIdentifier());
}
void Context::add(const char *id)
{
d.append(Id(id).uniqueIdentifier());
}
bool Context::contains(const char *id) const
{
return d.contains(Id(id).uniqueIdentifier());
}
} // namespace Core
<|endoftext|>
|
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2020 ScyllaDB Ltd.
*/
#include <seastar/testing/perf_tests.hh>
#include <seastar/core/sharded.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/fair_queue.hh>
#include <seastar/core/semaphore.hh>
#include <boost/range/irange.hpp>
struct local_fq_and_class {
seastar::fair_queue fq;
seastar::priority_class_ptr pclass;
unsigned executed = 0;
local_fq_and_class(seastar::fair_queue::config cfg)
: fq(std::move(cfg))
, pclass(fq.register_priority_class(1))
{}
~local_fq_and_class() {
fq.unregister_priority_class(pclass);
}
};
struct perf_fair_queue {
static constexpr unsigned requests_to_dispatch = 1000;
seastar::fair_queue::config cfg;
seastar::sharded<local_fq_and_class> local_fq;
seastar::fair_queue shared_fq;
std::vector<priority_class_ptr> shared_pclass;
uint64_t shared_executed = 0;
uint64_t shared_acked = 0;
perf_fair_queue()
: cfg({ std::chrono::milliseconds(100), 1, 1 })
, shared_fq(cfg)
{
local_fq.start(cfg).get();
for (unsigned i = 0; i < smp::count; ++i) {
shared_pclass.push_back(shared_fq.register_priority_class(1));
}
}
~perf_fair_queue() {
local_fq.stop().get();
for (auto& pc : shared_pclass) {
shared_fq.unregister_priority_class(pc);
}
}
};
PERF_TEST_F(perf_fair_queue, contended_local)
{
auto invokers = local_fq.invoke_on_all([] (local_fq_and_class& local) {
local.executed = 0;
return parallel_for_each(boost::irange(0u, requests_to_dispatch), [&local] (unsigned dummy) {
local.fq.queue(local.pclass, seastar::fair_queue_ticket{1, 1}, [&local] {
local.executed++;
local.fq.notify_requests_finished(seastar::fair_queue_ticket{1, 1});
});
return make_ready_future<>();
});
});
auto collectors = local_fq.invoke_on_all([] (local_fq_and_class& local) {
return do_until([&local] { return local.executed == requests_to_dispatch; }, [&local] {
local.fq.dispatch_requests();
return make_ready_future<>();
});
});
return when_all_succeed(std::move(invokers), std::move(collectors)).discard_result();
}
PERF_TEST_F(perf_fair_queue, contended_shared)
{
shared_acked = 0;
shared_executed = 0;
auto invokers = local_fq.invoke_on_all([this, coordinator = this_shard_id()] (local_fq_and_class& dummy) {
return parallel_for_each(boost::irange(0u, requests_to_dispatch), [this, coordinator] (unsigned dummy) {
return smp::submit_to(coordinator, [this] {
shared_fq.queue(shared_pclass[this_shard_id()], seastar::fair_queue_ticket{1, 1}, [this] {
shared_executed++;
});
return make_ready_future<>();
});
});
});
auto collectors = do_until([this] { return shared_acked == requests_to_dispatch * smp::count; }, [this] {
shared_fq.dispatch_requests();
uint32_t pending_ack = shared_executed - shared_acked;
shared_acked = shared_executed;
shared_fq.notify_requests_finished(seastar::fair_queue_ticket{pending_ack, pending_ack}, pending_ack);
return make_ready_future<>();
});
return when_all_succeed(std::move(invokers), std::move(collectors)).discard_result();
}
PERF_TEST_F(perf_fair_queue, contended_shared_amortized)
{
shared_acked = 0;
shared_executed = 0;
auto invokers = local_fq.invoke_on_all([this, coordinator = this_shard_id()] (local_fq_and_class& dummy) {
return smp::submit_to(coordinator, [this] {
return parallel_for_each(boost::irange(0u, requests_to_dispatch), [this] (unsigned dummy) {
shared_fq.queue(shared_pclass[this_shard_id()], seastar::fair_queue_ticket{1, 1}, [this] {
shared_executed++;
});
return make_ready_future<>();
});
});
});
auto collectors = do_until([this] { return shared_acked == requests_to_dispatch * smp::count; }, [this] {
shared_fq.dispatch_requests();
uint32_t pending_ack = shared_executed - shared_acked;
shared_acked = shared_executed;
shared_fq.notify_requests_finished(seastar::fair_queue_ticket{pending_ack, pending_ack}, pending_ack);
return make_ready_future<>();
});
return when_all_succeed(std::move(invokers), std::move(collectors)).discard_result();
}
<commit_msg>tests: Fix perf fair queue stuck<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2020 ScyllaDB Ltd.
*/
#include <seastar/testing/perf_tests.hh>
#include <seastar/core/sharded.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/fair_queue.hh>
#include <seastar/core/semaphore.hh>
#include <boost/range/irange.hpp>
struct local_fq_and_class {
seastar::fair_queue fq;
seastar::priority_class_ptr pclass;
unsigned executed = 0;
local_fq_and_class(seastar::fair_queue::config cfg)
: fq(std::move(cfg))
, pclass(fq.register_priority_class(1))
{}
~local_fq_and_class() {
fq.unregister_priority_class(pclass);
}
};
struct perf_fair_queue {
static constexpr unsigned requests_to_dispatch = 1000;
seastar::fair_queue::config cfg;
seastar::sharded<local_fq_and_class> local_fq;
seastar::fair_queue shared_fq;
std::vector<priority_class_ptr> shared_pclass;
uint64_t shared_executed = 0;
uint64_t shared_acked = 0;
perf_fair_queue()
: cfg({ std::chrono::milliseconds(100), 1, 1 })
, shared_fq(cfg)
{
local_fq.start(cfg).get();
for (unsigned i = 0; i < smp::count; ++i) {
shared_pclass.push_back(shared_fq.register_priority_class(1));
}
}
~perf_fair_queue() {
local_fq.stop().get();
for (auto& pc : shared_pclass) {
shared_fq.unregister_priority_class(pc);
}
}
};
PERF_TEST_F(perf_fair_queue, contended_local)
{
auto invokers = local_fq.invoke_on_all([] (local_fq_and_class& local) {
return parallel_for_each(boost::irange(0u, requests_to_dispatch), [&local] (unsigned dummy) {
local.fq.queue(local.pclass, seastar::fair_queue_ticket{1, 1}, [&local] {
local.executed++;
local.fq.notify_requests_finished(seastar::fair_queue_ticket{1, 1});
});
return make_ready_future<>();
});
});
auto collectors = local_fq.invoke_on_all([] (local_fq_and_class& local) {
// Zeroing this counter must be here, otherwise should the collectors win the
// execution order in when_all_succeed(), the do_until()'s stopping callback
// would return true immediately and the queue would not be dispatched.
//
// At the same time, although this counter is incremented by the lambda from
// invokers, it's not called until the fq.dispatch_requests() is, so there's no
// opposite problem if zeroing it here.
local.executed = 0;
return do_until([&local] { return local.executed == requests_to_dispatch; }, [&local] {
local.fq.dispatch_requests();
return make_ready_future<>();
});
});
return when_all_succeed(std::move(invokers), std::move(collectors)).discard_result();
}
PERF_TEST_F(perf_fair_queue, contended_shared)
{
shared_acked = 0;
shared_executed = 0;
auto invokers = local_fq.invoke_on_all([this, coordinator = this_shard_id()] (local_fq_and_class& dummy) {
return parallel_for_each(boost::irange(0u, requests_to_dispatch), [this, coordinator] (unsigned dummy) {
return smp::submit_to(coordinator, [this] {
shared_fq.queue(shared_pclass[this_shard_id()], seastar::fair_queue_ticket{1, 1}, [this] {
shared_executed++;
});
return make_ready_future<>();
});
});
});
auto collectors = do_until([this] { return shared_acked == requests_to_dispatch * smp::count; }, [this] {
shared_fq.dispatch_requests();
uint32_t pending_ack = shared_executed - shared_acked;
shared_acked = shared_executed;
shared_fq.notify_requests_finished(seastar::fair_queue_ticket{pending_ack, pending_ack}, pending_ack);
return make_ready_future<>();
});
return when_all_succeed(std::move(invokers), std::move(collectors)).discard_result();
}
PERF_TEST_F(perf_fair_queue, contended_shared_amortized)
{
shared_acked = 0;
shared_executed = 0;
auto invokers = local_fq.invoke_on_all([this, coordinator = this_shard_id()] (local_fq_and_class& dummy) {
return smp::submit_to(coordinator, [this] {
return parallel_for_each(boost::irange(0u, requests_to_dispatch), [this] (unsigned dummy) {
shared_fq.queue(shared_pclass[this_shard_id()], seastar::fair_queue_ticket{1, 1}, [this] {
shared_executed++;
});
return make_ready_future<>();
});
});
});
auto collectors = do_until([this] { return shared_acked == requests_to_dispatch * smp::count; }, [this] {
shared_fq.dispatch_requests();
uint32_t pending_ack = shared_executed - shared_acked;
shared_acked = shared_executed;
shared_fq.notify_requests_finished(seastar::fair_queue_ticket{pending_ack, pending_ack}, pending_ack);
return make_ready_future<>();
});
return when_all_succeed(std::move(invokers), std::move(collectors)).discard_result();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015-2016 Alexander Saprykin <xelfium@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef PLIBSYS_TESTS_STATIC
# define BOOST_TEST_DYN_LINK
#endif
#define BOOST_TEST_MODULE plibraryloader_test
#include "plibsys.h"
#include <stdio.h>
#ifdef PLIBSYS_TESTS_STATIC
# include <boost/test/included/unit_test.hpp>
#else
# include <boost/test/unit_test.hpp>
#endif
extern "C" ppointer pmem_alloc (psize nbytes)
{
P_UNUSED (nbytes);
return (ppointer) NULL;
}
extern "C" ppointer pmem_realloc (ppointer block, psize nbytes)
{
P_UNUSED (block);
P_UNUSED (nbytes);
return (ppointer) NULL;
}
extern "C" void pmem_free (ppointer block)
{
P_UNUSED (block);
}
BOOST_AUTO_TEST_SUITE (BOOST_TEST_MODULE)
BOOST_AUTO_TEST_CASE (plibraryloader_nomem_test)
{
p_libsys_init ();
/* We assume that 2nd argument is ourself library path */
BOOST_REQUIRE (boost::unit_test::framework::master_test_suite().argc == 2);
/* Cleanup from previous run */
p_file_remove ("." P_DIR_SEPARATOR "p_empty_file.txt", NULL);
FILE *file = fopen ("." P_DIR_SEPARATOR "p_empty_file.txt", "w");
BOOST_CHECK (file != NULL);
BOOST_CHECK (fclose (file) == 0);
PMemVTable vtable;
vtable.free = pmem_free;
vtable.malloc = pmem_alloc;
vtable.realloc = pmem_realloc;
BOOST_CHECK (p_mem_set_vtable (&vtable) == TRUE);
BOOST_CHECK (p_library_loader_new ("." P_DIR_SEPARATOR "p_empty_file.txt") == NULL);
BOOST_CHECK (p_library_loader_new (boost::unit_test::framework::master_test_suite().argv[1]) == NULL);
vtable.malloc = (ppointer (*)(psize)) malloc;
vtable.realloc = (ppointer (*)(ppointer, psize)) realloc;
vtable.free = (void (*)(ppointer)) free;
BOOST_CHECK (p_mem_set_vtable (&vtable) == TRUE);
BOOST_CHECK (p_file_remove ("." P_DIR_SEPARATOR "p_empty_file.txt", NULL) == TRUE);
p_libsys_shutdown ();
}
BOOST_AUTO_TEST_CASE (plibraryloader_general_test)
{
PLibraryLoader *loader;
pchar *err_msg;
void (*shutdown_func) (void);
p_libsys_init ();
/* We assume that 2nd argument is ourself library path */
BOOST_REQUIRE (boost::unit_test::framework::master_test_suite().argc == 2);
/* Invalid usage */
BOOST_CHECK (p_library_loader_new (NULL) == NULL);
BOOST_CHECK (p_library_loader_new ("./unexistent_file.nofile") == NULL);
BOOST_CHECK (p_library_loader_get_symbol (NULL, NULL) == NULL);
BOOST_CHECK (p_library_loader_get_symbol (NULL, "unexistent_symbol") == NULL);
p_library_loader_free (NULL);
/* General tests */
err_msg = p_library_loader_get_last_error ();
p_free (err_msg);
loader = p_library_loader_new (boost::unit_test::framework::master_test_suite().argv[1]);
BOOST_REQUIRE (loader != NULL);
BOOST_CHECK (p_library_loader_get_symbol (loader, "there_is_no_such_a_symbol") == (PFuncAddr) NULL);
err_msg = p_library_loader_get_last_error ();
BOOST_CHECK (err_msg != NULL);
p_free (err_msg);
shutdown_func = (void (*) (void)) p_library_loader_get_symbol (loader, "p_libsys_shutdown");
if (shutdown_func == NULL)
shutdown_func = (void (*) (void)) p_library_loader_get_symbol (loader, "_p_libsys_shutdown");
BOOST_REQUIRE (shutdown_func != NULL);
err_msg = p_library_loader_get_last_error ();
p_free (err_msg);
p_library_loader_free (loader);
/* We have already loaded reference to ourself library, it's OK */
shutdown_func ();
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>tests: Silent message box on Windows<commit_after>/*
* Copyright (C) 2015-2016 Alexander Saprykin <xelfium@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef PLIBSYS_TESTS_STATIC
# define BOOST_TEST_DYN_LINK
#endif
#define BOOST_TEST_MODULE plibraryloader_test
#include "plibsys.h"
#include <stdio.h>
#ifdef PLIBSYS_TESTS_STATIC
# include <boost/test/included/unit_test.hpp>
#else
# include <boost/test/unit_test.hpp>
#endif
extern "C" ppointer pmem_alloc (psize nbytes)
{
P_UNUSED (nbytes);
return (ppointer) NULL;
}
extern "C" ppointer pmem_realloc (ppointer block, psize nbytes)
{
P_UNUSED (block);
P_UNUSED (nbytes);
return (ppointer) NULL;
}
extern "C" void pmem_free (ppointer block)
{
P_UNUSED (block);
}
BOOST_AUTO_TEST_SUITE (BOOST_TEST_MODULE)
BOOST_AUTO_TEST_CASE (plibraryloader_nomem_test)
{
p_libsys_init ();
/* We assume that 2nd argument is ourself library path */
BOOST_REQUIRE (boost::unit_test::framework::master_test_suite().argc == 2);
/* Cleanup from previous run */
p_file_remove ("." P_DIR_SEPARATOR "p_empty_file.txt", NULL);
FILE *file = fopen ("." P_DIR_SEPARATOR "p_empty_file.txt", "w");
BOOST_CHECK (file != NULL);
BOOST_CHECK (fclose (file) == 0);
PMemVTable vtable;
vtable.free = pmem_free;
vtable.malloc = pmem_alloc;
vtable.realloc = pmem_realloc;
BOOST_CHECK (p_mem_set_vtable (&vtable) == TRUE);
#ifdef P_OS_WIN
SetErrorMode (SEM_FAILCRITICALERRORS);
#endif
BOOST_CHECK (p_library_loader_new ("." P_DIR_SEPARATOR "p_empty_file.txt") == NULL);
BOOST_CHECK (p_library_loader_new (boost::unit_test::framework::master_test_suite().argv[1]) == NULL);
#ifdef P_OS_WIN
SetErrorMode (0);
#endif
vtable.malloc = (ppointer (*)(psize)) malloc;
vtable.realloc = (ppointer (*)(ppointer, psize)) realloc;
vtable.free = (void (*)(ppointer)) free;
BOOST_CHECK (p_mem_set_vtable (&vtable) == TRUE);
BOOST_CHECK (p_file_remove ("." P_DIR_SEPARATOR "p_empty_file.txt", NULL) == TRUE);
p_libsys_shutdown ();
}
BOOST_AUTO_TEST_CASE (plibraryloader_general_test)
{
PLibraryLoader *loader;
pchar *err_msg;
void (*shutdown_func) (void);
p_libsys_init ();
/* We assume that 2nd argument is ourself library path */
BOOST_REQUIRE (boost::unit_test::framework::master_test_suite().argc == 2);
/* Invalid usage */
BOOST_CHECK (p_library_loader_new (NULL) == NULL);
BOOST_CHECK (p_library_loader_new ("./unexistent_file.nofile") == NULL);
BOOST_CHECK (p_library_loader_get_symbol (NULL, NULL) == NULL);
BOOST_CHECK (p_library_loader_get_symbol (NULL, "unexistent_symbol") == NULL);
p_library_loader_free (NULL);
/* General tests */
err_msg = p_library_loader_get_last_error ();
p_free (err_msg);
loader = p_library_loader_new (boost::unit_test::framework::master_test_suite().argv[1]);
BOOST_REQUIRE (loader != NULL);
BOOST_CHECK (p_library_loader_get_symbol (loader, "there_is_no_such_a_symbol") == (PFuncAddr) NULL);
err_msg = p_library_loader_get_last_error ();
BOOST_CHECK (err_msg != NULL);
p_free (err_msg);
shutdown_func = (void (*) (void)) p_library_loader_get_symbol (loader, "p_libsys_shutdown");
if (shutdown_func == NULL)
shutdown_func = (void (*) (void)) p_library_loader_get_symbol (loader, "_p_libsys_shutdown");
BOOST_REQUIRE (shutdown_func != NULL);
err_msg = p_library_loader_get_last_error ();
p_free (err_msg);
p_library_loader_free (loader);
/* We have already loaded reference to ourself library, it's OK */
shutdown_func ();
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>#pragma once
#include <libunittest/all.hpp>
#include <densitas/all.hpp>
#include <armadillo>
using namespace unittest::assertions;
using vector_t = arma::vec;
using matrix_t = arma::mat;
struct mock_model {
vector_t prediction;
vector_t train_y;
matrix_t train_X;
mock_model()
: prediction(), train_y(), train_X()
{}
void train(matrix_t& X, vector_t& y)
{
train_y = y;
train_X = X;
}
vector_t predict_proba(matrix_t&) const
{
return prediction;
}
};
const int no = densitas::model_adapter::no<mock_model>();
const int yes = densitas::model_adapter::yes<mock_model>();
const double dno = static_cast<double>(no);
const double dyes = static_cast<double>(yes);
namespace densitas {
namespace matrix_adapter {
template<>
inline
std::size_t n_rows(const matrix_t& matrix)
{
return matrix.n_rows;
}
template<>
inline
std::size_t n_columns(const matrix_t& matrix)
{
return matrix.n_cols;
}
} // matrix_adapter
namespace vector_adapter {
template<>
inline
std::size_t n_elements(const vector_t& vector)
{
return vector.n_elem;
}
} // vector_adapter
} // densitas
namespace unittest {
namespace assertions {
template<typename... Args>
void
assert_equal_containers(const matrix_t& expected,
const matrix_t& actual,
const Args&... message)
{
assert_equal(expected.n_rows, actual.n_rows, "n_rows don't match! ", message...);
assert_equal(expected.n_cols, actual.n_cols, "n_cols don't match! ", message...);
for (std::size_t i=0; i<expected.n_rows; ++i) {
if (!unittest::core::is_containers_equal(vector_t(expected.row(i).t()), vector_t(actual.row(i).t()))) {
const std::string text = "matrices are not equal";
unittest::fail(UNITTEST_FUNC, text, message...);
}
}
}
template<typename... Args>
void
assert_approx_equal_containers(const matrix_t& expected,
const matrix_t& actual,
const double eps,
const Args&... message)
{
assert_equal(expected.n_rows, actual.n_rows, "n_rows don't match! ", message...);
assert_equal(expected.n_cols, actual.n_cols, "n_cols don't match! ", message...);
for (std::size_t i=0; i<expected.n_rows; ++i) {
if (!unittest::core::is_containers_approx_equal(vector_t(expected.row(i).t()), vector_t(actual.row(i).t()), eps)) {
const std::string text = "matrices are not approx. equal";
unittest::fail(UNITTEST_FUNC, text, message...);
}
}
}
} // unittest
} // assertions
<commit_msg>use typedef instead of using for gcc4.6 support<commit_after>#pragma once
#include <libunittest/all.hpp>
#include <densitas/all.hpp>
#include <armadillo>
using namespace unittest::assertions;
typedef arma::vec vector_t;
typedef arma::mat matrix_t;
struct mock_model {
vector_t prediction;
vector_t train_y;
matrix_t train_X;
mock_model()
: prediction(), train_y(), train_X()
{}
void train(matrix_t& X, vector_t& y)
{
train_y = y;
train_X = X;
}
vector_t predict_proba(matrix_t&) const
{
return prediction;
}
};
const int no = densitas::model_adapter::no<mock_model>();
const int yes = densitas::model_adapter::yes<mock_model>();
const double dno = static_cast<double>(no);
const double dyes = static_cast<double>(yes);
namespace densitas {
namespace matrix_adapter {
template<>
inline
std::size_t n_rows(const matrix_t& matrix)
{
return matrix.n_rows;
}
template<>
inline
std::size_t n_columns(const matrix_t& matrix)
{
return matrix.n_cols;
}
} // matrix_adapter
namespace vector_adapter {
template<>
inline
std::size_t n_elements(const vector_t& vector)
{
return vector.n_elem;
}
} // vector_adapter
} // densitas
namespace unittest {
namespace assertions {
template<typename... Args>
void
assert_equal_containers(const matrix_t& expected,
const matrix_t& actual,
const Args&... message)
{
assert_equal(expected.n_rows, actual.n_rows, "n_rows don't match! ", message...);
assert_equal(expected.n_cols, actual.n_cols, "n_cols don't match! ", message...);
for (std::size_t i=0; i<expected.n_rows; ++i) {
if (!unittest::core::is_containers_equal(vector_t(expected.row(i).t()), vector_t(actual.row(i).t()))) {
const std::string text = "matrices are not equal";
unittest::fail(UNITTEST_FUNC, text, message...);
}
}
}
template<typename... Args>
void
assert_approx_equal_containers(const matrix_t& expected,
const matrix_t& actual,
const double eps,
const Args&... message)
{
assert_equal(expected.n_rows, actual.n_rows, "n_rows don't match! ", message...);
assert_equal(expected.n_cols, actual.n_cols, "n_cols don't match! ", message...);
for (std::size_t i=0; i<expected.n_rows; ++i) {
if (!unittest::core::is_containers_approx_equal(vector_t(expected.row(i).t()), vector_t(actual.row(i).t()), eps)) {
const std::string text = "matrices are not approx. equal";
unittest::fail(UNITTEST_FUNC, text, message...);
}
}
}
} // unittest
} // assertions
<|endoftext|>
|
<commit_before>
#ifndef EGE_PRIVATE_GRAPHIC_GEOMETRY_MATRIX_HXX
#define EGE_PRIVATE_GRAPHIC_GEOMETRY_MATRIX_HXX
namespace ege_private
{
namespace graphic
{
namespace geometry
{
namespace matrix
{
static inline void multiply( float* out, const float* left, const float* right )
{
out[ 0 ] = ( left[ 0 ] * right[ 0 ] ) + ( left[ 4 ] * right[ 1 ] ) + ( left[ 8 ] * right[ 2 ] ) + ( left[ 12 ] * right[ 3 ] );
out[ 4 ] = ( left[ 0 ] * right[ 4 ] ) + ( left[ 4 ] * right[ 5 ] ) + ( left[ 8 ] * right[ 6 ] ) + ( left[ 12 ] * right[ 7 ] );
out[ 8 ] = ( left[ 0 ] * right[ 8 ] ) + ( left[ 4 ] * right[ 9 ] ) + ( left[ 8 ] * right[ 10 ] ) + ( left[ 12 ] * right[ 11 ] );
out[ 12 ] = ( left[ 0 ] * right[ 12 ] ) + ( left[ 4 ] * right[ 13 ] ) + ( left[ 8 ] * right[ 14 ] ) + ( left[ 12 ] * right[ 15 ] );
out[ 1 ] = ( left[ 1 ] * right[ 0 ] ) + ( left[ 5 ] * right[ 1 ] ) + ( left[ 9 ] * right[ 2 ] ) + ( left[ 13 ] * right[ 3 ] );
out[ 5 ] = ( left[ 1 ] * right[ 4 ] ) + ( left[ 5 ] * right[ 5 ] ) + ( left[ 9 ] * right[ 6 ] ) + ( left[ 13 ] * right[ 7 ] );
out[ 9 ] = ( left[ 1 ] * right[ 8 ] ) + ( left[ 5 ] * right[ 9 ] ) + ( left[ 9 ] * right[ 10 ] ) + ( left[ 13 ] * right[ 11 ] );
out[ 13 ] = ( left[ 1 ] * right[ 12 ] ) + ( left[ 5 ] * right[ 13 ] ) + ( left[ 9 ] * right[ 14 ] ) + ( left[ 13 ] * right[ 15 ] );
out[ 2 ] = ( left[ 2 ] * right[ 0 ] ) + ( left[ 6 ] * right[ 1 ] ) + ( left[ 10 ] * right[ 2 ] ) + ( left[ 14 ] * right[ 3 ] );
out[ 6 ] = ( left[ 2 ] * right[ 4 ] ) + ( left[ 6 ] * right[ 5 ] ) + ( left[ 10 ] * right[ 6 ] ) + ( left[ 14 ] * right[ 7 ] );
out[ 10 ] = ( left[ 2 ] * right[ 8 ] ) + ( left[ 6 ] * right[ 9 ] ) + ( left[ 10 ] * right[ 10 ] ) + ( left[ 14 ] * right[ 11 ] );
out[ 14 ] = ( left[ 2 ] * right[ 12 ] ) + ( left[ 6 ] * right[ 13 ] ) + ( left[ 10 ] * right[ 14 ] ) + ( left[ 14 ] * right[ 15 ] );
out[ 3 ] = ( left[ 3 ] * right[ 0 ] ) + ( left[ 7 ] * right[ 1 ] ) + ( left[ 11 ] * right[ 2 ] ) + ( left[ 15 ] * right[ 3 ] );
out[ 7 ] = ( left[ 3 ] * right[ 4 ] ) + ( left[ 7 ] * right[ 5 ] ) + ( left[ 11 ] * right[ 6 ] ) + ( left[ 15 ] * right[ 7 ] );
out[ 11 ] = ( left[ 3 ] * right[ 8 ] ) + ( left[ 7 ] * right[ 9 ] ) + ( left[ 11 ] * right[ 10 ] ) + ( left[ 15 ] * right[ 11 ] );
out[ 15 ] = ( left[ 3 ] * right[ 12 ] ) + ( left[ 7 ] * right[ 13 ] ) + ( left[ 11 ] * right[ 14 ] ) + ( left[ 15 ] * right[ 15 ] );
}
}
}
}
}
#endif
<commit_msg>added function to transform a matrix into identity<commit_after>
#ifndef EGE_PRIVATE_GRAPHIC_GEOMETRY_MATRIX_HXX
#define EGE_PRIVATE_GRAPHIC_GEOMETRY_MATRIX_HXX
namespace ege_private
{
namespace graphic
{
namespace geometry
{
namespace matrix
{
static inline void multiply( float* out, const float* left, const float* right )
{
out[ 0 ] = ( left[ 0 ] * right[ 0 ] ) + ( left[ 4 ] * right[ 1 ] ) + ( left[ 8 ] * right[ 2 ] ) + ( left[ 12 ] * right[ 3 ] );
out[ 4 ] = ( left[ 0 ] * right[ 4 ] ) + ( left[ 4 ] * right[ 5 ] ) + ( left[ 8 ] * right[ 6 ] ) + ( left[ 12 ] * right[ 7 ] );
out[ 8 ] = ( left[ 0 ] * right[ 8 ] ) + ( left[ 4 ] * right[ 9 ] ) + ( left[ 8 ] * right[ 10 ] ) + ( left[ 12 ] * right[ 11 ] );
out[ 12 ] = ( left[ 0 ] * right[ 12 ] ) + ( left[ 4 ] * right[ 13 ] ) + ( left[ 8 ] * right[ 14 ] ) + ( left[ 12 ] * right[ 15 ] );
out[ 1 ] = ( left[ 1 ] * right[ 0 ] ) + ( left[ 5 ] * right[ 1 ] ) + ( left[ 9 ] * right[ 2 ] ) + ( left[ 13 ] * right[ 3 ] );
out[ 5 ] = ( left[ 1 ] * right[ 4 ] ) + ( left[ 5 ] * right[ 5 ] ) + ( left[ 9 ] * right[ 6 ] ) + ( left[ 13 ] * right[ 7 ] );
out[ 9 ] = ( left[ 1 ] * right[ 8 ] ) + ( left[ 5 ] * right[ 9 ] ) + ( left[ 9 ] * right[ 10 ] ) + ( left[ 13 ] * right[ 11 ] );
out[ 13 ] = ( left[ 1 ] * right[ 12 ] ) + ( left[ 5 ] * right[ 13 ] ) + ( left[ 9 ] * right[ 14 ] ) + ( left[ 13 ] * right[ 15 ] );
out[ 2 ] = ( left[ 2 ] * right[ 0 ] ) + ( left[ 6 ] * right[ 1 ] ) + ( left[ 10 ] * right[ 2 ] ) + ( left[ 14 ] * right[ 3 ] );
out[ 6 ] = ( left[ 2 ] * right[ 4 ] ) + ( left[ 6 ] * right[ 5 ] ) + ( left[ 10 ] * right[ 6 ] ) + ( left[ 14 ] * right[ 7 ] );
out[ 10 ] = ( left[ 2 ] * right[ 8 ] ) + ( left[ 6 ] * right[ 9 ] ) + ( left[ 10 ] * right[ 10 ] ) + ( left[ 14 ] * right[ 11 ] );
out[ 14 ] = ( left[ 2 ] * right[ 12 ] ) + ( left[ 6 ] * right[ 13 ] ) + ( left[ 10 ] * right[ 14 ] ) + ( left[ 14 ] * right[ 15 ] );
out[ 3 ] = ( left[ 3 ] * right[ 0 ] ) + ( left[ 7 ] * right[ 1 ] ) + ( left[ 11 ] * right[ 2 ] ) + ( left[ 15 ] * right[ 3 ] );
out[ 7 ] = ( left[ 3 ] * right[ 4 ] ) + ( left[ 7 ] * right[ 5 ] ) + ( left[ 11 ] * right[ 6 ] ) + ( left[ 15 ] * right[ 7 ] );
out[ 11 ] = ( left[ 3 ] * right[ 8 ] ) + ( left[ 7 ] * right[ 9 ] ) + ( left[ 11 ] * right[ 10 ] ) + ( left[ 15 ] * right[ 11 ] );
out[ 15 ] = ( left[ 3 ] * right[ 12 ] ) + ( left[ 7 ] * right[ 13 ] ) + ( left[ 11 ] * right[ 14 ] ) + ( left[ 15 ] * right[ 15 ] );
}
static inline void identity( float* matrix )
{
matrix[ 0 ] = 1.0f;
matrix[ 1 ] = 0.0f;
matrix[ 2 ] = 0.0f;
matrix[ 3 ] = 0.0f;
matrix[ 4 ] = 0.0f;
matrix[ 5 ] = 1.0f;
matrix[ 6 ] = 0.0f;
matrix[ 7 ] = 0.0f;
matrix[ 8 ] = 0.0f;
matrix[ 9 ] = 0.0f;
matrix[ 10 ] = 1.0f;
matrix[ 11 ] = 0.0f;
matrix[ 12 ] = 0.0f;
matrix[ 13 ] = 0.0f;
matrix[ 14 ] = 0.0f;
matrix[ 15 ] = 1.0f;
}
}
}
}
}
#endif
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Andrew Manson <g.real.ate@gmail.com>
//
#include "OsmBoundsGraphicsItem.h"
#include <QtCore/QDebug>
namespace Marble{
OsmBoundsGraphicsItem::OsmBoundsGraphicsItem() : GeoDataLineString()
{
}
OsmBoundsGraphicsItem::OsmBoundsGraphicsItem( GeoDataGeometry& other )
// : GeoDataLineString( other )
{
}
void OsmBoundsGraphicsItem::paint( Geopainter* painter, ViewportParams * viewport,
const QString &renderPos, GeoSceneLayer* layer )
{
Q_UNUSED( renderPos )
Q_UNUSED( layer )
qDebug() << "Painting from OSMBounds";
}
}
<commit_msg>correct type name<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Andrew Manson <g.real.ate@gmail.com>
//
#include "OsmBoundsGraphicsItem.h"
#include <QtCore/QDebug>
namespace Marble{
OsmBoundsGraphicsItem::OsmBoundsGraphicsItem() : GeoDataLineString()
{
}
OsmBoundsGraphicsItem::OsmBoundsGraphicsItem( GeoDataGeometry& other )
// : GeoDataLineString( other )
{
}
void OsmBoundsGraphicsItem::paint( GeoPainter* painter, ViewportParams * viewport,
const QString &renderPos, GeoSceneLayer* layer )
{
Q_UNUSED( renderPos )
Q_UNUSED( layer )
qDebug() << "Painting from OSMBounds";
}
}
<|endoftext|>
|
<commit_before>#include "../JSON_Parser.hxx"
bool JSON_Parser::EndObject(rapidjson::SizeType memberCount)
{
if(inside)
{
if(parsing_objective)
{
throw std::runtime_error(
"Invalid input file. Found an object end inside '"
+ objective_state.name + "'");
}
else if(parsing_normalization)
{
throw std::runtime_error(
"Invalid input file. Found an object end inside '"
+ normalization_state.name + "'");
}
else if(parsing_positive_matrices_with_prefactor)
{
positive_matrices_with_prefactor_state.json_end_object();
}
else
{
inside = false;
}
}
else
{
throw std::runtime_error(
"Invalid input file. Ending an object outside of the SDP");
}
return true;
}
<commit_msg>Fix warning<commit_after>#include "../JSON_Parser.hxx"
bool JSON_Parser::EndObject(rapidjson::SizeType)
{
if(inside)
{
if(parsing_objective)
{
throw std::runtime_error(
"Invalid input file. Found an object end inside '"
+ objective_state.name + "'");
}
else if(parsing_normalization)
{
throw std::runtime_error(
"Invalid input file. Found an object end inside '"
+ normalization_state.name + "'");
}
else if(parsing_positive_matrices_with_prefactor)
{
positive_matrices_with_prefactor_state.json_end_object();
}
else
{
inside = false;
}
}
else
{
throw std::runtime_error(
"Invalid input file. Ending an object outside of the SDP");
}
return true;
}
<|endoftext|>
|
<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__NORMAL_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__NORMAL_HPP__
#include <stan/prob/constants.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/prob/traits.hpp>
namespace stan {
namespace prob {
/**
* The log of the normal density for the given y, mean, and
* standard deviation. The standard deviation must be greater
* than 0.
*
* \f{eqnarray*}{
y &\sim& \mbox{\sf{N}} (\mu, \sigma^2) \\
\log (p (y \,|\, \mu, \sigma) ) &=& \log \left( \frac{1}{\sqrt{2 \pi} \sigma} \exp \left( - \frac{1}{2 \sigma^2} (y - \mu)^2 \right) \right) \\
&=& \log (1) - \frac{1}{2}\log (2 \pi) - \log (\sigma) - \frac{(y - \mu)^2}{2 \sigma^2}
\f}
*
* Errors are configured by policy. All variables must be finite
* and the scale must be strictly greater than zero.
*
* @param y A scalar variate.
* @param mu The location of the normal distribution.
* @param sigma The scale of the normal distribution.
* @return The log of the normal density of the specified arguments.
* @tparam propto Set to <code>true</code> if only calculated up
* to a proportion.
* @tparam T_y Type of scalar.
* @tparam T_loc Type of location.
* @tparam T_scale Type of scale.
* @tparam Policy Error-handling policy.
*/
template <bool propto,
typename T_y, typename T_loc, typename T_scale,
class Policy>
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma,
const Policy&) {
static const char* function = "stan::prob::normal_log<%1%>(%1%)";
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using boost::math::tools::promote_args;
typename promote_args<T_y,T_loc,T_scale>::type lp(0.0);
if (!check_not_nan(function, y, "Random variate y", &lp, Policy()))
return lp;
if (!check_finite(function, mu, "Location parameter, mu,",
&lp, Policy()))
return lp;
if (!check_not_nan(function, sigma, "Scale parameter, sigma,",
&lp, Policy()))
return lp;
if (!check_positive(function, sigma, "Scale parameter, sigma,",
&lp, Policy()))
return lp;
using stan::math::square;
if (include_summand<propto,T_y,T_loc,T_scale>::value)
lp -= square(y - mu) / (2.0 * square(sigma));
if (include_summand<propto,T_scale>::value)
lp -= log(sigma);
if (include_summand<propto>::value)
lp += NEG_LOG_SQRT_TWO_PI;
return lp;
}
template <bool propto,
typename T_y, typename T_loc, typename T_scale>
inline
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma) {
return normal_log<propto>(y,mu,sigma,stan::math::default_policy());
}
template <typename T_y, typename T_loc, typename T_scale,
class Policy>
inline
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma,
const Policy&) {
return normal_log<false>(y,mu,sigma,Policy());
}
template <typename T_y, typename T_loc, typename T_scale>
inline
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma) {
return normal_log<false>(y,mu,sigma,stan::math::default_policy());
}
/**
* Calculates the normal cumulative distribution function for the given
* variate, location, and scale.
*
* \f$\Phi(x) = \frac{1}{\sqrt{2 \pi}} \int_{-\inf}^x e^{-t^2/2} dt\f$.
*
* Errors are configured by policy. All variables must be finite
* and the scale must be strictly greater than zero.
*
* @param y A scalar variate.
* @param mu The location of the normal distribution.
* @param sigma The scale of the normal distriubtion
* @return The unit normal cdf evaluated at the specified arguments.
* @tparam propto Set to <code>true</code> if only calculated up to a
* proportion.
* @tparam T_y Type of y.
* @tparam T_loc Type of mean parameter.
* @tparam T_scale Type of standard deviation paramater.
* @tparam Policy Error-handling policy.
*/
template <typename T_y, typename T_loc, typename T_scale,
class Policy>
typename boost::math::tools::promote_args<T_y, T_loc, T_scale>::type
normal_p(const T_y& y, const T_loc& mu, const T_scale& sigma,
const Policy&) {
static const char* function = "stan::prob::normal_p(%1%)";
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using boost::math::tools::promote_args;
typename promote_args<T_y, T_loc, T_scale>::type lp;
if (!check_not_nan(function, y, "Random variate y", &lp, Policy()))
return lp;
if (!check_finite(function, mu, "Location parameter, mu,", &lp, Policy()))
return lp;
if (!check_not_nan(function, sigma, "Scale parameter, sigma,",
&lp, Policy()))
return lp;
if (!check_positive(function, sigma, "Scale parameter, sigma,",
&lp, Policy()))
return lp;
return 0.5 * erfc(-(y - mu)/(sigma * SQRT_2));
}
template <typename T_y, typename T_loc, typename T_scale>
inline
typename boost::math::tools::promote_args<T_y, T_loc, T_scale>::type
normal_p(const T_y& y, const T_loc& mu, const T_scale& sigma) {
return normal_p(y,mu,sigma,stan::math::default_policy());
}
/**
* The log of the normal density for the specified sequence of
* scalars given the specified mean and deviation. If the
* sequence of values is of length 0, the result is 0.0.
*
* <p>The result log probability is defined to be the sum of the
* log probabilities for each observation. Hence if the sequence
* is of length 0, the log probability is 0.0.
*
* @param y Sequence of scalars.
* @param mu Location parameter for the normal distribution.
* @param sigma Scale parameter for the normal distribution.
* @return The log of the product of the densities.
* @throw std::domain_error if the scale is not positive.
* @tparam T_y Underlying type of scalar in sequence.
* @tparam T_loc Type of location parameter.
*/
template <bool propto,
typename T_y, typename T_loc, typename T_scale,
class Policy>
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const std::vector<T_y>& y,
const T_loc& mu,
const T_scale& sigma,
const Policy&) {
static const char* function = "stan::prob::normal_log<%1%>(%1%)";
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using boost::math::tools::promote_args;
typename promote_args<T_y,T_loc,T_scale>::type lp;
if (!check_not_nan(function, y, "Random variate y", &lp, Policy()))
return lp;
if (!check_finite(function, mu, "Location parameter, mu,", &lp, Policy()))
return lp;
if (!check_not_nan(function, sigma, "Scale parameter, sigma,",
&lp, Policy()))
return lp;
if (!check_positive(function, sigma, "Scale parameter, sigma,",
&lp, Policy()))
return lp;
if (y.size() == 0)
return 0.0;
using stan::math::square;
using stan::math::multiply_log;
lp = 0.0;
if (include_summand<propto,T_y,T_loc,T_scale>::value) {
for (unsigned int n = 0; n < y.size(); ++n)
lp -= square(y[n] - mu);
lp /= 2.0 * square(sigma);
}
if (include_summand<propto,T_scale>::value)
lp -= multiply_log(y.size(),sigma);
if (include_summand<propto>::value)
lp += y.size() * NEG_LOG_SQRT_TWO_PI;
return lp;
}
template <bool propto,
typename T_y, typename T_loc, typename T_scale>
inline
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const std::vector<T_y>& y,
const T_loc& mu,
const T_scale& sigma) {
return normal_log<propto>(y,mu,sigma,stan::math::default_policy());
}
template <typename T_y, typename T_loc, typename T_scale,
class Policy>
inline
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const std::vector<T_y>& y,
const T_loc& mu,
const T_scale& sigma,
const Policy&) {
return normal_log<false>(y,mu,sigma,Policy());
}
template <typename T_y, typename T_loc, typename T_scale>
inline
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const std::vector<T_y>& y,
const T_loc& mu,
const T_scale& sigma) {
return normal_log<false>(y,mu,sigma,stan::math::default_policy());
}
}
}
#endif
<commit_msg>sorted imports<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__NORMAL_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__NORMAL_HPP__
#include <stan/math/error_handling.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>
namespace stan {
namespace prob {
/**
* The log of the normal density for the given y, mean, and
* standard deviation. The standard deviation must be greater
* than 0.
*
* \f{eqnarray*}{
y &\sim& \mbox{\sf{N}} (\mu, \sigma^2) \\
\log (p (y \,|\, \mu, \sigma) ) &=& \log \left( \frac{1}{\sqrt{2 \pi} \sigma} \exp \left( - \frac{1}{2 \sigma^2} (y - \mu)^2 \right) \right) \\
&=& \log (1) - \frac{1}{2}\log (2 \pi) - \log (\sigma) - \frac{(y - \mu)^2}{2 \sigma^2}
\f}
*
* Errors are configured by policy. All variables must be finite
* and the scale must be strictly greater than zero.
*
* @param y A scalar variate.
* @param mu The location of the normal distribution.
* @param sigma The scale of the normal distribution.
* @return The log of the normal density of the specified arguments.
* @tparam propto Set to <code>true</code> if only calculated up
* to a proportion.
* @tparam T_y Type of scalar.
* @tparam T_loc Type of location.
* @tparam T_scale Type of scale.
* @tparam Policy Error-handling policy.
*/
template <bool propto,
typename T_y, typename T_loc, typename T_scale,
class Policy>
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma,
const Policy&) {
static const char* function = "stan::prob::normal_log<%1%>(%1%)";
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using boost::math::tools::promote_args;
typename promote_args<T_y,T_loc,T_scale>::type lp(0.0);
if (!check_not_nan(function, y, "Random variate y", &lp, Policy()))
return lp;
if (!check_finite(function, mu, "Location parameter, mu,",
&lp, Policy()))
return lp;
if (!check_not_nan(function, sigma, "Scale parameter, sigma,",
&lp, Policy()))
return lp;
if (!check_positive(function, sigma, "Scale parameter, sigma,",
&lp, Policy()))
return lp;
using stan::math::square;
if (include_summand<propto,T_y,T_loc,T_scale>::value)
lp -= square(y - mu) / (2.0 * square(sigma));
if (include_summand<propto,T_scale>::value)
lp -= log(sigma);
if (include_summand<propto>::value)
lp += NEG_LOG_SQRT_TWO_PI;
return lp;
}
template <bool propto,
typename T_y, typename T_loc, typename T_scale>
inline
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma) {
return normal_log<propto>(y,mu,sigma,stan::math::default_policy());
}
template <typename T_y, typename T_loc, typename T_scale,
class Policy>
inline
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma,
const Policy&) {
return normal_log<false>(y,mu,sigma,Policy());
}
template <typename T_y, typename T_loc, typename T_scale>
inline
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const T_y& y, const T_loc& mu, const T_scale& sigma) {
return normal_log<false>(y,mu,sigma,stan::math::default_policy());
}
/**
* Calculates the normal cumulative distribution function for the given
* variate, location, and scale.
*
* \f$\Phi(x) = \frac{1}{\sqrt{2 \pi}} \int_{-\inf}^x e^{-t^2/2} dt\f$.
*
* Errors are configured by policy. All variables must be finite
* and the scale must be strictly greater than zero.
*
* @param y A scalar variate.
* @param mu The location of the normal distribution.
* @param sigma The scale of the normal distriubtion
* @return The unit normal cdf evaluated at the specified arguments.
* @tparam propto Set to <code>true</code> if only calculated up to a
* proportion.
* @tparam T_y Type of y.
* @tparam T_loc Type of mean parameter.
* @tparam T_scale Type of standard deviation paramater.
* @tparam Policy Error-handling policy.
*/
template <typename T_y, typename T_loc, typename T_scale,
class Policy>
typename boost::math::tools::promote_args<T_y, T_loc, T_scale>::type
normal_p(const T_y& y, const T_loc& mu, const T_scale& sigma,
const Policy&) {
static const char* function = "stan::prob::normal_p(%1%)";
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using boost::math::tools::promote_args;
typename promote_args<T_y, T_loc, T_scale>::type lp;
if (!check_not_nan(function, y, "Random variate y", &lp, Policy()))
return lp;
if (!check_finite(function, mu, "Location parameter, mu,", &lp, Policy()))
return lp;
if (!check_not_nan(function, sigma, "Scale parameter, sigma,",
&lp, Policy()))
return lp;
if (!check_positive(function, sigma, "Scale parameter, sigma,",
&lp, Policy()))
return lp;
return 0.5 * erfc(-(y - mu)/(sigma * SQRT_2));
}
template <typename T_y, typename T_loc, typename T_scale>
inline
typename boost::math::tools::promote_args<T_y, T_loc, T_scale>::type
normal_p(const T_y& y, const T_loc& mu, const T_scale& sigma) {
return normal_p(y,mu,sigma,stan::math::default_policy());
}
/**
* The log of the normal density for the specified sequence of
* scalars given the specified mean and deviation. If the
* sequence of values is of length 0, the result is 0.0.
*
* <p>The result log probability is defined to be the sum of the
* log probabilities for each observation. Hence if the sequence
* is of length 0, the log probability is 0.0.
*
* @param y Sequence of scalars.
* @param mu Location parameter for the normal distribution.
* @param sigma Scale parameter for the normal distribution.
* @return The log of the product of the densities.
* @throw std::domain_error if the scale is not positive.
* @tparam T_y Underlying type of scalar in sequence.
* @tparam T_loc Type of location parameter.
*/
template <bool propto,
typename T_y, typename T_loc, typename T_scale,
class Policy>
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const std::vector<T_y>& y,
const T_loc& mu,
const T_scale& sigma,
const Policy&) {
static const char* function = "stan::prob::normal_log<%1%>(%1%)";
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using boost::math::tools::promote_args;
typename promote_args<T_y,T_loc,T_scale>::type lp;
if (!check_not_nan(function, y, "Random variate y", &lp, Policy()))
return lp;
if (!check_finite(function, mu, "Location parameter, mu,", &lp, Policy()))
return lp;
if (!check_not_nan(function, sigma, "Scale parameter, sigma,",
&lp, Policy()))
return lp;
if (!check_positive(function, sigma, "Scale parameter, sigma,",
&lp, Policy()))
return lp;
if (y.size() == 0)
return 0.0;
using stan::math::square;
using stan::math::multiply_log;
lp = 0.0;
if (include_summand<propto,T_y,T_loc,T_scale>::value) {
for (unsigned int n = 0; n < y.size(); ++n)
lp -= square(y[n] - mu);
lp /= 2.0 * square(sigma);
}
if (include_summand<propto,T_scale>::value)
lp -= multiply_log(y.size(),sigma);
if (include_summand<propto>::value)
lp += y.size() * NEG_LOG_SQRT_TWO_PI;
return lp;
}
template <bool propto,
typename T_y, typename T_loc, typename T_scale>
inline
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const std::vector<T_y>& y,
const T_loc& mu,
const T_scale& sigma) {
return normal_log<propto>(y,mu,sigma,stan::math::default_policy());
}
template <typename T_y, typename T_loc, typename T_scale,
class Policy>
inline
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const std::vector<T_y>& y,
const T_loc& mu,
const T_scale& sigma,
const Policy&) {
return normal_log<false>(y,mu,sigma,Policy());
}
template <typename T_y, typename T_loc, typename T_scale>
inline
typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
normal_log(const std::vector<T_y>& y,
const T_loc& mu,
const T_scale& sigma) {
return normal_log<false>(y,mu,sigma,stan::math::default_policy());
}
}
}
#endif
<|endoftext|>
|
<commit_before>/*!
* Copyright (c) 2015 by Contributors
*/
#include <unistd.h>
#include <dmlc/logging.h>
#include <cstdio>
#include <thread>
#include <chrono>
#include <vector>
#include "mxnet/engine.h"
void Foo(mxnet::RunContext, int i) { printf("The fox says %d\n", i); }
int main() {
auto&& engine = mxnet::Engine::Get();
auto&& var = engine->NewVariable();
std::vector<mxnet::Engine::OprHandle> oprs;
// Test #1
printf("============= Test #1 ==============\n");
for (int i = 0; i < 10; ++i) {
oprs.push_back(engine->NewOperator(
[i](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
Foo(ctx, i);
std::this_thread::sleep_for(std::chrono::seconds{1});
cb();
},
{var}, {}));
engine->Push(oprs.at(i), mxnet::Context{});
}
engine->WaitForAll();
printf("Going to push delete\n");
// std::this_thread::sleep_for(std::chrono::seconds{1});
for (auto&& i : oprs) {
engine->DeleteOperator(i);
}
engine->PushDelete([](mxnet::RunContext) {}, mxnet::Context{}, var);
engine->WaitForAll();
printf("============= Test #2 ==============\n");
var = engine->NewVariable();
oprs.clear();
for (int i = 0; i < 10; ++i) {
oprs.push_back(engine->NewOperator(
[i](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
Foo(ctx, i);
std::this_thread::sleep_for(std::chrono::milliseconds{500});
cb();
},
{}, {var}));
engine->Push(oprs.at(i), mxnet::Context{});
}
// std::this_thread::sleep_for(std::chrono::seconds{1});
engine->WaitForAll();
for (auto&& i : oprs) {
engine->DeleteOperator(i);
}
engine->PushDelete([](mxnet::RunContext) {}, mxnet::Context{}, var);
printf("============= Test #3 ==============\n");
var = engine->NewVariable();
oprs.clear();
engine->WaitForVar(var);
engine->PushDelete([](mxnet::RunContext) {}, mxnet::Context{}, var);
engine->WaitForAll();
printf("============= Test #4 ==============\n");
var = engine->NewVariable();
oprs.clear();
oprs.push_back(engine->NewOperator(
[](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
std::this_thread::sleep_for(std::chrono::seconds{2});
Foo(ctx, 42);
cb();
},
{}, {var}));
engine->Push(oprs.at(0), mxnet::Context{});
LOG(INFO) << "Operator pushed, should wait for 2 seconds.";
engine->WaitForVar(var);
LOG(INFO) << "OK, here I am.";
for (auto&& i : oprs) {
engine->DeleteOperator(i);
}
engine->PushDelete([](mxnet::RunContext) {}, mxnet::Context{}, var);
engine->WaitForAll();
printf("============= Test #5 ==============\n");
var = engine->NewVariable();
oprs.clear();
oprs.push_back(engine->NewOperator(
[](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
Foo(ctx, 42);
std::this_thread::sleep_for(std::chrono::seconds{2});
cb();
},
{var}, {}));
engine->Push(oprs.at(0), mxnet::Context{});
LOG(INFO) << "Operator pushed, should not wait.";
engine->WaitForVar(var);
LOG(INFO) << "OK, here I am.";
engine->WaitForAll();
LOG(INFO) << "That was 2 seconds.";
for (auto&& i : oprs) {
engine->DeleteOperator(i);
}
engine->PushDelete([](mxnet::RunContext) {}, mxnet::Context{}, var);
engine->WaitForAll();
var = nullptr;
oprs.clear();
return 0;
}
<commit_msg>[engine-refactor] rename in test file<commit_after>/*!
* Copyright (c) 2015 by Contributors
*/
#include <unistd.h>
#include <dmlc/logging.h>
#include <cstdio>
#include <thread>
#include <chrono>
#include <vector>
#include "mxnet/engine.h"
void Foo(mxnet::RunContext, int i) { printf("The fox says %d\n", i); }
int main() {
auto&& engine = mxnet::Engine::Get();
auto&& var = engine->NewVariable();
std::vector<mxnet::Engine::OprHandle> oprs;
// Test #1
printf("============= Test #1 ==============\n");
for (int i = 0; i < 10; ++i) {
oprs.push_back(engine->NewOperator(
[i](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
Foo(ctx, i);
std::this_thread::sleep_for(std::chrono::seconds{1});
cb();
},
{var}, {}));
engine->Push(oprs.at(i), mxnet::Context{});
}
engine->WaitForAll();
printf("Going to push delete\n");
// std::this_thread::sleep_for(std::chrono::seconds{1});
for (auto&& i : oprs) {
engine->DeleteOperator(i);
}
engine->DeleteVariable([](mxnet::RunContext) {}, mxnet::Context{}, var);
engine->WaitForAll();
printf("============= Test #2 ==============\n");
var = engine->NewVariable();
oprs.clear();
for (int i = 0; i < 10; ++i) {
oprs.push_back(engine->NewOperator(
[i](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
Foo(ctx, i);
std::this_thread::sleep_for(std::chrono::milliseconds{500});
cb();
},
{}, {var}));
engine->Push(oprs.at(i), mxnet::Context{});
}
// std::this_thread::sleep_for(std::chrono::seconds{1});
engine->WaitForAll();
for (auto&& i : oprs) {
engine->DeleteOperator(i);
}
engine->DeleteVariable([](mxnet::RunContext) {}, mxnet::Context{}, var);
printf("============= Test #3 ==============\n");
var = engine->NewVariable();
oprs.clear();
engine->WaitForVar(var);
engine->DeleteVariable([](mxnet::RunContext) {}, mxnet::Context{}, var);
engine->WaitForAll();
printf("============= Test #4 ==============\n");
var = engine->NewVariable();
oprs.clear();
oprs.push_back(engine->NewOperator(
[](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
std::this_thread::sleep_for(std::chrono::seconds{2});
Foo(ctx, 42);
cb();
},
{}, {var}));
engine->Push(oprs.at(0), mxnet::Context{});
LOG(INFO) << "Operator pushed, should wait for 2 seconds.";
engine->WaitForVar(var);
LOG(INFO) << "OK, here I am.";
for (auto&& i : oprs) {
engine->DeleteOperator(i);
}
engine->DeleteVariable([](mxnet::RunContext) {}, mxnet::Context{}, var);
engine->WaitForAll();
printf("============= Test #5 ==============\n");
var = engine->NewVariable();
oprs.clear();
oprs.push_back(engine->NewOperator(
[](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
Foo(ctx, 42);
std::this_thread::sleep_for(std::chrono::seconds{2});
cb();
},
{var}, {}));
engine->Push(oprs.at(0), mxnet::Context{});
LOG(INFO) << "Operator pushed, should not wait.";
engine->WaitForVar(var);
LOG(INFO) << "OK, here I am.";
engine->WaitForAll();
LOG(INFO) << "That was 2 seconds.";
for (auto&& i : oprs) {
engine->DeleteOperator(i);
}
engine->DeleteVariable([](mxnet::RunContext) {}, mxnet::Context{}, var);
engine->WaitForAll();
var = nullptr;
oprs.clear();
return 0;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/hwpf/hwp/establish_system_smp/establish_system_smp.C $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* COPYRIGHT International Business Machines Corp. 2012,2013 */
/* */
/* p1 */
/* */
/* Object Code Only (OCO) source materials */
/* Licensed Internal Code Source Materials */
/* IBM HostBoot Licensed Internal Code */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* Origin: 30 */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file establish_system_smp.C
*
* Support file for IStep: establish_system_smp
* Establish System SMP
*
* *****************************************************************
* THIS FILE WAS GENERATED ON 2012-04-11:1611
* *****************************************************************
*
* HWP_IGNORE_VERSION_CHECK
*
*/
/******************************************************************************/
// Includes
/******************************************************************************/
#include <stdint.h>
#include <trace/interface.H>
#include <initservice/taskargs.H>
#include <errl/errlentry.H>
#include <initservice/isteps_trace.H>
#include <hwpisteperror.H>
#include <istep_mbox_msgs.H>
// targeting support
#include <targeting/common/commontargeting.H>
#include <smp_unfencing_inter_enclosure_abus_links.H>
#include <targeting/common/attributes.H>
// fapi support
#include <fapi.H>
#include <fapiPlatHwpInvoker.H>
#include "establish_system_smp.H"
// Uncomment these files as they become available:
// #include "host_coalesce_host/host_coalesce_host.H"
namespace ESTABLISH_SYSTEM_SMP
{
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace TARGETING;
using namespace fapi;
using namespace EDI_EI_INITIALIZATION;
//
// Wrapper function to call host_coalesce_host
//
void* call_host_coalesce_host( void *io_pArgs )
{
errlHndl_t l_errl = NULL;
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_coalesce_host entry" );
#if 0
// @@@@@ CUSTOM BLOCK: @@@@@
// figure out what targets we need
// customize any other inputs
// set up loops to go through all targets (if parallel, spin off a task)
// write HUID of target
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"target HUID %.8X", TARGETING::get_huid(l));
// cast OUR type of target to a FAPI type of target.
const fapi::Target l_fapi_@targetN_target( TARGET_TYPE_MEMBUF_CHIP,
(const_cast<TARGETING::Target*>(l_@targetN_target)) );
// call the HWP with each fapi::Target
FAPI_INVOKE_HWP( l_errl, host_coalesce_host, _args_...);
if ( l_errl )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR : .........." );
errlCommit( l_errl, HWPF_COMP_ID );
}
else
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"SUCCESS : .........." );
}
// @@@@@ END CUSTOM BLOCK: @@@@@
#endif
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_coalesce_host exit" );
// end task, returning any errorlogs to IStepDisp
return l_errl;
}
//******************************************************************************
// host_sys_fab_iovalid_processing function
//******************************************************************************
void host_sys_fab_iovalid_processing( msg_t* io_pMsg )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_sys_fab_iovalid_processing entry" );
iovalid_msg * drawerData = NULL;
uint16_t count = 0;
std::vector<TARGETING::EntityPath> present_drawers;
errlHndl_t l_errl = NULL;
// if there is extra data, start processing it
// else send back a msg to indicate invalid msg
if(io_pMsg->extra_data)
{
drawerData = (iovalid_msg *)io_pMsg->extra_data;
// setup a pointer to the first drawer entry in our data
TARGETING::EntityPath * ptr = drawerData->drawers;
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,"Master node %s "
"List size = %d bytes "
"Drawer count = %d",
ptr->toString(), drawerData->size, drawerData->count);
count = drawerData->count;
// get FABRIC_TO_PHYSICAL_NODE_MAP
TARGETING::Target * sys = NULL;
TARGETING::targetService().getTopLevelTarget( sys );
assert(sys != NULL);
uint8_t node_map[8];
bool rc =
sys->tryGetAttr<TARGETING::ATTR_FABRIC_TO_PHYSICAL_NODE_MAP>(node_map);
assert(rc == true);
TARGETING::ATTR_HB_EXISTING_IMAGE_type hb_existing_image = 0;
// create a vector with the present drawers
for(uint8_t i = 0; i < count; i++)
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"list entry[%d] - %s", i, ptr->toString());
present_drawers.push_back(*ptr);
TARGETING::EntityPath::PathElement pe =
ptr->pathElementOfType(TARGETING::TYPE_NODE);
// pe.instance is the drawer number - convert to logical node
uint8_t logical_node = node_map[pe.instance];
// set mask to msb of bitmap
TARGETING::ATTR_HB_EXISTING_IMAGE_type mask = 0x1 <<
((sizeof(TARGETING::ATTR_HB_EXISTING_IMAGE_type) * 8) -1);
// set bit for this logical node.
hb_existing_image |= (mask >> logical_node);
ptr++;
}
sys->setAttr<TARGETING::ATTR_HB_EXISTING_IMAGE>(hb_existing_image);
// $TODO RTC:63128 - exchange between present drawers to agree
// on valid endpoints
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"$TODO RTC:63128 - hb instances exchange and agree on cfg");
// after agreement, open abuses as required
l_errl = smp_unfencing_inter_enclosure_abus_links();
// release the storage from the message
free(io_pMsg->extra_data);
io_pMsg->extra_data = NULL;
io_pMsg->data[0] = INITSERVICE::HWSVR_MSG_SUCCESS;
}
else
{
// message needs to have at least one entry
// in the drawer list, else we will say invalid msg
io_pMsg->data[0] = INITSERVICE::HWSVR_INVALID_MESSAGE;
}
io_pMsg->data[1] = 0;
// if there is an error log add the ID to
// data 0
if(l_errl)
{
io_pMsg->data[0] = l_errl->eid();
errlCommit(l_errl, HWPF_COMP_ID);
}
// response will be sent by calling routine
// IStepDispatcher::handleMoreWorkNeededMsg()
// which will also execute the procedure to winkle all cores
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_sys_fab_iovalid_processing exit" );
}
}; // end namespace
<commit_msg>Load edi_ei_initialization module in establish_system_smp step<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/hwpf/hwp/establish_system_smp/establish_system_smp.C $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* COPYRIGHT International Business Machines Corp. 2012,2013 */
/* */
/* p1 */
/* */
/* Object Code Only (OCO) source materials */
/* Licensed Internal Code Source Materials */
/* IBM HostBoot Licensed Internal Code */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* Origin: 30 */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file establish_system_smp.C
*
* Support file for IStep: establish_system_smp
* Establish System SMP
*
* *****************************************************************
* THIS FILE WAS GENERATED ON 2012-04-11:1611
* *****************************************************************
*
* HWP_IGNORE_VERSION_CHECK
*
*/
/******************************************************************************/
// Includes
/******************************************************************************/
#include <stdint.h>
#include <trace/interface.H>
#include <initservice/taskargs.H>
#include <errl/errlentry.H>
#include <initservice/isteps_trace.H>
#include <hwpisteperror.H>
#include <istep_mbox_msgs.H>
#include <vfs/vfs.H>
// targeting support
#include <targeting/common/commontargeting.H>
#include <smp_unfencing_inter_enclosure_abus_links.H>
#include <targeting/common/attributes.H>
// fapi support
#include <fapi.H>
#include <fapiPlatHwpInvoker.H>
#include "establish_system_smp.H"
// Uncomment these files as they become available:
// #include "host_coalesce_host/host_coalesce_host.H"
namespace ESTABLISH_SYSTEM_SMP
{
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace TARGETING;
using namespace fapi;
using namespace EDI_EI_INITIALIZATION;
//
// Wrapper function to call host_coalesce_host
//
void* call_host_coalesce_host( void *io_pArgs )
{
errlHndl_t l_errl = NULL;
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_coalesce_host entry" );
#if 0
// @@@@@ CUSTOM BLOCK: @@@@@
// figure out what targets we need
// customize any other inputs
// set up loops to go through all targets (if parallel, spin off a task)
// write HUID of target
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"target HUID %.8X", TARGETING::get_huid(l));
// cast OUR type of target to a FAPI type of target.
const fapi::Target l_fapi_@targetN_target( TARGET_TYPE_MEMBUF_CHIP,
(const_cast<TARGETING::Target*>(l_@targetN_target)) );
// call the HWP with each fapi::Target
FAPI_INVOKE_HWP( l_errl, host_coalesce_host, _args_...);
if ( l_errl )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR : .........." );
errlCommit( l_errl, HWPF_COMP_ID );
}
else
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"SUCCESS : .........." );
}
// @@@@@ END CUSTOM BLOCK: @@@@@
#endif
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_coalesce_host exit" );
// end task, returning any errorlogs to IStepDisp
return l_errl;
}
//******************************************************************************
// host_sys_fab_iovalid_processing function
//******************************************************************************
void host_sys_fab_iovalid_processing( msg_t* io_pMsg )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_sys_fab_iovalid_processing entry" );
iovalid_msg * drawerData = NULL;
uint16_t count = 0;
std::vector<TARGETING::EntityPath> present_drawers;
errlHndl_t l_errl = NULL;
// if there is extra data, start processing it
// else send back a msg to indicate invalid msg
if(io_pMsg->extra_data)
{
drawerData = (iovalid_msg *)io_pMsg->extra_data;
// setup a pointer to the first drawer entry in our data
TARGETING::EntityPath * ptr = drawerData->drawers;
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,"Master node %s "
"List size = %d bytes "
"Drawer count = %d",
ptr->toString(), drawerData->size, drawerData->count);
count = drawerData->count;
// get FABRIC_TO_PHYSICAL_NODE_MAP
TARGETING::Target * sys = NULL;
TARGETING::targetService().getTopLevelTarget( sys );
assert(sys != NULL);
uint8_t node_map[8];
bool rc =
sys->tryGetAttr<TARGETING::ATTR_FABRIC_TO_PHYSICAL_NODE_MAP>(node_map);
assert(rc == true);
TARGETING::ATTR_HB_EXISTING_IMAGE_type hb_existing_image = 0;
// create a vector with the present drawers
for(uint8_t i = 0; i < count; i++)
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"list entry[%d] - %s", i, ptr->toString());
present_drawers.push_back(*ptr);
TARGETING::EntityPath::PathElement pe =
ptr->pathElementOfType(TARGETING::TYPE_NODE);
// pe.instance is the drawer number - convert to logical node
uint8_t logical_node = node_map[pe.instance];
// set mask to msb of bitmap
TARGETING::ATTR_HB_EXISTING_IMAGE_type mask = 0x1 <<
((sizeof(TARGETING::ATTR_HB_EXISTING_IMAGE_type) * 8) -1);
// set bit for this logical node.
hb_existing_image |= (mask >> logical_node);
ptr++;
}
sys->setAttr<TARGETING::ATTR_HB_EXISTING_IMAGE>(hb_existing_image);
// $TODO RTC:63128 - exchange between present drawers to agree
// on valid endpoints
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"$TODO RTC:63128 - hb instances exchange and agree on cfg");
bool l_libloaded = false;
if ( !VFS::module_is_loaded( "libedi_ei_initialization.so" ) )
{
l_errl = VFS::module_load( "libedi_ei_initialization.so" );
if ( l_errl )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK
"Could not load libedi_ei_initialization.so");
}
else
{
l_libloaded = true;
}
}
if(!l_errl)
{
// after agreement, open abuses as required
l_errl = smp_unfencing_inter_enclosure_abus_links();
}
if(l_libloaded) // loaded locally
{
l_errl = VFS::module_unload( "libedi_ei_initialization.so" );
if(l_errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK
"Could not un-load libedi_ei_initialization.so");
}
}
// release the storage from the message
free(io_pMsg->extra_data);
io_pMsg->extra_data = NULL;
io_pMsg->data[0] = INITSERVICE::HWSVR_MSG_SUCCESS;
}
else
{
// message needs to have at least one entry
// in the drawer list, else we will say invalid msg
io_pMsg->data[0] = INITSERVICE::HWSVR_INVALID_MESSAGE;
}
io_pMsg->data[1] = 0;
// if there is an error log add the ID to
// data 0
if(l_errl)
{
io_pMsg->data[0] = l_errl->eid();
errlCommit(l_errl, HWPF_COMP_ID);
}
// response will be sent by calling routine
// IStepDispatcher::handleMoreWorkNeededMsg()
// which will also execute the procedure to winkle all cores
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"host_sys_fab_iovalid_processing exit" );
}
}; // end namespace
<|endoftext|>
|
<commit_before>#include <exception>
#include <utility>
#include <QMessageBox>
#include "tronwidget.h"
#include "clamp.h"
TronWidget::TronWidget(QWidget *parent) :
QWidget(parent)
{
QObject::connect(&ticker, SIGNAL(timeout()),
this, SLOT(step()));
// TODO: Let user modify this interval?
ticker.setInterval(DEFAULT_TICK_INTERVAL);
}
TronWidget::~TronWidget()
{
tron.reset(nullptr);
}
void TronWidget::start()
{
tron.reset(new Tron(mapSize, playerCount, playerNames, playerColors));
resizeMap();
setFocus(Qt::OtherFocusReason);
ticker.start();
emit gameInProgress(true);
}
void TronWidget::stop()
{
ticker.stop();
emit gameInProgress(false);
}
void TronWidget::step()
{
if (tron) {
if (tron->step()) {
repaint(rect());
} else {
stop();
repaint(rect());
auto winner = tron->getWinner();
QString winnerString;
QString colorString;
if (winner == tron->getPlayers().end()) {
winnerString = "Tie Game";
colorString = "black";
} else {
winnerString = QString{"%1 won!"}.arg(winner->getName());
colorString = winner->getColor().name();
}
QMessageBox gameOverDialog{QMessageBox::Information, "Game Over", winnerString, QMessageBox::Ok, this};
gameOverDialog.setStyleSheet(QString("color: %1").arg(colorString));
gameOverDialog.exec();
}
}
}
void TronWidget::setPlayerCount(int playerCount)
{
this->playerCount = clamp(playerCount,
Tron::MIN_PLAYER_COUNT,
Tron::MAX_PLAYER_COUNT);
}
void TronWidget::setPlayerName(int player, QString name)
{
this->playerNames[player] = name;
}
auto TronWidget::getPlayerName(int player) const -> QString
{
return this->playerNames[player];
}
void TronWidget::setPlayerColor(int player, QColor color)
{
this->playerColors[player] = color;
}
auto TronWidget::getPlayerColor(int player) const -> QColor
{
return this->playerColors[player];
}
void TronWidget::setMapWidth(int width)
{
this->mapSize.setWidth(clamp(width,
Tron::MIN_MAP_WIDTH,
Tron::MAX_MAP_WIDTH));
}
void TronWidget::setMapHeight(int height)
{
this->mapSize.setHeight(clamp(height,
Tron::MIN_MAP_HEIGHT,
Tron::MAX_MAP_HEIGHT));
}
void TronWidget::resizeMap()
{
if (tron) {
// We need to keep the map on-screen no matter
// how the window is resized, so we choose the
// smallest dimension and divide it evenly.
int tileWidth = rect().width() / tron->getMapSize().width();
int tileHeight = rect().height() / tron->getMapSize().height();
tileSize = std::min(tileWidth, tileHeight);
} else {
tileSize = DEFAULT_TILE_SIZE;
}
}
void TronWidget::resizeEvent(QResizeEvent *)
{
resizeMap();
}
void TronWidget::paintEvent(QPaintEvent *)
{
if (tron) {
QPainter painter{this};
// Paint playing board
painter.setBrush(Qt::black);
painter.setPen(QPen(QBrush(Qt::white), 1));
painter.drawRect(rect().x(), rect().y(),
tron->getMapSize().width()*tileSize,
tron->getMapSize().height()*tileSize);
// Draw each player and its trail
painter.setPen(QPen(QBrush(Qt::white), 1));
for(int i = 0; i < tron->getPlayerCount(); ++i) {
auto player = tron->getPlayer(i);
painter.setBrush(player.getColor());
if (player.getIsPlaying()) {
QPoint p = player.getPosition();
painter.drawRect(p.x() * tileSize, p.y() * tileSize,
tileSize, tileSize);
}
for (QPoint pt : player.getTrail()) {
painter.drawRect(pt.x() * tileSize, pt.y() * tileSize,
tileSize, tileSize);
}
}
}
}
void TronWidget::keyPressEvent(QKeyEvent *event)
{
if (tron) {
if (keybindings.count(event->key()) > 0) {
// This key press is a game control
auto binding = keybindings.at(event->key());
// Check if this binding applies to an active player
if (binding.first < tron->getPlayerCount()) {
// Make the turn
tron->getPlayer(binding.first).turn(binding.second);
}
} else {
// This key press doesn't concern our game directly
// Pass it on to the default Qt implementation
QWidget::keyPressEvent(event);
}
}
}
std::map<int, std::pair<int, Player::Direction>>
TronWidget::keybindings
{
// Player One
{Qt::Key_Up, {0, Player::Direction::Up}},
{Qt::Key_Down, {0, Player::Direction::Down}},
{Qt::Key_Left, {0, Player::Direction::Left}},
{Qt::Key_Right, {0, Player::Direction::Right}},
// Player Two
{Qt::Key_W, {1, Player::Direction::Up}},
{Qt::Key_S, {1, Player::Direction::Down}},
{Qt::Key_A, {1, Player::Direction::Left}},
{Qt::Key_D, {1, Player::Direction::Right}},
// Player Three
{Qt::Key_I, {2, Player::Direction::Up}},
{Qt::Key_K, {2, Player::Direction::Down}},
{Qt::Key_J, {2, Player::Direction::Left}},
{Qt::Key_L, {2, Player::Direction::Right}},
// Player Four
{Qt::Key_T, {3, Player::Direction::Up}},
{Qt::Key_G, {3, Player::Direction::Down}},
{Qt::Key_F, {3, Player::Direction::Left}},
{Qt::Key_H, {3, Player::Direction::Right}},
};
const int TronWidget::DEFAULT_TILE_SIZE{20};
const int TronWidget::DEFAULT_TICK_INTERVAL{100};
<commit_msg>Hastened default tick interval.<commit_after>#include <exception>
#include <utility>
#include <QMessageBox>
#include "tronwidget.h"
#include "clamp.h"
TronWidget::TronWidget(QWidget *parent) :
QWidget(parent)
{
QObject::connect(&ticker, SIGNAL(timeout()),
this, SLOT(step()));
// TODO: Let user modify this interval?
ticker.setInterval(DEFAULT_TICK_INTERVAL);
}
TronWidget::~TronWidget()
{
tron.reset(nullptr);
}
void TronWidget::start()
{
tron.reset(new Tron(mapSize, playerCount, playerNames, playerColors));
resizeMap();
setFocus(Qt::OtherFocusReason);
ticker.start();
emit gameInProgress(true);
}
void TronWidget::stop()
{
ticker.stop();
emit gameInProgress(false);
}
void TronWidget::step()
{
if (tron) {
if (tron->step()) {
repaint(rect());
} else {
stop();
repaint(rect());
auto winner = tron->getWinner();
QString winnerString;
QString colorString;
if (winner == tron->getPlayers().end()) {
winnerString = "Tie Game";
colorString = "black";
} else {
winnerString = QString{"%1 won!"}.arg(winner->getName());
colorString = winner->getColor().name();
}
QMessageBox gameOverDialog{QMessageBox::Information, "Game Over", winnerString, QMessageBox::Ok, this};
gameOverDialog.setStyleSheet(QString("color: %1").arg(colorString));
gameOverDialog.exec();
}
}
}
void TronWidget::setPlayerCount(int playerCount)
{
this->playerCount = clamp(playerCount,
Tron::MIN_PLAYER_COUNT,
Tron::MAX_PLAYER_COUNT);
}
void TronWidget::setPlayerName(int player, QString name)
{
this->playerNames[player] = name;
}
auto TronWidget::getPlayerName(int player) const -> QString
{
return this->playerNames[player];
}
void TronWidget::setPlayerColor(int player, QColor color)
{
this->playerColors[player] = color;
}
auto TronWidget::getPlayerColor(int player) const -> QColor
{
return this->playerColors[player];
}
void TronWidget::setMapWidth(int width)
{
this->mapSize.setWidth(clamp(width,
Tron::MIN_MAP_WIDTH,
Tron::MAX_MAP_WIDTH));
}
void TronWidget::setMapHeight(int height)
{
this->mapSize.setHeight(clamp(height,
Tron::MIN_MAP_HEIGHT,
Tron::MAX_MAP_HEIGHT));
}
void TronWidget::resizeMap()
{
if (tron) {
// We need to keep the map on-screen no matter
// how the window is resized, so we choose the
// smallest dimension and divide it evenly.
int tileWidth = rect().width() / tron->getMapSize().width();
int tileHeight = rect().height() / tron->getMapSize().height();
tileSize = std::min(tileWidth, tileHeight);
} else {
tileSize = DEFAULT_TILE_SIZE;
}
}
void TronWidget::resizeEvent(QResizeEvent *)
{
resizeMap();
}
void TronWidget::paintEvent(QPaintEvent *)
{
if (tron) {
QPainter painter{this};
// Paint playing board
painter.setBrush(Qt::black);
painter.setPen(QPen(QBrush(Qt::white), 1));
painter.drawRect(rect().x(), rect().y(),
tron->getMapSize().width()*tileSize,
tron->getMapSize().height()*tileSize);
// Draw each player and its trail
painter.setPen(QPen(QBrush(Qt::white), 1));
for(int i = 0; i < tron->getPlayerCount(); ++i) {
auto player = tron->getPlayer(i);
painter.setBrush(player.getColor());
if (player.getIsPlaying()) {
QPoint p = player.getPosition();
painter.drawRect(p.x() * tileSize, p.y() * tileSize,
tileSize, tileSize);
}
for (QPoint pt : player.getTrail()) {
painter.drawRect(pt.x() * tileSize, pt.y() * tileSize,
tileSize, tileSize);
}
}
}
}
void TronWidget::keyPressEvent(QKeyEvent *event)
{
if (tron) {
if (keybindings.count(event->key()) > 0) {
// This key press is a game control
auto binding = keybindings.at(event->key());
// Check if this binding applies to an active player
if (binding.first < tron->getPlayerCount()) {
// Make the turn
tron->getPlayer(binding.first).turn(binding.second);
}
} else {
// This key press doesn't concern our game directly
// Pass it on to the default Qt implementation
QWidget::keyPressEvent(event);
}
}
}
std::map<int, std::pair<int, Player::Direction>>
TronWidget::keybindings
{
// Player One
{Qt::Key_Up, {0, Player::Direction::Up}},
{Qt::Key_Down, {0, Player::Direction::Down}},
{Qt::Key_Left, {0, Player::Direction::Left}},
{Qt::Key_Right, {0, Player::Direction::Right}},
// Player Two
{Qt::Key_W, {1, Player::Direction::Up}},
{Qt::Key_S, {1, Player::Direction::Down}},
{Qt::Key_A, {1, Player::Direction::Left}},
{Qt::Key_D, {1, Player::Direction::Right}},
// Player Three
{Qt::Key_I, {2, Player::Direction::Up}},
{Qt::Key_K, {2, Player::Direction::Down}},
{Qt::Key_J, {2, Player::Direction::Left}},
{Qt::Key_L, {2, Player::Direction::Right}},
// Player Four
{Qt::Key_T, {3, Player::Direction::Up}},
{Qt::Key_G, {3, Player::Direction::Down}},
{Qt::Key_F, {3, Player::Direction::Left}},
{Qt::Key_H, {3, Player::Direction::Right}},
};
const int TronWidget::DEFAULT_TILE_SIZE{20};
const int TronWidget::DEFAULT_TICK_INTERVAL{80};
<|endoftext|>
|
<commit_before>
#include <tree.hpp>
#include <catch.hpp>
SCENARIO("null")
{
Tree<int> a;
REQUIRE(a.tree_one()==NULL);
}
SCENARIO("find")
{
Tree<int> a;
a.add(5);
bool b=a.find(5);
REQUIRE(b == 1);
}
<commit_msg>Update init.cpp<commit_after>
#include <tree.hpp>
#include <catch.hpp>
SCENARIO("null")
{
Tree<int> a;
REQUIRE(a.tree_one()==NULL);
}
SCENARIO("find")
{
Tree<int> a;
REQUIRE(a.find(0) == 0);
}
<|endoftext|>
|
<commit_before>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
}
<commit_msg>Add testcases for sphere<commit_after>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include <sphere.cpp>
#include <glm/vec3.hpp>
TEST_CASE("get volume of sphere", "[volume]") {
Sphere sphere;
REQUIRE(sphere.volume() == Approx(4.1888));
}
TEST_CASE("get area of sphere", "[area]") {
Sphere sphere;
REQUIRE(sphere.area() == Approx(12.5664));
}
TEST_CASE("get radius of sphere", "[radius]") {
Sphere sphere;
REQUIRE(sphere.radius() == 1);
}
TEST_CASE("get center of sphere", "[center]") {
Sphere sphere;
glm::vec3 tmp{0,0,0};
REQUIRE(sphere.center() == tmp);
}
TEST_CASE("constructors of sphere", "[constructors]") {
Sphere s1;
Sphere s2{{0,0,0},1};
REQUIRE(s1.center() == s2.center());
REQUIRE(s1.radius() == s2.radius());
REQUIRE(s1.area() == s2.area());
REQUIRE(s1.volume() == s2.volume());
}
int main(int argc, char *argv[]) {
return Catch::Session().run(argc, argv);
}
<|endoftext|>
|
<commit_before>
#include <cstdlib>
#include <iostream>
#include "gtest/gtest.h"
#include "gl-batch-context/Context.hpp"
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Small comment regarding PNG library that should be used.<commit_after>
#include <cstdlib>
#include <iostream>
#include "gtest/gtest.h"
#include "gl-batch-context/Context.hpp"
/// \todo Use lodepng to write png files. It's small and we can easily
/// create a CPM external for it.
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>/* This file is part of the Vc library.
Copyright (C) 2009 Matthias Kretz <kretz@kde.org>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Vc/Vc>
#include "unittest.h"
#include <iostream>
#include "vectormemoryhelper.h"
#include <cmath>
using namespace Vc;
template<typename Vec> void testInc()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(i);
data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 1 : 0);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
Vec aa(a);
COMPARE(aa(m)++, a);
COMPARE(aa, b);
COMPARE(++a(m), b);
COMPARE(a, b);
}
}
template<typename Vec> void testDec()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(i + 1);
data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 1 : 0);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
Vec aa(a);
COMPARE(aa(m)--, a);
COMPARE(--a(m), b);
COMPARE(a, b);
COMPARE(aa, b);
}
}
template<typename Vec> void testPlusEq()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(i + 1);
data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
COMPARE(a(m) += static_cast<T>(2), b);
COMPARE(a, b);
}
}
template<typename Vec> void testMinusEq()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(i + 2);
data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 2 : 0);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
COMPARE(a(m) -= static_cast<T>(2), b);
COMPARE(a, b);
}
}
template<typename Vec> void testTimesEq()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(i);
data[i + Vec::Size] = data[i] * static_cast<T>(data[i] < border ? 2 : 1);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
COMPARE(a(m) *= static_cast<T>(2), b);
COMPARE(a, b);
}
}
template<typename Vec> void testDivEq()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(5 * i);
data[i + Vec::Size] = data[i] / static_cast<T>(data[i] < border ? 3 : 1);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
COMPARE(a(m) /= static_cast<T>(3), b);
COMPARE(a, b);
}
}
template<typename Vec> void testAssign()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(i);
data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
COMPARE(a(m) = b, b);
COMPARE(a, b);
}
}
template<typename Vec> void testZero()
{
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
typedef typename Vec::IndexType I;
for (int cut = 0; cut < Vec::Size; ++cut) {
const Mask mask(I(Vc::IndexesFromZero) < cut);
//std::cout << mask << std::endl;
const T aa = 4;
Vec a(aa);
Vec b(Vc::Zero);
b(!mask) = a;
a.makeZero(mask);
COMPARE(a, b);
}
}
template<typename Vec> void testCount()
{
typedef typename Vec::EntryType T;
typedef typename Vec::IndexType I;
typedef typename Vec::Mask M;
for (int cut = 0; cut <= Vec::Size; ++cut) {
const M mask(I(Vc::IndexesFromZero) < cut);
//std::cout << mask << std::endl;
COMPARE(mask.count(), cut);
}
}
template<typename Vec> void testFirstOne()
{
typedef typename Vec::EntryType T;
typedef typename Vec::IndexType I;
typedef typename Vec::Mask M;
for (int i = 0; i < Vec::Size; ++i) {
const M mask(I(Vc::IndexesFromZero) == i);
COMPARE(mask.firstOne(), i);
}
}
int main()
{
runTest(testInc<int_v>);
runTest(testInc<uint_v>);
runTest(testInc<float_v>);
runTest(testInc<double_v>);
runTest(testInc<short_v>);
runTest(testInc<ushort_v>);
runTest(testInc<sfloat_v>);
runTest(testDec<int_v>);
runTest(testDec<uint_v>);
runTest(testDec<float_v>);
runTest(testDec<double_v>);
runTest(testDec<short_v>);
runTest(testDec<ushort_v>);
runTest(testDec<sfloat_v>);
runTest(testPlusEq<int_v>);
runTest(testPlusEq<uint_v>);
runTest(testPlusEq<float_v>);
runTest(testPlusEq<double_v>);
runTest(testPlusEq<short_v>);
runTest(testPlusEq<ushort_v>);
runTest(testPlusEq<sfloat_v>);
runTest(testMinusEq<int_v>);
runTest(testMinusEq<uint_v>);
runTest(testMinusEq<float_v>);
runTest(testMinusEq<double_v>);
runTest(testMinusEq<short_v>);
runTest(testMinusEq<ushort_v>);
runTest(testMinusEq<sfloat_v>);
runTest(testTimesEq<int_v>);
runTest(testTimesEq<uint_v>);
runTest(testTimesEq<float_v>);
runTest(testTimesEq<double_v>);
runTest(testTimesEq<short_v>);
runTest(testTimesEq<ushort_v>);
runTest(testTimesEq<sfloat_v>);
runTest(testDivEq<int_v>);
runTest(testDivEq<uint_v>);
runTest(testDivEq<float_v>);
runTest(testDivEq<double_v>);
runTest(testDivEq<short_v>);
runTest(testDivEq<ushort_v>);
runTest(testDivEq<sfloat_v>);
runTest(testAssign<int_v>);
runTest(testAssign<uint_v>);
runTest(testAssign<float_v>);
runTest(testAssign<double_v>);
runTest(testAssign<short_v>);
runTest(testAssign<ushort_v>);
runTest(testAssign<sfloat_v>);
runTest(testZero<int_v>);
runTest(testZero<uint_v>);
runTest(testZero<float_v>);
runTest(testZero<double_v>);
runTest(testZero<short_v>);
runTest(testZero<ushort_v>);
runTest(testZero<sfloat_v>);
runTest(testCount<int_v>);
runTest(testCount<uint_v>);
runTest(testCount<float_v>);
runTest(testCount<double_v>);
runTest(testCount<short_v>);
runTest(testCount<ushort_v>);
runTest(testCount<sfloat_v>);
runTest(testFirstOne<int_v>);
runTest(testFirstOne<uint_v>);
runTest(testFirstOne<float_v>);
runTest(testFirstOne<double_v>);
runTest(testFirstOne<short_v>);
runTest(testFirstOne<ushort_v>);
runTest(testFirstOne<sfloat_v>);
return 0;
}
<commit_msg>test Float8GatherMask<commit_after>/* This file is part of the Vc library.
Copyright (C) 2009 Matthias Kretz <kretz@kde.org>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Vc/Vc>
#include "unittest.h"
#include <iostream>
#include "vectormemoryhelper.h"
#include <cmath>
using namespace Vc;
template<typename Vec> void testInc()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(i);
data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 1 : 0);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
Vec aa(a);
COMPARE(aa(m)++, a);
COMPARE(aa, b);
COMPARE(++a(m), b);
COMPARE(a, b);
}
}
template<typename Vec> void testDec()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(i + 1);
data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 1 : 0);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
Vec aa(a);
COMPARE(aa(m)--, a);
COMPARE(--a(m), b);
COMPARE(a, b);
COMPARE(aa, b);
}
}
template<typename Vec> void testPlusEq()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(i + 1);
data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
COMPARE(a(m) += static_cast<T>(2), b);
COMPARE(a, b);
}
}
template<typename Vec> void testMinusEq()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(i + 2);
data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 2 : 0);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
COMPARE(a(m) -= static_cast<T>(2), b);
COMPARE(a, b);
}
}
template<typename Vec> void testTimesEq()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(i);
data[i + Vec::Size] = data[i] * static_cast<T>(data[i] < border ? 2 : 1);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
COMPARE(a(m) *= static_cast<T>(2), b);
COMPARE(a, b);
}
}
template<typename Vec> void testDivEq()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(5 * i);
data[i + Vec::Size] = data[i] / static_cast<T>(data[i] < border ? 3 : 1);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
COMPARE(a(m) /= static_cast<T>(3), b);
COMPARE(a, b);
}
}
template<typename Vec> void testAssign()
{
VectorMemoryHelper<Vec> mem(2);
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
T *data = mem;
for (int borderI = 0; borderI < Vec::Size; ++borderI) {
const T border = static_cast<T>(borderI);
for (int i = 0; i < Vec::Size; ++i) {
data[i] = static_cast<T>(i);
data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0);
}
Vec a(&data[0]);
Vec b(&data[Vec::Size]);
Mask m = a < border;
COMPARE(a(m) = b, b);
COMPARE(a, b);
}
}
template<typename Vec> void testZero()
{
typedef typename Vec::EntryType T;
typedef typename Vec::Mask Mask;
typedef typename Vec::IndexType I;
for (int cut = 0; cut < Vec::Size; ++cut) {
const Mask mask(I(Vc::IndexesFromZero) < cut);
//std::cout << mask << std::endl;
const T aa = 4;
Vec a(aa);
Vec b(Vc::Zero);
b(!mask) = a;
a.makeZero(mask);
COMPARE(a, b);
}
}
template<typename Vec> void testCount()
{
typedef typename Vec::EntryType T;
typedef typename Vec::IndexType I;
typedef typename Vec::Mask M;
for (int cut = 0; cut <= Vec::Size; ++cut) {
const M mask(I(Vc::IndexesFromZero) < cut);
//std::cout << mask << std::endl;
COMPARE(mask.count(), cut);
}
}
template<typename Vec> void testFirstOne()
{
typedef typename Vec::EntryType T;
typedef typename Vec::IndexType I;
typedef typename Vec::Mask M;
for (int i = 0; i < Vec::Size; ++i) {
const M mask(I(Vc::IndexesFromZero) == i);
COMPARE(mask.firstOne(), i);
}
}
#ifdef VC_IMPL_SSE
void testFloat8GatherMask()
{
Memory<short_v, short_v::Size * 256> data;
short_v::Memory andMemory;
for (int i = 0; i < short_v::Size; ++i) {
andMemory[i] = 1 << i;
}
const short_v andMask(andMemory);
for (unsigned int i = 0; i < data.vectorsCount(); ++i) {
data.vector(i) = andMask & i;
}
for (unsigned int i = 0; i < data.vectorsCount(); ++i) {
const short_m mask = data.vector(i) == short_v::Zero();
SSE::Float8GatherMask
gatherMaskA(mask),
gatherMaskB(static_cast<sfloat_m>(mask));
COMPARE(gatherMaskA.toInt(), gatherMaskB.toInt());
}
}
#endif
int main()
{
runTest(testInc<int_v>);
runTest(testInc<uint_v>);
runTest(testInc<float_v>);
runTest(testInc<double_v>);
runTest(testInc<short_v>);
runTest(testInc<ushort_v>);
runTest(testInc<sfloat_v>);
runTest(testDec<int_v>);
runTest(testDec<uint_v>);
runTest(testDec<float_v>);
runTest(testDec<double_v>);
runTest(testDec<short_v>);
runTest(testDec<ushort_v>);
runTest(testDec<sfloat_v>);
runTest(testPlusEq<int_v>);
runTest(testPlusEq<uint_v>);
runTest(testPlusEq<float_v>);
runTest(testPlusEq<double_v>);
runTest(testPlusEq<short_v>);
runTest(testPlusEq<ushort_v>);
runTest(testPlusEq<sfloat_v>);
runTest(testMinusEq<int_v>);
runTest(testMinusEq<uint_v>);
runTest(testMinusEq<float_v>);
runTest(testMinusEq<double_v>);
runTest(testMinusEq<short_v>);
runTest(testMinusEq<ushort_v>);
runTest(testMinusEq<sfloat_v>);
runTest(testTimesEq<int_v>);
runTest(testTimesEq<uint_v>);
runTest(testTimesEq<float_v>);
runTest(testTimesEq<double_v>);
runTest(testTimesEq<short_v>);
runTest(testTimesEq<ushort_v>);
runTest(testTimesEq<sfloat_v>);
runTest(testDivEq<int_v>);
runTest(testDivEq<uint_v>);
runTest(testDivEq<float_v>);
runTest(testDivEq<double_v>);
runTest(testDivEq<short_v>);
runTest(testDivEq<ushort_v>);
runTest(testDivEq<sfloat_v>);
runTest(testAssign<int_v>);
runTest(testAssign<uint_v>);
runTest(testAssign<float_v>);
runTest(testAssign<double_v>);
runTest(testAssign<short_v>);
runTest(testAssign<ushort_v>);
runTest(testAssign<sfloat_v>);
runTest(testZero<int_v>);
runTest(testZero<uint_v>);
runTest(testZero<float_v>);
runTest(testZero<double_v>);
runTest(testZero<short_v>);
runTest(testZero<ushort_v>);
runTest(testZero<sfloat_v>);
runTest(testCount<int_v>);
runTest(testCount<uint_v>);
runTest(testCount<float_v>);
runTest(testCount<double_v>);
runTest(testCount<short_v>);
runTest(testCount<ushort_v>);
runTest(testCount<sfloat_v>);
runTest(testFirstOne<int_v>);
runTest(testFirstOne<uint_v>);
runTest(testFirstOne<float_v>);
runTest(testFirstOne<double_v>);
runTest(testFirstOne<short_v>);
runTest(testFirstOne<ushort_v>);
runTest(testFirstOne<sfloat_v>);
#ifdef VC_IMPL_SSE
runTest(testFloat8GatherMask);
#endif
return 0;
}
<|endoftext|>
|
<commit_before>/*
* SimpleClusterView.cpp
*
* Copyright (C) 2010 by VISUS (Universitaet Stuttgart).
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "cluster/SimpleClusterView.h"
#include "cluster/SimpleClusterClientViewRegistration.h"
#include "cluster/SimpleClusterClient.h"
#include "cluster/SimpleClusterCommUtil.h"
#include "param/IntParam.h"
#include "param/StringParam.h"
#include "AbstractNamedObject.h"
#include "CoreInstance.h"
#include <GL/gl.h>
#include "vislib/assert.h"
#include "vislib/DNS.h"
#include "vislib/IPHostEntry.h"
#include "vislib/NetworkInformation.h"
#include "vislib/Thread.h"
#include <climits>
using namespace megamol::core;
/*
* cluster::SimpleClusterView::SimpleClusterView
*/
cluster::SimpleClusterView::SimpleClusterView(void) : view::AbstractTileView(),
firstFrame(false), frozen(false), frozenTime(0.0), frozenCam(NULL),
registerSlot("register", "The slot registering this view"), client(NULL), initMsg(NULL),
heartBeatPortSlot("heartbeat::port", "The port the heartbeat server communicates on"),
heartBeatServerSlot("heartbeat::server", "The machine the heartbeat server runs on") {
this->registerSlot.SetCompatibleCall<SimpleClusterClientViewRegistrationDescription>();
this->MakeSlotAvailable(&this->registerSlot);
this->heartBeatPortSlot << new param::IntParam(0, 0, USHRT_MAX);
this->MakeSlotAvailable(&this->heartBeatPortSlot);
this->heartBeatServerSlot << new param::StringParam("");
this->MakeSlotAvailable(&this->heartBeatServerSlot);
this->heartBeatServerSlot.ForceSetDirty();
}
/*
* cluster::SimpleClusterView::~SimpleClusterView
*/
cluster::SimpleClusterView::~SimpleClusterView(void) {
this->Release();
this->frozenCam = NULL; // DO NOT DELETE
ASSERT(this->client == NULL);
}
namespace intern {
/**
* Selects adapters which match this predicate
*/
bool iamSelectAdapterCallback(const vislib::net::NetworkInformation::Adapter& adapter, void *userContext) {
vislib::net::TIPHostEntry *he = static_cast<vislib::net::TIPHostEntry*>(userContext);
vislib::Array<vislib::net::IPAgnosticAddress> a1 = he->GetAddresses();
vislib::net::NetworkInformation::UnicastAddressList a2 = adapter.GetUnicastAddresses();
for (SIZE_T i2 = 0; i2 < a2.Count(); i2++) {
if (a1.Contains(a2[i2].GetAddress())) {
return true;
}
}
return false;
}
}
/*
* cluster::SimpleClusterView::Render
*/
void cluster::SimpleClusterView::Render(float time, double instTime) {
if (this->firstFrame) {
this->firstFrame = false;
this->initTileViewParameters();
AbstractNamedObject *ano = this;
while (ano != NULL) {
if (this->loadConfiguration(ano->Name())) break;
ano = ano->Parent();
}
if (this->GetCoreInstance()->Configuration().IsConfigValueSet("scv-heartbeat-port")) {
try {
this->heartBeatPortSlot.Param<param::IntParam>()->SetValue(
vislib::CharTraitsW::ParseInt(
this->GetCoreInstance()->Configuration().ConfigValue("scv-heartbeat-port")));
} catch(vislib::Exception e) {
vislib::sys::Log::DefaultLog.WriteError(
"Failed to load heartbeat port configuration: %s [%s, %d]\n",
e.GetMsgA(), e.GetFile(), e.GetLine());
} catch(...) {
vislib::sys::Log::DefaultLog.WriteError(
"Failed to load heartbeat port configuration: Unknown exception\n");
}
}
if (this->GetCoreInstance()->Configuration().IsConfigValueSet("scv-heartbeat-server")) {
this->heartBeatServerSlot.Param<param::StringParam>()->SetValue(
this->GetCoreInstance()->Configuration().ConfigValue("scv-heartbeat-server"));
}
}
if (this->initMsg != NULL) {
if (this->initMsg->GetHeader().GetMessageID() == MSG_MODULGRAPH) {
this->GetCoreInstance()->SetupGraphFromNetwork(this->initMsg);
this->client->ContinueSetup();
} else if (this->initMsg->GetHeader().GetMessageID() == MSG_CAMERAUPDATE) {
this->client->ContinueSetup(2);
}
SAFE_DELETE(this->initMsg);
}
if (this->client == NULL) {
SimpleClusterClientViewRegistration *sccvr
= this->registerSlot.CallAs<SimpleClusterClientViewRegistration>();
if (sccvr != NULL) {
sccvr->SetView(this);
if ((*sccvr)()) {
this->client = sccvr->GetClient();
}
}
}
if (this->heartBeatPortSlot.IsDirty() || this->heartBeatServerSlot.IsDirty()) {
try {
vislib::net::TIPHostEntry he;
vislib::net::DNS::GetHostEntry(he, this->heartBeatServerSlot.Param<param::StringParam>()->Value());
vislib::net::NetworkInformation::AdapterList adapters;
vislib::net::NetworkInformation::GetAdaptersForPredicate(adapters,
intern::iamSelectAdapterCallback,
static_cast<void*>(&he));
if (!adapters.IsEmpty()) {
// TODO: Implement Server
}
// TODO: Implement Client
} catch(vislib::Exception e) {
vislib::sys::Log::DefaultLog.WriteError(
"Failed to configure heartbeat: %s [%s, %d]\n",
e.GetMsgA(), e.GetFile(), e.GetLine());
} catch(...) {
vislib::sys::Log::DefaultLog.WriteError(
"Failed to configure heartbeat: Unknown exception\n");
}
}
view::CallRenderView *crv = this->getCallRenderView();
this->checkParameters();
if (!this->frozen) {
this->frozenTime = instTime;
}
if (crv != NULL) {
crv->ResetAll();
crv->SetTime(time);
crv->SetInstanceTime(instTime);
crv->SetProjection(this->getProjType(), this->getEye());
if ((this->getVirtWidth() != 0) && (this->getVirtHeight() != 0)
&& (this->getTileW() != 0) && (this->getTileH() != 0)) {
crv->SetTile(this->getVirtWidth(), this->getVirtHeight(),
this->getTileX(), this->getTileY(), this->getTileW(), this->getTileH());
}
crv->SetOutputBuffer(GL_BACK, this->getViewportWidth(), this->getViewportHeight());
//if ((this->netVSyncBarrier != NULL) && (this->netVSyncBarrier->GetDataSize() > 0)) {
// //printf("Barrier with %u bytes data\n", this->netVSyncBarrier->GetDataSize());
// vislib::RawStorageSerialiser camera(
// this->netVSyncBarrier->GetData() + 4,
// this->netVSyncBarrier->GetDataSize() - 4);
//}
view::AbstractView *view = NULL;
if (crv->PeekCalleeSlot() != NULL) view = dynamic_cast<view::AbstractView*>(
const_cast<AbstractNamedObject*>(crv->PeekCalleeSlot()->Parent()));
if (view != NULL){
if (this->frozenCam != NULL) view->DeserialiseCamera(*this->frozenCam);
/* this forces to use this time */
//view->SetFrameTime(static_cast<float>(this->frozenTime));
}
if (!(*crv)(view::CallRenderView::CALL_RENDER)) {
this->renderFallbackView();
}
} else {
this->renderFallbackView();
}
::glFlush();
}
/*
* cluster::SimpleClusterView::Unregister
*/
void cluster::SimpleClusterView::Unregister(cluster::SimpleClusterClient *client) {
if (this->client == client) {
if (this->client != NULL) {
this->client->Unregister(this);
}
this->client = NULL;
}
}
/*
* cluster::SimpleClusterView::DisconnectViewCall
*/
void cluster::SimpleClusterView::DisconnectViewCall(void) {
this->disconnectOutgoingRenderCall();
}
/*
* cluster::SimpleClusterView::SetSetupMessage
*/
void cluster::SimpleClusterView::SetSetupMessage(const vislib::net::AbstractSimpleMessage& msg) {
if (this->initMsg != NULL) {
SAFE_DELETE(this->initMsg);
}
this->initMsg = new vislib::net::SimpleMessage(msg);
}
/*
* cluster::SimpleClusterView::SetCamIniMessage
*/
void cluster::SimpleClusterView::SetCamIniMessage(void) {
if (this->initMsg != NULL) {
SAFE_DELETE(this->initMsg);
}
vislib::net::SimpleMessage *m = new vislib::net::SimpleMessage();
m->GetHeader().SetMessageID(MSG_CAMERAUPDATE);
this->initMsg = m;
}
/*
* cluster::SimpleClusterView::ConnectView
*/
void cluster::SimpleClusterView::ConnectView(const vislib::StringA toName) {
this->GetCoreInstance()->InstantiateCall(this->FullName() + "::renderView", toName,
CallDescriptionManager::Instance()->Find("CallRenderView"));
}
/*
* cluster::SimpleClusterView::create
*/
bool cluster::SimpleClusterView::create(void) {
this->firstFrame = true;
return true;
}
/*
* cluster::SimpleClusterView::release
*/
void cluster::SimpleClusterView::release(void) {
this->frozenCam = NULL; // DO NOT DELETE
if (this->client != NULL) {
this->client->Unregister(this);
this->client = NULL;
}
if (this->initMsg != NULL) {
SAFE_DELETE(this->initMsg);
}
}
/*
* cluster::SimpleClusterView::renderFallbackView
*/
void cluster::SimpleClusterView::renderFallbackView(void) {
::glClearColor(0.1f, 0.1f, 0.2f, 1.0f);
::glClear(GL_COLOR_BUFFER_BIT);
::glMatrixMode(GL_PROJECTION);
::glLoadIdentity();
::glMatrixMode(GL_MODELVIEW);
::glLoadIdentity();
::glRotated(this->frozenTime * 36.0, 0.0, 0.0, 1.0);
::glColor3ub(200, 200, 255);
::glBegin(GL_LINES);
::glVertex2i(0, 0);
::glVertex2i(1, 0);
::glEnd();
}
/*
* cluster::SimpleClusterView::UpdateFreeze
*/
void cluster::SimpleClusterView::UpdateFreeze(bool freeze) {
this->frozen = freeze;
this->frozenTime = this->instance()->GetCoreInstanceTime(); // HAZARD
}
/*
* cluster::SimpleClusterView::loadConfiguration
*/
bool cluster::SimpleClusterView::loadConfiguration(const vislib::StringA& name) {
vislib::StringA vname(name);
vname.Append("-tvtile");
if (this->instance()->Configuration().IsConfigValueSet(vname)) {
return this->setTile(this->instance()->Configuration().ConfigValue(vname));
}
return false;
}
<commit_msg>Resetting dirty flag for heart beat settings (removed unused code)<commit_after>/*
* SimpleClusterView.cpp
*
* Copyright (C) 2010 by VISUS (Universitaet Stuttgart).
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "cluster/SimpleClusterView.h"
#include "cluster/SimpleClusterClientViewRegistration.h"
#include "cluster/SimpleClusterClient.h"
#include "cluster/SimpleClusterCommUtil.h"
#include "param/IntParam.h"
#include "param/StringParam.h"
#include "AbstractNamedObject.h"
#include "CoreInstance.h"
#include <GL/gl.h>
#include "vislib/assert.h"
#include "vislib/DNS.h"
#include "vislib/IPHostEntry.h"
#include "vislib/NetworkInformation.h"
#include "vislib/Thread.h"
#include <climits>
using namespace megamol::core;
/*
* cluster::SimpleClusterView::SimpleClusterView
*/
cluster::SimpleClusterView::SimpleClusterView(void) : view::AbstractTileView(),
firstFrame(false), frozen(false), frozenTime(0.0), frozenCam(NULL),
registerSlot("register", "The slot registering this view"), client(NULL), initMsg(NULL),
heartBeatPortSlot("heartbeat::port", "The port the heartbeat server communicates on"),
heartBeatServerSlot("heartbeat::server", "The machine the heartbeat server runs on") {
this->registerSlot.SetCompatibleCall<SimpleClusterClientViewRegistrationDescription>();
this->MakeSlotAvailable(&this->registerSlot);
this->heartBeatPortSlot << new param::IntParam(0, 0, USHRT_MAX);
this->MakeSlotAvailable(&this->heartBeatPortSlot);
this->heartBeatServerSlot << new param::StringParam("");
this->MakeSlotAvailable(&this->heartBeatServerSlot);
this->heartBeatServerSlot.ForceSetDirty();
}
/*
* cluster::SimpleClusterView::~SimpleClusterView
*/
cluster::SimpleClusterView::~SimpleClusterView(void) {
this->Release();
this->frozenCam = NULL; // DO NOT DELETE
ASSERT(this->client == NULL);
}
namespace intern {
/**
* Selects adapters which match this predicate
*/
bool iamSelectAdapterCallback(const vislib::net::NetworkInformation::Adapter& adapter, void *userContext) {
vislib::net::TIPHostEntry *he = static_cast<vislib::net::TIPHostEntry*>(userContext);
vislib::Array<vislib::net::IPAgnosticAddress> a1 = he->GetAddresses();
vislib::net::NetworkInformation::UnicastAddressList a2 = adapter.GetUnicastAddresses();
for (SIZE_T i2 = 0; i2 < a2.Count(); i2++) {
if (a1.Contains(a2[i2].GetAddress())) {
return true;
}
}
return false;
}
}
/*
* cluster::SimpleClusterView::Render
*/
void cluster::SimpleClusterView::Render(float time, double instTime) {
if (this->firstFrame) {
this->firstFrame = false;
this->initTileViewParameters();
AbstractNamedObject *ano = this;
while (ano != NULL) {
if (this->loadConfiguration(ano->Name())) break;
ano = ano->Parent();
}
if (this->GetCoreInstance()->Configuration().IsConfigValueSet("scv-heartbeat-port")) {
try {
this->heartBeatPortSlot.Param<param::IntParam>()->SetValue(
vislib::CharTraitsW::ParseInt(
this->GetCoreInstance()->Configuration().ConfigValue("scv-heartbeat-port")));
} catch(vislib::Exception e) {
vislib::sys::Log::DefaultLog.WriteError(
"Failed to load heartbeat port configuration: %s [%s, %d]\n",
e.GetMsgA(), e.GetFile(), e.GetLine());
} catch(...) {
vislib::sys::Log::DefaultLog.WriteError(
"Failed to load heartbeat port configuration: Unknown exception\n");
}
}
if (this->GetCoreInstance()->Configuration().IsConfigValueSet("scv-heartbeat-server")) {
this->heartBeatServerSlot.Param<param::StringParam>()->SetValue(
this->GetCoreInstance()->Configuration().ConfigValue("scv-heartbeat-server"));
}
}
if (this->initMsg != NULL) {
if (this->initMsg->GetHeader().GetMessageID() == MSG_MODULGRAPH) {
this->GetCoreInstance()->SetupGraphFromNetwork(this->initMsg);
this->client->ContinueSetup();
} else if (this->initMsg->GetHeader().GetMessageID() == MSG_CAMERAUPDATE) {
this->client->ContinueSetup(2);
}
SAFE_DELETE(this->initMsg);
}
if (this->client == NULL) {
SimpleClusterClientViewRegistration *sccvr
= this->registerSlot.CallAs<SimpleClusterClientViewRegistration>();
if (sccvr != NULL) {
sccvr->SetView(this);
if ((*sccvr)()) {
this->client = sccvr->GetClient();
}
}
}
if (this->heartBeatPortSlot.IsDirty() || this->heartBeatServerSlot.IsDirty()) {
this->heartBeatPortSlot.ResetDirty();
this->heartBeatServerSlot.ResetDirty();
try {
//vislib::net::TIPHostEntry he;
//vislib::net::DNS::GetHostEntry(he, this->heartBeatServerSlot.Param<param::StringParam>()->Value());
//vislib::net::NetworkInformation::AdapterList adapters;
//vislib::net::NetworkInformation::GetAdaptersForPredicate(adapters,
// intern::iamSelectAdapterCallback,
// static_cast<void*>(&he));
//if (!adapters.IsEmpty()) {
// // TODO: Implement Server
//}
//// TODO: Implement Client
} catch(vislib::Exception e) {
vislib::sys::Log::DefaultLog.WriteError(
"Failed to configure heartbeat: %s [%s, %d]\n",
e.GetMsgA(), e.GetFile(), e.GetLine());
} catch(...) {
vislib::sys::Log::DefaultLog.WriteError(
"Failed to configure heartbeat: Unknown exception\n");
}
}
view::CallRenderView *crv = this->getCallRenderView();
this->checkParameters();
if (!this->frozen) {
this->frozenTime = instTime;
}
if (crv != NULL) {
crv->ResetAll();
crv->SetTime(time);
crv->SetInstanceTime(instTime);
crv->SetProjection(this->getProjType(), this->getEye());
if ((this->getVirtWidth() != 0) && (this->getVirtHeight() != 0)
&& (this->getTileW() != 0) && (this->getTileH() != 0)) {
crv->SetTile(this->getVirtWidth(), this->getVirtHeight(),
this->getTileX(), this->getTileY(), this->getTileW(), this->getTileH());
}
crv->SetOutputBuffer(GL_BACK, this->getViewportWidth(), this->getViewportHeight());
//if ((this->netVSyncBarrier != NULL) && (this->netVSyncBarrier->GetDataSize() > 0)) {
// //printf("Barrier with %u bytes data\n", this->netVSyncBarrier->GetDataSize());
// vislib::RawStorageSerialiser camera(
// this->netVSyncBarrier->GetData() + 4,
// this->netVSyncBarrier->GetDataSize() - 4);
//}
view::AbstractView *view = NULL;
if (crv->PeekCalleeSlot() != NULL) view = dynamic_cast<view::AbstractView*>(
const_cast<AbstractNamedObject*>(crv->PeekCalleeSlot()->Parent()));
if (view != NULL){
if (this->frozenCam != NULL) view->DeserialiseCamera(*this->frozenCam);
/* this forces to use this time */
//view->SetFrameTime(static_cast<float>(this->frozenTime));
}
if (!(*crv)(view::CallRenderView::CALL_RENDER)) {
this->renderFallbackView();
}
} else {
this->renderFallbackView();
}
::glFlush();
}
/*
* cluster::SimpleClusterView::Unregister
*/
void cluster::SimpleClusterView::Unregister(cluster::SimpleClusterClient *client) {
if (this->client == client) {
if (this->client != NULL) {
this->client->Unregister(this);
}
this->client = NULL;
}
}
/*
* cluster::SimpleClusterView::DisconnectViewCall
*/
void cluster::SimpleClusterView::DisconnectViewCall(void) {
this->disconnectOutgoingRenderCall();
}
/*
* cluster::SimpleClusterView::SetSetupMessage
*/
void cluster::SimpleClusterView::SetSetupMessage(const vislib::net::AbstractSimpleMessage& msg) {
if (this->initMsg != NULL) {
SAFE_DELETE(this->initMsg);
}
this->initMsg = new vislib::net::SimpleMessage(msg);
}
/*
* cluster::SimpleClusterView::SetCamIniMessage
*/
void cluster::SimpleClusterView::SetCamIniMessage(void) {
if (this->initMsg != NULL) {
SAFE_DELETE(this->initMsg);
}
vislib::net::SimpleMessage *m = new vislib::net::SimpleMessage();
m->GetHeader().SetMessageID(MSG_CAMERAUPDATE);
this->initMsg = m;
}
/*
* cluster::SimpleClusterView::ConnectView
*/
void cluster::SimpleClusterView::ConnectView(const vislib::StringA toName) {
this->GetCoreInstance()->InstantiateCall(this->FullName() + "::renderView", toName,
CallDescriptionManager::Instance()->Find("CallRenderView"));
}
/*
* cluster::SimpleClusterView::create
*/
bool cluster::SimpleClusterView::create(void) {
this->firstFrame = true;
return true;
}
/*
* cluster::SimpleClusterView::release
*/
void cluster::SimpleClusterView::release(void) {
this->frozenCam = NULL; // DO NOT DELETE
if (this->client != NULL) {
this->client->Unregister(this);
this->client = NULL;
}
if (this->initMsg != NULL) {
SAFE_DELETE(this->initMsg);
}
}
/*
* cluster::SimpleClusterView::renderFallbackView
*/
void cluster::SimpleClusterView::renderFallbackView(void) {
::glClearColor(0.1f, 0.1f, 0.2f, 1.0f);
::glClear(GL_COLOR_BUFFER_BIT);
::glMatrixMode(GL_PROJECTION);
::glLoadIdentity();
::glMatrixMode(GL_MODELVIEW);
::glLoadIdentity();
::glRotated(this->frozenTime * 36.0, 0.0, 0.0, 1.0);
::glColor3ub(200, 200, 255);
::glBegin(GL_LINES);
::glVertex2i(0, 0);
::glVertex2i(1, 0);
::glEnd();
}
/*
* cluster::SimpleClusterView::UpdateFreeze
*/
void cluster::SimpleClusterView::UpdateFreeze(bool freeze) {
this->frozen = freeze;
this->frozenTime = this->instance()->GetCoreInstanceTime(); // HAZARD
}
/*
* cluster::SimpleClusterView::loadConfiguration
*/
bool cluster::SimpleClusterView::loadConfiguration(const vislib::StringA& name) {
vislib::StringA vname(name);
vname.Append("-tvtile");
if (this->instance()->Configuration().IsConfigValueSet(vname)) {
return this->setTile(this->instance()->Configuration().ConfigValue(vname));
}
return false;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2007 Apple Inc.
* Copyright (C) 2007 Alp Toker <alp@atoker.com>
* Copyright (C) 2008 Collabora Ltd.
* Copyright (C) 2008, 2009 Google Inc.
* Copyright (C) 2009 Kenneth Rohde Christiansen
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "core/layout/LayoutThemeDefault.h"
#include "core/CSSValueKeywords.h"
#include "core/layout/LayoutObject.h"
#include "core/layout/LayoutProgress.h"
#include "core/layout/LayoutThemeFontProvider.h"
#include "core/paint/MediaControlsPainter.h"
#include "platform/LayoutTestSupport.h"
#include "platform/PlatformResourceLoader.h"
#include "platform/graphics/Color.h"
#include "platform/scroll/ScrollbarTheme.h"
#include "public/platform/Platform.h"
#include "public/platform/WebThemeEngine.h"
namespace blink {
enum PaddingType {
TopPadding,
RightPadding,
BottomPadding,
LeftPadding
};
static const int styledMenuListInternalPadding[4] = { 1, 4, 1, 4 };
// These values all match Safari/Win.
static const float defaultControlFontPixelSize = 13;
static const float defaultCancelButtonSize = 9;
static const float minCancelButtonSize = 5;
static const float maxCancelButtonSize = 21;
static const float defaultSearchFieldResultsDecorationSize = 13;
static const float minSearchFieldResultsDecorationSize = 9;
static const float maxSearchFieldResultsDecorationSize = 30;
static bool useMockTheme()
{
return LayoutTestSupport::isRunningLayoutTest();
}
unsigned LayoutThemeDefault::m_activeSelectionBackgroundColor = 0xff1e90ff;
unsigned LayoutThemeDefault::m_activeSelectionForegroundColor = Color::black;
unsigned LayoutThemeDefault::m_inactiveSelectionBackgroundColor = 0xffc8c8c8;
unsigned LayoutThemeDefault::m_inactiveSelectionForegroundColor = 0xff323232;
double LayoutThemeDefault::m_caretBlinkInterval;
LayoutThemeDefault::LayoutThemeDefault()
{
m_caretBlinkInterval = LayoutTheme::caretBlinkInterval();
}
LayoutThemeDefault::~LayoutThemeDefault()
{
}
bool LayoutThemeDefault::supportsFocusRing(const ComputedStyle& style) const
{
if (useMockTheme()) {
// Don't use focus rings for buttons when mocking controls.
return style.appearance() == ButtonPart
|| style.appearance() == PushButtonPart
|| style.appearance() == SquareButtonPart;
}
// This causes Blink to draw the focus rings for us.
return false;
}
Color LayoutThemeDefault::systemColor(CSSValueID cssValueId) const
{
static const Color defaultButtonGrayColor(0xffdddddd);
static const Color defaultMenuColor(0xfff7f7f7);
if (cssValueId == CSSValueButtonface) {
if (useMockTheme())
return Color(0xc0, 0xc0, 0xc0);
return defaultButtonGrayColor;
}
if (cssValueId == CSSValueMenu)
return defaultMenuColor;
return LayoutTheme::systemColor(cssValueId);
}
// Use the Windows style sheets to match their metrics.
String LayoutThemeDefault::extraDefaultStyleSheet()
{
return LayoutTheme::extraDefaultStyleSheet()
+ loadResourceAsASCIIString("themeWin.css")
+ loadResourceAsASCIIString("themeChromiumSkia.css")
#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
+ loadResourceAsASCIIString("themeInputMultipleFields.css")
#endif
+ loadResourceAsASCIIString("themeChromium.css");
}
String LayoutThemeDefault::extraQuirksStyleSheet()
{
return loadResourceAsASCIIString("themeWinQuirks.css");
}
Color LayoutThemeDefault::activeListBoxSelectionBackgroundColor() const
{
return Color(0x28, 0x28, 0x28);
}
Color LayoutThemeDefault::activeListBoxSelectionForegroundColor() const
{
return Color::black;
}
Color LayoutThemeDefault::inactiveListBoxSelectionBackgroundColor() const
{
return Color(0xc8, 0xc8, 0xc8);
}
Color LayoutThemeDefault::inactiveListBoxSelectionForegroundColor() const
{
return Color(0x32, 0x32, 0x32);
}
Color LayoutThemeDefault::platformActiveSelectionBackgroundColor() const
{
if (useMockTheme())
return Color(0x00, 0x00, 0xff); // Royal blue.
return m_activeSelectionBackgroundColor;
}
Color LayoutThemeDefault::platformInactiveSelectionBackgroundColor() const
{
if (useMockTheme())
return Color(0x99, 0x99, 0x99); // Medium gray.
return m_inactiveSelectionBackgroundColor;
}
Color LayoutThemeDefault::platformActiveSelectionForegroundColor() const
{
if (useMockTheme())
return Color(0xff, 0xff, 0xcc); // Pale yellow.
return m_activeSelectionForegroundColor;
}
Color LayoutThemeDefault::platformInactiveSelectionForegroundColor() const
{
if (useMockTheme())
return Color::white;
return m_inactiveSelectionForegroundColor;
}
IntSize LayoutThemeDefault::sliderTickSize() const
{
if (useMockTheme())
return IntSize(1, 3);
return IntSize(1, 6);
}
int LayoutThemeDefault::sliderTickOffsetFromTrackCenter() const
{
if (useMockTheme())
return 11;
return -16;
}
void LayoutThemeDefault::adjustSliderThumbSize(ComputedStyle& style, Element* element) const
{
IntSize size = Platform::current()->themeEngine()->getSize(WebThemeEngine::PartSliderThumb);
// FIXME: Mock theme doesn't handle zoomed sliders.
float zoomLevel = useMockTheme() ? 1 : style.effectiveZoom();
if (style.appearance() == SliderThumbHorizontalPart) {
style.setWidth(Length(size.width() * zoomLevel, Fixed));
style.setHeight(Length(size.height() * zoomLevel, Fixed));
} else if (style.appearance() == SliderThumbVerticalPart) {
style.setWidth(Length(size.height() * zoomLevel, Fixed));
style.setHeight(Length(size.width() * zoomLevel, Fixed));
} else {
MediaControlsPainter::adjustMediaSliderThumbSize(style);
}
}
void LayoutThemeDefault::setCaretBlinkInterval(double interval)
{
m_caretBlinkInterval = interval;
}
void LayoutThemeDefault::setSelectionColors(
unsigned activeBackgroundColor,
unsigned activeForegroundColor,
unsigned inactiveBackgroundColor,
unsigned inactiveForegroundColor)
{
m_activeSelectionBackgroundColor = activeBackgroundColor;
m_activeSelectionForegroundColor = activeForegroundColor;
m_inactiveSelectionBackgroundColor = inactiveBackgroundColor;
m_inactiveSelectionForegroundColor = inactiveForegroundColor;
}
void LayoutThemeDefault::setCheckboxSize(ComputedStyle& style) const
{
// If the width and height are both specified, then we have nothing to do.
if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
return;
IntSize size = Platform::current()->themeEngine()->getSize(WebThemeEngine::PartCheckbox);
float zoomLevel = style.effectiveZoom();
size.setWidth(size.width() * zoomLevel);
size.setHeight(size.height() * zoomLevel);
setSizeIfAuto(style, size);
}
void LayoutThemeDefault::setRadioSize(ComputedStyle& style) const
{
// If the width and height are both specified, then we have nothing to do.
if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
return;
IntSize size = Platform::current()->themeEngine()->getSize(WebThemeEngine::PartRadio);
float zoomLevel = style.effectiveZoom();
size.setWidth(size.width() * zoomLevel);
size.setHeight(size.height() * zoomLevel);
setSizeIfAuto(style, size);
}
void LayoutThemeDefault::adjustInnerSpinButtonStyle(ComputedStyle& style, Element*) const
{
IntSize size = Platform::current()->themeEngine()->getSize(WebThemeEngine::PartInnerSpinButton);
style.setWidth(Length(size.width(), Fixed));
style.setMinWidth(Length(size.width(), Fixed));
}
bool LayoutThemeDefault::shouldOpenPickerWithF4Key() const
{
return true;
}
bool LayoutThemeDefault::shouldUseFallbackTheme(const ComputedStyle& style) const
{
if (useMockTheme()) {
// The mock theme can't handle zoomed controls, so we fall back to the "fallback" theme.
ControlPart part = style.appearance();
if (part == CheckboxPart || part == RadioPart)
return style.effectiveZoom() != 1;
}
return LayoutTheme::shouldUseFallbackTheme(style);
}
bool LayoutThemeDefault::supportsHover(const ComputedStyle& style) const
{
return true;
}
Color LayoutThemeDefault::platformFocusRingColor() const
{
static Color focusRingColor(229, 151, 0, 255);
return focusRingColor;
}
double LayoutThemeDefault::caretBlinkInterval() const
{
// Disable the blinking caret in layout test mode, as it introduces
// a race condition for the pixel tests. http://b/1198440
if (LayoutTestSupport::isRunningLayoutTest())
return 0;
return m_caretBlinkInterval;
}
void LayoutThemeDefault::systemFont(CSSValueID systemFontID, FontStyle& fontStyle, FontWeight& fontWeight, float& fontSize, AtomicString& fontFamily) const
{
LayoutThemeFontProvider::systemFont(systemFontID, fontStyle, fontWeight, fontSize, fontFamily);
}
int LayoutThemeDefault::minimumMenuListSize(const ComputedStyle& style) const
{
return 0;
}
// Return a rectangle that has the same center point as |original|, but with a
// size capped at |width| by |height|.
IntRect center(const IntRect& original, int width, int height)
{
width = std::min(original.width(), width);
height = std::min(original.height(), height);
int x = original.x() + (original.width() - width) / 2;
int y = original.y() + (original.height() - height) / 2;
return IntRect(x, y, width, height);
}
void LayoutThemeDefault::adjustButtonStyle(ComputedStyle& style, Element*) const
{
if (style.appearance() == PushButtonPart) {
// Ignore line-height.
style.setLineHeight(ComputedStyle::initialLineHeight());
}
}
void LayoutThemeDefault::adjustSearchFieldStyle(ComputedStyle& style, Element*) const
{
// Ignore line-height.
style.setLineHeight(ComputedStyle::initialLineHeight());
}
void LayoutThemeDefault::adjustSearchFieldCancelButtonStyle(ComputedStyle& style, Element*) const
{
// Scale the button size based on the font size
float fontScale = style.fontSize() / defaultControlFontPixelSize;
int cancelButtonSize = lroundf(std::min(std::max(minCancelButtonSize, defaultCancelButtonSize * fontScale), maxCancelButtonSize));
style.setWidth(Length(cancelButtonSize, Fixed));
style.setHeight(Length(cancelButtonSize, Fixed));
}
void LayoutThemeDefault::adjustSearchFieldDecorationStyle(ComputedStyle& style, Element*) const
{
IntSize emptySize(1, 11);
style.setWidth(Length(emptySize.width(), Fixed));
style.setHeight(Length(emptySize.height(), Fixed));
}
void LayoutThemeDefault::adjustSearchFieldResultsDecorationStyle(ComputedStyle& style, Element*) const
{
// Scale the decoration size based on the font size
float fontScale = style.fontSize() / defaultControlFontPixelSize;
int magnifierSize = lroundf(std::min(std::max(minSearchFieldResultsDecorationSize, defaultSearchFieldResultsDecorationSize * fontScale),
maxSearchFieldResultsDecorationSize));
style.setWidth(Length(magnifierSize, Fixed));
style.setHeight(Length(magnifierSize, Fixed));
}
void LayoutThemeDefault::adjustMenuListStyle(ComputedStyle& style, Element*) const
{
// Height is locked to auto on all browsers.
style.setLineHeight(ComputedStyle::initialLineHeight());
}
void LayoutThemeDefault::adjustMenuListButtonStyle(ComputedStyle& style, Element* e) const
{
adjustMenuListStyle(style, e);
}
int LayoutThemeDefault::popupInternalPaddingLeft(const ComputedStyle& style) const
{
return menuListInternalPadding(style, LeftPadding);
}
int LayoutThemeDefault::popupInternalPaddingRight(const ComputedStyle& style) const
{
return menuListInternalPadding(style, RightPadding);
}
int LayoutThemeDefault::popupInternalPaddingTop(const ComputedStyle& style) const
{
return menuListInternalPadding(style, TopPadding);
}
int LayoutThemeDefault::popupInternalPaddingBottom(const ComputedStyle& style) const
{
return menuListInternalPadding(style, BottomPadding);
}
// static
void LayoutThemeDefault::setDefaultFontSize(int fontSize)
{
LayoutThemeFontProvider::setDefaultFontSize(fontSize);
}
int LayoutThemeDefault::menuListArrowPadding() const
{
return ScrollbarTheme::theme()->scrollbarThickness();
}
int LayoutThemeDefault::menuListInternalPadding(const ComputedStyle& style, int paddingType) const
{
// This internal padding is in addition to the user-supplied padding.
// Matches the FF behavior.
int padding = styledMenuListInternalPadding[paddingType];
// Reserve the space for right arrow here. The rest of the padding is
// set by adjustMenuListStyle, since PopMenuWin.cpp uses the padding from
// LayoutMenuList to lay out the individual items in the popup.
// If the MenuList actually has appearance "NoAppearance", then that means
// we don't draw a button, so don't reserve space for it.
const int barType = style.direction() == LTR ? RightPadding : LeftPadding;
if (paddingType == barType && style.appearance() != NoControlPart)
padding += menuListArrowPadding();
return padding;
}
bool LayoutThemeDefault::shouldShowPlaceholderWhenFocused() const
{
return true;
}
//
// Following values are come from default of GTK+
//
static const int progressAnimationFrames = 10;
static const double progressAnimationInterval = 0.125;
double LayoutThemeDefault::animationRepeatIntervalForProgressBar() const
{
return progressAnimationInterval;
}
double LayoutThemeDefault::animationDurationForProgressBar() const
{
return progressAnimationInterval * progressAnimationFrames * 2; // "2" for back and forth
}
} // namespace blink
<commit_msg>* 改动下拉框hover态颜色,以前的黑字比较难辨认<commit_after>/*
* Copyright (C) 2007 Apple Inc.
* Copyright (C) 2007 Alp Toker <alp@atoker.com>
* Copyright (C) 2008 Collabora Ltd.
* Copyright (C) 2008, 2009 Google Inc.
* Copyright (C) 2009 Kenneth Rohde Christiansen
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "core/layout/LayoutThemeDefault.h"
#include "core/CSSValueKeywords.h"
#include "core/layout/LayoutObject.h"
#include "core/layout/LayoutProgress.h"
#include "core/layout/LayoutThemeFontProvider.h"
#include "core/paint/MediaControlsPainter.h"
#include "platform/LayoutTestSupport.h"
#include "platform/PlatformResourceLoader.h"
#include "platform/graphics/Color.h"
#include "platform/scroll/ScrollbarTheme.h"
#include "public/platform/Platform.h"
#include "public/platform/WebThemeEngine.h"
namespace blink {
enum PaddingType {
TopPadding,
RightPadding,
BottomPadding,
LeftPadding
};
static const int styledMenuListInternalPadding[4] = { 1, 4, 1, 4 };
// These values all match Safari/Win.
static const float defaultControlFontPixelSize = 13;
static const float defaultCancelButtonSize = 9;
static const float minCancelButtonSize = 5;
static const float maxCancelButtonSize = 21;
static const float defaultSearchFieldResultsDecorationSize = 13;
static const float minSearchFieldResultsDecorationSize = 9;
static const float maxSearchFieldResultsDecorationSize = 30;
static bool useMockTheme()
{
return LayoutTestSupport::isRunningLayoutTest();
}
unsigned LayoutThemeDefault::m_activeSelectionBackgroundColor = 0xff1e90ff;
unsigned LayoutThemeDefault::m_activeSelectionForegroundColor = Color::white; // Color::black;
unsigned LayoutThemeDefault::m_inactiveSelectionBackgroundColor = 0xffc8c8c8;
unsigned LayoutThemeDefault::m_inactiveSelectionForegroundColor = 0xff323232;
double LayoutThemeDefault::m_caretBlinkInterval;
LayoutThemeDefault::LayoutThemeDefault()
{
m_caretBlinkInterval = LayoutTheme::caretBlinkInterval();
}
LayoutThemeDefault::~LayoutThemeDefault()
{
}
bool LayoutThemeDefault::supportsFocusRing(const ComputedStyle& style) const
{
if (useMockTheme()) {
// Don't use focus rings for buttons when mocking controls.
return style.appearance() == ButtonPart
|| style.appearance() == PushButtonPart
|| style.appearance() == SquareButtonPart;
}
// This causes Blink to draw the focus rings for us.
return false;
}
Color LayoutThemeDefault::systemColor(CSSValueID cssValueId) const
{
static const Color defaultButtonGrayColor(0xffdddddd);
static const Color defaultMenuColor(0xfff7f7f7);
if (cssValueId == CSSValueButtonface) {
if (useMockTheme())
return Color(0xc0, 0xc0, 0xc0);
return defaultButtonGrayColor;
}
if (cssValueId == CSSValueMenu)
return defaultMenuColor;
return LayoutTheme::systemColor(cssValueId);
}
// Use the Windows style sheets to match their metrics.
String LayoutThemeDefault::extraDefaultStyleSheet()
{
return LayoutTheme::extraDefaultStyleSheet()
+ loadResourceAsASCIIString("themeWin.css")
+ loadResourceAsASCIIString("themeChromiumSkia.css")
#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
+ loadResourceAsASCIIString("themeInputMultipleFields.css")
#endif
+ loadResourceAsASCIIString("themeChromium.css");
}
String LayoutThemeDefault::extraQuirksStyleSheet()
{
return loadResourceAsASCIIString("themeWinQuirks.css");
}
Color LayoutThemeDefault::activeListBoxSelectionBackgroundColor() const
{
return Color(0x28, 0x28, 0x28);
}
Color LayoutThemeDefault::activeListBoxSelectionForegroundColor() const
{
return Color::black;
}
Color LayoutThemeDefault::inactiveListBoxSelectionBackgroundColor() const
{
return Color(0xc8, 0xc8, 0xc8);
}
Color LayoutThemeDefault::inactiveListBoxSelectionForegroundColor() const
{
return Color(0x32, 0x32, 0x32);
}
Color LayoutThemeDefault::platformActiveSelectionBackgroundColor() const
{
if (useMockTheme())
return Color(0x00, 0x00, 0xff); // Royal blue.
return m_activeSelectionBackgroundColor;
}
Color LayoutThemeDefault::platformInactiveSelectionBackgroundColor() const
{
if (useMockTheme())
return Color(0x99, 0x99, 0x99); // Medium gray.
return m_inactiveSelectionBackgroundColor;
}
Color LayoutThemeDefault::platformActiveSelectionForegroundColor() const
{
if (useMockTheme())
return Color(0xff, 0xff, 0xcc); // Pale yellow.
return m_activeSelectionForegroundColor;
}
Color LayoutThemeDefault::platformInactiveSelectionForegroundColor() const
{
if (useMockTheme())
return Color::white;
return m_inactiveSelectionForegroundColor;
}
IntSize LayoutThemeDefault::sliderTickSize() const
{
if (useMockTheme())
return IntSize(1, 3);
return IntSize(1, 6);
}
int LayoutThemeDefault::sliderTickOffsetFromTrackCenter() const
{
if (useMockTheme())
return 11;
return -16;
}
void LayoutThemeDefault::adjustSliderThumbSize(ComputedStyle& style, Element* element) const
{
IntSize size = Platform::current()->themeEngine()->getSize(WebThemeEngine::PartSliderThumb);
// FIXME: Mock theme doesn't handle zoomed sliders.
float zoomLevel = useMockTheme() ? 1 : style.effectiveZoom();
if (style.appearance() == SliderThumbHorizontalPart) {
style.setWidth(Length(size.width() * zoomLevel, Fixed));
style.setHeight(Length(size.height() * zoomLevel, Fixed));
} else if (style.appearance() == SliderThumbVerticalPart) {
style.setWidth(Length(size.height() * zoomLevel, Fixed));
style.setHeight(Length(size.width() * zoomLevel, Fixed));
} else {
MediaControlsPainter::adjustMediaSliderThumbSize(style);
}
}
void LayoutThemeDefault::setCaretBlinkInterval(double interval)
{
m_caretBlinkInterval = interval;
}
void LayoutThemeDefault::setSelectionColors(
unsigned activeBackgroundColor,
unsigned activeForegroundColor,
unsigned inactiveBackgroundColor,
unsigned inactiveForegroundColor)
{
m_activeSelectionBackgroundColor = activeBackgroundColor;
m_activeSelectionForegroundColor = activeForegroundColor;
m_inactiveSelectionBackgroundColor = inactiveBackgroundColor;
m_inactiveSelectionForegroundColor = inactiveForegroundColor;
}
void LayoutThemeDefault::setCheckboxSize(ComputedStyle& style) const
{
// If the width and height are both specified, then we have nothing to do.
if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
return;
IntSize size = Platform::current()->themeEngine()->getSize(WebThemeEngine::PartCheckbox);
float zoomLevel = style.effectiveZoom();
size.setWidth(size.width() * zoomLevel);
size.setHeight(size.height() * zoomLevel);
setSizeIfAuto(style, size);
}
void LayoutThemeDefault::setRadioSize(ComputedStyle& style) const
{
// If the width and height are both specified, then we have nothing to do.
if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
return;
IntSize size = Platform::current()->themeEngine()->getSize(WebThemeEngine::PartRadio);
float zoomLevel = style.effectiveZoom();
size.setWidth(size.width() * zoomLevel);
size.setHeight(size.height() * zoomLevel);
setSizeIfAuto(style, size);
}
void LayoutThemeDefault::adjustInnerSpinButtonStyle(ComputedStyle& style, Element*) const
{
IntSize size = Platform::current()->themeEngine()->getSize(WebThemeEngine::PartInnerSpinButton);
style.setWidth(Length(size.width(), Fixed));
style.setMinWidth(Length(size.width(), Fixed));
}
bool LayoutThemeDefault::shouldOpenPickerWithF4Key() const
{
return true;
}
bool LayoutThemeDefault::shouldUseFallbackTheme(const ComputedStyle& style) const
{
if (useMockTheme()) {
// The mock theme can't handle zoomed controls, so we fall back to the "fallback" theme.
ControlPart part = style.appearance();
if (part == CheckboxPart || part == RadioPart)
return style.effectiveZoom() != 1;
}
return LayoutTheme::shouldUseFallbackTheme(style);
}
bool LayoutThemeDefault::supportsHover(const ComputedStyle& style) const
{
return true;
}
Color LayoutThemeDefault::platformFocusRingColor() const
{
static Color focusRingColor(229, 151, 0, 255);
return focusRingColor;
}
double LayoutThemeDefault::caretBlinkInterval() const
{
// Disable the blinking caret in layout test mode, as it introduces
// a race condition for the pixel tests. http://b/1198440
if (LayoutTestSupport::isRunningLayoutTest())
return 0;
return m_caretBlinkInterval;
}
void LayoutThemeDefault::systemFont(CSSValueID systemFontID, FontStyle& fontStyle, FontWeight& fontWeight, float& fontSize, AtomicString& fontFamily) const
{
LayoutThemeFontProvider::systemFont(systemFontID, fontStyle, fontWeight, fontSize, fontFamily);
}
int LayoutThemeDefault::minimumMenuListSize(const ComputedStyle& style) const
{
return 0;
}
// Return a rectangle that has the same center point as |original|, but with a
// size capped at |width| by |height|.
IntRect center(const IntRect& original, int width, int height)
{
width = std::min(original.width(), width);
height = std::min(original.height(), height);
int x = original.x() + (original.width() - width) / 2;
int y = original.y() + (original.height() - height) / 2;
return IntRect(x, y, width, height);
}
void LayoutThemeDefault::adjustButtonStyle(ComputedStyle& style, Element*) const
{
if (style.appearance() == PushButtonPart) {
// Ignore line-height.
style.setLineHeight(ComputedStyle::initialLineHeight());
}
}
void LayoutThemeDefault::adjustSearchFieldStyle(ComputedStyle& style, Element*) const
{
// Ignore line-height.
style.setLineHeight(ComputedStyle::initialLineHeight());
}
void LayoutThemeDefault::adjustSearchFieldCancelButtonStyle(ComputedStyle& style, Element*) const
{
// Scale the button size based on the font size
float fontScale = style.fontSize() / defaultControlFontPixelSize;
int cancelButtonSize = lroundf(std::min(std::max(minCancelButtonSize, defaultCancelButtonSize * fontScale), maxCancelButtonSize));
style.setWidth(Length(cancelButtonSize, Fixed));
style.setHeight(Length(cancelButtonSize, Fixed));
}
void LayoutThemeDefault::adjustSearchFieldDecorationStyle(ComputedStyle& style, Element*) const
{
IntSize emptySize(1, 11);
style.setWidth(Length(emptySize.width(), Fixed));
style.setHeight(Length(emptySize.height(), Fixed));
}
void LayoutThemeDefault::adjustSearchFieldResultsDecorationStyle(ComputedStyle& style, Element*) const
{
// Scale the decoration size based on the font size
float fontScale = style.fontSize() / defaultControlFontPixelSize;
int magnifierSize = lroundf(std::min(std::max(minSearchFieldResultsDecorationSize, defaultSearchFieldResultsDecorationSize * fontScale),
maxSearchFieldResultsDecorationSize));
style.setWidth(Length(magnifierSize, Fixed));
style.setHeight(Length(magnifierSize, Fixed));
}
void LayoutThemeDefault::adjustMenuListStyle(ComputedStyle& style, Element*) const
{
// Height is locked to auto on all browsers.
style.setLineHeight(ComputedStyle::initialLineHeight());
}
void LayoutThemeDefault::adjustMenuListButtonStyle(ComputedStyle& style, Element* e) const
{
adjustMenuListStyle(style, e);
}
int LayoutThemeDefault::popupInternalPaddingLeft(const ComputedStyle& style) const
{
return menuListInternalPadding(style, LeftPadding);
}
int LayoutThemeDefault::popupInternalPaddingRight(const ComputedStyle& style) const
{
return menuListInternalPadding(style, RightPadding);
}
int LayoutThemeDefault::popupInternalPaddingTop(const ComputedStyle& style) const
{
return menuListInternalPadding(style, TopPadding);
}
int LayoutThemeDefault::popupInternalPaddingBottom(const ComputedStyle& style) const
{
return menuListInternalPadding(style, BottomPadding);
}
// static
void LayoutThemeDefault::setDefaultFontSize(int fontSize)
{
LayoutThemeFontProvider::setDefaultFontSize(fontSize);
}
int LayoutThemeDefault::menuListArrowPadding() const
{
return ScrollbarTheme::theme()->scrollbarThickness();
}
int LayoutThemeDefault::menuListInternalPadding(const ComputedStyle& style, int paddingType) const
{
// This internal padding is in addition to the user-supplied padding.
// Matches the FF behavior.
int padding = styledMenuListInternalPadding[paddingType];
// Reserve the space for right arrow here. The rest of the padding is
// set by adjustMenuListStyle, since PopMenuWin.cpp uses the padding from
// LayoutMenuList to lay out the individual items in the popup.
// If the MenuList actually has appearance "NoAppearance", then that means
// we don't draw a button, so don't reserve space for it.
const int barType = style.direction() == LTR ? RightPadding : LeftPadding;
if (paddingType == barType && style.appearance() != NoControlPart)
padding += menuListArrowPadding();
return padding;
}
bool LayoutThemeDefault::shouldShowPlaceholderWhenFocused() const
{
return true;
}
//
// Following values are come from default of GTK+
//
static const int progressAnimationFrames = 10;
static const double progressAnimationInterval = 0.125;
double LayoutThemeDefault::animationRepeatIntervalForProgressBar() const
{
return progressAnimationInterval;
}
double LayoutThemeDefault::animationDurationForProgressBar() const
{
return progressAnimationInterval * progressAnimationFrames * 2; // "2" for back and forth
}
} // namespace blink
<|endoftext|>
|
<commit_before>#include <QtCore/QCoreApplication>
#include <QtCore/QEvent>
#include <QtCore/QHash>
#include <QtCore/QMultiHash>
#include <QtCore/QSocketNotifier>
#include <QtCore/QThread>
#include <event2/event.h>
#include <event2/thread.h>
#include <unistd.h>
#include "eventdispatcher_libevent.h"
static int make_pipe(int pipefd[2])
{
int res = ::pipe(pipefd);
if (-1 == res) {
return res;
}
evutil_make_socket_closeonexec(pipefd[0]);
evutil_make_socket_nonblocking(pipefd[0]);
evutil_make_socket_closeonexec(pipefd[1]);
evutil_make_socket_nonblocking(pipefd[1]);
return 0;
}
class EventDispatcherLibEventPrivate {
public:
EventDispatcherLibEventPrivate(EventDispatcherLibEvent* const q);
~EventDispatcherLibEventPrivate(void);
bool processEvents(QEventLoop::ProcessEventsFlags flags);
void registerSocketNotifier(QSocketNotifier* notifier);
void unregisterSocketNotifier(QSocketNotifier* notifier);
void registerTimer(int timerId, int interval, QObject* object);
bool unregisterTimer(int timerId);
bool unregisterTimers(QObject* object);
QList<QAbstractEventDispatcher::TimerInfo> registeredTimers(QObject* object) const;
struct SocketNotifierInfo {
QSocketNotifier* sn;
struct event* ev;
};
struct TimerInfo {
EventDispatcherLibEventPrivate* self;
struct event* ev;
int timerId;
int interval;
QObject* object;
};
typedef QMultiHash<evutil_socket_t, SocketNotifierInfo> SocketNotifierHash;
typedef QHash<int, TimerInfo*> TimerHash;
private:
Q_DISABLE_COPY(EventDispatcherLibEventPrivate)
Q_DECLARE_PUBLIC(EventDispatcherLibEvent)
EventDispatcherLibEvent* const q_ptr;
bool m_interrupt;
int m_thread_pipe[2];
struct event_base* m_base;
struct event* m_wakeup;
SocketNotifierHash m_notifiers;
TimerHash m_timers;
static void socket_notifier_callback(evutil_socket_t fd, short int events, void* arg);
static void timer_callback(evutil_socket_t fd, short int events, void* arg);
static void wake_up_handler(evutil_socket_t fd, short int events, void* arg);
};
EventDispatcherLibEventPrivate::EventDispatcherLibEventPrivate(EventDispatcherLibEvent* const q)
: q_ptr(q), m_interrupt(false), m_thread_pipe(), m_base(0), m_wakeup(0),
m_notifiers(), m_timers()
{
this->m_base = event_base_new();
if (-1 == make_pipe(this->m_thread_pipe)) {
#ifndef QT_NO_DEBUG
qFatal("%s: Unable to create pipe", Q_FUNC_INFO);
#else
qErrnoWarning("%s: Unable to create pipe", Q_FUNC_INFO);
#endif
m_thread_pipe[0] = -1;
m_thread_pipe[1] = -1;
}
else {
this->m_wakeup = event_new(this->m_base, this->m_thread_pipe[0], EV_READ | EV_PERSIST, EventDispatcherLibEventPrivate::wake_up_handler, 0);
event_add(this->m_wakeup, 0);
}
}
EventDispatcherLibEventPrivate::~EventDispatcherLibEventPrivate(void)
{
if (this->m_thread_pipe[0] != -1) {
evutil_closesocket(this->m_thread_pipe[0]);
}
if (this->m_thread_pipe[1] != -1) {
evutil_closesocket(this->m_thread_pipe[1]);
}
if (this->m_wakeup) {
event_del(this->m_wakeup);
event_free(this->m_wakeup);
this->m_wakeup = 0;
}
if (this->m_base) {
event_base_free(this->m_base);
this->m_base = 0;
}
}
bool EventDispatcherLibEventPrivate::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_Q(EventDispatcherLibEvent);
Q_EMIT q->awake();
QCoreApplication::sendPostedEvents();
const bool canWait = (!this->m_interrupt && (flags & QEventLoop::WaitForMoreEvents));
do {
if (canWait) {
Q_EMIT q->aboutToBlock();
event_base_loop(this->m_base, EVLOOP_ONCE);
}
else {
event_base_loop(this->m_base, EVLOOP_NONBLOCK | EVLOOP_ONCE);
}
QCoreApplication::sendPostedEvents();
} while (!this->m_interrupt && !canWait);
this->m_interrupt = false;
return true;
}
void EventDispatcherLibEventPrivate::registerSocketNotifier(QSocketNotifier* notifier)
{
evutil_socket_t sockfd = notifier->socket();
short int what;
switch (notifier->type()) {
case QSocketNotifier::Read: what = EV_READ; break;
case QSocketNotifier::Write: what = EV_WRITE; break;
case QSocketNotifier::Exception: /// FIXME
return;
default:
Q_ASSERT(false);
return;
}
what |= EV_PERSIST;
struct event* ev = event_new(this->m_base, sockfd, what, EventDispatcherLibEventPrivate::socket_notifier_callback, this);
event_add(ev, 0);
SocketNotifierInfo data;
data.sn = notifier;
data.ev = ev;
this->m_notifiers.insertMulti(sockfd, data);
}
void EventDispatcherLibEventPrivate::unregisterSocketNotifier(QSocketNotifier* notifier)
{
evutil_socket_t sockfd = notifier->socket();
SocketNotifierHash::Iterator it = this->m_notifiers.find(sockfd);
while (it != this->m_notifiers.end() && it.key() == sockfd) {
SocketNotifierInfo& data = it.value();
if (data.sn == notifier) {
event_del(data.ev);
event_free(data.ev);
it = this->m_notifiers.erase(it);
}
else {
++it;
}
}
}
void EventDispatcherLibEventPrivate::registerTimer(int timerId, int interval, QObject* object)
{
EventDispatcherLibEventPrivate::TimerInfo* info = new EventDispatcherLibEventPrivate::TimerInfo;
info->self = this;
info->ev = event_new(this->m_base, -1, EV_PERSIST, EventDispatcherLibEventPrivate::timer_callback, info);
info->timerId = timerId;
info->interval = interval;
info->object = object;
struct timeval tv;
tv.tv_sec = interval / 1000;
tv.tv_usec = interval % 1000;
event_add(info->ev, &tv);
this->m_timers.insert(timerId, info);
}
bool EventDispatcherLibEventPrivate::unregisterTimer(int timerId)
{
TimerHash::Iterator it = this->m_timers.find(timerId);
if (it != this->m_timers.end()) {
EventDispatcherLibEventPrivate::TimerInfo* info = it.value();
event_del(info->ev);
event_free(info->ev);
delete info;
this->m_timers.erase(it);
return true;
}
return false;
}
bool EventDispatcherLibEventPrivate::unregisterTimers(QObject* object)
{
TimerHash::Iterator it = this->m_timers.begin();
while (it != this->m_timers.end()) {
EventDispatcherLibEventPrivate::TimerInfo* info = it.value();
if (object == info->object) {
event_del(info->ev);
event_free(info->ev);
delete info;
it = this->m_timers.erase(it);
}
else {
++it;
}
}
return true;
}
QList<QAbstractEventDispatcher::TimerInfo> EventDispatcherLibEventPrivate::registeredTimers(QObject* object) const
{
QList<QAbstractEventDispatcher::TimerInfo> res;
TimerHash::ConstIterator it = this->m_timers.constBegin();
while (it != this->m_timers.constEnd()) {
EventDispatcherLibEventPrivate::TimerInfo* info = it.value();
if (object == info->object) {
QAbstractEventDispatcher::TimerInfo ti(it.key(), info->interval);
res.append(ti);
++it;
}
}
return res;
}
void EventDispatcherLibEventPrivate::socket_notifier_callback(int fd, short int events, void* arg)
{
EventDispatcherLibEventPrivate* disp = reinterpret_cast<EventDispatcherLibEventPrivate*>(arg);
SocketNotifierHash::Iterator it = disp->m_notifiers.find(fd);
while (it != disp->m_notifiers.end() && it.key() == fd) {
SocketNotifierInfo& data = it.value();
QSocketNotifier::Type type = data.sn->type();
if ((QSocketNotifier::Read == type && (events & EV_READ)) || (QSocketNotifier::Write == type && (events & EV_WRITE))) {
QEvent e(QEvent::SockAct);
QCoreApplication::sendEvent(data.sn, &e);
}
++it;
}
}
void EventDispatcherLibEventPrivate::timer_callback(int fd, short int events, void* arg)
{
Q_ASSERT(-1 == fd);
Q_ASSERT(events & EV_TIMEOUT);
Q_UNUSED(fd)
Q_UNUSED(events)
EventDispatcherLibEventPrivate::TimerInfo* info = reinterpret_cast<EventDispatcherLibEventPrivate::TimerInfo*>(arg);
QTimerEvent event(info->timerId);
QCoreApplication::sendEvent(info->object, &event);
}
void EventDispatcherLibEventPrivate::wake_up_handler(int fd, short int events, void* arg)
{
Q_UNUSED(events)
Q_UNUSED(arg)
char buf[256];
while (::read(fd, buf, 256) > 0) {
// Do nothing
}
}
EventDispatcherLibEvent::EventDispatcherLibEvent(QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(new EventDispatcherLibEventPrivate(this))
{
}
EventDispatcherLibEvent::~EventDispatcherLibEvent(void)
{
}
bool EventDispatcherLibEvent::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_D(EventDispatcherLibEvent);
return d->processEvents(flags);
}
bool EventDispatcherLibEvent::hasPendingEvents(void)
{
extern Q_CORE_EXPORT uint qGlobalPostedEventsCount();
return qGlobalPostedEventsCount() > 0;
}
void EventDispatcherLibEvent::registerSocketNotifier(QSocketNotifier* notifier)
{
#ifndef QT_NO_DEBUG
if (notifier->socket() < 0) {
qWarning("QSocketNotifier: Internal error: sockfd < 0");
return;
}
else if (notifier->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be enabled from another thread");
return;
}
#endif
if (notifier->type() == QSocketNotifier::Exception) {
return;
}
Q_D(EventDispatcherLibEvent);
d->registerSocketNotifier(notifier);
}
void EventDispatcherLibEvent::unregisterSocketNotifier(QSocketNotifier* notifier)
{
#ifndef QT_NO_DEBUG
if (notifier->socket() < 0) {
qWarning("QSocketNotifier: Internal error: sockfd < 0");
return;
}
else if (notifier->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be disabled from another thread");
return;
}
#endif
// Short circuit, we do not support QSocketNotifier::Exception
if (notifier->type() == QSocketNotifier::Exception) {
return;
}
Q_D(EventDispatcherLibEvent);
d->unregisterSocketNotifier(notifier);
}
void EventDispatcherLibEvent::registerTimer(int timerId, int interval, QObject* object)
{
#ifndef QT_NO_DEBUG
if (timerId < 1 || interval < 0 || !object) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return;
}
if (object->thread() != this->thread() && this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be started from another thread", Q_FUNC_INFO);
return;
}
#endif
Q_D(EventDispatcherLibEvent);
d->registerTimer(timerId, interval, object);
}
bool EventDispatcherLibEvent::unregisterTimer(int timerId)
{
#ifndef QT_NO_DEBUG
if (timerId < 1) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return;
}
if (this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be stopped from another thread", Q_FUNC_INFO);
return;
}
#endif
Q_D(EventDispatcherLibEvent);
return d->unregisterTimer(timerId);
}
bool EventDispatcherLibEvent::unregisterTimers(QObject* object)
{
#ifndef QT_NO_DEBUG
if (!object) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return;
}
if (object->thread() != this->thread() && this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be stopped from another thread", Q_FUNC_INFO);
return;
}
#endif
Q_D(EventDispatcherLibEvent);
return d->unregisterTimers(object);
}
QList<QAbstractEventDispatcher::TimerInfo> EventDispatcherLibEvent::registeredTimers(QObject* object) const
{
if (!object) {
qWarning("%s: invalid argument", Q_FUNC_INFO);
return QList<QAbstractEventDispatcher::TimerInfo>();
}
Q_D(const EventDispatcherLibEvent);
return d->registeredTimers(object);
}
void EventDispatcherLibEvent::wakeUp(void)
{
Q_D(EventDispatcherLibEvent);
if (d->m_thread_pipe[1] != -1) {
if (::write(d->m_thread_pipe[1], "w", 1) != 1) {
// Avoid compiler's warning
}
}
}
void EventDispatcherLibEvent::interrupt(void)
{
Q_D(EventDispatcherLibEvent);
d->m_interrupt = true;
this->wakeUp();
}
void EventDispatcherLibEvent::flush(void)
{
}
<commit_msg>tv_sec is 1,000,000 tv_usec, not 1,000<commit_after>#include <QtCore/QCoreApplication>
#include <QtCore/QEvent>
#include <QtCore/QHash>
#include <QtCore/QMultiHash>
#include <QtCore/QSocketNotifier>
#include <QtCore/QThread>
#include <event2/event.h>
#include <event2/thread.h>
#include <unistd.h>
#include "eventdispatcher_libevent.h"
static int make_pipe(int pipefd[2])
{
int res = ::pipe(pipefd);
if (-1 == res) {
return res;
}
evutil_make_socket_closeonexec(pipefd[0]);
evutil_make_socket_nonblocking(pipefd[0]);
evutil_make_socket_closeonexec(pipefd[1]);
evutil_make_socket_nonblocking(pipefd[1]);
return 0;
}
class EventDispatcherLibEventPrivate {
public:
EventDispatcherLibEventPrivate(EventDispatcherLibEvent* const q);
~EventDispatcherLibEventPrivate(void);
bool processEvents(QEventLoop::ProcessEventsFlags flags);
void registerSocketNotifier(QSocketNotifier* notifier);
void unregisterSocketNotifier(QSocketNotifier* notifier);
void registerTimer(int timerId, int interval, QObject* object);
bool unregisterTimer(int timerId);
bool unregisterTimers(QObject* object);
QList<QAbstractEventDispatcher::TimerInfo> registeredTimers(QObject* object) const;
struct SocketNotifierInfo {
QSocketNotifier* sn;
struct event* ev;
};
struct TimerInfo {
EventDispatcherLibEventPrivate* self;
struct event* ev;
int timerId;
int interval;
QObject* object;
};
typedef QMultiHash<evutil_socket_t, SocketNotifierInfo> SocketNotifierHash;
typedef QHash<int, TimerInfo*> TimerHash;
private:
Q_DISABLE_COPY(EventDispatcherLibEventPrivate)
Q_DECLARE_PUBLIC(EventDispatcherLibEvent)
EventDispatcherLibEvent* const q_ptr;
bool m_interrupt;
int m_thread_pipe[2];
struct event_base* m_base;
struct event* m_wakeup;
SocketNotifierHash m_notifiers;
TimerHash m_timers;
static void socket_notifier_callback(evutil_socket_t fd, short int events, void* arg);
static void timer_callback(evutil_socket_t fd, short int events, void* arg);
static void wake_up_handler(evutil_socket_t fd, short int events, void* arg);
};
EventDispatcherLibEventPrivate::EventDispatcherLibEventPrivate(EventDispatcherLibEvent* const q)
: q_ptr(q), m_interrupt(false), m_thread_pipe(), m_base(0), m_wakeup(0),
m_notifiers(), m_timers()
{
this->m_base = event_base_new();
if (-1 == make_pipe(this->m_thread_pipe)) {
#ifndef QT_NO_DEBUG
qFatal("%s: Unable to create pipe", Q_FUNC_INFO);
#else
qErrnoWarning("%s: Unable to create pipe", Q_FUNC_INFO);
#endif
m_thread_pipe[0] = -1;
m_thread_pipe[1] = -1;
}
else {
this->m_wakeup = event_new(this->m_base, this->m_thread_pipe[0], EV_READ | EV_PERSIST, EventDispatcherLibEventPrivate::wake_up_handler, 0);
event_add(this->m_wakeup, 0);
}
}
EventDispatcherLibEventPrivate::~EventDispatcherLibEventPrivate(void)
{
if (this->m_thread_pipe[0] != -1) {
evutil_closesocket(this->m_thread_pipe[0]);
}
if (this->m_thread_pipe[1] != -1) {
evutil_closesocket(this->m_thread_pipe[1]);
}
if (this->m_wakeup) {
event_del(this->m_wakeup);
event_free(this->m_wakeup);
this->m_wakeup = 0;
}
if (this->m_base) {
event_base_free(this->m_base);
this->m_base = 0;
}
}
bool EventDispatcherLibEventPrivate::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_Q(EventDispatcherLibEvent);
Q_EMIT q->awake();
QCoreApplication::sendPostedEvents();
const bool canWait = (!this->m_interrupt && (flags & QEventLoop::WaitForMoreEvents));
do {
if (canWait) {
Q_EMIT q->aboutToBlock();
event_base_loop(this->m_base, EVLOOP_ONCE);
}
else {
event_base_loop(this->m_base, EVLOOP_NONBLOCK | EVLOOP_ONCE);
}
QCoreApplication::sendPostedEvents();
} while (!this->m_interrupt && !canWait);
this->m_interrupt = false;
return true;
}
void EventDispatcherLibEventPrivate::registerSocketNotifier(QSocketNotifier* notifier)
{
evutil_socket_t sockfd = notifier->socket();
short int what;
switch (notifier->type()) {
case QSocketNotifier::Read: what = EV_READ; break;
case QSocketNotifier::Write: what = EV_WRITE; break;
case QSocketNotifier::Exception: /// FIXME
return;
default:
Q_ASSERT(false);
return;
}
what |= EV_PERSIST;
struct event* ev = event_new(this->m_base, sockfd, what, EventDispatcherLibEventPrivate::socket_notifier_callback, this);
event_add(ev, 0);
SocketNotifierInfo data;
data.sn = notifier;
data.ev = ev;
this->m_notifiers.insertMulti(sockfd, data);
}
void EventDispatcherLibEventPrivate::unregisterSocketNotifier(QSocketNotifier* notifier)
{
evutil_socket_t sockfd = notifier->socket();
SocketNotifierHash::Iterator it = this->m_notifiers.find(sockfd);
while (it != this->m_notifiers.end() && it.key() == sockfd) {
SocketNotifierInfo& data = it.value();
if (data.sn == notifier) {
event_del(data.ev);
event_free(data.ev);
it = this->m_notifiers.erase(it);
}
else {
++it;
}
}
}
void EventDispatcherLibEventPrivate::registerTimer(int timerId, int interval, QObject* object)
{
EventDispatcherLibEventPrivate::TimerInfo* info = new EventDispatcherLibEventPrivate::TimerInfo;
info->self = this;
info->ev = event_new(this->m_base, -1, EV_PERSIST, EventDispatcherLibEventPrivate::timer_callback, info);
info->timerId = timerId;
info->interval = interval;
info->object = object;
struct timeval tv;
tv.tv_sec = interval / 1000000;
tv.tv_usec = interval % 1000000;
event_add(info->ev, &tv);
this->m_timers.insert(timerId, info);
}
bool EventDispatcherLibEventPrivate::unregisterTimer(int timerId)
{
TimerHash::Iterator it = this->m_timers.find(timerId);
if (it != this->m_timers.end()) {
EventDispatcherLibEventPrivate::TimerInfo* info = it.value();
event_del(info->ev);
event_free(info->ev);
delete info;
this->m_timers.erase(it);
return true;
}
return false;
}
bool EventDispatcherLibEventPrivate::unregisterTimers(QObject* object)
{
TimerHash::Iterator it = this->m_timers.begin();
while (it != this->m_timers.end()) {
EventDispatcherLibEventPrivate::TimerInfo* info = it.value();
if (object == info->object) {
event_del(info->ev);
event_free(info->ev);
delete info;
it = this->m_timers.erase(it);
}
else {
++it;
}
}
return true;
}
QList<QAbstractEventDispatcher::TimerInfo> EventDispatcherLibEventPrivate::registeredTimers(QObject* object) const
{
QList<QAbstractEventDispatcher::TimerInfo> res;
TimerHash::ConstIterator it = this->m_timers.constBegin();
while (it != this->m_timers.constEnd()) {
EventDispatcherLibEventPrivate::TimerInfo* info = it.value();
if (object == info->object) {
QAbstractEventDispatcher::TimerInfo ti(it.key(), info->interval);
res.append(ti);
++it;
}
}
return res;
}
void EventDispatcherLibEventPrivate::socket_notifier_callback(int fd, short int events, void* arg)
{
EventDispatcherLibEventPrivate* disp = reinterpret_cast<EventDispatcherLibEventPrivate*>(arg);
SocketNotifierHash::Iterator it = disp->m_notifiers.find(fd);
while (it != disp->m_notifiers.end() && it.key() == fd) {
SocketNotifierInfo& data = it.value();
QSocketNotifier::Type type = data.sn->type();
if ((QSocketNotifier::Read == type && (events & EV_READ)) || (QSocketNotifier::Write == type && (events & EV_WRITE))) {
QEvent e(QEvent::SockAct);
QCoreApplication::sendEvent(data.sn, &e);
}
++it;
}
}
void EventDispatcherLibEventPrivate::timer_callback(int fd, short int events, void* arg)
{
Q_ASSERT(-1 == fd);
Q_ASSERT(events & EV_TIMEOUT);
Q_UNUSED(fd)
Q_UNUSED(events)
EventDispatcherLibEventPrivate::TimerInfo* info = reinterpret_cast<EventDispatcherLibEventPrivate::TimerInfo*>(arg);
QTimerEvent event(info->timerId);
QCoreApplication::sendEvent(info->object, &event);
}
void EventDispatcherLibEventPrivate::wake_up_handler(int fd, short int events, void* arg)
{
Q_UNUSED(events)
Q_UNUSED(arg)
char buf[256];
while (::read(fd, buf, 256) > 0) {
// Do nothing
}
}
EventDispatcherLibEvent::EventDispatcherLibEvent(QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(new EventDispatcherLibEventPrivate(this))
{
}
EventDispatcherLibEvent::~EventDispatcherLibEvent(void)
{
}
bool EventDispatcherLibEvent::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_D(EventDispatcherLibEvent);
return d->processEvents(flags);
}
bool EventDispatcherLibEvent::hasPendingEvents(void)
{
extern Q_CORE_EXPORT uint qGlobalPostedEventsCount();
return qGlobalPostedEventsCount() > 0;
}
void EventDispatcherLibEvent::registerSocketNotifier(QSocketNotifier* notifier)
{
#ifndef QT_NO_DEBUG
if (notifier->socket() < 0) {
qWarning("QSocketNotifier: Internal error: sockfd < 0");
return;
}
else if (notifier->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be enabled from another thread");
return;
}
#endif
if (notifier->type() == QSocketNotifier::Exception) {
return;
}
Q_D(EventDispatcherLibEvent);
d->registerSocketNotifier(notifier);
}
void EventDispatcherLibEvent::unregisterSocketNotifier(QSocketNotifier* notifier)
{
#ifndef QT_NO_DEBUG
if (notifier->socket() < 0) {
qWarning("QSocketNotifier: Internal error: sockfd < 0");
return;
}
else if (notifier->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be disabled from another thread");
return;
}
#endif
// Short circuit, we do not support QSocketNotifier::Exception
if (notifier->type() == QSocketNotifier::Exception) {
return;
}
Q_D(EventDispatcherLibEvent);
d->unregisterSocketNotifier(notifier);
}
void EventDispatcherLibEvent::registerTimer(int timerId, int interval, QObject* object)
{
#ifndef QT_NO_DEBUG
if (timerId < 1 || interval < 0 || !object) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return;
}
if (object->thread() != this->thread() && this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be started from another thread", Q_FUNC_INFO);
return;
}
#endif
Q_D(EventDispatcherLibEvent);
d->registerTimer(timerId, interval, object);
}
bool EventDispatcherLibEvent::unregisterTimer(int timerId)
{
#ifndef QT_NO_DEBUG
if (timerId < 1) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return;
}
if (this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be stopped from another thread", Q_FUNC_INFO);
return;
}
#endif
Q_D(EventDispatcherLibEvent);
return d->unregisterTimer(timerId);
}
bool EventDispatcherLibEvent::unregisterTimers(QObject* object)
{
#ifndef QT_NO_DEBUG
if (!object) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return;
}
if (object->thread() != this->thread() && this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be stopped from another thread", Q_FUNC_INFO);
return;
}
#endif
Q_D(EventDispatcherLibEvent);
return d->unregisterTimers(object);
}
QList<QAbstractEventDispatcher::TimerInfo> EventDispatcherLibEvent::registeredTimers(QObject* object) const
{
if (!object) {
qWarning("%s: invalid argument", Q_FUNC_INFO);
return QList<QAbstractEventDispatcher::TimerInfo>();
}
Q_D(const EventDispatcherLibEvent);
return d->registeredTimers(object);
}
void EventDispatcherLibEvent::wakeUp(void)
{
Q_D(EventDispatcherLibEvent);
if (d->m_thread_pipe[1] != -1) {
if (::write(d->m_thread_pipe[1], "w", 1) != 1) {
// Avoid compiler's warning
}
}
}
void EventDispatcherLibEvent::interrupt(void)
{
Q_D(EventDispatcherLibEvent);
d->m_interrupt = true;
this->wakeUp();
}
void EventDispatcherLibEvent::flush(void)
{
}
<|endoftext|>
|
<commit_before>
#include "netmessages.h"
#include "demofilebitbuf.h"
#include <cassert>
namespace math
{
unsigned int log2(unsigned int value)
{
unsigned int res = 0;
while (value >>= 1)
++res;
return res;
}
unsigned int Bits2Bytes(unsigned int bits)
{
return ((bits + 7) >> 3);
}
}
void Net_NOP(CBitRead& bitbuf)
{
// nothing
}
void Net_Disconnect(CBitRead& bitbuf)
{
char message[1024];
bitbuf.ReadString(message, sizeof(message));
}
void Net_File(CBitRead& bitbuf)
{
const unsigned int transferID = bitbuf.ReadUBitLong(32);
char filename[1024];
bitbuf.ReadString(filename, sizeof(filename));
const bool isRequest = bitbuf.ReadOneBit() != 0;
}
void Net_Tick(CBitRead& bitbuf)
{
static const float NET_TICK_SCALEUP = 100000.0f;
const int tick = bitbuf.ReadLong();
const float hostFrameTime = (float)bitbuf.ReadUBitLong(16) / NET_TICK_SCALEUP;
const float hostFrameTimeStdDev = (float)bitbuf.ReadUBitLong(16) / NET_TICK_SCALEUP;
}
void Net_StringCmd(CBitRead& bitbuf)
{
char commandBuffer[1024];
bitbuf.ReadString(commandBuffer, sizeof(commandBuffer));
}
void Net_SetConVar(CBitRead& bitbuf)
{
typedef struct cvar_s
{
char name[MAX_OSPATH];
char value[MAX_OSPATH];
} cvar_t;
const int numVars = bitbuf.ReadByte();
cvar_t cvar;
for (int i = 0; i < numVars; ++i)
{
bitbuf.ReadString(cvar.name, sizeof(cvar.name));
bitbuf.ReadString(cvar.value, sizeof(cvar.value));
}
}
void Net_SignonState(CBitRead& bitbuf)
{
const int signonState = bitbuf.ReadByte();
//assert(signonState == SIGNONSTATE_PRESPAWN);
const int spawnCount = bitbuf.ReadLong();
}
void SVC_Print(CBitRead& bitbuf)
{
char textBuffer[2048];
bitbuf.ReadString(textBuffer, sizeof(textBuffer));
}
void SVC_ServerInfo(CBitRead& bitbuf)
{
const int protocol = bitbuf.ReadShort(); // protocol version
const int serverCount = bitbuf.ReadLong(); // number of changelevels since server start
const bool isHLTV = bitbuf.ReadOneBit() != 0; // HLTV server ?
const bool isDedicated = bitbuf.ReadOneBit() != 0; // dedicated server ?
const int clientCRC = bitbuf.ReadLong(); // client.dll CRC server is using
const int maxClasses = bitbuf.ReadWord(); // max number of server classes
if (protocol <= 17)
{
const int mapCRC = bitbuf.ReadLong(); // server map CRC
}
else
{
char unknown[16];
bitbuf.ReadBytes(unknown, sizeof(unknown));
}
const int playerSlot = bitbuf.ReadByte(); // our client slot number
const int maxClients = bitbuf.ReadByte(); // max number of clients on server
const float tickInterval = bitbuf.ReadFloat(); // server tick interval
const char os = bitbuf.ReadChar(); // 'l' = linux, 'w' = Win32
char gameDir[MAX_OSPATH]; // game directory eg "tf2"
char mapName[MAX_OSPATH]; // name of current map
char skyName[MAX_OSPATH]; // name of current skybox
char hostName[MAX_OSPATH]; // host name
bitbuf.ReadString(gameDir, sizeof(gameDir));
bitbuf.ReadString(mapName, sizeof(mapName));
bitbuf.ReadString(skyName, sizeof(skyName));
bitbuf.ReadString(hostName, sizeof(hostName));
}
void SVC_SendTable(CBitRead& bitbuf)
{
const bool needsDecoder = bitbuf.ReadOneBit() != 0;
const int dataLengthBits = bitbuf.ReadShort();
bitbuf.SeekRelative(dataLengthBits);
}
void SVC_ClassInfo(CBitRead& bitbuf)
{
typedef struct class_s
{
int classID;
char datatablename[256];
char classname[256];
} class_t;
const int numServerClasses = bitbuf.ReadShort();
const int nServerClassBits = math::log2(numServerClasses) + 1;
// if true, client creates own SendTables & classinfos from game.dll
const bool createOnClient = bitbuf.ReadOneBit() != 0;
if (!createOnClient)
{
class_t serverclass;
for (int i = 0; i < numServerClasses; ++i)
{
serverclass.classID = bitbuf.ReadUBitLong(nServerClassBits);
bitbuf.ReadString(serverclass.classname, sizeof(serverclass.classname));
bitbuf.ReadString(serverclass.datatablename, sizeof(serverclass.datatablename));
}
}
}
void SVC_SetPause(CBitRead& bitbuf)
{
const bool paused = bitbuf.ReadOneBit() != 0;
}
void SVC_CreateStringTable(CBitRead& bitbuf)
{
if (bitbuf.PeekUBitLong(8) == ':')
{
bitbuf.ReadByte();
}
char tableName[256];
bitbuf.ReadString(tableName, sizeof(tableName));
const int maxEntries = bitbuf.ReadWord();
const int encodeBits = math::log2(maxEntries);
const int numEntries = bitbuf.ReadUBitLong(encodeBits + 1);
const int lengthInBits = bitbuf.ReadUBitLong(NET_MAX_PALYLOAD_BITS + 3);
const bool userDataFixedSize = bitbuf.ReadOneBit() != 0;
if (userDataFixedSize)
{
const int userDataSize = bitbuf.ReadUBitLong(12);
const int userDataSizeBits = bitbuf.ReadUBitLong(4);
}
bitbuf.SeekRelative(lengthInBits);
}
void SVC_UpdateStringTable(CBitRead& bitbuf)
{
const int tableId = bitbuf.ReadUBitLong(math::log2(MAX_TABLES));
const int numChangedEntries = (bitbuf.ReadOneBit() != 0) ? bitbuf.ReadWord() : 1;
const int lengthInBits = bitbuf.ReadUBitLong(20);
bitbuf.SeekRelative(lengthInBits);
}
void SVC_VoiceInit(CBitRead& bitbuf)
{
char voiceCodec[MAX_OSPATH]; // used voice codec .dll
bitbuf.ReadString(voiceCodec, sizeof(voiceCodec));
const int quality = bitbuf.ReadByte(); // custom quality setting
}
void SVC_VoiceData(CBitRead& bitbuf)
{
const int fromClientIndex = bitbuf.ReadByte();
const bool proximity = !!bitbuf.ReadByte();
const int lengthInBits = bitbuf.ReadWord();
bitbuf.SeekRelative(lengthInBits);
}
void SVC_HLTV(CBitRead& bitbuf)
{
//const int state = bitbuf.ReadByte();
assert(false);
}
void SVC_Sounds(CBitRead& bitbuf)
{
const bool reliableSound = bitbuf.ReadOneBit() != 0;
int numSounds;
int lengthInBits;
if (reliableSound)
{
numSounds = 1;
lengthInBits = bitbuf.ReadUBitLong(8);
}
else
{
numSounds = bitbuf.ReadUBitLong(8);
lengthInBits = bitbuf.ReadUBitLong(16);
}
bitbuf.SeekRelative(lengthInBits);
}
void SVC_SetView(CBitRead& bitbuf)
{
const int entIndex = bitbuf.ReadUBitLong(MAX_EDICT_BITS);
}
void SVC_FixAngle(CBitRead& bitbuf)
{
const bool relative = bitbuf.ReadOneBit() != 0;
const float x = bitbuf.ReadBitAngle(16);
const float y = bitbuf.ReadBitAngle(16);
const float z = bitbuf.ReadBitAngle(16);
}
void SVC_CrosshairAngle(CBitRead& bitbuf)
{
const float x = bitbuf.ReadBitAngle(16);
const float y = bitbuf.ReadBitAngle(16);
const float z = bitbuf.ReadBitAngle(16);
}
void SVC_BSPDecal(CBitRead& bitbuf)
{
Vector pos;
bitbuf.ReadBitVec3Coord(pos);
const int decalTextureIndex = bitbuf.ReadUBitLong(MAX_DECAL_INDEX_BITS);
if (bitbuf.ReadOneBit() != 0)
{
const int entIndex = bitbuf.ReadUBitLong(MAX_EDICT_BITS);
const int modelIndex = bitbuf.ReadUBitLong(SP_MODEL_INDEX_BITS);
}
else
{
const int entIndex = 0;
const int modelIndex = 0;
}
const bool lowPriority = bitbuf.ReadOneBit() != 0;
}
void SVC_TerrainMod(CBitRead& bitbuf)
{
assert(false);
}
void SVC_UserMessage(CBitRead& bitbuf)
{
const int msgType = bitbuf.ReadByte();
// max 256 * 8 bits, see MAX_USER_MSG_DATA
const int lengthInBits = bitbuf.ReadUBitLong(11);
bitbuf.SeekRelative(lengthInBits);
}
void SVC_EntityMessage(CBitRead& bitbuf)
{
const int entIndex = bitbuf.ReadUBitLong(MAX_EDICT_BITS);
const int classID = bitbuf.ReadUBitLong(MAX_SERVER_CLASS_BITS);
// max 256 * 8 bits
const int lengthInBits = bitbuf.ReadUBitLong(11);
bitbuf.SeekRelative(lengthInBits);
}
void SVC_GameEvent(CBitRead& bitbuf)
{
const int lengthInBits = bitbuf.ReadUBitLong(11);
//uint32 eventId = bitbuf.ReadUBitLong(9);
bitbuf.SeekRelative(lengthInBits);
}
void SVC_PacketEntities(CBitRead& bitbuf)
{
const int maxEntries = bitbuf.ReadUBitLong(MAX_EDICT_BITS);
const bool isDelta = bitbuf.ReadOneBit() != 0;
if (isDelta)
{
const int deltaFrom = bitbuf.ReadLong();
}
else
{
const int deltaFrom = -1;
}
const int numBaseline = bitbuf.ReadUBitLong(1);
const int numUpdatedEntries = bitbuf.ReadUBitLong(MAX_EDICT_BITS);
const int lengthInBits = bitbuf.ReadUBitLong(DELTASIZE_BITS);
const bool updateBaseline = bitbuf.ReadOneBit() != 0;
bitbuf.SeekRelative(lengthInBits);
}
void SVC_TempEntities(CBitRead& bitbuf)
{
const int numEntries = bitbuf.ReadUBitLong(EVENT_INDEX_BITS);
const int lengthInBits = bitbuf.ReadUBitLong(NET_MAX_PALYLOAD_BITS);
bitbuf.SeekRelative(lengthInBits);
}
void SVC_Prefetch(CBitRead& bitbuf)
{
enum
{
SOUND = 0,
};
const short type = SOUND; // bitbuf.ReadUBitLong(1);
const short soundIndex = bitbuf.ReadUBitLong(MAX_SOUND_INDEX_BITS);
}
void SVC_Menu(CBitRead& bitbuf)
{
typedef enum
{
DIALOG_MSG = 0, // just an on screen message
DIALOG_MENU, // an options menu
DIALOG_TEXT, // a richtext dialog
DIALOG_ENTRY, // an entry box
DIALOG_ASKCONNECT // Ask the client to connect to a specified IP address. Only the "time" and "title" keys are used.
} DIALOG_TYPE;
DIALOG_TYPE type = (DIALOG_TYPE)bitbuf.ReadShort();
const int lengthInBytes = bitbuf.ReadWord();
bitbuf.SeekRelative(lengthInBytes * 8);
}
void SVC_GameEventList(CBitRead& bitbuf)
{
const int numEvents = bitbuf.ReadUBitLong(MAX_EVENT_BITS);
for (int i = 0; i < numEvents; ++i)
{
const int id = bitbuf.ReadUBitLong(MAX_EVENT_BITS);
char name[MAX_EVENT_NAME_LENGTH];
bitbuf.ReadString(name, sizeof(name));
printf("%s\n", name);
assert(false);
// gameeventmanager.cpp ParseEventList
}
const int lengthInBits = bitbuf.ReadUBitLong(20);
bitbuf.SeekRelative(lengthInBits);
}
void SVC_GetCvarValue(CBitRead& bitbuf)
{
typedef int QueryCvarCookie_t;
QueryCvarCookie_t cookie = bitbuf.ReadSBitLong(32);
char cvarName[256];
bitbuf.ReadString(cvarName, sizeof(cvarName));
}
static const int NUM_MESSAGES = static_cast<uint8_t>(NetMsg::SVC_LASTMSG) + 1;
void ProcessNetMsg(const std::uint32_t msgType, CBitRead& bitbuf)
{
static NetMsgFn netMsgHandler[NUM_MESSAGES] =
{
&Net_NOP,
&Net_Disconnect,
&Net_File,
&Net_Tick,
&Net_StringCmd,
&Net_SetConVar,
&Net_SignonState,
&SVC_Print,
&SVC_ServerInfo,
&SVC_SendTable,
&SVC_ClassInfo,
&SVC_SetPause,
&SVC_CreateStringTable,
&SVC_UpdateStringTable,
&SVC_VoiceInit,
&SVC_VoiceData,
&SVC_HLTV,
&SVC_Sounds,
&SVC_SetView,
&SVC_FixAngle,
&SVC_CrosshairAngle,
&SVC_BSPDecal,
&SVC_TerrainMod,
&SVC_UserMessage,
&SVC_EntityMessage,
&SVC_GameEvent,
&SVC_PacketEntities,
&SVC_TempEntities,
&SVC_Prefetch,
&SVC_Menu,
&SVC_GameEventList,
&SVC_GetCvarValue
};
assert(msgType < NUM_MESSAGES);
netMsgHandler[msgType](bitbuf);
}
<commit_msg>Modified SVC_ServerInfo for current protocol<commit_after>
#include "netmessages.h"
#include "demofilebitbuf.h"
#include <cassert>
namespace math
{
unsigned int log2(unsigned int value)
{
unsigned int res = 0;
while (value >>= 1)
++res;
return res;
}
unsigned int Bits2Bytes(unsigned int bits)
{
return ((bits + 7) >> 3);
}
}
void Net_NOP(CBitRead& bitbuf)
{
// nothing
}
void Net_Disconnect(CBitRead& bitbuf)
{
char message[1024];
bitbuf.ReadString(message, sizeof(message));
}
void Net_File(CBitRead& bitbuf)
{
const unsigned int transferID = bitbuf.ReadUBitLong(32);
char filename[1024];
bitbuf.ReadString(filename, sizeof(filename));
const bool isRequest = bitbuf.ReadOneBit() != 0;
}
void Net_Tick(CBitRead& bitbuf)
{
static const float NET_TICK_SCALEUP = 100000.0f;
const int tick = bitbuf.ReadLong();
const float hostFrameTime = (float)bitbuf.ReadUBitLong(16) / NET_TICK_SCALEUP;
const float hostFrameTimeStdDev = (float)bitbuf.ReadUBitLong(16) / NET_TICK_SCALEUP;
}
void Net_StringCmd(CBitRead& bitbuf)
{
char commandBuffer[1024];
bitbuf.ReadString(commandBuffer, sizeof(commandBuffer));
}
void Net_SetConVar(CBitRead& bitbuf)
{
typedef struct cvar_s
{
char name[MAX_OSPATH];
char value[MAX_OSPATH];
} cvar_t;
const int numVars = bitbuf.ReadByte();
cvar_t cvar;
for (int i = 0; i < numVars; ++i)
{
bitbuf.ReadString(cvar.name, sizeof(cvar.name));
bitbuf.ReadString(cvar.value, sizeof(cvar.value));
}
}
void Net_SignonState(CBitRead& bitbuf)
{
const int signonState = bitbuf.ReadByte();
//assert(signonState == SIGNONSTATE_PRESPAWN);
const int spawnCount = bitbuf.ReadLong();
}
void SVC_Print(CBitRead& bitbuf)
{
char textBuffer[2048];
bitbuf.ReadString(textBuffer, sizeof(textBuffer));
}
void SVC_ServerInfo(CBitRead& bitbuf)
{
const int protocol = bitbuf.ReadShort(); // protocol version
const int serverCount = bitbuf.ReadLong(); // number of changelevels since server start
const bool isHLTV = bitbuf.ReadOneBit() != 0; // HLTV server ?
const bool isDedicated = bitbuf.ReadOneBit() != 0; // dedicated server ?
const int clientCRC = bitbuf.ReadLong(); // client.dll CRC server is using
const int maxClasses = bitbuf.ReadWord(); // max number of server classes
if (protocol <= 17)
{
const int mapCRC = bitbuf.ReadLong(); // server map CRC
}
else
{
char unknown[16];
bitbuf.ReadBytes(unknown, sizeof(unknown));
}
const int playerSlot = bitbuf.ReadByte(); // our client slot number
const int maxClients = bitbuf.ReadByte(); // max number of clients on server
const float tickInterval = bitbuf.ReadFloat(); // server tick interval
const char os = bitbuf.ReadChar(); // 'l' = linux, 'w' = Win32
char gameDir[MAX_OSPATH]; // game directory eg "tf2"
char mapName[MAX_OSPATH]; // name of current map
char skyName[MAX_OSPATH]; // name of current skybox
char hostName[MAX_OSPATH]; // host name
bitbuf.ReadString(gameDir, sizeof(gameDir));
bitbuf.ReadString(mapName, sizeof(mapName));
bitbuf.ReadString(skyName, sizeof(skyName));
bitbuf.ReadString(hostName, sizeof(hostName));
// TODO:
// if (this.something() > 15)
// {
const bool unknown = bitbuf.ReadOneBit() != 0;
// }
}
void SVC_SendTable(CBitRead& bitbuf)
{
const bool needsDecoder = bitbuf.ReadOneBit() != 0;
const int dataLengthBits = bitbuf.ReadShort();
bitbuf.SeekRelative(dataLengthBits);
}
void SVC_ClassInfo(CBitRead& bitbuf)
{
typedef struct class_s
{
int classID;
char datatablename[256];
char classname[256];
} class_t;
const int numServerClasses = bitbuf.ReadShort();
const int nServerClassBits = math::log2(numServerClasses) + 1;
// if true, client creates own SendTables & classinfos from game.dll
const bool createOnClient = bitbuf.ReadOneBit() != 0;
if (!createOnClient)
{
class_t serverclass;
for (int i = 0; i < numServerClasses; ++i)
{
serverclass.classID = bitbuf.ReadUBitLong(nServerClassBits);
bitbuf.ReadString(serverclass.classname, sizeof(serverclass.classname));
bitbuf.ReadString(serverclass.datatablename, sizeof(serverclass.datatablename));
}
}
}
void SVC_SetPause(CBitRead& bitbuf)
{
const bool paused = bitbuf.ReadOneBit() != 0;
}
void SVC_CreateStringTable(CBitRead& bitbuf)
{
if (bitbuf.PeekUBitLong(8) == ':')
{
bitbuf.ReadByte();
}
char tableName[256];
bitbuf.ReadString(tableName, sizeof(tableName));
const int maxEntries = bitbuf.ReadWord();
const int encodeBits = math::log2(maxEntries);
const int numEntries = bitbuf.ReadUBitLong(encodeBits + 1);
const int lengthInBits = bitbuf.ReadUBitLong(NET_MAX_PALYLOAD_BITS + 3);
const bool userDataFixedSize = bitbuf.ReadOneBit() != 0;
if (userDataFixedSize)
{
const int userDataSize = bitbuf.ReadUBitLong(12);
const int userDataSizeBits = bitbuf.ReadUBitLong(4);
}
bitbuf.SeekRelative(lengthInBits);
}
void SVC_UpdateStringTable(CBitRead& bitbuf)
{
const int tableId = bitbuf.ReadUBitLong(math::log2(MAX_TABLES));
const int numChangedEntries = (bitbuf.ReadOneBit() != 0) ? bitbuf.ReadWord() : 1;
const int lengthInBits = bitbuf.ReadUBitLong(20);
bitbuf.SeekRelative(lengthInBits);
}
void SVC_VoiceInit(CBitRead& bitbuf)
{
char voiceCodec[MAX_OSPATH]; // used voice codec .dll
bitbuf.ReadString(voiceCodec, sizeof(voiceCodec));
const int quality = bitbuf.ReadByte(); // custom quality setting
}
void SVC_VoiceData(CBitRead& bitbuf)
{
const int fromClientIndex = bitbuf.ReadByte();
const bool proximity = !!bitbuf.ReadByte();
const int lengthInBits = bitbuf.ReadWord();
bitbuf.SeekRelative(lengthInBits);
}
void SVC_HLTV(CBitRead& bitbuf)
{
//const int state = bitbuf.ReadByte();
assert(false);
}
void SVC_Sounds(CBitRead& bitbuf)
{
const bool reliableSound = bitbuf.ReadOneBit() != 0;
int numSounds;
int lengthInBits;
if (reliableSound)
{
numSounds = 1;
lengthInBits = bitbuf.ReadUBitLong(8);
}
else
{
numSounds = bitbuf.ReadUBitLong(8);
lengthInBits = bitbuf.ReadUBitLong(16);
}
bitbuf.SeekRelative(lengthInBits);
}
void SVC_SetView(CBitRead& bitbuf)
{
const int entIndex = bitbuf.ReadUBitLong(MAX_EDICT_BITS);
}
void SVC_FixAngle(CBitRead& bitbuf)
{
const bool relative = bitbuf.ReadOneBit() != 0;
const float x = bitbuf.ReadBitAngle(16);
const float y = bitbuf.ReadBitAngle(16);
const float z = bitbuf.ReadBitAngle(16);
}
void SVC_CrosshairAngle(CBitRead& bitbuf)
{
const float x = bitbuf.ReadBitAngle(16);
const float y = bitbuf.ReadBitAngle(16);
const float z = bitbuf.ReadBitAngle(16);
}
void SVC_BSPDecal(CBitRead& bitbuf)
{
Vector pos;
bitbuf.ReadBitVec3Coord(pos);
const int decalTextureIndex = bitbuf.ReadUBitLong(MAX_DECAL_INDEX_BITS);
if (bitbuf.ReadOneBit() != 0)
{
const int entIndex = bitbuf.ReadUBitLong(MAX_EDICT_BITS);
const int modelIndex = bitbuf.ReadUBitLong(SP_MODEL_INDEX_BITS);
}
else
{
const int entIndex = 0;
const int modelIndex = 0;
}
const bool lowPriority = bitbuf.ReadOneBit() != 0;
}
void SVC_TerrainMod(CBitRead& bitbuf)
{
assert(false);
}
void SVC_UserMessage(CBitRead& bitbuf)
{
const int msgType = bitbuf.ReadByte();
// max 256 * 8 bits, see MAX_USER_MSG_DATA
const int lengthInBits = bitbuf.ReadUBitLong(11);
bitbuf.SeekRelative(lengthInBits);
}
void SVC_EntityMessage(CBitRead& bitbuf)
{
const int entIndex = bitbuf.ReadUBitLong(MAX_EDICT_BITS);
const int classID = bitbuf.ReadUBitLong(MAX_SERVER_CLASS_BITS);
// max 256 * 8 bits
const int lengthInBits = bitbuf.ReadUBitLong(11);
bitbuf.SeekRelative(lengthInBits);
}
void SVC_GameEvent(CBitRead& bitbuf)
{
const int lengthInBits = bitbuf.ReadUBitLong(11);
//uint32 eventId = bitbuf.ReadUBitLong(9);
bitbuf.SeekRelative(lengthInBits);
}
void SVC_PacketEntities(CBitRead& bitbuf)
{
const int maxEntries = bitbuf.ReadUBitLong(MAX_EDICT_BITS);
const bool isDelta = bitbuf.ReadOneBit() != 0;
if (isDelta)
{
const int deltaFrom = bitbuf.ReadLong();
}
else
{
const int deltaFrom = -1;
}
const int numBaseline = bitbuf.ReadUBitLong(1);
const int numUpdatedEntries = bitbuf.ReadUBitLong(MAX_EDICT_BITS);
const int lengthInBits = bitbuf.ReadUBitLong(DELTASIZE_BITS);
const bool updateBaseline = bitbuf.ReadOneBit() != 0;
bitbuf.SeekRelative(lengthInBits);
}
void SVC_TempEntities(CBitRead& bitbuf)
{
const int numEntries = bitbuf.ReadUBitLong(EVENT_INDEX_BITS);
const int lengthInBits = bitbuf.ReadUBitLong(NET_MAX_PALYLOAD_BITS);
bitbuf.SeekRelative(lengthInBits);
}
void SVC_Prefetch(CBitRead& bitbuf)
{
enum
{
SOUND = 0,
};
const short type = SOUND; // bitbuf.ReadUBitLong(1);
const short soundIndex = bitbuf.ReadUBitLong(MAX_SOUND_INDEX_BITS);
}
void SVC_Menu(CBitRead& bitbuf)
{
typedef enum
{
DIALOG_MSG = 0, // just an on screen message
DIALOG_MENU, // an options menu
DIALOG_TEXT, // a richtext dialog
DIALOG_ENTRY, // an entry box
DIALOG_ASKCONNECT // Ask the client to connect to a specified IP address. Only the "time" and "title" keys are used.
} DIALOG_TYPE;
DIALOG_TYPE type = (DIALOG_TYPE)bitbuf.ReadShort();
const int lengthInBytes = bitbuf.ReadWord();
bitbuf.SeekRelative(lengthInBytes * 8);
}
void SVC_GameEventList(CBitRead& bitbuf)
{
const int numEvents = bitbuf.ReadUBitLong(MAX_EVENT_BITS);
for (int i = 0; i < numEvents; ++i)
{
const int id = bitbuf.ReadUBitLong(MAX_EVENT_BITS);
char name[MAX_EVENT_NAME_LENGTH];
bitbuf.ReadString(name, sizeof(name));
printf("%s\n", name);
assert(false);
// gameeventmanager.cpp ParseEventList
}
const int lengthInBits = bitbuf.ReadUBitLong(20);
bitbuf.SeekRelative(lengthInBits);
}
void SVC_GetCvarValue(CBitRead& bitbuf)
{
typedef int QueryCvarCookie_t;
QueryCvarCookie_t cookie = bitbuf.ReadSBitLong(32);
char cvarName[256];
bitbuf.ReadString(cvarName, sizeof(cvarName));
}
static const int NUM_MESSAGES = static_cast<uint8_t>(NetMsg::SVC_LASTMSG) + 1;
void ProcessNetMsg(const std::uint32_t msgType, CBitRead& bitbuf)
{
static NetMsgFn netMsgHandler[NUM_MESSAGES] =
{
&Net_NOP,
&Net_Disconnect,
&Net_File,
&Net_Tick,
&Net_StringCmd,
&Net_SetConVar,
&Net_SignonState,
&SVC_Print,
&SVC_ServerInfo,
&SVC_SendTable,
&SVC_ClassInfo,
&SVC_SetPause,
&SVC_CreateStringTable,
&SVC_UpdateStringTable,
&SVC_VoiceInit,
&SVC_VoiceData,
&SVC_HLTV,
&SVC_Sounds,
&SVC_SetView,
&SVC_FixAngle,
&SVC_CrosshairAngle,
&SVC_BSPDecal,
&SVC_TerrainMod,
&SVC_UserMessage,
&SVC_EntityMessage,
&SVC_GameEvent,
&SVC_PacketEntities,
&SVC_TempEntities,
&SVC_Prefetch,
&SVC_Menu,
&SVC_GameEventList,
&SVC_GetCvarValue
};
assert(msgType < NUM_MESSAGES);
netMsgHandler[msgType](bitbuf);
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* 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 Willow Garage, Inc. 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 OWNER 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.
*
* $Id$
*
*/
#ifndef PCL_FILTERS_IMPL_STATISTICAL_OUTLIER_REMOVAL_H_
#define PCL_FILTERS_IMPL_STATISTICAL_OUTLIER_REMOVAL_H_
#include "pcl/filters/statistical_outlier_removal.h"
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::StatisticalOutlierRemoval<PointT>::applyFilter (PointCloud &output)
{
if (std_mul_ == 0.0)
{
PCL_ERROR ("[pcl::%s::applyFilter] Standard deviation multiplier not set!\n", getClassName ().c_str ());
output.width = output.height = 0;
output.points.clear ();
return;
}
// Initialize the spatial locator
//initTree (spatial_locator_type_, tree_, k_);
// TODO: fix this
tree_.reset (new KdTreeFLANN<PointT> ());
// Send the input dataset to the spatial locator
tree_->setInputCloud (input_);
// Allocate enough space to hold the results
std::vector<int> nn_indices (mean_k_);
std::vector<float> nn_dists (mean_k_);
std::vector<float> distances (indices_->size ());
// Go over all the points and calculate the mean or smallest distance
for (size_t cp = 0; cp < indices_->size (); ++cp)
{
if (!pcl_isfinite (input_->points[(*indices_)[cp]].x) ||
!pcl_isfinite (input_->points[(*indices_)[cp]].y) ||
!pcl_isfinite (input_->points[(*indices_)[cp]].z))
{
distances[cp] = 0;
continue;
}
if (tree_->nearestKSearch ((*indices_)[cp], mean_k_, nn_indices, nn_dists) == 0)
{
distances[cp] = 0;
PCL_WARN ("[pcl::%s::applyFilter] Searching for the closest %d neighbors failed.\n", getClassName ().c_str (), mean_k_);
continue;
}
// Minimum distance (if mean_k_ == 2) or mean distance
double dist_sum = 0;
for (int j = 1; j < mean_k_; ++j)
dist_sum += sqrt (nn_dists[j]);
distances[cp] = dist_sum / (mean_k_-1);
}
// Estimate the mean and the standard deviation of the distance vector
double mean, stddev;
getMeanStd (distances, mean, stddev);
double distance_threshold = mean + std_mul_ * stddev; // a distance that is bigger than this signals an outlier
output.points.resize (input_->points.size ()); // reserve enough space
removed_indices_->resize (input_->points.size ());
// Build a new cloud by neglecting outliers
int nr_p = 0;
int nr_removed_p = 0;
for (size_t cp = 0; cp < indices_->size (); ++cp)
{
if (negative_)
{
if (distances[cp] <= distance_threshold)
{
if (extract_removed_indices_)
{
(*removed_indices_)[nr_removed_p] = cp;
nr_removed_p++;
}
continue;
}
}
else
{
if (distances[cp] > distance_threshold)
{
if (extract_removed_indices_)
{
(*removed_indices_)[nr_removed_p] = cp;
nr_removed_p++;
}
continue;
}
}
output.points[nr_p++] = input_->points[(*indices_)[cp]];
}
output.points.resize (nr_p);
output.width = nr_p;
output.height = 1;
output.is_dense = true; // nearestKSearch filters invalid points
removed_indices_->resize (nr_removed_p);
}
#define PCL_INSTANTIATE_StatisticalOutlierRemoval(T) template class PCL_EXPORTS pcl::StatisticalOutlierRemoval<T>;
#endif // PCL_FILTERS_IMPL_STATISTICAL_OUTLIER_REMOVAL_H_
<commit_msg>we do not care for the results to be sorted when using StatisticalAnalysis outlier removal<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* 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 Willow Garage, Inc. 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 OWNER 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.
*
* $Id$
*
*/
#ifndef PCL_FILTERS_IMPL_STATISTICAL_OUTLIER_REMOVAL_H_
#define PCL_FILTERS_IMPL_STATISTICAL_OUTLIER_REMOVAL_H_
#include "pcl/filters/statistical_outlier_removal.h"
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::StatisticalOutlierRemoval<PointT>::applyFilter (PointCloud &output)
{
if (std_mul_ == 0.0)
{
PCL_ERROR ("[pcl::%s::applyFilter] Standard deviation multiplier not set!\n", getClassName ().c_str ());
output.width = output.height = 0;
output.points.clear ();
return;
}
// Initialize the spatial locator
//initTree (spatial_locator_type_, tree_, k_);
// TODO: fix this
tree_.reset (new KdTreeFLANN<PointT> (false));
// Send the input dataset to the spatial locator
tree_->setInputCloud (input_);
// Allocate enough space to hold the results
std::vector<int> nn_indices (mean_k_);
std::vector<float> nn_dists (mean_k_);
std::vector<float> distances (indices_->size ());
// Go over all the points and calculate the mean or smallest distance
for (size_t cp = 0; cp < indices_->size (); ++cp)
{
if (!pcl_isfinite (input_->points[(*indices_)[cp]].x) ||
!pcl_isfinite (input_->points[(*indices_)[cp]].y) ||
!pcl_isfinite (input_->points[(*indices_)[cp]].z))
{
distances[cp] = 0;
continue;
}
if (tree_->nearestKSearch ((*indices_)[cp], mean_k_, nn_indices, nn_dists) == 0)
{
distances[cp] = 0;
PCL_WARN ("[pcl::%s::applyFilter] Searching for the closest %d neighbors failed.\n", getClassName ().c_str (), mean_k_);
continue;
}
// Minimum distance (if mean_k_ == 2) or mean distance
double dist_sum = 0;
for (int j = 1; j < mean_k_; ++j)
dist_sum += sqrt (nn_dists[j]);
distances[cp] = dist_sum / (mean_k_-1);
}
// Estimate the mean and the standard deviation of the distance vector
double mean, stddev;
getMeanStd (distances, mean, stddev);
double distance_threshold = mean + std_mul_ * stddev; // a distance that is bigger than this signals an outlier
output.points.resize (input_->points.size ()); // reserve enough space
removed_indices_->resize (input_->points.size ());
// Build a new cloud by neglecting outliers
int nr_p = 0;
int nr_removed_p = 0;
for (size_t cp = 0; cp < indices_->size (); ++cp)
{
if (negative_)
{
if (distances[cp] <= distance_threshold)
{
if (extract_removed_indices_)
{
(*removed_indices_)[nr_removed_p] = cp;
nr_removed_p++;
}
continue;
}
}
else
{
if (distances[cp] > distance_threshold)
{
if (extract_removed_indices_)
{
(*removed_indices_)[nr_removed_p] = cp;
nr_removed_p++;
}
continue;
}
}
output.points[nr_p++] = input_->points[(*indices_)[cp]];
}
output.points.resize (nr_p);
output.width = nr_p;
output.height = 1;
output.is_dense = true; // nearestKSearch filters invalid points
removed_indices_->resize (nr_removed_p);
}
#define PCL_INSTANTIATE_StatisticalOutlierRemoval(T) template class PCL_EXPORTS pcl::StatisticalOutlierRemoval<T>;
#endif // PCL_FILTERS_IMPL_STATISTICAL_OUTLIER_REMOVAL_H_
<|endoftext|>
|
<commit_before>#include "poScene/ui/ButtonSet.h"
using namespace std::placeholders;
namespace po
{
namespace scene
{
namespace ui
{
ButtonSetRef ButtonSet::create()
{
return ButtonSetRef( new ButtonSet() );
}
ButtonSet::ButtonSet()
: mType( Type::RADIO )
{
}
// Add Buttons
void ButtonSet::addButton( ButtonRef button, bool addToView )
{
button->setType( Button::Type::TOGGLE );
mButtons.push_back( button );
mButtonConnections[button] += button->getSignalToggled().connect( std::bind( &ButtonSet::buttonToggledHandler, this, ::_1 ) );
if( addToView ) {
getView()->addSubview( button );
}
}
void ButtonSet::addButtons( const std::vector<ButtonRef>& buttons, bool addToView )
{
for( auto& button : buttons ) {
addButton( button, addToView );
}
}
// Remove Buttons
void ButtonSet::removeButton( ButtonRef button )
{
std::vector<ButtonRef>::iterator iter = std::find( mButtons.begin(), mButtons.end(), button );
if( iter != mButtons.end() ) {
mButtons.erase( iter );
mButtonConnections.erase( *iter );
if( button->getSuperview() == getView() ) {
button->removeFromSuperview();
}
}
}
void ButtonSet::removeButtons( const std::vector<ButtonRef>& buttons )
{
for( auto& button : buttons ) {
removeButton( button );
}
}
// Return a list of selected buttons
// If radio should only be one, checkbox could be multiple
std::vector<ButtonRef> ButtonSet::getSelectedButtons()
{
std::vector<ButtonRef> selectedButtons;
for( auto& button : mButtons ) {
if( button->getState() == Button::State::SELECTED ) {
selectedButtons.push_back( button );
}
}
return selectedButtons;
}
void ButtonSet::selectButton( ButtonRef selectedButton )
{
if( mType == Type::RADIO ) {
for( auto& button : mButtons ) {
if( button->getState() == Button::State::SELECTED && button != selectedButton ) {
button->setState( Button::State::NORMAL );
if( !mDelegate.expired() ) {
ButtonSetRef self = std::dynamic_pointer_cast<ButtonSet>( shared_from_this() );
mDelegate.lock()->buttonSetDidDeselectButton( self, button );
}
}
}
}
if( selectedButton->getState() != Button::State::SELECTED ) {
selectedButton->setState( Button::State::SELECTED );
}
if( !mDelegate.expired() ) {
ButtonSetRef self = std::dynamic_pointer_cast<ButtonSet>( shared_from_this() );
mDelegate.lock()->buttonSetDidSelectButton( self, selectedButton );
}
}
void ButtonSet::selectAllButtons()
{
CI_ASSERT_MSG( mType == Type::CHECKBOX, "You can not select all buttons in a radio button set." );
for( auto& button : mButtons ) {
selectButton( button );
}
}
void ButtonSet::deselectAllButtons()
{
}
// -------------------------------
// Event listeners
void ButtonSet::buttonToggledHandler( ButtonRef button )
{
switch( mType ) {
case Type::RADIO:
// Don't allow buttons to be de-selected on their own
if( button->getState() == Button::State::NORMAL ) {
button->setState( Button::State::SELECTED );
}
// Previously unselected button selected
else {
selectButton( button );
}
return;
}
}
}
}
}<commit_msg>adding deselect method to button set<commit_after>#include "poScene/ui/ButtonSet.h"
using namespace std::placeholders;
namespace po
{
namespace scene
{
namespace ui
{
ButtonSetRef ButtonSet::create()
{
return ButtonSetRef( new ButtonSet() );
}
ButtonSet::ButtonSet()
: mType( Type::RADIO )
{
}
// Add Buttons
void ButtonSet::addButton( ButtonRef button, bool addToView )
{
button->setType( Button::Type::TOGGLE );
mButtons.push_back( button );
mButtonConnections[button] += button->getSignalToggled().connect( std::bind( &ButtonSet::buttonToggledHandler, this, ::_1 ) );
if( addToView ) {
getView()->addSubview( button );
}
}
void ButtonSet::addButtons( const std::vector<ButtonRef>& buttons, bool addToView )
{
for( auto& button : buttons ) {
addButton( button, addToView );
}
}
// Remove Buttons
void ButtonSet::removeButton( ButtonRef button )
{
std::vector<ButtonRef>::iterator iter = std::find( mButtons.begin(), mButtons.end(), button );
if( iter != mButtons.end() ) {
mButtons.erase( iter );
mButtonConnections.erase( *iter );
if( button->getSuperview() == getView() ) {
button->removeFromSuperview();
}
}
}
void ButtonSet::removeButtons( const std::vector<ButtonRef>& buttons )
{
for( auto& button : buttons ) {
removeButton( button );
}
}
// Return a list of selected buttons
// If radio should only be one, checkbox could be multiple
std::vector<ButtonRef> ButtonSet::getSelectedButtons()
{
std::vector<ButtonRef> selectedButtons;
for( auto& button : mButtons ) {
if( button->getState() == Button::State::SELECTED ) {
selectedButtons.push_back( button );
}
}
return selectedButtons;
}
void ButtonSet::selectButton( ButtonRef selectedButton )
{
if( mType == Type::RADIO ) {
for( auto& button : mButtons ) {
if( button->getState() == Button::State::SELECTED && button != selectedButton ) {
button->setState( Button::State::NORMAL );
if( !mDelegate.expired() ) {
ButtonSetRef self = std::dynamic_pointer_cast<ButtonSet>( shared_from_this() );
mDelegate.lock()->buttonSetDidDeselectButton( self, button );
}
}
}
}
if( selectedButton->getState() != Button::State::SELECTED ) {
selectedButton->setState( Button::State::SELECTED );
}
if( !mDelegate.expired() ) {
ButtonSetRef self = std::dynamic_pointer_cast<ButtonSet>( shared_from_this() );
mDelegate.lock()->buttonSetDidSelectButton( self, selectedButton );
}
}
void ButtonSet::deselectButton( ButtonRef deSelectedButton )
{
deSelectedButton->setState( Button::State::NORMAL );
if( !mDelegate.expired() ) {
ButtonSetRef self = std::dynamic_pointer_cast<ButtonSet>( shared_from_this() );
mDelegate.lock()->buttonSetDidDeselectButton( self, deSelectedButton );
}
}
void ButtonSet::selectAllButtons()
{
CI_ASSERT_MSG( mType == Type::CHECKBOX, "You can not select all buttons in a radio button set." );
for( auto& button : mButtons ) {
selectButton( button );
}
}
void ButtonSet::deselectAllButtons()
{
for( auto& button : mButtons ) {
deselectButton( button );
}
}
// -------------------------------
// Event listeners
void ButtonSet::buttonToggledHandler( ButtonRef button )
{
switch( mType ) {
case Type::RADIO:
// Don't allow buttons to be de-selected on their own
if( button->getState() == Button::State::NORMAL ) {
button->setState( Button::State::SELECTED );
}
// Previously unselected button selected
else {
selectButton( button );
}
return;
}
}
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
#define CATCH_CONFIG_RUNNER
#include "mfem.hpp"
#include "catch.hpp"
int main(int argc, char *argv[])
{
#ifdef MFEM_USE_MPI
mfem::MPI_Session mpi;
#endif
// There must be exactly one instance.
Catch::Session session;
// Apply provided command line arguments.
int r = session.applyCommandLine(argc, argv);
if (r != 0)
{
return r;
}
#ifdef MFEM_USE_MPI
// Force to only run parallel tests if the tests
// are executed on multiple processors.
if (mpi.WorldSize() > 1)
{
auto cfg = session.configData();
cfg.testsOrTags.push_back("[Parallel]");
session.useConfigData(cfg);
if (mpi.Root())
{
mfem::out
<< "WARNING: Only running the [Parallel] label on MPI ranks > 1." << std::endl;
}
}
#endif
int result = session.run();
return result;
}
<commit_msg>Modification to which unit tests are run<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
#define CATCH_CONFIG_RUNNER
#include "mfem.hpp"
#include "catch.hpp"
int main(int argc, char *argv[])
{
// There must be exactly one instance.
Catch::Session session;
// Apply provided command line arguments.
int r = session.applyCommandLine(argc, argv);
if (r != 0)
{
return r;
}
#ifdef MFEM_USE_MPI
mfem::MPI_Session mpi;
// Force tests not tagged as [Parallel] to run only on MPI rank 0
if (mpi.WorldRank() > 0)
{
auto cfg = session.configData();
cfg.testsOrTags.push_back("[Parallel]");
session.useConfigData(cfg);
}
if (mpi.WorldSize() > 1 && mpi.Root())
{
mfem::out
<< "WARNING: Only running the [Parallel] label on MPI ranks > 1."
<< std::endl;
}
#endif
int result = session.run();
return result;
}
<|endoftext|>
|
<commit_before>#pragma once
#include "file64_api.hpp"
#include "../../base/base.hpp"
#include "../../std/string.hpp"
#include "../../std/target_os.hpp"
#include "../../std/noncopyable.hpp"
#ifdef OMIM_OS_TIZEN
namespace Tizen
{
namespace Io
{
class File;
}
}
#endif
namespace my {
class FileData: private noncopyable
{
public:
/// @note Do not change order (@see FileData::FileData).
enum Op { OP_READ = 0, OP_WRITE_TRUNCATE, OP_WRITE_EXISTING, OP_APPEND };
FileData(string const & fileName, Op op);
~FileData();
uint64_t Size() const;
uint64_t Pos() const;
void Seek(uint64_t pos);
void Read(uint64_t pos, void * p, size_t size);
void Write(void const * p, size_t size);
void Flush();
void Truncate(uint64_t sz);
string GetName() const { return m_FileName; }
private:
#ifdef OMIM_OS_TIZEN
Tizen::Io::File * m_File;
#else
FILE * m_File;
#endif
string m_FileName;
Op m_Op;
string GetErrorProlog() const;
};
bool GetFileSize(string const & fName, uint64_t & sz);
bool DeleteFileX(string const & fName);
bool RenameFileX(string const & fOld, string const & fNew);
/// @return false if copy fails. DO NOT THROWS exceptions
bool CopyFileX(string const & fOld, string const & fNew);
bool IsEqualFiles(string const & firstFile, string const & secondFile);
}
<commit_msg>[Tizen] change position of include<commit_after>#pragma once
#include "../../std/target_os.hpp"
#include "file64_api.hpp"
#include "../../base/base.hpp"
#include "../../std/string.hpp"
#include "../../std/noncopyable.hpp"
#ifdef OMIM_OS_TIZEN
namespace Tizen
{
namespace Io
{
class File;
}
}
#endif
namespace my {
class FileData: private noncopyable
{
public:
/// @note Do not change order (@see FileData::FileData).
enum Op { OP_READ = 0, OP_WRITE_TRUNCATE, OP_WRITE_EXISTING, OP_APPEND };
FileData(string const & fileName, Op op);
~FileData();
uint64_t Size() const;
uint64_t Pos() const;
void Seek(uint64_t pos);
void Read(uint64_t pos, void * p, size_t size);
void Write(void const * p, size_t size);
void Flush();
void Truncate(uint64_t sz);
string GetName() const { return m_FileName; }
private:
#ifdef OMIM_OS_TIZEN
Tizen::Io::File * m_File;
#else
FILE * m_File;
#endif
string m_FileName;
Op m_Op;
string GetErrorProlog() const;
};
bool GetFileSize(string const & fName, uint64_t & sz);
bool DeleteFileX(string const & fName);
bool RenameFileX(string const & fOld, string const & fNew);
/// @return false if copy fails. DO NOT THROWS exceptions
bool CopyFileX(string const & fOld, string const & fNew);
bool IsEqualFiles(string const & firstFile, string const & secondFile);
}
<|endoftext|>
|
<commit_before>#include <rxx.h>
#include <usenet.h>
#include <group.h>
grouplist::grouplist ()
{
it = group_db->enumerate();
d = it->nextElement();
};
static rxx listrx ("^(\\d+)(<[^>]+>)([^:]+):");
void
grouplist::next (str *f, unsigned long *i)
{
ptr<dbrec> data = group_db->lookup (d->key);
char *c = data->value;
int len = data->len, cnt = 0;
for (; listrx.search (str (c, len))
; c += listrx.len (0), len -= listrx.len (0) )
cnt++;
*f = str (d->key->value, d->key->len);
*i = cnt;
d = it->nextElement();
}
newsgroup::newsgroup () :
rec (NULL),
cur_art (0),
start (0),
stop (0),
c (NULL),
len (0)
{
}
int
newsgroup::open (str g)
{
rec = group_db->lookup (New refcounted<dbrec> (g, g.len ()));
if (rec == NULL)
return -1;
warn << "group " << g << " rec len " << rec->len << "\n";
group_name = g;
cur_art = 1;
return 0;
}
int
newsgroup::open (str g, unsigned long *count,
unsigned long *first, unsigned long *last)
{
if (open (g) < 0)
return -1;
char *c = rec->value;
int len = rec->len;
warn << "xv " << str (c, len) << "\n";
*count = 0;
*first = 0;
*last = 0;
for (; listrx.search (str (c, len))
; c += listrx.len (0), len -= listrx.len (0) ) {
if (*count == 0)
*first = strtoul (listrx[1], NULL, 10);
(*count)++;
*last = strtoul (listrx[1], NULL, 10);
}
return 0;
}
static rxx listrxend ("(\\d+)(<[^>]+>)([^:]+):$");
void
newsgroup::addid (str msgid, chordID ID)
{
assert (rec);
str old (rec->value, rec->len), updated;
ptr<dbrec> k = New refcounted<dbrec> (group_name, group_name.len ());
if (listrxend.search (old))
updated = strbuf () << old <<
strtoul (listrxend[1], NULL, 10) + 1 << msgid << ID << ":";
else
updated = strbuf () << "1" << msgid << ID << ":";
rec = New refcounted<dbrec> (updated, updated.len ());
group_db->insert (k, rec);
}
// now returns the chordid
chordID
newsgroup::getid (unsigned long index)
{
if (rec == NULL)
return 0;
char *c = rec->value;
int len = rec->len;
for (; listrx.search (str (c, len))
; c += listrx.len (0), len -= listrx.len (0) ) {
if (index == strtoul (listrx[1], NULL, 10))
return bigint (listrx[3], 16);
else if (index < strtoul (listrx[1], NULL, 10))
return 0;
}
return 0;
}
static rxx getchordid ("^X-ChordID: (.+)$", "m");
chordID
newsgroup::getid (str msgid)
{
ptr<dbrec> key, d;
key = New refcounted<dbrec> (msgid, msgid.len ());
d = header_db->lookup (key);
if (d && getchordid.search (str (d->value, d->len)))
return bigint (getchordid[1], 16);
else
return 0;
}
void
newsgroup::xover (unsigned long a, unsigned long b)
{
start = a;
stop = b;
assert (rec);
c = rec->value;
len = rec->len;
while (listrx.search (str (c, len)) &&
(strtoul (listrx[1], NULL, 10) < start))
c += listrx.len (0), len -= listrx.len (0);
}
static rxx oversub ("Subject: (.+)\\r");
static rxx overfrom ("From: (.+)\\r");
static rxx overdate ("Date: (.+)\\r");
static rxx overmsgid ("Message-ID: (.+)\\r");
static rxx overref ("References: (.+)\\r");
static rxx overlines ("X-Lines: (.+)\\r");
str
tabfilter (str f)
{
unsigned int i;
strbuf out;
for (i=0; i<f.len (); i++)
if (f[i] == '\t')
out << " ";
else
out.tosuio ()->copy (f.cstr() + i, 1); // xxx bleh
return str (out);
}
// format: "subject\tauthor\tdate\t<msgid>\treferences\tsize\tlines"
strbuf
newsgroup::next (void)
{
ptr<dbrec> art;
strbuf resp;
resp << start << "\t";
if (more () && len > 0 &&
listrx.search (str (c, len))) {
art = header_db->lookup(New refcounted<dbrec> (listrx[2],
listrx[2].len ()));
warn << "mgs " << listrx[2] << "\n";
warn << "header " << str (art->value, art->len) << "\n";
if (art == NULL)
warn << "missing article\n";
else {
str msg (art->value, art->len); // xxx
if (oversub.search (msg) &&
overfrom.search (msg) &&
overdate.search (msg)) {
resp << tabfilter (oversub[1]) << "\t"
<< tabfilter (overfrom[1]) << "\t";
resp << tabfilter (overdate[1]) << "\t";
if (overmsgid.search (msg))
resp << tabfilter (overmsgid[1]) << "\t";
else
resp << tabfilter (listrx[2]) << "\t";
if (overref.search (msg))
resp << tabfilter (overref[1]);
resp << "\t" << art->len << "\t";
if (overlines.search (msg))
resp << tabfilter (overlines[1]);
else
resp << "0";
} else
warn << "msg parse error\n";
}
c += listrx.len (0);
len -= listrx.len (0);
}
start++;
resp << "\t\r\n";
return resp;
}
<commit_msg>Less verbose in the safe case. Avoid a null pointer deref in the process. Clean up the output sent to the remote end in the case of missing articles.<commit_after>#include <rxx.h>
#include <usenet.h>
#include <group.h>
grouplist::grouplist ()
{
it = group_db->enumerate();
d = it->nextElement();
};
static rxx listrx ("^(\\d+)(<[^>]+>)([^:]+):");
void
grouplist::next (str *f, unsigned long *i)
{
ptr<dbrec> data = group_db->lookup (d->key);
char *c = data->value;
int len = data->len, cnt = 0;
for (; listrx.search (str (c, len))
; c += listrx.len (0), len -= listrx.len (0) )
cnt++;
*f = str (d->key->value, d->key->len);
*i = cnt;
d = it->nextElement();
}
newsgroup::newsgroup () :
rec (NULL),
cur_art (0),
start (0),
stop (0),
c (NULL),
len (0)
{
}
int
newsgroup::open (str g)
{
rec = group_db->lookup (New refcounted<dbrec> (g, g.len ()));
if (rec == NULL)
return -1;
warn << "group " << g << " rec len " << rec->len << "\n";
group_name = g;
cur_art = 1;
return 0;
}
int
newsgroup::open (str g, unsigned long *count,
unsigned long *first, unsigned long *last)
{
if (open (g) < 0)
return -1;
char *c = rec->value;
int len = rec->len;
warn << "xv " << str (c, len) << "\n";
*count = 0;
*first = 0;
*last = 0;
for (; listrx.search (str (c, len))
; c += listrx.len (0), len -= listrx.len (0) ) {
if (*count == 0)
*first = strtoul (listrx[1], NULL, 10);
(*count)++;
*last = strtoul (listrx[1], NULL, 10);
}
return 0;
}
static rxx listrxend ("(\\d+)(<[^>]+>)([^:]+):$");
void
newsgroup::addid (str msgid, chordID ID)
{
assert (rec);
str old (rec->value, rec->len), updated;
ptr<dbrec> k = New refcounted<dbrec> (group_name, group_name.len ());
if (listrxend.search (old))
updated = strbuf () << old <<
strtoul (listrxend[1], NULL, 10) + 1 << msgid << ID << ":";
else
updated = strbuf () << "1" << msgid << ID << ":";
rec = New refcounted<dbrec> (updated, updated.len ());
group_db->insert (k, rec);
}
// now returns the chordid
chordID
newsgroup::getid (unsigned long index)
{
if (rec == NULL)
return 0;
char *c = rec->value;
int len = rec->len;
for (; listrx.search (str (c, len))
; c += listrx.len (0), len -= listrx.len (0) ) {
if (index == strtoul (listrx[1], NULL, 10))
return bigint (listrx[3], 16);
else if (index < strtoul (listrx[1], NULL, 10))
return 0;
}
return 0;
}
static rxx getchordid ("^X-ChordID: (.+)$", "m");
chordID
newsgroup::getid (str msgid)
{
ptr<dbrec> key, d;
key = New refcounted<dbrec> (msgid, msgid.len ());
d = header_db->lookup (key);
if (d && getchordid.search (str (d->value, d->len)))
return bigint (getchordid[1], 16);
else
return 0;
}
void
newsgroup::xover (unsigned long a, unsigned long b)
{
start = a;
stop = b;
assert (rec);
c = rec->value;
len = rec->len;
while (listrx.search (str (c, len)) &&
(strtoul (listrx[1], NULL, 10) < start))
c += listrx.len (0), len -= listrx.len (0);
}
static rxx oversub ("Subject: (.+)\\r");
static rxx overfrom ("From: (.+)\\r");
static rxx overdate ("Date: (.+)\\r");
static rxx overmsgid ("Message-ID: (.+)\\r");
static rxx overref ("References: (.+)\\r");
static rxx overlines ("X-Lines: (.+)\\r");
str
tabfilter (str f)
{
unsigned int i;
strbuf out;
for (i=0; i<f.len (); i++)
if (f[i] == '\t')
out << " ";
else
out.tosuio ()->copy (f.cstr() + i, 1); // xxx bleh
return str (out);
}
// format: "subject\tauthor\tdate\t<msgid>\treferences\tsize\tlines"
strbuf
newsgroup::next (void)
{
ptr<dbrec> art;
strbuf resp;
if (more () && len > 0 &&
listrx.search (str (c, len)))
{
art = header_db->lookup(New refcounted<dbrec> (listrx[2],
listrx[2].len ()));
if (art == NULL) {
warn << "missing article " << start << "\n";
} else {
str msg (art->value, art->len); // xxx
if (oversub.search (msg) &&
overfrom.search (msg) &&
overdate.search (msg)) {
resp << start << "\t";
resp << tabfilter (oversub[1]) << "\t"
<< tabfilter (overfrom[1]) << "\t";
resp << tabfilter (overdate[1]) << "\t";
if (overmsgid.search (msg))
resp << tabfilter (overmsgid[1]) << "\t";
else
resp << tabfilter (listrx[2]) << "\t";
if (overref.search (msg))
resp << tabfilter (overref[1]);
resp << "\t" << art->len << "\t";
if (overlines.search (msg))
resp << tabfilter (overlines[1]);
else
resp << "0";
} else {
warn << "msg parse error\n";
warn << "msg " << listrx[2] << "\n";
warn << "header " << msg << "\n";
}
}
c += listrx.len (0);
len -= listrx.len (0);
}
start++;
resp << "\t\r\n";
return resp;
}
<|endoftext|>
|
<commit_before>#include "yaml-cpp/yaml.h"
#include "yaml-cpp/eventhandler.h"
#include <fstream>
#include <iostream>
#include <vector>
struct Params {
bool hasFile;
std::string fileName;
};
Params ParseArgs(int argc, char **argv) {
Params p;
std::vector<std::string> args(argv + 1, argv + argc);
return p;
}
class NullEventHandler: public YAML::EventHandler
{
public:
virtual void OnDocumentStart(const YAML::Mark&) {}
virtual void OnDocumentEnd() {}
virtual void OnNull(const YAML::Mark&, YAML::anchor_t) {}
virtual void OnAlias(const YAML::Mark&, YAML::anchor_t) {}
virtual void OnScalar(const YAML::Mark&, const std::string&, YAML::anchor_t, const std::string&) {}
virtual void OnSequenceStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {}
virtual void OnSequenceEnd() {}
virtual void OnMapStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {}
virtual void OnMapEnd() {}
};
void parse(std::istream& input)
{
try {
#if YAML_CPP_OLD_API
YAML::Parser parser(input);
YAML::Node doc;
while(parser.GetNextDocument(doc)) {
YAML::Emitter emitter;
emitter << doc;
std::cout << emitter.c_str() << "\n";
}
#else
// TODO: Parse with new API
#endif
} catch(const YAML::Exception& e) {
std::cerr << e.what() << "\n";
}
}
int main(int argc, char **argv)
{
Params p = ParseArgs(argc, argv);
if(argc > 1) {
std::ifstream fin;
fin.open(argv[1]);
parse(fin);
} else {
parse(std::cin);
}
return 0;
}
<commit_msg>Set up util/parse for the new API<commit_after>#include "yaml-cpp/yaml.h"
#include "yaml-cpp/eventhandler.h"
#include <fstream>
#include <iostream>
#include <vector>
struct Params {
bool hasFile;
std::string fileName;
};
Params ParseArgs(int argc, char **argv) {
Params p;
std::vector<std::string> args(argv + 1, argv + argc);
return p;
}
class NullEventHandler: public YAML::EventHandler
{
public:
virtual void OnDocumentStart(const YAML::Mark&) {}
virtual void OnDocumentEnd() {}
virtual void OnNull(const YAML::Mark&, YAML::anchor_t) {}
virtual void OnAlias(const YAML::Mark&, YAML::anchor_t) {}
virtual void OnScalar(const YAML::Mark&, const std::string&, YAML::anchor_t, const std::string&) {}
virtual void OnSequenceStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {}
virtual void OnSequenceEnd() {}
virtual void OnMapStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {}
virtual void OnMapEnd() {}
};
void parse(std::istream& input)
{
try {
#if YAML_CPP_OLD_API
YAML::Parser parser(input);
YAML::Node doc;
while(parser.GetNextDocument(doc)) {
YAML::Emitter emitter;
emitter << doc;
std::cout << emitter.c_str() << "\n";
}
#else
YAML::Node doc = YAML::Parse(input);
std::cout << doc << "\n";
#endif
} catch(const YAML::Exception& e) {
std::cerr << e.what() << "\n";
}
}
int main(int argc, char **argv)
{
Params p = ParseArgs(argc, argv);
if(argc > 1) {
std::ifstream fin;
fin.open(argv[1]);
parse(fin);
} else {
parse(std::cin);
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include "default_tensor_engine.h"
#include <vespa/vespalib/eval/value.h>
#include <vespa/vespalib/eval/tensor_spec.h>
#include <vespa/vespalib/eval/operation_visitor.h>
#include "tensor.h"
#include "dense/dense_tensor_builder.h"
#include "default_tensor.h"
namespace vespalib {
namespace tensor {
using ErrorValue = eval::ErrorValue;
using DoubleValue = eval::DoubleValue;
using TensorValue = eval::TensorValue;
const DefaultTensorEngine DefaultTensorEngine::_engine;
eval::ValueType
DefaultTensorEngine::type_of(const Tensor &tensor) const
{
assert(&tensor.engine() == this);
const tensor::Tensor &my_tensor = static_cast<const tensor::Tensor &>(tensor);
return my_tensor.getType().as_value_type();
}
bool
DefaultTensorEngine::equal(const Tensor &a, const Tensor &b) const
{
assert(&a.engine() == this);
assert(&b.engine() == this);
const tensor::Tensor &my_a = static_cast<const tensor::Tensor &>(a);
const tensor::Tensor &my_b = static_cast<const tensor::Tensor &>(b);
return my_a.equals(my_b);
}
vespalib::string
DefaultTensorEngine::to_string(const Tensor &tensor) const
{
assert(&tensor.engine() == this);
const tensor::Tensor &my_tensor = static_cast<const tensor::Tensor &>(tensor);
return my_tensor.toString();
}
struct IsAddOperation : public eval::DefaultOperationVisitor {
bool result = false;
void visitDefault(const eval::Operation &) override {}
void visit(const eval::operation::Add &) override { result = true; }
};
std::unique_ptr<eval::Tensor>
DefaultTensorEngine::create(const TensorSpec &spec) const
{
ValueType type = ValueType::from_spec(spec.type());
bool is_dense = false;
bool is_sparse = false;
for (const auto &dimension: type.dimensions()) {
if (dimension.is_mapped()) {
is_sparse = true;
}
if (dimension.is_indexed()) {
is_dense = true;
}
}
if (type.dimensions().empty()) {
// XXX: should be number instead, but need to match empty sparse tensors elsewhere
is_sparse = true;
}
assert(is_dense != is_sparse);
if (is_dense) {
DenseTensorBuilder builder;
std::map<vespalib::string,DenseTensorBuilder::Dimension> dimension_map;
for (const auto &dimension: type.dimensions()) {
dimension_map[dimension.name] = builder.defineDimension(dimension.name, dimension.size);
}
for (const auto &cell: spec.cells()) {
const auto &address = cell.first;
for (const auto &binding: address) {
builder.addLabel(dimension_map[binding.first], binding.second.index);
}
builder.addCell(cell.second);
}
return builder.build();
} else { // sparse
DefaultTensor::builder builder;
std::map<vespalib::string,DefaultTensor::builder::Dimension> dimension_map;
for (const auto &dimension: type.dimensions()) {
dimension_map[dimension.name] = builder.define_dimension(dimension.name);
}
for (const auto &cell: spec.cells()) {
const auto &address = cell.first;
for (const auto &binding: address) {
builder.add_label(dimension_map[binding.first], binding.second.name);
}
builder.add_cell(cell.second);
}
return builder.build();
}
}
const eval::Value &
DefaultTensorEngine::reduce(const Tensor &tensor, const BinaryOperation &op, const std::vector<vespalib::string> &dimensions, Stash &stash) const
{
assert(&tensor.engine() == this);
const tensor::Tensor &my_tensor = static_cast<const tensor::Tensor &>(tensor);
IsAddOperation check;
op.accept(check);
if (check.result) {
if (dimensions.empty()) { // sum
return stash.create<eval::DoubleValue>(my_tensor.sum());
} else { // dimension sum
tensor::Tensor::UP result;
for (const auto &dimension: dimensions) {
if (result) {
result = result->sum(dimension);
} else {
result = my_tensor.sum(dimension);
}
}
return stash.create<TensorValue>(std::move(result));
}
}
return stash.create<ErrorValue>();
}
struct CellFunctionAdapter : tensor::CellFunction {
const eval::UnaryOperation &op;
CellFunctionAdapter(const eval::UnaryOperation &op_in) : op(op_in) {}
virtual double apply(double value) const override { return op.eval(value); }
};
const eval::Value &
DefaultTensorEngine::map(const UnaryOperation &op, const Tensor &a, Stash &stash) const
{
assert(&a.engine() == this);
const tensor::Tensor &my_a = static_cast<const tensor::Tensor &>(a);
CellFunctionAdapter cell_function(op);
return stash.create<TensorValue>(my_a.apply(cell_function));
}
struct TensorOperationOverride : eval::DefaultOperationVisitor {
const tensor::Tensor &lhs;
const tensor::Tensor &rhs;
tensor::Tensor::UP result;
TensorOperationOverride(const tensor::Tensor &lhs_in,
const tensor::Tensor &rhs_in)
: lhs(lhs_in), rhs(rhs_in), result() {}
virtual void visitDefault(const eval::Operation &) override {
// empty result indicates error
}
virtual void visit(const eval::operation::Add &) override {
result = lhs.add(rhs);
}
virtual void visit(const eval::operation::Sub &) override {
result = lhs.subtract(rhs);
}
virtual void visit(const eval::operation::Mul &) override {
if (lhs.getType() == rhs.getType()) {
result = lhs.match(rhs);
} else {
result = lhs.multiply(rhs);
}
}
virtual void visit(const eval::operation::Min &) override {
result = lhs.min(rhs);
}
virtual void visit(const eval::operation::Max &) override {
result = lhs.max(rhs);
}
};
const eval::Value &
DefaultTensorEngine::apply(const BinaryOperation &op, const Tensor &a, const Tensor &b, Stash &stash) const
{
assert(&a.engine() == this);
assert(&b.engine() == this);
const tensor::Tensor &my_a = static_cast<const tensor::Tensor &>(a);
const tensor::Tensor &my_b = static_cast<const tensor::Tensor &>(b);
TensorOperationOverride tensor_override(my_a, my_b);
op.accept(tensor_override);
if (tensor_override.result) {
return stash.create<TensorValue>(std::move(tensor_override.result));
} else {
return stash.create<ErrorValue>();
}
}
} // namespace vespalib::tensor
} // namespace vespalib
<commit_msg>do not crash on unsupported functionality<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include "default_tensor_engine.h"
#include <vespa/vespalib/eval/value.h>
#include <vespa/vespalib/eval/tensor_spec.h>
#include <vespa/vespalib/eval/operation_visitor.h>
#include "tensor.h"
#include "dense/dense_tensor_builder.h"
#include "default_tensor.h"
namespace vespalib {
namespace tensor {
using ErrorValue = eval::ErrorValue;
using DoubleValue = eval::DoubleValue;
using TensorValue = eval::TensorValue;
const DefaultTensorEngine DefaultTensorEngine::_engine;
eval::ValueType
DefaultTensorEngine::type_of(const Tensor &tensor) const
{
assert(&tensor.engine() == this);
const tensor::Tensor &my_tensor = static_cast<const tensor::Tensor &>(tensor);
return my_tensor.getType().as_value_type();
}
bool
DefaultTensorEngine::equal(const Tensor &a, const Tensor &b) const
{
assert(&a.engine() == this);
assert(&b.engine() == this);
const tensor::Tensor &my_a = static_cast<const tensor::Tensor &>(a);
const tensor::Tensor &my_b = static_cast<const tensor::Tensor &>(b);
if (my_a.getType().type() != my_b.getType().type()) {
return false;
}
return my_a.equals(my_b);
}
vespalib::string
DefaultTensorEngine::to_string(const Tensor &tensor) const
{
assert(&tensor.engine() == this);
const tensor::Tensor &my_tensor = static_cast<const tensor::Tensor &>(tensor);
return my_tensor.toString();
}
struct IsAddOperation : public eval::DefaultOperationVisitor {
bool result = false;
void visitDefault(const eval::Operation &) override {}
void visit(const eval::operation::Add &) override { result = true; }
};
std::unique_ptr<eval::Tensor>
DefaultTensorEngine::create(const TensorSpec &spec) const
{
ValueType type = ValueType::from_spec(spec.type());
bool is_dense = false;
bool is_sparse = false;
for (const auto &dimension: type.dimensions()) {
if (dimension.is_mapped()) {
is_sparse = true;
}
if (dimension.is_indexed()) {
is_dense = true;
}
}
if (is_dense && is_sparse) {
return DefaultTensor::builder().build();
} else if (is_dense) {
DenseTensorBuilder builder;
std::map<vespalib::string,DenseTensorBuilder::Dimension> dimension_map;
for (const auto &dimension: type.dimensions()) {
dimension_map[dimension.name] = builder.defineDimension(dimension.name, dimension.size);
}
for (const auto &cell: spec.cells()) {
const auto &address = cell.first;
for (const auto &binding: address) {
builder.addLabel(dimension_map[binding.first], binding.second.index);
}
builder.addCell(cell.second);
}
return builder.build();
} else { // sparse
DefaultTensor::builder builder;
std::map<vespalib::string,DefaultTensor::builder::Dimension> dimension_map;
for (const auto &dimension: type.dimensions()) {
dimension_map[dimension.name] = builder.define_dimension(dimension.name);
}
for (const auto &cell: spec.cells()) {
const auto &address = cell.first;
for (const auto &binding: address) {
builder.add_label(dimension_map[binding.first], binding.second.name);
}
builder.add_cell(cell.second);
}
return builder.build();
}
}
const eval::Value &
DefaultTensorEngine::reduce(const Tensor &tensor, const BinaryOperation &op, const std::vector<vespalib::string> &dimensions, Stash &stash) const
{
assert(&tensor.engine() == this);
const tensor::Tensor &my_tensor = static_cast<const tensor::Tensor &>(tensor);
IsAddOperation check;
op.accept(check);
if (check.result) {
if (dimensions.empty()) { // sum
return stash.create<eval::DoubleValue>(my_tensor.sum());
} else { // dimension sum
tensor::Tensor::UP result;
for (const auto &dimension: dimensions) {
if (result) {
result = result->sum(dimension);
} else {
result = my_tensor.sum(dimension);
}
}
return stash.create<TensorValue>(std::move(result));
}
}
return stash.create<ErrorValue>();
}
struct CellFunctionAdapter : tensor::CellFunction {
const eval::UnaryOperation &op;
CellFunctionAdapter(const eval::UnaryOperation &op_in) : op(op_in) {}
virtual double apply(double value) const override { return op.eval(value); }
};
const eval::Value &
DefaultTensorEngine::map(const UnaryOperation &op, const Tensor &a, Stash &stash) const
{
assert(&a.engine() == this);
const tensor::Tensor &my_a = static_cast<const tensor::Tensor &>(a);
CellFunctionAdapter cell_function(op);
return stash.create<TensorValue>(my_a.apply(cell_function));
}
struct TensorOperationOverride : eval::DefaultOperationVisitor {
const tensor::Tensor &lhs;
const tensor::Tensor &rhs;
tensor::Tensor::UP result;
TensorOperationOverride(const tensor::Tensor &lhs_in,
const tensor::Tensor &rhs_in)
: lhs(lhs_in), rhs(rhs_in), result() {}
virtual void visitDefault(const eval::Operation &) override {
// empty result indicates error
}
virtual void visit(const eval::operation::Add &) override {
result = lhs.add(rhs);
}
virtual void visit(const eval::operation::Sub &) override {
result = lhs.subtract(rhs);
}
virtual void visit(const eval::operation::Mul &) override {
if (lhs.getType() == rhs.getType()) {
result = lhs.match(rhs);
} else {
result = lhs.multiply(rhs);
}
}
virtual void visit(const eval::operation::Min &) override {
result = lhs.min(rhs);
}
virtual void visit(const eval::operation::Max &) override {
result = lhs.max(rhs);
}
};
const eval::Value &
DefaultTensorEngine::apply(const BinaryOperation &op, const Tensor &a, const Tensor &b, Stash &stash) const
{
assert(&a.engine() == this);
assert(&b.engine() == this);
const tensor::Tensor &my_a = static_cast<const tensor::Tensor &>(a);
const tensor::Tensor &my_b = static_cast<const tensor::Tensor &>(b);
if (my_a.getType().type() != my_b.getType().type()) {
return stash.create<ErrorValue>();
}
TensorOperationOverride tensor_override(my_a, my_b);
op.accept(tensor_override);
if (tensor_override.result) {
return stash.create<TensorValue>(std::move(tensor_override.result));
} else {
return stash.create<ErrorValue>();
}
}
} // namespace vespalib::tensor
} // namespace vespalib
<|endoftext|>
|
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// model a single track chain system, as part of a tracked vehicle. Uses JSON input files
//
// =============================================================================
#include <cstdio>
#include "subsys/trackSystem/TrackSystem.h"
namespace chrono {
// -----------------------------------------------------------------------------
// Static variables
// idler
const ChVector<> TrackSystem::m_idlerPos(-2.0, 0.75, 0);
const ChQuaternion<> TrackSystem::m_idlerRot(QUNIT);
// drive gear
const ChVector<> TrackSystem::m_gearPos(2.0, 0.75, 0);
const ChQuaternion<> TrackSystem::m_gearRot(QUNIT);
// Support rollers
const int TrackSystem::m_numRollers = 0;
const double TrackSystem::m_rollerMass = 100.0;
const double TrackSystem::m_roller_radius = 0.2;
const double TrackSystem::m_roller_width = 0.2;
// suspension
// const std::string m_suspensionFilename;
const int TrackSystem::m_numSuspensions = 5;
TrackSystem::TrackSystem(const std::string& name, int track_idx)
: m_track_idx(track_idx), m_name(name)
{
// FILE* fp = fopen(filename.c_str(), "r");
// char readBuffer[65536];
// fclose(fp);
Create(track_idx);
}
void TrackSystem::Create(int track_idx)
{
/*
// read idler info
assert(d.HasMember("Idler"));
m_idlerMass = d["Idler"]["Mass"].GetDouble();
m_idlerPos = loadVector(d["Idler"]["Location"]);
m_idlerInertia = loadVector(d["Idler"]["Inertia"]);
m_idlerRadius = d["Spindle"]["Radius"].GetDouble();
m_idlerWidth = d["Spindle"]["Width"].GetDouble();
m_idler_K = d["Idler"]["SpringK"].GetDouble();
m_idler_C = d["Idler"]["SpringC"].GetDouble();
// Read Drive Gear data
assert(d.HasMember("Drive Gear"));
assert(d["Drive Gear"].IsObject());
m_gearMass = d["Drive Gear"]["Mass"].GetDouble();
m_gearPos = loadVector(d["Drive Gear"]["Location"]);
m_gearInertia = loadVector(d["Drive Gear"]["Inertia"]);
m_gearRadius = d["Drive Gear"]["Radius"].GetDouble();
m_gearWidth = d["Drive Gear"]["Width"].GetDouble();
// Read Support Roller info
assert(d.HasMember("Support Roller"));
assert(d["Support Roller"].IsObject());
m_rollerMass = d["Support Roller"]["Mass"].GetDouble();
m_rollerInertia = loadVector(d["Support Roller"]["Inertia"]);
m_rollerRadius = d["Support Roller"]["Radius"].GetDouble();
m_rollerWidth = d["Support Roller"]["Width"].GetDouble();
assert(d["Support Roller"]["Location"].IsArray());
m_NumRollers = d["Support Roller"]["Location"].Size();
m_rollerLocs.resize(m_NumRollers);
for(int i = 0; i < m_NumRollers; i++ )
{
m_rollerLocs[i] = loadVector(d["Support Roller"]["Location"][i]);
}
// Read Suspension data
assert(d.HasMember("Suspension"));
assert(d["Suspension"].IsObject());
assert(d["Suspension"]["Location"].IsArray() );
m_suspensionFilename = d["Suspension"]["Input File"].GetString();
m_NumSuspensions = d["Suspension"]["Location"].Size();
m_suspensionLocs.resize(m_NumSuspensions);
for(int j = 0; j < m_NumSuspensions; j++)
{
m_suspensionLocs[j] = loadVector(d["Suspension"]["Locaiton"][j]);
}
// Read Track Chain data
assert(d.HasMember("Track Chain"));
assert(d["Track Chain"].IsObject());
m_trackChainFilename = d["Track Chain"]["Input File"].GetString()
*/
// create the various subsystems, from the class private variables
BuildSubsystems();
}
void TrackSystem::BuildSubsystems()
{
// build one of each of the following subsystems
m_driveGear = ChSharedPtr<DriveGear>(new DriveGear() );
m_idler = ChSharedPtr<IdlerSimple>(new IdlerSimple() );
m_chain = ChSharedPtr<TrackChain>(new TrackChain());
// build suspension/road wheel subsystems
m_suspensions.resize(m_numSuspensions);
for(int i = 0; i < m_numSuspensions; i++)
{
m_suspensions[i] = ChSharedPtr<TorsionArmSuspension>(new TorsionArmSuspension());
}
// build support wheel subsystems (if any)
m_supportRollers.resize(m_numRollers);
m_supportRollers_rev.resize(m_numRollers);
for(int j = 0; j < m_numRollers; j++)
{
m_supportRollers[j] = ChSharedPtr<ChBody>(new ChBody);
}
}
void TrackSystem::Initialize(ChSharedPtr<ChBodyAuxRef> chassis,
const ChVector<>& location)
{
// initialize 1 of each of the following subsystems:
m_driveGear->Initialize(chassis, m_gearPos, QUNIT);
m_idler->Initialize(chassis, m_idlerPos, QUNIT);
// initialize the road wheels & torsion arm suspension subsystems
for(int i = 0; i < m_suspensionLocs.size(); i++)
{
m_suspensions[i]->Initialize(chassis, m_suspensionLocs[i], QUNIT);
}
// initialize the support rollers
for(int j = 0; j < m_rollerLocs.size(); j++)
{
initialize_roller(m_supportRollers[j], chassis,
m_rollerLocs[j], QUNIT, j);
}
}
// initialize a roller at the specified location and orientation, w.r.t. TrackSystem c-sys
void TrackSystem::initialize_roller(ChSharedPtr<ChBody> body, ChSharedPtr<ChBodyAuxRef> chassis,
const ChVector<>& loc, const ChQuaternion<>& rot, int idx)
{
// express loc and rot in the global c-sys
ChFrame<> frame_to_abs(loc, rot);
body->SetPos(loc);
body->SetRot(rot);
body->SetMass(m_rollerMass);
// transform point to absolute frame and initialize
// add the revolute joint at the location and w/ orientation specified
// Add a visual asset
}
} // end namespace chrono
<commit_msg>use new constructors for subsystems<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// model a single track chain system, as part of a tracked vehicle. Uses JSON input files
//
// =============================================================================
#include <cstdio>
#include "subsys/trackSystem/TrackSystem.h"
namespace chrono {
// -----------------------------------------------------------------------------
// Static variables
// idler
const ChVector<> TrackSystem::m_idlerPos(-2.0, 0.75, 0);
const ChQuaternion<> TrackSystem::m_idlerRot(QUNIT);
// drive gear
const ChVector<> TrackSystem::m_gearPos(2.0, 0.75, 0);
const ChQuaternion<> TrackSystem::m_gearRot(QUNIT);
// Support rollers
const int TrackSystem::m_numRollers = 0;
const double TrackSystem::m_rollerMass = 100.0;
const double TrackSystem::m_roller_radius = 0.2;
const double TrackSystem::m_roller_width = 0.2;
// suspension
// const std::string m_suspensionFilename;
const int TrackSystem::m_numSuspensions = 5;
TrackSystem::TrackSystem(const std::string& name, int track_idx)
: m_track_idx(track_idx), m_name(name)
{
// FILE* fp = fopen(filename.c_str(), "r");
// char readBuffer[65536];
// fclose(fp);
Create(track_idx);
}
void TrackSystem::Create(int track_idx)
{
/*
// read idler info
assert(d.HasMember("Idler"));
m_idlerMass = d["Idler"]["Mass"].GetDouble();
m_idlerPos = loadVector(d["Idler"]["Location"]);
m_idlerInertia = loadVector(d["Idler"]["Inertia"]);
m_idlerRadius = d["Spindle"]["Radius"].GetDouble();
m_idlerWidth = d["Spindle"]["Width"].GetDouble();
m_idler_K = d["Idler"]["SpringK"].GetDouble();
m_idler_C = d["Idler"]["SpringC"].GetDouble();
// Read Drive Gear data
assert(d.HasMember("Drive Gear"));
assert(d["Drive Gear"].IsObject());
m_gearMass = d["Drive Gear"]["Mass"].GetDouble();
m_gearPos = loadVector(d["Drive Gear"]["Location"]);
m_gearInertia = loadVector(d["Drive Gear"]["Inertia"]);
m_gearRadius = d["Drive Gear"]["Radius"].GetDouble();
m_gearWidth = d["Drive Gear"]["Width"].GetDouble();
// Read Support Roller info
assert(d.HasMember("Support Roller"));
assert(d["Support Roller"].IsObject());
m_rollerMass = d["Support Roller"]["Mass"].GetDouble();
m_rollerInertia = loadVector(d["Support Roller"]["Inertia"]);
m_rollerRadius = d["Support Roller"]["Radius"].GetDouble();
m_rollerWidth = d["Support Roller"]["Width"].GetDouble();
assert(d["Support Roller"]["Location"].IsArray());
m_NumRollers = d["Support Roller"]["Location"].Size();
m_rollerLocs.resize(m_NumRollers);
for(int i = 0; i < m_NumRollers; i++ )
{
m_rollerLocs[i] = loadVector(d["Support Roller"]["Location"][i]);
}
// Read Suspension data
assert(d.HasMember("Suspension"));
assert(d["Suspension"].IsObject());
assert(d["Suspension"]["Location"].IsArray() );
m_suspensionFilename = d["Suspension"]["Input File"].GetString();
m_NumSuspensions = d["Suspension"]["Location"].Size();
m_suspensionLocs.resize(m_NumSuspensions);
for(int j = 0; j < m_NumSuspensions; j++)
{
m_suspensionLocs[j] = loadVector(d["Suspension"]["Locaiton"][j]);
}
// Read Track Chain data
assert(d.HasMember("Track Chain"));
assert(d["Track Chain"].IsObject());
m_trackChainFilename = d["Track Chain"]["Input File"].GetString()
*/
// create the various subsystems, from the class static variables
BuildSubsystems();
}
void TrackSystem::BuildSubsystems()
{
// build one of each of the following subsystems
m_driveGear = ChSharedPtr<DriveGear>(new DriveGear("drive gear "+std::to_string(m_track_idx)) );
m_idler = ChSharedPtr<IdlerSimple>(new IdlerSimple("idler "+std::to_string(m_track_idx)) );
m_chain = ChSharedPtr<TrackChain>(new TrackChain("chain "+std::to_string(m_track_idx)) );
// build suspension/road wheel subsystems
m_suspensions.resize(m_numSuspensions);
for(int i = 0; i < m_numSuspensions; i++)
{
m_suspensions[i] = ChSharedPtr<TorsionArmSuspension>(new TorsionArmSuspension("suspension "+std::to_string(i) +", chain "+std::to_string(m_track_idx)) );
}
// build support wheel subsystems (if any)
m_supportRollers.resize(m_numRollers);
m_supportRollers_rev.resize(m_numRollers);
for(int j = 0; j < m_numRollers; j++)
{
m_supportRollers[j] = ChSharedPtr<ChBody>(new ChBody);
m_supportRollers[j]->SetNameString("support roller"+std::to_string(j)+", chain "+std::to_string(m_track_idx) );
}
}
void TrackSystem::Initialize(ChSharedPtr<ChBodyAuxRef> chassis,
const ChVector<>& location)
{
// initialize 1 of each of the following subsystems:
m_driveGear->Initialize(chassis, m_gearPos, QUNIT);
m_idler->Initialize(chassis, m_idlerPos, QUNIT);
// initialize the road wheels & torsion arm suspension subsystems
for(int i = 0; i < m_suspensionLocs.size(); i++)
{
m_suspensions[i]->Initialize(chassis, m_suspensionLocs[i], QUNIT);
}
// initialize the support rollers
for(int j = 0; j < m_rollerLocs.size(); j++)
{
initialize_roller(m_supportRollers[j], chassis,
m_rollerLocs[j], QUNIT, j);
}
}
// initialize a roller at the specified location and orientation, w.r.t. TrackSystem c-sys
void TrackSystem::initialize_roller(ChSharedPtr<ChBody> body, ChSharedPtr<ChBodyAuxRef> chassis,
const ChVector<>& loc, const ChQuaternion<>& rot, int idx)
{
// express loc and rot in the global c-sys
ChFrame<> frame_to_abs(loc, rot);
body->SetPos(loc);
body->SetRot(rot);
body->SetMass(m_rollerMass);
// transform point to absolute frame and initialize
// add the revolute joint at the location and w/ orientation specified
// Add a visual asset
}
} // end namespace chrono
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* 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.txt
*
* 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 "selxIdentityTransformRegistrationComponent.h"
#include "selxCheckTemplateProperties.h"
#include <string>
namespace selx
{
template< int Dimensionality, class TPixel >
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::IdentityTransformRegistrationComponent( const std::string & name,
LoggerImpl & logger ) : Superclass( name, logger )
{
this->m_DisplacementField = DisplacementFieldImageType::New();
}
template< int Dimensionality, class TPixel >
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::~IdentityTransformRegistrationComponent()
{
}
template< int Dimensionality, class TPixel >
int
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::Accept( typename itkImageFixedInterface< Dimensionality, TPixel >::Pointer component )
{
// Since SuperElastix is an itk filter in a pipeline, we need to set the domain of the resulting deformation field before running the registration.
// As done in pairwise registration, typically, we use the domain of the fixed image for that.
auto fixed = component->GetItkImageFixed();
fixed->UpdateOutputInformation();
auto size = fixed->GetLargestPossibleRegion().GetSize();
this->m_DisplacementField->SetRegions(size);
auto spacing = fixed->GetSpacing();
this->m_DisplacementField->SetSpacing(spacing);
auto origin = fixed->GetOrigin();
this->m_DisplacementField->SetOrigin(origin);
auto direction = fixed->GetDirection();
this->m_DisplacementField->SetDirection(direction);
this->m_ImageFixedInterface = component;
return 0;
}
template< int Dimensionality, class TPixel >
int
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::Accept( typename itkImageMovingInterface< Dimensionality, TPixel >::Pointer component )
{
this->m_ImageMovingInterface = component;
return 0;
}
template< int Dimensionality, class TPixel >
typename IdentityTransformRegistrationComponent< Dimensionality, TPixel >::DisplacementFieldImageType::Pointer
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::GetDisplacementFieldItkImage()
{
return this->m_DisplacementField;
}
template< int Dimensionality, class TPixel >
void
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::RunRegistration( void )
{
auto fixed = this->m_ImageFixedInterface->GetItkImageFixed();
auto moving = this->m_ImageMovingInterface->GetItkImageMoving();
fixed->UpdateLargestPossibleRegion();
moving->UpdateLargestPossibleRegion();
// Here you can implement your registration algorithm using the fixed and moving image.
// For an Identity Transform it is just creating a vector field with zeros.
this->m_DisplacementField->Allocate();
}
template< int Dimensionality, class TPixel >
bool
IdentityTransformRegistrationComponent< Dimensionality, TPixel >
::MeetsCriterion( const CriterionType & criterion )
{
bool hasUndefinedCriteria( false );
bool meetsCriteria( false );
auto status = CheckTemplateProperties( this->TemplateProperties(), criterion );
if( status == CriterionStatus::Satisfied )
{
return true;
}
else if( status == CriterionStatus::Failed )
{
return false;
} // else: CriterionStatus::Unknown
return meetsCriteria;
}
} //end namespace selx
<commit_msg>BUG: wrong function to update and expose raw image data<commit_after>/*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* 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.txt
*
* 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 "selxIdentityTransformRegistrationComponent.h"
#include "selxCheckTemplateProperties.h"
#include <string>
namespace selx
{
template< int Dimensionality, class TPixel >
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::IdentityTransformRegistrationComponent( const std::string & name,
LoggerImpl & logger ) : Superclass( name, logger )
{
this->m_DisplacementField = DisplacementFieldImageType::New();
}
template< int Dimensionality, class TPixel >
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::~IdentityTransformRegistrationComponent()
{
}
template< int Dimensionality, class TPixel >
int
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::Accept( typename itkImageFixedInterface< Dimensionality, TPixel >::Pointer component )
{
// Since SuperElastix is an itk filter in a pipeline, we need to set the domain of the resulting deformation field before running the registration.
// As done in pairwise registration, typically, we use the domain of the fixed image for that.
auto fixed = component->GetItkImageFixed();
fixed->UpdateOutputInformation();
auto size = fixed->GetLargestPossibleRegion().GetSize();
this->m_DisplacementField->SetRegions(size);
auto spacing = fixed->GetSpacing();
this->m_DisplacementField->SetSpacing(spacing);
auto origin = fixed->GetOrigin();
this->m_DisplacementField->SetOrigin(origin);
auto direction = fixed->GetDirection();
this->m_DisplacementField->SetDirection(direction);
this->m_ImageFixedInterface = component;
return 0;
}
template< int Dimensionality, class TPixel >
int
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::Accept( typename itkImageMovingInterface< Dimensionality, TPixel >::Pointer component )
{
this->m_ImageMovingInterface = component;
return 0;
}
template< int Dimensionality, class TPixel >
typename IdentityTransformRegistrationComponent< Dimensionality, TPixel >::DisplacementFieldImageType::Pointer
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::GetDisplacementFieldItkImage()
{
return this->m_DisplacementField;
}
template< int Dimensionality, class TPixel >
void
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::RunRegistration( void )
{
auto fixed = this->m_ImageFixedInterface->GetItkImageFixed();
auto moving = this->m_ImageMovingInterface->GetItkImageMoving();
fixed->SetRequestedRegionToLargestPossibleRegion();
fixed->Update();
// Raw pixel data is accessible by GetBufferPointer()
moving->SetRequestedRegionToLargestPossibleRegion();
moving->Update();
// Raw pixel data is accessible by GetBufferPointer()
// Here you can implement your registration algorithm using the fixed and moving image.
// For an Identity Transform it is just creating a vector field with zeros.
this->m_DisplacementField->Allocate();
}
template< int Dimensionality, class TPixel >
bool
IdentityTransformRegistrationComponent< Dimensionality, TPixel >
::MeetsCriterion( const CriterionType & criterion )
{
bool hasUndefinedCriteria( false );
bool meetsCriteria( false );
auto status = CheckTemplateProperties( this->TemplateProperties(), criterion );
if( status == CriterionStatus::Satisfied )
{
return true;
}
else if( status == CriterionStatus::Failed )
{
return false;
} // else: CriterionStatus::Unknown
return meetsCriteria;
}
} //end namespace selx
<|endoftext|>
|
<commit_before>//
// Copyright (C) 2013-2014 mogemimi.
//
// Distributed under the MIT License.
// See accompanying file LICENSE.md or copy at
// http://enginetrouble.net/pomdog/LICENSE.md for details.
//
#ifndef POMDOG_PREREQUISITESDIRECT3D11_EED05C73_4879_45F8_B1EB_0AABCC8FBCD5_HPP
#define POMDOG_PREREQUISITESDIRECT3D11_EED05C73_4879_45F8_B1EB_0AABCC8FBCD5_HPP
#if (_MSC_VER > 1000)
# pragma once
#endif
#include "../Platform.Win32/Win32Prerequisites.hpp"
#include <d3d11.h>
#include <d3dcompiler.h>
#include <d3d11shader.h>
#include <wrl/client.h> // ComPtr
namespace Pomdog {
namespace Details {
namespace RenderSystem {
namespace Direct3D11 {
class GraphicsDeviceDirect3D11;
class GraphicsContextDirect3D11;
}// namespace Direct3D11
}// namespace RenderSystem
}// namespace Details
}// namespace Readymade
#endif // !defined(POMDOG_PREREQUISITESDIRECT3D11_EED05C73_4879_45F8_B1EB_0AABCC8FBCD5_HPP)
<commit_msg>Update forward declarations header in Direct3D<commit_after>//
// Copyright (C) 2013-2014 mogemimi.
//
// Distributed under the MIT License.
// See accompanying file LICENSE.md or copy at
// http://enginetrouble.net/pomdog/LICENSE.md for details.
//
#ifndef POMDOG_PREREQUISITESDIRECT3D11_EED05C73_4879_45F8_B1EB_0AABCC8FBCD5_HPP
#define POMDOG_PREREQUISITESDIRECT3D11_EED05C73_4879_45F8_B1EB_0AABCC8FBCD5_HPP
#if (_MSC_VER > 1000)
# pragma once
#endif
#include "../Platform.Win32/Win32Prerequisites.hpp"
#include <d3d11.h>
#include <d3dcompiler.h>
#include <d3d11shader.h>
#include <wrl/client.h> // ComPtr
namespace Pomdog {
namespace Details {
namespace RenderSystem {
namespace Direct3D11 {
class BlendStateDirect3D11;
class ConstantBufferDirect3D11;
class ConstantLayoutDirect3D11;
class DepthStencilStateDirect3D11;
class EffectPassDirect3D11;
class EffectReflectionDirect3D11;
class GraphicsDeviceDirect3D11;
class GraphicsContextDirect3D11;
class IndexBufferDirect3D11;
class InputLayoutDirect3D11;
class RasterizerStateDirect3D11;
class RenderTarget2DDirect3D11;
class SamplerStateDirect3D11;
class Texture2DDirect3D11;
class VertexBufferDirect3D11;
}// namespace Direct3D11
}// namespace RenderSystem
}// namespace Details
}// namespace Readymade
#endif // !defined(POMDOG_PREREQUISITESDIRECT3D11_EED05C73_4879_45F8_B1EB_0AABCC8FBCD5_HPP)
<|endoftext|>
|
<commit_before>#include <babylon/babylon_fwd.h>
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/cameras/follow_camera.h>
#include <babylon/engines/scene.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/standard_material.h>
#include <babylon/materials/textures/cube_texture.h>
#include <babylon/materials/textures/texture.h>
#include <babylon/maths/curve3.h>
#include <babylon/maths/vector3.h>
#include <babylon/meshes/mesh.h>
#include <babylon/samples/babylon_register_sample.h>
namespace BABYLON {
FWD_CLASS_SPTR(FollowCamera)
FWD_CLASS_SPTR(Mesh)
namespace Samples {
/**
* @brief Rollercoaster Scene. Scene demonstrating a follow camera following a moving target.
* @see https://www.babylonjs-playground.com/#1HH4OJ#29
*/
class RollercoasterScene : public IRenderableScene {
public:
RollercoasterScene(ICanvas* iCanvas) : IRenderableScene(iCanvas)
{
}
~RollercoasterScene() override = default;
const char* getName() override
{
return "Rollercoaster Scene";
}
void initializeScene(ICanvas* canvas, Scene* scene) override
{
// Image resources for textures
std::string urlRoof = "textures/rooftile2.jpg";
std::string urlWall = "textures/stonewall.jpg";
std::string urlGrass = "textures/grass2.jpg";
std::string urlSkyBox = "textures/skybox/skybox";
// Let's create a scene with an hemispheric light
scene->clearColor = Color3(0.4f, 0.6f, 1.f);
auto light = HemisphericLight::New("light1", Vector3(0.f, 1.f, 0.2f), scene);
light->intensity = 0.7f;
// Then the sky with a Skybox
auto skybox = Mesh::CreateBox("skyBox", 2000.f, scene, false, Mesh::BACKSIDE);
auto skyboxMaterial = StandardMaterial::New("skyBox", scene);
auto reflectionTexture = CubeTexture::New(urlSkyBox, scene);
reflectionTexture->coordinatesMode = TextureConstants::SKYBOX_MODE;
skyboxMaterial->diffuseColor = Color3(0.f, 0.f, 0.f);
skyboxMaterial->specularColor = Color3(0.f, 0.f, 0.f);
skyboxMaterial->reflectionTexture = reflectionTexture;
skybox->material = skyboxMaterial;
// Then the ground with a textured big disc
auto ground = Mesh::CreateDisc("ground", 800, 60, scene);
ground->rotation().x = Math::PI_2;
auto matGround = StandardMaterial::New("mg", scene);
ground->material = matGround;
auto groundTexture = Texture::New(urlGrass, scene);
groundTexture->uScale = 100.f;
groundTexture->vScale = 100.f;
matGround->diffuseTexture = groundTexture;
matGround->specularColor = Color3::Black();
// Now we will draw the roller coaster rails
// We set a closed curve by concatenating 5 different curves :
// 1 - a set of three chained loops
// 2 - a left turn
// 3 - a hill
// 4 - a right turn
// 5 - a tiny hermite spline to close the curve
// Curve computation ============================================
Curve3 continued;
float x = 0.f, y = 0.f, z = 0.f;
// Loops : cosinus and sinus
std::vector<Vector3> loops;
size_t nbpt = 200;
auto nbptf = static_cast<float>(nbpt);
float pi6 = Math::PI * 6.f;
for (float lp = 0; lp < nbpt; ++lp) {
x = lp - nbptf / 2.f + (nbptf / 5.f - lp / 8.f) * std::cos(pi6 * lp / nbptf);
y = nbptf / 5.f + (nbptf / 5.f - lp / 8.f) * std::sin(pi6 * lp / nbptf);
z = lp - nbptf;
loops.emplace_back(Vector3(x, y, z));
}
// First turn : cosinus and sinus
std::vector<Vector3> turn1;
float ang = Math::PI;
nbpt = 40;
nbptf = static_cast<float>(nbpt);
for (float tp = 0; tp < nbpt; ++tp) {
x = 30.f * std::cos(ang * tp / nbptf - 0.8f);
y = 30.f * std::sin(ang * tp / nbptf);
z = 30.f * std::sin(ang * tp / nbptf - 0.8f);
turn1.emplace_back(Vector3(x, y, z));
}
// Hill : exponential
std::vector<Vector3> hill;
nbpt = 80;
nbptf = static_cast<float>(nbpt);
for (float hp = 0; hp < nbpt; ++hp) {
x = -hp * 2.f;
y = 80.f * std::exp(-(hp - nbptf / 3.f) * (hp - nbptf / 3.f) / (nbptf * 5.f));
z = -hp * 3.2f;
hill.emplace_back(Vector3(x, y, z));
}
// Second turn : cosinus and sinus
std::vector<Vector3> turn2;
nbpt = 60;
nbptf = static_cast<float>(nbpt);
ang = -Math::PI * 3.f / 2.f;
for (float tp = 0; tp < nbpt; ++tp) {
x = 30.f * std::cos(ang * tp / nbptf - 0.6f);
y = -tp / 2.5f;
z = 30.f * std::sin(ang * tp / nbptf - 0.6f);
turn2.emplace_back(Vector3(x, y, z));
}
// Close rails with hermite
Curve3 curloops(loops);
Curve3 curturn1(turn1);
Curve3 curhill(hill);
Curve3 curturn2(turn2);
continued
= (curloops).continueCurve3(curturn1).continueCurve3(curhill).continueCurve3(curturn2);
_points = continued.getPoints();
auto p1 = _points[_points.size() - 1];
auto t1 = (p1.subtract(_points[_points.size() - 2])).scale(10.f);
auto p2 = _points[0];
auto t2 = (_points[1].subtract(p2)).scale(30.f);
auto hermite = Curve3::CreateHermiteSpline(p1, t1, p2, t2, 15);
// Full final curve
continued = hermite.continueCurve3(continued);
_points = continued.getPoints();
// Curve computed ===========================================
// Let's know define a simple triangular shape for the rails
std::vector<Vector3> shape{
Vector3(0.f, 2.f, 0.f), //
Vector3(-1.f, 0.f, 0.f), //
Vector3(0.f, -2.f, 0.f), //
};
shape.emplace_back(shape[0]);
// Let's now extrude this shape along the curve to draw the whole roller
// coaster
auto origin = Vector3::Zero();
auto rollerCoaster = Mesh::ExtrudeShape("rc", shape, _points, 2, 0, Mesh::NO_CAP, scene);
auto mat = StandardMaterial::New("mat1", scene);
mat->diffuseColor = Color3(1.f, 0.8f, 1.f);
mat->wireframe = true;
rollerCoaster->material = mat;
rollerCoaster->position = origin;
// As the first and final extruded shape may not fit along a closed curve, we
// hide this junction with a little house
auto house = Mesh::CreateBox("house", 10, scene);
house->scaling().x = 2.f;
house->scaling().z = 1.5f;
house->rotation().y = 0.6f;
house->position = _points[0];
auto roof = Mesh::CreateCylinder("roof", 22, 20, 20, 3, 1, scene);
roof->rotation().y = house->rotation().y;
roof->rotation().z = Math::PI_2;
roof->position().x = house->position().x;
roof->position().y = 12;
roof->position().z = house->position().z;
auto wallTexture = Texture::New(urlWall, scene);
auto houseMat = StandardMaterial::New("housemat", scene);
houseMat->diffuseTexture = wallTexture;
house->material = houseMat;
auto roofTexture = Texture::New(urlRoof, scene);
roofTexture->uScale = 10.f;
roofTexture->vScale = 5.f;
auto roofMat = StandardMaterial::New("roofmat", scene);
roofMat->specularColor = Color3::Black();
roofMat->diffuseTexture = roofTexture;
roof->material = roofMat;
// All immobile meshes can be now frozen to avoid un-needed matrix
// computations
skybox->freezeWorldMatrix();
ground->freezeWorldMatrix();
house->freezeWorldMatrix();
roof->freezeWorldMatrix();
// We've got the rails, we need now a wagon !
_wagon = Mesh::CreateBox("wagon", 4, scene);
_wagon->scaling().x = 2.f;
auto matWagon = StandardMaterial::New("mw", scene);
matWagon->diffuseColor = Color3(1.f, 0.f, 0.8f);
_wagon->material = matWagon;
_wagon->position = origin;
// Just in case you want to position the roller coaster somewhere else
// translate the relative curve points to the same origin than the mesh
_lg = _points.size();
for (size_t pt = 0; pt < _lg; ++pt) {
_points[pt].addInPlace(origin);
}
// Let's add a Follow Camera.
// It is set initially very far from the roller-coaster in order to get an
// "approach"" effect on start
_followCam = FollowCamera::New("fcam", Vector3(20.f, 200.f, -800.f), scene);
_followCam->lockedTarget = _wagon;
_followCam->attachControl(canvas, true);
// followCam.target = wagon;
_followCam->radius = 50.f;
_followCam->maxCameraSpeed = 1.f;
scene->activeCamera = _followCam;
// All meshes and cam are set, so now let's handle the wagon trajectory
// Let's create a Path3D object with the curve
auto path3d = Path3D(_points);
_tgts = path3d.getTangents();
_norms = path3d.getNormals();
_binorms = path3d.getBinormals();
// let's scale the normals, where the wagon will be attached, to be a little
// farther from the rails
float shift = 2.f;
for (size_t n = 0; n < _lg; n++) {
_norms[n].scaleInPlace(shift);
}
// Let's initialize now some variables for updating the wagon position each
// frame
_i = 0;
_j = 1;
_curvect = _points[_j].subtract(_points[_i]);
_rot = Vector3::RotationFromAxis(_tgts[_i], _norms[_i], _binorms[_i]);
_pos = Vector3::Zero();
_scaled = Vector3::Zero();
_step = 3;
_k = 0;
// Animation
// the wagon slides many steps on each curve segment
scene->registerBeforeRender([this](Scene* /*scene*/, EventState& /*es*/) {
_curvect.scaleToRef(static_cast<float>(_k) / static_cast<float>(_step), _scaled);
_points[_i].addToRef(_scaled, _pos);
_pos.addInPlace(_norms[_i]);
_wagon->position = _pos;
_wagon->rotation = _rot;
++_k;
// next segment
if (_k == _step) {
_i = (_i + 1) % _lg;
_j = (_i + 1) % _lg;
_rot = Vector3::RotationFromAxis(_tgts[_i], _norms[_i], _binorms[_i]);
_points[_j].subtractToRef(_points[_i], _curvect);
_k = 0;
if (_i == 0) {
// followCam->radius = 50.f + 200.f * Math::random();
}
}
_followCam->position().y = 50.f;
});
}
private:
// List with points
std::vector<Vector3> _points;
// Points size
size_t _lg;
// Tangent vectors
std::vector<Vector3> _tgts;
// Normal vectors
std::vector<Vector3> _norms;
// Binormal vectors
std::vector<Vector3> _binorms;
// Curve current point
size_t _i;
// Curve next current point
size_t _j;
// Curve current segment
Vector3 _curvect;
// Wagon current rotation
Vector3 _rot;
// Wagon current position
Vector3 _pos;
// Current scaled segment
Vector3 _scaled;
// nb steps on each segment
size_t _step;
// Counter
size_t _k;
// Wagon Mesh
MeshPtr _wagon;
// Follow Camera
FollowCameraPtr _followCam;
}; // end of class RollercoasterScene
BABYLON_REGISTER_SAMPLE("Cameras", RollercoasterScene)
} // end of namespace Samples
} // end of namespace BABYLON
<commit_msg>Added lambda return type<commit_after>#include <babylon/babylon_fwd.h>
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/cameras/follow_camera.h>
#include <babylon/engines/scene.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/standard_material.h>
#include <babylon/materials/textures/cube_texture.h>
#include <babylon/materials/textures/texture.h>
#include <babylon/maths/curve3.h>
#include <babylon/maths/vector3.h>
#include <babylon/meshes/mesh.h>
#include <babylon/samples/babylon_register_sample.h>
namespace BABYLON {
FWD_CLASS_SPTR(FollowCamera)
FWD_CLASS_SPTR(Mesh)
namespace Samples {
/**
* @brief Rollercoaster Scene. Scene demonstrating a follow camera following a moving target.
* @see https://www.babylonjs-playground.com/#1HH4OJ#29
*/
class RollercoasterScene : public IRenderableScene {
public:
RollercoasterScene(ICanvas* iCanvas) : IRenderableScene(iCanvas)
{
}
~RollercoasterScene() override = default;
const char* getName() override
{
return "Rollercoaster Scene";
}
void initializeScene(ICanvas* canvas, Scene* scene) override
{
// Image resources for textures
std::string urlRoof = "textures/rooftile2.jpg";
std::string urlWall = "textures/stonewall.jpg";
std::string urlGrass = "textures/grass2.jpg";
std::string urlSkyBox = "textures/skybox/skybox";
// Let's create a scene with an hemispheric light
scene->clearColor = Color3(0.4f, 0.6f, 1.f);
auto light = HemisphericLight::New("light1", Vector3(0.f, 1.f, 0.2f), scene);
light->intensity = 0.7f;
// Then the sky with a Skybox
auto skybox = Mesh::CreateBox("skyBox", 2000.f, scene, false, Mesh::BACKSIDE);
auto skyboxMaterial = StandardMaterial::New("skyBox", scene);
auto reflectionTexture = CubeTexture::New(urlSkyBox, scene);
reflectionTexture->coordinatesMode = TextureConstants::SKYBOX_MODE;
skyboxMaterial->diffuseColor = Color3(0.f, 0.f, 0.f);
skyboxMaterial->specularColor = Color3(0.f, 0.f, 0.f);
skyboxMaterial->reflectionTexture = reflectionTexture;
skybox->material = skyboxMaterial;
// Then the ground with a textured big disc
auto ground = Mesh::CreateDisc("ground", 800, 60, scene);
ground->rotation().x = Math::PI_2;
auto matGround = StandardMaterial::New("mg", scene);
ground->material = matGround;
auto groundTexture = Texture::New(urlGrass, scene);
groundTexture->uScale = 100.f;
groundTexture->vScale = 100.f;
matGround->diffuseTexture = groundTexture;
matGround->specularColor = Color3::Black();
// Now we will draw the roller coaster rails
// We set a closed curve by concatenating 5 different curves :
// 1 - a set of three chained loops
// 2 - a left turn
// 3 - a hill
// 4 - a right turn
// 5 - a tiny hermite spline to close the curve
// Curve computation ============================================
Curve3 continued;
float x = 0.f, y = 0.f, z = 0.f;
// Loops : cosinus and sinus
std::vector<Vector3> loops;
size_t nbpt = 200;
auto nbptf = static_cast<float>(nbpt);
float pi6 = Math::PI * 6.f;
for (float lp = 0; lp < nbpt; ++lp) {
x = lp - nbptf / 2.f + (nbptf / 5.f - lp / 8.f) * std::cos(pi6 * lp / nbptf);
y = nbptf / 5.f + (nbptf / 5.f - lp / 8.f) * std::sin(pi6 * lp / nbptf);
z = lp - nbptf;
loops.emplace_back(Vector3(x, y, z));
}
// First turn : cosinus and sinus
std::vector<Vector3> turn1;
float ang = Math::PI;
nbpt = 40;
nbptf = static_cast<float>(nbpt);
for (float tp = 0; tp < nbpt; ++tp) {
x = 30.f * std::cos(ang * tp / nbptf - 0.8f);
y = 30.f * std::sin(ang * tp / nbptf);
z = 30.f * std::sin(ang * tp / nbptf - 0.8f);
turn1.emplace_back(Vector3(x, y, z));
}
// Hill : exponential
std::vector<Vector3> hill;
nbpt = 80;
nbptf = static_cast<float>(nbpt);
for (float hp = 0; hp < nbpt; ++hp) {
x = -hp * 2.f;
y = 80.f * std::exp(-(hp - nbptf / 3.f) * (hp - nbptf / 3.f) / (nbptf * 5.f));
z = -hp * 3.2f;
hill.emplace_back(Vector3(x, y, z));
}
// Second turn : cosinus and sinus
std::vector<Vector3> turn2;
nbpt = 60;
nbptf = static_cast<float>(nbpt);
ang = -Math::PI * 3.f / 2.f;
for (float tp = 0; tp < nbpt; ++tp) {
x = 30.f * std::cos(ang * tp / nbptf - 0.6f);
y = -tp / 2.5f;
z = 30.f * std::sin(ang * tp / nbptf - 0.6f);
turn2.emplace_back(Vector3(x, y, z));
}
// Close rails with hermite
Curve3 curloops(loops);
Curve3 curturn1(turn1);
Curve3 curhill(hill);
Curve3 curturn2(turn2);
continued
= (curloops).continueCurve3(curturn1).continueCurve3(curhill).continueCurve3(curturn2);
_points = continued.getPoints();
auto p1 = _points[_points.size() - 1];
auto t1 = (p1.subtract(_points[_points.size() - 2])).scale(10.f);
auto p2 = _points[0];
auto t2 = (_points[1].subtract(p2)).scale(30.f);
auto hermite = Curve3::CreateHermiteSpline(p1, t1, p2, t2, 15);
// Full final curve
continued = hermite.continueCurve3(continued);
_points = continued.getPoints();
// Curve computed ===========================================
// Let's know define a simple triangular shape for the rails
std::vector<Vector3> shape{
Vector3(0.f, 2.f, 0.f), //
Vector3(-1.f, 0.f, 0.f), //
Vector3(0.f, -2.f, 0.f), //
};
shape.emplace_back(shape[0]);
// Let's now extrude this shape along the curve to draw the whole roller
// coaster
auto origin = Vector3::Zero();
auto rollerCoaster = Mesh::ExtrudeShape("rc", shape, _points, 2, 0, Mesh::NO_CAP, scene);
auto mat = StandardMaterial::New("mat1", scene);
mat->diffuseColor = Color3(1.f, 0.8f, 1.f);
mat->wireframe = true;
rollerCoaster->material = mat;
rollerCoaster->position = origin;
// As the first and final extruded shape may not fit along a closed curve, we
// hide this junction with a little house
auto house = Mesh::CreateBox("house", 10, scene);
house->scaling().x = 2.f;
house->scaling().z = 1.5f;
house->rotation().y = 0.6f;
house->position = _points[0];
auto roof = Mesh::CreateCylinder("roof", 22, 20, 20, 3, 1, scene);
roof->rotation().y = house->rotation().y;
roof->rotation().z = Math::PI_2;
roof->position().x = house->position().x;
roof->position().y = 12;
roof->position().z = house->position().z;
auto wallTexture = Texture::New(urlWall, scene);
auto houseMat = StandardMaterial::New("housemat", scene);
houseMat->diffuseTexture = wallTexture;
house->material = houseMat;
auto roofTexture = Texture::New(urlRoof, scene);
roofTexture->uScale = 10.f;
roofTexture->vScale = 5.f;
auto roofMat = StandardMaterial::New("roofmat", scene);
roofMat->specularColor = Color3::Black();
roofMat->diffuseTexture = roofTexture;
roof->material = roofMat;
// All immobile meshes can be now frozen to avoid un-needed matrix
// computations
skybox->freezeWorldMatrix();
ground->freezeWorldMatrix();
house->freezeWorldMatrix();
roof->freezeWorldMatrix();
// We've got the rails, we need now a wagon !
_wagon = Mesh::CreateBox("wagon", 4, scene);
_wagon->scaling().x = 2.f;
auto matWagon = StandardMaterial::New("mw", scene);
matWagon->diffuseColor = Color3(1.f, 0.f, 0.8f);
_wagon->material = matWagon;
_wagon->position = origin;
// Just in case you want to position the roller coaster somewhere else
// translate the relative curve points to the same origin than the mesh
_lg = _points.size();
for (size_t pt = 0; pt < _lg; ++pt) {
_points[pt].addInPlace(origin);
}
// Let's add a Follow Camera.
// It is set initially very far from the roller-coaster in order to get an
// "approach"" effect on start
_followCam = FollowCamera::New("fcam", Vector3(20.f, 200.f, -800.f), scene);
_followCam->lockedTarget = _wagon;
_followCam->attachControl(canvas, true);
// followCam.target = wagon;
_followCam->radius = 50.f;
_followCam->maxCameraSpeed = 1.f;
scene->activeCamera = _followCam;
// All meshes and cam are set, so now let's handle the wagon trajectory
// Let's create a Path3D object with the curve
auto path3d = Path3D(_points);
_tgts = path3d.getTangents();
_norms = path3d.getNormals();
_binorms = path3d.getBinormals();
// let's scale the normals, where the wagon will be attached, to be a little
// farther from the rails
float shift = 2.f;
for (size_t n = 0; n < _lg; n++) {
_norms[n].scaleInPlace(shift);
}
// Let's initialize now some variables for updating the wagon position each
// frame
_i = 0;
_j = 1;
_curvect = _points[_j].subtract(_points[_i]);
_rot = Vector3::RotationFromAxis(_tgts[_i], _norms[_i], _binorms[_i]);
_pos = Vector3::Zero();
_scaled = Vector3::Zero();
_step = 3;
_k = 0;
// Animation
// the wagon slides many steps on each curve segment
scene->registerBeforeRender([this](Scene* /*scene*/, EventState& /*es*/) -> void {
_curvect.scaleToRef(static_cast<float>(_k) / static_cast<float>(_step), _scaled);
_points[_i].addToRef(_scaled, _pos);
_pos.addInPlace(_norms[_i]);
_wagon->position = _pos;
_wagon->rotation = _rot;
++_k;
// next segment
if (_k == _step) {
_i = (_i + 1) % _lg;
_j = (_i + 1) % _lg;
_rot = Vector3::RotationFromAxis(_tgts[_i], _norms[_i], _binorms[_i]);
_points[_j].subtractToRef(_points[_i], _curvect);
_k = 0;
if (_i == 0) {
// followCam->radius = 50.f + 200.f * Math::random();
}
}
_followCam->position().y = 50.f;
});
}
private:
// List with points
std::vector<Vector3> _points;
// Points size
size_t _lg;
// Tangent vectors
std::vector<Vector3> _tgts;
// Normal vectors
std::vector<Vector3> _norms;
// Binormal vectors
std::vector<Vector3> _binorms;
// Curve current point
size_t _i;
// Curve next current point
size_t _j;
// Curve current segment
Vector3 _curvect;
// Wagon current rotation
Vector3 _rot;
// Wagon current position
Vector3 _pos;
// Current scaled segment
Vector3 _scaled;
// nb steps on each segment
size_t _step;
// Counter
size_t _k;
// Wagon Mesh
MeshPtr _wagon;
// Follow Camera
FollowCameraPtr _followCam;
}; // end of class RollercoasterScene
BABYLON_REGISTER_SAMPLE("Cameras", RollercoasterScene)
} // end of namespace Samples
} // end of namespace BABYLON
<|endoftext|>
|
<commit_before>#include "chainerx/routines/statistics.h"
#include "chainerx/array.h"
#include "chainerx/axes.h"
#include "chainerx/backprop_mode.h"
#include "chainerx/backward.h"
#include "chainerx/backward_builder.h"
#include "chainerx/backward_context.h"
#include "chainerx/macro.h"
#include "chainerx/routines/creation.h"
namespace chainerx {
Array Mean(const Array& a, const OptionalAxes& axis, bool keepdims) {
Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim());
Array out = internal::EmptyReduced(a.shape(), a.dtype(), sorted_axis, keepdims, a.device());
Scalar n = internal::CountItemsAlongAxes(a.shape(), sorted_axis);
{
NoBackpropModeScope scope{};
a.device().Sum(a, sorted_axis, out);
a.device().DivideAS(out, n, out);
}
BackwardBuilder bb{"mean", a, out};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([n, sorted_axis, in_shape = a.shape(), keepdims](BackwardContext& bctx) {
const Array& gout = *bctx.output_grad();
CHAINERX_ASSERT(std::is_sorted(sorted_axis.begin(), sorted_axis.end()));
if (!(in_shape.ndim() == 0 || sorted_axis.empty() || keepdims)) {
Shape out_shape_broadcastable = gout.shape();
for (auto axis : sorted_axis) {
out_shape_broadcastable.insert(out_shape_broadcastable.begin() + axis, 1);
}
bctx.input_grad() = gout.Reshape(out_shape_broadcastable).BroadcastTo(in_shape) / n;
} else {
bctx.input_grad() = gout.BroadcastTo(in_shape) / n;
}
});
}
bb.Finalize();
return out;
}
Array Var(const Array& a, const OptionalAxes& axis, bool keepdims) {
// TODO(hvy): Consider allowing device implementations.
Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim());
Array diff = a - Mean(a, sorted_axis, true);
return Mean(diff * diff, sorted_axis, keepdims);
}
} // namespace chainerx
<commit_msg>promote_integral2floats<commit_after>#include "chainerx/routines/statistics.h"
#include "chainerx/array.h"
#include "chainerx/axes.h"
#include "chainerx/backprop_mode.h"
#include "chainerx/backward.h"
#include "chainerx/backward_builder.h"
#include "chainerx/backward_context.h"
#include "chainerx/dtype.h"
#include "chainerx/macro.h"
#include "chainerx/routines/creation.h"
#include "chainerx/routines/type_util.h"
namespace chainerx {
Dtype promote_int2float(Dtype dtype){
return GetKind(dtype) == DtypeKind::kFloat? dtype :internal::GetDefaultDtype(DtypeKind::kFloat);
}
Array Mean(const Array& a, const OptionalAxes& axis, bool keepdims) {
Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim());
Dtype out_dtype = promote_int2float(a.dtype());
Array out = internal::EmptyReduced(a.shape(), out_dtype, sorted_axis, keepdims, a.device());
Scalar n = internal::CountItemsAlongAxes(a.shape(), sorted_axis);
{
NoBackpropModeScope scope{};
a.device().Sum(a, sorted_axis, out);
a.device().DivideAS(out, n, out);
}
BackwardBuilder bb{"mean", a, out};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([n, sorted_axis, in_shape = a.shape(), keepdims](BackwardContext& bctx) {
const Array& gout = *bctx.output_grad();
CHAINERX_ASSERT(std::is_sorted(sorted_axis.begin(), sorted_axis.end()));
if (!(in_shape.ndim() == 0 || sorted_axis.empty() || keepdims)) {
Shape out_shape_broadcastable = gout.shape();
for (auto axis : sorted_axis) {
out_shape_broadcastable.insert(out_shape_broadcastable.begin() + axis, 1);
}
bctx.input_grad() = gout.Reshape(out_shape_broadcastable).BroadcastTo(in_shape) / n;
} else {
bctx.input_grad() = gout.BroadcastTo(in_shape) / n;
}
});
}
bb.Finalize();
return out;
}
Array Var(const Array& a, const OptionalAxes& axis, bool keepdims) {
// TODO(hvy): Consider allowing device implementations.
Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim());
Dtype mean_out = promote_int2float(a.dtype());
// TODO: remove once subtract allows mixed types.
Array diff = a.AsType(mean_out, true) - Mean(a, sorted_axis, true);
return Mean(diff * diff, sorted_axis, keepdims);
}
} // namespace chainerx
<|endoftext|>
|
<commit_before><commit_msg>Remove all infobars from a tab when its renderer crashes. They are irrelevant in the sad tab.<commit_after><|endoftext|>
|
<commit_before><commit_msg>Close pop up notification when navigating to other site.<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/url_fixer_upper.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_process_filter.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/perf/mem_usage.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#ifndef NDEBUG
#define TEST_ITERATIONS "2"
#else
#define TEST_ITERATIONS "10"
#endif
// URL at which data files may be found for HTTP tests. The document root of
// this URL's server should point to data/page_cycler/.
#define BASE_URL L"http://localhost:8000"
namespace {
class PageCyclerTest : public UITest {
public:
PageCyclerTest() {
show_window_ = true;
// Expose garbage collection for the page cycler tests.
CommandLine::AppendSwitchWithValue(&launch_arguments_,
switches::kJavaScriptFlags,
L"--expose_gc");
}
// For HTTP tests, the name must be safe for use in a URL without escaping.
void RunPageCycler(const wchar_t* name, std::wstring* pages,
std::wstring* timings, bool use_http) {
GURL test_url;
if (use_http) {
std::wstring test_path(BASE_URL);
file_util::AppendToPath(&test_path, name);
file_util::AppendToPath(&test_path, L"start.html");
test_url = GURL(test_path);
} else {
std::wstring test_path;
PathService::Get(base::DIR_EXE, &test_path);
file_util::UpOneDirectory(&test_path);
file_util::UpOneDirectory(&test_path);
file_util::AppendToPath(&test_path, L"data");
file_util::AppendToPath(&test_path, L"page_cycler");
file_util::AppendToPath(&test_path, name);
file_util::AppendToPath(&test_path, L"start.html");
test_url = net::FilePathToFileURL(test_path);
}
// run N iterations
GURL::Replacements replacements;
const char query_string[] = "iterations=" TEST_ITERATIONS "&auto=1";
replacements.SetQuery(
query_string,
url_parse::Component(0, arraysize(query_string) - 1));
test_url = test_url.ReplaceComponents(replacements);
scoped_ptr<TabProxy> tab(GetActiveTab());
tab->NavigateToURL(test_url);
// Wait for the test to finish.
ASSERT_TRUE(WaitUntilCookieValue(tab.get(), test_url, "__pc_done",
3000, UITest::test_timeout_ms(), "1"));
std::string cookie;
ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_pages", &cookie));
pages->swap(UTF8ToWide(cookie));
ASSERT_FALSE(pages->empty());
ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_timings", &cookie));
timings->swap(UTF8ToWide(cookie));
ASSERT_FALSE(timings->empty());
}
void PrintIOPerfInfo(const wchar_t* test_name) {
BrowserProcessFilter chrome_filter(L"");
process_util::NamedProcessIterator
chrome_process_itr(chrome::kBrowserProcessExecutableName,
&chrome_filter);
const PROCESSENTRY32* chrome_entry;
while(chrome_entry = chrome_process_itr.NextProcessEntry()) {
uint32 pid = chrome_entry->th32ProcessID;
HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION,
false,
pid);
scoped_ptr<process_util::ProcessMetrics> process_metrics;
IO_COUNTERS io_counters;
process_metrics.reset(
process_util::ProcessMetrics::CreateProcessMetrics(process_handle));
ZeroMemory(&io_counters, sizeof(io_counters));
if (process_metrics.get()->GetIOCounters(&io_counters)) {
// Print out IO performance. We assume that the values can be
// converted to size_t (they're reported as ULONGLONG, 64-bit numbers).
std::wstring chrome_name =
(pid == chrome_filter.browser_process_id()) ? L"_b" : L"_r";
PrintResult(L"read_op", chrome_name, chrome_name + test_name,
static_cast<size_t>(io_counters.ReadOperationCount), L"",
false /* not important */);
PrintResult(L"write_op", chrome_name, chrome_name + test_name,
static_cast<size_t>(io_counters.WriteOperationCount), L"",
false /* not important */);
PrintResult(L"other_op", chrome_name, chrome_name + test_name,
static_cast<size_t>(io_counters.OtherOperationCount), L"",
false /* not important */);
size_t total = static_cast<size_t>(io_counters.ReadOperationCount +
io_counters.WriteOperationCount +
io_counters.OtherOperationCount);
PrintResult(L"total_op", chrome_name, chrome_name + test_name,
total, L"", true /* important */);
PrintResult(L"read_byte", chrome_name, chrome_name + test_name,
static_cast<size_t>(io_counters.ReadTransferCount / 1024),
L"kb", false /* not important */);
PrintResult(L"write_byte", chrome_name, chrome_name + test_name,
static_cast<size_t>(io_counters.WriteTransferCount / 1024),
L"kb", false /* not important */);
PrintResult(L"other_byte", chrome_name, chrome_name + test_name,
static_cast<size_t>(io_counters.OtherTransferCount / 1024),
L"kb", false /* not important */);
total = static_cast<size_t>((io_counters.ReadTransferCount +
io_counters.WriteTransferCount +
io_counters.OtherTransferCount) / 1024);
PrintResult(L"total_byte", chrome_name, chrome_name + test_name,
total, L"kb", true /* important */);
}
}
}
void PrintMemoryUsageInfo(const wchar_t* test_name) {
BrowserProcessFilter chrome_filter(L"");
process_util::NamedProcessIterator
chrome_process_itr(chrome::kBrowserProcessExecutableName,
&chrome_filter);
const PROCESSENTRY32* chrome_entry;
while(chrome_entry = chrome_process_itr.NextProcessEntry()) {
uint32 pid = chrome_entry->th32ProcessID;
size_t peak_virtual_size;
size_t current_virtual_size;
size_t peak_working_set_size;
size_t current_working_set_size;
if (GetMemoryInfo(pid, &peak_virtual_size, ¤t_virtual_size,
&peak_working_set_size, ¤t_working_set_size)) {
std::wstring chrome_name =
(pid == chrome_filter.browser_process_id()) ? L"_b" : L"_r";
std::wstring trace_name(test_name);
PrintResult(L"vm_peak", chrome_name,
L"vm_pk" + chrome_name + trace_name,
peak_virtual_size, L"bytes",
true /* important */);
PrintResult(L"vm_final", chrome_name,
L"vm_f" + chrome_name + trace_name,
current_virtual_size, L"bytes",
false /* not important */);
PrintResult(L"ws_peak", chrome_name,
L"ws_pk" + chrome_name + trace_name,
peak_working_set_size, L"bytes",
true /* important */);
PrintResult(L"ws_final", chrome_name,
L"ws_pk" + chrome_name + trace_name,
current_working_set_size, L"bytes",
false /* not important */);
}
}
}
// When use_http is true, the test name passed here will be used directly in
// the path to the test data, so it must be safe for use in a URL without
// escaping. (No pound (#), question mark (?), semicolon (;), non-ASCII, or
// other funny stuff.)
void RunTest(const wchar_t* name, bool use_http) {
std::wstring pages, timings;
RunPageCycler(name, &pages, &timings, use_http);
if (timings.empty())
return;
PrintMemoryUsageInfo(L"");
PrintIOPerfInfo(L"");
wprintf(L"\nPages: [%ls]\n", pages.c_str());
PrintResultList(L"times", L"", L"t", timings, L"ms",
true /* important */);
}
};
class PageCyclerReferenceTest : public PageCyclerTest {
public:
// override the browser directory that is used by UITest::SetUp to cause it
// to use the reference build instead.
void SetUp() {
std::wstring dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
file_util::AppendToPath(&dir, L"reference_build");
file_util::AppendToPath(&dir, L"chrome");
browser_directory_ = dir;
UITest::SetUp();
}
void RunTest(const wchar_t* name, bool use_http) {
std::wstring pages, timings;
RunPageCycler(name, &pages, &timings, use_http);
if (timings.empty())
return;
PrintMemoryUsageInfo(L"_ref");
PrintIOPerfInfo(L"_ref");
PrintResultList(L"times", L"", L"t_ref", timings, L"ms",
true /* important */);
}
};
} // namespace
// file-URL tests
TEST_F(PageCyclerTest, MozFile) {
RunTest(L"moz", false);
}
TEST_F(PageCyclerReferenceTest, MozFile) {
RunTest(L"moz", false);
}
TEST_F(PageCyclerTest, Intl1File) {
RunTest(L"intl1", false);
}
TEST_F(PageCyclerReferenceTest, Intl1File) {
RunTest(L"intl1", false);
}
TEST_F(PageCyclerTest, Intl2File) {
RunTest(L"intl2", false);
}
TEST_F(PageCyclerReferenceTest, Intl2File) {
RunTest(L"intl2", false);
}
TEST_F(PageCyclerTest, DomFile) {
RunTest(L"dom", false);
}
TEST_F(PageCyclerReferenceTest, DomFile) {
RunTest(L"dom", false);
}
TEST_F(PageCyclerTest, DhtmlFile) {
RunTest(L"dhtml", false);
}
TEST_F(PageCyclerReferenceTest, DhtmlFile) {
RunTest(L"dhtml", false);
}
// http (localhost) tests
TEST_F(PageCyclerTest, MozHttp) {
RunTest(L"moz", true);
}
TEST_F(PageCyclerReferenceTest, MozHttp) {
RunTest(L"moz", true);
}
TEST_F(PageCyclerTest, Intl1Http) {
RunTest(L"intl1", true);
}
TEST_F(PageCyclerReferenceTest, Intl1Http) {
RunTest(L"intl1", true);
}
TEST_F(PageCyclerTest, Intl2Http) {
RunTest(L"intl2", true);
}
TEST_F(PageCyclerReferenceTest, Intl2Http) {
RunTest(L"intl2", true);
}
TEST_F(PageCyclerTest, DomHttp) {
RunTest(L"dom", true);
}
TEST_F(PageCyclerReferenceTest, DomHttp) {
RunTest(L"dom", true);
}
TEST_F(PageCyclerTest, BloatHttp) {
RunTest(L"bloat", true);
}
TEST_F(PageCyclerReferenceTest, BloatHttp) {
RunTest(L"bloat", true);
}
<commit_msg>Add prefixes to I/O data trace names so they can be distinguished on the waterfall.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/url_fixer_upper.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_process_filter.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/perf/mem_usage.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#ifndef NDEBUG
#define TEST_ITERATIONS "2"
#else
#define TEST_ITERATIONS "10"
#endif
// URL at which data files may be found for HTTP tests. The document root of
// this URL's server should point to data/page_cycler/.
#define BASE_URL L"http://localhost:8000"
namespace {
class PageCyclerTest : public UITest {
public:
PageCyclerTest() {
show_window_ = true;
// Expose garbage collection for the page cycler tests.
CommandLine::AppendSwitchWithValue(&launch_arguments_,
switches::kJavaScriptFlags,
L"--expose_gc");
}
// For HTTP tests, the name must be safe for use in a URL without escaping.
void RunPageCycler(const wchar_t* name, std::wstring* pages,
std::wstring* timings, bool use_http) {
GURL test_url;
if (use_http) {
std::wstring test_path(BASE_URL);
file_util::AppendToPath(&test_path, name);
file_util::AppendToPath(&test_path, L"start.html");
test_url = GURL(test_path);
} else {
std::wstring test_path;
PathService::Get(base::DIR_EXE, &test_path);
file_util::UpOneDirectory(&test_path);
file_util::UpOneDirectory(&test_path);
file_util::AppendToPath(&test_path, L"data");
file_util::AppendToPath(&test_path, L"page_cycler");
file_util::AppendToPath(&test_path, name);
file_util::AppendToPath(&test_path, L"start.html");
test_url = net::FilePathToFileURL(test_path);
}
// run N iterations
GURL::Replacements replacements;
const char query_string[] = "iterations=" TEST_ITERATIONS "&auto=1";
replacements.SetQuery(
query_string,
url_parse::Component(0, arraysize(query_string) - 1));
test_url = test_url.ReplaceComponents(replacements);
scoped_ptr<TabProxy> tab(GetActiveTab());
tab->NavigateToURL(test_url);
// Wait for the test to finish.
ASSERT_TRUE(WaitUntilCookieValue(tab.get(), test_url, "__pc_done",
3000, UITest::test_timeout_ms(), "1"));
std::string cookie;
ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_pages", &cookie));
pages->swap(UTF8ToWide(cookie));
ASSERT_FALSE(pages->empty());
ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_timings", &cookie));
timings->swap(UTF8ToWide(cookie));
ASSERT_FALSE(timings->empty());
}
void PrintIOPerfInfo(const wchar_t* test_name) {
BrowserProcessFilter chrome_filter(L"");
process_util::NamedProcessIterator
chrome_process_itr(chrome::kBrowserProcessExecutableName,
&chrome_filter);
const PROCESSENTRY32* chrome_entry;
while(chrome_entry = chrome_process_itr.NextProcessEntry()) {
uint32 pid = chrome_entry->th32ProcessID;
HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION,
false,
pid);
scoped_ptr<process_util::ProcessMetrics> process_metrics;
IO_COUNTERS io_counters;
process_metrics.reset(
process_util::ProcessMetrics::CreateProcessMetrics(process_handle));
ZeroMemory(&io_counters, sizeof(io_counters));
if (process_metrics.get()->GetIOCounters(&io_counters)) {
// Print out IO performance. We assume that the values can be
// converted to size_t (they're reported as ULONGLONG, 64-bit numbers).
std::wstring chrome_name =
(pid == chrome_filter.browser_process_id()) ? L"_b" : L"_r";
PrintResult(L"read_op", chrome_name,
L"r_op" + chrome_name + test_name,
static_cast<size_t>(io_counters.ReadOperationCount), L"",
false /* not important */);
PrintResult(L"write_op", chrome_name,
L"w_op" + chrome_name + test_name,
static_cast<size_t>(io_counters.WriteOperationCount), L"",
false /* not important */);
PrintResult(L"other_op", chrome_name,
L"o_op" + chrome_name + test_name,
static_cast<size_t>(io_counters.OtherOperationCount), L"",
false /* not important */);
size_t total = static_cast<size_t>(io_counters.ReadOperationCount +
io_counters.WriteOperationCount +
io_counters.OtherOperationCount);
PrintResult(L"total_op", chrome_name,
L"IO_op" + chrome_name + test_name,
total, L"", true /* important */);
PrintResult(L"read_byte", chrome_name,
L"r_b" + chrome_name + test_name,
static_cast<size_t>(io_counters.ReadTransferCount / 1024),
L"kb", false /* not important */);
PrintResult(L"write_byte", chrome_name,
L"w_b" + chrome_name + test_name,
static_cast<size_t>(io_counters.WriteTransferCount / 1024),
L"kb", false /* not important */);
PrintResult(L"other_byte", chrome_name,
L"o_b" + chrome_name + test_name,
static_cast<size_t>(io_counters.OtherTransferCount / 1024),
L"kb", false /* not important */);
total = static_cast<size_t>((io_counters.ReadTransferCount +
io_counters.WriteTransferCount +
io_counters.OtherTransferCount) / 1024);
PrintResult(L"total_byte", chrome_name,
L"IO_b" + chrome_name + test_name,
total, L"kb", true /* important */);
}
}
}
void PrintMemoryUsageInfo(const wchar_t* test_name) {
BrowserProcessFilter chrome_filter(L"");
process_util::NamedProcessIterator
chrome_process_itr(chrome::kBrowserProcessExecutableName,
&chrome_filter);
const PROCESSENTRY32* chrome_entry;
while(chrome_entry = chrome_process_itr.NextProcessEntry()) {
uint32 pid = chrome_entry->th32ProcessID;
size_t peak_virtual_size;
size_t current_virtual_size;
size_t peak_working_set_size;
size_t current_working_set_size;
if (GetMemoryInfo(pid, &peak_virtual_size, ¤t_virtual_size,
&peak_working_set_size, ¤t_working_set_size)) {
std::wstring chrome_name =
(pid == chrome_filter.browser_process_id()) ? L"_b" : L"_r";
std::wstring trace_name(test_name);
PrintResult(L"vm_peak", chrome_name,
L"vm_pk" + chrome_name + trace_name,
peak_virtual_size, L"bytes",
true /* important */);
PrintResult(L"vm_final", chrome_name,
L"vm_f" + chrome_name + trace_name,
current_virtual_size, L"bytes",
false /* not important */);
PrintResult(L"ws_peak", chrome_name,
L"ws_pk" + chrome_name + trace_name,
peak_working_set_size, L"bytes",
true /* important */);
PrintResult(L"ws_final", chrome_name,
L"ws_pk" + chrome_name + trace_name,
current_working_set_size, L"bytes",
false /* not important */);
}
}
}
// When use_http is true, the test name passed here will be used directly in
// the path to the test data, so it must be safe for use in a URL without
// escaping. (No pound (#), question mark (?), semicolon (;), non-ASCII, or
// other funny stuff.)
void RunTest(const wchar_t* name, bool use_http) {
std::wstring pages, timings;
RunPageCycler(name, &pages, &timings, use_http);
if (timings.empty())
return;
PrintMemoryUsageInfo(L"");
PrintIOPerfInfo(L"");
wprintf(L"\nPages: [%ls]\n", pages.c_str());
PrintResultList(L"times", L"", L"t", timings, L"ms",
true /* important */);
}
};
class PageCyclerReferenceTest : public PageCyclerTest {
public:
// override the browser directory that is used by UITest::SetUp to cause it
// to use the reference build instead.
void SetUp() {
std::wstring dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
file_util::AppendToPath(&dir, L"reference_build");
file_util::AppendToPath(&dir, L"chrome");
browser_directory_ = dir;
UITest::SetUp();
}
void RunTest(const wchar_t* name, bool use_http) {
std::wstring pages, timings;
RunPageCycler(name, &pages, &timings, use_http);
if (timings.empty())
return;
PrintMemoryUsageInfo(L"_ref");
PrintIOPerfInfo(L"_ref");
PrintResultList(L"times", L"", L"t_ref", timings, L"ms",
true /* important */);
}
};
} // namespace
// file-URL tests
TEST_F(PageCyclerTest, MozFile) {
RunTest(L"moz", false);
}
TEST_F(PageCyclerReferenceTest, MozFile) {
RunTest(L"moz", false);
}
TEST_F(PageCyclerTest, Intl1File) {
RunTest(L"intl1", false);
}
TEST_F(PageCyclerReferenceTest, Intl1File) {
RunTest(L"intl1", false);
}
TEST_F(PageCyclerTest, Intl2File) {
RunTest(L"intl2", false);
}
TEST_F(PageCyclerReferenceTest, Intl2File) {
RunTest(L"intl2", false);
}
TEST_F(PageCyclerTest, DomFile) {
RunTest(L"dom", false);
}
TEST_F(PageCyclerReferenceTest, DomFile) {
RunTest(L"dom", false);
}
TEST_F(PageCyclerTest, DhtmlFile) {
RunTest(L"dhtml", false);
}
TEST_F(PageCyclerReferenceTest, DhtmlFile) {
RunTest(L"dhtml", false);
}
// http (localhost) tests
TEST_F(PageCyclerTest, MozHttp) {
RunTest(L"moz", true);
}
TEST_F(PageCyclerReferenceTest, MozHttp) {
RunTest(L"moz", true);
}
TEST_F(PageCyclerTest, Intl1Http) {
RunTest(L"intl1", true);
}
TEST_F(PageCyclerReferenceTest, Intl1Http) {
RunTest(L"intl1", true);
}
TEST_F(PageCyclerTest, Intl2Http) {
RunTest(L"intl2", true);
}
TEST_F(PageCyclerReferenceTest, Intl2Http) {
RunTest(L"intl2", true);
}
TEST_F(PageCyclerTest, DomHttp) {
RunTest(L"dom", true);
}
TEST_F(PageCyclerReferenceTest, DomHttp) {
RunTest(L"dom", true);
}
TEST_F(PageCyclerTest, BloatHttp) {
RunTest(L"bloat", true);
}
TEST_F(PageCyclerReferenceTest, BloatHttp) {
RunTest(L"bloat", true);
}
<|endoftext|>
|
<commit_before><commit_msg>The version of gcc on mac (4.2) doesn't like inheriting from a test in an anonymous namespace. Just move the actual test cases into the namespace so everything is in the same translation unit.<commit_after><|endoftext|>
|
<commit_before><commit_msg>Enable new tab test reference builds on Mac now that the reference builds are new enough.<commit_after><|endoftext|>
|
<commit_before><commit_msg>Fix Chrome frame builder redness.<commit_after><|endoftext|>
|
<commit_before>/*
Copyright (c) 2011, Alexandre Abadie <Alexandre.Abadie@irisa.fr>
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 <organization> 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 Alexandre <email> ''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 Alexandre <email> 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.
*/
#include "medHomepageArea.h"
#include <medViewerArea.h>
#include <medHomepageButton.h>
#include <medGui/medViewerConfiguration.h>
#include <medGui/medViewerConfigurationFactory.h>
class medHomepageAreaPrivate
{
public:
QGraphicsScene * configurationsButtonsScene;
QGraphicsProxyWidget * configurationsButtonsProxyWidget;
QWidget * configurationsButtonsWidget;
QGraphicsScene * userButtonsScene;
QGraphicsProxyWidget * userButtonsProxyWidget;
QWidget * userButtonsWidget;
QGraphicsScene * infoScene;
QGraphicsProxyWidget * infoProxyWidget;
QWidget * infoWidget;
QPropertyAnimation * configurationAnimation;
QPropertyAnimation * userAnimation;
QPropertyAnimation * infoAnimation;
QParallelAnimationGroup * animation;
medViewerArea * viewerArea;
};
medHomepageArea::medHomepageArea ( QWidget * parent ) : QWidget ( parent ), d ( new medHomepageAreaPrivate )
{
d->viewerArea = NULL;
setupUi ( this );
// d->configurationsButtonsView = new QGraphicsView ( this );
d->configurationsButtonsScene = new QGraphicsScene ( configurationsGraphicsView );
configurationsGraphicsView->setScene ( d->configurationsButtonsScene );
configurationsGraphicsView->setStyleSheet ( "background: #313131;border: 0px;padding: 0px 0px 0px 0px;" );
configurationsGraphicsView->setFocusPolicy ( Qt::NoFocus );
//Configurations buttons (browser, visualization, registration, diffusion, etc)
d->configurationsButtonsWidget = new QWidget ( configurationsGraphicsView );
d->configurationsButtonsWidget->setMinimumWidth ( 200 );
d->userButtonsScene = new QGraphicsScene ( infoGraphicsView );
userGraphicsView->setScene ( d->userButtonsScene );
userGraphicsView->setStyleSheet ( "background: #313131;border: 0px;padding: 0px 0px 0px 0px;" );
userGraphicsView->setFocusPolicy ( Qt::NoFocus );
//Configurations buttons (Help, about, settings)
d->userButtonsWidget = new QWidget ( userGraphicsView );
d->userButtonsWidget->setMinimumWidth ( 200 );
d->infoScene = new QGraphicsScene ( userGraphicsView );
infoGraphicsView->setScene ( d->infoScene );
infoGraphicsView->setStyleSheet ( "background: #313131;border: 0px;padding: 0px 0px 0px 0px;" );
infoGraphicsView->setFocusPolicy ( Qt::NoFocus );
QHBoxLayout * userButtonsLayout = new QHBoxLayout ( userGraphicsView );
// QPushButton * helpButton = new QPushButton(userGraphicsView);
medHomepageButton * helpButton = new medHomepageButton ( userGraphicsView );
helpButton->setText ( "Help" );
helpButton->setMinimumHeight ( 30 );
helpButton->setMaximumWidth ( 150 );
helpButton->setMinimumWidth ( 150 );
helpButton->setFocusPolicy ( Qt::NoFocus );
helpButton->setIcon(QIcon(":icons/help.svg"));
helpButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
QObject::connect ( helpButton,SIGNAL ( clicked() ),this, SLOT ( onShowHelp() ) );
// QPushButton * aboutButton = new QPushButton(userGraphicsView);
medHomepageButton * aboutButton = new medHomepageButton ( userGraphicsView );
aboutButton->setText ( "About" );
aboutButton->setMinimumHeight ( 30 );
aboutButton->setMaximumWidth ( 150 );
aboutButton->setMinimumWidth ( 150 );
aboutButton->setFocusPolicy ( Qt::NoFocus );
aboutButton->setIcon(QIcon(":icons/about.png"));
aboutButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
QObject::connect ( aboutButton,SIGNAL ( clicked() ),this, SLOT ( onShowAbout() ) );
// QPushButton * settingsButton = new QPushButton(userGraphicsView);
medHomepageButton * settingsButton = new medHomepageButton ( userGraphicsView );
settingsButton->setText ( "Settings" );
settingsButton->setMinimumHeight ( 30 );
settingsButton->setMaximumWidth ( 150 );
settingsButton->setMinimumWidth ( 150 );
settingsButton->setFocusPolicy ( Qt::NoFocus );
settingsButton->setIcon(QIcon(":icons/settings.svg"));
settingsButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
QObject::connect ( settingsButton,SIGNAL ( clicked() ),this, SLOT ( onShowSettings() ) );
userButtonsLayout->insertWidget ( 0, settingsButton );
userButtonsLayout->insertWidget ( 1, aboutButton );
userButtonsLayout->insertWidget ( 2, helpButton );
d->userButtonsWidget->setLayout ( userButtonsLayout );
d->userButtonsProxyWidget = d->userButtonsScene->addWidget ( d->userButtonsWidget );
d->userButtonsProxyWidget->setPos ( d->userButtonsScene->width() - 100, 0 );
// //Special widget : image, text, etc. QtWebkit ?
d->infoWidget = new QWidget ( infoGraphicsView );
QVBoxLayout * infoLayout = new QVBoxLayout ( this );
QLabel * medinriaLabel = new QLabel ( this );
medinriaLabel->setPixmap ( QPixmap ( ":pixmaps/medinria-logo.png" ).scaled ( 300,100 ) );
QLabel * textLabel = new QLabel;
textLabel->setText ( "The ultimate medical imaging platform" );
infoLayout->insertWidget ( 0,medinriaLabel );
infoLayout->insertWidget ( 1, textLabel );
d->infoWidget->setLayout ( infoLayout );
d->infoProxyWidget = d->infoScene->addWidget ( d->infoWidget );
d->animation = new QParallelAnimationGroup ( this );
d->configurationAnimation = new QPropertyAnimation ( d->configurationsButtonsWidget, "pos" );
d->configurationAnimation->setDuration ( 750 );
d->configurationAnimation->setEasingCurve ( QEasingCurve::OutCubic );
d->userAnimation = new QPropertyAnimation ( d->userButtonsWidget, "pos" );
d->userAnimation->setDuration ( 750 );
d->userAnimation->setEasingCurve ( QEasingCurve::OutCubic );
d->userAnimation->setStartValue ( QPoint ( ( d->userButtonsScene->width() / 2 ) + 250, 0 ) );
d->userAnimation->setEndValue ( QPoint ( ( d->userButtonsScene->width() / 2 ) , 0 ) );
d->infoAnimation = new QPropertyAnimation ( d->infoWidget, "pos" );
d->infoAnimation->setDuration ( 900 );
d->infoAnimation->setEasingCurve ( QEasingCurve::OutCubic );
d->infoAnimation->setStartValue ( QPoint ( ( d->infoScene->width() / 2 ) + 1000 , 250 ) );
d->infoAnimation->setEndValue ( QPoint ( ( d->infoScene->width() / 2 ) + 300 , 250 ) );
d->animation->addAnimation(d->configurationAnimation);
d->animation->addAnimation(d->userAnimation);
d->animation->addAnimation(d->infoAnimation);
}
medHomepageArea::~medHomepageArea()
{
delete d;
d = NULL;
}
void medHomepageArea::initPage ( void )
{
QList<QString> configList = medViewerConfigurationFactory::instance()->configurations();
QVBoxLayout * configurationButtonsLayout = new QVBoxLayout ( this );
QLabel * configurationLabel = new QLabel("Available workspaces:");
configurationButtonsLayout->addWidget(configurationLabel);
// // QPushButton * buttonBrowser = new QPushButton ( this );
medHomepageButton * browserButton = new medHomepageButton ( this );
browserButton->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon );
browserButton->setIcon ( QIcon ( ":/icons/folder.png" ) );
browserButton->setText ( "Browser" );
browserButton->setMinimumHeight ( 30 );
browserButton->setMaximumWidth ( 200 );
browserButton->setMinimumWidth ( 200 );
browserButton->setFocusPolicy ( Qt::NoFocus );
configurationButtonsLayout->addWidget ( browserButton);
QObject::connect ( browserButton, SIGNAL ( clicked() ),this, SLOT ( onShowBrowser() ) );
for ( int i = 0; i< configList.size(); i++ )
{
// QPushButton * button = new QPushButton ( this );
medHomepageButton * button = new medHomepageButton ( this );
button->setText ( configList.at ( i ) );
button->setFocusPolicy ( Qt::NoFocus );
button->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon );
button->setMinimumHeight ( 30 );
button->setMaximumWidth ( 200 );
button->setMinimumWidth ( 200 );;
// configurationButtonsLayout->addWidget ( button,i + 1,0 );
configurationButtonsLayout->addWidget ( button);
QObject::connect ( button, SIGNAL ( clicked ( QString ) ),this, SLOT ( onShowConfiguration ( QString ) ) );
}
d->configurationsButtonsWidget->setLayout ( configurationButtonsLayout );
d->configurationsButtonsProxyWidget = d->configurationsButtonsScene->addWidget ( d->configurationsButtonsWidget );
d->configurationAnimation->setStartValue ( QPoint ( ( d->configurationsButtonsScene->width() / 2 ) - 250, 250 ) );
d->configurationAnimation->setEndValue ( QPoint ( ( d->configurationsButtonsScene->width() / 2 ) + 100 , 250 ) );
}
QParallelAnimationGroup* medHomepageArea::getAnimation ( void )
{
return d->animation;
}
void medHomepageArea::setViewerArea ( medViewerArea* viewer )
{
d->viewerArea = viewer;
}
void medHomepageArea::onShowBrowser ( void )
{
emit showBrowser();
}
void medHomepageArea::onShowConfiguration ( QString configuration )
{
emit showViewer();
emit showConfiguration ( configuration );
}
void medHomepageArea::onShowAbout ( void )
{
// emit showAbout();
QMessageBox * msgBox = new QMessageBox ( QApplication::activeWindow() );
msgBox->setIcon ( QMessageBox::Information );
msgBox->setText ( "This is an ultimate medical imaging platform" );
msgBox->exec();
delete msgBox;
}
void medHomepageArea::onShowHelp ( void )
{
// emit showHelp();
QMessageBox * msgBox = new QMessageBox ( QApplication::activeWindow() );
msgBox->setIcon ( QMessageBox::Information );
msgBox->setText ( "Help ! Help !" );
msgBox->exec();
delete msgBox;
}
void medHomepageArea::onShowSettings ( void )
{
emit showSettings();
}
<commit_msg>some cosmetic improvements of the home page<commit_after>/*
Copyright (c) 2011, Alexandre Abadie <Alexandre.Abadie@irisa.fr>
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 <organization> 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 Alexandre <email> ''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 Alexandre <email> 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.
*/
#include "medHomepageArea.h"
#include <medViewerArea.h>
#include <medHomepageButton.h>
#include <medGui/medViewerConfiguration.h>
#include <medGui/medViewerConfigurationFactory.h>
class medHomepageAreaPrivate
{
public:
QGraphicsScene * configurationsButtonsScene;
QGraphicsProxyWidget * configurationsButtonsProxyWidget;
QWidget * configurationsButtonsWidget;
QGraphicsScene * userButtonsScene;
QGraphicsProxyWidget * userButtonsProxyWidget;
QWidget * userButtonsWidget;
QGraphicsScene * infoScene;
QGraphicsProxyWidget * infoProxyWidget;
QWidget * infoWidget;
QPropertyAnimation * configurationAnimation;
QPropertyAnimation * userAnimation;
QPropertyAnimation * infoAnimation;
QParallelAnimationGroup * animation;
medViewerArea * viewerArea;
};
medHomepageArea::medHomepageArea ( QWidget * parent ) : QWidget ( parent ), d ( new medHomepageAreaPrivate )
{
d->viewerArea = NULL;
setupUi ( this );
// d->configurationsButtonsView = new QGraphicsView ( this );
d->configurationsButtonsScene = new QGraphicsScene ( configurationsGraphicsView );
configurationsGraphicsView->setScene ( d->configurationsButtonsScene );
configurationsGraphicsView->setStyleSheet ( "background: #313131;border: 0px;padding: 0px 0px 0px 0px;" );
configurationsGraphicsView->setFocusPolicy ( Qt::NoFocus );
//Configurations buttons (browser, visualization, registration, diffusion, etc)
d->configurationsButtonsWidget = new QWidget ( configurationsGraphicsView );
d->configurationsButtonsWidget->setMinimumWidth ( 200 );
d->userButtonsScene = new QGraphicsScene ( infoGraphicsView );
userGraphicsView->setScene ( d->userButtonsScene );
userGraphicsView->setStyleSheet ( "background: #313131;border: 0px;padding: 0px 0px 0px 0px;" );
userGraphicsView->setFocusPolicy ( Qt::NoFocus );
//Configurations buttons (Help, about, settings)
d->userButtonsWidget = new QWidget ( userGraphicsView );
d->userButtonsWidget->setMinimumWidth ( 200 );
d->infoScene = new QGraphicsScene ( userGraphicsView );
infoGraphicsView->setScene ( d->infoScene );
infoGraphicsView->setStyleSheet ( "background: #313131;border: 0px;padding: 0px 0px 0px 0px;" );
infoGraphicsView->setFocusPolicy ( Qt::NoFocus );
QHBoxLayout * userButtonsLayout = new QHBoxLayout ( userGraphicsView );
// QPushButton * helpButton = new QPushButton(userGraphicsView);
medHomepageButton * helpButton = new medHomepageButton ( userGraphicsView );
helpButton->setText ( "Help" );
helpButton->setMinimumHeight ( 30 );
helpButton->setMaximumWidth ( 150 );
helpButton->setMinimumWidth ( 150 );
helpButton->setFocusPolicy ( Qt::NoFocus );
helpButton->setIcon(QIcon(":icons/help.svg"));
helpButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
QObject::connect ( helpButton,SIGNAL ( clicked() ),this, SLOT ( onShowHelp() ) );
// QPushButton * aboutButton = new QPushButton(userGraphicsView);
medHomepageButton * aboutButton = new medHomepageButton ( userGraphicsView );
aboutButton->setText ( "About" );
aboutButton->setMinimumHeight ( 30 );
aboutButton->setMaximumWidth ( 150 );
aboutButton->setMinimumWidth ( 150 );
aboutButton->setFocusPolicy ( Qt::NoFocus );
aboutButton->setIcon(QIcon(":icons/about.png"));
aboutButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
QObject::connect ( aboutButton,SIGNAL ( clicked() ),this, SLOT ( onShowAbout() ) );
// QPushButton * settingsButton = new QPushButton(userGraphicsView);
medHomepageButton * settingsButton = new medHomepageButton ( userGraphicsView );
settingsButton->setText ( "Settings" );
settingsButton->setMinimumHeight ( 30 );
settingsButton->setMaximumWidth ( 150 );
settingsButton->setMinimumWidth ( 150 );
settingsButton->setFocusPolicy ( Qt::NoFocus );
settingsButton->setIcon(QIcon(":icons/settings.svg"));
settingsButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
QObject::connect ( settingsButton,SIGNAL ( clicked() ),this, SLOT ( onShowSettings() ) );
userButtonsLayout->insertWidget ( 0, settingsButton );
userButtonsLayout->insertWidget ( 1, aboutButton );
userButtonsLayout->insertWidget ( 2, helpButton );
d->userButtonsWidget->setLayout ( userButtonsLayout );
d->userButtonsProxyWidget = d->userButtonsScene->addWidget ( d->userButtonsWidget );
d->userButtonsProxyWidget->setPos ( d->userButtonsScene->width() - 100, 0 );
// //Special widget : image, text, etc. QtWebkit ?
d->infoWidget = new QWidget ( infoGraphicsView );
QVBoxLayout * infoLayout = new QVBoxLayout ( this );
QLabel * medinriaLabel = new QLabel ( this );
medinriaLabel->setPixmap ( QPixmap ( ":pixmaps/medinria-logo.png" ).scaled ( 300,100 ) );
QLabel * textLabel = new QLabel;
textLabel->setText ( "The ultimate medical imaging platform" );
infoLayout->insertWidget ( 0,medinriaLabel );
infoLayout->insertWidget ( 1, textLabel );
d->infoWidget->setLayout ( infoLayout );
d->infoProxyWidget = d->infoScene->addWidget ( d->infoWidget );
d->animation = new QParallelAnimationGroup ( this );
d->configurationAnimation = new QPropertyAnimation ( d->configurationsButtonsWidget, "pos" );
d->configurationAnimation->setDuration ( 750 );
d->configurationAnimation->setEasingCurve ( QEasingCurve::OutCubic );
d->userAnimation = new QPropertyAnimation ( d->userButtonsWidget, "pos" );
d->userAnimation->setDuration ( 750 );
d->userAnimation->setEasingCurve ( QEasingCurve::OutCubic );
d->userAnimation->setStartValue ( QPoint ( ( d->userButtonsScene->width() / 2 ) + 250, 0 ) );
d->userAnimation->setEndValue ( QPoint ( ( d->userButtonsScene->width() / 2 ) , 0 ) );
d->infoAnimation = new QPropertyAnimation ( d->infoWidget, "pos" );
d->infoAnimation->setDuration ( 900 );
d->infoAnimation->setEasingCurve ( QEasingCurve::OutCubic );
d->infoAnimation->setStartValue ( QPoint ( ( d->infoScene->width() / 2 ) + 1000 , 250 ) );
d->infoAnimation->setEndValue ( QPoint ( ( d->infoScene->width() / 2 ) + 300 , 250 ) );
d->animation->addAnimation(d->configurationAnimation);
d->animation->addAnimation(d->userAnimation);
d->animation->addAnimation(d->infoAnimation);
}
medHomepageArea::~medHomepageArea()
{
delete d;
d = NULL;
}
void medHomepageArea::initPage ( void )
{
QList<QString> configList = medViewerConfigurationFactory::instance()->configurations();
QVBoxLayout * configurationButtonsLayout = new QVBoxLayout ( this );
QLabel * configurationLabel = new QLabel("Available workspaces:");
configurationButtonsLayout->addWidget(configurationLabel);
// // QPushButton * buttonBrowser = new QPushButton ( this );
medHomepageButton * browserButton = new medHomepageButton ( this );
browserButton->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon );
browserButton->setIcon ( QIcon ( ":/icons/folder.png" ) );
browserButton->setText ( "Browser" );
browserButton->setMinimumHeight ( 30 );
browserButton->setMaximumWidth ( 200 );
browserButton->setMinimumWidth ( 200 );
browserButton->setFocusPolicy ( Qt::NoFocus );
configurationButtonsLayout->addWidget ( browserButton);
QObject::connect ( browserButton, SIGNAL ( clicked() ),this, SLOT ( onShowBrowser() ) );
for ( int i = 0; i< configList.size(); i++ )
{
// QPushButton * button = new QPushButton ( this );
medHomepageButton * button = new medHomepageButton ( this );
button->setText ( configList.at ( i ) );
button->setFocusPolicy ( Qt::NoFocus );
button->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon );
button->setMinimumHeight ( 30 );
button->setMaximumWidth ( 200 );
button->setMinimumWidth ( 200 );;
configurationButtonsLayout->addWidget ( button);
QObject::connect ( button, SIGNAL ( clicked ( QString ) ),this, SLOT ( onShowConfiguration ( QString ) ) );
}
d->configurationsButtonsWidget->setLayout ( configurationButtonsLayout );
d->configurationsButtonsProxyWidget = d->configurationsButtonsScene->addWidget ( d->configurationsButtonsWidget );
d->configurationAnimation->setStartValue ( QPoint ( ( d->configurationsButtonsScene->width() / 2 ) - 250, 250 ) );
d->configurationAnimation->setEndValue ( QPoint ( ( d->configurationsButtonsScene->width() / 2 ) + 100 , 250 ) );
}
QParallelAnimationGroup* medHomepageArea::getAnimation ( void )
{
return d->animation;
}
void medHomepageArea::setViewerArea ( medViewerArea* viewer )
{
d->viewerArea = viewer;
}
void medHomepageArea::onShowBrowser ( void )
{
emit showBrowser();
}
void medHomepageArea::onShowConfiguration ( QString configuration )
{
emit showViewer();
emit showConfiguration ( configuration );
}
void medHomepageArea::onShowAbout ( void )
{
QString aboutMessage("This is an ultimate medical imaging platform");
QMessageBox::about(this,"About Medinria", aboutMessage);
// QMessageBox * msgBox = new QMessageBox ( QApplication::activeWindow() );
// msgBox->setIcon ( QMessageBox::Information );
// msgBox->setText ( "This is an ultimate medical imaging platform" );
// msgBox->exec();
// delete msgBox;
}
void medHomepageArea::onShowHelp ( void )
{
// emit showHelp();
QMessageBox * msgBox = new QMessageBox ( QApplication::activeWindow() );
msgBox->setIcon ( QMessageBox::Information );
msgBox->setText ( "Help ! Help !" );
msgBox->exec();
delete msgBox;
}
void medHomepageArea::onShowSettings ( void )
{
emit showSettings();
}
<|endoftext|>
|
<commit_before>#ifndef ENTT_POLY_POLY_HPP
#define ENTT_POLY_POLY_HPP
#include <cstddef>
#include <functional>
#include <tuple>
#include <type_traits>
#include <utility>
#include "../config/config.h"
#include "../core/any.hpp"
#include "../core/type_info.hpp"
#include "../core/type_traits.hpp"
#include "fwd.hpp"
namespace entt {
/*! @brief Inspector class used to infer the type of the virtual table. */
struct poly_inspector {
/**
* @brief Generic conversion operator (definition only).
* @tparam Type Type to which conversion is requested.
*/
template <class Type>
operator Type &&() const;
/**
* @brief Dummy invocation function (definition only).
* @tparam Member Index of the function to invoke.
* @tparam Args Types of arguments to pass to the function.
* @param args The arguments to pass to the function.
* @return A poly inspector convertible to any type.
*/
template<auto Member, typename... Args>
poly_inspector invoke(Args &&... args) const;
/*! @copydoc invoke */
template<auto Member, typename... Args>
poly_inspector invoke(Args &&... args);
};
/**
* @brief Static virtual table factory.
* @tparam Concept Concept descriptor.
* @tparam Len Size of the storage reserved for the small buffer optimization.
*/
template<typename Concept, std::size_t Len>
class poly_vtable {
using inspector = typename Concept::template type<poly_inspector>;
template<typename Ret, typename... Args>
static auto vtable_entry(Ret(*)(inspector &, Args...)) -> Ret(*)(basic_any<Len> &, Args...);
template<typename Ret, typename... Args>
static auto vtable_entry(Ret(*)(const inspector &, Args...)) -> Ret(*)(const basic_any<Len> &, Args...);
template<typename Ret, typename... Args>
static auto vtable_entry(Ret(*)(Args...)) -> Ret(*)(const basic_any<Len> &, Args...);
template<typename Ret, typename... Args>
static auto vtable_entry(Ret(inspector:: *)(Args...)) -> Ret(*)(basic_any<Len> &, Args...);
template<typename Ret, typename... Args>
static auto vtable_entry(Ret(inspector:: *)(Args...) const) -> Ret(*)(const basic_any<Len> &, Args...);
template<auto... Candidate>
static auto make_vtable(value_list<Candidate...>)
-> std::tuple<decltype(vtable_entry(Candidate))...>;
template<typename... Func>
[[nodiscard]] static constexpr auto make_vtable(type_list<Func...>) {
if constexpr(sizeof...(Func) == 0) {
return decltype(make_vtable(typename Concept::template impl<inspector>{})){};
} else if constexpr((std::is_function_v<Func> && ...)) {
return decltype(std::make_tuple(vtable_entry(std::declval<Func inspector:: *>())...)){};
}
}
template<typename Type, auto Candidate, typename Ret, typename Any, typename... Args>
static void fill_vtable_entry(Ret(* &entry)(Any &, Args...)) {
if constexpr(std::is_invocable_r_v<Ret, decltype(Candidate), Args...>) {
entry = +[](Any &, Args... args) -> Ret {
return std::invoke(Candidate, std::forward<Args>(args)...);
};
} else {
entry = +[](Any &instance, Args... args) -> Ret {
return static_cast<Ret>(std::invoke(Candidate, any_cast<constness_as_t<Type, Any> &>(instance), std::forward<Args>(args)...));
};
}
}
template<typename Type, auto... Index>
[[nodiscard]] static auto fill_vtable(std::index_sequence<Index...>) {
type impl{};
(fill_vtable_entry<Type, value_list_element_v<Index, typename Concept::template impl<Type>>>(std::get<Index>(impl)), ...);
return impl;
}
public:
/*! @brief Virtual table type. */
using type = decltype(make_vtable(Concept{}));
/**
* @brief Returns a static virtual table for a specific concept and type.
* @tparam Type The type for which to generate the virtual table.
* @return A static virtual table for the given concept and type.
*/
template<typename Type>
[[nodiscard]] static const auto * instance() {
static_assert(std::is_same_v<Type, std::decay_t<Type>>, "Type differs from its decayed form");
static const auto vtable = fill_vtable<Type>(std::make_index_sequence<Concept::template impl<Type>::size>{});
return &vtable;
}
};
/**
* @brief Poly base class used to inject functionalities into concepts.
* @tparam Poly The outermost poly class.
*/
template<typename Poly>
struct poly_base {
/**
* @brief Invokes a function from the static virtual table.
* @tparam Member Index of the function to invoke.
* @tparam Args Types of arguments to pass to the function.
* @param self A reference to the poly object that made the call.
* @param args The arguments to pass to the function.
* @return The return value of the invoked function, if any.
*/
template<auto Member, typename... Args>
[[nodiscard]] decltype(auto) invoke(const poly_base &self, Args &&... args) const {
const auto &poly = static_cast<const Poly &>(self);
return std::get<Member>(*poly.vtable)(poly.storage, std::forward<Args>(args)...);
}
/*! @copydoc invoke */
template<auto Member, typename... Args>
[[nodiscard]] decltype(auto) invoke(poly_base &self, Args &&... args) {
auto &poly = static_cast<Poly &>(self);
return std::get<Member>(*poly.vtable)(poly.storage, std::forward<Args>(args)...);
}
};
/**
* @brief Shortcut for calling `poly_base<Type>::invoke`.
* @tparam Member Index of the function to invoke.
* @tparam Poly A fully defined poly object.
* @tparam Args Types of arguments to pass to the function.
* @param self A reference to the poly object that made the call.
* @param args The arguments to pass to the function.
* @return The return value of the invoked function, if any.
*/
template<auto Member, typename Poly, typename... Args>
decltype(auto) poly_call(Poly &&self, Args &&... args) {
return std::forward<Poly>(self).template invoke<Member>(self, std::forward<Args>(args)...);
}
/**
* @brief Static polymorphism made simple and within everyone's reach.
*
* Static polymorphism is a very powerful tool in C++, albeit sometimes
* cumbersome to obtain.<br/>
* This class aims to make it simple and easy to use.
*
* @note
* Both deduced and defined static virtual tables are supported.<br/>
* Moreover, the `poly` class template also works with unmanaged objects.
*
* @tparam Concept Concept descriptor.
* @tparam Len Size of the storage reserved for the small buffer optimization.
*/
template<typename Concept, std::size_t Len>
class poly: private Concept::template type<poly_base<poly<Concept, Len>>> {
/*! @brief A poly base is allowed to snoop into a poly object. */
friend struct poly_base<poly>;
using vtable_type = typename poly_vtable<Concept, Len>::type;
public:
/*! @brief Concept type. */
using concept_type = typename Concept::template type<poly_base<poly>>;
/*! @brief Default constructor. */
poly() ENTT_NOEXCEPT
: storage{},
vtable{}
{}
/**
* @brief Constructs a poly by directly initializing the new object.
* @tparam Type Type of object to use to initialize the poly.
* @tparam Args Types of arguments to use to construct the new instance.
* @param args Parameters to use to construct the instance.
*/
template<typename Type, typename... Args>
explicit poly(std::in_place_type_t<Type>, Args &&... args)
: storage{std::in_place_type<Type>, std::forward<Args>(args)...},
vtable{poly_vtable<Concept, Len>::template instance<std::remove_const_t<std::remove_reference_t<Type>>>()}
{}
/**
* @brief Constructs a poly that holds an unmanaged object.
* @tparam Type Type of object to use to initialize the poly.
* @param value An instance of an object to use to initialize the poly.
*/
template<typename Type>
poly(std::reference_wrapper<Type> value)
: poly{std::in_place_type<Type &>, value.get()}
{}
/**
* @brief Constructs a poly from a given value.
* @tparam Type Type of object to use to initialize the poly.
* @param value An instance of an object to use to initialize the poly.
*/
template<typename Type, typename = std::enable_if_t<!std::is_same_v<std::remove_cv_t<std::remove_reference_t<Type>>, poly>>>
poly(Type &&value) ENTT_NOEXCEPT
: poly{std::in_place_type<std::remove_cv_t<std::remove_reference_t<Type>>>, std::forward<Type>(value)}
{}
/**
* @brief Copy constructor.
* @param other The instance to copy from.
*/
poly(const poly &other) = default;
/**
* @brief Move constructor.
* @param other The instance to move from.
*/
poly(poly &&other) ENTT_NOEXCEPT
: poly{}
{
swap(*this, other);
}
/**
* @brief Assignment operator.
* @param other The instance to assign from.
* @return This poly object.
*/
poly & operator=(poly other) {
swap(other, *this);
return *this;
}
/**
* @brief Returns the type of the contained object.
* @return The type of the contained object, if any.
*/
[[nodiscard]] type_info type() const ENTT_NOEXCEPT {
return storage.type();
}
/**
* @brief Returns an opaque pointer to the contained instance.
* @return An opaque pointer the contained instance, if any.
*/
[[nodiscard]] const void * data() const ENTT_NOEXCEPT {
return storage.data();
}
/*! @copydoc data */
[[nodiscard]] void * data() ENTT_NOEXCEPT {
return storage.data();
}
/**
* @brief Replaces the contained object by creating a new instance directly.
* @tparam Type Type of object to use to initialize the poly.
* @tparam Args Types of arguments to use to construct the new instance.
* @param args Parameters to use to construct the instance.
*/
template<typename Type, typename... Args>
void emplace(Args &&... args) {
storage.template emplace<Type>(std::forward<Args>(args)...);
vtable = poly_vtable<Concept, Len>::template instance<Type>();
}
/*! @brief Destroys contained object */
void reset() {
*this = poly{};
}
/**
* @brief Returns false if a poly is empty, true otherwise.
* @return False if the poly is empty, true otherwise.
*/
[[nodiscard]] explicit operator bool() const ENTT_NOEXCEPT {
return !(vtable == nullptr);
}
/**
* @brief Returns a pointer to the underlying concept.
* @return A pointer to the underlying concept.
*/
[[nodiscard]] concept_type * operator->() ENTT_NOEXCEPT {
return this;
}
/*! @copydoc operator-> */
[[nodiscard]] const concept_type * operator->() const ENTT_NOEXCEPT {
return this;
}
/**
* @brief Swaps two poly objects.
* @param lhs A valid poly object.
* @param rhs A valid poly object.
*/
friend void swap(poly &lhs, poly &rhs) {
using std::swap;
swap(lhs.storage, rhs.storage);
swap(lhs.vtable, rhs.vtable);
}
/**
* @brief Aliasing constructor.
* @return A poly that shares a reference to an unmanaged object.
*/
[[nodiscard]] poly as_ref() ENTT_NOEXCEPT {
poly ref = std::as_const(*this).as_ref();
ref.storage = storage.as_ref();
return ref;
}
/*! @copydoc as_ref */
[[nodiscard]] poly as_ref() const ENTT_NOEXCEPT {
poly ref{};
ref.storage = storage.as_ref();
ref.vtable = vtable;
return ref;
}
private:
basic_any<Len> storage;
const vtable_type *vtable;
};
}
#endif
<commit_msg>poly: ::emplace support for reference types<commit_after>#ifndef ENTT_POLY_POLY_HPP
#define ENTT_POLY_POLY_HPP
#include <cstddef>
#include <functional>
#include <tuple>
#include <type_traits>
#include <utility>
#include "../config/config.h"
#include "../core/any.hpp"
#include "../core/type_info.hpp"
#include "../core/type_traits.hpp"
#include "fwd.hpp"
namespace entt {
/*! @brief Inspector class used to infer the type of the virtual table. */
struct poly_inspector {
/**
* @brief Generic conversion operator (definition only).
* @tparam Type Type to which conversion is requested.
*/
template <class Type>
operator Type &&() const;
/**
* @brief Dummy invocation function (definition only).
* @tparam Member Index of the function to invoke.
* @tparam Args Types of arguments to pass to the function.
* @param args The arguments to pass to the function.
* @return A poly inspector convertible to any type.
*/
template<auto Member, typename... Args>
poly_inspector invoke(Args &&... args) const;
/*! @copydoc invoke */
template<auto Member, typename... Args>
poly_inspector invoke(Args &&... args);
};
/**
* @brief Static virtual table factory.
* @tparam Concept Concept descriptor.
* @tparam Len Size of the storage reserved for the small buffer optimization.
*/
template<typename Concept, std::size_t Len>
class poly_vtable {
using inspector = typename Concept::template type<poly_inspector>;
template<typename Ret, typename... Args>
static auto vtable_entry(Ret(*)(inspector &, Args...)) -> Ret(*)(basic_any<Len> &, Args...);
template<typename Ret, typename... Args>
static auto vtable_entry(Ret(*)(const inspector &, Args...)) -> Ret(*)(const basic_any<Len> &, Args...);
template<typename Ret, typename... Args>
static auto vtable_entry(Ret(*)(Args...)) -> Ret(*)(const basic_any<Len> &, Args...);
template<typename Ret, typename... Args>
static auto vtable_entry(Ret(inspector:: *)(Args...)) -> Ret(*)(basic_any<Len> &, Args...);
template<typename Ret, typename... Args>
static auto vtable_entry(Ret(inspector:: *)(Args...) const) -> Ret(*)(const basic_any<Len> &, Args...);
template<auto... Candidate>
static auto make_vtable(value_list<Candidate...>)
-> std::tuple<decltype(vtable_entry(Candidate))...>;
template<typename... Func>
[[nodiscard]] static constexpr auto make_vtable(type_list<Func...>) {
if constexpr(sizeof...(Func) == 0) {
return decltype(make_vtable(typename Concept::template impl<inspector>{})){};
} else if constexpr((std::is_function_v<Func> && ...)) {
return decltype(std::make_tuple(vtable_entry(std::declval<Func inspector:: *>())...)){};
}
}
template<typename Type, auto Candidate, typename Ret, typename Any, typename... Args>
static void fill_vtable_entry(Ret(* &entry)(Any &, Args...)) {
if constexpr(std::is_invocable_r_v<Ret, decltype(Candidate), Args...>) {
entry = +[](Any &, Args... args) -> Ret {
return std::invoke(Candidate, std::forward<Args>(args)...);
};
} else {
entry = +[](Any &instance, Args... args) -> Ret {
return static_cast<Ret>(std::invoke(Candidate, any_cast<constness_as_t<Type, Any> &>(instance), std::forward<Args>(args)...));
};
}
}
template<typename Type, auto... Index>
[[nodiscard]] static auto fill_vtable(std::index_sequence<Index...>) {
type impl{};
(fill_vtable_entry<Type, value_list_element_v<Index, typename Concept::template impl<Type>>>(std::get<Index>(impl)), ...);
return impl;
}
public:
/*! @brief Virtual table type. */
using type = decltype(make_vtable(Concept{}));
/**
* @brief Returns a static virtual table for a specific concept and type.
* @tparam Type The type for which to generate the virtual table.
* @return A static virtual table for the given concept and type.
*/
template<typename Type>
[[nodiscard]] static const auto * instance() {
static_assert(std::is_same_v<Type, std::decay_t<Type>>, "Type differs from its decayed form");
static const auto vtable = fill_vtable<Type>(std::make_index_sequence<Concept::template impl<Type>::size>{});
return &vtable;
}
};
/**
* @brief Poly base class used to inject functionalities into concepts.
* @tparam Poly The outermost poly class.
*/
template<typename Poly>
struct poly_base {
/**
* @brief Invokes a function from the static virtual table.
* @tparam Member Index of the function to invoke.
* @tparam Args Types of arguments to pass to the function.
* @param self A reference to the poly object that made the call.
* @param args The arguments to pass to the function.
* @return The return value of the invoked function, if any.
*/
template<auto Member, typename... Args>
[[nodiscard]] decltype(auto) invoke(const poly_base &self, Args &&... args) const {
const auto &poly = static_cast<const Poly &>(self);
return std::get<Member>(*poly.vtable)(poly.storage, std::forward<Args>(args)...);
}
/*! @copydoc invoke */
template<auto Member, typename... Args>
[[nodiscard]] decltype(auto) invoke(poly_base &self, Args &&... args) {
auto &poly = static_cast<Poly &>(self);
return std::get<Member>(*poly.vtable)(poly.storage, std::forward<Args>(args)...);
}
};
/**
* @brief Shortcut for calling `poly_base<Type>::invoke`.
* @tparam Member Index of the function to invoke.
* @tparam Poly A fully defined poly object.
* @tparam Args Types of arguments to pass to the function.
* @param self A reference to the poly object that made the call.
* @param args The arguments to pass to the function.
* @return The return value of the invoked function, if any.
*/
template<auto Member, typename Poly, typename... Args>
decltype(auto) poly_call(Poly &&self, Args &&... args) {
return std::forward<Poly>(self).template invoke<Member>(self, std::forward<Args>(args)...);
}
/**
* @brief Static polymorphism made simple and within everyone's reach.
*
* Static polymorphism is a very powerful tool in C++, albeit sometimes
* cumbersome to obtain.<br/>
* This class aims to make it simple and easy to use.
*
* @note
* Both deduced and defined static virtual tables are supported.<br/>
* Moreover, the `poly` class template also works with unmanaged objects.
*
* @tparam Concept Concept descriptor.
* @tparam Len Size of the storage reserved for the small buffer optimization.
*/
template<typename Concept, std::size_t Len>
class poly: private Concept::template type<poly_base<poly<Concept, Len>>> {
/*! @brief A poly base is allowed to snoop into a poly object. */
friend struct poly_base<poly>;
using vtable_type = typename poly_vtable<Concept, Len>::type;
public:
/*! @brief Concept type. */
using concept_type = typename Concept::template type<poly_base<poly>>;
/*! @brief Default constructor. */
poly() ENTT_NOEXCEPT
: storage{},
vtable{}
{}
/**
* @brief Constructs a poly by directly initializing the new object.
* @tparam Type Type of object to use to initialize the poly.
* @tparam Args Types of arguments to use to construct the new instance.
* @param args Parameters to use to construct the instance.
*/
template<typename Type, typename... Args>
explicit poly(std::in_place_type_t<Type>, Args &&... args)
: storage{std::in_place_type<Type>, std::forward<Args>(args)...},
vtable{poly_vtable<Concept, Len>::template instance<std::remove_const_t<std::remove_reference_t<Type>>>()}
{}
/**
* @brief Constructs a poly that holds an unmanaged object.
* @tparam Type Type of object to use to initialize the poly.
* @param value An instance of an object to use to initialize the poly.
*/
template<typename Type>
poly(std::reference_wrapper<Type> value)
: poly{std::in_place_type<Type &>, value.get()}
{}
/**
* @brief Constructs a poly from a given value.
* @tparam Type Type of object to use to initialize the poly.
* @param value An instance of an object to use to initialize the poly.
*/
template<typename Type, typename = std::enable_if_t<!std::is_same_v<std::remove_cv_t<std::remove_reference_t<Type>>, poly>>>
poly(Type &&value) ENTT_NOEXCEPT
: poly{std::in_place_type<std::remove_cv_t<std::remove_reference_t<Type>>>, std::forward<Type>(value)}
{}
/**
* @brief Copy constructor.
* @param other The instance to copy from.
*/
poly(const poly &other) = default;
/**
* @brief Move constructor.
* @param other The instance to move from.
*/
poly(poly &&other) ENTT_NOEXCEPT
: poly{}
{
swap(*this, other);
}
/**
* @brief Assignment operator.
* @param other The instance to assign from.
* @return This poly object.
*/
poly & operator=(poly other) {
swap(other, *this);
return *this;
}
/**
* @brief Returns the type of the contained object.
* @return The type of the contained object, if any.
*/
[[nodiscard]] type_info type() const ENTT_NOEXCEPT {
return storage.type();
}
/**
* @brief Returns an opaque pointer to the contained instance.
* @return An opaque pointer the contained instance, if any.
*/
[[nodiscard]] const void * data() const ENTT_NOEXCEPT {
return storage.data();
}
/*! @copydoc data */
[[nodiscard]] void * data() ENTT_NOEXCEPT {
return storage.data();
}
/**
* @brief Replaces the contained object by creating a new instance directly.
* @tparam Type Type of object to use to initialize the poly.
* @tparam Args Types of arguments to use to construct the new instance.
* @param args Parameters to use to construct the instance.
*/
template<typename Type, typename... Args>
void emplace(Args &&... args) {
*this = poly{std::in_place_type<Type>, std::forward<Args>(args)...};
}
/*! @brief Destroys contained object */
void reset() {
*this = poly{};
}
/**
* @brief Returns false if a poly is empty, true otherwise.
* @return False if the poly is empty, true otherwise.
*/
[[nodiscard]] explicit operator bool() const ENTT_NOEXCEPT {
return !(vtable == nullptr);
}
/**
* @brief Returns a pointer to the underlying concept.
* @return A pointer to the underlying concept.
*/
[[nodiscard]] concept_type * operator->() ENTT_NOEXCEPT {
return this;
}
/*! @copydoc operator-> */
[[nodiscard]] const concept_type * operator->() const ENTT_NOEXCEPT {
return this;
}
/**
* @brief Swaps two poly objects.
* @param lhs A valid poly object.
* @param rhs A valid poly object.
*/
friend void swap(poly &lhs, poly &rhs) {
using std::swap;
swap(lhs.storage, rhs.storage);
swap(lhs.vtable, rhs.vtable);
}
/**
* @brief Aliasing constructor.
* @return A poly that shares a reference to an unmanaged object.
*/
[[nodiscard]] poly as_ref() ENTT_NOEXCEPT {
poly ref = std::as_const(*this).as_ref();
ref.storage = storage.as_ref();
return ref;
}
/*! @copydoc as_ref */
[[nodiscard]] poly as_ref() const ENTT_NOEXCEPT {
poly ref{};
ref.storage = storage.as_ref();
ref.vtable = vtable;
return ref;
}
private:
basic_any<Len> storage;
const vtable_type *vtable;
};
}
#endif
<|endoftext|>
|
<commit_before>/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* expand/include.cpp
* - include!/include_str!/include_bytes! support
*/
#include <synext_macro.hpp>
#include <synext.hpp> // for Expand_BareExpr
#include <parse/common.hpp>
#include <parse/parseerror.hpp> // for GET_CHECK_TOK
#include <parse/ttstream.hpp>
#include <parse/lex.hpp> // Lexer (new files)
#include <ast/expr.hpp>
namespace {
::std::string get_string(const Span& sp, TokenStream& lex, const ::AST::Crate& crate, AST::Module& mod)
{
auto n = Parse_ExprVal(lex);
ASSERT_BUG(sp, n, "No expression returned");
Expand_BareExpr(crate, mod, n);
auto* string_np = dynamic_cast<AST::ExprNode_String*>(&*n);
if( !string_np ) {
ERROR(sp, E0000, "include! requires a string literal - got " << *n);
}
return mv$( string_np->m_value );
}
::std::string get_path_relative_to(const ::std::string& base_path, ::std::string path)
{
if( path[0] == '/' ) {
return path;
}
else if( base_path.size() == 0 ) {
return path;
}
else if( base_path[base_path.size()-1] == '/' ) {
return base_path + path;
}
else {
auto slash = base_path.find_last_of('/');
if( slash == ::std::string::npos )
{
return path;
}
else
{
slash += 1;
::std::string rv;
rv.reserve( slash + path.size() );
rv.append( base_path.begin(), base_path.begin() + slash );
rv.append( path.begin(), path.end() );
return rv;
}
}
}
};
class CIncludeExpander:
public ExpandProcMacro
{
::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override
{
if( ident != "" )
ERROR(sp, E0000, "include! doesn't take an ident");
Token tok;
auto lex = TTStream(tt);
auto path = get_string(sp, lex, crate, mod);
GET_CHECK_TOK(tok, lex, TOK_EOF);
::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));
return box$( Lexer(file_path) );
}
};
// TODO: include_str! and include_bytes!
STATIC_MACRO("include", CIncludeExpander);
<commit_msg>Expand - Handle windows paths in `include!`<commit_after>/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* expand/include.cpp
* - include!/include_str!/include_bytes! support
*/
#include <synext_macro.hpp>
#include <synext.hpp> // for Expand_BareExpr
#include <parse/common.hpp>
#include <parse/parseerror.hpp> // for GET_CHECK_TOK
#include <parse/ttstream.hpp>
#include <parse/lex.hpp> // Lexer (new files)
#include <ast/expr.hpp>
namespace {
::std::string get_string(const Span& sp, TokenStream& lex, const ::AST::Crate& crate, AST::Module& mod)
{
auto n = Parse_ExprVal(lex);
ASSERT_BUG(sp, n, "No expression returned");
Expand_BareExpr(crate, mod, n);
auto* string_np = dynamic_cast<AST::ExprNode_String*>(&*n);
if( !string_np ) {
ERROR(sp, E0000, "include! requires a string literal - got " << *n);
}
return mv$( string_np->m_value );
}
::std::string get_path_relative_to(const ::std::string& base_path, ::std::string path)
{
DEBUG(base_path << ", " << path);
if( path[0] == '/' || path[0] == '\\' ) {
return path;
}
else if( base_path.size() == 0 ) {
return path;
}
else if( base_path.back() == '/' || base_path.back() == '\\' ) {
return base_path + path;
}
else {
auto slash = ::std::min( base_path.find_last_of('/'), base_path.find_last_of('\\') );
if( slash == ::std::string::npos )
{
return path;
}
else
{
slash += 1;
::std::string rv;
rv.reserve( slash + path.size() );
rv.append( base_path.begin(), base_path.begin() + slash );
rv.append( path.begin(), path.end() );
return rv;
}
}
}
};
class CIncludeExpander:
public ExpandProcMacro
{
::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override
{
if( ident != "" )
ERROR(sp, E0000, "include! doesn't take an ident");
Token tok;
auto lex = TTStream(tt);
auto path = get_string(sp, lex, crate, mod);
GET_CHECK_TOK(tok, lex, TOK_EOF);
::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));
try {
return box$( Lexer(file_path) );
}
catch(::std::runtime_error& e)
{
ERROR(sp, E0000, e.what());
}
}
};
// TODO: include_str! and include_bytes!
STATIC_MACRO("include", CIncludeExpander);
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2020, The Regents of the University of California
// 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 copyright holder 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.
///////////////////////////////////////////////////////////////////////////////
#include "fin/Finale.h"
#include "DensityFill.h"
namespace fin {
////////////////////////////////////////////////////////////////
Finale::Finale() : db_(nullptr), debug_(false)
{
}
void Finale::init(odb::dbDatabase* db, Logger* logger)
{
db_ = db;
logger_ = logger;
}
void Finale::setDebug()
{
debug_ = true;
}
void Finale::densityFill(const char* rules_filename, const odb::Rect& fill_area)
{
DensityFill filler(db_, logger_, debug_);
filler.fill(rules_filename, fill_area);
}
} // namespace fin
<commit_msg>fin: coverity fixes<commit_after>/////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2020, The Regents of the University of California
// 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 copyright holder 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.
///////////////////////////////////////////////////////////////////////////////
#include "DensityFill.h"
#include "fin/Finale.h"
namespace fin {
////////////////////////////////////////////////////////////////
Finale::Finale() : db_(nullptr), logger_(nullptr), debug_(false)
{
}
void Finale::init(odb::dbDatabase* db, Logger* logger)
{
db_ = db;
logger_ = logger;
}
void Finale::setDebug()
{
debug_ = true;
}
void Finale::densityFill(const char* rules_filename, const odb::Rect& fill_area)
{
DensityFill filler(db_, logger_, debug_);
filler.fill(rules_filename, fill_area);
}
} // namespace fin
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <kangaru/kangaru.hpp>
/**
* This example explains moderate use of kangaru and it's components.
* It covers providing instances to the container, self-injection
*/
using std::string;
using std::cout;
using std::endl;
using std::move;
struct WoodStack {
int planks;
};
struct Product {
Product(WoodStack& stack) {
stack.planks--;
}
string name;
};
// This is our wood stack service definition
struct WoodStackService : kgr::SingleService<WoodStack> {};
// This is our product service definition
struct ProductService : kgr::Service<Product, kgr::Dependency<WoodStackService>> {};
struct Carpenter {
Carpenter(kgr::Container& _container, WoodStack& _stack) : container{_container}, stack{_stack} {}
// We are using ServiceType, which in this case is an alias to unique_ptr<Product>.
void makeProduct(string name) {
if (stack.planks > 0) {
cout << "Another " << name << " made, but only " << stack.planks << " planks left!" << endl;
auto product = container.service<ProductService>();
product.name = name;
products.emplace_back(move(product));
} else {
cout << "No planks left, no product made." << endl;
}
}
private:
std::vector<Product> products;
kgr::Container& container;
WoodStack& stack;
};
// This is our carpenter service definition
struct CarpenterService : kgr::Service<Carpenter, kgr::Dependency<kgr::ContainerService, WoodStackService>> {};
int main()
{
kgr::Container container;
// We made the stack ourself and set the number of planks to 2
WoodStack stack{2};
// We are providing our stack instance to the container.
container.instance<WoodStackService>(std::move(stack));
// It has the Container and the WoodStack injected.
auto gerald = container.service<CarpenterService>();
// Will print: Another computer desk made, but only 1 planks left!
gerald.makeProduct("computer desk");
// Will print: Another chair made, but only 0 planks left!
gerald.makeProduct("chair");
// Will print: No planks left, no product made.
// As a result, product3 is not made.
gerald.makeProduct("table");
}
<commit_msg>Using emplace instead of instanciate<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <kangaru/kangaru.hpp>
/**
* This example explains moderate use of kangaru and it's components.
* It covers providing instances to the container, self-injection
*/
using std::string;
using std::cout;
using std::endl;
using std::move;
struct WoodStack {
int planks;
};
struct Product {
Product(WoodStack& stack) {
stack.planks--;
}
string name;
};
// This is our wood stack service definition
struct WoodStackService : kgr::SingleService<WoodStack> {};
// This is our product service definition
struct ProductService : kgr::Service<Product, kgr::Dependency<WoodStackService>> {};
struct Carpenter {
Carpenter(kgr::Container& _container, WoodStack& _stack) : container{_container}, stack{_stack} {}
// We are using ServiceType, which in this case is an alias to unique_ptr<Product>.
void makeProduct(string name) {
if (stack.planks > 0) {
cout << "Another " << name << " made, but only " << stack.planks << " planks left!" << endl;
auto product = container.service<ProductService>();
product.name = name;
products.emplace_back(move(product));
} else {
cout << "No planks left, no product made." << endl;
}
}
private:
std::vector<Product> products;
kgr::Container& container;
WoodStack& stack;
};
// This is our carpenter service definition
struct CarpenterService : kgr::Service<Carpenter, kgr::Dependency<kgr::ContainerService, WoodStackService>> {};
int main()
{
kgr::Container container;
// We made the stack ourself and set the number of planks to 2
container.emplace<WoodStackService>(2);
// It has the Container and the WoodStack injected.
auto gerald = container.service<CarpenterService>();
// Will print: Another computer desk made, but only 1 planks left!
gerald.makeProduct("computer desk");
// Will print: Another chair made, but only 0 planks left!
gerald.makeProduct("chair");
// Will print: No planks left, no product made.
// As a result, product3 is not made.
gerald.makeProduct("table");
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <memory>
#include "kangaru.hpp"
/**
* This example explains moderate use of kangaru and it's components.
* It covers providing instances to the container, self-injection
*/
using namespace std;
using namespace kgr;
struct WoodStack {
int planks;
};
struct Product {
Product(WoodStack* stack) {
stack->planks--;
}
string name;
};
// This is our wood stack service definitions
struct WoodStackService : Type<WoodStack*>, Single {
WoodStackService(shared_ptr<WoodStack> instance) : _instance{move(instance)} {}
static WoodStackService construct() {
return make_shared<WoodStack>();
}
ServiceType forward() {
return _instance.get();
}
private:
shared_ptr<WoodStack> _instance;
};
// This is our product service definitions
struct ProductService : Type<unique_ptr<Product>> {
ProductService(unique_ptr<Product> instance) : _instance{move(instance)} {}
static ProductService construct(WoodStackService& stack) {
return unique_ptr<Product>(new Product{stack.forward()});
}
ServiceType forward() {
return move(_instance);
}
private:
unique_ptr<Product> _instance;
};
struct Carpenter {
Carpenter(Container& _container, WoodStack* _stack) : container{&_container}, stack{_stack} {}
// We are using ServiceType, which in this case is an alias to unique_ptr<Product>.
// Since the pointer type can be changed, using only unique_ptr here may be wrong.
ProductService::ServiceType makeProduct(string name) {
if (stack->planks > 0) {
cout << "Another " << name << " made, but only " << stack->planks << " planks left!" << endl;
auto product = container->service<ProductService>();
product->name = name;
return product;
}
cout << "No planks left, no product made." << endl;
return nullptr;
}
private:
Container* container;
WoodStack* stack;
};
// This is our carpenter service definitions
struct CarpenterService : Type<Carpenter> {
CarpenterService(Carpenter instance) : _instance{move(instance)} {}
static CarpenterService construct(ContainerService container, WoodStackService& stack) {
return Carpenter{container.forward(), stack.forward()};
}
ServiceType forward() {
return move(_instance);
}
private:
Carpenter _instance;
};
int main()
{
auto container = make_container();
// We made the stack ourself and set the number of planks to 2
auto stack = make_shared<WoodStack>();
// We are providing our stack instance to the container.
container.instance(WoodStackService{stack});
stack->planks = 2;
// It has the Container and the WoodStack injected.
auto gerald = container.service<CarpenterService>();
// Will print: Another computer desk made, but only 1 planks left!
auto product1 = gerald.makeProduct("computer desk");
// Will print: Another chair made, but only 0 planks left!
auto product2 = gerald.makeProduct("chair");
// Will print: No planks left, no product made.
// As a result, product3 is null.
auto product3 = gerald.makeProduct("table");
if (!product3) {
cout << "There's definitely no product made!" << endl;
}
return 0;
}
<commit_msg>removed Type<commit_after>#include <iostream>
#include <string>
#include <memory>
#include "kangaru.hpp"
/**
* This example explains moderate use of kangaru and it's components.
* It covers providing instances to the container, self-injection
*/
using namespace std;
using namespace kgr;
struct WoodStack {
int planks;
};
struct Product {
Product(WoodStack* stack) {
stack->planks--;
}
string name;
};
// This is our wood stack service definitions
struct WoodStackService : Single {
WoodStackService(shared_ptr<WoodStack> instance) : _instance{move(instance)} {}
static WoodStackService construct() {
return make_shared<WoodStack>();
}
WoodStack* forward() {
return _instance.get();
}
private:
shared_ptr<WoodStack> _instance;
};
// This is our product service definitions
struct ProductService {
ProductService(unique_ptr<Product> instance) : _instance{move(instance)} {}
static ProductService construct(WoodStackService& stack) {
return unique_ptr<Product>(new Product{stack.forward()});
}
unique_ptr<Product> forward() {
return move(_instance);
}
private:
unique_ptr<Product> _instance;
};
struct Carpenter {
Carpenter(Container& _container, WoodStack* _stack) : container{&_container}, stack{_stack} {}
// We are using ServiceType, which in this case is an alias to unique_ptr<Product>.
// Since the pointer type can be changed, using only unique_ptr here may be wrong.
ServiceType<ProductService> makeProduct(string name) {
if (stack->planks > 0) {
cout << "Another " << name << " made, but only " << stack->planks << " planks left!" << endl;
auto product = container->service<ProductService>();
product->name = name;
return product;
}
cout << "No planks left, no product made." << endl;
return nullptr;
}
private:
Container* container;
WoodStack* stack;
};
// This is our carpenter service definitions
struct CarpenterService {
CarpenterService(Carpenter instance) : _instance{move(instance)} {}
static CarpenterService construct(ContainerService container, WoodStackService& stack) {
return Carpenter{container.forward(), stack.forward()};
}
Carpenter forward() {
return move(_instance);
}
private:
Carpenter _instance;
};
int main()
{
auto container = make_container();
// We made the stack ourself and set the number of planks to 2
auto stack = make_shared<WoodStack>();
// We are providing our stack instance to the container.
container.instance(WoodStackService{stack});
stack->planks = 2;
// It has the Container and the WoodStack injected.
auto gerald = container.service<CarpenterService>();
// Will print: Another computer desk made, but only 1 planks left!
auto product1 = gerald.makeProduct("computer desk");
// Will print: Another chair made, but only 0 planks left!
auto product2 = gerald.makeProduct("chair");
// Will print: No planks left, no product made.
// As a result, product3 is null.
auto product3 = gerald.makeProduct("table");
if (!product3) {
cout << "There's definitely no product made!" << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#include <tools/iparser.hxx>
#include <tools/geninfo.hxx>
#include "bootstrp/appdef.hxx"
#include <stdio.h>
/*****************************************************************************/
#ifdef UNX
int main( int argc, char *argv[] )
#else
int _cdecl main( int argc, char *argv[] )
#endif
/*****************************************************************************/
{
if ( argc == 1 ) {
fprintf( stdout, "\ni_server.exe v2.0 (c) 2000\n\n" );
fprintf( stdout, "Syntax: i_server -i accesspath [-l] [-d database] \n" );
fprintf( stdout, "Example: - i_server -i vcl364/settings/now\n" );
fprintf( stdout, " returns value of settings \"now\" of version \"vcl364\"\n" );
fprintf( stdout, " - i_server -i vcl364/settings -l\n" );
fprintf( stdout, " returns a list of all settings of version \"vcl364\"\n" );
}
else {
BOOL bError = FALSE;
BOOL bList = FALSE;
ByteString sInfo( "" );
ByteString sDataBase( GetDefStandList());
BOOL bGetNow = FALSE;
int nCount = 1;
while (( nCount < argc ) &&
( !bError ))
{
if ( ByteString( argv[nCount] ).ToUpperAscii() == "-I" ) {
// requestet info path
nCount++;
if( nCount < argc ) {
sInfo = ByteString( argv[nCount] );
nCount++;
}
else bError = TRUE;
}
else if ( ByteString( argv[nCount] ).ToUpperAscii() == "-D" ) {
// requestet info path
nCount++;
if( nCount < argc ) {
sDataBase = ByteString( argv[nCount] );
nCount++;
}
else bError = TRUE;
}
else if ( ByteString( argv[nCount] ).ToUpperAscii() == "-L" ) {
// request list of childs
nCount++;
bList = TRUE;
}
else if ( ByteString( argv[nCount] ).ToUpperAscii() == "-N" ) {
// request list of childs
nCount++;
bGetNow = TRUE;
}
else {
bError = TRUE;
}
}
if ( !bError ) {
InformationParser aParser( REPLACE_VARIABLES );
ByteString sStandList( sDataBase );
String s = String( sStandList, gsl_getSystemTextEncoding());
GenericInformationList *pList = aParser.Execute( s );
if ( !pList )
return 1;
if ( sInfo.Len()) {
GenericInformation *pInfo = pList->GetInfo( sInfo, TRUE );
if ( pInfo ) {
ByteString sValue( pInfo->GetValue());
// show the info and its value
fprintf( stdout, "%s %s\n", pInfo->GetBuffer(), sValue.GetBuffer());
if ( bList ) {
GenericInformationList *pList = pInfo->GetSubList();
if ( pList ) {
// show whole list of childs and their values
for( ULONG i = 0; i < pList->Count(); i++ ) {
GenericInformation *pInfo = pList->GetObject( i );
ByteString sValue( pInfo->GetValue());
fprintf( stdout, " %s %s\n", pInfo->GetBuffer(), sValue.GetBuffer());
}
}
}
return 0;
}
return 1;
}
else {
// show whole list of childs and their values
for( ULONG i = 0; i < pList->Count(); i++ ) {
GenericInformation *pInfo = pList->GetObject( i );
if ( bGetNow ) {
ByteString sPath( "settings/now" );
GenericInformation *pSubInfo = pInfo->GetSubInfo( sPath, TRUE );
if ( pSubInfo && pSubInfo->GetValue() == "_TRUE" )
fprintf( stdout, "%s\n", pInfo->GetBuffer());
}
else {
ByteString sValue( pInfo->GetValue());
fprintf( stdout, " %s %s\n", pInfo->GetBuffer(), sValue.GetBuffer());
}
}
return 0;
}
}
else
fprintf( stderr, "%s: Fehler in der Kommandozeile!", argv[0] );
// command line arror !!!
}
return 1;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Removed an uncompiled file<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Luke San Antonio
* All rights reserved.
*/
#include "program.h"
#include <sstream>
#include <fstream>
#include "../../common/log.h"
namespace survive
{
namespace gfx
{
namespace gl
{
std::string load_stream(std::istream&& stream) noexcept
{
std::string ret;
while(!stream.eof() && stream.good())
{
ret.push_back(stream.get());
}
return ret;
}
void compile_shader(GLuint shade, std::string const& data)
{
int len = data.size();
auto data_cstr = data.data();
glShaderSource(shade, 1, &data_cstr, &len);
glCompileShader(shade);
GLint result = 0;
glGetShaderiv(shade, GL_COMPILE_STATUS, &result);
if(result == GL_FALSE)
{
// Compilation failed.
constexpr size_t info_log_length = 2048;
auto info_log = new char[info_log_length];
glGetShaderInfoLog(shade, info_log_length - 1, NULL, info_log);
info_log[info_log_length - 1] = '\0';
log_e("Shader compilation failed (info log):\n%", info_log);
delete[] info_log;
}
}
Program Program::from_contents(std::string v, std::string f) noexcept
{
auto program = Program{};
program.vshade = glCreateShader(GL_VERTEX_SHADER);
program.fshade = glCreateShader(GL_FRAGMENT_SHADER);
compile_shader(program.vshade, v);
compile_shader(program.fshade, f);
program.program = glCreateProgram();
glAttachShader(program.program, program.vshade);
glAttachShader(program.program, program.fshade);
glLinkProgram(program.program);
GLint result = GL_FALSE;
glGetProgramiv(program.program, GL_LINK_STATUS, &result);
if(result == GL_FALSE)
{
// Compilation failed.
constexpr size_t info_log_length = 2048;
auto info_log = new char[info_log_length];
glGetProgramInfoLog(program.program, info_log_length - 1, NULL,
info_log);
info_log[info_log_length - 1] = '\0';
log_e("Program linking failed (info log):\n%", info_log);
delete[] info_log;
}
return program;
}
Program Program::from_streams(std::istream&& v, std::istream&& f) noexcept
{
return Program::from_contents(load_stream(std::move(v)),
load_stream(std::move(f)));
}
Program Program::from_files(std::string vs, std::string fs) noexcept
{
std::ifstream vsfile{vs};
std::ifstream fsfile{fs};
return Program::from_streams(std::move(vsfile), std::move(fsfile));
}
void Program::use() noexcept
{
glUseProgram(program);
}
GLint Program::get_uniform_location(std::string n) noexcept
{
return glGetUniformLocation(program, n.data());
}
Program::Program(Program&& p1) noexcept
: vshade(p1.vshade), fshade(p1.fshade),
program(p1.program)
{
p1.vshade = 0;
p1.fshade = 0;
p1.program = 0;
}
Program& Program::operator=(Program&& p1) noexcept
{
vshade = p1.vshade;
fshade = p1.fshade;
program = p1.program;
p1.vshade = 0;
p1.fshade = 0;
p1.program = 0;
return *this;
}
Program::~Program() noexcept
{
#ifndef SURVIVE_RELEASE_BUILD
GLint current_program;
glGetIntegerv(GL_CURRENT_PROGRAM, ¤t_program);
if(static_cast<GLuint>(current_program) == program)
{
log_w("% (Shader program) destructed while in use;"
"Removing binding", name);
glUseProgram(0);
}
#endif
if(program) glDeleteProgram(program);
if(fshade) glDeleteProgram(fshade);
if(vshade) glDeleteProgram(vshade);
}
}
}
}
<commit_msg>Changed the warning string in the Program destructor.<commit_after>/*
* Copyright (C) 2014 Luke San Antonio
* All rights reserved.
*/
#include "program.h"
#include <sstream>
#include <fstream>
#include "../../common/log.h"
namespace survive
{
namespace gfx
{
namespace gl
{
std::string load_stream(std::istream&& stream) noexcept
{
std::string ret;
while(!stream.eof() && stream.good())
{
ret.push_back(stream.get());
}
return ret;
}
void compile_shader(GLuint shade, std::string const& data)
{
int len = data.size();
auto data_cstr = data.data();
glShaderSource(shade, 1, &data_cstr, &len);
glCompileShader(shade);
GLint result = 0;
glGetShaderiv(shade, GL_COMPILE_STATUS, &result);
if(result == GL_FALSE)
{
// Compilation failed.
constexpr size_t info_log_length = 2048;
auto info_log = new char[info_log_length];
glGetShaderInfoLog(shade, info_log_length - 1, NULL, info_log);
info_log[info_log_length - 1] = '\0';
log_e("Shader compilation failed (info log):\n%", info_log);
delete[] info_log;
}
}
Program Program::from_contents(std::string v, std::string f) noexcept
{
auto program = Program{};
program.vshade = glCreateShader(GL_VERTEX_SHADER);
program.fshade = glCreateShader(GL_FRAGMENT_SHADER);
compile_shader(program.vshade, v);
compile_shader(program.fshade, f);
program.program = glCreateProgram();
glAttachShader(program.program, program.vshade);
glAttachShader(program.program, program.fshade);
glLinkProgram(program.program);
GLint result = GL_FALSE;
glGetProgramiv(program.program, GL_LINK_STATUS, &result);
if(result == GL_FALSE)
{
// Compilation failed.
constexpr size_t info_log_length = 2048;
auto info_log = new char[info_log_length];
glGetProgramInfoLog(program.program, info_log_length - 1, NULL,
info_log);
info_log[info_log_length - 1] = '\0';
log_e("Program linking failed (info log):\n%", info_log);
delete[] info_log;
}
return program;
}
Program Program::from_streams(std::istream&& v, std::istream&& f) noexcept
{
return Program::from_contents(load_stream(std::move(v)),
load_stream(std::move(f)));
}
Program Program::from_files(std::string vs, std::string fs) noexcept
{
std::ifstream vsfile{vs};
std::ifstream fsfile{fs};
return Program::from_streams(std::move(vsfile), std::move(fsfile));
}
void Program::use() noexcept
{
glUseProgram(program);
}
GLint Program::get_uniform_location(std::string n) noexcept
{
return glGetUniformLocation(program, n.data());
}
Program::Program(Program&& p1) noexcept
: vshade(p1.vshade), fshade(p1.fshade),
program(p1.program)
{
p1.vshade = 0;
p1.fshade = 0;
p1.program = 0;
}
Program& Program::operator=(Program&& p1) noexcept
{
vshade = p1.vshade;
fshade = p1.fshade;
program = p1.program;
p1.vshade = 0;
p1.fshade = 0;
p1.program = 0;
return *this;
}
Program::~Program() noexcept
{
#ifndef SURVIVE_RELEASE_BUILD
GLint current_program;
glGetIntegerv(GL_CURRENT_PROGRAM, ¤t_program);
if(static_cast<GLuint>(current_program) == program)
{
log_w("'%' (Shader program) destructed while in use; "
"Removing binding", name);
glUseProgram(0);
}
#endif
if(program) glDeleteProgram(program);
if(fshade) glDeleteProgram(fshade);
if(vshade) glDeleteProgram(vshade);
}
}
}
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CoreGameState.cc
// (C) 2013-2015 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "Coregamestate.h"
#include "graphicsfeatureunit.h"
#include "input/keyboard.h"
#include "coreproject/coregameapplication.h"
namespace Tools
{
__ImplementClass(Tools::CoreGameState, 'CMGS', BaseGameFeature::GameStateHandler);
using namespace BaseGameFeature;
using namespace GraphicsFeature;
using namespace Util;
using namespace Math;
//------------------------------------------------------------------------------
/**
*/
CoreGameState::CoreGameState()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
CoreGameState::~CoreGameState()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnStateEnter( const Util::String& prevState )
{
GameStateHandler::OnStateEnter(prevState);
this->focusset = false;
//const Ptr<UI::UiLayout>& layout = UI::UiFeatureUnit::Instance()->GetLayout("main_menu");
//Ptr<UI::UiElement> element = layout->GetElement("updatetext");
//return element->GetText();
}
//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnStateLeave( const Util::String& nextState )
{
GameStateHandler::OnStateLeave(nextState);
}
//------------------------------------------------------------------------------
/**
*/
Util::String
CoreGameState::OnFrame()
{
//handle all user input
if (Input::InputServer::HasInstance())
{
this->HandleInput();
}
return GameStateHandler::OnFrame();
}
//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnLoadBefore()
{
}
//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnLoadAfter()
{
}
void CoreGameState::OnNetworkStarted()
{
}
//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::HandleInput()
{
const Ptr<Input::Keyboard>& kbd = Input::InputServer::Instance()->GetDefaultKeyboard();
if (kbd->KeyPressed(Input::Key::H))
{
this->player = FactoryManager::Instance()->CreateEntityByTemplate("Player", "dummychar");
EntityManager::Instance()->AttachEntity(this->player);
FocusManager::Instance()->SetCameraFocusEntity(this->player, false);
FocusManager::Instance()->SetInputFocusEntity(this->player, false);
}
if(kbd->KeyPressed(Input::Key::J))
{
if (player != NULL)
{
FocusManager::Instance()->SetCameraFocusEntity(this->player, false);
FocusManager::Instance()->SetInputFocusEntity(this->player, false);
}
}
}
} // namespace Tools<commit_msg>Spawn fix<commit_after>//------------------------------------------------------------------------------
// CoreGameState.cc
// (C) 2013-2015 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "Coregamestate.h"
#include "graphicsfeatureunit.h"
#include "input/keyboard.h"
#include "coreproject/coregameapplication.h"
namespace Tools
{
__ImplementClass(Tools::CoreGameState, 'CMGS', BaseGameFeature::GameStateHandler);
using namespace BaseGameFeature;
using namespace GraphicsFeature;
using namespace Util;
using namespace Math;
//------------------------------------------------------------------------------
/**
*/
CoreGameState::CoreGameState()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
CoreGameState::~CoreGameState()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnStateEnter( const Util::String& prevState )
{
GameStateHandler::OnStateEnter(prevState);
this->focusset = false;
//const Ptr<UI::UiLayout>& layout = UI::UiFeatureUnit::Instance()->GetLayout("main_menu");
//Ptr<UI::UiElement> element = layout->GetElement("updatetext");
//return element->GetText();
}
//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnStateLeave( const Util::String& nextState )
{
GameStateHandler::OnStateLeave(nextState);
}
//------------------------------------------------------------------------------
/**
*/
Util::String
CoreGameState::OnFrame()
{
//handle all user input
if (Input::InputServer::HasInstance())
{
this->HandleInput();
}
return GameStateHandler::OnFrame();
}
//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnLoadBefore()
{
}
//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnLoadAfter()
{
}
void CoreGameState::OnNetworkStarted()
{
}
//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::HandleInput()
{
const Ptr<Input::Keyboard>& kbd = Input::InputServer::Instance()->GetDefaultKeyboard();
if (kbd->KeyDown(Input::Key::H))
{
this->player = FactoryManager::Instance()->CreateEntityByTemplate("Player", "dummychar");
EntityManager::Instance()->AttachEntity(this->player);
FocusManager::Instance()->SetCameraFocusEntity(this->player, false);
FocusManager::Instance()->SetInputFocusEntity(this->player, false);
}
if (kbd->KeyDown(Input::Key::J))
{
if (player != NULL)
{
FocusManager::Instance()->SetCameraFocusEntity(this->player, false);
FocusManager::Instance()->SetInputFocusEntity(this->player, false);
}
}
}
} // namespace Tools<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_aura.h"
#include "chrome/browser/tab_contents/web_drop_target_win.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_delegate.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_views.h"
#include "content/browser/renderer_host/render_widget_host_view_aura.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/tab_contents/tab_contents_view.h"
#include "ui/aura/event.h"
#include "ui/aura/window.h"
#include "views/views_delegate.h"
#include "views/widget/widget.h"
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewAura, public:
NativeTabContentsViewAura::NativeTabContentsViewAura(
internal::NativeTabContentsViewDelegate* delegate)
: views::NativeWidgetAura(delegate->AsNativeWidgetDelegate()),
delegate_(delegate) {
}
NativeTabContentsViewAura::~NativeTabContentsViewAura() {
}
TabContents* NativeTabContentsViewAura::GetTabContents() const {
return delegate_->GetTabContents();
}
void NativeTabContentsViewAura::EndDragging() {
delegate_->OnNativeTabContentsViewDraggingEnded();
// TODO(beng):
NOTIMPLEMENTED();
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewAura, NativeTabContentsView implementation:
void NativeTabContentsViewAura::InitNativeTabContentsView() {
views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
params.native_widget = this;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.parent = NULL;
GetWidget()->Init(params);
}
void NativeTabContentsViewAura::Unparent() {
// Note that we do not DCHECK on focus_manager_ as it may be NULL when used
// with an external tab container.
views::Widget::ReparentNativeView(GetNativeView(), NULL);
// TODO(beng):
NOTIMPLEMENTED();
}
RenderWidgetHostView* NativeTabContentsViewAura::CreateRenderWidgetHostView(
RenderWidgetHost* render_widget_host) {
RenderWidgetHostViewAura* view =
new RenderWidgetHostViewAura(render_widget_host);
view->Init();
GetNativeView()->AddChild(view->GetNativeView());
view->Show();
return view;
}
gfx::NativeWindow NativeTabContentsViewAura::GetTopLevelNativeWindow() const {
// TODO(beng):
NOTIMPLEMENTED();
return NULL;
}
void NativeTabContentsViewAura::SetPageTitle(const string16& title) {
// TODO(beng):
NOTIMPLEMENTED();
}
void NativeTabContentsViewAura::StartDragging(const WebDropData& drop_data,
WebKit::WebDragOperationsMask ops,
const SkBitmap& image,
const gfx::Point& image_offset) {
// TODO(beng):
NOTIMPLEMENTED();
}
void NativeTabContentsViewAura::CancelDrag() {
// TODO(beng):
NOTIMPLEMENTED();
}
bool NativeTabContentsViewAura::IsDoingDrag() const {
// TODO(beng):
NOTIMPLEMENTED();
return false;
}
void NativeTabContentsViewAura::SetDragCursor(
WebKit::WebDragOperation operation) {
// TODO(beng):
NOTIMPLEMENTED();
}
views::NativeWidget* NativeTabContentsViewAura::AsNativeWidget() {
return this;
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewAura, views::NativeWidgetAura overrides:
void NativeTabContentsViewAura::OnBoundsChanged(const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds) {
delegate_->OnNativeTabContentsViewSized(new_bounds.size());
views::NativeWidgetAura::OnBoundsChanged(old_bounds, new_bounds);
}
bool NativeTabContentsViewAura::OnMouseEvent(aura::MouseEvent* event) {
if (!delegate_->IsShowingSadTab()) {
switch (event->type()) {
case ui::ET_MOUSE_EXITED:
delegate_->OnNativeTabContentsViewMouseMove(false);
break;
case ui::ET_MOUSE_MOVED:
delegate_->OnNativeTabContentsViewMouseMove(true);
break;
default:
// TODO(oshima): mouse wheel
break;
}
}
// Pass all mouse event to renderer.
return views::NativeWidgetAura::OnMouseEvent(event);
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsView, public:
// static
NativeTabContentsView* NativeTabContentsView::CreateNativeTabContentsView(
internal::NativeTabContentsViewDelegate* delegate) {
return new NativeTabContentsViewViews(delegate);
// TODO(beng): switch over to this.
// return new NativeTabContentsViewAura(delegate);
}
<commit_msg>Fix aura bustage. Was part of earlier CL but not included in CL for some reason.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_aura.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_delegate.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_views.h"
#include "content/browser/renderer_host/render_widget_host_view_aura.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/tab_contents/tab_contents_view.h"
#include "ui/aura/event.h"
#include "ui/aura/window.h"
#include "views/views_delegate.h"
#include "views/widget/widget.h"
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewAura, public:
NativeTabContentsViewAura::NativeTabContentsViewAura(
internal::NativeTabContentsViewDelegate* delegate)
: views::NativeWidgetAura(delegate->AsNativeWidgetDelegate()),
delegate_(delegate) {
}
NativeTabContentsViewAura::~NativeTabContentsViewAura() {
}
TabContents* NativeTabContentsViewAura::GetTabContents() const {
return delegate_->GetTabContents();
}
void NativeTabContentsViewAura::EndDragging() {
delegate_->OnNativeTabContentsViewDraggingEnded();
// TODO(beng):
NOTIMPLEMENTED();
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewAura, NativeTabContentsView implementation:
void NativeTabContentsViewAura::InitNativeTabContentsView() {
views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
params.native_widget = this;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.parent = NULL;
GetWidget()->Init(params);
}
void NativeTabContentsViewAura::Unparent() {
// Note that we do not DCHECK on focus_manager_ as it may be NULL when used
// with an external tab container.
views::Widget::ReparentNativeView(GetNativeView(), NULL);
// TODO(beng):
NOTIMPLEMENTED();
}
RenderWidgetHostView* NativeTabContentsViewAura::CreateRenderWidgetHostView(
RenderWidgetHost* render_widget_host) {
RenderWidgetHostViewAura* view =
new RenderWidgetHostViewAura(render_widget_host);
view->Init();
GetNativeView()->AddChild(view->GetNativeView());
view->Show();
return view;
}
gfx::NativeWindow NativeTabContentsViewAura::GetTopLevelNativeWindow() const {
// TODO(beng):
NOTIMPLEMENTED();
return NULL;
}
void NativeTabContentsViewAura::SetPageTitle(const string16& title) {
// TODO(beng):
NOTIMPLEMENTED();
}
void NativeTabContentsViewAura::StartDragging(const WebDropData& drop_data,
WebKit::WebDragOperationsMask ops,
const SkBitmap& image,
const gfx::Point& image_offset) {
// TODO(beng):
NOTIMPLEMENTED();
}
void NativeTabContentsViewAura::CancelDrag() {
// TODO(beng):
NOTIMPLEMENTED();
}
bool NativeTabContentsViewAura::IsDoingDrag() const {
// TODO(beng):
NOTIMPLEMENTED();
return false;
}
void NativeTabContentsViewAura::SetDragCursor(
WebKit::WebDragOperation operation) {
// TODO(beng):
NOTIMPLEMENTED();
}
views::NativeWidget* NativeTabContentsViewAura::AsNativeWidget() {
return this;
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewAura, views::NativeWidgetAura overrides:
void NativeTabContentsViewAura::OnBoundsChanged(const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds) {
delegate_->OnNativeTabContentsViewSized(new_bounds.size());
views::NativeWidgetAura::OnBoundsChanged(old_bounds, new_bounds);
}
bool NativeTabContentsViewAura::OnMouseEvent(aura::MouseEvent* event) {
if (!delegate_->IsShowingSadTab()) {
switch (event->type()) {
case ui::ET_MOUSE_EXITED:
delegate_->OnNativeTabContentsViewMouseMove(false);
break;
case ui::ET_MOUSE_MOVED:
delegate_->OnNativeTabContentsViewMouseMove(true);
break;
default:
// TODO(oshima): mouse wheel
break;
}
}
// Pass all mouse event to renderer.
return views::NativeWidgetAura::OnMouseEvent(event);
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsView, public:
// static
NativeTabContentsView* NativeTabContentsView::CreateNativeTabContentsView(
internal::NativeTabContentsViewDelegate* delegate) {
return new NativeTabContentsViewViews(delegate);
// TODO(beng): switch over to this.
// return new NativeTabContentsViewAura(delegate);
}
<|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/webrtc/native_desktop_media_list.h"
#include <map>
#include <set>
#include <sstream>
#include "base/hash.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/browser/media/webrtc/desktop_media_list_observer.h"
#include "content/public/browser/browser_thread.h"
#include "media/base/video_util.h"
#include "third_party/libyuv/include/libyuv/scale_argb.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/skia_util.h"
using content::BrowserThread;
using content::DesktopMediaID;
namespace {
// Update the list every second.
const int kDefaultUpdatePeriod = 1000;
// Returns a hash of a DesktopFrame content to detect when image for a desktop
// media source has changed.
uint32_t GetFrameHash(webrtc::DesktopFrame* frame) {
int data_size = frame->stride() * frame->size().height();
return base::SuperFastHash(reinterpret_cast<char*>(frame->data()), data_size);
}
gfx::ImageSkia ScaleDesktopFrame(std::unique_ptr<webrtc::DesktopFrame> frame,
gfx::Size size) {
gfx::Rect scaled_rect = media::ComputeLetterboxRegion(
gfx::Rect(0, 0, size.width(), size.height()),
gfx::Size(frame->size().width(), frame->size().height()));
SkBitmap result;
result.allocN32Pixels(scaled_rect.width(), scaled_rect.height(), true);
result.lockPixels();
uint8* pixels_data = reinterpret_cast<uint8*>(result.getPixels());
libyuv::ARGBScale(frame->data(), frame->stride(),
frame->size().width(), frame->size().height(),
pixels_data, result.rowBytes(),
scaled_rect.width(), scaled_rect.height(),
libyuv::kFilterBilinear);
// Set alpha channel values to 255 for all pixels.
// TODO(sergeyu): Fix screen/window capturers to capture alpha channel and
// remove this code. Currently screen/window capturers (at least some
// implementations) only capture R, G and B channels and set Alpha to 0.
// crbug.com/264424
for (int y = 0; y < result.height(); ++y) {
for (int x = 0; x < result.width(); ++x) {
pixels_data[result.rowBytes() * y + x * result.bytesPerPixel() + 3] =
0xff;
}
}
result.unlockPixels();
return gfx::ImageSkia::CreateFrom1xBitmap(result);
}
} // namespace
NativeDesktopMediaList::SourceDescription::SourceDescription(
DesktopMediaID id,
const base::string16& name)
: id(id),
name(name) {
}
class NativeDesktopMediaList::Worker
: public webrtc::DesktopCapturer::Callback {
public:
Worker(base::WeakPtr<NativeDesktopMediaList> media_list,
std::unique_ptr<webrtc::DesktopCapturer> screen_capturer,
std::unique_ptr<webrtc::DesktopCapturer> window_capturer);
~Worker() override;
void Refresh(const gfx::Size& thumbnail_size,
content::DesktopMediaID::Id view_dialog_id);
private:
typedef std::map<DesktopMediaID, uint32> ImageHashesMap;
// webrtc::DesktopCapturer::Callback interface.
void OnCaptureResult(webrtc::DesktopCapturer::Result result,
std::unique_ptr<webrtc::DesktopFrame> frame) override;
base::WeakPtr<NativeDesktopMediaList> media_list_;
std::unique_ptr<webrtc::DesktopCapturer> screen_capturer_;
std::unique_ptr<webrtc::DesktopCapturer> window_capturer_;
std::unique_ptr<webrtc::DesktopFrame> current_frame_;
ImageHashesMap image_hashes_;
DISALLOW_COPY_AND_ASSIGN(Worker);
};
NativeDesktopMediaList::Worker::Worker(
base::WeakPtr<NativeDesktopMediaList> media_list,
std::unique_ptr<webrtc::DesktopCapturer> screen_capturer,
std::unique_ptr<webrtc::DesktopCapturer> window_capturer)
: media_list_(media_list),
screen_capturer_(std::move(screen_capturer)),
window_capturer_(std::move(window_capturer)) {
if (screen_capturer_)
screen_capturer_->Start(this);
if (window_capturer_)
window_capturer_->Start(this);
}
NativeDesktopMediaList::Worker::~Worker() {}
void NativeDesktopMediaList::Worker::Refresh(
const gfx::Size& thumbnail_size,
content::DesktopMediaID::Id view_dialog_id) {
std::vector<SourceDescription> sources;
if (screen_capturer_) {
webrtc::DesktopCapturer::SourceList screens;
if (screen_capturer_->GetSourceList(&screens)) {
bool mutiple_screens = screens.size() > 1;
base::string16 title;
for (size_t i = 0; i < screens.size(); ++i) {
if (mutiple_screens) {
title = base::UTF8ToUTF16("Screen " + base::IntToString(i+1));
} else {
title = base::UTF8ToUTF16("Entire screen");
}
sources.push_back(SourceDescription(DesktopMediaID(
DesktopMediaID::TYPE_SCREEN, screens[i].id), title));
}
}
}
if (window_capturer_) {
webrtc::DesktopCapturer::SourceList windows;
if (window_capturer_->GetSourceList(&windows)) {
for (webrtc::DesktopCapturer::SourceList::iterator it = windows.begin();
it != windows.end(); ++it) {
// Skip the picker dialog window.
if (it->id != view_dialog_id) {
sources.push_back(SourceDescription(
DesktopMediaID(DesktopMediaID::TYPE_WINDOW, it->id),
base::UTF8ToUTF16(it->title)));
}
}
}
}
// Update list of windows before updating thumbnails.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&NativeDesktopMediaList::OnSourcesList,
media_list_, sources));
ImageHashesMap new_image_hashes;
// Get a thumbnail for each source.
for (size_t i = 0; i < sources.size(); ++i) {
SourceDescription& source = sources[i];
switch (source.id.type) {
case DesktopMediaID::TYPE_SCREEN:
if (!screen_capturer_->SelectSource(source.id.id))
continue;
screen_capturer_->CaptureFrame();
break;
case DesktopMediaID::TYPE_WINDOW:
if (!window_capturer_->SelectSource(source.id.id))
continue;
window_capturer_->CaptureFrame();
break;
default:
NOTREACHED();
}
// Expect that DesktopCapturer to always captures frames synchronously.
// |current_frame_| may be NULL if capture failed (e.g. because window has
// been closed).
if (current_frame_) {
uint32_t frame_hash = GetFrameHash(current_frame_.get());
new_image_hashes[source.id] = frame_hash;
// Scale the image only if it has changed.
ImageHashesMap::iterator it = image_hashes_.find(source.id);
if (it == image_hashes_.end() || it->second != frame_hash) {
gfx::ImageSkia thumbnail =
ScaleDesktopFrame(std::move(current_frame_), thumbnail_size);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&NativeDesktopMediaList::OnSourceThumbnail,
media_list_, i, thumbnail));
}
}
}
image_hashes_.swap(new_image_hashes);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&NativeDesktopMediaList::OnRefreshFinished, media_list_));
}
void NativeDesktopMediaList::Worker::OnCaptureResult(
webrtc::DesktopCapturer::Result result,
std::unique_ptr<webrtc::DesktopFrame> frame) {
current_frame_ = std::move(frame);
}
NativeDesktopMediaList::NativeDesktopMediaList(
std::unique_ptr<webrtc::DesktopCapturer> screen_capturer,
std::unique_ptr<webrtc::DesktopCapturer> window_capturer)
: screen_capturer_(std::move(screen_capturer)),
window_capturer_(std::move(window_capturer)),
update_period_(base::TimeDelta::FromMilliseconds(kDefaultUpdatePeriod)),
thumbnail_size_(100, 100),
view_dialog_id_(-1),
observer_(NULL),
weak_factory_(this) {
base::SequencedWorkerPool* worker_pool = BrowserThread::GetBlockingPool();
capture_task_runner_ = worker_pool->GetSequencedTaskRunner(
worker_pool->GetSequenceToken());
}
NativeDesktopMediaList::~NativeDesktopMediaList() {
capture_task_runner_->DeleteSoon(FROM_HERE, worker_.release());
}
void NativeDesktopMediaList::SetUpdatePeriod(base::TimeDelta period) {
DCHECK(!observer_);
update_period_ = period;
}
void NativeDesktopMediaList::SetThumbnailSize(
const gfx::Size& thumbnail_size) {
thumbnail_size_ = thumbnail_size;
}
void NativeDesktopMediaList::SetViewDialogWindowId(
content::DesktopMediaID::Id dialog_id) {
view_dialog_id_ = dialog_id;
}
void NativeDesktopMediaList::StartUpdating(DesktopMediaListObserver* observer) {
DCHECK(!observer_);
DCHECK(screen_capturer_ || window_capturer_);
observer_ = observer;
worker_.reset(new Worker(weak_factory_.GetWeakPtr(),
std::move(screen_capturer_),
std::move(window_capturer_)));
Refresh();
}
int NativeDesktopMediaList::GetSourceCount() const {
return sources_.size();
}
const DesktopMediaList::Source& NativeDesktopMediaList::GetSource(
int index) const {
return sources_[index];
}
std::vector<DesktopMediaList::Source> NativeDesktopMediaList::GetSources() const {
return sources_;
}
void NativeDesktopMediaList::Refresh() {
capture_task_runner_->PostTask(
FROM_HERE, base::Bind(&Worker::Refresh, base::Unretained(worker_.get()),
thumbnail_size_, view_dialog_id_));
}
void NativeDesktopMediaList::OnSourcesList(
const std::vector<SourceDescription>& new_sources) {
typedef std::set<content::DesktopMediaID> SourceSet;
SourceSet new_source_set;
for (size_t i = 0; i < new_sources.size(); ++i) {
new_source_set.insert(new_sources[i].id);
}
// Iterate through the old sources to find the removed sources.
for (size_t i = 0; i < sources_.size(); ++i) {
if (new_source_set.find(sources_[i].id) == new_source_set.end()) {
observer_->OnSourceRemoved(i);
sources_.erase(sources_.begin() + i);
--i;
}
}
// Iterate through the new sources to find the added sources.
if (new_sources.size() > sources_.size()) {
SourceSet old_source_set;
for (size_t i = 0; i < sources_.size(); ++i) {
old_source_set.insert(sources_[i].id);
}
for (size_t i = 0; i < new_sources.size(); ++i) {
if (old_source_set.find(new_sources[i].id) == old_source_set.end()) {
sources_.insert(sources_.begin() + i, Source());
sources_[i].id = new_sources[i].id;
sources_[i].name = new_sources[i].name;
observer_->OnSourceAdded(i);
}
}
}
DCHECK_EQ(new_sources.size(), sources_.size());
// Find the moved/changed sources.
size_t pos = 0;
while (pos < sources_.size()) {
if (!(sources_[pos].id == new_sources[pos].id)) {
// Find the source that should be moved to |pos|, starting from |pos + 1|
// of |sources_|, because entries before |pos| should have been sorted.
size_t old_pos = pos + 1;
for (; old_pos < sources_.size(); ++old_pos) {
if (sources_[old_pos].id == new_sources[pos].id)
break;
}
DCHECK(sources_[old_pos].id == new_sources[pos].id);
// Move the source from |old_pos| to |pos|.
Source temp = sources_[old_pos];
sources_.erase(sources_.begin() + old_pos);
sources_.insert(sources_.begin() + pos, temp);
observer_->OnSourceMoved(old_pos, pos);
}
if (sources_[pos].name != new_sources[pos].name) {
sources_[pos].name = new_sources[pos].name;
observer_->OnSourceNameChanged(pos);
}
++pos;
}
}
void NativeDesktopMediaList::OnSourceThumbnail(
int index,
const gfx::ImageSkia& image) {
DCHECK_LT(index, static_cast<int>(sources_.size()));
sources_[index].thumbnail = image;
observer_->OnSourceThumbnailChanged(index);
}
void NativeDesktopMediaList::OnRefreshFinished() {
// Give a chance to the observer to stop the refresh work.
bool is_continue = observer_->OnRefreshFinished();
if (is_continue) {
BrowserThread::PostDelayedTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&NativeDesktopMediaList::Refresh,
weak_factory_.GetWeakPtr()),
update_period_);
}
}
<commit_msg>SkBitmap no longer needs lock/unlock<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/webrtc/native_desktop_media_list.h"
#include <map>
#include <set>
#include <sstream>
#include "base/hash.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/browser/media/webrtc/desktop_media_list_observer.h"
#include "content/public/browser/browser_thread.h"
#include "media/base/video_util.h"
#include "third_party/libyuv/include/libyuv/scale_argb.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/skia_util.h"
using content::BrowserThread;
using content::DesktopMediaID;
namespace {
// Update the list every second.
const int kDefaultUpdatePeriod = 1000;
// Returns a hash of a DesktopFrame content to detect when image for a desktop
// media source has changed.
uint32_t GetFrameHash(webrtc::DesktopFrame* frame) {
int data_size = frame->stride() * frame->size().height();
return base::SuperFastHash(reinterpret_cast<char*>(frame->data()), data_size);
}
gfx::ImageSkia ScaleDesktopFrame(std::unique_ptr<webrtc::DesktopFrame> frame,
gfx::Size size) {
gfx::Rect scaled_rect = media::ComputeLetterboxRegion(
gfx::Rect(0, 0, size.width(), size.height()),
gfx::Size(frame->size().width(), frame->size().height()));
SkBitmap result;
result.allocN32Pixels(scaled_rect.width(), scaled_rect.height(), true);
uint8* pixels_data = reinterpret_cast<uint8*>(result.getPixels());
libyuv::ARGBScale(frame->data(), frame->stride(),
frame->size().width(), frame->size().height(),
pixels_data, result.rowBytes(),
scaled_rect.width(), scaled_rect.height(),
libyuv::kFilterBilinear);
// Set alpha channel values to 255 for all pixels.
// TODO(sergeyu): Fix screen/window capturers to capture alpha channel and
// remove this code. Currently screen/window capturers (at least some
// implementations) only capture R, G and B channels and set Alpha to 0.
// crbug.com/264424
for (int y = 0; y < result.height(); ++y) {
for (int x = 0; x < result.width(); ++x) {
pixels_data[result.rowBytes() * y + x * result.bytesPerPixel() + 3] =
0xff;
}
}
return gfx::ImageSkia::CreateFrom1xBitmap(result);
}
} // namespace
NativeDesktopMediaList::SourceDescription::SourceDescription(
DesktopMediaID id,
const base::string16& name)
: id(id),
name(name) {
}
class NativeDesktopMediaList::Worker
: public webrtc::DesktopCapturer::Callback {
public:
Worker(base::WeakPtr<NativeDesktopMediaList> media_list,
std::unique_ptr<webrtc::DesktopCapturer> screen_capturer,
std::unique_ptr<webrtc::DesktopCapturer> window_capturer);
~Worker() override;
void Refresh(const gfx::Size& thumbnail_size,
content::DesktopMediaID::Id view_dialog_id);
private:
typedef std::map<DesktopMediaID, uint32> ImageHashesMap;
// webrtc::DesktopCapturer::Callback interface.
void OnCaptureResult(webrtc::DesktopCapturer::Result result,
std::unique_ptr<webrtc::DesktopFrame> frame) override;
base::WeakPtr<NativeDesktopMediaList> media_list_;
std::unique_ptr<webrtc::DesktopCapturer> screen_capturer_;
std::unique_ptr<webrtc::DesktopCapturer> window_capturer_;
std::unique_ptr<webrtc::DesktopFrame> current_frame_;
ImageHashesMap image_hashes_;
DISALLOW_COPY_AND_ASSIGN(Worker);
};
NativeDesktopMediaList::Worker::Worker(
base::WeakPtr<NativeDesktopMediaList> media_list,
std::unique_ptr<webrtc::DesktopCapturer> screen_capturer,
std::unique_ptr<webrtc::DesktopCapturer> window_capturer)
: media_list_(media_list),
screen_capturer_(std::move(screen_capturer)),
window_capturer_(std::move(window_capturer)) {
if (screen_capturer_)
screen_capturer_->Start(this);
if (window_capturer_)
window_capturer_->Start(this);
}
NativeDesktopMediaList::Worker::~Worker() {}
void NativeDesktopMediaList::Worker::Refresh(
const gfx::Size& thumbnail_size,
content::DesktopMediaID::Id view_dialog_id) {
std::vector<SourceDescription> sources;
if (screen_capturer_) {
webrtc::DesktopCapturer::SourceList screens;
if (screen_capturer_->GetSourceList(&screens)) {
bool mutiple_screens = screens.size() > 1;
base::string16 title;
for (size_t i = 0; i < screens.size(); ++i) {
if (mutiple_screens) {
title = base::UTF8ToUTF16("Screen " + base::IntToString(i+1));
} else {
title = base::UTF8ToUTF16("Entire screen");
}
sources.push_back(SourceDescription(DesktopMediaID(
DesktopMediaID::TYPE_SCREEN, screens[i].id), title));
}
}
}
if (window_capturer_) {
webrtc::DesktopCapturer::SourceList windows;
if (window_capturer_->GetSourceList(&windows)) {
for (webrtc::DesktopCapturer::SourceList::iterator it = windows.begin();
it != windows.end(); ++it) {
// Skip the picker dialog window.
if (it->id != view_dialog_id) {
sources.push_back(SourceDescription(
DesktopMediaID(DesktopMediaID::TYPE_WINDOW, it->id),
base::UTF8ToUTF16(it->title)));
}
}
}
}
// Update list of windows before updating thumbnails.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&NativeDesktopMediaList::OnSourcesList,
media_list_, sources));
ImageHashesMap new_image_hashes;
// Get a thumbnail for each source.
for (size_t i = 0; i < sources.size(); ++i) {
SourceDescription& source = sources[i];
switch (source.id.type) {
case DesktopMediaID::TYPE_SCREEN:
if (!screen_capturer_->SelectSource(source.id.id))
continue;
screen_capturer_->CaptureFrame();
break;
case DesktopMediaID::TYPE_WINDOW:
if (!window_capturer_->SelectSource(source.id.id))
continue;
window_capturer_->CaptureFrame();
break;
default:
NOTREACHED();
}
// Expect that DesktopCapturer to always captures frames synchronously.
// |current_frame_| may be NULL if capture failed (e.g. because window has
// been closed).
if (current_frame_) {
uint32_t frame_hash = GetFrameHash(current_frame_.get());
new_image_hashes[source.id] = frame_hash;
// Scale the image only if it has changed.
ImageHashesMap::iterator it = image_hashes_.find(source.id);
if (it == image_hashes_.end() || it->second != frame_hash) {
gfx::ImageSkia thumbnail =
ScaleDesktopFrame(std::move(current_frame_), thumbnail_size);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&NativeDesktopMediaList::OnSourceThumbnail,
media_list_, i, thumbnail));
}
}
}
image_hashes_.swap(new_image_hashes);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&NativeDesktopMediaList::OnRefreshFinished, media_list_));
}
void NativeDesktopMediaList::Worker::OnCaptureResult(
webrtc::DesktopCapturer::Result result,
std::unique_ptr<webrtc::DesktopFrame> frame) {
current_frame_ = std::move(frame);
}
NativeDesktopMediaList::NativeDesktopMediaList(
std::unique_ptr<webrtc::DesktopCapturer> screen_capturer,
std::unique_ptr<webrtc::DesktopCapturer> window_capturer)
: screen_capturer_(std::move(screen_capturer)),
window_capturer_(std::move(window_capturer)),
update_period_(base::TimeDelta::FromMilliseconds(kDefaultUpdatePeriod)),
thumbnail_size_(100, 100),
view_dialog_id_(-1),
observer_(NULL),
weak_factory_(this) {
base::SequencedWorkerPool* worker_pool = BrowserThread::GetBlockingPool();
capture_task_runner_ = worker_pool->GetSequencedTaskRunner(
worker_pool->GetSequenceToken());
}
NativeDesktopMediaList::~NativeDesktopMediaList() {
capture_task_runner_->DeleteSoon(FROM_HERE, worker_.release());
}
void NativeDesktopMediaList::SetUpdatePeriod(base::TimeDelta period) {
DCHECK(!observer_);
update_period_ = period;
}
void NativeDesktopMediaList::SetThumbnailSize(
const gfx::Size& thumbnail_size) {
thumbnail_size_ = thumbnail_size;
}
void NativeDesktopMediaList::SetViewDialogWindowId(
content::DesktopMediaID::Id dialog_id) {
view_dialog_id_ = dialog_id;
}
void NativeDesktopMediaList::StartUpdating(DesktopMediaListObserver* observer) {
DCHECK(!observer_);
DCHECK(screen_capturer_ || window_capturer_);
observer_ = observer;
worker_.reset(new Worker(weak_factory_.GetWeakPtr(),
std::move(screen_capturer_),
std::move(window_capturer_)));
Refresh();
}
int NativeDesktopMediaList::GetSourceCount() const {
return sources_.size();
}
const DesktopMediaList::Source& NativeDesktopMediaList::GetSource(
int index) const {
return sources_[index];
}
std::vector<DesktopMediaList::Source> NativeDesktopMediaList::GetSources() const {
return sources_;
}
void NativeDesktopMediaList::Refresh() {
capture_task_runner_->PostTask(
FROM_HERE, base::Bind(&Worker::Refresh, base::Unretained(worker_.get()),
thumbnail_size_, view_dialog_id_));
}
void NativeDesktopMediaList::OnSourcesList(
const std::vector<SourceDescription>& new_sources) {
typedef std::set<content::DesktopMediaID> SourceSet;
SourceSet new_source_set;
for (size_t i = 0; i < new_sources.size(); ++i) {
new_source_set.insert(new_sources[i].id);
}
// Iterate through the old sources to find the removed sources.
for (size_t i = 0; i < sources_.size(); ++i) {
if (new_source_set.find(sources_[i].id) == new_source_set.end()) {
observer_->OnSourceRemoved(i);
sources_.erase(sources_.begin() + i);
--i;
}
}
// Iterate through the new sources to find the added sources.
if (new_sources.size() > sources_.size()) {
SourceSet old_source_set;
for (size_t i = 0; i < sources_.size(); ++i) {
old_source_set.insert(sources_[i].id);
}
for (size_t i = 0; i < new_sources.size(); ++i) {
if (old_source_set.find(new_sources[i].id) == old_source_set.end()) {
sources_.insert(sources_.begin() + i, Source());
sources_[i].id = new_sources[i].id;
sources_[i].name = new_sources[i].name;
observer_->OnSourceAdded(i);
}
}
}
DCHECK_EQ(new_sources.size(), sources_.size());
// Find the moved/changed sources.
size_t pos = 0;
while (pos < sources_.size()) {
if (!(sources_[pos].id == new_sources[pos].id)) {
// Find the source that should be moved to |pos|, starting from |pos + 1|
// of |sources_|, because entries before |pos| should have been sorted.
size_t old_pos = pos + 1;
for (; old_pos < sources_.size(); ++old_pos) {
if (sources_[old_pos].id == new_sources[pos].id)
break;
}
DCHECK(sources_[old_pos].id == new_sources[pos].id);
// Move the source from |old_pos| to |pos|.
Source temp = sources_[old_pos];
sources_.erase(sources_.begin() + old_pos);
sources_.insert(sources_.begin() + pos, temp);
observer_->OnSourceMoved(old_pos, pos);
}
if (sources_[pos].name != new_sources[pos].name) {
sources_[pos].name = new_sources[pos].name;
observer_->OnSourceNameChanged(pos);
}
++pos;
}
}
void NativeDesktopMediaList::OnSourceThumbnail(
int index,
const gfx::ImageSkia& image) {
DCHECK_LT(index, static_cast<int>(sources_.size()));
sources_[index].thumbnail = image;
observer_->OnSourceThumbnailChanged(index);
}
void NativeDesktopMediaList::OnRefreshFinished() {
// Give a chance to the observer to stop the refresh work.
bool is_continue = observer_->OnRefreshFinished();
if (is_continue) {
BrowserThread::PostDelayedTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&NativeDesktopMediaList::Refresh,
weak_factory_.GetWeakPtr()),
update_period_);
}
}
<|endoftext|>
|
<commit_before>/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __STOUT_DURATION_HPP__
#define __STOUT_DURATION_HPP__
#include <ctype.h> // For 'isdigit'.
#include <limits.h> // For 'LLONG_(MAX|MIN)'
#include <iomanip>
#include <iostream>
#include <string>
#include "error.hpp"
#include "numify.hpp"
#include "try.hpp"
class Duration
{
public:
static Try<Duration> parse(const std::string& s)
{
// TODO(benh): Support negative durations (i.e., starts with '-').
size_t index = 0;
while (index < s.size()) {
if (isdigit(s[index]) || s[index] == '.') {
index++;
continue;
}
Try<double> value = numify<double>(s.substr(0, index));
if (value.isError()) {
return Error(value.error());
}
const std::string& unit = s.substr(index);
if (unit == "ns") {
return Duration(value.get(), NANOSECONDS);
} else if (unit == "us") {
return Duration(value.get(), MICROSECONDS);
} else if (unit == "ms") {
return Duration(value.get(), MILLISECONDS);
} else if (unit == "secs") {
return Duration(value.get(), SECONDS);
} else if (unit == "mins") {
return Duration(value.get(), MINUTES);
} else if (unit == "hrs") {
return Duration(value.get(), HOURS);
} else if (unit == "days") {
return Duration(value.get(), DAYS);
} else if (unit == "weeks") {
return Duration(value.get(), WEEKS);
} else {
return Error("Unknown duration unit '" + unit + "'");
}
}
return Error("Invalid duration '" + s + "'");
}
static Try<Duration> create(double seconds);
Duration() : nanos(0) {}
int64_t ns() const { return nanos; }
double us() const { return static_cast<double>(nanos) / MICROSECONDS; }
double ms() const { return static_cast<double>(nanos) / MILLISECONDS; }
double secs() const { return static_cast<double>(nanos) / SECONDS; }
double mins() const { return static_cast<double>(nanos) / MINUTES; }
double hrs() const { return static_cast<double>(nanos) / HOURS; }
double days() const { return static_cast<double>(nanos) / DAYS; }
double weeks() const { return static_cast<double>(nanos) / WEEKS; }
bool operator < (const Duration& d) const { return nanos < d.nanos; }
bool operator <= (const Duration& d) const { return nanos <= d.nanos; }
bool operator > (const Duration& d) const { return nanos > d.nanos; }
bool operator >= (const Duration& d) const { return nanos >= d.nanos; }
bool operator == (const Duration& d) const { return nanos == d.nanos; }
bool operator != (const Duration& d) const { return nanos != d.nanos; }
Duration& operator += (const Duration& that)
{
nanos += that.nanos;
return *this;
}
Duration& operator -= (const Duration& that)
{
nanos -= that.nanos;
return *this;
}
Duration& operator *= (double multiplier)
{
nanos = static_cast<int64_t>(nanos * multiplier);
return *this;
}
Duration& operator /= (double divisor)
{
nanos = static_cast<int64_t>(nanos / divisor);
return *this;
}
Duration operator + (const Duration& that) const
{
Duration sum = *this;
sum += that;
return sum;
}
Duration operator - (const Duration& that) const
{
Duration diff = *this;
diff -= that;
return diff;
}
Duration operator * (double multiplier) const
{
Duration product = *this;
product *= multiplier;
return product;
}
Duration operator / (double divisor) const
{
Duration quotient = *this;
quotient /= divisor;
return quotient;
}
// TODO(xujyan): Use constexpr for the following variables after
// switching to C++11.
// A constant holding the maximum value a Duration can have.
static Duration max();
// A constant holding the minimum (negative) value a Duration can
// have.
static Duration min();
// A constant holding a Duration of a "zero" value.
static Duration zero() { return Duration(); }
protected:
static const int64_t NANOSECONDS = 1;
static const int64_t MICROSECONDS = 1000 * NANOSECONDS;
static const int64_t MILLISECONDS = 1000 * MICROSECONDS;
static const int64_t SECONDS = 1000 * MILLISECONDS;
static const int64_t MINUTES = 60 * SECONDS;
static const int64_t HOURS = 60 * MINUTES;
static const int64_t DAYS = 24 * HOURS;
static const int64_t WEEKS = 7 * DAYS;
// For the Seconds, Minutes, Hours, Days & Weeks constructor.
Duration(int32_t value, int64_t unit)
: nanos(value * unit) {}
// For the Nanoseconds, Microseconds, Milliseconds constructor.
Duration(int64_t value, int64_t unit)
: nanos(value * unit) {}
private:
// Used only by "parse".
Duration(double value, int64_t unit)
: nanos(static_cast<int64_t>(value * unit)) {}
int64_t nanos;
friend std::ostream& operator << (
std::ostream& stream,
const Duration& duration);
};
class Nanoseconds : public Duration
{
public:
explicit Nanoseconds(int64_t nanoseconds)
: Duration(nanoseconds, NANOSECONDS) {}
Nanoseconds(const Duration& d) : Duration(d) {}
};
class Microseconds : public Duration
{
public:
explicit Microseconds(int64_t microseconds)
: Duration(microseconds, MICROSECONDS) {}
Microseconds(const Duration& d) : Duration(d) {}
};
class Milliseconds : public Duration
{
public:
explicit Milliseconds(int64_t milliseconds)
: Duration(milliseconds, MILLISECONDS) {}
Milliseconds(const Duration& d) : Duration(d) {}
};
class Seconds : public Duration
{
public:
explicit Seconds(int64_t seconds)
: Duration(seconds, SECONDS) {}
Seconds(const Duration& d) : Duration(d) {}
};
class Minutes : public Duration
{
public:
explicit Minutes(int32_t minutes)
: Duration(minutes, MINUTES) {}
Minutes(const Duration& d) : Duration(d) {}
};
class Hours : public Duration
{
public:
explicit Hours(int32_t hours)
: Duration(hours, HOURS) {}
Hours(const Duration& d) : Duration(d) {}
};
class Days : public Duration
{
public:
explicit Days(int32_t days)
: Duration(days, DAYS) {}
Days(const Duration& d) : Duration(d) {}
};
class Weeks : public Duration
{
public:
explicit Weeks(int32_t value) : Duration(value, WEEKS) {}
Weeks(const Duration& d) : Duration(d) {}
};
inline std::ostream& operator << (
std::ostream& stream,
const Duration& duration_)
{
long precision = stream.precision();
// Output the duration in full double precision.
stream.precision(std::numeric_limits<double>::digits10);
// Parse the duration as the sign and the absolute value.
Duration duration = duration_;
if (duration_ < Duration::zero()) {
stream << "-";
// Duration::min() may not be representable as a positive Duration.
if (duration_ == Duration::min()) {
duration = Duration::max();
} else {
duration = duration_ * -1;
}
}
// First determine which bucket of time unit the duration falls into
// then check whether the duration can be represented as a whole
// number with this time unit or a smaller one.
// e.g. 1.42857142857143weeks falls into the 'Weeks' bucket but
// reads better with a smaller unit: '10days'. So we use 'days'
// instead of 'weeks' to output the duration.
int64_t nanoseconds = duration.ns();
if (duration < Microseconds(1)) {
stream << duration.ns() << "ns";
} else if (duration < Milliseconds(1)) {
if (nanoseconds % Duration::MICROSECONDS != 0) {
// We can't get a whole number using this unit but we can at
// one level down.
stream << duration.ns() << "ns";
} else {
stream << duration.us() << "us";
}
} else if (duration < Seconds(1)) {
if (nanoseconds % Duration::MILLISECONDS != 0 &&
nanoseconds % Duration::MICROSECONDS == 0) {
stream << duration.us() << "us";
} else {
stream << duration.ms() << "ms";
}
} else if (duration < Minutes(1)) {
if (nanoseconds % Duration::SECONDS != 0 &&
nanoseconds % Duration::MILLISECONDS == 0) {
stream << duration.ms() << "ms";
} else {
stream << duration.secs() << "secs";
}
} else if (duration < Hours(1)) {
if (nanoseconds % Duration::MINUTES != 0 &&
nanoseconds % Duration::SECONDS == 0) {
stream << duration.secs() << "secs";
} else {
stream << duration.mins() << "mins";
}
} else if (duration < Days(1)) {
if (nanoseconds % Duration::HOURS != 0 &&
nanoseconds % Duration::MINUTES == 0) {
stream << duration.mins() << "mins";
} else {
stream << duration.hrs() << "hrs";
}
} else if (duration < Weeks(1)) {
if (nanoseconds % Duration::DAYS != 0 &&
nanoseconds % Duration::HOURS == 0) {
stream << duration.hrs() << "hrs";
} else {
stream << duration.days() << "days";
}
} else {
if (nanoseconds % Duration::WEEKS != 0 &&
nanoseconds % Duration::DAYS == 0) {
stream << duration.days() << "days";
} else {
stream << duration.weeks() << "weeks";
}
}
// Return the stream to original formatting state.
stream.precision(precision);
return stream;
}
inline Try<Duration> Duration::create(double seconds)
{
if (seconds * SECONDS > LLONG_MAX || seconds * SECONDS < LLONG_MIN) {
return Error("Argument out of the range that a Duration can represent due "
"to int64_t's size limit");
}
return Nanoseconds(static_cast<int64_t>(seconds * SECONDS));
}
inline Duration Duration::max() { return Nanoseconds(LLONG_MAX); }
inline Duration Duration::min() { return Nanoseconds(LLONG_MIN); }
#endif // __STOUT_DURATION_HPP__
<commit_msg>Add 'value' and 'units' methods to Duration subclasses.<commit_after>/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __STOUT_DURATION_HPP__
#define __STOUT_DURATION_HPP__
#include <ctype.h> // For 'isdigit'.
#include <limits.h> // For 'LLONG_(MAX|MIN)'
#include <iomanip>
#include <iostream>
#include <string>
#include "error.hpp"
#include "numify.hpp"
#include "try.hpp"
class Duration
{
public:
static Try<Duration> parse(const std::string& s)
{
// TODO(benh): Support negative durations (i.e., starts with '-').
size_t index = 0;
while (index < s.size()) {
if (isdigit(s[index]) || s[index] == '.') {
index++;
continue;
}
Try<double> value = numify<double>(s.substr(0, index));
if (value.isError()) {
return Error(value.error());
}
const std::string& unit = s.substr(index);
if (unit == "ns") {
return Duration(value.get(), NANOSECONDS);
} else if (unit == "us") {
return Duration(value.get(), MICROSECONDS);
} else if (unit == "ms") {
return Duration(value.get(), MILLISECONDS);
} else if (unit == "secs") {
return Duration(value.get(), SECONDS);
} else if (unit == "mins") {
return Duration(value.get(), MINUTES);
} else if (unit == "hrs") {
return Duration(value.get(), HOURS);
} else if (unit == "days") {
return Duration(value.get(), DAYS);
} else if (unit == "weeks") {
return Duration(value.get(), WEEKS);
} else {
return Error("Unknown duration unit '" + unit + "'");
}
}
return Error("Invalid duration '" + s + "'");
}
static Try<Duration> create(double seconds);
Duration() : nanos(0) {}
int64_t ns() const { return nanos; }
double us() const { return static_cast<double>(nanos) / MICROSECONDS; }
double ms() const { return static_cast<double>(nanos) / MILLISECONDS; }
double secs() const { return static_cast<double>(nanos) / SECONDS; }
double mins() const { return static_cast<double>(nanos) / MINUTES; }
double hrs() const { return static_cast<double>(nanos) / HOURS; }
double days() const { return static_cast<double>(nanos) / DAYS; }
double weeks() const { return static_cast<double>(nanos) / WEEKS; }
bool operator < (const Duration& d) const { return nanos < d.nanos; }
bool operator <= (const Duration& d) const { return nanos <= d.nanos; }
bool operator > (const Duration& d) const { return nanos > d.nanos; }
bool operator >= (const Duration& d) const { return nanos >= d.nanos; }
bool operator == (const Duration& d) const { return nanos == d.nanos; }
bool operator != (const Duration& d) const { return nanos != d.nanos; }
Duration& operator += (const Duration& that)
{
nanos += that.nanos;
return *this;
}
Duration& operator -= (const Duration& that)
{
nanos -= that.nanos;
return *this;
}
Duration& operator *= (double multiplier)
{
nanos = static_cast<int64_t>(nanos * multiplier);
return *this;
}
Duration& operator /= (double divisor)
{
nanos = static_cast<int64_t>(nanos / divisor);
return *this;
}
Duration operator + (const Duration& that) const
{
Duration sum = *this;
sum += that;
return sum;
}
Duration operator - (const Duration& that) const
{
Duration diff = *this;
diff -= that;
return diff;
}
Duration operator * (double multiplier) const
{
Duration product = *this;
product *= multiplier;
return product;
}
Duration operator / (double divisor) const
{
Duration quotient = *this;
quotient /= divisor;
return quotient;
}
// TODO(xujyan): Use constexpr for the following variables after
// switching to C++11.
// A constant holding the maximum value a Duration can have.
static Duration max();
// A constant holding the minimum (negative) value a Duration can
// have.
static Duration min();
// A constant holding a Duration of a "zero" value.
static Duration zero() { return Duration(); }
protected:
static const int64_t NANOSECONDS = 1;
static const int64_t MICROSECONDS = 1000 * NANOSECONDS;
static const int64_t MILLISECONDS = 1000 * MICROSECONDS;
static const int64_t SECONDS = 1000 * MILLISECONDS;
static const int64_t MINUTES = 60 * SECONDS;
static const int64_t HOURS = 60 * MINUTES;
static const int64_t DAYS = 24 * HOURS;
static const int64_t WEEKS = 7 * DAYS;
// For the Seconds, Minutes, Hours, Days & Weeks constructor.
Duration(int32_t value, int64_t unit)
: nanos(value * unit) {}
// For the Nanoseconds, Microseconds, Milliseconds constructor.
Duration(int64_t value, int64_t unit)
: nanos(value * unit) {}
private:
// Used only by "parse".
Duration(double value, int64_t unit)
: nanos(static_cast<int64_t>(value * unit)) {}
int64_t nanos;
friend std::ostream& operator << (
std::ostream& stream,
const Duration& duration);
};
class Nanoseconds : public Duration
{
public:
explicit Nanoseconds(int64_t nanoseconds)
: Duration(nanoseconds, NANOSECONDS) {}
Nanoseconds(const Duration& d) : Duration(d) {}
double value() const { return static_cast<double>(this->ns()); }
static std::string units() { return "ns"; }
};
class Microseconds : public Duration
{
public:
explicit Microseconds(int64_t microseconds)
: Duration(microseconds, MICROSECONDS) {}
Microseconds(const Duration& d) : Duration(d) {}
double value() const { return this->us(); }
static std::string units() { return "us"; }
};
class Milliseconds : public Duration
{
public:
explicit Milliseconds(int64_t milliseconds)
: Duration(milliseconds, MILLISECONDS) {}
Milliseconds(const Duration& d) : Duration(d) {}
double value() const { return this->ms(); }
static std::string units() { return "ms"; }
};
class Seconds : public Duration
{
public:
explicit Seconds(int64_t seconds)
: Duration(seconds, SECONDS) {}
Seconds(const Duration& d) : Duration(d) {}
double value() const { return this->secs(); }
static std::string units() { return "secs"; }
};
class Minutes : public Duration
{
public:
explicit Minutes(int32_t minutes)
: Duration(minutes, MINUTES) {}
Minutes(const Duration& d) : Duration(d) {}
double value() const { return this->mins(); }
static std::string units() { return "mins"; }
};
class Hours : public Duration
{
public:
explicit Hours(int32_t hours)
: Duration(hours, HOURS) {}
Hours(const Duration& d) : Duration(d) {}
double value() const { return this->hrs(); }
static std::string units() { return "hrs"; }
};
class Days : public Duration
{
public:
explicit Days(int32_t days)
: Duration(days, DAYS) {}
Days(const Duration& d) : Duration(d) {}
double value() const { return this->days(); }
static std::string units() { return "days"; }
};
class Weeks : public Duration
{
public:
explicit Weeks(int32_t value) : Duration(value, WEEKS) {}
Weeks(const Duration& d) : Duration(d) {}
double value() const { return this->weeks(); }
static std::string units() { return "weeks"; }
};
inline std::ostream& operator << (
std::ostream& stream,
const Duration& duration_)
{
long precision = stream.precision();
// Output the duration in full double precision.
stream.precision(std::numeric_limits<double>::digits10);
// Parse the duration as the sign and the absolute value.
Duration duration = duration_;
if (duration_ < Duration::zero()) {
stream << "-";
// Duration::min() may not be representable as a positive Duration.
if (duration_ == Duration::min()) {
duration = Duration::max();
} else {
duration = duration_ * -1;
}
}
// First determine which bucket of time unit the duration falls into
// then check whether the duration can be represented as a whole
// number with this time unit or a smaller one.
// e.g. 1.42857142857143weeks falls into the 'Weeks' bucket but
// reads better with a smaller unit: '10days'. So we use 'days'
// instead of 'weeks' to output the duration.
int64_t nanoseconds = duration.ns();
if (duration < Microseconds(1)) {
stream << duration.ns() << Nanoseconds::units();
} else if (duration < Milliseconds(1)) {
if (nanoseconds % Duration::MICROSECONDS != 0) {
// We can't get a whole number using this unit but we can at
// one level down.
stream << duration.ns() << Nanoseconds::units();
} else {
stream << duration.us() << Microseconds::units();
}
} else if (duration < Seconds(1)) {
if (nanoseconds % Duration::MILLISECONDS != 0 &&
nanoseconds % Duration::MICROSECONDS == 0) {
stream << duration.us() << Microseconds::units();
} else {
stream << duration.ms() << Milliseconds::units();
}
} else if (duration < Minutes(1)) {
if (nanoseconds % Duration::SECONDS != 0 &&
nanoseconds % Duration::MILLISECONDS == 0) {
stream << duration.ms() << Milliseconds::units();
} else {
stream << duration.secs() << Seconds::units();
}
} else if (duration < Hours(1)) {
if (nanoseconds % Duration::MINUTES != 0 &&
nanoseconds % Duration::SECONDS == 0) {
stream << duration.secs() << Seconds::units();
} else {
stream << duration.mins() << Minutes::units();
}
} else if (duration < Days(1)) {
if (nanoseconds % Duration::HOURS != 0 &&
nanoseconds % Duration::MINUTES == 0) {
stream << duration.mins() << Minutes::units();
} else {
stream << duration.hrs() << Hours::units();
}
} else if (duration < Weeks(1)) {
if (nanoseconds % Duration::DAYS != 0 &&
nanoseconds % Duration::HOURS == 0) {
stream << duration.hrs() << Hours::units();
} else {
stream << duration.days() << Days::units();
}
} else {
if (nanoseconds % Duration::WEEKS != 0 &&
nanoseconds % Duration::DAYS == 0) {
stream << duration.days() << Days::units();
} else {
stream << duration.weeks() << Weeks::units();
}
}
// Return the stream to original formatting state.
stream.precision(precision);
return stream;
}
inline Try<Duration> Duration::create(double seconds)
{
if (seconds * SECONDS > LLONG_MAX || seconds * SECONDS < LLONG_MIN) {
return Error("Argument out of the range that a Duration can represent due "
"to int64_t's size limit");
}
return Nanoseconds(static_cast<int64_t>(seconds * SECONDS));
}
inline Duration Duration::max() { return Nanoseconds(LLONG_MAX); }
inline Duration Duration::min() { return Nanoseconds(LLONG_MIN); }
#endif // __STOUT_DURATION_HPP__
<|endoftext|>
|
<commit_before>#include "qhextheme.h"
#include <QGuiApplication>
#include <QPalette>
#include <QWidget>
#include <QFont>
#ifdef Q_OS_MAC
#define MONOSPACE_FONT "Courier"
#else
#define MONOSPACE_FONT "Monospace"
#endif
QHexTheme::QHexTheme(QObject *parent): QObject(parent)
{
QWidget* container = static_cast<QWidget*>(parent);
QFont f(MONOSPACE_FONT, qApp->font().pointSize());
f.setStyleHint(QFont::TypeWriter); // Use monospace fonts
container->setFont(f);
container->setBackgroundRole(QPalette::Base);
this->_selectedcursor = QColor(Qt::lightGray);
this->_addressbackground = QColor(0xF0, 0xF0, 0xFE);
this->_addressforeground = QColor(Qt::darkBlue);
this->_alternateaddressforeground = QColor(Qt::red);
this->_alternatelinecolor = QColor(0xF0, 0xF0, 0xFE);
this->_linecolor = QColor(0xFF, 0xFF, 0xA0);
}
QColor QHexTheme::baseColor() const
{
return this->_basecolor;
}
QColor QHexTheme::selectedCursor() const
{
return this->_selectedcursor;
}
QColor QHexTheme::addressBackground() const
{
return this->_addressbackground;
}
QColor QHexTheme::addressForeground() const
{
return this->_addressforeground;
}
QColor QHexTheme::alternateAddressForeground() const
{
return this->_alternateaddressforeground;
}
QColor QHexTheme::alternateLineColor() const
{
return this->_alternatelinecolor;
}
QColor QHexTheme::lineColor() const
{
return this->_linecolor;
}
void QHexTheme::setBaseColor(const QColor &color)
{
if(this->_basecolor == color)
return;
this->_basecolor = color;
emit themeChanged();
}
void QHexTheme::setSelectedCursor(const QColor &color)
{
if(this->_selectedcursor == color)
return;
this->_selectedcursor = color;
emit themeChanged();
}
void QHexTheme::setAddressBackground(const QColor &color)
{
if(this->_addressbackground == color)
return;
this->_addressbackground = color;
emit themeChanged();
}
void QHexTheme::setAddressForeground(const QColor &color)
{
if(this->_addressforeground == color)
return;
this->_addressforeground = color;
emit themeChanged();
}
void QHexTheme::setAlternateAddressForeground(const QColor &color)
{
if(this->_alternateaddressforeground == color)
return;
this->_alternateaddressforeground = color;
emit themeChanged();
}
void QHexTheme::setAlternateLineColor(const QColor &color)
{
if(this->_alternatelinecolor == color)
return;
this->_alternatelinecolor = color;
emit themeChanged();
}
void QHexTheme::setLineColor(const QColor &color)
{
if(this->_linecolor == color)
return;
this->_linecolor = color;
emit themeChanged();
}
<commit_msg>QHexTheme: Use system's monospace font<commit_after>#include "qhextheme.h"
#include <QGuiApplication>
#include <QFontDatabase>
#include <QPalette>
#include <QWidget>
QHexTheme::QHexTheme(QObject *parent): QObject(parent)
{
QWidget* container = static_cast<QWidget*>(parent);
container->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
container->setBackgroundRole(QPalette::Base);
this->_selectedcursor = QColor(Qt::lightGray);
this->_addressbackground = QColor(0xF0, 0xF0, 0xFE);
this->_addressforeground = QColor(Qt::darkBlue);
this->_alternateaddressforeground = QColor(Qt::red);
this->_alternatelinecolor = QColor(0xF0, 0xF0, 0xFE);
this->_linecolor = QColor(0xFF, 0xFF, 0xA0);
}
QColor QHexTheme::baseColor() const
{
return this->_basecolor;
}
QColor QHexTheme::selectedCursor() const
{
return this->_selectedcursor;
}
QColor QHexTheme::addressBackground() const
{
return this->_addressbackground;
}
QColor QHexTheme::addressForeground() const
{
return this->_addressforeground;
}
QColor QHexTheme::alternateAddressForeground() const
{
return this->_alternateaddressforeground;
}
QColor QHexTheme::alternateLineColor() const
{
return this->_alternatelinecolor;
}
QColor QHexTheme::lineColor() const
{
return this->_linecolor;
}
void QHexTheme::setBaseColor(const QColor &color)
{
if(this->_basecolor == color)
return;
this->_basecolor = color;
emit themeChanged();
}
void QHexTheme::setSelectedCursor(const QColor &color)
{
if(this->_selectedcursor == color)
return;
this->_selectedcursor = color;
emit themeChanged();
}
void QHexTheme::setAddressBackground(const QColor &color)
{
if(this->_addressbackground == color)
return;
this->_addressbackground = color;
emit themeChanged();
}
void QHexTheme::setAddressForeground(const QColor &color)
{
if(this->_addressforeground == color)
return;
this->_addressforeground = color;
emit themeChanged();
}
void QHexTheme::setAlternateAddressForeground(const QColor &color)
{
if(this->_alternateaddressforeground == color)
return;
this->_alternateaddressforeground = color;
emit themeChanged();
}
void QHexTheme::setAlternateLineColor(const QColor &color)
{
if(this->_alternatelinecolor == color)
return;
this->_alternatelinecolor = color;
emit themeChanged();
}
void QHexTheme::setLineColor(const QColor &color)
{
if(this->_linecolor == color)
return;
this->_linecolor = color;
emit themeChanged();
}
<|endoftext|>
|
<commit_before>#include "gui_system.h"
#include "engine/delegate.h"
#include "engine/delegate_list.h"
#include "engine/engine.h"
#include "engine/iallocator.h"
#include "engine/input_system.h"
#include "engine/lua_wrapper.h"
#include "engine/matrix.h"
#include "engine/path.h"
#include "engine/resource_manager.h"
#include "renderer/material.h"
#include "renderer/material_manager.h"
#include "renderer/pipeline.h"
#include "renderer/shader.h"
#pragma warning(disable : 4267)
#include "tb_renderer_batcher.h"
#include <animation/tb_animation.h>
#include <bgfx/bgfx.h>
#include <tb_core.h>
#include <tb_font_renderer.h>
#include <tb_language.h>
#include <tb_msg.h>
#include <tb_node_tree.h>
#include <tb_renderer.h>
#include <tb_system.h>
#include <tb_widgets.h>
#include <tb_widgets_common.h>
#include <tb_widgets_reader.h>
using namespace tb;
namespace tb
{
void TBSystem::RescheduleTimer(double fire_time) {}
}
namespace Lumix
{
struct GUISystemImpl;
struct RootWidget : public TBWidget
{
RootWidget(GUISystemImpl& system) : gui_system(system) {}
bool OnEvent(const TBWidgetEvent& ev) override;
GUISystemImpl& gui_system;
};
struct LuaEvent
{
bool invoke()
{
if (lua_rawgeti(state, LUA_REGISTRYINDEX, function_ref) != LUA_TFUNCTION)
{
ASSERT(false);
}
if (lua_pcall(state, 0, 0, 0) != LUA_OK)
{
g_log_error.log("Gui") << lua_tostring(state, -1);
lua_pop(state, 1);
}
return true;
}
lua_State* state;
int function_ref;
};
struct BGFXBitmap : public TBBitmap
{
int Width() override { return w; }
int Height() override { return h; }
void SetData(uint32* data) override
{
pipeline->destroyTexture(tex);
tex = pipeline->createTexture(w, h, data);
}
Pipeline* pipeline;
bgfx::TextureHandle tex;
int w, h;
};
struct GUIRenderer : public TBRendererBatcher
{
GUIRenderer(Engine& engine)
: m_pipeline(nullptr)
{
m_decl.begin()
.add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)
.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
.end();
auto* material_manager = engine.getResourceManager().get(ResourceType("material"));
auto* resource = material_manager->load(Path("pipelines/imgui/imgui.mat"));
m_material = static_cast<Material*>(resource);
}
~GUIRenderer()
{
if (m_material) m_material->getResourceManager().unload(*m_material);
if (m_pipeline) m_pipeline->destroyUniform(m_texture_uniform);
}
TBBitmap* CreateBitmap(int width, int height, uint32* data) override
{
if (!m_pipeline) return nullptr;
auto* bitmap = new BGFXBitmap();
bitmap->tex = m_pipeline->createTexture(width, height, data);
bitmap->w = width;
bitmap->h = height;
bitmap->pipeline = m_pipeline;
return bitmap;
}
void RenderBatch(Batch* batch) override
{
if (!m_material->isReady()) return;
if (!m_pipeline->checkAvailTransientBuffers(batch->vertex_count, m_decl, batch->vertex_count)) return;
bgfx::TransientVertexBuffer vertex_buffer;
bgfx::TransientIndexBuffer index_buffer;
m_pipeline->allocTransientBuffers(
&vertex_buffer, batch->vertex_count, m_decl, &index_buffer, batch->vertex_count);
int16* idcs = (int16*)index_buffer.data;
struct Vertex
{
float x, y;
float u, v;
uint32 color;
};
Vertex* vtcs = (Vertex*)vertex_buffer.data;
for (int i = 0; i < batch->vertex_count; ++i)
{
idcs[i] = i;
vtcs[i].x = batch->vertex[i].x;
vtcs[i].y = batch->vertex[i].y;
vtcs[i].u = batch->vertex[i].u;
vtcs[i].v = batch->vertex[i].v;
vtcs[i].color = batch->vertex[i].col;
}
if (batch->bitmap) m_pipeline->setTexture(0, ((BGFXBitmap*)(batch->bitmap))->tex, m_texture_uniform);
m_pipeline->render(vertex_buffer,
index_buffer,
Matrix::IDENTITY,
0,
batch->vertex_count,
BGFX_STATE_BLEND_ALPHA,
m_material->getShaderInstance());
}
void SetClipRect(const TBRect& rect) override { m_pipeline->setScissor(rect.x, rect.y, rect.w, rect.h); }
Material* m_material;
bgfx::VertexDecl m_decl;
Pipeline* m_pipeline;
bgfx::UniformHandle m_texture_uniform;
};
struct GUISystemImpl : public GUISystem
{
GUISystemImpl(Engine& engine)
: m_engine(engine)
, m_renderer(engine)
, m_interface(nullptr)
, m_root_widget(*this)
, m_lua_events(engine.getAllocator())
{
tb_core_init(&m_renderer);
engine.getInputSystem().eventListener().bind<GUISystemImpl, &GUISystemImpl::onInputEvent>(this);
registerLuaAPI();
}
~GUISystemImpl()
{
m_engine.getInputSystem().eventListener().unbind<GUISystemImpl, &GUISystemImpl::onInputEvent>(this);
tb_core_shutdown();
}
void showGUI(bool show)
{
m_interface->enableCursor(show);
m_root_widget.SetVisibility(show ? WIDGET_VISIBILITY_VISIBLE : WIDGET_VISIBILITY_GONE);
}
bool isGUIShown() const
{
return m_root_widget.GetVisibility() == WIDGET_VISIBILITY_VISIBLE;
}
void loadFile(const char* path)
{
m_root_widget.DeleteAllChildren();
g_widgets_reader->LoadFile(&m_root_widget, path);
}
static int registerEvent(lua_State* L)
{
auto* gui = LuaWrapper::checkArg<GUISystemImpl*>(L, 1);
EVENT_TYPE event_type = (EVENT_TYPE)LuaWrapper::checkArg<int>(L, 2);
TBID widget_id = LuaWrapper::checkArg<const char*>(L, 3);
LuaEvent event;
event.state = L;
lua_pushvalue(L, 4);
event.function_ref = luaL_ref(L, LUA_REGISTRYINDEX);
lua_pop(L, 1);
uint64 event_id = (uint64)event_type << 32 | (uint32)widget_id;
gui->m_lua_events.insert(event_id, event);
return 0;
}
void unregisterEvent(int event_type, const char* widget_id)
{
TBID tb_widget_id(widget_id);
uint64 event_id = (uint64)event_type << 32 | (uint32)tb_widget_id;
m_lua_events.erase(event_id);
}
void registerLuaAPI()
{
lua_State* L = m_engine.getState();
#define REGISTER_FUNCTION(name) \
do {\
auto f = &LuaWrapper::wrapMethod<GUISystemImpl, decltype(&GUISystemImpl::name), \
&GUISystemImpl::name>; \
LuaWrapper::createSystemFunction(L, "Gui", #name, f); \
} while(false) \
REGISTER_FUNCTION(showGUI);
REGISTER_FUNCTION(isGUIShown);
REGISTER_FUNCTION(loadFile);
REGISTER_FUNCTION(unregisterEvent);
LuaWrapper::createSystemFunction(L, "Gui", "registerEvent", &GUISystemImpl::registerEvent);
LuaWrapper::createSystemVariable(L, "Gui", "instance", this);
LuaWrapper::createSystemVariable(L, "Gui", "EVENT_TYPE_CLICK", EVENT_TYPE_CLICK);
#undef REGISTER_FUNCTION
}
void setInterface(Interface* interface) override
{
// For safe typecasting
if (m_renderer.m_pipeline)
{
m_renderer.m_pipeline->destroyUniform(m_renderer.m_texture_uniform);
}
m_renderer.m_pipeline = nullptr;
m_interface = interface;
if (!m_interface) return;
auto* pipeline = m_interface->getPipeline();
pipeline->addCustomCommandHandler("renderIngameGUI")
.callback.bind<GUISystemImpl, &GUISystemImpl::pipelineCallback>(this);
m_renderer.m_pipeline = m_interface->getPipeline();
m_renderer.m_texture_uniform = m_renderer.m_pipeline->createTextureUniform("u_texture");
void register_stb_font_renderer();
register_stb_font_renderer();
g_font_manager->AddFontInfo("gui/vera.ttf", "Vera");
TBFontDescription fd;
fd.SetID(TBIDC("Vera"));
fd.SetSize(g_tb_skin->GetDimensionConverter()->DpToPx(14));
g_font_manager->SetDefaultFontDescription(fd);
TBFontFace* font = g_font_manager->CreateFontFace(g_font_manager->GetDefaultFontDescription());
if (font)
font->RenderGlyphs(
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz");
g_tb_lng->Load("gui/language/lng_en.tb.txt");
g_tb_skin->Load("gui/skin/skin.tb.txt");
}
void pipelineCallback()
{
int w = (int)m_interface->getSize().x;
int h = (int)m_interface->getSize().y;
m_renderer.BeginPaint(w, h);
Lumix::Matrix ortho;
m_root_widget.SetSize(w, h);
ortho.setOrtho(0.0f, (float)w, (float)h, 0.0f, -1.0f, 1.0f, false);
m_interface->getPipeline()->setViewProjection(ortho, w, h);
m_root_widget.InvokePaint(TBWidget::PaintProps());
m_renderer.EndPaint();
}
void onInputEvent(InputSystem::InputEvent& event)
{
Vec2 mouse_pos = m_engine.getInputSystem().getMousePos() - m_interface->getPos();
switch (event.type)
{
case InputSystem::InputEvent::POINTER_DOWN:
m_root_widget.InvokePointerDown((int)mouse_pos.x, (int)mouse_pos.y, 1, TB_MODIFIER_NONE, false);
break;
case InputSystem::InputEvent::POINTER_UP:
m_root_widget.InvokePointerUp((int)mouse_pos.x, (int)mouse_pos.y, TB_MODIFIER_NONE, false);
break;
case InputSystem::InputEvent::POINTER_MOVE:
m_root_widget.InvokePointerMove((int)mouse_pos.x, (int)mouse_pos.y, TB_MODIFIER_NONE, false);
break;
case InputSystem::InputEvent::KEY_DOWN:
m_root_widget.InvokeKey(event.key.sym, TB_KEY_UNDEFINED, TB_MODIFIER_NONE, true);
break;
case InputSystem::InputEvent::KEY_UP:
m_root_widget.InvokeKey(event.key.sym, TB_KEY_UNDEFINED, TB_MODIFIER_NONE, false);
break;
}
}
void update(float) override
{
float dx = m_engine.getInputSystem().getMouseXMove();
float dy = m_engine.getInputSystem().getMouseYMove();
Vec2 mouse_pos = m_engine.getInputSystem().getMousePos() - m_interface->getPos();
if (dx != 0 || dy != 0)
{
m_root_widget.InvokePointerMove((int)mouse_pos.x, (int)mouse_pos.y, TB_MODIFIER_NONE, false);
}
TBAnimationManager::Update();
m_root_widget.InvokeProcessStates();
m_root_widget.InvokeProcess();
TBMessageHandler::ProcessMessages();
}
void stopGame() override { m_lua_events.clear(); }
const char* getName() const override { return "gui"; }
Engine& m_engine;
RootWidget m_root_widget;
GUIRenderer m_renderer;
Interface* m_interface;
HashMap<uint64, LuaEvent> m_lua_events;
};
bool RootWidget::OnEvent(const TBWidgetEvent& ev)
{
uint64 event_id = (uint64)ev.type << 32 | (uint32)ev.target->GetID();
auto iter = gui_system.m_lua_events.find(event_id);
if (!iter.isValid()) return false;
return iter.value().invoke();
}
LUMIX_PLUGIN_ENTRY(gui)
{
return LUMIX_NEW(engine.getAllocator(), GUISystemImpl)(engine);
}
} // namespace Lumix
<commit_msg>ingame gui's slider value can be accessed from Lua<commit_after>#include "gui_system.h"
#include "engine/delegate.h"
#include "engine/delegate_list.h"
#include "engine/engine.h"
#include "engine/iallocator.h"
#include "engine/input_system.h"
#include "engine/lua_wrapper.h"
#include "engine/matrix.h"
#include "engine/path.h"
#include "engine/resource_manager.h"
#include "renderer/material.h"
#include "renderer/material_manager.h"
#include "renderer/pipeline.h"
#include "renderer/shader.h"
#pragma warning(disable : 4267)
#include "tb_renderer_batcher.h"
#include <animation/tb_animation.h>
#include <bgfx/bgfx.h>
#include <tb_core.h>
#include <tb_font_renderer.h>
#include <tb_language.h>
#include <tb_msg.h>
#include <tb_node_tree.h>
#include <tb_renderer.h>
#include <tb_system.h>
#include <tb_widgets.h>
#include <tb_widgets_common.h>
#include <tb_widgets_reader.h>
using namespace tb;
namespace tb
{
void TBSystem::RescheduleTimer(double fire_time) {}
}
namespace Lumix
{
struct GUISystemImpl;
struct RootWidget : public TBWidget
{
RootWidget(GUISystemImpl& system) : gui_system(system) {}
bool OnEvent(const TBWidgetEvent& ev) override;
GUISystemImpl& gui_system;
};
struct LuaEvent
{
bool invoke()
{
if (lua_rawgeti(state, LUA_REGISTRYINDEX, function_ref) != LUA_TFUNCTION)
{
ASSERT(false);
}
if (lua_pcall(state, 0, 0, 0) != LUA_OK)
{
g_log_error.log("Gui") << lua_tostring(state, -1);
lua_pop(state, 1);
}
return true;
}
lua_State* state;
int function_ref;
};
struct BGFXBitmap : public TBBitmap
{
int Width() override { return w; }
int Height() override { return h; }
void SetData(uint32* data) override
{
pipeline->destroyTexture(tex);
tex = pipeline->createTexture(w, h, data);
}
Pipeline* pipeline;
bgfx::TextureHandle tex;
int w, h;
};
struct GUIRenderer : public TBRendererBatcher
{
GUIRenderer(Engine& engine)
: m_pipeline(nullptr)
{
m_decl.begin()
.add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)
.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
.end();
auto* material_manager = engine.getResourceManager().get(ResourceType("material"));
auto* resource = material_manager->load(Path("pipelines/imgui/imgui.mat"));
m_material = static_cast<Material*>(resource);
}
~GUIRenderer()
{
if (m_material) m_material->getResourceManager().unload(*m_material);
if (m_pipeline) m_pipeline->destroyUniform(m_texture_uniform);
}
TBBitmap* CreateBitmap(int width, int height, uint32* data) override
{
if (!m_pipeline) return nullptr;
auto* bitmap = new BGFXBitmap();
bitmap->tex = m_pipeline->createTexture(width, height, data);
bitmap->w = width;
bitmap->h = height;
bitmap->pipeline = m_pipeline;
return bitmap;
}
void RenderBatch(Batch* batch) override
{
if (!m_material->isReady()) return;
if (!m_pipeline->checkAvailTransientBuffers(batch->vertex_count, m_decl, batch->vertex_count)) return;
bgfx::TransientVertexBuffer vertex_buffer;
bgfx::TransientIndexBuffer index_buffer;
m_pipeline->allocTransientBuffers(
&vertex_buffer, batch->vertex_count, m_decl, &index_buffer, batch->vertex_count);
int16* idcs = (int16*)index_buffer.data;
struct Vertex
{
float x, y;
float u, v;
uint32 color;
};
Vertex* vtcs = (Vertex*)vertex_buffer.data;
for (int i = 0; i < batch->vertex_count; ++i)
{
idcs[i] = i;
vtcs[i].x = batch->vertex[i].x;
vtcs[i].y = batch->vertex[i].y;
vtcs[i].u = batch->vertex[i].u;
vtcs[i].v = batch->vertex[i].v;
vtcs[i].color = batch->vertex[i].col;
}
if (batch->bitmap) m_pipeline->setTexture(0, ((BGFXBitmap*)(batch->bitmap))->tex, m_texture_uniform);
m_pipeline->render(vertex_buffer,
index_buffer,
Matrix::IDENTITY,
0,
batch->vertex_count,
BGFX_STATE_BLEND_ALPHA,
m_material->getShaderInstance());
}
void SetClipRect(const TBRect& rect) override { m_pipeline->setScissor(rect.x, rect.y, rect.w, rect.h); }
Material* m_material;
bgfx::VertexDecl m_decl;
Pipeline* m_pipeline;
bgfx::UniformHandle m_texture_uniform;
};
struct GUISystemImpl : public GUISystem
{
GUISystemImpl(Engine& engine)
: m_engine(engine)
, m_renderer(engine)
, m_interface(nullptr)
, m_root_widget(*this)
, m_lua_events(engine.getAllocator())
{
tb_core_init(&m_renderer);
engine.getInputSystem().eventListener().bind<GUISystemImpl, &GUISystemImpl::onInputEvent>(this);
registerLuaAPI();
}
~GUISystemImpl()
{
m_engine.getInputSystem().eventListener().unbind<GUISystemImpl, &GUISystemImpl::onInputEvent>(this);
tb_core_shutdown();
}
void showGUI(bool show)
{
m_interface->enableCursor(show);
m_root_widget.SetVisibility(show ? WIDGET_VISIBILITY_VISIBLE : WIDGET_VISIBILITY_GONE);
}
bool isGUIShown() const
{
return m_root_widget.GetVisibility() == WIDGET_VISIBILITY_VISIBLE;
}
void loadFile(const char* path)
{
m_root_widget.DeleteAllChildren();
g_widgets_reader->LoadFile(&m_root_widget, path);
}
int getSliderValue(const char* id)
{
auto* slider = m_root_widget.GetWidgetByID(tb::TBID(id));
return slider->GetValue();
}
void setSliderValue(const char* id, int value)
{
auto* slider = m_root_widget.GetWidgetByID(tb::TBID(id));
slider->SetValue(value);
}
static int registerEvent(lua_State* L)
{
auto* gui = LuaWrapper::checkArg<GUISystemImpl*>(L, 1);
EVENT_TYPE event_type = (EVENT_TYPE)LuaWrapper::checkArg<int>(L, 2);
TBID widget_id = LuaWrapper::checkArg<const char*>(L, 3);
LuaEvent event;
event.state = L;
lua_pushvalue(L, 4);
event.function_ref = luaL_ref(L, LUA_REGISTRYINDEX);
lua_pop(L, 1);
uint64 event_id = (uint64)event_type << 32 | (uint32)widget_id;
gui->m_lua_events.insert(event_id, event);
return 0;
}
void unregisterEvent(int event_type, const char* widget_id)
{
TBID tb_widget_id(widget_id);
uint64 event_id = (uint64)event_type << 32 | (uint32)tb_widget_id;
m_lua_events.erase(event_id);
}
void registerLuaAPI()
{
lua_State* L = m_engine.getState();
#define REGISTER_FUNCTION(name) \
do {\
auto f = &LuaWrapper::wrapMethod<GUISystemImpl, decltype(&GUISystemImpl::name), \
&GUISystemImpl::name>; \
LuaWrapper::createSystemFunction(L, "Gui", #name, f); \
} while(false) \
REGISTER_FUNCTION(showGUI);
REGISTER_FUNCTION(isGUIShown);
REGISTER_FUNCTION(loadFile);
REGISTER_FUNCTION(getSliderValue);
REGISTER_FUNCTION(setSliderValue);
REGISTER_FUNCTION(unregisterEvent);
LuaWrapper::createSystemFunction(L, "Gui", "registerEvent", &GUISystemImpl::registerEvent);
LuaWrapper::createSystemVariable(L, "Gui", "instance", this);
LuaWrapper::createSystemVariable(L, "Gui", "EVENT_TYPE_CLICK", EVENT_TYPE_CLICK);
LuaWrapper::createSystemVariable(L, "Gui", "EVENT_TYPE_CHANGED", EVENT_TYPE_CHANGED);
#undef REGISTER_FUNCTION
}
void setInterface(Interface* interface) override
{
// For safe typecasting
if (m_renderer.m_pipeline)
{
m_renderer.m_pipeline->destroyUniform(m_renderer.m_texture_uniform);
}
m_renderer.m_pipeline = nullptr;
m_interface = interface;
if (!m_interface) return;
auto* pipeline = m_interface->getPipeline();
pipeline->addCustomCommandHandler("renderIngameGUI")
.callback.bind<GUISystemImpl, &GUISystemImpl::pipelineCallback>(this);
m_renderer.m_pipeline = m_interface->getPipeline();
m_renderer.m_texture_uniform = m_renderer.m_pipeline->createTextureUniform("u_texture");
void register_stb_font_renderer();
register_stb_font_renderer();
g_font_manager->AddFontInfo("gui/vera.ttf", "Vera");
TBFontDescription fd;
fd.SetID(TBIDC("Vera"));
fd.SetSize(g_tb_skin->GetDimensionConverter()->DpToPx(14));
g_font_manager->SetDefaultFontDescription(fd);
TBFontFace* font = g_font_manager->CreateFontFace(g_font_manager->GetDefaultFontDescription());
if (font)
font->RenderGlyphs(
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz");
g_tb_lng->Load("gui/language/lng_en.tb.txt");
g_tb_skin->Load("gui/skin/skin.tb.txt");
}
void pipelineCallback()
{
int w = (int)m_interface->getSize().x;
int h = (int)m_interface->getSize().y;
m_renderer.BeginPaint(w, h);
Lumix::Matrix ortho;
m_root_widget.SetSize(w, h);
ortho.setOrtho(0.0f, (float)w, (float)h, 0.0f, -1.0f, 1.0f, false);
m_interface->getPipeline()->setViewProjection(ortho, w, h);
m_root_widget.InvokePaint(TBWidget::PaintProps());
m_renderer.EndPaint();
}
void onInputEvent(InputSystem::InputEvent& event)
{
Vec2 mouse_pos = m_engine.getInputSystem().getMousePos() - m_interface->getPos();
switch (event.type)
{
case InputSystem::InputEvent::POINTER_DOWN:
m_root_widget.InvokePointerDown((int)mouse_pos.x, (int)mouse_pos.y, 1, TB_MODIFIER_NONE, false);
break;
case InputSystem::InputEvent::POINTER_UP:
m_root_widget.InvokePointerUp((int)mouse_pos.x, (int)mouse_pos.y, TB_MODIFIER_NONE, false);
break;
case InputSystem::InputEvent::POINTER_MOVE:
m_root_widget.InvokePointerMove((int)mouse_pos.x, (int)mouse_pos.y, TB_MODIFIER_NONE, false);
break;
case InputSystem::InputEvent::KEY_DOWN:
m_root_widget.InvokeKey(event.key.sym, TB_KEY_UNDEFINED, TB_MODIFIER_NONE, true);
break;
case InputSystem::InputEvent::KEY_UP:
m_root_widget.InvokeKey(event.key.sym, TB_KEY_UNDEFINED, TB_MODIFIER_NONE, false);
break;
}
}
void update(float) override
{
float dx = m_engine.getInputSystem().getMouseXMove();
float dy = m_engine.getInputSystem().getMouseYMove();
Vec2 mouse_pos = m_engine.getInputSystem().getMousePos() - m_interface->getPos();
if (dx != 0 || dy != 0)
{
m_root_widget.InvokePointerMove((int)mouse_pos.x, (int)mouse_pos.y, TB_MODIFIER_NONE, false);
}
TBAnimationManager::Update();
m_root_widget.InvokeProcessStates();
m_root_widget.InvokeProcess();
TBMessageHandler::ProcessMessages();
}
void stopGame() override { m_lua_events.clear(); }
const char* getName() const override { return "gui"; }
Engine& m_engine;
RootWidget m_root_widget;
GUIRenderer m_renderer;
Interface* m_interface;
HashMap<uint64, LuaEvent> m_lua_events;
};
bool RootWidget::OnEvent(const TBWidgetEvent& ev)
{
uint64 event_id = (uint64)ev.type << 32 | (uint32)ev.target->GetID();
auto iter = gui_system.m_lua_events.find(event_id);
if (!iter.isValid()) return false;
return iter.value().invoke();
}
LUMIX_PLUGIN_ENTRY(gui)
{
return LUMIX_NEW(engine.getAllocator(), GUISystemImpl)(engine);
}
} // namespace Lumix
<|endoftext|>
|
<commit_before>/* This file is part of the Tufão project
Copyright (C) 2012 Vinícius dos Santos Oliveira <vini.ipsmaker@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any
later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "priv/httpfileserver.h"
#include <QtCore/QFileInfo>
#include <QtCore/QDateTime>
#include <QtCore/QPair>
#include <QtCore/QDir>
#include <QtCore/QUrl>
#include <QtNetwork/QAbstractSocket>
#include "httpserverrequest.h"
static qint64 bufferSize = BUFFER_SIZE;
inline static QList< QPair<qulonglong, qulonglong> >
ranges(const Tufao::Headers &headers, qulonglong fileSize)
{
if (!headers.contains("Range"))
return QList< QPair<qulonglong, qulonglong> >();
QList< QPair<qulonglong, qulonglong> > ranges;
QList<QByteArray> rangeHeaders(headers.values("Range"));
foreach (QByteArray rangesSpecifier, rangeHeaders) {
static const QByteArray bytesUnit("bytes=");
if (!rangesSpecifier.startsWith(bytesUnit))
continue;
QList<QByteArray> rangeSet(rangesSpecifier.mid(bytesUnit.size())
.split(','));
foreach (QByteArray rangeSpec, rangeSet) {
rangeSpec = rangeSpec.trimmed();
if (rangeSpec.startsWith('-')) {
bool ok;
qulonglong nbytes = rangeSpec.mid(1).toULongLong(&ok);
if (!ok || nbytes == 0)
continue;
if (nbytes >= fileSize) {
ranges.push_back(QPair<qulonglong, qulonglong>
(0, fileSize - 1));
} else {
ranges.push_back(QPair<qulonglong, qulonglong>
(fileSize - nbytes, fileSize - 1));
}
} else {
int i = rangeSpec.indexOf('-');
if (i == -1)
continue;
bool ok[2];
QPair<qulonglong, qulonglong>
range(rangeSpec.toULongLong(ok),
rangeSpec.mid(1 + i).toULongLong());
if (!ok[1])
range.second = fileSize - 1;
if (!ok[0] || range.second < range.first
|| range.first >= fileSize)
continue;
if (range.second >= fileSize)
range.second = fileSize;
ranges.push_back(range);
}
}
}
return ranges;
}
namespace Tufao {
HttpFileServer::HttpFileServer(const QString &dir, QObject *parent) :
AbstractHttpServerRequestHandler(parent),
priv(new Priv(dir))
{
}
HttpFileServer::~HttpFileServer()
{
delete priv;
}
// split method in check and transmit phases
// also, how the hell will this work with 404-responses?
void HttpFileServer::serveFile(const QString &fileName,
HttpServerRequest &request,
HttpServerResponse &response)
{
// Check if method is alright
{
const QByteArray method(request.method());
if (method != "GET" && method != "HEAD") {
response.writeHead(HttpResponseStatusCode::METHOD_NOT_ALLOWED);
response.headers().insert("Allow", "GET, HEAD");
response.end();
return;
}
}
QFileInfo fileInfo(fileName);
if (!fileInfo.exists()) {
response.writeHead(HttpResponseStatusCode::NOT_FOUND);
response.end();
return;
}
// Check "If-Modified-Since" header
if (request.headers().contains("If-Modified-Since")) {
foreach (const QByteArray &value,
request.headers().values("If-Modified-Since")) {
QDateTime date(Headers::toDateTime(value));
// Ignore invalid values
if (fileInfo.lastModified() < date || !date.isValid()) {
continue;
} else if (fileInfo.lastModified() == date) {
response.writeHead(HttpResponseStatusCode::NOT_MODIFIED);
response.end();
}
}
}
// Check "If-Unmodified-Since" header
if (request.headers().contains("If-Unmodified-Since")) {
foreach (const QByteArray &value,
request.headers().values("If-Unmodified-Since")) {
QDateTime date(Headers::toDateTime(value));
// Ignore invalid values
if (fileInfo.lastModified() < date || !date.isValid()) {
continue;
} else if (fileInfo.lastModified() > date) {
response.writeHead(HttpResponseStatusCode::PRECONDITION_FAILED);
response.end();
}
}
}
// Check If-Range header
if (request.headers().contains("If-Range")
&& request.headers().contains("Range")) {
foreach (QByteArray value, request.headers().values("If-Range")) {
// Ignore ETags
int strSize = value.size();
if ((strSize > 0 && value[0] == '"')
|| (strSize > 1 && value[0] == 'W' && value[1] == '/')) {
continue;
} else {
QDateTime date(Headers::toDateTime(value));
// Ignore invalid values
if (fileInfo.lastModified() < date || !date.isValid()) {
continue;
} else if (fileInfo.lastModified() > date) {
// Return the entire entity using a 200 response
request.headers().remove("Range");
break;
}
}
}
}
// All conditionals were okay, continue...
response.headers().insert("Accept-Ranges", "bytes");
response.headers().insert("Date", Headers
::fromDateTime(QDateTime::currentDateTime()));
response.headers().insert("Last-Modified", Headers
::fromDateTime(fileInfo.lastModified()));
if (request.method() == "HEAD") {
response.writeHead(HttpResponseStatusCode::OK);
response.end();
return;
}
QFile file(fileName);
file.open(QIODevice::ReadOnly);
QList< QPair<qulonglong, qulonglong> >
ranges(::ranges(request.headers(), fileInfo.size()));
// Not a byterange request
if (!ranges.size()) {
// Not a _satisfiable_ byterange request
if (request.headers().contains("Range")) {
static const QByteArray bytesUnit("bytes */");
response.writeHead(HttpResponseStatusCode
::REQUESTED_RANGE_NOT_SATISFIABLE);
response.headers().insert("Content-Range", bytesUnit
+ QByteArray::number(fileInfo.size()));
response.end();
return;
}
// Just send the entity
response.writeHead(HttpResponseStatusCode::OK);
while (!file.atEnd()) {
response << file.read(::bufferSize);
request.socket().flush();
}
response.end();
} else if (ranges.size() == 1) {
// ONE range
static const QByteArray bytesUnit("bytes ");
response.writeHead(HttpResponseStatusCode::OK);
QPair<qulonglong, qulonglong> &range(ranges[0]);
response.headers().insert("Content-Range", bytesUnit
+ QByteArray::number(range.first)
+ '-'
+ QByteArray::number(range.second)
+ '/'
+ QByteArray::number(fileInfo.size()));
file.seek(range.first);
qint64 remaining = 1 + range.second - range.first;
while (remaining) {
QByteArray chunk(file.read(qMin(remaining, ::bufferSize)));
response << chunk;
request.socket().flush();
remaining -= chunk.size();
}
response.end();
} else {
// MULTIPLE ranges
QByteArray contentType(response.headers().value("Content-Type"));
response.headers().replace("Content-Type", "multipart/byteranges;"
" boundary=THIS_STRING_SEPARATES");
for (int i = 0;i != ranges.size();++i) {
QPair<qulonglong, qulonglong> &range(ranges[i]);
response << "--THIS_STRING_SEPARATES\r\n";
if (!contentType.isEmpty())
response << "Content-type: " << contentType << "\r\n";
response << QByteArray("Content-range: bytes")
<< QByteArray::number(range.first) << QByteArray(1, '-')
<< QByteArray::number(range.second)
<< QByteArray(1, '/')
<< QByteArray::number(fileInfo.size()) << "\r\n"
<< QByteArray("\r\n");
file.seek(range.first);
qint64 remaining = 1 + range.second - range.first;
while (remaining) {
QByteArray chunk(file.read(qMin(remaining, ::bufferSize)));
response << chunk;
request.socket().flush();
remaining -= chunk.size();
}
}
response.end("--THIS_STRING_SEPARATES--\r\n");
}
}
bool HttpFileServer::serveFile(const QString &fileName,
HttpServerResponse &response,
HttpResponseStatusCode statusCode)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
return false;
response.writeHead(statusCode);
qint64 remaining = file.size();
while (remaining) {
QByteArray chunk(file.read(qMin(remaining, ::bufferSize)));
response << chunk;
response.flush();
remaining -= chunk.size();
}
response.end();
return true;
}
qint64 HttpFileServer::bufferSize()
{
return ::bufferSize;
}
void HttpFileServer::setBufferSize(qint64 size)
{
if (size <= 0)
return;
::bufferSize = size;
}
bool HttpFileServer::handleRequest(HttpServerRequest &request,
HttpServerResponse &response)
{
QString fileName{
QDir::cleanPath(priv->rootDir
+ QDir::toNativeSeparators(request.url()
.path(QUrl::FullyDecoded)))};
if (!fileName.startsWith(priv->rootDir + QDir::separator()))
return false;
{
QFileInfo fileInfo(fileName);
if (!fileInfo.exists() || !fileInfo.isFile())
return false;
}
serveFile(fileName, request, response);
return true;
}
} // namespace Tufao
<commit_msg>Removed obsolete comment in HttpFileServer code<commit_after>/* This file is part of the Tufão project
Copyright (C) 2012 Vinícius dos Santos Oliveira <vini.ipsmaker@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any
later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "priv/httpfileserver.h"
#include <QtCore/QFileInfo>
#include <QtCore/QDateTime>
#include <QtCore/QPair>
#include <QtCore/QDir>
#include <QtCore/QUrl>
#include <QtNetwork/QAbstractSocket>
#include "httpserverrequest.h"
static qint64 bufferSize = BUFFER_SIZE;
inline static QList< QPair<qulonglong, qulonglong> >
ranges(const Tufao::Headers &headers, qulonglong fileSize)
{
if (!headers.contains("Range"))
return QList< QPair<qulonglong, qulonglong> >();
QList< QPair<qulonglong, qulonglong> > ranges;
QList<QByteArray> rangeHeaders(headers.values("Range"));
foreach (QByteArray rangesSpecifier, rangeHeaders) {
static const QByteArray bytesUnit("bytes=");
if (!rangesSpecifier.startsWith(bytesUnit))
continue;
QList<QByteArray> rangeSet(rangesSpecifier.mid(bytesUnit.size())
.split(','));
foreach (QByteArray rangeSpec, rangeSet) {
rangeSpec = rangeSpec.trimmed();
if (rangeSpec.startsWith('-')) {
bool ok;
qulonglong nbytes = rangeSpec.mid(1).toULongLong(&ok);
if (!ok || nbytes == 0)
continue;
if (nbytes >= fileSize) {
ranges.push_back(QPair<qulonglong, qulonglong>
(0, fileSize - 1));
} else {
ranges.push_back(QPair<qulonglong, qulonglong>
(fileSize - nbytes, fileSize - 1));
}
} else {
int i = rangeSpec.indexOf('-');
if (i == -1)
continue;
bool ok[2];
QPair<qulonglong, qulonglong>
range(rangeSpec.toULongLong(ok),
rangeSpec.mid(1 + i).toULongLong());
if (!ok[1])
range.second = fileSize - 1;
if (!ok[0] || range.second < range.first
|| range.first >= fileSize)
continue;
if (range.second >= fileSize)
range.second = fileSize;
ranges.push_back(range);
}
}
}
return ranges;
}
namespace Tufao {
HttpFileServer::HttpFileServer(const QString &dir, QObject *parent) :
AbstractHttpServerRequestHandler(parent),
priv(new Priv(dir))
{
}
HttpFileServer::~HttpFileServer()
{
delete priv;
}
void HttpFileServer::serveFile(const QString &fileName,
HttpServerRequest &request,
HttpServerResponse &response)
{
// Check if method is alright
{
const QByteArray method(request.method());
if (method != "GET" && method != "HEAD") {
response.writeHead(HttpResponseStatusCode::METHOD_NOT_ALLOWED);
response.headers().insert("Allow", "GET, HEAD");
response.end();
return;
}
}
QFileInfo fileInfo(fileName);
if (!fileInfo.exists()) {
response.writeHead(HttpResponseStatusCode::NOT_FOUND);
response.end();
return;
}
// Check "If-Modified-Since" header
if (request.headers().contains("If-Modified-Since")) {
foreach (const QByteArray &value,
request.headers().values("If-Modified-Since")) {
QDateTime date(Headers::toDateTime(value));
// Ignore invalid values
if (fileInfo.lastModified() < date || !date.isValid()) {
continue;
} else if (fileInfo.lastModified() == date) {
response.writeHead(HttpResponseStatusCode::NOT_MODIFIED);
response.end();
}
}
}
// Check "If-Unmodified-Since" header
if (request.headers().contains("If-Unmodified-Since")) {
foreach (const QByteArray &value,
request.headers().values("If-Unmodified-Since")) {
QDateTime date(Headers::toDateTime(value));
// Ignore invalid values
if (fileInfo.lastModified() < date || !date.isValid()) {
continue;
} else if (fileInfo.lastModified() > date) {
response.writeHead(HttpResponseStatusCode::PRECONDITION_FAILED);
response.end();
}
}
}
// Check If-Range header
if (request.headers().contains("If-Range")
&& request.headers().contains("Range")) {
foreach (QByteArray value, request.headers().values("If-Range")) {
// Ignore ETags
int strSize = value.size();
if ((strSize > 0 && value[0] == '"')
|| (strSize > 1 && value[0] == 'W' && value[1] == '/')) {
continue;
} else {
QDateTime date(Headers::toDateTime(value));
// Ignore invalid values
if (fileInfo.lastModified() < date || !date.isValid()) {
continue;
} else if (fileInfo.lastModified() > date) {
// Return the entire entity using a 200 response
request.headers().remove("Range");
break;
}
}
}
}
// All conditionals were okay, continue...
response.headers().insert("Accept-Ranges", "bytes");
response.headers().insert("Date", Headers
::fromDateTime(QDateTime::currentDateTime()));
response.headers().insert("Last-Modified", Headers
::fromDateTime(fileInfo.lastModified()));
if (request.method() == "HEAD") {
response.writeHead(HttpResponseStatusCode::OK);
response.end();
return;
}
QFile file(fileName);
file.open(QIODevice::ReadOnly);
QList< QPair<qulonglong, qulonglong> >
ranges(::ranges(request.headers(), fileInfo.size()));
// Not a byterange request
if (!ranges.size()) {
// Not a _satisfiable_ byterange request
if (request.headers().contains("Range")) {
static const QByteArray bytesUnit("bytes */");
response.writeHead(HttpResponseStatusCode
::REQUESTED_RANGE_NOT_SATISFIABLE);
response.headers().insert("Content-Range", bytesUnit
+ QByteArray::number(fileInfo.size()));
response.end();
return;
}
// Just send the entity
response.writeHead(HttpResponseStatusCode::OK);
while (!file.atEnd()) {
response << file.read(::bufferSize);
request.socket().flush();
}
response.end();
} else if (ranges.size() == 1) {
// ONE range
static const QByteArray bytesUnit("bytes ");
response.writeHead(HttpResponseStatusCode::OK);
QPair<qulonglong, qulonglong> &range(ranges[0]);
response.headers().insert("Content-Range", bytesUnit
+ QByteArray::number(range.first)
+ '-'
+ QByteArray::number(range.second)
+ '/'
+ QByteArray::number(fileInfo.size()));
file.seek(range.first);
qint64 remaining = 1 + range.second - range.first;
while (remaining) {
QByteArray chunk(file.read(qMin(remaining, ::bufferSize)));
response << chunk;
request.socket().flush();
remaining -= chunk.size();
}
response.end();
} else {
// MULTIPLE ranges
QByteArray contentType(response.headers().value("Content-Type"));
response.headers().replace("Content-Type", "multipart/byteranges;"
" boundary=THIS_STRING_SEPARATES");
for (int i = 0;i != ranges.size();++i) {
QPair<qulonglong, qulonglong> &range(ranges[i]);
response << "--THIS_STRING_SEPARATES\r\n";
if (!contentType.isEmpty())
response << "Content-type: " << contentType << "\r\n";
response << QByteArray("Content-range: bytes")
<< QByteArray::number(range.first) << QByteArray(1, '-')
<< QByteArray::number(range.second)
<< QByteArray(1, '/')
<< QByteArray::number(fileInfo.size()) << "\r\n"
<< QByteArray("\r\n");
file.seek(range.first);
qint64 remaining = 1 + range.second - range.first;
while (remaining) {
QByteArray chunk(file.read(qMin(remaining, ::bufferSize)));
response << chunk;
request.socket().flush();
remaining -= chunk.size();
}
}
response.end("--THIS_STRING_SEPARATES--\r\n");
}
}
bool HttpFileServer::serveFile(const QString &fileName,
HttpServerResponse &response,
HttpResponseStatusCode statusCode)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
return false;
response.writeHead(statusCode);
qint64 remaining = file.size();
while (remaining) {
QByteArray chunk(file.read(qMin(remaining, ::bufferSize)));
response << chunk;
response.flush();
remaining -= chunk.size();
}
response.end();
return true;
}
qint64 HttpFileServer::bufferSize()
{
return ::bufferSize;
}
void HttpFileServer::setBufferSize(qint64 size)
{
if (size <= 0)
return;
::bufferSize = size;
}
bool HttpFileServer::handleRequest(HttpServerRequest &request,
HttpServerResponse &response)
{
QString fileName{
QDir::cleanPath(priv->rootDir
+ QDir::toNativeSeparators(request.url()
.path(QUrl::FullyDecoded)))};
if (!fileName.startsWith(priv->rootDir + QDir::separator()))
return false;
{
QFileInfo fileInfo(fileName);
if (!fileInfo.exists() || !fileInfo.isFile())
return false;
}
serveFile(fileName, request, response);
return true;
}
} // namespace Tufao
<|endoftext|>
|
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "urihandler.h"
#ifndef KORG_NODCOP
#include <dcopclient.h>
#include "kmailIface_stub.h"
#endif
#include <kiconloader.h>
#include <krun.h>
#include <kapplication.h>
#include <kprocess.h>
#include <kdebug.h>
bool UriHandler::process( const QString &uri )
{
kdDebug(5850) << "UriHandler::process(): " << uri << endl;
#ifndef KORG_NODCOP
if ( uri.startsWith( "kmail:" ) ) {
// make sure kmail is running or the part is shown
kapp->startServiceByDesktopPath("kmail");
// parse string, show
int colon = uri.find( ':' );
// extract 'number' from 'kmail:<number>/<id>'
QString serialNumberStr = uri.mid( colon + 1 );
serialNumberStr = serialNumberStr.left( serialNumberStr.find( '/' ) );
KMailIface_stub kmailIface( "kmail", "KMailIface" );
kmailIface.showMail( serialNumberStr.toUInt(), QString() );
return true;
} else if ( uri.startsWith( "mailto:" ) ) {
KApplication::kApplication()->invokeMailer( uri.mid(7), QString::null );
return true;
} else if ( uri.startsWith( "uid:" ) ) {
DCOPClient *client = KApplication::kApplication()->dcopClient();
const QByteArray noParamData;
const QByteArray paramData;
QByteArray replyData;
QCString replyTypeStr;
bool foundAbbrowser = client->call( "kaddressbook", "KAddressBookIface",
"interfaces()", noParamData,
replyTypeStr, replyData );
if ( foundAbbrowser ) {
//KAddressbook is already running, so just DCOP to it to bring up the contact editor
#if KDE_IS_VERSION( 3, 2, 90 )
kapp->updateRemoteUserTimestamp("kaddressbook");
#endif
DCOPRef kaddressbook( "kaddressbook", "KAddressBookIface" );
kaddressbook.send( "showContactEditor", uri.mid( 6 ) );
return true;
} else {
/*
KaddressBook is not already running. Pass it the UID of the contact via the command line while starting it - its neater.
We start it without its main interface
*/
KIconLoader *iconLoader = new KIconLoader();
QString iconPath = iconLoader->iconPath( "go", KIcon::Small );
delete iconLoader;
QString tmpStr = "kaddressbook --editor-only --uid ";
tmpStr += KProcess::quote( uri.mid( 6 ) );
KRun::runCommand( tmpStr, "KAddressBook", iconPath );
return true;
}
}
else { // no special URI, let KDE handle it
new KRun(KURL( uri ));
}
#endif
return false;
}
<commit_msg>This should be the global iconloader anyway.<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "urihandler.h"
#ifndef KORG_NODCOP
#include <dcopclient.h>
#include "kmailIface_stub.h"
#endif
#include <kiconloader.h>
#include <krun.h>
#include <kapplication.h>
#include <kprocess.h>
#include <kdebug.h>
bool UriHandler::process( const QString &uri )
{
kdDebug(5850) << "UriHandler::process(): " << uri << endl;
#ifndef KORG_NODCOP
if ( uri.startsWith( "kmail:" ) ) {
// make sure kmail is running or the part is shown
kapp->startServiceByDesktopPath("kmail");
// parse string, show
int colon = uri.find( ':' );
// extract 'number' from 'kmail:<number>/<id>'
QString serialNumberStr = uri.mid( colon + 1 );
serialNumberStr = serialNumberStr.left( serialNumberStr.find( '/' ) );
KMailIface_stub kmailIface( "kmail", "KMailIface" );
kmailIface.showMail( serialNumberStr.toUInt(), QString() );
return true;
} else if ( uri.startsWith( "mailto:" ) ) {
KApplication::kApplication()->invokeMailer( uri.mid(7), QString::null );
return true;
} else if ( uri.startsWith( "uid:" ) ) {
DCOPClient *client = KApplication::kApplication()->dcopClient();
const QByteArray noParamData;
const QByteArray paramData;
QByteArray replyData;
QCString replyTypeStr;
bool foundAbbrowser = client->call( "kaddressbook", "KAddressBookIface",
"interfaces()", noParamData,
replyTypeStr, replyData );
if ( foundAbbrowser ) {
//KAddressbook is already running, so just DCOP to it to bring up the contact editor
#if KDE_IS_VERSION( 3, 2, 90 )
kapp->updateRemoteUserTimestamp("kaddressbook");
#endif
DCOPRef kaddressbook( "kaddressbook", "KAddressBookIface" );
kaddressbook.send( "showContactEditor", uri.mid( 6 ) );
return true;
} else {
/*
KaddressBook is not already running. Pass it the UID of the contact via the command line while starting it - its neater.
We start it without its main interface
*/
QString iconPath = KGlobal::iconLoader()->iconPath( "go", KIcon::Small );
QString tmpStr = "kaddressbook --editor-only --uid ";
tmpStr += KProcess::quote( uri.mid( 6 ) );
KRun::runCommand( tmpStr, "KAddressBook", iconPath );
return true;
}
}
else { // no special URI, let KDE handle it
new KRun(KURL( uri ));
}
#endif
return false;
}
<|endoftext|>
|
<commit_before>#pragma once
namespace principia {
namespace ksp_plugin {
// A boolean which is constructed true and becomes false when |Flop| is called.
class Monostable {
public:
Monostable() = default;
~Monostable() = default;
Monostable(Monostable const&) = delete;
Monostable(Monostable&&) = delete;;
Monostable& operator=(Monostable const&) = delete;
Monostable& operator=(Monostable&&) = delete;
void Flop();
operator bool() const;
private:
bool transient_ = true;
};
} // namespace ksp_plugin
} // namespace principia
<commit_msg>Why didn't the linter catch that?<commit_after>#pragma once
namespace principia {
namespace ksp_plugin {
// A boolean which is constructed true and becomes false when |Flop| is called.
class Monostable {
public:
Monostable() = default;
~Monostable() = default;
Monostable(Monostable const&) = delete;
Monostable(Monostable&&) = delete;
Monostable& operator=(Monostable const&) = delete;
Monostable& operator=(Monostable&&) = delete;
void Flop();
operator bool() const;
private:
bool transient_ = true;
};
} // namespace ksp_plugin
} // namespace principia
<|endoftext|>
|
<commit_before>#include "text_blob.h"
#include "wx/dcgraph.h"
#include "wx/graphics.h"
#include "wx/tokenzr.h"
#include <iostream>
#include <algorithm>
wxTextBlob::wxTextBlob()
: m_TextExtentContext{wxGraphicsContext::Create()}
, m_GlyphAdvanceX {0}
, m_LineHeight {0}
, m_TextParts {} {
}
wxString wxTextBlob::wxFontToFCDesc(const wxFont * pFont) {
wxString desc(pFont->GetFaceName());
desc << ":size=" << pFont->GetPointSize();
switch (pFont->GetStyle()) {
case wxFONTSTYLE_ITALIC:
case wxFONTSTYLE_SLANT:
desc << ":slant=italic";
break;
default:
break;
}
switch(pFont->GetWeight()){
case wxFONTWEIGHT_BOLD:
desc << ":weight=200";
break;
case wxFONTWEIGHT_LIGHT:
desc << ":weight=50";
break;
default:
break;
}
return desc;
}
wxPoint wxTextBlob::AddText(const wxString & text,
const wxPoint pt,
const wxFont * pFont,
wxColour fore_color,
wxColour back_color) {
(void)text;
(void)pt;
(void)pFont;
(void)fore_color;
(void)back_color;
m_TextExtentContext->SetFont(*pFont, fore_color);
std::cout << "font:" << pFont->GetNativeFontInfoUserDesc() << "," << pFont->GetPointSize() << "," << pFont->GetPixelSize().y << pFont->GetWeight()
<< wxFontToFCDesc(pFont) << std::endl;
wxStringTokenizer tokenizer(text, "\n", wxTOKEN_RET_EMPTY_ALL);
wxPoint tmpPt{pt}, lastPt;
bool empty_token = false;
do {
auto token = tokenizer.HasMoreTokens() ? tokenizer.GetNextToken() : text;
empty_token = token.IsEmpty();
wxDouble width = 0.0, height = 0.0, leading = 0.0;
m_TextExtentContext->GetTextExtent(empty_token ? " " : token,
&width,
&height,
nullptr,
&leading);
if (empty_token) width = 0;
m_TextParts.push_back(
{token, tmpPt, pFont,
fore_color, back_color,
{(int)width, (int)std::max(height + leading, (wxDouble)m_LineHeight)}
});
lastPt = tmpPt;
lastPt.x += width;
tmpPt.x = pt.x;
tmpPt.y += std::max(height + leading, (wxDouble)m_LineHeight);
} while(tokenizer.HasMoreTokens());
return empty_token ? tmpPt : lastPt;
}
void wxTextBlob::Render(wxGraphicsContext * context) {
(void)context;
context->PushState();
for(auto it = m_TextParts.begin(),
it_end = m_TextParts.end();
it != it_end;
it++) {
context->SetFont(*it->pFont, it->fore);
if (it->back != wxNullColour) {
context->DrawText(it->text, it->pt.x, it->pt.y, context->CreateBrush(wxBrush(it->back)));
} else {
context->DrawText(it->text, it->pt.x, it->pt.y);
}
}
context->PopState();
}
<commit_msg>remove debug print<commit_after>#include "text_blob.h"
#include "wx/dcgraph.h"
#include "wx/graphics.h"
#include "wx/tokenzr.h"
#include <iostream>
#include <algorithm>
wxTextBlob::wxTextBlob()
: m_TextExtentContext{wxGraphicsContext::Create()}
, m_GlyphAdvanceX {0}
, m_LineHeight {0}
, m_TextParts {} {
}
wxString wxTextBlob::wxFontToFCDesc(const wxFont * pFont) {
wxString desc(pFont->GetFaceName());
desc << ":size=" << pFont->GetPointSize();
switch (pFont->GetStyle()) {
case wxFONTSTYLE_ITALIC:
case wxFONTSTYLE_SLANT:
desc << ":slant=italic";
break;
default:
break;
}
switch(pFont->GetWeight()){
case wxFONTWEIGHT_BOLD:
desc << ":weight=200";
break;
case wxFONTWEIGHT_LIGHT:
desc << ":weight=50";
break;
default:
break;
}
return desc;
}
wxPoint wxTextBlob::AddText(const wxString & text,
const wxPoint pt,
const wxFont * pFont,
wxColour fore_color,
wxColour back_color) {
(void)text;
(void)pt;
(void)pFont;
(void)fore_color;
(void)back_color;
m_TextExtentContext->SetFont(*pFont, fore_color);
wxStringTokenizer tokenizer(text, "\n", wxTOKEN_RET_EMPTY_ALL);
wxPoint tmpPt{pt}, lastPt;
bool empty_token = false;
do {
auto token = tokenizer.HasMoreTokens() ? tokenizer.GetNextToken() : text;
empty_token = token.IsEmpty();
wxDouble width = 0.0, height = 0.0, leading = 0.0;
m_TextExtentContext->GetTextExtent(empty_token ? " " : token,
&width,
&height,
nullptr,
&leading);
if (empty_token) width = 0;
m_TextParts.push_back(
{token, tmpPt, pFont,
fore_color, back_color,
{(int)width, (int)std::max(height + leading, (wxDouble)m_LineHeight)}
});
lastPt = tmpPt;
lastPt.x += width;
tmpPt.x = pt.x;
tmpPt.y += std::max(height + leading, (wxDouble)m_LineHeight);
} while(tokenizer.HasMoreTokens());
return empty_token ? tmpPt : lastPt;
}
void wxTextBlob::Render(wxGraphicsContext * context) {
(void)context;
context->PushState();
for(auto it = m_TextParts.begin(),
it_end = m_TextParts.end();
it != it_end;
it++) {
context->SetFont(*it->pFont, it->fore);
if (it->back != wxNullColour) {
context->DrawText(it->text, it->pt.x, it->pt.y, context->CreateBrush(wxBrush(it->back)));
} else {
context->DrawText(it->text, it->pt.x, it->pt.y);
}
}
context->PopState();
}
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "GoToDialog.h"
#include "MarbleWidget.h"
#include "MarbleModel.h"
#include "MarbleRunnerManager.h"
#include "MarblePlacemarkModel.h"
#include "GeoDataTreeModel.h"
#include "GeoDataDocument.h"
#include "GeoDataFolder.h"
#include "PositionTracking.h"
#include "BookmarkManager.h"
#include "routing/RoutingManager.h"
#include "routing/RouteRequest.h"
#include <QtCore/QAbstractListModel>
#include <QtCore/QTimer>
#include <QtGui/QPushButton>
#include <QtGui/QPainter>
namespace Marble
{
namespace
{
int const GeoDataLookAtRole = Qt::UserRole + 1;
}
class TargetModel : public QAbstractListModel
{
public:
TargetModel( MarbleWidget* marbleWidget, QObject * parent = 0 );
virtual int rowCount ( const QModelIndex & parent = QModelIndex() ) const;
virtual QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const;
void setShowRoutingItems( bool show );
private:
QVariant currentLocationData ( int role ) const;
QVariant routeData ( const QVector<GeoDataPlacemark> &via, int index, int role ) const;
QVariant homeData ( int role ) const;
QVariant bookmarkData ( int index, int role ) const;
QVector<GeoDataPlacemark> viaPoints() const;
MarbleWidget* m_marbleWidget;
QVector<GeoDataPlacemark*> m_bookmarks;
bool m_hasCurrentLocation;
bool m_showRoutingItems;
};
class GoToDialogPrivate
{
public:
GoToDialog* m_parent;
MarbleWidget* m_marbleWidget;
GeoDataLookAt m_lookAt;
TargetModel* m_targetModel;
MarbleRunnerManager* m_runnerManager;
GeoDataDocument *m_document;
GeoDataTreeModel m_placemarkModel;
QTimer m_progressTimer;
int m_currentFrame;
QVector<QIcon> m_progressAnimation;
GoToDialogPrivate( GoToDialog* parent, MarbleWidget* marbleWidget );
void saveSelection( const QModelIndex &index );
void createProgressAnimation();
};
TargetModel::TargetModel( MarbleWidget* marbleWidget, QObject * parent ) :
QAbstractListModel( parent ),
m_marbleWidget( marbleWidget ), m_hasCurrentLocation( false ),
m_showRoutingItems( true )
{
BookmarkManager* manager = marbleWidget->model()->bookmarkManager();
foreach( GeoDataFolder * folder, manager->folders() ) {
QVector<GeoDataPlacemark*> bookmarks = folder->placemarkList();
QVector<GeoDataPlacemark*>::const_iterator iter = bookmarks.constBegin();
QVector<GeoDataPlacemark*>::const_iterator end = bookmarks.constEnd();
for ( ; iter != end; ++iter ) {
m_bookmarks.push_back( *iter );
}
}
PositionTracking* tracking = m_marbleWidget->model()->positionTracking();
m_hasCurrentLocation = tracking && tracking->status() == PositionProviderStatusAvailable;
}
QVector<GeoDataPlacemark> TargetModel::viaPoints() const
{
if ( !m_showRoutingItems ) {
return QVector<GeoDataPlacemark>();
}
RouteRequest* request = m_marbleWidget->model()->routingManager()->routeRequest();
QVector<GeoDataPlacemark> result;
for ( int i = 0; i < request->size(); ++i ) {
if ( request->at( i ).longitude() != 0.0 || request->at( i ).latitude() != 0.0 ) {
GeoDataPlacemark placemark;
placemark.setCoordinate( request->at( i ) );
placemark.setName( request->name( i ) );
result.push_back( placemark );
}
}
return result;
}
int TargetModel::rowCount ( const QModelIndex & parent ) const
{
int result = 0;
if ( !parent.isValid() ) {
result += m_hasCurrentLocation ? 1 : 0;
result += viaPoints().size(); // route
result += 1; // home location
result += m_bookmarks.size(); // bookmarks
return result;
}
return result;
}
QVariant TargetModel::currentLocationData ( int role ) const
{
PositionTracking* tracking = m_marbleWidget->model()->positionTracking();
if ( tracking && tracking->status() == PositionProviderStatusAvailable ) {
GeoDataCoordinates currentLocation = tracking->currentLocation();
switch( role ) {
case Qt::DisplayRole: return tr( "Current Location: %1" ).arg( currentLocation.toString() ) ;
case Qt::DecorationRole: return QIcon( ":/icons/gps.png" );
case GeoDataLookAtRole: {
GeoDataLookAt result;
result.setCoordinates( currentLocation );
// By happy coincidence this equals OpenStreetMap tile level 15
result.setRange( 851.807 );
return qVariantFromValue( result );
}
}
}
return QVariant();
}
QVariant TargetModel::routeData ( const QVector<GeoDataPlacemark> &via, int index, int role ) const
{
RouteRequest* request = m_marbleWidget->model()->routingManager()->routeRequest();
switch( role ) {
case Qt::DisplayRole: return via.at( index ).name();
case Qt::DecorationRole: return QIcon( request->pixmap( index ) );
case GeoDataLookAtRole: {
GeoDataLookAt result;
result.setCoordinates( via.at( index ).coordinate() );
// By happy coincidence this equals OpenStreetMap tile level 16
result.setRange( 425.903 );
return qVariantFromValue( result );
}
}
return QVariant();
}
QVariant TargetModel::homeData ( int role ) const
{
switch( role ) {
case Qt::DisplayRole: return tr( "Home" );
case Qt::DecorationRole: return QIcon( ":/icons/go-home.png" );
case GeoDataLookAtRole: {
qreal lon( 0.0 ), lat( 0.0 );
int zoom( 0 );
m_marbleWidget->model()->home( lon, lat, zoom );
GeoDataLookAt result;
result.setLongitude( lon, GeoDataCoordinates::Degree );
result.setLatitude( lat, GeoDataCoordinates::Degree );
result.setRange( m_marbleWidget->distanceFromZoom( zoom ) * KM2METER );
return qVariantFromValue( result );
}
}
return QVariant();
}
QVariant TargetModel::bookmarkData ( int index, int role ) const
{
switch( role ) {
case Qt::DisplayRole: {
GeoDataFolder* folder = dynamic_cast<GeoDataFolder*>( m_bookmarks[index]->parent() );
Q_ASSERT( folder && "Internal bookmark representation has changed. Please report this as a bug at http://bugs.kde.org." );
if ( folder ) {
return QString(folder->name() + QLatin1String(" / ") + m_bookmarks[index]->name());
}
}
case Qt::DecorationRole: return QIcon( ":/icons/bookmarks.png" );
case GeoDataLookAtRole: return qVariantFromValue( *m_bookmarks[index]->lookAt() );
}
return QVariant();
}
QVariant TargetModel::data ( const QModelIndex & index, int role ) const
{
if ( index.isValid() && index.row() >= 0 && index.row() < rowCount() ) {
int row = index.row();
bool const isCurrentLocation = row == 0 && m_hasCurrentLocation;
int homeOffset = m_hasCurrentLocation ? 1 : 0;
QVector<GeoDataPlacemark> via = viaPoints();
bool const isRoute = row >= homeOffset && row < homeOffset + via.size();
if ( isCurrentLocation ) {
return currentLocationData( role );
} else if ( isRoute ) {
int routeIndex = row - homeOffset;
Q_ASSERT( routeIndex >= 0 && routeIndex < via.size() );
return routeData( via, routeIndex, role );
} else {
int bookmarkIndex = row - homeOffset - via.size();
if ( bookmarkIndex == 0 ) {
return homeData( role );
} else {
--bookmarkIndex;
Q_ASSERT( bookmarkIndex >= 0 && bookmarkIndex < m_bookmarks.size() );
return bookmarkData( bookmarkIndex, role );
}
}
}
return QVariant();
}
void TargetModel::setShowRoutingItems( bool show )
{
m_showRoutingItems = show;
reset();
}
void GoToDialogPrivate::createProgressAnimation()
{
bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
int const iconSize = smallScreen ? 32 : 16;
// Size parameters
qreal const h = iconSize / 2.0; // Half of the icon size
qreal const q = h / 2.0; // Quarter of the icon size
qreal const d = 7.5; // Circle diameter
qreal const r = d / 2.0; // Circle radius
// Canvas parameters
QImage canvas( iconSize, iconSize, QImage::Format_ARGB32 );
QPainter painter( &canvas );
painter.setRenderHint( QPainter::Antialiasing, true );
painter.setPen( QColor ( Qt::gray ) );
painter.setBrush( QColor( Qt::white ) );
// Create all frames
for( double t = 0.0; t < 2 * M_PI; t += M_PI / 8.0 ) {
canvas.fill( Qt::transparent );
QRectF firstCircle( h - r + q * cos( t ), h - r + q * sin( t ), d, d );
QRectF secondCircle( h - r + q * cos( t + M_PI ), h - r + q * sin( t + M_PI ), d, d );
painter.drawEllipse( firstCircle );
painter.drawEllipse( secondCircle );
m_progressAnimation.push_back( QIcon( QPixmap::fromImage( canvas ) ) );
}
}
GoToDialogPrivate::GoToDialogPrivate( GoToDialog* parent, MarbleWidget* marbleWidget ) :
m_parent( parent), m_marbleWidget( marbleWidget ), m_targetModel( 0 ),
m_runnerManager( 0 ), m_document( new GeoDataDocument ), m_currentFrame( 0 )
{
m_progressTimer.setInterval( 100 );
}
void GoToDialogPrivate::saveSelection( const QModelIndex &index )
{
if ( m_parent->searchButton->isChecked() && m_document->size() ) {
QVariant coordinates = m_placemarkModel.data( index, MarblePlacemarkModel::CoordinateRole );
m_lookAt = GeoDataLookAt();
m_lookAt.setCoordinates( qVariantValue<GeoDataCoordinates>( coordinates ) );
// By happy coincidence this equals OpenStreetMap tile level 16
m_lookAt.setRange( 425.903 );
} else {
QVariant data = index.data( GeoDataLookAtRole );
m_lookAt = qVariantValue<GeoDataLookAt>( data );
}
m_parent->accept();
}
void GoToDialog::startSearch()
{
QString const searchTerm = searchLineEdit->text().trimmed();
if ( searchTerm.isEmpty() ) {
return;
}
if ( !d->m_runnerManager ) {
d->m_runnerManager = new MarbleRunnerManager( d->m_marbleWidget->model()->pluginManager(), this );
d->m_runnerManager->setModel( d->m_marbleWidget->model() );
connect( d->m_runnerManager, SIGNAL( searchResultChanged( QVector<GeoDataPlacemark*> ) ),
this, SLOT( updateSearchResult( QVector<GeoDataPlacemark*> ) ) );
connect( d->m_runnerManager, SIGNAL( searchFinished( QString ) ),
this, SLOT( stopProgressAnimation() ) );
}
d->m_runnerManager->findPlacemarks( searchTerm );
if ( d->m_progressAnimation.isEmpty() ) {
d->createProgressAnimation();
}
d->m_progressTimer.start();
progressButton->setVisible( true );
searchLineEdit->setEnabled( false );
updateResultMessage( 0 );
}
void GoToDialog::updateSearchResult( QVector<GeoDataPlacemark*> placemarks )
{
d->m_placemarkModel.setRootDocument( 0 );
d->m_document->clear();
foreach (GeoDataPlacemark *placemark, placemarks) {
d->m_document->append( new GeoDataPlacemark( *placemark ) );
}
d->m_placemarkModel.setRootDocument( d->m_document );
bookmarkListView->setModel( &d->m_placemarkModel );
updateResultMessage( d->m_placemarkModel.rowCount() );
}
GoToDialog::GoToDialog( MarbleWidget* marbleWidget, QWidget * parent, Qt::WindowFlags flags ) :
QDialog( parent, flags ), d( new GoToDialogPrivate( this, marbleWidget ) )
{
#ifdef Q_WS_MAEMO_5
setAttribute( Qt::WA_Maemo5StackedWindow );
setWindowFlags( Qt::Window );
#endif // Q_WS_MAEMO_5
setupUi( this );
#if QT_VERSION >= 0x40700
searchLineEdit->setPlaceholderText( tr( "Address or search term" ) );
#endif
d->m_targetModel = new TargetModel( marbleWidget, this );
d->m_placemarkModel.setRootDocument( d->m_document );
bookmarkListView->setModel( d->m_targetModel );
connect( bookmarkListView, SIGNAL( activated( QModelIndex ) ),
this, SLOT( saveSelection ( QModelIndex ) ) );
connect( searchLineEdit, SIGNAL( returnPressed() ),
this, SLOT( startSearch() ) );
buttonBox->button( QDialogButtonBox::Close )->setAutoDefault( false );
connect( searchButton, SIGNAL( clicked( bool ) ),
this, SLOT( updateSearchMode() ) );
connect( browseButton, SIGNAL( clicked( bool ) ),
this, SLOT( updateSearchMode() ) );
connect( &d->m_progressTimer, SIGNAL( timeout() ),
this, SLOT( updateProgress() ) );
connect( progressButton, SIGNAL( clicked( bool ) ),
this, SLOT( stopProgressAnimation() ) );
updateSearchMode();
progressButton->setVisible( false );
}
GoToDialog::~GoToDialog()
{
delete d;
}
GeoDataLookAt GoToDialog::lookAt() const
{
return d->m_lookAt;
}
void GoToDialog::setShowRoutingItems( bool show )
{
d->m_targetModel->setShowRoutingItems( show );
}
void GoToDialog::setSearchEnabled( bool enabled )
{
browseButton->setVisible( enabled );
searchButton->setVisible( enabled );
if ( !enabled ) {
searchButton->setChecked( false );
updateSearchMode();
}
}
void GoToDialog::updateSearchMode()
{
bool const searchEnabled = searchButton->isChecked();
searchLineEdit->setVisible( searchEnabled );
descriptionLabel->setVisible( searchEnabled );
progressButton->setVisible( searchEnabled && d->m_progressTimer.isActive() );
if ( searchEnabled ) {
bookmarkListView->setModel( &d->m_placemarkModel );
} else {
bookmarkListView->setModel( d->m_targetModel );
}
}
void GoToDialog::updateProgress()
{
if ( !d->m_progressAnimation.isEmpty() ) {
d->m_currentFrame = ( d->m_currentFrame + 1 ) % d->m_progressAnimation.size();
QIcon frame = d->m_progressAnimation[d->m_currentFrame];
progressButton->setIcon( frame );
}
}
void GoToDialog::stopProgressAnimation()
{
searchLineEdit->setEnabled( true );
d->m_progressTimer.stop();
updateResultMessage( bookmarkListView->model()->rowCount() );
progressButton->setVisible( false );
}
void GoToDialog::updateResultMessage( int results )
{
descriptionLabel->setText( tr( "%n results found.", "Number of search results", results ) );
}
}
#include "GoToDialog.moc"
<commit_msg>GoToDialog: more precise member names<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org>
// Copyright 2011 Bernhard Beschow <bbeschow@cs.tu-berlin.de>
//
#include "GoToDialog.h"
#include "MarbleWidget.h"
#include "MarbleModel.h"
#include "MarbleRunnerManager.h"
#include "MarblePlacemarkModel.h"
#include "GeoDataTreeModel.h"
#include "GeoDataDocument.h"
#include "GeoDataFolder.h"
#include "PositionTracking.h"
#include "BookmarkManager.h"
#include "routing/RoutingManager.h"
#include "routing/RouteRequest.h"
#include <QtCore/QAbstractListModel>
#include <QtCore/QTimer>
#include <QtGui/QPushButton>
#include <QtGui/QPainter>
namespace Marble
{
namespace
{
int const GeoDataLookAtRole = Qt::UserRole + 1;
}
class TargetModel : public QAbstractListModel
{
public:
TargetModel( MarbleWidget* marbleWidget, QObject * parent = 0 );
virtual int rowCount ( const QModelIndex & parent = QModelIndex() ) const;
virtual QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const;
void setShowRoutingItems( bool show );
private:
QVariant currentLocationData ( int role ) const;
QVariant routeData ( const QVector<GeoDataPlacemark> &via, int index, int role ) const;
QVariant homeData ( int role ) const;
QVariant bookmarkData ( int index, int role ) const;
QVector<GeoDataPlacemark> viaPoints() const;
MarbleWidget* m_marbleWidget;
QVector<GeoDataPlacemark*> m_bookmarks;
bool m_hasCurrentLocation;
bool m_showRoutingItems;
};
class GoToDialogPrivate
{
public:
GoToDialog* m_parent;
MarbleWidget* m_marbleWidget;
GeoDataLookAt m_lookAt;
TargetModel m_targetModel;
MarbleRunnerManager* m_runnerManager;
GeoDataDocument *m_searchResult;
GeoDataTreeModel m_searchResultModel;
QTimer m_progressTimer;
int m_currentFrame;
QVector<QIcon> m_progressAnimation;
GoToDialogPrivate( GoToDialog* parent, MarbleWidget* marbleWidget );
void saveSelection( const QModelIndex &index );
void createProgressAnimation();
};
TargetModel::TargetModel( MarbleWidget* marbleWidget, QObject * parent ) :
QAbstractListModel( parent ),
m_marbleWidget( marbleWidget ), m_hasCurrentLocation( false ),
m_showRoutingItems( true )
{
BookmarkManager* manager = marbleWidget->model()->bookmarkManager();
foreach( GeoDataFolder * folder, manager->folders() ) {
QVector<GeoDataPlacemark*> bookmarks = folder->placemarkList();
QVector<GeoDataPlacemark*>::const_iterator iter = bookmarks.constBegin();
QVector<GeoDataPlacemark*>::const_iterator end = bookmarks.constEnd();
for ( ; iter != end; ++iter ) {
m_bookmarks.push_back( *iter );
}
}
PositionTracking* tracking = m_marbleWidget->model()->positionTracking();
m_hasCurrentLocation = tracking && tracking->status() == PositionProviderStatusAvailable;
}
QVector<GeoDataPlacemark> TargetModel::viaPoints() const
{
if ( !m_showRoutingItems ) {
return QVector<GeoDataPlacemark>();
}
RouteRequest* request = m_marbleWidget->model()->routingManager()->routeRequest();
QVector<GeoDataPlacemark> result;
for ( int i = 0; i < request->size(); ++i ) {
if ( request->at( i ).longitude() != 0.0 || request->at( i ).latitude() != 0.0 ) {
GeoDataPlacemark placemark;
placemark.setCoordinate( request->at( i ) );
placemark.setName( request->name( i ) );
result.push_back( placemark );
}
}
return result;
}
int TargetModel::rowCount ( const QModelIndex & parent ) const
{
int result = 0;
if ( !parent.isValid() ) {
result += m_hasCurrentLocation ? 1 : 0;
result += viaPoints().size(); // route
result += 1; // home location
result += m_bookmarks.size(); // bookmarks
return result;
}
return result;
}
QVariant TargetModel::currentLocationData ( int role ) const
{
PositionTracking* tracking = m_marbleWidget->model()->positionTracking();
if ( tracking && tracking->status() == PositionProviderStatusAvailable ) {
GeoDataCoordinates currentLocation = tracking->currentLocation();
switch( role ) {
case Qt::DisplayRole: return tr( "Current Location: %1" ).arg( currentLocation.toString() ) ;
case Qt::DecorationRole: return QIcon( ":/icons/gps.png" );
case GeoDataLookAtRole: {
GeoDataLookAt result;
result.setCoordinates( currentLocation );
// By happy coincidence this equals OpenStreetMap tile level 15
result.setRange( 851.807 );
return qVariantFromValue( result );
}
}
}
return QVariant();
}
QVariant TargetModel::routeData ( const QVector<GeoDataPlacemark> &via, int index, int role ) const
{
RouteRequest* request = m_marbleWidget->model()->routingManager()->routeRequest();
switch( role ) {
case Qt::DisplayRole: return via.at( index ).name();
case Qt::DecorationRole: return QIcon( request->pixmap( index ) );
case GeoDataLookAtRole: {
GeoDataLookAt result;
result.setCoordinates( via.at( index ).coordinate() );
// By happy coincidence this equals OpenStreetMap tile level 16
result.setRange( 425.903 );
return qVariantFromValue( result );
}
}
return QVariant();
}
QVariant TargetModel::homeData ( int role ) const
{
switch( role ) {
case Qt::DisplayRole: return tr( "Home" );
case Qt::DecorationRole: return QIcon( ":/icons/go-home.png" );
case GeoDataLookAtRole: {
qreal lon( 0.0 ), lat( 0.0 );
int zoom( 0 );
m_marbleWidget->model()->home( lon, lat, zoom );
GeoDataLookAt result;
result.setLongitude( lon, GeoDataCoordinates::Degree );
result.setLatitude( lat, GeoDataCoordinates::Degree );
result.setRange( m_marbleWidget->distanceFromZoom( zoom ) * KM2METER );
return qVariantFromValue( result );
}
}
return QVariant();
}
QVariant TargetModel::bookmarkData ( int index, int role ) const
{
switch( role ) {
case Qt::DisplayRole: {
GeoDataFolder* folder = dynamic_cast<GeoDataFolder*>( m_bookmarks[index]->parent() );
Q_ASSERT( folder && "Internal bookmark representation has changed. Please report this as a bug at http://bugs.kde.org." );
if ( folder ) {
return QString(folder->name() + QLatin1String(" / ") + m_bookmarks[index]->name());
}
}
case Qt::DecorationRole: return QIcon( ":/icons/bookmarks.png" );
case GeoDataLookAtRole: return qVariantFromValue( *m_bookmarks[index]->lookAt() );
}
return QVariant();
}
QVariant TargetModel::data ( const QModelIndex & index, int role ) const
{
if ( index.isValid() && index.row() >= 0 && index.row() < rowCount() ) {
int row = index.row();
bool const isCurrentLocation = row == 0 && m_hasCurrentLocation;
int homeOffset = m_hasCurrentLocation ? 1 : 0;
QVector<GeoDataPlacemark> via = viaPoints();
bool const isRoute = row >= homeOffset && row < homeOffset + via.size();
if ( isCurrentLocation ) {
return currentLocationData( role );
} else if ( isRoute ) {
int routeIndex = row - homeOffset;
Q_ASSERT( routeIndex >= 0 && routeIndex < via.size() );
return routeData( via, routeIndex, role );
} else {
int bookmarkIndex = row - homeOffset - via.size();
if ( bookmarkIndex == 0 ) {
return homeData( role );
} else {
--bookmarkIndex;
Q_ASSERT( bookmarkIndex >= 0 && bookmarkIndex < m_bookmarks.size() );
return bookmarkData( bookmarkIndex, role );
}
}
}
return QVariant();
}
void TargetModel::setShowRoutingItems( bool show )
{
m_showRoutingItems = show;
reset();
}
void GoToDialogPrivate::createProgressAnimation()
{
bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
int const iconSize = smallScreen ? 32 : 16;
// Size parameters
qreal const h = iconSize / 2.0; // Half of the icon size
qreal const q = h / 2.0; // Quarter of the icon size
qreal const d = 7.5; // Circle diameter
qreal const r = d / 2.0; // Circle radius
// Canvas parameters
QImage canvas( iconSize, iconSize, QImage::Format_ARGB32 );
QPainter painter( &canvas );
painter.setRenderHint( QPainter::Antialiasing, true );
painter.setPen( QColor ( Qt::gray ) );
painter.setBrush( QColor( Qt::white ) );
// Create all frames
for( double t = 0.0; t < 2 * M_PI; t += M_PI / 8.0 ) {
canvas.fill( Qt::transparent );
QRectF firstCircle( h - r + q * cos( t ), h - r + q * sin( t ), d, d );
QRectF secondCircle( h - r + q * cos( t + M_PI ), h - r + q * sin( t + M_PI ), d, d );
painter.drawEllipse( firstCircle );
painter.drawEllipse( secondCircle );
m_progressAnimation.push_back( QIcon( QPixmap::fromImage( canvas ) ) );
}
}
GoToDialogPrivate::GoToDialogPrivate( GoToDialog* parent, MarbleWidget* marbleWidget ) :
m_parent( parent), m_marbleWidget( marbleWidget ), m_targetModel( marbleWidget ),
m_runnerManager( 0 ), m_searchResult( new GeoDataDocument ), m_currentFrame( 0 )
{
m_progressTimer.setInterval( 100 );
}
void GoToDialogPrivate::saveSelection( const QModelIndex &index )
{
if ( m_parent->searchButton->isChecked() && m_searchResult->size() ) {
QVariant coordinates = m_searchResultModel.data( index, MarblePlacemarkModel::CoordinateRole );
m_lookAt = GeoDataLookAt();
m_lookAt.setCoordinates( qVariantValue<GeoDataCoordinates>( coordinates ) );
// By happy coincidence this equals OpenStreetMap tile level 16
m_lookAt.setRange( 425.903 );
} else {
QVariant data = index.data( GeoDataLookAtRole );
m_lookAt = qVariantValue<GeoDataLookAt>( data );
}
m_parent->accept();
}
void GoToDialog::startSearch()
{
QString const searchTerm = searchLineEdit->text().trimmed();
if ( searchTerm.isEmpty() ) {
return;
}
if ( !d->m_runnerManager ) {
d->m_runnerManager = new MarbleRunnerManager( d->m_marbleWidget->model()->pluginManager(), this );
d->m_runnerManager->setModel( d->m_marbleWidget->model() );
connect( d->m_runnerManager, SIGNAL( searchResultChanged( QVector<GeoDataPlacemark*> ) ),
this, SLOT( updateSearchResult( QVector<GeoDataPlacemark*> ) ) );
connect( d->m_runnerManager, SIGNAL( searchFinished( QString ) ),
this, SLOT( stopProgressAnimation() ) );
}
d->m_runnerManager->findPlacemarks( searchTerm );
if ( d->m_progressAnimation.isEmpty() ) {
d->createProgressAnimation();
}
d->m_progressTimer.start();
progressButton->setVisible( true );
searchLineEdit->setEnabled( false );
updateResultMessage( 0 );
}
void GoToDialog::updateSearchResult( QVector<GeoDataPlacemark*> placemarks )
{
d->m_searchResultModel.setRootDocument( 0 );
d->m_searchResult->clear();
foreach (GeoDataPlacemark *placemark, placemarks) {
d->m_searchResult->append( new GeoDataPlacemark( *placemark ) );
}
d->m_searchResultModel.setRootDocument( d->m_searchResult );
bookmarkListView->setModel( &d->m_searchResultModel );
updateResultMessage( d->m_searchResultModel.rowCount() );
}
GoToDialog::GoToDialog( MarbleWidget* marbleWidget, QWidget * parent, Qt::WindowFlags flags ) :
QDialog( parent, flags ), d( new GoToDialogPrivate( this, marbleWidget ) )
{
#ifdef Q_WS_MAEMO_5
setAttribute( Qt::WA_Maemo5StackedWindow );
setWindowFlags( Qt::Window );
#endif // Q_WS_MAEMO_5
setupUi( this );
#if QT_VERSION >= 0x40700
searchLineEdit->setPlaceholderText( tr( "Address or search term" ) );
#endif
d->m_searchResultModel.setRootDocument( d->m_searchResult );
bookmarkListView->setModel( &d->m_targetModel );
connect( bookmarkListView, SIGNAL( activated( QModelIndex ) ),
this, SLOT( saveSelection ( QModelIndex ) ) );
connect( searchLineEdit, SIGNAL( returnPressed() ),
this, SLOT( startSearch() ) );
buttonBox->button( QDialogButtonBox::Close )->setAutoDefault( false );
connect( searchButton, SIGNAL( clicked( bool ) ),
this, SLOT( updateSearchMode() ) );
connect( browseButton, SIGNAL( clicked( bool ) ),
this, SLOT( updateSearchMode() ) );
connect( &d->m_progressTimer, SIGNAL( timeout() ),
this, SLOT( updateProgress() ) );
connect( progressButton, SIGNAL( clicked( bool ) ),
this, SLOT( stopProgressAnimation() ) );
updateSearchMode();
progressButton->setVisible( false );
}
GoToDialog::~GoToDialog()
{
delete d;
}
GeoDataLookAt GoToDialog::lookAt() const
{
return d->m_lookAt;
}
void GoToDialog::setShowRoutingItems( bool show )
{
d->m_targetModel.setShowRoutingItems( show );
}
void GoToDialog::setSearchEnabled( bool enabled )
{
browseButton->setVisible( enabled );
searchButton->setVisible( enabled );
if ( !enabled ) {
searchButton->setChecked( false );
updateSearchMode();
}
}
void GoToDialog::updateSearchMode()
{
bool const searchEnabled = searchButton->isChecked();
searchLineEdit->setVisible( searchEnabled );
descriptionLabel->setVisible( searchEnabled );
progressButton->setVisible( searchEnabled && d->m_progressTimer.isActive() );
if ( searchEnabled ) {
bookmarkListView->setModel( &d->m_searchResultModel );
} else {
bookmarkListView->setModel( &d->m_targetModel );
}
}
void GoToDialog::updateProgress()
{
if ( !d->m_progressAnimation.isEmpty() ) {
d->m_currentFrame = ( d->m_currentFrame + 1 ) % d->m_progressAnimation.size();
QIcon frame = d->m_progressAnimation[d->m_currentFrame];
progressButton->setIcon( frame );
}
}
void GoToDialog::stopProgressAnimation()
{
searchLineEdit->setEnabled( true );
d->m_progressTimer.stop();
updateResultMessage( bookmarkListView->model()->rowCount() );
progressButton->setVisible( false );
}
void GoToDialog::updateResultMessage( int results )
{
descriptionLabel->setText( tr( "%n results found.", "Number of search results", results ) );
}
}
#include "GoToDialog.moc"
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libetonyek project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "IWORKTable.h"
#include <boost/numeric/conversion/cast.hpp>
#include <glm/glm.hpp>
#include "libetonyek_utils.h"
#include "IWORKDocumentInterface.h"
#include "IWORKProperties.h"
#include "IWORKStyle.h"
#include "IWORKTypes.h"
using boost::numeric_cast;
namespace libetonyek
{
namespace
{
void writeBorder(librevenge::RVNGPropertyList &props, const char *name, IWORKGridLine_t &line, std::size_t index)
{
if (!line.is_tree_valid())
line.build_tree();
IWORKStylePtr_t style;
line.search_tree(index, style);
if (style && style->has<property::SFTStrokeProperty>())
{
const IWORKStroke &stroke = style->get<property::SFTStrokeProperty>();
props.insert(name, makeBorder(stroke));
}
}
void writeCellFormat(librevenge::RVNGPropertyList &props, const IWORKStylePtr_t &style, const IWORKCellType type, const boost::optional<std::string> &value)
{
using namespace property;
switch (type)
{
case IWORK_CELL_TYPE_NUMBER :
if (style->has<SFTCellStylePropertyNumberFormat>() && value)
{
const IWORKNumberFormat &format = style->get<SFTCellStylePropertyNumberFormat>();
if (style->getIdent())
props.insert("librevenge:name", style->getIdent());
props.insert("librevenge:value", get(value).c_str());
switch (format.m_type)
{
case IWORK_CELL_NUMBER_TYPE_CURRENCY :
props.insert("librevenge:value-type", "currency");
props.insert("number:currency-style", format.m_currencyCode.c_str());
break;
case IWORK_CELL_NUMBER_TYPE_PERCENTAGE :
props.insert("librevenge:value-type", "percentage");
props.insert("number:decimal-places", format.m_decimalPlaces);
break;
case IWORK_CELL_NUMBER_TYPE_SCIENTIFIC :
props.insert("librevenge:value-type", "scientific");
props.insert("number:decimal-places", format.m_decimalPlaces);
break;
case IWORK_CELL_NUMBER_TYPE_DOUBLE :
props.insert("librevenge:value-type", "double");
props.insert("number:decimal-places", format.m_decimalPlaces);
break;
}
}
break;
case IWORK_CELL_TYPE_DATE_TIME :
if (style->has<SFTCellStylePropertyDateTimeFormat>() && value)
{
if (style->getIdent())
props.insert("librevenge:name", style->getIdent());
props.insert("librevenge:value-type", "date");
}
break;
case IWORK_CELL_TYPE_DURATION :
if (style->has<SFTCellStylePropertyDurationFormat>() && value)
{
// TODO: How to insert format and convert?
// const IWORKDurationFormat &format = style->get<SFTCellStylePropertyDurationFormat>();
// props.insert("librevenge:format",format.m_format.c_str());
props.insert("librevenge:value", get(value).c_str());
props.insert("librevenge:value-type", "time");
if (style->getIdent())
props.insert("librevenge:name", style->getIdent());
}
break;
case IWORK_CELL_TYPE_BOOL:
if (value)
{
props.insert("librevenge:value", get(value).c_str());
props.insert("librevenge:value-type", "bool");
}
break;
case IWORK_CELL_TYPE_TEXT :
default:
//TODO: librevenge:name ?
if (value)
props.insert("librevenge:value-type", "string");
break;
}
}
}
IWORKTable::Cell::Cell()
: m_content()
, m_columnSpan(1)
, m_rowSpan(1)
, m_covered(false)
, m_formula()
, m_style()
, m_type(IWORK_CELL_TYPE_TEXT)
, m_value()
{
}
IWORKTable::IWORKTable()
: m_table()
, m_columnSizes()
, m_rowSizes()
, m_verticalLines()
, m_horizontalLines()
, m_tableNameMap()
{
}
void IWORKTable::setSizes(const IWORKColumnSizes_t &columnSizes, const IWORKRowSizes_t &rowSizes)
{
m_columnSizes = columnSizes;
m_rowSizes = rowSizes;
// init. content table of appropriate dimensions
m_table = Table_t(m_rowSizes.size(), Row_t(m_columnSizes.size()));
}
void IWORKTable::setBorders(const IWORKGridLineList_t &verticalLines, const IWORKGridLineList_t &horizontalLines)
{
m_verticalLines = verticalLines;
m_horizontalLines = horizontalLines;
}
void IWORKTable::setTableNameMap(const IWORKTableNameMapPtr_t &tableNameMap)
{
m_tableNameMap = tableNameMap;
}
void IWORKTable::insertCell(const unsigned column, const unsigned row, const boost::optional<std::string> &value, const IWORKOutputElements &content, const unsigned columnSpan, const unsigned rowSpan, const boost::optional<IWORKFormula> &formula, const IWORKStylePtr_t &style, const IWORKCellType type)
{
if ((m_rowSizes.size() <= row) || (m_columnSizes.size() <= column))
return;
Cell cell;
cell.m_content = content;
cell.m_columnSpan = columnSpan;
cell.m_rowSpan = rowSpan;
cell.m_formula = formula;
cell.m_style = style;
cell.m_type = type;
cell.m_value = value;
m_table[row][column] = cell;
}
void IWORKTable::insertCoveredCell(const unsigned column, const unsigned row)
{
if ((m_rowSizes.size() <= row) || (m_columnSizes.size() <= column))
return;
Cell cell;
cell.m_covered = true;
m_table[row][column] = cell;
}
void IWORKTable::draw(const librevenge::RVNGPropertyList &tableProps, IWORKOutputElements &elements)
{
librevenge::RVNGPropertyListVector columnSizes;
for (IWORKColumnSizes_t::const_iterator it = m_columnSizes.begin(); m_columnSizes.end() != it; ++it)
{
librevenge::RVNGPropertyList column;
column.insert("style:column-width", pt2in(*it));
columnSizes.append(column);
}
librevenge::RVNGPropertyList allTableProps(tableProps);
allTableProps.insert("librevenge:table-columns", columnSizes);
elements.addOpenTable(allTableProps);
for (std::size_t r = 0; m_table.size() != r; ++r)
{
const Row_t &row = m_table[r];
librevenge::RVNGPropertyList rowProps;
rowProps.insert("style:row-height", pt2in(m_rowSizes[r]));
elements.addOpenTableRow(rowProps);
for (std::size_t c = 0; row.size() != c; ++c)
{
const Cell &cell = row[c];
librevenge::RVNGPropertyList cellProps;
cellProps.insert("librevenge:column", numeric_cast<int>(c));
cellProps.insert("librevenge:row", numeric_cast<int>(r));
cellProps.insert("fo:vertical-align", "middle");
if (r < m_horizontalLines.size())
writeBorder(cellProps, "fo:border-top", m_horizontalLines[r], c);
if (r+1 < m_horizontalLines.size())
writeBorder(cellProps, "fo:border-bottom", m_horizontalLines[r+1], c);
if (c < m_verticalLines.size())
writeBorder(cellProps, "fo:border-left", m_verticalLines[c], r);
if (c+1 < m_verticalLines.size())
writeBorder(cellProps, "fo:border-right", m_verticalLines[c+1], r);
if (cell.m_covered)
{
elements.addInsertCoveredTableCell(cellProps);
}
else
{
if (1 < cell.m_columnSpan)
cellProps.insert("table:number-columns-spanned", numeric_cast<int>(cell.m_columnSpan));
if (1 < cell.m_rowSpan)
cellProps.insert("table:number-rows-spanned", numeric_cast<int>(cell.m_rowSpan));
if (cell.m_style)
writeCellFormat(cellProps, cell.m_style, cell.m_type, cell.m_value);
if (cell.m_formula)
elements.addOpenFormulaCell(cellProps, cell.m_formula, m_tableNameMap);
else
elements.addOpenTableCell(cellProps);
if (!cell.m_content.empty())
elements.append(cell.m_content);
elements.addCloseTableCell();
}
}
elements.addCloseTableRow();
}
elements.addCloseTable();
}
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>output duration as standard time format<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libetonyek project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "IWORKTable.h"
#include <boost/numeric/conversion/cast.hpp>
#include <glm/glm.hpp>
#include "libetonyek_xml.h"
#include "libetonyek_utils.h"
#include "IWORKDocumentInterface.h"
#include "IWORKProperties.h"
#include "IWORKStyle.h"
#include "IWORKTypes.h"
using boost::numeric_cast;
namespace libetonyek
{
namespace
{
void writeBorder(librevenge::RVNGPropertyList &props, const char *name, IWORKGridLine_t &line, std::size_t index)
{
if (!line.is_tree_valid())
line.build_tree();
IWORKStylePtr_t style;
line.search_tree(index, style);
if (style && style->has<property::SFTStrokeProperty>())
{
const IWORKStroke &stroke = style->get<property::SFTStrokeProperty>();
props.insert(name, makeBorder(stroke));
}
}
void writeCellFormat(librevenge::RVNGPropertyList &props, const IWORKStylePtr_t &style, const IWORKCellType type, const boost::optional<std::string> &value)
{
using namespace property;
switch (type)
{
case IWORK_CELL_TYPE_NUMBER :
if (style->has<SFTCellStylePropertyNumberFormat>() && value)
{
const IWORKNumberFormat &format = style->get<SFTCellStylePropertyNumberFormat>();
if (style->getIdent())
props.insert("librevenge:name", style->getIdent());
props.insert("librevenge:value", get(value).c_str());
switch (format.m_type)
{
case IWORK_CELL_NUMBER_TYPE_CURRENCY :
props.insert("librevenge:value-type", "currency");
props.insert("number:currency-style", format.m_currencyCode.c_str());
break;
case IWORK_CELL_NUMBER_TYPE_PERCENTAGE :
props.insert("librevenge:value-type", "percentage");
props.insert("number:decimal-places", format.m_decimalPlaces);
break;
case IWORK_CELL_NUMBER_TYPE_SCIENTIFIC :
props.insert("librevenge:value-type", "scientific");
props.insert("number:decimal-places", format.m_decimalPlaces);
break;
case IWORK_CELL_NUMBER_TYPE_DOUBLE :
props.insert("librevenge:value-type", "double");
props.insert("number:decimal-places", format.m_decimalPlaces);
break;
}
}
break;
case IWORK_CELL_TYPE_DATE_TIME :
if (style->has<SFTCellStylePropertyDateTimeFormat>() && value)
{
if (style->getIdent())
props.insert("librevenge:name", style->getIdent());
props.insert("librevenge:value-type", "date");
}
break;
case IWORK_CELL_TYPE_DURATION :
if (style->has<SFTCellStylePropertyDurationFormat>() && value)
{
// TODO: How to insert format and convert?
// const IWORKDurationFormat &format = style->get<SFTCellStylePropertyDurationFormat>();
// props.insert("librevenge:format",format.m_format.c_str());
const int seconds = int_cast(get(value).c_str());
props.insert("librevenge:value-type", "time");
props.insert("librevenge:hours", seconds / 3600);
props.insert("librevenge:minutes", (seconds % 3600) / 60);
props.insert("librevenge:seconds", (seconds % 3600) % 60);
if (style->getIdent())
props.insert("librevenge:name", style->getIdent());
}
break;
case IWORK_CELL_TYPE_BOOL:
if (value)
{
props.insert("librevenge:value", get(value).c_str());
props.insert("librevenge:value-type", "bool");
}
break;
case IWORK_CELL_TYPE_TEXT :
default:
//TODO: librevenge:name ?
if (value)
props.insert("librevenge:value-type", "string");
break;
}
}
}
IWORKTable::Cell::Cell()
: m_content()
, m_columnSpan(1)
, m_rowSpan(1)
, m_covered(false)
, m_formula()
, m_style()
, m_type(IWORK_CELL_TYPE_TEXT)
, m_value()
{
}
IWORKTable::IWORKTable()
: m_table()
, m_columnSizes()
, m_rowSizes()
, m_verticalLines()
, m_horizontalLines()
, m_tableNameMap()
{
}
void IWORKTable::setSizes(const IWORKColumnSizes_t &columnSizes, const IWORKRowSizes_t &rowSizes)
{
m_columnSizes = columnSizes;
m_rowSizes = rowSizes;
// init. content table of appropriate dimensions
m_table = Table_t(m_rowSizes.size(), Row_t(m_columnSizes.size()));
}
void IWORKTable::setBorders(const IWORKGridLineList_t &verticalLines, const IWORKGridLineList_t &horizontalLines)
{
m_verticalLines = verticalLines;
m_horizontalLines = horizontalLines;
}
void IWORKTable::setTableNameMap(const IWORKTableNameMapPtr_t &tableNameMap)
{
m_tableNameMap = tableNameMap;
}
void IWORKTable::insertCell(const unsigned column, const unsigned row, const boost::optional<std::string> &value, const IWORKOutputElements &content, const unsigned columnSpan, const unsigned rowSpan, const boost::optional<IWORKFormula> &formula, const IWORKStylePtr_t &style, const IWORKCellType type)
{
if ((m_rowSizes.size() <= row) || (m_columnSizes.size() <= column))
return;
Cell cell;
cell.m_content = content;
cell.m_columnSpan = columnSpan;
cell.m_rowSpan = rowSpan;
cell.m_formula = formula;
cell.m_style = style;
cell.m_type = type;
cell.m_value = value;
m_table[row][column] = cell;
}
void IWORKTable::insertCoveredCell(const unsigned column, const unsigned row)
{
if ((m_rowSizes.size() <= row) || (m_columnSizes.size() <= column))
return;
Cell cell;
cell.m_covered = true;
m_table[row][column] = cell;
}
void IWORKTable::draw(const librevenge::RVNGPropertyList &tableProps, IWORKOutputElements &elements)
{
librevenge::RVNGPropertyListVector columnSizes;
for (IWORKColumnSizes_t::const_iterator it = m_columnSizes.begin(); m_columnSizes.end() != it; ++it)
{
librevenge::RVNGPropertyList column;
column.insert("style:column-width", pt2in(*it));
columnSizes.append(column);
}
librevenge::RVNGPropertyList allTableProps(tableProps);
allTableProps.insert("librevenge:table-columns", columnSizes);
elements.addOpenTable(allTableProps);
for (std::size_t r = 0; m_table.size() != r; ++r)
{
const Row_t &row = m_table[r];
librevenge::RVNGPropertyList rowProps;
rowProps.insert("style:row-height", pt2in(m_rowSizes[r]));
elements.addOpenTableRow(rowProps);
for (std::size_t c = 0; row.size() != c; ++c)
{
const Cell &cell = row[c];
librevenge::RVNGPropertyList cellProps;
cellProps.insert("librevenge:column", numeric_cast<int>(c));
cellProps.insert("librevenge:row", numeric_cast<int>(r));
cellProps.insert("fo:vertical-align", "middle");
if (r < m_horizontalLines.size())
writeBorder(cellProps, "fo:border-top", m_horizontalLines[r], c);
if (r+1 < m_horizontalLines.size())
writeBorder(cellProps, "fo:border-bottom", m_horizontalLines[r+1], c);
if (c < m_verticalLines.size())
writeBorder(cellProps, "fo:border-left", m_verticalLines[c], r);
if (c+1 < m_verticalLines.size())
writeBorder(cellProps, "fo:border-right", m_verticalLines[c+1], r);
if (cell.m_covered)
{
elements.addInsertCoveredTableCell(cellProps);
}
else
{
if (1 < cell.m_columnSpan)
cellProps.insert("table:number-columns-spanned", numeric_cast<int>(cell.m_columnSpan));
if (1 < cell.m_rowSpan)
cellProps.insert("table:number-rows-spanned", numeric_cast<int>(cell.m_rowSpan));
if (cell.m_style)
writeCellFormat(cellProps, cell.m_style, cell.m_type, cell.m_value);
if (cell.m_formula)
elements.addOpenFormulaCell(cellProps, cell.m_formula, m_tableNameMap);
else
elements.addOpenTableCell(cellProps);
if (!cell.m_content.empty())
elements.append(cell.m_content);
elements.addCloseTableCell();
}
}
elements.addCloseTableRow();
}
elements.addCloseTable();
}
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|>
|
<commit_before>// Copyright 2019 DeepMind Technologies Limited.
//
// 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 "reverb/cc/client.h"
#include <algorithm>
#include <memory>
#include "grpcpp/support/channel_arguments.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "reverb/cc/platform/grpc_utils.h"
#include "reverb/cc/platform/logging.h"
#include "reverb/cc/reverb_service.pb.h"
#include "reverb/cc/schema.pb.h"
#include "reverb/cc/support/grpc_util.h"
#include "reverb/cc/support/uint128.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/errors.h"
namespace deepmind {
namespace reverb {
namespace {
constexpr int kMaxMessageSize = 30 * 1000 * 1000;
grpc::ChannelArguments CreateChannelArguments() {
grpc::ChannelArguments arguments;
arguments.SetMaxReceiveMessageSize(kMaxMessageSize);
arguments.SetMaxSendMessageSize(kMaxMessageSize);
arguments.SetInt(GRPC_ARG_MAX_RECONNECT_BACKOFF_MS, 30 * 1000);
arguments.SetLoadBalancingPolicyName("round_robin");
return arguments;
}
} // namespace
Client::Client(std::shared_ptr</* grpc_gen:: */ReverbService::StubInterface> stub)
: stub_(std::move(stub)) {
REVERB_CHECK(stub_ != nullptr);
}
Client::Client(absl::string_view server_address)
: stub_(/* grpc_gen:: */ReverbService::NewStub(
CreateCustomGrpcChannel(server_address, MakeChannelCredentials(),
CreateChannelArguments()))) {}
tensorflow::Status Client::MaybeUpdateServerInfoCache(
absl::Duration timeout,
std::shared_ptr<internal::FlatSignatureMap>* cached_flat_signatures) {
// TODO(b/154927570): Once tables can be mutated on the server, we'll need to
// decide a new rule for updating the server info, instead of doing it just
// once at the beginning.
{
// Exit early if we have table info cached.
absl::ReaderMutexLock lock(&cached_table_mu_);
if (cached_flat_signatures_) {
*cached_flat_signatures = cached_flat_signatures_;
return tensorflow::Status::OK();
}
}
if (timeout == -absl::InfiniteDuration()) {
// If timeout is -infinity, the user asked for data to be returned
// immediately and without error; but we don't have anything already cached.
// Just act like everything is fine! (Return empty signatures).
*cached_flat_signatures = std::make_shared<internal::FlatSignatureMap>();
return tensorflow::Status::OK();
}
// This performs an RPC, so don't run it within a mutex.
// Note, this operation can run into a race condition where multiple
// threads of the same Client request server info, get different
// values, and one of these overwrites cached_table_info_ with a staler
// ServerInfo after another thread writes a newer version of ServerInfo
// Then future writers see stale signatures.
//
// In practice this isn't a real issue because:
// (1) This type of concurrency is not common: once ServerInfo
// is set, this code path isn't executed again.
// (2) ServerInfo doesn't change often on a reverb server.
// (3) Due to the default gRPC client load balancing mechanism,
// a client with a stub connection to one IP of a group of
// servers will always use the same IP address for all
// consecutive requests. So even concurrent requests will all
// go to the same server ("pick_first" policy):
//
// https://github.com/grpc/grpc/blob/631fe79f84af295c60aea5693350b45154827398/src/core/ext/filters/client_channel/client_channel.cc#L1661
struct ServerInfo info;
TF_RETURN_IF_ERROR(GetServerInfo(timeout, &info));
absl::MutexLock lock(&cached_table_mu_);
TF_RETURN_IF_ERROR(LockedUpdateServerInfoCache(info));
*cached_flat_signatures = cached_flat_signatures_;
return tensorflow::Status::OK();
}
tensorflow::Status Client::NewWriter(int chunk_length, int max_timesteps,
bool delta_encoded,
std::unique_ptr<Writer>* writer) {
// TODO(b/154928265): caching this request? For example, if
// it's been N seconds or minutes, it may be time to
// get an updated ServerInfo and see if there are new tables.
std::shared_ptr<internal::FlatSignatureMap> cached_flat_signatures;
// TODO(b/154927687): It is not ideal that this blocks forever. We should
// probably limit this and ignore the signature if it couldn't be found within
// some limits.
TF_RETURN_IF_ERROR(MaybeUpdateServerInfoCache(absl::InfiniteDuration(),
&cached_flat_signatures));
*writer = absl::make_unique<Writer>(stub_, chunk_length, max_timesteps,
delta_encoded,
std::move(cached_flat_signatures));
return tensorflow::Status::OK();
}
tensorflow::Status Client::MutatePriorities(
absl::string_view table, const std::vector<KeyWithPriority>& updates,
const std::vector<uint64_t>& deletes) {
grpc::ClientContext context;
context.set_wait_for_ready(true);
MutatePrioritiesRequest request;
request.set_table(table.data(), table.size());
for (const KeyWithPriority& item : updates) {
*request.add_updates() = item;
}
for (int64_t key : deletes) {
request.add_delete_keys(key);
}
MutatePrioritiesResponse response;
return FromGrpcStatus(stub_->MutatePriorities(&context, request, &response));
}
tensorflow::Status Client::NewSampler(
const std::string& table, const Sampler::Options& options,
internal::DtypesAndShapes dtypes_and_shapes,
std::unique_ptr<Sampler>* sampler) {
*sampler = absl::make_unique<Sampler>(stub_, table, options,
std::move(dtypes_and_shapes));
return tensorflow::Status::OK();
}
tensorflow::Status Client::NewSampler(const std::string& table,
const Sampler::Options& options,
absl::Duration validation_timeout,
std::unique_ptr<Sampler>* sampler) {
internal::DtypesAndShapes dtypes_and_shapes;
auto status = GetDtypesAndShapesForSampler(table, validation_timeout,
&dtypes_and_shapes);
if (tensorflow::errors::IsDeadlineExceeded(status)) {
REVERB_LOG(REVERB_WARNING)
<< "Unable to validate shapes and dtypes of new sampler for '" << table
<< "' as server could not be reached in time (" << validation_timeout
<< "). We were thus unable to fetch signature from server. The "
"sampler will be constructed without validating the dtypes "
"and shapes.";
}
return NewSampler(table, options, std::move(dtypes_and_shapes), sampler);
}
tensorflow::Status Client::GetDtypesAndShapesForSampler(
const std::string& table, absl::Duration validation_timeout,
internal::DtypesAndShapes* dtypes_and_shapes) {
// TODO(b/154928265): caching this request? For example, if
// it's been N seconds or minutes, it may be time to
// get an updated ServerInfo and see if there are new tables.
std::shared_ptr<internal::FlatSignatureMap> cached_flat_signatures;
TF_RETURN_IF_ERROR(
MaybeUpdateServerInfoCache(validation_timeout, &cached_flat_signatures));
const auto iter = cached_flat_signatures->find(table);
if (iter == cached_flat_signatures->end()) {
std::vector<std::string> table_names;
for (const auto& table : *cached_flat_signatures) {
table_names.push_back(absl::StrCat("'", table.first, "'"));
}
REVERB_LOG(REVERB_WARNING)
<< "Unable to find table '" << table
<< "' in server signature. Perhaps the table hasn't yet been added to "
"the server? Available tables: ["
<< absl::StrJoin(table_names, ", ") << "].";
dtypes_and_shapes->reset();
} else if (!iter->second) {
// Found the table, but signature is empty.
dtypes_and_shapes->reset();
} else {
// Found the table, and found a signature. Add the 4-element prefix for the
// SampleInfo.
const auto& old_dtypes_and_shapes = iter->second;
std::vector<internal::TensorSpec> dtypes_and_shapes_vec;
dtypes_and_shapes_vec.reserve(4 + old_dtypes_and_shapes->size());
// First element of sampled signature is the key.
dtypes_and_shapes_vec.push_back(
{"key", tensorflow::DT_UINT64, tensorflow::PartialTensorShape({})});
// Second element of sampled signature is the probability value.
dtypes_and_shapes_vec.push_back({"probability", tensorflow::DT_DOUBLE,
tensorflow::PartialTensorShape({})});
// Third element of sampled signature is the size of the table.
dtypes_and_shapes_vec.push_back({"table_size", tensorflow::DT_INT64,
tensorflow::PartialTensorShape({})});
// Fourth element of sampled signature is the priority value.
dtypes_and_shapes_vec.push_back({"priority", tensorflow::DT_DOUBLE,
tensorflow::PartialTensorShape({})});
for (const auto& dtype_and_shape : *old_dtypes_and_shapes) {
dtypes_and_shapes_vec.push_back(dtype_and_shape);
}
dtypes_and_shapes->emplace(std::move(dtypes_and_shapes_vec));
}
return tensorflow::Status::OK();
}
tensorflow::Status Client::NewSampler(
const std::string& table, const Sampler::Options& options,
const tensorflow::DataTypeVector& validation_dtypes,
const std::vector<tensorflow::PartialTensorShape>& validation_shapes,
absl::Duration validation_timeout, std::unique_ptr<Sampler>* sampler) {
if (validation_dtypes.size() != validation_shapes.size()) {
return tensorflow::errors::InvalidArgument(
"validation_shapes.size() != validation_dtypes.size() (",
validation_shapes.size(), " vs. ", validation_dtypes.size(), ")");
}
internal::DtypesAndShapes dtypes_and_shapes;
TF_RETURN_IF_ERROR(GetDtypesAndShapesForSampler(table, validation_timeout,
&dtypes_and_shapes));
// Only perform check if the table had a signature associated with it.
if (dtypes_and_shapes) {
if (dtypes_and_shapes->size() != validation_shapes.size()) {
return tensorflow::errors::InvalidArgument(
"Inconsistent number of tensors requested from table '", table,
"'. Requested ", validation_shapes.size(),
" tensors, but table signature shows ", dtypes_and_shapes->size(),
" tensors. Table signature: ",
internal::DtypesShapesString(*dtypes_and_shapes));
}
for (int i = 0; i < dtypes_and_shapes->size(); ++i) {
if (dtypes_and_shapes->at(i).dtype != validation_dtypes[i] ||
!dtypes_and_shapes->at(i).shape.IsCompatibleWith(
validation_shapes[i])) {
return tensorflow::errors::InvalidArgument(
"Requested incompatible tensor at flattened index ", i,
" from table '", table, "'. Requested (dtype, shape): (",
tensorflow::DataTypeString(validation_dtypes[i]), ", ",
validation_shapes[i].DebugString(),
"). Signature (dtype, shape): (",
tensorflow::DataTypeString(dtypes_and_shapes->at(i).dtype), ", ",
dtypes_and_shapes->at(i).shape.DebugString(),
"). Table signature: ",
internal::DtypesShapesString(*dtypes_and_shapes));
}
}
} else {
// dtypes_and_shapes lacks any signature info; build it from
// the validation inputs.
std::vector<internal::TensorSpec> dtypes_and_shapes_vec;
dtypes_and_shapes_vec.reserve(validation_shapes.size());
for (int i = 0; i < validation_shapes.size(); ++i) {
dtypes_and_shapes_vec.push_back(
{/*name=*/"?", validation_dtypes[i], validation_shapes[i]});
}
dtypes_and_shapes.emplace(std::move(dtypes_and_shapes_vec));
}
// TODO(b/154927849): Do sanity checks on the buffer_size and max_samples.
// TODO(b/154928566): Maybe we don't even need to expose the buffer_size.
return NewSampler(table, options, std::move(dtypes_and_shapes), sampler);
}
tensorflow::Status Client::GetServerInfo(absl::Duration timeout,
struct ServerInfo* info) {
grpc::ClientContext context;
context.set_wait_for_ready(true);
if (timeout != absl::InfiniteDuration()) {
context.set_deadline(std::chrono::system_clock::now() +
absl::ToChronoSeconds(timeout));
}
ServerInfoRequest request;
ServerInfoResponse response;
TF_RETURN_IF_ERROR(
FromGrpcStatus(stub_->ServerInfo(&context, request, &response)));
info->tables_state_id = MessageToUint128(response.tables_state_id());
for (class TableInfo& table : *response.mutable_table_info()) {
info->table_info.emplace_back(std::move(table));
}
return tensorflow::Status::OK();
}
tensorflow::Status Client::ServerInfo(struct ServerInfo* info) {
return ServerInfo(absl::InfiniteDuration(), info);
}
tensorflow::Status Client::ServerInfo(absl::Duration timeout,
struct ServerInfo* info) {
struct ServerInfo local_info;
TF_RETURN_IF_ERROR(GetServerInfo(timeout, &local_info));
{
absl::MutexLock lock(&cached_table_mu_);
TF_RETURN_IF_ERROR(LockedUpdateServerInfoCache(local_info));
}
std::swap(*info, local_info);
return tensorflow::Status::OK();
}
tensorflow::Status Client::LockedUpdateServerInfoCache(
const struct ServerInfo& info) {
if (!cached_flat_signatures_ || tables_state_id_ != info.tables_state_id) {
internal::FlatSignatureMap signatures;
for (const auto& table_info : info.table_info) {
TF_RETURN_IF_ERROR(internal::FlatSignatureFromTableInfo(
table_info, &(signatures[table_info.name()])));
}
cached_flat_signatures_.reset(
new internal::FlatSignatureMap(std::move(signatures)));
tables_state_id_ = info.tables_state_id;
}
return tensorflow::Status::OK();
}
tensorflow::Status Client::Reset(const std::string& table) {
grpc::ClientContext context;
context.set_wait_for_ready(true);
ResetRequest request;
request.set_table(table);
ResetResponse response;
return FromGrpcStatus(stub_->Reset(&context, request, &response));
}
tensorflow::Status Client::Checkpoint(std::string* path) {
grpc::ClientContext context;
context.set_fail_fast(true);
CheckpointRequest request;
CheckpointResponse response;
TF_RETURN_IF_ERROR(
FromGrpcStatus(stub_->Checkpoint(&context, request, &response)));
*path = response.checkpoint_path();
return tensorflow::Status::OK();
}
} // namespace reverb
} // namespace deepmind
<commit_msg>Remove obsolete TODO.<commit_after>// Copyright 2019 DeepMind Technologies Limited.
//
// 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 "reverb/cc/client.h"
#include <algorithm>
#include <memory>
#include "grpcpp/support/channel_arguments.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "reverb/cc/platform/grpc_utils.h"
#include "reverb/cc/platform/logging.h"
#include "reverb/cc/reverb_service.pb.h"
#include "reverb/cc/schema.pb.h"
#include "reverb/cc/support/grpc_util.h"
#include "reverb/cc/support/uint128.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/errors.h"
namespace deepmind {
namespace reverb {
namespace {
constexpr int kMaxMessageSize = 30 * 1000 * 1000;
grpc::ChannelArguments CreateChannelArguments() {
grpc::ChannelArguments arguments;
arguments.SetMaxReceiveMessageSize(kMaxMessageSize);
arguments.SetMaxSendMessageSize(kMaxMessageSize);
arguments.SetInt(GRPC_ARG_MAX_RECONNECT_BACKOFF_MS, 30 * 1000);
arguments.SetLoadBalancingPolicyName("round_robin");
return arguments;
}
} // namespace
Client::Client(std::shared_ptr</* grpc_gen:: */ReverbService::StubInterface> stub)
: stub_(std::move(stub)) {
REVERB_CHECK(stub_ != nullptr);
}
Client::Client(absl::string_view server_address)
: stub_(/* grpc_gen:: */ReverbService::NewStub(
CreateCustomGrpcChannel(server_address, MakeChannelCredentials(),
CreateChannelArguments()))) {}
tensorflow::Status Client::MaybeUpdateServerInfoCache(
absl::Duration timeout,
std::shared_ptr<internal::FlatSignatureMap>* cached_flat_signatures) {
// TODO(b/154927570): Once tables can be mutated on the server, we'll need to
// decide a new rule for updating the server info, instead of doing it just
// once at the beginning.
{
// Exit early if we have table info cached.
absl::ReaderMutexLock lock(&cached_table_mu_);
if (cached_flat_signatures_) {
*cached_flat_signatures = cached_flat_signatures_;
return tensorflow::Status::OK();
}
}
if (timeout == -absl::InfiniteDuration()) {
// If timeout is -infinity, the user asked for data to be returned
// immediately and without error; but we don't have anything already cached.
// Just act like everything is fine! (Return empty signatures).
*cached_flat_signatures = std::make_shared<internal::FlatSignatureMap>();
return tensorflow::Status::OK();
}
// This performs an RPC, so don't run it within a mutex.
// Note, this operation can run into a race condition where multiple
// threads of the same Client request server info, get different
// values, and one of these overwrites cached_table_info_ with a staler
// ServerInfo after another thread writes a newer version of ServerInfo
// Then future writers see stale signatures.
//
// In practice this isn't a real issue because:
// (1) This type of concurrency is not common: once ServerInfo
// is set, this code path isn't executed again.
// (2) ServerInfo doesn't change often on a reverb server.
// (3) Due to the default gRPC client load balancing mechanism,
// a client with a stub connection to one IP of a group of
// servers will always use the same IP address for all
// consecutive requests. So even concurrent requests will all
// go to the same server ("pick_first" policy):
//
// https://github.com/grpc/grpc/blob/631fe79f84af295c60aea5693350b45154827398/src/core/ext/filters/client_channel/client_channel.cc#L1661
struct ServerInfo info;
TF_RETURN_IF_ERROR(GetServerInfo(timeout, &info));
absl::MutexLock lock(&cached_table_mu_);
TF_RETURN_IF_ERROR(LockedUpdateServerInfoCache(info));
*cached_flat_signatures = cached_flat_signatures_;
return tensorflow::Status::OK();
}
tensorflow::Status Client::NewWriter(int chunk_length, int max_timesteps,
bool delta_encoded,
std::unique_ptr<Writer>* writer) {
// TODO(b/154928265): caching this request? For example, if
// it's been N seconds or minutes, it may be time to
// get an updated ServerInfo and see if there are new tables.
std::shared_ptr<internal::FlatSignatureMap> cached_flat_signatures;
// TODO(b/154927687): It is not ideal that this blocks forever. We should
// probably limit this and ignore the signature if it couldn't be found within
// some limits.
TF_RETURN_IF_ERROR(MaybeUpdateServerInfoCache(absl::InfiniteDuration(),
&cached_flat_signatures));
*writer = absl::make_unique<Writer>(stub_, chunk_length, max_timesteps,
delta_encoded,
std::move(cached_flat_signatures));
return tensorflow::Status::OK();
}
tensorflow::Status Client::MutatePriorities(
absl::string_view table, const std::vector<KeyWithPriority>& updates,
const std::vector<uint64_t>& deletes) {
grpc::ClientContext context;
context.set_wait_for_ready(true);
MutatePrioritiesRequest request;
request.set_table(table.data(), table.size());
for (const KeyWithPriority& item : updates) {
*request.add_updates() = item;
}
for (int64_t key : deletes) {
request.add_delete_keys(key);
}
MutatePrioritiesResponse response;
return FromGrpcStatus(stub_->MutatePriorities(&context, request, &response));
}
tensorflow::Status Client::NewSampler(
const std::string& table, const Sampler::Options& options,
internal::DtypesAndShapes dtypes_and_shapes,
std::unique_ptr<Sampler>* sampler) {
*sampler = absl::make_unique<Sampler>(stub_, table, options,
std::move(dtypes_and_shapes));
return tensorflow::Status::OK();
}
tensorflow::Status Client::NewSampler(const std::string& table,
const Sampler::Options& options,
absl::Duration validation_timeout,
std::unique_ptr<Sampler>* sampler) {
internal::DtypesAndShapes dtypes_and_shapes;
auto status = GetDtypesAndShapesForSampler(table, validation_timeout,
&dtypes_and_shapes);
if (tensorflow::errors::IsDeadlineExceeded(status)) {
REVERB_LOG(REVERB_WARNING)
<< "Unable to validate shapes and dtypes of new sampler for '" << table
<< "' as server could not be reached in time (" << validation_timeout
<< "). We were thus unable to fetch signature from server. The "
"sampler will be constructed without validating the dtypes "
"and shapes.";
}
return NewSampler(table, options, std::move(dtypes_and_shapes), sampler);
}
tensorflow::Status Client::GetDtypesAndShapesForSampler(
const std::string& table, absl::Duration validation_timeout,
internal::DtypesAndShapes* dtypes_and_shapes) {
// TODO(b/154928265): caching this request? For example, if
// it's been N seconds or minutes, it may be time to
// get an updated ServerInfo and see if there are new tables.
std::shared_ptr<internal::FlatSignatureMap> cached_flat_signatures;
TF_RETURN_IF_ERROR(
MaybeUpdateServerInfoCache(validation_timeout, &cached_flat_signatures));
const auto iter = cached_flat_signatures->find(table);
if (iter == cached_flat_signatures->end()) {
std::vector<std::string> table_names;
for (const auto& table : *cached_flat_signatures) {
table_names.push_back(absl::StrCat("'", table.first, "'"));
}
REVERB_LOG(REVERB_WARNING)
<< "Unable to find table '" << table
<< "' in server signature. Perhaps the table hasn't yet been added to "
"the server? Available tables: ["
<< absl::StrJoin(table_names, ", ") << "].";
dtypes_and_shapes->reset();
} else if (!iter->second) {
// Found the table, but signature is empty.
dtypes_and_shapes->reset();
} else {
// Found the table, and found a signature. Add the 4-element prefix for the
// SampleInfo.
const auto& old_dtypes_and_shapes = iter->second;
std::vector<internal::TensorSpec> dtypes_and_shapes_vec;
dtypes_and_shapes_vec.reserve(4 + old_dtypes_and_shapes->size());
// First element of sampled signature is the key.
dtypes_and_shapes_vec.push_back(
{"key", tensorflow::DT_UINT64, tensorflow::PartialTensorShape({})});
// Second element of sampled signature is the probability value.
dtypes_and_shapes_vec.push_back({"probability", tensorflow::DT_DOUBLE,
tensorflow::PartialTensorShape({})});
// Third element of sampled signature is the size of the table.
dtypes_and_shapes_vec.push_back({"table_size", tensorflow::DT_INT64,
tensorflow::PartialTensorShape({})});
// Fourth element of sampled signature is the priority value.
dtypes_and_shapes_vec.push_back({"priority", tensorflow::DT_DOUBLE,
tensorflow::PartialTensorShape({})});
for (const auto& dtype_and_shape : *old_dtypes_and_shapes) {
dtypes_and_shapes_vec.push_back(dtype_and_shape);
}
dtypes_and_shapes->emplace(std::move(dtypes_and_shapes_vec));
}
return tensorflow::Status::OK();
}
tensorflow::Status Client::NewSampler(
const std::string& table, const Sampler::Options& options,
const tensorflow::DataTypeVector& validation_dtypes,
const std::vector<tensorflow::PartialTensorShape>& validation_shapes,
absl::Duration validation_timeout, std::unique_ptr<Sampler>* sampler) {
if (validation_dtypes.size() != validation_shapes.size()) {
return tensorflow::errors::InvalidArgument(
"validation_shapes.size() != validation_dtypes.size() (",
validation_shapes.size(), " vs. ", validation_dtypes.size(), ")");
}
internal::DtypesAndShapes dtypes_and_shapes;
TF_RETURN_IF_ERROR(GetDtypesAndShapesForSampler(table, validation_timeout,
&dtypes_and_shapes));
// Only perform check if the table had a signature associated with it.
if (dtypes_and_shapes) {
if (dtypes_and_shapes->size() != validation_shapes.size()) {
return tensorflow::errors::InvalidArgument(
"Inconsistent number of tensors requested from table '", table,
"'. Requested ", validation_shapes.size(),
" tensors, but table signature shows ", dtypes_and_shapes->size(),
" tensors. Table signature: ",
internal::DtypesShapesString(*dtypes_and_shapes));
}
for (int i = 0; i < dtypes_and_shapes->size(); ++i) {
if (dtypes_and_shapes->at(i).dtype != validation_dtypes[i] ||
!dtypes_and_shapes->at(i).shape.IsCompatibleWith(
validation_shapes[i])) {
return tensorflow::errors::InvalidArgument(
"Requested incompatible tensor at flattened index ", i,
" from table '", table, "'. Requested (dtype, shape): (",
tensorflow::DataTypeString(validation_dtypes[i]), ", ",
validation_shapes[i].DebugString(),
"). Signature (dtype, shape): (",
tensorflow::DataTypeString(dtypes_and_shapes->at(i).dtype), ", ",
dtypes_and_shapes->at(i).shape.DebugString(),
"). Table signature: ",
internal::DtypesShapesString(*dtypes_and_shapes));
}
}
} else {
// dtypes_and_shapes lacks any signature info; build it from
// the validation inputs.
std::vector<internal::TensorSpec> dtypes_and_shapes_vec;
dtypes_and_shapes_vec.reserve(validation_shapes.size());
for (int i = 0; i < validation_shapes.size(); ++i) {
dtypes_and_shapes_vec.push_back(
{/*name=*/"?", validation_dtypes[i], validation_shapes[i]});
}
dtypes_and_shapes.emplace(std::move(dtypes_and_shapes_vec));
}
// TODO(b/154927849): Do sanity checks on the buffer_size and max_samples.
return NewSampler(table, options, std::move(dtypes_and_shapes), sampler);
}
tensorflow::Status Client::GetServerInfo(absl::Duration timeout,
struct ServerInfo* info) {
grpc::ClientContext context;
context.set_wait_for_ready(true);
if (timeout != absl::InfiniteDuration()) {
context.set_deadline(std::chrono::system_clock::now() +
absl::ToChronoSeconds(timeout));
}
ServerInfoRequest request;
ServerInfoResponse response;
TF_RETURN_IF_ERROR(
FromGrpcStatus(stub_->ServerInfo(&context, request, &response)));
info->tables_state_id = MessageToUint128(response.tables_state_id());
for (class TableInfo& table : *response.mutable_table_info()) {
info->table_info.emplace_back(std::move(table));
}
return tensorflow::Status::OK();
}
tensorflow::Status Client::ServerInfo(struct ServerInfo* info) {
return ServerInfo(absl::InfiniteDuration(), info);
}
tensorflow::Status Client::ServerInfo(absl::Duration timeout,
struct ServerInfo* info) {
struct ServerInfo local_info;
TF_RETURN_IF_ERROR(GetServerInfo(timeout, &local_info));
{
absl::MutexLock lock(&cached_table_mu_);
TF_RETURN_IF_ERROR(LockedUpdateServerInfoCache(local_info));
}
std::swap(*info, local_info);
return tensorflow::Status::OK();
}
tensorflow::Status Client::LockedUpdateServerInfoCache(
const struct ServerInfo& info) {
if (!cached_flat_signatures_ || tables_state_id_ != info.tables_state_id) {
internal::FlatSignatureMap signatures;
for (const auto& table_info : info.table_info) {
TF_RETURN_IF_ERROR(internal::FlatSignatureFromTableInfo(
table_info, &(signatures[table_info.name()])));
}
cached_flat_signatures_.reset(
new internal::FlatSignatureMap(std::move(signatures)));
tables_state_id_ = info.tables_state_id;
}
return tensorflow::Status::OK();
}
tensorflow::Status Client::Reset(const std::string& table) {
grpc::ClientContext context;
context.set_wait_for_ready(true);
ResetRequest request;
request.set_table(table);
ResetResponse response;
return FromGrpcStatus(stub_->Reset(&context, request, &response));
}
tensorflow::Status Client::Checkpoint(std::string* path) {
grpc::ClientContext context;
context.set_fail_fast(true);
CheckpointRequest request;
CheckpointResponse response;
TF_RETURN_IF_ERROR(
FromGrpcStatus(stub_->Checkpoint(&context, request, &response)));
*path = response.checkpoint_path();
return tensorflow::Status::OK();
}
} // namespace reverb
} // namespace deepmind
<|endoftext|>
|
<commit_before>/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "astutil.h"
#include "expr.h"
#include "optimizations.h"
#include "passes.h"
#include "resolveIntents.h"
#include "stmt.h"
#include "stringutil.h"
#include "symbol.h"
#include "type.h"
static Type* getWrapRecordBaseType(Type* type);
//
// removes _array and _domain wrapper records
//
void
removeWrapRecords() {
//
// do not remove wrap records if dead code elimination is disabled
// (or weakened because inlining or copy propagation is disabled)
// because code associated with accesses to the removed
// _valueType field will remain
//
if (fNoDeadCodeElimination || fNoInline || fNoCopyPropagation)
return;
//
// replace use of _valueType field with type
//
forv_Vec(CallExpr, call, gCallExprs) {
if (call->isPrimitive(PRIM_GET_PRIV_CLASS)) {
SET_LINENO(call);
call->get(1)->replace(new SymExpr(call->get(1)->typeInfo()->symbol));
}
}
//
// remove defs of _valueType field
//
forv_Vec(CallExpr, call, gCallExprs) {
if (call->isPrimitive(PRIM_SET_MEMBER) ||
call->isPrimitive(PRIM_GET_MEMBER) ||
call->isPrimitive(PRIM_GET_MEMBER_VALUE)) {
if (SymExpr* se = toSymExpr(call->get(2))) {
if (!strcmp(se->var->name, "_valueType")) {
se->getStmtExpr()->remove();
}
}
}
}
//
// remove _valueType fields
//
forv_Vec(AggregateType, ct, gAggregateTypes) {
for_fields(field, ct) {
if (!strcmp(field->name, "_valueType"))
field->defPoint->remove();
}
}
//
// remove formals for _valueType fields in constructors
//
compute_call_sites();
forv_Vec(FnSymbol, fn, gFnSymbols) {
for_formals(formal, fn) {
if (!strcmp(formal->name, "_valueType")) {
forv_Vec(CallExpr, call, *fn->calledBy) {
formal_to_actual(call, formal)->remove();
}
formal->defPoint->remove();
}
}
}
//
// replace accesses of _value with wrap record
//
forv_Vec(CallExpr, call, gCallExprs) {
if (call->isPrimitive(PRIM_SET_MEMBER)) {
if (SymExpr* se = toSymExpr(call->get(1))) {
if (isRecordWrappedType(se->var->type)) {
call->primitive = primitives[PRIM_MOVE];
call->get(2)->remove();
}
}
} else if (call->isPrimitive(PRIM_GET_MEMBER)) {
if (SymExpr* se = toSymExpr(call->get(1))) {
if (isRecordWrappedType(se->var->type)) {
call->primitive = primitives[PRIM_ADDR_OF];
call->get(2)->remove();
}
}
} else if (call->isPrimitive(PRIM_GET_MEMBER_VALUE)) {
if (SymExpr* se = toSymExpr(call->get(1))) {
if (isRecordWrappedType(se->var->type)) {
call->replace(se->remove());
}
if (se->var->type->symbol->hasFlag(FLAG_REF)) {
Type* vt = se->getValType();
if (isRecordWrappedType(vt)) {
SET_LINENO(call);
call->replace(new CallExpr(PRIM_DEREF, se->remove()));
}
}
}
}
}
//
// scalar replace wrap records
//
forv_Vec(VarSymbol, var, gVarSymbols) {
if (Type* type = getWrapRecordBaseType(var->type))
if (!var->defPoint->parentSymbol->hasFlag(FLAG_REF))
var->type = type;
}
forv_Vec(ArgSymbol, arg, gArgSymbols) {
if (Type* type = getWrapRecordBaseType(arg->type)) {
arg->intent = blankIntentForType(type); // see test/arrays/deitz/part7/test_out_array
arg->type = type;
}
}
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (Type* type = getWrapRecordBaseType(fn->retType))
fn->retType = type;
}
//
// fix array element type for arrays of arrays and arrays of domains
//
forv_Vec(AggregateType, ct, gAggregateTypes) {
if (ct->symbol->hasFlag(FLAG_DATA_CLASS)) {
if (TypeSymbol* ts = getDataClassType(ct->symbol)) {
if (isRecordWrappedType(ts->typeInfo())) {
setDataClassType(ct->symbol, ts->type->getField("_value")->type->symbol);
}
}
}
}
}
static Type*
getWrapRecordBaseType(Type* type) {
if (isRecordWrappedType(type)) {
return type->getField("_value")->type;
} else if (type->symbol->hasFlag(FLAG_REF)) {
Type* vt = type->getValType();
if (isRecordWrappedType(vt)) {
return vt->getField("_value")->type->refType;
}
}
return NULL;
}
<commit_msg>Revise removeWrapRecords to avoid generating bogus C code.<commit_after>/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "astutil.h"
#include "expr.h"
#include "optimizations.h"
#include "passes.h"
#include "resolveIntents.h"
#include "stmt.h"
#include "stringutil.h"
#include "symbol.h"
#include "type.h"
#include "stlUtil.h"
static Type* getWrapRecordBaseType(Type* type);
//
// removes _array and _domain wrapper records
//
void
removeWrapRecords() {
//
// do not remove wrap records if dead code elimination is disabled
// (or weakened because inlining or copy propagation is disabled)
// because code associated with accesses to the removed
// _valueType field will remain
//
if (fNoDeadCodeElimination || fNoInline || fNoCopyPropagation)
return;
//
// replace use of _valueType field with type
//
forv_Vec(CallExpr, call, gCallExprs) {
if (call->isPrimitive(PRIM_GET_PRIV_CLASS)) {
SET_LINENO(call);
call->get(1)->replace(new SymExpr(call->get(1)->typeInfo()->symbol));
}
}
//
// remove defs of _valueType field
//
forv_Vec(CallExpr, call, gCallExprs) {
if (call->isPrimitive(PRIM_SET_MEMBER) ||
call->isPrimitive(PRIM_GET_MEMBER) ||
call->isPrimitive(PRIM_GET_MEMBER_VALUE)) {
if (SymExpr* se = toSymExpr(call->get(2))) {
if (!strcmp(se->var->name, "_valueType")) {
se->getStmtExpr()->remove();
}
}
}
}
//
// remove _valueType fields
//
forv_Vec(AggregateType, ct, gAggregateTypes) {
for_fields(field, ct) {
if (!strcmp(field->name, "_valueType"))
field->defPoint->remove();
}
}
//
// remove actuals bound to _valueType formals.
//
compute_call_sites();
forv_Vec(FnSymbol, fn, gFnSymbols) {
for_formals(formal, fn) {
if (!strcmp(formal->name, "_valueType")) {
forv_Vec(CallExpr, call, *fn->calledBy) {
formal_to_actual(call, formal)->remove();
}
}
}
}
//
// remove all uses of _valueType formals, and then the formal itself.
//
forv_Vec(FnSymbol, fn, gFnSymbols) {
for_formals(formal, fn) {
if (!strcmp(formal->name, "_valueType")) {
// Remove all uses of _valueType within the body of this function.
std::vector<SymExpr*> symExprs;
collectSymExprsSTL(fn->body, symExprs);
for_vector(SymExpr, se, symExprs) {
// Ignore dead ones.
if (se->parentSymbol == NULL)
continue;
// Weed out all but the formal we're interested in.
if (se->var != formal)
continue;
// OK, remove the entire statement accessing the _valueType formal.
Expr* stmt = se->getStmtExpr();
stmt->remove();
}
formal->defPoint->remove();
}
}
}
//
// replace accesses of _value with wrap record
//
forv_Vec(CallExpr, call, gCallExprs) {
if (call->parentSymbol == NULL)
continue;
if (call->isPrimitive(PRIM_SET_MEMBER)) {
if (SymExpr* se = toSymExpr(call->get(1))) {
if (isRecordWrappedType(se->var->type)) {
call->primitive = primitives[PRIM_MOVE];
call->get(2)->remove();
}
}
} else if (call->isPrimitive(PRIM_GET_MEMBER)) {
if (SymExpr* se = toSymExpr(call->get(1))) {
if (isRecordWrappedType(se->var->type)) {
call->primitive = primitives[PRIM_ADDR_OF];
call->get(2)->remove();
}
}
} else if (call->isPrimitive(PRIM_GET_MEMBER_VALUE)) {
if (SymExpr* se = toSymExpr(call->get(1))) {
if (isRecordWrappedType(se->var->type)) {
call->replace(se->remove());
}
if (se->var->type->symbol->hasFlag(FLAG_REF)) {
Type* vt = se->getValType();
if (isRecordWrappedType(vt)) {
SET_LINENO(call);
call->replace(new CallExpr(PRIM_DEREF, se->remove()));
}
}
}
}
}
//
// scalar replace wrap records
//
forv_Vec(VarSymbol, var, gVarSymbols) {
if (Type* type = getWrapRecordBaseType(var->type))
if (!var->defPoint->parentSymbol->hasFlag(FLAG_REF))
var->type = type;
}
forv_Vec(ArgSymbol, arg, gArgSymbols) {
if (Type* type = getWrapRecordBaseType(arg->type)) {
arg->intent = blankIntentForType(type); // see test/arrays/deitz/part7/test_out_array
arg->type = type;
}
}
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (Type* type = getWrapRecordBaseType(fn->retType))
fn->retType = type;
}
//
// fix array element type for arrays of arrays and arrays of domains
//
forv_Vec(AggregateType, ct, gAggregateTypes) {
if (ct->symbol->hasFlag(FLAG_DATA_CLASS)) {
if (TypeSymbol* ts = getDataClassType(ct->symbol)) {
if (isRecordWrappedType(ts->typeInfo())) {
setDataClassType(ct->symbol, ts->type->getField("_value")->type->symbol);
}
}
}
}
}
static Type*
getWrapRecordBaseType(Type* type) {
if (isRecordWrappedType(type)) {
return type->getField("_value")->type;
} else if (type->symbol->hasFlag(FLAG_REF)) {
Type* vt = type->getValType();
if (isRecordWrappedType(vt)) {
return vt->getField("_value")->type->refType;
}
}
return NULL;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/mss_generic_check.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mss_generic_check.H
/// @brief Checker functions for generic API
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef _MSS_GENERIC_CHECK_H_
#define _MSS_GENERIC_CHECK_H_
#include <fapi2.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <generic/memory/lib/utils/c_str.H>
namespace mss
{
namespace check
{
///
/// @brief Checks conditional passes and implements traces & exits if it fails
/// @tparam T fapi2 target type
/// @tparam IT input data type
/// @tparam FFDC error callout code type
/// @param[in] i_target fapi2 target
/// @param[in] i_conditional conditional that we are testing against
/// @param[in] i_byte_index byte index
/// @param[in] i_data debug data
/// @param[in] i_ffdc_codes FFDC code
/// @param[in] i_err_str error string - defaulted to ""
/// @return FAPI2_RC_SUCCESS iff okay
///
template< fapi2::TargetType T, typename IT , typename FFDC >
inline fapi2::ReturnCode invalid_value(const fapi2::Target<T>& i_target,
const bool i_conditional,
const size_t i_byte_index,
const IT i_data,
const FFDC i_ffdc_codes,
const char* i_err_str = "")
{
FAPI_ASSERT(i_conditional,
fapi2::MSS_FAILED_DATA_INTEGRITY_CHECK().
set_VALUE(i_data).
set_BYTE(i_byte_index).
set_TARGET(i_target).
set_FFDC_CODE(i_ffdc_codes),
"%s %s Byte %d, Data returned: %d.",
spd::c_str(i_target),
i_err_str,
i_byte_index,
i_data);
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
} // fail_for_invalid_value
} // check
}// mss
#endif
<commit_msg>Add snapshot of generic/memory for master-p10<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/mss_generic_check.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mss_generic_check.H
/// @brief Checker functions for generic API
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef _MSS_GENERIC_CHECK_H_
#define _MSS_GENERIC_CHECK_H_
#include <fapi2.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <generic/memory/lib/utils/scom.H>
#include <generic/memory/lib/utils/c_str.H>
namespace mss
{
namespace check
{
///
/// @brief Checks whether any FIRs have lit up on a target
/// @tparam MC MC type for which to check FIR's
/// @tparam T the fapi2::TargetType which hold the FIR bits
/// @param[in] i_target - the target on which to operate
/// @param[in,out] io_rc - the return code for the function
/// @param[out] o_fir_error - true iff a FIR was hit
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
template< mss::mc_type MC, fapi2::TargetType T >
fapi2::ReturnCode bad_fir_bits( const fapi2::Target<T>& i_target, fapi2::ReturnCode& io_rc, bool& o_fir_error );
///
/// @brief Checks whether the passed in FIRs have any un-masked errors set
/// @tparam MC MC type for which to check FIR's
/// @tparam T the fapi2::TargetType which hold the FIR bits
/// @param[in] i_target - the target on which to operate
/// @param[in] i_fir_regs - FIR register and mask register
/// @param[out] o_fir_error - true iff a FIR was hit
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
template< mss::mc_type MC, fapi2::TargetType T >
inline fapi2::ReturnCode fir_with_mask( const fapi2::Target<T>& i_target,
const std::pair<uint64_t, uint64_t>& i_fir_regs,
bool& o_fir_error )
{
// Temporary variables to make the code a bit more readable
const auto FIR_REG = i_fir_regs.first;
const auto FIR_MASK = i_fir_regs.second;
fapi2::buffer<uint64_t> l_fir;
fapi2::buffer<uint64_t> l_fir_mask;
// Read the registers
FAPI_TRY(mss::getScom(i_target, FIR_REG, l_fir));
FAPI_TRY(mss::getScom(i_target, FIR_MASK, l_fir_mask));
// The mask register will need to be inverted as a 0 in the mask register means the FIR is legit
// A bitwise and works the opposite way
l_fir_mask.invert();
// If we have any unmasked bit, set that we have a FIR error and exit out with success
// Note: we want to set success here as PRD will find the FIR as "new" and retrigger the procedure this way
o_fir_error = ((l_fir & l_fir_mask) != 0);
// And print the information for debuggability
FAPI_INF("%s %s on reg 0x%016lx value 0x%016lx and mask 0x%016lx value 0x%016lx", mss::c_str(i_target),
o_fir_error ? "has FIR's set" : "has no FIR's set", FIR_REG, l_fir, FIR_MASK, l_fir_mask.invert());
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Checks whether a FIR or unlocked PLL could be the root cause of another failure
/// @tparam MC MC type for which to check FIR's
/// @tparam T the fapi2::TargetType which hold the FIR bits
/// @param[in] i_target - the target on which to operate
/// @param[in,out] io_rc - the return code for the function
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
/// @note This is a helper function to enable unit testing
///
template< mss::mc_type MC, fapi2::TargetType T >
fapi2::ReturnCode hostboot_fir_or_pll_fail( const fapi2::Target<T>& i_target, fapi2::ReturnCode& io_rc)
{
// We didn't have an error, so return success
if(io_rc == fapi2::FAPI2_RC_SUCCESS)
{
FAPI_INF("%s has a good return code, returning success", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
fapi2::ReturnCode l_fircheck_scom_err(fapi2::FAPI2_RC_SUCCESS);
bool l_fir_error = false;
FAPI_ERR("%s has a bad return code, time to check some firs!", mss::c_str(i_target));
l_fircheck_scom_err = bad_fir_bits<MC>(i_target, io_rc, l_fir_error);
FAPI_ERR("%s took a fail. FIR was %s", mss::c_str(i_target),
l_fir_error ? "set - returning FIR RC" : "unset - returning inputted RC");
// If we had a FIR error, log the original error and return success
// PRD will handle the original error
if(l_fir_error)
{
fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;
}
else
{
fapi2::current_err = io_rc;
}
return fapi2::current_err;
}
///
/// @brief Checks whether a FIR or unlocked PLL could be the root cause of another failure, if a check fir boolean is passed in
/// @tparam MC MC type for which to check FIR's
/// @tparam T the fapi2::TargetType which hold the FIR bits
/// @param[in] i_target - the target on which to operate
/// @param[in,out] io_rc - the return code for the function
/// @param[in] i_check_fir - true IFF the FIR needs to be checked - defaults to true
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
template< mss::mc_type MC, fapi2::TargetType T >
fapi2::ReturnCode fir_or_pll_fail( const fapi2::Target<T>& i_target,
fapi2::ReturnCode& io_rc,
const bool i_check_fir = true)
{
#ifdef __HOSTBOOT_MODULE
fapi2::ReturnCode l_rc(io_rc);
// If need be, check the FIR below
if(i_check_fir)
{
// Handle any issues according to PRD FIR scheme, as a FIR could have caused this issue
l_rc = hostboot_fir_or_pll_fail<MC>(i_target, l_rc);
}
return l_rc;
#else
return io_rc;
#endif
}
///
/// @brief Checks conditional passes and implements traces & exits if it fails
/// @tparam T fapi2 target type
/// @tparam IT input data type
/// @tparam FFDC error callout code type
/// @param[in] i_target fapi2 target
/// @param[in] i_conditional conditional that we are testing against
/// @param[in] i_byte_index byte index
/// @param[in] i_data debug data
/// @param[in] i_ffdc_codes FFDC code
/// @param[in] i_err_str error string - defaulted to ""
/// @return FAPI2_RC_SUCCESS iff okay
///
template< fapi2::TargetType T, typename IT , typename FFDC >
inline fapi2::ReturnCode invalid_value(const fapi2::Target<T>& i_target,
const bool i_conditional,
const size_t i_byte_index,
const IT i_data,
const FFDC i_ffdc_codes,
const char* i_err_str = "")
{
FAPI_ASSERT(i_conditional,
fapi2::MSS_FAILED_DATA_INTEGRITY_CHECK().
set_VALUE(i_data).
set_BYTE(i_byte_index).
set_TARGET(i_target).
set_FFDC_CODE(i_ffdc_codes),
"%s %s Byte %d, Data returned: %d.",
spd::c_str(i_target),
i_err_str,
i_byte_index,
i_data);
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
} // fail_for_invalid_value
} // check
}// mss
#endif
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010 Harshit Jain <hjain.itbhu@gmail.com>
//
#include "KmlTimeStampTagHandler.h"
#include "MarbleDebug.h"
#include "KmlElementDictionary.h"
#include "GeoDataTimeStamp.h"
#include "GeoDataFeature.h"
#include "GeoParser.h"
namespace Marble
{
namespace kml
{
KML_DEFINE_TAG_HANDLER( TimeStamp )
GeoNode* KmlTimeStampTagHandler::parse( GeoParser& parser ) const
{
Q_ASSERT( parser.isStartElement() && parser.isValidElement( kmlTag_TimeStamp ) );
GeoStackItem parentItem = parser.parentElement();
if ( parentItem.nodeAs<GeoDataFeature>() ) {
GeoDataTimeStamp timeStamp;
QString id = parser.attribute( "id" ).trimmed();
parentItem.nodeAs<GeoDataFeature>()->setTimeStamp( timeStamp );
return &parentItem.nodeAs<GeoDataFeature>()->timeStamp();
}
return 0;
}
}
}
<commit_msg>Must not implicitly cast static_cast result to boolean<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010 Harshit Jain <hjain.itbhu@gmail.com>
//
#include "KmlTimeStampTagHandler.h"
#include "MarbleDebug.h"
#include "KmlElementDictionary.h"
#include "GeoDataTimeStamp.h"
#include "GeoDataFeature.h"
#include "GeoParser.h"
namespace Marble
{
namespace kml
{
KML_DEFINE_TAG_HANDLER( TimeStamp )
GeoNode* KmlTimeStampTagHandler::parse( GeoParser& parser ) const
{
Q_ASSERT( parser.isStartElement() && parser.isValidElement( kmlTag_TimeStamp ) );
GeoStackItem parentItem = parser.parentElement();
if ( parentItem.is<GeoDataFeature>() ) {
parentItem.nodeAs<GeoDataFeature>()->setTimeStamp( GeoDataTimeStamp() );
return &parentItem.nodeAs<GeoDataFeature>()->timeStamp();
}
return 0;
}
}
}
<|endoftext|>
|
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2010 Klaus Post
Copyright (C) 2014-2015 Pedro Côrte-Real
Copyright (C) 2017 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/SamsungV2Decompressor.h"
#include "common/Common.h" // for uint32, ushort16, int32
#include "common/Point.h" // for iPoint2D
#include "common/RawImage.h" // for RawImage, RawImageData
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include "io/BitPumpMSB32.h" // for BitPumpMSB32
#include "io/ByteStream.h" // for ByteStream
#include <algorithm> // for max
#include <cassert> // for assert
#include <type_traits> // for underlying_type, underlyin...
namespace rawspeed {
// Seriously Samsung just use lossless jpeg already, it compresses better too :)
// Thanks to Michael Reichmann (Luminous Landscape) for putting Pedro Côrte-Real
// in contact and Loring von Palleske (Samsung) for pointing to the open-source
// code of Samsung's DNG converter at http://opensource.samsung.com/
enum struct SamsungV2Decompressor::OptFlags : uint32 {
NONE = 0U, // no flags
SKIP = 1U << 0U, // Skip checking if we need differences from previous line
MV = 1U << 1U, // Simplify motion vector definition
QP = 1U << 2U, // Don't scale the diff values
// all possible flags
ALL = SKIP | MV | QP,
};
constexpr SamsungV2Decompressor::OptFlags
operator|(SamsungV2Decompressor::OptFlags lhs,
SamsungV2Decompressor::OptFlags rhs) {
return static_cast<SamsungV2Decompressor::OptFlags>(
static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(
lhs) |
static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(
rhs));
}
constexpr bool operator&(SamsungV2Decompressor::OptFlags lhs,
SamsungV2Decompressor::OptFlags rhs) {
return SamsungV2Decompressor::OptFlags::NONE !=
static_cast<SamsungV2Decompressor::OptFlags>(
static_cast<
std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(
lhs) &
static_cast<
std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(
rhs));
}
SamsungV2Decompressor::SamsungV2Decompressor(const RawImage& image,
const ByteStream& bs, int bit)
: AbstractSamsungDecompressor(image), bits(bit) {
BitPumpMSB32 startpump(bs);
// Process the initial metadata bits, we only really use initVal, width and
// height (the last two match the TIFF values anyway)
startpump.getBits(16); // NLCVersion
startpump.getBits(4); // ImgFormat
bitDepth = startpump.getBits(4) + 1;
startpump.getBits(4); // NumBlkInRCUnit
startpump.getBits(4); // CompressionRatio
width = startpump.getBits(16);
height = startpump.getBits(16);
startpump.getBits(16); // TileWidth
startpump.getBits(4); // reserved
// The format includes an optimization code that sets 3 flags to change the
// decoding parameters
const uint32 optflags = startpump.getBits(4);
if (optflags > static_cast<uint32>(OptFlags::ALL))
ThrowRDE("Invalid opt flags %x", optflags);
_flags = static_cast<OptFlags>(optflags);
startpump.getBits(8); // OverlapWidth
startpump.getBits(8); // reserved
startpump.getBits(8); // Inc
startpump.getBits(2); // reserved
initVal = startpump.getBits(14);
if (width == 0 || height == 0 || width % 16 != 0 || width > 6496 ||
height > 4336)
ThrowRDE("Unexpected image dimensions found: (%u; %u)", width, height);
if (width != static_cast<uint32>(mRaw->dim.x) ||
height != static_cast<uint32>(mRaw->dim.y))
ThrowRDE("EXIF image dimensions do not match dimensions from raw header");
data = startpump.getStream(startpump.getRemainSize());
}
void SamsungV2Decompressor::decompress() {
switch (_flags) {
case OptFlags::NONE:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::NONE>(row);
break;
case OptFlags::ALL:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::ALL>(row);
break;
case OptFlags::SKIP:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::SKIP>(row);
break;
case OptFlags::MV:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::MV>(row);
break;
case OptFlags::QP:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::QP>(row);
break;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch"
case OptFlags::SKIP | OptFlags::MV:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::SKIP | OptFlags::MV>(row);
break;
case OptFlags::SKIP | OptFlags::QP:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::SKIP | OptFlags::QP>(row);
break;
case OptFlags::MV | OptFlags::QP:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::MV | OptFlags::QP>(row);
break;
#pragma GCC diagnostic pop
default:
__builtin_unreachable();
}
}
template <SamsungV2Decompressor::OptFlags optflags>
void SamsungV2Decompressor::decompressRow(uint32 row) {
// The format is relatively straightforward. Each line gets encoded as a set
// of differences from pixels from another line. Pixels are grouped in blocks
// of 16 (8 green, 8 red or blue). Each block is encoded in three sections.
// First 1 or 4 bits to specify which reference pixels to use, then a section
// that specifies for each pixel the number of bits in the difference, then
// the actual difference bits
// Align pump to 16byte boundary
const auto line_offset = data.getPosition();
if ((line_offset & 0xf) != 0)
data.skipBytes(16 - (line_offset & 0xf));
BitPumpMSB32 pump(data);
auto* img = reinterpret_cast<ushort16*>(mRaw->getData(0, row));
ushort16* img_up = reinterpret_cast<ushort16*>(
mRaw->getData(0, std::max(0, static_cast<int>(row) - 1)));
ushort16* img_up2 = reinterpret_cast<ushort16*>(
mRaw->getData(0, std::max(0, static_cast<int>(row) - 2)));
// Initialize the motion and diff modes at the start of the line
uint32 motion = 7;
// By default we are not scaling values at all
int32 scale = 0;
uint32 diffBitsMode[3][2] = {{0}};
for (auto& i : diffBitsMode)
i[0] = i[1] = (row == 0 || row == 1) ? 7 : 4;
assert(width >= 16);
for (uint32 col = 0; col < width; col += 16) {
if (!(optflags & OptFlags::QP) && !(col & 63)) {
int32 scalevals[] = {0, -2, 2};
uint32 i = pump.getBits(2);
scale = i < 3 ? scale + scalevals[i] : pump.getBits(12);
}
// First we figure out which reference pixels mode we're in
if (optflags & OptFlags::MV)
motion = pump.getBits(1) ? 3 : 7;
else if (!pump.getBits(1))
motion = pump.getBits(3);
if ((row == 0 || row == 1) && (motion != 7))
ThrowRDE("At start of image and motion isn't 7. File corrupted?");
if (motion == 7) {
// The base case, just set all pixels to the previous ones on the same
// line If we're at the left edge we just start at the initial value
for (uint32 i = 0; i < 16; i++)
img[i] = (col == 0) ? initVal : *(img + i - 2);
} else {
// The complex case, we now need to actually lookup one or two lines
// above
if (row < 2)
ThrowRDE(
"Got a previous line lookup on first two lines. File corrupted?");
int32 motionOffset[7] = {-4, -2, -2, 0, 0, 2, 4};
int32 motionDoAverage[7] = {0, 0, 1, 0, 1, 0, 0};
int32 slideOffset = motionOffset[motion];
int32 doAverage = motionDoAverage[motion];
for (uint32 i = 0; i < 16; i++) {
ushort16* refpixel;
if ((row + i) & 0x1) {
// Red or blue pixels use same color two lines up
refpixel = img_up2 + i + slideOffset;
if (col == 0 && img_up2 > refpixel)
ThrowRDE("Bad motion %u at the beginning of the row", motion);
} else {
// Green pixel N uses Green pixel N from row above
// (top left or top right)
refpixel = img_up + i + slideOffset + (((i % 2) != 0) ? -1 : 1);
if (col == 0 && img_up > refpixel)
ThrowRDE("Bad motion %u at the beginning of the row", motion);
}
// In some cases we use as reference interpolation of this pixel and
// the next
if (doAverage)
img[i] = (*refpixel + *(refpixel + 2) + 1) >> 1;
else
img[i] = *refpixel;
}
}
// Figure out how many difference bits we have to read for each pixel
uint32 diffBits[4] = {0};
if (optflags & OptFlags::SKIP || !pump.getBits(1)) {
uint32 flags[4];
for (unsigned int& flag : flags)
flag = pump.getBits(2);
for (uint32 i = 0; i < 4; i++) {
// The color is 0-Green 1-Blue 2-Red
uint32 colornum = (row % 2 != 0) ? i >> 1 : ((i >> 1) + 2) % 3;
assert(flags[i] <= 3);
switch (flags[i]) {
case 0:
diffBits[i] = diffBitsMode[colornum][0];
break;
case 1:
diffBits[i] = diffBitsMode[colornum][0] + 1;
break;
case 2:
diffBits[i] = diffBitsMode[colornum][0] - 1;
break;
case 3:
diffBits[i] = pump.getBits(4);
break;
default:
__builtin_unreachable();
}
diffBitsMode[colornum][0] = diffBitsMode[colornum][1];
diffBitsMode[colornum][1] = diffBits[i];
if (diffBits[i] > bitDepth + 1)
ThrowRDE("Too many difference bits. File corrupted?");
}
}
// Actually read the differences and write them to the pixels
for (uint32 i = 0; i < 16; i++) {
uint32 len = diffBits[i >> 2];
int32 diff = pump.getBits(len);
// If the first bit is 1 we need to turn this into a negative number
if (len != 0 && diff >> (len - 1))
diff -= (1 << len);
ushort16* value = nullptr;
// Apply the diff to pixels 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15
if (row % 2)
value = &img[((i & 0x7) << 1) + 1 - (i >> 3)];
else
value = &img[((i & 0x7) << 1) + (i >> 3)];
diff = diff * (scale * 2 + 1) + scale;
*value = clampBits(static_cast<int>(*value) + diff, bits);
}
img += 16;
img_up += 16;
img_up2 += 16;
}
data.skipBytes(pump.getBufferPosition());
}
} // namespace rawspeed
<commit_msg>SamsungV2Decompressor::decompressRow(): mark static data as such<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2010 Klaus Post
Copyright (C) 2014-2015 Pedro Côrte-Real
Copyright (C) 2017 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/SamsungV2Decompressor.h"
#include "common/Common.h" // for uint32, ushort16, int32
#include "common/Point.h" // for iPoint2D
#include "common/RawImage.h" // for RawImage, RawImageData
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include "io/BitPumpMSB32.h" // for BitPumpMSB32
#include "io/ByteStream.h" // for ByteStream
#include <algorithm> // for max
#include <cassert> // for assert
#include <type_traits> // for underlying_type, underlyin...
namespace rawspeed {
// Seriously Samsung just use lossless jpeg already, it compresses better too :)
// Thanks to Michael Reichmann (Luminous Landscape) for putting Pedro Côrte-Real
// in contact and Loring von Palleske (Samsung) for pointing to the open-source
// code of Samsung's DNG converter at http://opensource.samsung.com/
enum struct SamsungV2Decompressor::OptFlags : uint32 {
NONE = 0U, // no flags
SKIP = 1U << 0U, // Skip checking if we need differences from previous line
MV = 1U << 1U, // Simplify motion vector definition
QP = 1U << 2U, // Don't scale the diff values
// all possible flags
ALL = SKIP | MV | QP,
};
constexpr SamsungV2Decompressor::OptFlags
operator|(SamsungV2Decompressor::OptFlags lhs,
SamsungV2Decompressor::OptFlags rhs) {
return static_cast<SamsungV2Decompressor::OptFlags>(
static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(
lhs) |
static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(
rhs));
}
constexpr bool operator&(SamsungV2Decompressor::OptFlags lhs,
SamsungV2Decompressor::OptFlags rhs) {
return SamsungV2Decompressor::OptFlags::NONE !=
static_cast<SamsungV2Decompressor::OptFlags>(
static_cast<
std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(
lhs) &
static_cast<
std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(
rhs));
}
SamsungV2Decompressor::SamsungV2Decompressor(const RawImage& image,
const ByteStream& bs, int bit)
: AbstractSamsungDecompressor(image), bits(bit) {
BitPumpMSB32 startpump(bs);
// Process the initial metadata bits, we only really use initVal, width and
// height (the last two match the TIFF values anyway)
startpump.getBits(16); // NLCVersion
startpump.getBits(4); // ImgFormat
bitDepth = startpump.getBits(4) + 1;
startpump.getBits(4); // NumBlkInRCUnit
startpump.getBits(4); // CompressionRatio
width = startpump.getBits(16);
height = startpump.getBits(16);
startpump.getBits(16); // TileWidth
startpump.getBits(4); // reserved
// The format includes an optimization code that sets 3 flags to change the
// decoding parameters
const uint32 optflags = startpump.getBits(4);
if (optflags > static_cast<uint32>(OptFlags::ALL))
ThrowRDE("Invalid opt flags %x", optflags);
_flags = static_cast<OptFlags>(optflags);
startpump.getBits(8); // OverlapWidth
startpump.getBits(8); // reserved
startpump.getBits(8); // Inc
startpump.getBits(2); // reserved
initVal = startpump.getBits(14);
if (width == 0 || height == 0 || width % 16 != 0 || width > 6496 ||
height > 4336)
ThrowRDE("Unexpected image dimensions found: (%u; %u)", width, height);
if (width != static_cast<uint32>(mRaw->dim.x) ||
height != static_cast<uint32>(mRaw->dim.y))
ThrowRDE("EXIF image dimensions do not match dimensions from raw header");
data = startpump.getStream(startpump.getRemainSize());
}
void SamsungV2Decompressor::decompress() {
switch (_flags) {
case OptFlags::NONE:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::NONE>(row);
break;
case OptFlags::ALL:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::ALL>(row);
break;
case OptFlags::SKIP:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::SKIP>(row);
break;
case OptFlags::MV:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::MV>(row);
break;
case OptFlags::QP:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::QP>(row);
break;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch"
case OptFlags::SKIP | OptFlags::MV:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::SKIP | OptFlags::MV>(row);
break;
case OptFlags::SKIP | OptFlags::QP:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::SKIP | OptFlags::QP>(row);
break;
case OptFlags::MV | OptFlags::QP:
for (uint32 row = 0; row < height; row++)
decompressRow<OptFlags::MV | OptFlags::QP>(row);
break;
#pragma GCC diagnostic pop
default:
__builtin_unreachable();
}
}
template <SamsungV2Decompressor::OptFlags optflags>
void SamsungV2Decompressor::decompressRow(uint32 row) {
// The format is relatively straightforward. Each line gets encoded as a set
// of differences from pixels from another line. Pixels are grouped in blocks
// of 16 (8 green, 8 red or blue). Each block is encoded in three sections.
// First 1 or 4 bits to specify which reference pixels to use, then a section
// that specifies for each pixel the number of bits in the difference, then
// the actual difference bits
// Align pump to 16byte boundary
const auto line_offset = data.getPosition();
if ((line_offset & 0xf) != 0)
data.skipBytes(16 - (line_offset & 0xf));
BitPumpMSB32 pump(data);
auto* img = reinterpret_cast<ushort16*>(mRaw->getData(0, row));
ushort16* img_up = reinterpret_cast<ushort16*>(
mRaw->getData(0, std::max(0, static_cast<int>(row) - 1)));
ushort16* img_up2 = reinterpret_cast<ushort16*>(
mRaw->getData(0, std::max(0, static_cast<int>(row) - 2)));
// Initialize the motion and diff modes at the start of the line
uint32 motion = 7;
// By default we are not scaling values at all
int32 scale = 0;
uint32 diffBitsMode[3][2] = {{0}};
for (auto& i : diffBitsMode)
i[0] = i[1] = (row == 0 || row == 1) ? 7 : 4;
assert(width >= 16);
for (uint32 col = 0; col < width; col += 16) {
if (!(optflags & OptFlags::QP) && !(col & 63)) {
static constexpr int32 scalevals[] = {0, -2, 2};
uint32 i = pump.getBits(2);
scale = i < 3 ? scale + scalevals[i] : pump.getBits(12);
}
// First we figure out which reference pixels mode we're in
if (optflags & OptFlags::MV)
motion = pump.getBits(1) ? 3 : 7;
else if (!pump.getBits(1))
motion = pump.getBits(3);
if ((row == 0 || row == 1) && (motion != 7))
ThrowRDE("At start of image and motion isn't 7. File corrupted?");
if (motion == 7) {
// The base case, just set all pixels to the previous ones on the same
// line If we're at the left edge we just start at the initial value
for (uint32 i = 0; i < 16; i++)
img[i] = (col == 0) ? initVal : *(img + i - 2);
} else {
// The complex case, we now need to actually lookup one or two lines
// above
if (row < 2)
ThrowRDE(
"Got a previous line lookup on first two lines. File corrupted?");
static constexpr int32 motionOffset[7] = {-4, -2, -2, 0, 0, 2, 4};
static constexpr int32 motionDoAverage[7] = {0, 0, 1, 0, 1, 0, 0};
int32 slideOffset = motionOffset[motion];
int32 doAverage = motionDoAverage[motion];
for (uint32 i = 0; i < 16; i++) {
ushort16* refpixel;
if ((row + i) & 0x1) {
// Red or blue pixels use same color two lines up
refpixel = img_up2 + i + slideOffset;
if (col == 0 && img_up2 > refpixel)
ThrowRDE("Bad motion %u at the beginning of the row", motion);
} else {
// Green pixel N uses Green pixel N from row above
// (top left or top right)
refpixel = img_up + i + slideOffset + (((i % 2) != 0) ? -1 : 1);
if (col == 0 && img_up > refpixel)
ThrowRDE("Bad motion %u at the beginning of the row", motion);
}
// In some cases we use as reference interpolation of this pixel and
// the next
if (doAverage)
img[i] = (*refpixel + *(refpixel + 2) + 1) >> 1;
else
img[i] = *refpixel;
}
}
// Figure out how many difference bits we have to read for each pixel
uint32 diffBits[4] = {0};
if (optflags & OptFlags::SKIP || !pump.getBits(1)) {
uint32 flags[4];
for (unsigned int& flag : flags)
flag = pump.getBits(2);
for (uint32 i = 0; i < 4; i++) {
// The color is 0-Green 1-Blue 2-Red
uint32 colornum = (row % 2 != 0) ? i >> 1 : ((i >> 1) + 2) % 3;
assert(flags[i] <= 3);
switch (flags[i]) {
case 0:
diffBits[i] = diffBitsMode[colornum][0];
break;
case 1:
diffBits[i] = diffBitsMode[colornum][0] + 1;
break;
case 2:
diffBits[i] = diffBitsMode[colornum][0] - 1;
break;
case 3:
diffBits[i] = pump.getBits(4);
break;
default:
__builtin_unreachable();
}
diffBitsMode[colornum][0] = diffBitsMode[colornum][1];
diffBitsMode[colornum][1] = diffBits[i];
if (diffBits[i] > bitDepth + 1)
ThrowRDE("Too many difference bits. File corrupted?");
}
}
// Actually read the differences and write them to the pixels
for (uint32 i = 0; i < 16; i++) {
uint32 len = diffBits[i >> 2];
int32 diff = pump.getBits(len);
// If the first bit is 1 we need to turn this into a negative number
if (len != 0 && diff >> (len - 1))
diff -= (1 << len);
ushort16* value = nullptr;
// Apply the diff to pixels 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15
if (row % 2)
value = &img[((i & 0x7) << 1) + 1 - (i >> 3)];
else
value = &img[((i & 0x7) << 1) + (i >> 3)];
diff = diff * (scale * 2 + 1) + scale;
*value = clampBits(static_cast<int>(*value) + diff, bits);
}
img += 16;
img_up += 16;
img_up2 += 16;
}
data.skipBytes(pump.getBufferPosition());
}
} // namespace rawspeed
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: xihelper.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2003-11-05 13:41:45 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// ============================================================================
#ifndef SC_XIHELPER_HXX
#define SC_XIHELPER_HXX
#ifndef _MyEDITDATA_HXX
#include <svx/editdata.hxx>
#endif
#ifndef SC_XISTREAM_HXX
#include "xistream.hxx"
#endif
#ifndef SC_XIROOT_HXX
#include "xiroot.hxx"
#endif
class ScMatrix;
// Byte/Unicode strings =======================================================
/** This class represents an unformatted or formatted string and provides importing from stream. */
class XclImpString
{
private:
String maString; /// The text data of the string.
XclFormatRunVec maFormats; /// All formatting runs.
public:
/** Constructs an unformatted string. */
explicit XclImpString( const String& rString );
/** Constructs a formatted string by reading completely from stream. */
explicit XclImpString( XclImpStream& rStrm, XclStrFlags nFlags = EXC_STR_DEFAULT );
~XclImpString();
/** Insert a formatting run to the format buffer. */
void AppendFormat( sal_uInt16 nChar, sal_uInt16 nFontIx );
/** Reads and appends the formatting information (run count and runs) from stream. */
void ReadFormats( XclImpStream& rStrm );
/** Reads and appends nRunCount formatting runs from stream. */
void ReadFormats( XclImpStream& rStrm, sal_uInt16 nRunCount );
/** Returns the pure text data of the string. */
inline const String& GetText() const { return maString; }
/** Returns true, if the string contains formatting information. */
inline bool IsRich() const { return !maFormats.empty(); }
/** Returns the formatting run vector. */
inline const XclFormatRunVec& GetFormats() const { return maFormats; }
};
// String->EditEngine conversion ==============================================
class ScBaseCell;
class EditTextObject;
/** This class provides methods to convert an XclImpString.
@The string can be converted to an edit engine text object or directly
to a Calc edit cell. */
class XclImpStringHelper : ScfNoInstance
{
public:
/** Returns a new edit engine text object.
@param nXFIndex Index to XF for first text portion (for escapement). */
static EditTextObject* CreateTextObject(
const XclImpRoot& rRoot,
const XclImpString& rString,
sal_uInt32 nXFIndex = 0 );
/** Creates a new text cell or edit cell for a Calc document.
@param nXFIndex Index to XF for first text portion (for escapement). */
static ScBaseCell* CreateCell(
const XclImpRoot& rRoot,
const XclImpString& rString,
sal_uInt32 nXFIndex = 0 );
};
// Header/footer conversion ===================================================
class EditEngine;
class EditTextObject;
class SfxItemSet;
class SvxFieldItem;
struct XclFontData;
/** Converts an Excel header/footer string into three edit engine text objects.
@descr Header/footer content is divided into three parts: Left, center and
right portion. All formatting information is encoded in the Excel string
using special character seuences. A control sequence starts with the ampersand
character.
Supported control sequences:
&L start of left portion
&C start of center portion
&R start of right portion
&P current page number
&N page count
&D current date
&T current time
&A table name
&F file name without path (see also &Z&F)
&Z file path without file name (converted to full file name, see also &Z&F)
&Z&F file path and name
&U underlining on/off
&E double underlining on/off
&S strikeout characters on/off
&X superscript on/off
&Y subscript on/off
&"fontname,fontstyle" use font with name 'fontname' and style 'fontstyle'
&fontheight set font height in points ('fontheight' is a decimal value)
Known but unsupported control sequences:
&G picture
*/
class XclImpHFConverter : protected XclImpRoot, ScfNoCopy
{
private:
typedef ::std::auto_ptr< EditTextObject > EditTextObjectPtr;
typedef ::std::auto_ptr< XclFontData > XclFontDataPtr;
EditEngine& mrEE; /// The header/footer edit engine.
EditTextObjectPtr mppObjs[ 3 ]; /// Edit engine text objects for all portions.
ESelection mpSels[ 3 ]; /// Edit engine selections for all portions.
String maCurrText; /// Current text to insert into edit engine.
XclFontDataPtr mpFontData; /// Font data of current text.
sal_uInt16 mnCurrObj; /// The current portion.
public:
explicit XclImpHFConverter( const XclImpRoot& rRoot );
~XclImpHFConverter();
/** Parses the passed string and creates three new edit engine text objects. */
void ParseString( const String& rHFString );
/** Creates a ScPageHFItem and inserts it into the passed item set. */
void FillToItemSet( SfxItemSet& rItemSet, sal_uInt16 nWhichId );
private:
/** Returns the current edit engine text object. */
inline EditTextObjectPtr& GetCurrObj() { return mppObjs[ mnCurrObj ]; }
/** Returns the current selection. */
inline ESelection& GetCurrSel() { return mpSels[ mnCurrObj ]; }
/** Sets the font attributes at the current selection.
@descr After that, the start position of the current selection object is
adjusted to the end of the selection. */
void SetAttribs();
/** Resets font data to application default font. */
void ResetFontData();
/** Inserts maCurrText into edit engine and adjusts the current selection object.
@descr The text shall not contain a newline character.
The text will be cleared after insertion. */
void InsertText();
/** Inserts a line break and adjusts the current selection object. */
void InsertLineBreak();
/** Inserts the passed text field and adjusts the current selection object. */
void InsertField( const SvxFieldItem& rFieldItem );
/** Creates the edit engine text object of current portion from edit engine. */
void CreateCurrObject();
/** Changes current header/footer portion to eNew.
@descr Creates text object of current portion and reinitializes edit engine. */
void SetNewPortion( sal_uInt16 nNew );
};
// URL conversion =============================================================
/** This class contains static methods to decode an URL stored in an Excel file.
@descr Excel URLs can contain a sheet name, for instance: path\[test.xls]Sheet1
This sheet name will be extracted automatically. */
class XclImpUrlHelper : ScfNoInstance
{
public:
/** Decodes an encoded external document URL with optional sheet name.
@param rUrl Returns the decoded file name incl. path.
@param rTabName Returns the decoded sheet name.
@param rbSameWb Returns true, if the URL is a reference to the own workbook.
@param rEncodedUrl An encoded URL from Excel. */
static void DecodeUrl(
String& rUrl,
String& rTabName,
bool& rbSameWb,
const XclImpRoot& rRoot,
const String& rEncodedUrl );
/** Decodes an encoded external document URL without sheet name.
@param rUrl Returns the decoded file name incl. path.
@param rbSameWb Returns true, if the URL is a reference to the own workbook.
@param rEncodedUrl An encoded URL from Excel. */
static void DecodeUrl(
String& rUrl,
bool& rbSameWb,
const XclImpRoot& rRoot,
const String& rEncodedUrl );
/** Decodes the passed URL to OLE or DDE link components.
@descr For DDE links: Decodes to application name and topic.
For OLE object links: Decodes to class name and document URL.
@return true = decoding was successful, returned strings are valid (not empty). */
static bool DecodeLink( String& rApplic, String& rTopic, const String rEncUrl );
};
// Cached Values ==============================================================
class ScTokenArray;
/** This class stores one cached value of a cached value list (used for instance in
CRN, EXTERNNAME, tArray). */
class XclImpCachedValue : ScfNoCopy
{
protected:
typedef ::std::auto_ptr< String > StringPtr;
typedef ::std::auto_ptr< const ScTokenArray > ScTokenArrayPtr;
StringPtr mpStr; /// Cached value is a string.
double mfValue; /// Cached value is a double.
ScTokenArrayPtr mpTokArr; /// Cached value is a formula or error code or Boolean.
sal_uInt8 mnType; /// The type of the cached value (EXC_CACHEDVAL_*).
sal_uInt16 mnCol; /// Column index of the cached cell.
sal_uInt16 mnRow; /// Row index of the cached cell.
public:
/** Creates a cached value and reads contents from stream and stores it with its array address. */
XclImpCachedValue( XclImpStream& rStrm,
sal_uInt16 nCol,
sal_uInt16 nRow);
virtual ~XclImpCachedValue();
/** Returns the type of the cached value (EXC_CACHEDVAL_*). */
inline sal_uInt8 GetType() const { return mnType; }
/** Returns the cached string value, if this is a EXC_CACHEDVAL_STRING. */
inline const String* GetString() const { return mpStr.get(); }
/** Returns the cached double value if this is a EXC_CACHEDVAL_DOUBLE. */
inline double GetValue() const { return mfValue; }
/** Returns the token array if this is a Boolean value or error value. */
inline const ScTokenArray* GetTokArray() const { return mpTokArr.get(); }
inline sal_uInt16 GetCol() const { return mnCol; }
inline sal_uInt16 GetRow() const { return mnRow; }
};
class XclImpCachedMatrix
{
protected:
typedef ScfDelList< XclImpCachedValue > XclImpValueList;
XclImpValueList maValueList; /// List of cached cell values.
sal_uInt16 mnColumns; /// Number of cached columns.
sal_uInt16 mnRows; /// Number of cached rows.
public:
explicit XclImpCachedMatrix( sal_uInt16 nCols, sal_uInt16 nRows);
~XclImpCachedMatrix();
/** Copies the contents of our cached matrix into the ScMatrix. */
void FillMatrix(ScDocument &rDoc, ScMatrix *pMatrix) const ;
/** Stores the contents of an external referenced cell in the Value list. */
inline void AppendValue( XclImpCachedValue* pCachedValue ) { maValueList.Append( pCachedValue ); }
inline sal_uInt16 GetColumns() const { return mnColumns; }
inline sal_uInt16 GetRows() const { return mnRows; }
};
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS cac (1.4.42); FILE MERGED 2003/11/14 12:59:28 dr 1.4.42.2: RESYNC: (1.4-1.5); FILE MERGED 2003/11/03 14:35:08 dr 1.4.42.1: #i4070# use ScMatrix class directly<commit_after>/*************************************************************************
*
* $RCSfile: xihelper.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2004-03-08 11:52:05 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// ============================================================================
#ifndef SC_XIHELPER_HXX
#define SC_XIHELPER_HXX
#ifndef _MyEDITDATA_HXX
#include <svx/editdata.hxx>
#endif
#ifndef SC_MATRIX_HXX
#include "scmatrix.hxx"
#endif
#ifndef SC_XISTREAM_HXX
#include "xistream.hxx"
#endif
#ifndef SC_XIROOT_HXX
#include "xiroot.hxx"
#endif
class ScMatrix;
// Byte/Unicode strings =======================================================
/** This class represents an unformatted or formatted string and provides importing from stream. */
class XclImpString
{
private:
String maString; /// The text data of the string.
XclFormatRunVec maFormats; /// All formatting runs.
public:
/** Constructs an unformatted string. */
explicit XclImpString( const String& rString );
/** Constructs a formatted string by reading completely from stream. */
explicit XclImpString( XclImpStream& rStrm, XclStrFlags nFlags = EXC_STR_DEFAULT );
~XclImpString();
/** Insert a formatting run to the format buffer. */
void AppendFormat( sal_uInt16 nChar, sal_uInt16 nFontIx );
/** Reads and appends the formatting information (run count and runs) from stream. */
void ReadFormats( XclImpStream& rStrm );
/** Reads and appends nRunCount formatting runs from stream. */
void ReadFormats( XclImpStream& rStrm, sal_uInt16 nRunCount );
/** Returns the pure text data of the string. */
inline const String& GetText() const { return maString; }
/** Returns true, if the string contains formatting information. */
inline bool IsRich() const { return !maFormats.empty(); }
/** Returns the formatting run vector. */
inline const XclFormatRunVec& GetFormats() const { return maFormats; }
};
// String->EditEngine conversion ==============================================
class ScBaseCell;
class EditTextObject;
/** This class provides methods to convert an XclImpString.
@The string can be converted to an edit engine text object or directly
to a Calc edit cell. */
class XclImpStringHelper : ScfNoInstance
{
public:
/** Returns a new edit engine text object.
@param nXFIndex Index to XF for first text portion (for escapement). */
static EditTextObject* CreateTextObject(
const XclImpRoot& rRoot,
const XclImpString& rString,
sal_uInt32 nXFIndex = 0 );
/** Creates a new text cell or edit cell for a Calc document.
@param nXFIndex Index to XF for first text portion (for escapement). */
static ScBaseCell* CreateCell(
const XclImpRoot& rRoot,
const XclImpString& rString,
sal_uInt32 nXFIndex = 0 );
};
// Header/footer conversion ===================================================
class EditEngine;
class EditTextObject;
class SfxItemSet;
class SvxFieldItem;
struct XclFontData;
/** Converts an Excel header/footer string into three edit engine text objects.
@descr Header/footer content is divided into three parts: Left, center and
right portion. All formatting information is encoded in the Excel string
using special character seuences. A control sequence starts with the ampersand
character.
Supported control sequences:
&L start of left portion
&C start of center portion
&R start of right portion
&P current page number
&N page count
&D current date
&T current time
&A table name
&F file name without path (see also &Z&F)
&Z file path without file name (converted to full file name, see also &Z&F)
&Z&F file path and name
&U underlining on/off
&E double underlining on/off
&S strikeout characters on/off
&X superscript on/off
&Y subscript on/off
&"fontname,fontstyle" use font with name 'fontname' and style 'fontstyle'
&fontheight set font height in points ('fontheight' is a decimal value)
Known but unsupported control sequences:
&G picture
*/
class XclImpHFConverter : protected XclImpRoot, ScfNoCopy
{
private:
typedef ::std::auto_ptr< EditTextObject > EditTextObjectPtr;
typedef ::std::auto_ptr< XclFontData > XclFontDataPtr;
EditEngine& mrEE; /// The header/footer edit engine.
EditTextObjectPtr mppObjs[ 3 ]; /// Edit engine text objects for all portions.
ESelection mpSels[ 3 ]; /// Edit engine selections for all portions.
String maCurrText; /// Current text to insert into edit engine.
XclFontDataPtr mpFontData; /// Font data of current text.
sal_uInt16 mnCurrObj; /// The current portion.
public:
explicit XclImpHFConverter( const XclImpRoot& rRoot );
~XclImpHFConverter();
/** Parses the passed string and creates three new edit engine text objects. */
void ParseString( const String& rHFString );
/** Creates a ScPageHFItem and inserts it into the passed item set. */
void FillToItemSet( SfxItemSet& rItemSet, sal_uInt16 nWhichId );
private:
/** Returns the current edit engine text object. */
inline EditTextObjectPtr& GetCurrObj() { return mppObjs[ mnCurrObj ]; }
/** Returns the current selection. */
inline ESelection& GetCurrSel() { return mpSels[ mnCurrObj ]; }
/** Sets the font attributes at the current selection.
@descr After that, the start position of the current selection object is
adjusted to the end of the selection. */
void SetAttribs();
/** Resets font data to application default font. */
void ResetFontData();
/** Inserts maCurrText into edit engine and adjusts the current selection object.
@descr The text shall not contain a newline character.
The text will be cleared after insertion. */
void InsertText();
/** Inserts a line break and adjusts the current selection object. */
void InsertLineBreak();
/** Inserts the passed text field and adjusts the current selection object. */
void InsertField( const SvxFieldItem& rFieldItem );
/** Creates the edit engine text object of current portion from edit engine. */
void CreateCurrObject();
/** Changes current header/footer portion to eNew.
@descr Creates text object of current portion and reinitializes edit engine. */
void SetNewPortion( sal_uInt16 nNew );
};
// URL conversion =============================================================
/** This class contains static methods to decode an URL stored in an Excel file.
@descr Excel URLs can contain a sheet name, for instance: path\[test.xls]Sheet1
This sheet name will be extracted automatically. */
class XclImpUrlHelper : ScfNoInstance
{
public:
/** Decodes an encoded external document URL with optional sheet name.
@param rUrl Returns the decoded file name incl. path.
@param rTabName Returns the decoded sheet name.
@param rbSameWb Returns true, if the URL is a reference to the own workbook.
@param rEncodedUrl An encoded URL from Excel. */
static void DecodeUrl(
String& rUrl,
String& rTabName,
bool& rbSameWb,
const XclImpRoot& rRoot,
const String& rEncodedUrl );
/** Decodes an encoded external document URL without sheet name.
@param rUrl Returns the decoded file name incl. path.
@param rbSameWb Returns true, if the URL is a reference to the own workbook.
@param rEncodedUrl An encoded URL from Excel. */
static void DecodeUrl(
String& rUrl,
bool& rbSameWb,
const XclImpRoot& rRoot,
const String& rEncodedUrl );
/** Decodes the passed URL to OLE or DDE link components.
@descr For DDE links: Decodes to application name and topic.
For OLE object links: Decodes to class name and document URL.
@return true = decoding was successful, returned strings are valid (not empty). */
static bool DecodeLink( String& rApplic, String& rTopic, const String rEncUrl );
};
// Cached Values ==============================================================
class ScTokenArray;
/** This class stores one cached value of a cached value list (used for instance in
CRN, EXTERNNAME, tArray). */
class XclImpCachedValue : ScfNoCopy
{
protected:
typedef ::std::auto_ptr< String > StringPtr;
typedef ::std::auto_ptr< const ScTokenArray > ScTokenArrayPtr;
StringPtr mpStr; /// Cached value is a string.
double mfValue; /// Cached value is a double.
ScTokenArrayPtr mpTokArr; /// Cached value is a formula or error code or Boolean.
sal_uInt8 mnBoolErr; /// Boolean value or Excel error code.
sal_uInt8 mnType; /// The type of the cached value (EXC_CACHEDVAL_*).
public:
/** Creates a cached value and reads contents from stream and stores it with its array address. */
explicit XclImpCachedValue( XclImpStream& rStrm );
virtual ~XclImpCachedValue();
/** Returns the type of the cached value (EXC_CACHEDVAL_*). */
inline sal_uInt8 GetType() const { return mnType; }
/** Returns the cached string value, if this value is a string, else an empty string. */
inline const String& GetString() const { return mpStr.get() ? *mpStr : EMPTY_STRING; }
/** Returns the cached number, if this value has number type, else 0.0. */
inline double GetValue() const { return mfValue; }
/** Returns the cached Boolean value, if this value has Boolean type, else false. */
inline bool GetBool() const { return (mnType == EXC_CACHEDVAL_BOOL) && (mnBoolErr != 0); }
/** Returns the cached Calc error code, if this value has Error type, else 0. */
USHORT GetError() const;
/** Returns the token array if this is a Boolean value or error value, else 0. */
inline const ScTokenArray* GetBoolErrFmla() const { return mpTokArr.get(); }
};
// ----------------------------------------------------------------------------
/** Contains cached values in a 2-dimensional array. */
class XclImpCachedMatrix
{
public:
explicit XclImpCachedMatrix( XclImpStream& rStrm );
~XclImpCachedMatrix();
/** Creates a new ScMatrix object and fills it with the contained values. */
ScMatrixRef CreateScMatrix() const;
private:
typedef ScfDelList< XclImpCachedValue > XclImpValueList;
XclImpValueList maValueList; /// List of cached cell values.
USHORT mnScCols; /// Number of cached columns.
USHORT mnScRows; /// Number of cached rows.
};
// ============================================================================
#endif
<|endoftext|>
|
<commit_before><commit_msg>More reduction of scoping inside for loop.<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlsorti.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: kz $ $Date: 2006-07-21 12:54:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include "xmlsorti.hxx"
#include "xmlimprt.hxx"
#include "docuno.hxx"
#ifndef SC_CONVUNO_HXX
#include "convuno.hxx"
#endif
#ifndef _SC_XMLCONVERTER_HXX
#include "XMLConverter.hxx"
#endif
#ifndef SC_UNONAMES_HXX
#include "unonames.hxx"
#endif
#include <xmloff/xmltkmap.hxx>
#include <xmloff/nmspmap.hxx>
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#define SC_USERLIST "UserList"
using namespace com::sun::star;
using namespace xmloff::token;
//------------------------------------------------------------------
ScXMLSortContext::ScXMLSortContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) :
SvXMLImportContext( rImport, nPrfx, rLName ),
bEnabledUserList(sal_False),
bBindFormatsToContent(sal_True),
bIsCaseSensitive(sal_False),
bCopyOutputData(sal_False),
sCountry(),
sLanguage(),
sAlgorithm(),
pDatabaseRangeContext(pTempDatabaseRangeContext),
nUserListIndex(0)
{
sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0);
const SvXMLTokenMap& rAttrTokenMap(GetScImport().GetSortAttrTokenMap());
for( sal_Int16 i=0; i < nAttrCount; ++i )
{
const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i ));
rtl::OUString aLocalName;
USHORT nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName ));
const rtl::OUString& sValue(xAttrList->getValueByIndex( i ));
switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
{
case XML_TOK_SORT_ATTR_BIND_STYLES_TO_CONTENT :
{
bBindFormatsToContent = IsXMLToken(sValue, XML_TRUE);
}
break;
case XML_TOK_SORT_ATTR_TARGET_RANGE_ADDRESS :
{
ScRange aScRange;
sal_Int32 nOffset(0);
if (ScXMLConverter::GetRangeFromString( aScRange, sValue, GetScImport().GetDocument(), nOffset ))
{
ScUnoConversion::FillApiAddress( aOutputPosition, aScRange.aStart );
bCopyOutputData = sal_True;
}
}
break;
case XML_TOK_SORT_ATTR_CASE_SENSITIVE :
{
bIsCaseSensitive = IsXMLToken(sValue, XML_TRUE);
}
break;
case XML_TOK_SORT_ATTR_LANGUAGE :
sLanguage = sValue;
break;
case XML_TOK_SORT_ATTR_COUNTRY :
sCountry = sValue;
break;
case XML_TOK_SORT_ATTR_ALGORITHM :
sAlgorithm = sValue;
break;
}
}
}
ScXMLSortContext::~ScXMLSortContext()
{
}
SvXMLImportContext *ScXMLSortContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext(0);
const SvXMLTokenMap& rTokenMap(GetScImport().GetSortElemTokenMap());
switch( rTokenMap.Get( nPrefix, rLName ) )
{
case XML_TOK_SORT_SORT_BY :
{
pContext = new ScXMLSortByContext( GetScImport(), nPrefix,
rLName, xAttrList, this);
}
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );
return pContext;
}
void ScXMLSortContext::EndElement()
{
sal_Int32 nLangLength(sLanguage.getLength());
sal_Int32 nCountryLength(sCountry.getLength());
sal_Int32 nAlgoLength(sAlgorithm.getLength());
sal_uInt8 i (0);
if (nLangLength || nCountryLength)
++i;
if (nAlgoLength)
++i;
uno::Sequence <beans::PropertyValue> aSortDescriptor(7 + i);
aSortDescriptor[0].Name = rtl::OUString::createFromAscii(SC_UNONAME_BINDFMT);
aSortDescriptor[0].Value = ::cppu::bool2any(bBindFormatsToContent);
aSortDescriptor[1].Name = rtl::OUString::createFromAscii(SC_UNONAME_COPYOUT);
aSortDescriptor[1].Value = ::cppu::bool2any(bCopyOutputData);
aSortDescriptor[2].Name = rtl::OUString::createFromAscii(SC_UNONAME_ISCASE);
aSortDescriptor[2].Value = ::cppu::bool2any(bIsCaseSensitive);
aSortDescriptor[3].Name = rtl::OUString::createFromAscii(SC_UNONAME_ISULIST);
aSortDescriptor[3].Value = ::cppu::bool2any(bEnabledUserList);
aSortDescriptor[4].Name = rtl::OUString::createFromAscii(SC_UNONAME_OUTPOS);
aSortDescriptor[4].Value <<= aOutputPosition;
aSortDescriptor[5].Name = rtl::OUString::createFromAscii(SC_UNONAME_UINDEX);
aSortDescriptor[5].Value <<= nUserListIndex;
aSortDescriptor[6].Name = rtl::OUString::createFromAscii(SC_UNONAME_SORTFLD);
aSortDescriptor[6].Value <<= aSortFields;
if (nLangLength || nCountryLength)
{
lang::Locale aLocale;
aLocale.Language = sLanguage;
aLocale.Country = sCountry;
aSortDescriptor[7].Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_COLLLOC));
aSortDescriptor[7].Value <<= aLocale;
}
if (nAlgoLength)
{
aSortDescriptor[6 + i].Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_COLLALG));
aSortDescriptor[6 + i].Value <<= sAlgorithm;
}
pDatabaseRangeContext->SetSortSequence(aSortDescriptor);
}
void ScXMLSortContext::AddSortField(const rtl::OUString& sFieldNumber, const rtl::OUString& sDataType, const rtl::OUString& sOrder)
{
util::SortField aSortField;
aSortField.Field = sFieldNumber.toInt32();
if (IsXMLToken(sOrder, XML_ASCENDING))
aSortField.SortAscending = sal_True;
else
aSortField.SortAscending = sal_False;
if (sDataType.getLength() > 8)
{
rtl::OUString sTemp = sDataType.copy(0, 8);
if (sTemp.compareToAscii(SC_USERLIST) == 0)
{
bEnabledUserList = sal_True;
sTemp = sDataType.copy(8);
nUserListIndex = static_cast<sal_Int16>(sTemp.toInt32());
}
else
{
if (IsXMLToken(sDataType, XML_AUTOMATIC))
aSortField.FieldType = util::SortFieldType_AUTOMATIC;
}
}
else
{
if (IsXMLToken(sDataType, XML_TEXT))
aSortField.FieldType = util::SortFieldType_ALPHANUMERIC;
else if (IsXMLToken(sDataType, XML_NUMBER))
aSortField.FieldType = util::SortFieldType_NUMERIC;
}
aSortFields.realloc(aSortFields.getLength() + 1);
aSortFields[aSortFields.getLength() - 1] = aSortField;
}
ScXMLSortByContext::ScXMLSortByContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
ScXMLSortContext* pTempSortContext) :
SvXMLImportContext( rImport, nPrfx, rLName ),
sOrder(GetXMLToken(XML_ASCENDING)),
sDataType(GetXMLToken(XML_AUTOMATIC)),
pSortContext(pTempSortContext)
{
sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0);
const SvXMLTokenMap& rAttrTokenMap(GetScImport().GetSortSortByAttrTokenMap());
for( sal_Int16 i=0; i < nAttrCount; ++i )
{
const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i ));
rtl::OUString aLocalName;
USHORT nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName ));
const rtl::OUString& sValue(xAttrList->getValueByIndex( i ));
switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
{
case XML_TOK_SORT_BY_ATTR_FIELD_NUMBER :
{
sFieldNumber = sValue;
}
break;
case XML_TOK_SORT_BY_ATTR_DATA_TYPE :
{
sDataType = sValue;
}
break;
case XML_TOK_SORT_BY_ATTR_ORDER :
{
sOrder = sValue;
}
break;
}
}
}
ScXMLSortByContext::~ScXMLSortByContext()
{
}
SvXMLImportContext *ScXMLSortByContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
return new SvXMLImportContext( GetImport(), nPrefix, rLName );
}
void ScXMLSortByContext::EndElement()
{
pSortContext->AddSortField(sFieldNumber, sDataType, sOrder);
}
<commit_msg>INTEGRATION: CWS calcwarnings (1.15.108); FILE MERGED 2006/12/13 10:30:19 nn 1.15.108.2: #i69284# warning-free: filter/xml, unxlngi6 2006/12/01 13:29:20 nn 1.15.108.1: #i69284# warning-free: filter/xml, wntmsci10<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlsorti.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: vg $ $Date: 2007-02-27 12:52:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include "xmlsorti.hxx"
#include "xmlimprt.hxx"
#include "docuno.hxx"
#ifndef SC_CONVUNO_HXX
#include "convuno.hxx"
#endif
#ifndef _SC_XMLCONVERTER_HXX
#include "XMLConverter.hxx"
#endif
#ifndef SC_UNONAMES_HXX
#include "unonames.hxx"
#endif
#include <xmloff/xmltkmap.hxx>
#include <xmloff/nmspmap.hxx>
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#define SC_USERLIST "UserList"
using namespace com::sun::star;
using namespace xmloff::token;
//------------------------------------------------------------------
ScXMLSortContext::ScXMLSortContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) :
SvXMLImportContext( rImport, nPrfx, rLName ),
pDatabaseRangeContext(pTempDatabaseRangeContext),
sCountry(),
sLanguage(),
sAlgorithm(),
nUserListIndex(0),
bCopyOutputData(sal_False),
bBindFormatsToContent(sal_True),
bIsCaseSensitive(sal_False),
bEnabledUserList(sal_False)
{
sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0);
const SvXMLTokenMap& rAttrTokenMap(GetScImport().GetSortAttrTokenMap());
for( sal_Int16 i=0; i < nAttrCount; ++i )
{
const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i ));
rtl::OUString aLocalName;
USHORT nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName ));
const rtl::OUString& sValue(xAttrList->getValueByIndex( i ));
switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
{
case XML_TOK_SORT_ATTR_BIND_STYLES_TO_CONTENT :
{
bBindFormatsToContent = IsXMLToken(sValue, XML_TRUE);
}
break;
case XML_TOK_SORT_ATTR_TARGET_RANGE_ADDRESS :
{
ScRange aScRange;
sal_Int32 nOffset(0);
if (ScXMLConverter::GetRangeFromString( aScRange, sValue, GetScImport().GetDocument(), nOffset ))
{
ScUnoConversion::FillApiAddress( aOutputPosition, aScRange.aStart );
bCopyOutputData = sal_True;
}
}
break;
case XML_TOK_SORT_ATTR_CASE_SENSITIVE :
{
bIsCaseSensitive = IsXMLToken(sValue, XML_TRUE);
}
break;
case XML_TOK_SORT_ATTR_LANGUAGE :
sLanguage = sValue;
break;
case XML_TOK_SORT_ATTR_COUNTRY :
sCountry = sValue;
break;
case XML_TOK_SORT_ATTR_ALGORITHM :
sAlgorithm = sValue;
break;
}
}
}
ScXMLSortContext::~ScXMLSortContext()
{
}
SvXMLImportContext *ScXMLSortContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext(0);
const SvXMLTokenMap& rTokenMap(GetScImport().GetSortElemTokenMap());
switch( rTokenMap.Get( nPrefix, rLName ) )
{
case XML_TOK_SORT_SORT_BY :
{
pContext = new ScXMLSortByContext( GetScImport(), nPrefix,
rLName, xAttrList, this);
}
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );
return pContext;
}
void ScXMLSortContext::EndElement()
{
sal_Int32 nLangLength(sLanguage.getLength());
sal_Int32 nCountryLength(sCountry.getLength());
sal_Int32 nAlgoLength(sAlgorithm.getLength());
sal_uInt8 i (0);
if (nLangLength || nCountryLength)
++i;
if (nAlgoLength)
++i;
uno::Sequence <beans::PropertyValue> aSortDescriptor(7 + i);
aSortDescriptor[0].Name = rtl::OUString::createFromAscii(SC_UNONAME_BINDFMT);
aSortDescriptor[0].Value = ::cppu::bool2any(bBindFormatsToContent);
aSortDescriptor[1].Name = rtl::OUString::createFromAscii(SC_UNONAME_COPYOUT);
aSortDescriptor[1].Value = ::cppu::bool2any(bCopyOutputData);
aSortDescriptor[2].Name = rtl::OUString::createFromAscii(SC_UNONAME_ISCASE);
aSortDescriptor[2].Value = ::cppu::bool2any(bIsCaseSensitive);
aSortDescriptor[3].Name = rtl::OUString::createFromAscii(SC_UNONAME_ISULIST);
aSortDescriptor[3].Value = ::cppu::bool2any(bEnabledUserList);
aSortDescriptor[4].Name = rtl::OUString::createFromAscii(SC_UNONAME_OUTPOS);
aSortDescriptor[4].Value <<= aOutputPosition;
aSortDescriptor[5].Name = rtl::OUString::createFromAscii(SC_UNONAME_UINDEX);
aSortDescriptor[5].Value <<= nUserListIndex;
aSortDescriptor[6].Name = rtl::OUString::createFromAscii(SC_UNONAME_SORTFLD);
aSortDescriptor[6].Value <<= aSortFields;
if (nLangLength || nCountryLength)
{
lang::Locale aLocale;
aLocale.Language = sLanguage;
aLocale.Country = sCountry;
aSortDescriptor[7].Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_COLLLOC));
aSortDescriptor[7].Value <<= aLocale;
}
if (nAlgoLength)
{
aSortDescriptor[6 + i].Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_COLLALG));
aSortDescriptor[6 + i].Value <<= sAlgorithm;
}
pDatabaseRangeContext->SetSortSequence(aSortDescriptor);
}
void ScXMLSortContext::AddSortField(const rtl::OUString& sFieldNumber, const rtl::OUString& sDataType, const rtl::OUString& sOrder)
{
util::SortField aSortField;
aSortField.Field = sFieldNumber.toInt32();
if (IsXMLToken(sOrder, XML_ASCENDING))
aSortField.SortAscending = sal_True;
else
aSortField.SortAscending = sal_False;
if (sDataType.getLength() > 8)
{
rtl::OUString sTemp = sDataType.copy(0, 8);
if (sTemp.compareToAscii(SC_USERLIST) == 0)
{
bEnabledUserList = sal_True;
sTemp = sDataType.copy(8);
nUserListIndex = static_cast<sal_Int16>(sTemp.toInt32());
}
else
{
if (IsXMLToken(sDataType, XML_AUTOMATIC))
aSortField.FieldType = util::SortFieldType_AUTOMATIC;
}
}
else
{
if (IsXMLToken(sDataType, XML_TEXT))
aSortField.FieldType = util::SortFieldType_ALPHANUMERIC;
else if (IsXMLToken(sDataType, XML_NUMBER))
aSortField.FieldType = util::SortFieldType_NUMERIC;
}
aSortFields.realloc(aSortFields.getLength() + 1);
aSortFields[aSortFields.getLength() - 1] = aSortField;
}
ScXMLSortByContext::ScXMLSortByContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
ScXMLSortContext* pTempSortContext) :
SvXMLImportContext( rImport, nPrfx, rLName ),
pSortContext(pTempSortContext),
sDataType(GetXMLToken(XML_AUTOMATIC)),
sOrder(GetXMLToken(XML_ASCENDING))
{
sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0);
const SvXMLTokenMap& rAttrTokenMap(GetScImport().GetSortSortByAttrTokenMap());
for( sal_Int16 i=0; i < nAttrCount; ++i )
{
const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i ));
rtl::OUString aLocalName;
USHORT nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName ));
const rtl::OUString& sValue(xAttrList->getValueByIndex( i ));
switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
{
case XML_TOK_SORT_BY_ATTR_FIELD_NUMBER :
{
sFieldNumber = sValue;
}
break;
case XML_TOK_SORT_BY_ATTR_DATA_TYPE :
{
sDataType = sValue;
}
break;
case XML_TOK_SORT_BY_ATTR_ORDER :
{
sOrder = sValue;
}
break;
}
}
}
ScXMLSortByContext::~ScXMLSortByContext()
{
}
SvXMLImportContext *ScXMLSortByContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& /* xAttrList */ )
{
return new SvXMLImportContext( GetImport(), nPrefix, rLName );
}
void ScXMLSortByContext::EndElement()
{
pSortContext->AddSortField(sFieldNumber, sDataType, sOrder);
}
<|endoftext|>
|
<commit_before><commit_msg>Separate method for code that determins glue state from referenced cells.<commit_after><|endoftext|>
|
<commit_before>// -*-c++-*-
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/CullFace>
#include <osg/ImageStream>
#include <osgGA/TrackballManipulator>
osg::ImageStream* s_imageStream = 0;
class PostSwapFinishCallback : public Producer::Camera::Callback
{
public:
PostSwapFinishCallback() {}
virtual void operator()(const Producer::Camera& camera)
{
// osg::Timer_t start_tick = osg::Timer::instance()->tick();
osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler()));
if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState()));
// glFinish();
//osg::notify(osg::NOTICE)<<"callback after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
}
};
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler() {}
void set(osg::Node* node);
virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
};
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='s')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
return true;
}
else if (ea.getKey()=='r')
{
return true;
}
else if (ea.getKey()=='l')
{
return true;
}
return false;
}
default:
return false;
}
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Pause movie");
usage.addKeyboardMouseBinding("s","Play movie");
usage.addKeyboardMouseBinding("r","Start movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
osg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image)
{
bool useTextureRectangle = true;
if (useTextureRectangle)
{
osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,image->t(), image->s(),0.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::TextureRectangle(image),
osg::StateAttribute::ON);
return pictureQuad;
}
else
{
osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,0.0f, 1.0f,1.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::Texture2D(image),
osg::StateAttribute::ON);
return pictureQuad;
}
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// register the handler to add keyboard and mosue handling.
MovieEventHandler* meh = new MovieEventHandler();
viewer.getEventHandlerList().push_front(meh);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
osg::Vec3 pos(0.0f,0.0f,0.0f);
for(int i=1;i<arguments.argc();++i)
{
if (arguments.isString(i))
{
osg::Image* image = osgDB::readImageFile(arguments[i]);
osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image);
if (imagestream) imagestream->play();
if (image)
{
geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image));
geode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
pos.z() += image->t()*1.5f;
}
else
{
std::cout<<"Unable to read file "<<arguments[i]<<std::endl;
}
}
}
if (geode->getNumDrawables()==0)
{
// nothing loaded.
return 1;
}
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
meh->set(geode.get());
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
}
/*
// set up a post swap callback to flush deleted GL objects and compile new GL objects
for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum)
{
Producer::Camera* camera=viewer.getCamera(cameraNum);
camera->addPostSwapCallback(new PostSwapFinishCallback());
}
*/
// set the scene to render
viewer.setSceneData(geode.get());
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<commit_msg>Added experiment GLSL fragment shader to clip out dark areas of videos.<commit_after>// -*-c++-*-
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/CullFace>
#include <osg/ImageStream>
#include <osgGA/TrackballManipulator>
osg::ImageStream* s_imageStream = 0;
class PostSwapFinishCallback : public Producer::Camera::Callback
{
public:
PostSwapFinishCallback() {}
virtual void operator()(const Producer::Camera& camera)
{
// osg::Timer_t start_tick = osg::Timer::instance()->tick();
osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler()));
if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState()));
// glFinish();
//osg::notify(osg::NOTICE)<<"callback after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
}
};
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler() {}
void set(osg::Node* node);
virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
};
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='s')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
return true;
}
else if (ea.getKey()=='r')
{
return true;
}
else if (ea.getKey()=='l')
{
return true;
}
return false;
}
default:
return false;
}
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Pause movie");
usage.addKeyboardMouseBinding("s","Play movie");
usage.addKeyboardMouseBinding("r","Start movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
osg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image, bool useTextureRectangle)
{
if (useTextureRectangle)
{
osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,image->t(), image->s(),0.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::TextureRectangle(image),
osg::StateAttribute::ON);
return pictureQuad;
}
else
{
osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,1.0f, 1.0f,0.0f);
osg::Texture2D* texture = new osg::Texture2D(image);
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
texture,
osg::StateAttribute::ON);
return pictureQuad;
}
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
bool useTextureRectangle = true;
bool useShader = false;
// construct the viewer.
osgProducer::Viewer viewer(arguments);
while (arguments.read("--texture2D")) useTextureRectangle=false;
while (arguments.read("--shader")) useShader=true;
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// register the handler to add keyboard and mosue handling.
MovieEventHandler* meh = new MovieEventHandler();
viewer.getEventHandlerList().push_front(meh);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
osg::Vec3 pos(0.0f,0.0f,0.0f);
osg::StateSet* stateset = geode->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
if (useShader)
{
//useTextureRectangle = false;
static const char *shaderSource = {
"uniform vec4 cutoff_color;\n"
"uniform samplerRect movie_texture;"
"void main(void)\n"
"{\n"
" vec4 texture_color = textureRect(movie_texture, gl_TexCoord[0]); \n"
" if (all(lessThanEqual(texture_color,cutoff_color))) discard; \n"
" gl_FragColor = texture_color;\n"
"}\n"
};
osg::Program* program = new osg::Program;
program->addShader(new osg::Shader(osg::Shader::FRAGMENT,shaderSource));
stateset->addUniform(new osg::Uniform("cutoff_color",osg::Vec4(0.1f,0.1f,0.1f,1.0f)));
stateset->addUniform(new osg::Uniform("movie_texture",0));
stateset->setAttribute(program);
}
for(int i=1;i<arguments.argc();++i)
{
if (arguments.isString(i))
{
osg::Image* image = osgDB::readImageFile(arguments[i]);
osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image);
if (imagestream) imagestream->play();
if (image)
{
geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image, useTextureRectangle));
pos.z() += image->t()*1.5f;
}
else
{
std::cout<<"Unable to read file "<<arguments[i]<<std::endl;
}
}
}
if (geode->getNumDrawables()==0)
{
// nothing loaded.
return 1;
}
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
meh->set(geode.get());
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
}
/*
// set up a post swap callback to flush deleted GL objects and compile new GL objects
for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum)
{
Producer::Camera* camera=viewer.getCamera(cameraNum);
camera->addPostSwapCallback(new PostSwapFinishCallback());
}
*/
// set the scene to render
viewer.setSceneData(geode.get());
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<|endoftext|>
|
<commit_before>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
//
// Simple example of use of Producer::RenderSurface to create an OpenGL
// graphics window, and OSG for rendering.
#include <Producer/RenderSurface>
#include <osg/Timer>
#include <osgUtil/SceneView>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgProducer/Viewer>
#include <sstream>
#define MIN_NEARFAROFFSET 0.1
class SliceProcessor
{
public:
SliceProcessor() : _sliceNumber(128), _sliceDelta(0.1), _nearPlane(0.0), _farPlane(MIN_NEARFAROFFSET)
{
//
}
SliceProcessor( const double& objectRadius, unsigned int numberSlices) : _sliceNumber(numberSlices)
{
_sliceDelta = (objectRadius*2) / _sliceNumber;
_nearPlane = objectRadius; // note: distance from viewpoint is going to be set 2x radius
_farPlane = _nearPlane+MIN_NEARFAROFFSET;
_image = new osg::Image;
if( _sliceDelta > MIN_NEARFAROFFSET )
{
_nearFarOffset = MIN_NEARFAROFFSET;
}
else
{
_nearFarOffset = _sliceDelta;
}
_image->allocateImage( _sliceNumber, _sliceNumber,_sliceNumber, GL_RGBA, GL_UNSIGNED_BYTE );
}
// needs 3D-Texture object
osg::Image* _image;
unsigned int _sliceNumber;
double _sliceDelta;
double _nearPlane;
double _farPlane;
double _nearFarOffset;
// needs function to do rendering and slicing
};
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of osg::AnimationPath and UpdateCallbacks for adding animation to your scenes.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("-o <filename>","Object to be loaded");
if( arguments.read( "-h" ) || arguments.read( "--help" ) )
{
std::cout << "Argumentlist:" << std::endl;
std::cout << "\t-o <filename> sets object to be loaded and sliced" << std::endl;
std::cout << "\t--slices <unsigned int> sets number of slices through the object" << std::endl;
std::cout << "\t--near <double> sets start for near clipping plane" << std::endl;
std::cout << "\t--far <double> sets start for far clipping plane" << std::endl;
return 1;
}
std::string outputName("volume_tex.dds");
while( arguments.read( "-o", outputName ) ) { }
unsigned int numberSlices = 128;
while( arguments.read( "--slices", numberSlices) ) { }
double nearClip=0.0f;
double farClip=0.0f;
while( arguments.read( "--near",nearClip ) ) { }
while( arguments.read( "--far", farClip) ) { }
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles( arguments );
if (!loadedModel)
{
std::cout << "No data loaded." << std::endl;
return 1;
}
const osg::BoundingSphere& bs = loadedModel->getBound();
SliceProcessor* sp = new SliceProcessor( (double)bs.radius(), numberSlices );
if (nearClip!=0.0) sp->_nearPlane = nearClip;
if (farClip!=0.0) sp->_farPlane = farClip;
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
// create the window to draw to.
osg::ref_ptr<Producer::RenderSurface> renderSurface = new Producer::RenderSurface;
renderSurface->setWindowName("osgsimple");
renderSurface->setWindowRectangle(100,100,numberSlices,numberSlices);
renderSurface->useBorder(true);
// make sure we have a alpha channel in the colour buffer, to enable
// alpha on read back.
Producer::VisualChooser* rs_vc = renderSurface->getVisualChooser();
if (!rs_vc)
{
rs_vc = new Producer::VisualChooser;
rs_vc->setSimpleConfiguration();
renderSurface->setVisualChooser(rs_vc);
}
rs_vc->setAlphaSize(8);
// create the graphics context.
renderSurface->realize();
// create the view of the scene.
osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
sceneView->setDefaults();
sceneView->setSceneData(loadedModel.get());
// initialize the view to look at the center of the scene graph
osg::Matrix viewMatrix;
// distance from viewport to object's center is set to be 2x bs.radius()
viewMatrix.makeLookAt(bs.center()-osg::Vec3(0.0,2.0f*bs.radius(),0.0),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
// turn off autocompution of near and far clipping planes
sceneView->setComputeNearFarMode(osgUtil::CullVisitor::DO_NOT_COMPUTE_NEAR_FAR);
// set the clear color of the background to make sure that the alpha is 0.0.
sceneView->setClearColor(osg::Vec4(0.0f,0.0f,0.0f,0.0f));
// record the timer tick at the start of rendering.
osg::Timer_t start_tick = osg::Timer::instance()->tick();
std::cout << "radius: " << bs.radius() << std::endl;
unsigned int frameNum = 0;
double tmpNear, tmpFar;
std::string baseImageName("shot_");
std::string tmpImageName;
osg::Image* tmpImage = new osg::Image;
// main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
for( unsigned int i = 0 ; i < sp->_sliceNumber && renderSurface->isRealized() ; ++i )
{
// set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly
osg::ref_ptr<osg::FrameStamp> frameStamp = new osg::FrameStamp;
frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,osg::Timer::instance()->tick()));
frameStamp->setFrameNumber(frameNum++);
// pass frame stamp to the SceneView so that the update, cull and draw traversals all use the same FrameStamp
sceneView->setFrameStamp(frameStamp.get());
// update the viewport dimensions, incase the window has been resized.
sceneView->setViewport(0,0,renderSurface->getWindowWidth(),renderSurface->getWindowHeight());
// set the view
sceneView->setViewMatrix(viewMatrix);
// set Projection Matrix
tmpNear = sp->_nearPlane+i*sp->_sliceDelta;
tmpFar = sp->_farPlane+(i*sp->_sliceDelta)+sp->_nearFarOffset;
sceneView->setProjectionMatrixAsOrtho(-(bs.radius()+bs.radius()/2), bs.radius()+bs.radius()/2,-bs.radius(), bs.radius(), tmpNear, tmpFar);
// do the update traversal the scene graph - such as updating animations
sceneView->update();
// do the cull traversal, collect all objects in the view frustum into a sorted set of rendering bins
sceneView->cull();
// draw the rendering bins.
sceneView->draw();
// Swap Buffers
renderSurface->swapBuffers();
std::cout << "before readPixels: _r = " << sp->_image->r() << std::endl;
tmpImage->readPixels(sceneView->getViewport()->x(),sceneView->getViewport()->y(),sceneView->getViewport()->width(),sceneView->getViewport()->height(),GL_RGBA,GL_UNSIGNED_BYTE);
// std::cout << "vor copySubImage: _r = " << sp->_image->r() << std::endl;
sp->_image->copySubImage( 0, 0, i, tmpImage );
/*
std::ostringstream o;
o << baseImageName << i << ".rgba";
tmpImageName = o.str();
osgDB::writeImageFile( *(sp->_image), tmpImageName );
std::cout << "Wrote image to file: " << tmpImageName << std::endl;
*/
}
osgDB::writeImageFile( *(sp->_image), outputName);
return 0;
}
<commit_msg>Removed include of Producer/RenderSurface<commit_after>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
//
// Simple example of use of Producer::RenderSurface to create an OpenGL
// graphics window, and OSG for rendering.
#include <osg/Timer>
#include <osgUtil/SceneView>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgProducer/Viewer>
#include <sstream>
#define MIN_NEARFAROFFSET 0.1
class SliceProcessor
{
public:
SliceProcessor() : _sliceNumber(128), _sliceDelta(0.1), _nearPlane(0.0), _farPlane(MIN_NEARFAROFFSET)
{
//
}
SliceProcessor( const double& objectRadius, unsigned int numberSlices) : _sliceNumber(numberSlices)
{
_sliceDelta = (objectRadius*2) / _sliceNumber;
_nearPlane = objectRadius; // note: distance from viewpoint is going to be set 2x radius
_farPlane = _nearPlane+MIN_NEARFAROFFSET;
_image = new osg::Image;
if( _sliceDelta > MIN_NEARFAROFFSET )
{
_nearFarOffset = MIN_NEARFAROFFSET;
}
else
{
_nearFarOffset = _sliceDelta;
}
_image->allocateImage( _sliceNumber, _sliceNumber,_sliceNumber, GL_RGBA, GL_UNSIGNED_BYTE );
}
// needs 3D-Texture object
osg::Image* _image;
unsigned int _sliceNumber;
double _sliceDelta;
double _nearPlane;
double _farPlane;
double _nearFarOffset;
// needs function to do rendering and slicing
};
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of osg::AnimationPath and UpdateCallbacks for adding animation to your scenes.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("-o <filename>","Object to be loaded");
if( arguments.read( "-h" ) || arguments.read( "--help" ) )
{
std::cout << "Argumentlist:" << std::endl;
std::cout << "\t-o <filename> sets object to be loaded and sliced" << std::endl;
std::cout << "\t--slices <unsigned int> sets number of slices through the object" << std::endl;
std::cout << "\t--near <double> sets start for near clipping plane" << std::endl;
std::cout << "\t--far <double> sets start for far clipping plane" << std::endl;
return 1;
}
std::string outputName("volume_tex.dds");
while( arguments.read( "-o", outputName ) ) { }
unsigned int numberSlices = 128;
while( arguments.read( "--slices", numberSlices) ) { }
double nearClip=0.0f;
double farClip=0.0f;
while( arguments.read( "--near",nearClip ) ) { }
while( arguments.read( "--far", farClip) ) { }
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles( arguments );
if (!loadedModel)
{
std::cout << "No data loaded." << std::endl;
return 1;
}
const osg::BoundingSphere& bs = loadedModel->getBound();
SliceProcessor* sp = new SliceProcessor( (double)bs.radius(), numberSlices );
if (nearClip!=0.0) sp->_nearPlane = nearClip;
if (farClip!=0.0) sp->_farPlane = farClip;
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
// create the window to draw to.
osg::ref_ptr<Producer::RenderSurface> renderSurface = new Producer::RenderSurface;
renderSurface->setWindowName("osgsimple");
renderSurface->setWindowRectangle(100,100,numberSlices,numberSlices);
renderSurface->useBorder(true);
// make sure we have a alpha channel in the colour buffer, to enable
// alpha on read back.
Producer::VisualChooser* rs_vc = renderSurface->getVisualChooser();
if (!rs_vc)
{
rs_vc = new Producer::VisualChooser;
rs_vc->setSimpleConfiguration();
renderSurface->setVisualChooser(rs_vc);
}
rs_vc->setAlphaSize(8);
// create the graphics context.
renderSurface->realize();
// create the view of the scene.
osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
sceneView->setDefaults();
sceneView->setSceneData(loadedModel.get());
// initialize the view to look at the center of the scene graph
osg::Matrix viewMatrix;
// distance from viewport to object's center is set to be 2x bs.radius()
viewMatrix.makeLookAt(bs.center()-osg::Vec3(0.0,2.0f*bs.radius(),0.0),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
// turn off autocompution of near and far clipping planes
sceneView->setComputeNearFarMode(osgUtil::CullVisitor::DO_NOT_COMPUTE_NEAR_FAR);
// set the clear color of the background to make sure that the alpha is 0.0.
sceneView->setClearColor(osg::Vec4(0.0f,0.0f,0.0f,0.0f));
// record the timer tick at the start of rendering.
osg::Timer_t start_tick = osg::Timer::instance()->tick();
std::cout << "radius: " << bs.radius() << std::endl;
unsigned int frameNum = 0;
double tmpNear, tmpFar;
std::string baseImageName("shot_");
std::string tmpImageName;
osg::Image* tmpImage = new osg::Image;
// main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
for( unsigned int i = 0 ; i < sp->_sliceNumber && renderSurface->isRealized() ; ++i )
{
// set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly
osg::ref_ptr<osg::FrameStamp> frameStamp = new osg::FrameStamp;
frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,osg::Timer::instance()->tick()));
frameStamp->setFrameNumber(frameNum++);
// pass frame stamp to the SceneView so that the update, cull and draw traversals all use the same FrameStamp
sceneView->setFrameStamp(frameStamp.get());
// update the viewport dimensions, incase the window has been resized.
sceneView->setViewport(0,0,renderSurface->getWindowWidth(),renderSurface->getWindowHeight());
// set the view
sceneView->setViewMatrix(viewMatrix);
// set Projection Matrix
tmpNear = sp->_nearPlane+i*sp->_sliceDelta;
tmpFar = sp->_farPlane+(i*sp->_sliceDelta)+sp->_nearFarOffset;
sceneView->setProjectionMatrixAsOrtho(-(bs.radius()+bs.radius()/2), bs.radius()+bs.radius()/2,-bs.radius(), bs.radius(), tmpNear, tmpFar);
// do the update traversal the scene graph - such as updating animations
sceneView->update();
// do the cull traversal, collect all objects in the view frustum into a sorted set of rendering bins
sceneView->cull();
// draw the rendering bins.
sceneView->draw();
// Swap Buffers
renderSurface->swapBuffers();
std::cout << "before readPixels: _r = " << sp->_image->r() << std::endl;
tmpImage->readPixels(sceneView->getViewport()->x(),sceneView->getViewport()->y(),sceneView->getViewport()->width(),sceneView->getViewport()->height(),GL_RGBA,GL_UNSIGNED_BYTE);
// std::cout << "vor copySubImage: _r = " << sp->_image->r() << std::endl;
sp->_image->copySubImage( 0, 0, i, tmpImage );
/*
std::ostringstream o;
o << baseImageName << i << ".rgba";
tmpImageName = o.str();
osgDB::writeImageFile( *(sp->_image), tmpImageName );
std::cout << "Wrote image to file: " << tmpImageName << std::endl;
*/
}
osgDB::writeImageFile( *(sp->_image), outputName);
return 0;
}
<|endoftext|>
|
<commit_before>#include "hermes1d.h"
#include "python_api.h"
#include "_hermes1d_api.h"
static int N_eq = 1;
int N_elem = 40; // number of elements
double A = 0, B = 20; // domain end points
int P_init = 2; // initial polynomal degree
double l = 0;
double lhs(int num, double *x, double *weights,
double *u, double *dudx, double *v, double *dvdx,
double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
void *user_data)
{
double val = 0;
for(int i = 0; i<num; i++) {
double coeff;
double r = x[i];
// specify r^2*V:
// Hydrogen:
double rrV = -r; // r^2 * (-1/r) = -r
// Harmonic oscillator:
//double rrV = r*r*r*r; // r^2 * (r^2) = r^4
coeff = 0.5*r*r*dudx[i]*dvdx[i] + (rrV + 0.5 * (l + 1)*l) *u[i]*v[i];
val += coeff*weights[i];
}
return val;
}
double rhs(int num, double *x, double *weights,
double *u, double *dudx, double *v, double *dvdx,
double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
void *user_data)
{
double val = 0;
for(int i = 0; i < num; i++) {
double r = x[i];
val += u[i]*v[i]*r*r*weights[i];
}
return val;
}
double E;
double residual(int num, double *x, double *weights,
double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
double *v, double *dvdx, void *user_data)
{
double *u = &u_prev[0][0][0];
double *dudx = &du_prevdx[0][0][0];
double val = 0;
for(int i = 0; i<num; i++) {
double coeff;
coeff = 0.5*x[i]*x[i]*dudx[i]*dvdx[i] -u[i]*v[i]*x[i]
+ 0.5 * (l + 1)*l *u[i]*v[i];
coeff -= E*u[i]*v[i]*x[i]*x[i];
val += coeff*weights[i];
}
return val;
}
// This is obsoleted and should be moved to hermes_common as a way to export
// DenseMatrix to Python:
void insert_matrix(Python *p, DenseMatrix *mat, int len)
{
double _mat[len*len];
for(int i=0; i<len; i++)
for(int j=0; j<len; j++)
_mat[i*len+j] = mat->get(i, j);
p->push("len", c2py_int(len));
p->push("mat", c2numpy_double(_mat, len*len));
p->exec("_ = mat.reshape((len, len))");
p->exec("del len");
p->exec("del mat");
}
/******************************************************************************/
int main(int argc, char* argv[]) {
// create mesh
Mesh *mesh = new Mesh(A, B, N_elem, P_init, N_eq);
// you can set the zero dirichlet at the right hand side
//mesh.set_bc_right_dirichlet(0, 0);
// variable for the total number of DOF
int N_dof = mesh->assign_dofs();
printf("ndofs: %d\n", N_dof);
// register weak forms
DiscreteProblem *dp1 = new DiscreteProblem();
dp1->add_matrix_form(0, 0, lhs);
DiscreteProblem *dp2 = new DiscreteProblem();
dp2->add_matrix_form(0, 0, rhs);
DiscreteProblem *dp3 = new DiscreteProblem();
dp3->add_vector_form(0, residual);
// allocate Jacobi matrix and residual
CooMatrix *mat1 = new CooMatrix(N_dof);
CooMatrix *mat2 = new CooMatrix(N_dof);
double *y_prev = new double[N_dof];
dp1->assemble_matrix(mesh, mat1);
dp2->assemble_matrix(mesh, mat2);
Python p;
p.exec("print 'Python initialized'");
p.push("A", c2py_CooMatrix(mat1));
p.push("B", c2py_CooMatrix(mat2));
p.exec("from utils import solve_eig_numpy, solve_eig_pysparse");
p.exec("eigs = solve_eig_numpy(A.to_scipy_coo(), B.to_scipy_coo())");
//p.exec("eigs = solve_eig_pysparse(A.to_scipy_coo(), B.to_scipy_coo())");
p.exec("E, v = eigs[0]");
int n;
double *res = new double[N_dof];
E = py2c_double(p.pull("E"));
printf("E=%.10f\n", E);
E = -0.5;
dp3->assemble_vector(mesh, res);
// calculate L2 norm of residual vector
double res_norm = 0;
for(int i=0; i<N_dof; i++) res_norm += res[i]*res[i];
res_norm = sqrt(res_norm);
printf("L2 norm of the residual: %f\n", res_norm);
Linearizer l(mesh);
const char *out_filename = "solution.gp";
l.plot_solution(out_filename);
printf("still ok\n");
if (import_hermes1d___hermes1d())
throw std::runtime_error("");
p.push("mesh", c2py_Mesh(mesh));
printf("2\n");
p.exec("from plot import plot_eigs, plot_file");
p.exec("plot_eigs(mesh, eigs)");
printf("Done.\n");
return 0;
}
<commit_msg>Remove insert_matrix()<commit_after>#include "hermes1d.h"
#include "python_api.h"
#include "_hermes1d_api.h"
static int N_eq = 1;
int N_elem = 40; // number of elements
double A = 0, B = 20; // domain end points
int P_init = 2; // initial polynomal degree
double l = 0;
double lhs(int num, double *x, double *weights,
double *u, double *dudx, double *v, double *dvdx,
double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
void *user_data)
{
double val = 0;
for(int i = 0; i<num; i++) {
double coeff;
double r = x[i];
// specify r^2*V:
// Hydrogen:
double rrV = -r; // r^2 * (-1/r) = -r
// Harmonic oscillator:
//double rrV = r*r*r*r; // r^2 * (r^2) = r^4
coeff = 0.5*r*r*dudx[i]*dvdx[i] + (rrV + 0.5 * (l + 1)*l) *u[i]*v[i];
val += coeff*weights[i];
}
return val;
}
double rhs(int num, double *x, double *weights,
double *u, double *dudx, double *v, double *dvdx,
double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
void *user_data)
{
double val = 0;
for(int i = 0; i < num; i++) {
double r = x[i];
val += u[i]*v[i]*r*r*weights[i];
}
return val;
}
double E;
double residual(int num, double *x, double *weights,
double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
double *v, double *dvdx, void *user_data)
{
double *u = &u_prev[0][0][0];
double *dudx = &du_prevdx[0][0][0];
double val = 0;
for(int i = 0; i<num; i++) {
double coeff;
coeff = 0.5*x[i]*x[i]*dudx[i]*dvdx[i] -u[i]*v[i]*x[i]
+ 0.5 * (l + 1)*l *u[i]*v[i];
coeff -= E*u[i]*v[i]*x[i]*x[i];
val += coeff*weights[i];
}
return val;
}
/******************************************************************************/
int main(int argc, char* argv[]) {
// create mesh
Mesh *mesh = new Mesh(A, B, N_elem, P_init, N_eq);
// you can set the zero dirichlet at the right hand side
//mesh.set_bc_right_dirichlet(0, 0);
// variable for the total number of DOF
int N_dof = mesh->assign_dofs();
printf("ndofs: %d\n", N_dof);
// register weak forms
DiscreteProblem *dp1 = new DiscreteProblem();
dp1->add_matrix_form(0, 0, lhs);
DiscreteProblem *dp2 = new DiscreteProblem();
dp2->add_matrix_form(0, 0, rhs);
DiscreteProblem *dp3 = new DiscreteProblem();
dp3->add_vector_form(0, residual);
// allocate Jacobi matrix and residual
CooMatrix *mat1 = new CooMatrix(N_dof);
CooMatrix *mat2 = new CooMatrix(N_dof);
double *y_prev = new double[N_dof];
dp1->assemble_matrix(mesh, mat1);
dp2->assemble_matrix(mesh, mat2);
Python p;
p.exec("print 'Python initialized'");
p.push("A", c2py_CooMatrix(mat1));
p.push("B", c2py_CooMatrix(mat2));
p.exec("from utils import solve_eig_numpy, solve_eig_pysparse");
p.exec("eigs = solve_eig_numpy(A.to_scipy_coo(), B.to_scipy_coo())");
//p.exec("eigs = solve_eig_pysparse(A.to_scipy_coo(), B.to_scipy_coo())");
p.exec("E, v = eigs[0]");
int n;
double *res = new double[N_dof];
E = py2c_double(p.pull("E"));
printf("E=%.10f\n", E);
E = -0.5;
dp3->assemble_vector(mesh, res);
// calculate L2 norm of residual vector
double res_norm = 0;
for(int i=0; i<N_dof; i++) res_norm += res[i]*res[i];
res_norm = sqrt(res_norm);
printf("L2 norm of the residual: %f\n", res_norm);
Linearizer l(mesh);
const char *out_filename = "solution.gp";
l.plot_solution(out_filename);
printf("still ok\n");
if (import_hermes1d___hermes1d())
throw std::runtime_error("");
p.push("mesh", c2py_Mesh(mesh));
printf("2\n");
p.exec("from plot import plot_eigs, plot_file");
p.exec("plot_eigs(mesh, eigs)");
printf("Done.\n");
return 0;
}
<|endoftext|>
|
<commit_before>
#include <iostream>
#include <fstream>
#include <ostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <llvm/Support/raw_os_ostream.h>
#include <libdevcore/Common.h>
#include <libdevcore/CommonIO.h>
#include <libevmface/Instruction.h>
#include <libevmjit/Compiler.h>
#include <libevmjit/ExecutionEngine.h>
void show_usage()
{
// FIXME: Use arg[0] as program name?
std::cerr << "usage: evmcc (-b|-c|-d)+ <inputfile.bc>\n";
}
int main(int argc, char** argv)
{
std::string input_file;
bool opt_dissassemble = false;
bool opt_show_bytes = false;
bool opt_compile = false;
bool opt_interpret = false;
bool opt_dump_graph = false;
bool opt_unknown = false;
size_t initialGas = 10000;
for (int i = 1; i < argc; i++)
{
std::string option = argv[i];
if (option == "-b")
opt_show_bytes = true;
else if (option == "-c")
opt_compile = true;
else if (option == "-d")
opt_dissassemble = true;
else if (option == "-i")
opt_interpret = true;
else if (option == "-g")
opt_dump_graph = true;
else if (option == "-G" && i + 1 < argc)
{
std::string gasValue = argv[++i];
initialGas = boost::lexical_cast<size_t>(gasValue);
std::cerr << "Initial gas set to " << initialGas << "\n";
}
else if (option[0] != '-' && input_file.empty())
input_file = option;
else
{
opt_unknown = true;
break;
}
}
if (opt_unknown ||
input_file.empty() ||
(!opt_show_bytes && !opt_compile && !opt_dissassemble && !opt_interpret))
{
show_usage();
exit(1);
}
std::ifstream ifs(input_file);
if (!ifs.is_open())
{
std::cerr << "cannot open file " << input_file << std::endl;
exit(1);
}
std::string src((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
boost::algorithm::trim(src);
using namespace dev;
bytes bytecode = fromHex(src);
if (opt_show_bytes)
{
std::cout << memDump(bytecode) << std::endl;
}
if (opt_dissassemble)
{
std::string assembly = eth::disassemble(bytecode);
std::cout << assembly << std::endl;
}
if (opt_compile || opt_interpret)
{
auto compiler = eth::jit::Compiler();
auto module = compiler.compile({bytecode.data(), bytecode.size()});
module->dump();
if (opt_dump_graph)
{
std::ofstream ofs("blocks.dot");
compiler.dumpBasicBlockGraph(ofs);
ofs.close();
std::cout << "Basic blocks graph written to block.dot\n";
}
if (opt_interpret)
{
auto engine = eth::jit::ExecutionEngine();
u256 gas = initialGas;
auto result = engine.run(std::move(module), gas);
return result;
}
}
return 0;
}
<commit_msg>1. Indenting spaces converted to tabs 2. Options changed: -G --> -g<commit_after>
#include <chrono>
#include <iostream>
#include <fstream>
#include <ostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <llvm/Support/raw_os_ostream.h>
#include <libdevcore/Common.h>
#include <libdevcore/CommonIO.h>
#include <libevmface/Instruction.h>
#include <libevmjit/Compiler.h>
#include <libevmjit/ExecutionEngine.h>
void show_usage()
{
// FIXME: Use arg[0] as program name?
std::cerr << "usage: evmcc (-b|-c|-d)+ <inputfile.bc>\n";
}
int main(int argc, char** argv)
{
std::string input_file;
bool opt_dissassemble = false;
bool opt_show_bytes = false;
bool opt_compile = false;
bool opt_interpret = false;
bool opt_dump_graph = false;
bool opt_unknown = false;
bool opt_verbose = false;
size_t initialGas = 10000;
for (int i = 1; i < argc; i++)
{
std::string option = argv[i];
if (option == "-b")
opt_show_bytes = true;
else if (option == "-c")
opt_compile = true;
else if (option == "-d")
opt_dissassemble = true;
else if (option == "-i")
opt_interpret = true;
else if (option == "--dump-cfg")
opt_dump_graph = true;
else if (option == "-g" && i + 1 < argc)
{
std::string gasValue = argv[++i];
initialGas = boost::lexical_cast<size_t>(gasValue);
std::cerr << "Initial gas set to " << initialGas << "\n";
}
else if (option == "-v")
opt_verbose = true;
else if (option[0] != '-' && input_file.empty())
input_file = option;
else
{
opt_unknown = true;
break;
}
}
if (opt_unknown ||
input_file.empty() ||
(!opt_show_bytes && !opt_compile && !opt_dissassemble && !opt_interpret))
{
show_usage();
exit(1);
}
std::ifstream ifs(input_file);
if (!ifs.is_open())
{
std::cerr << "cannot open file " << input_file << std::endl;
exit(1);
}
std::string src((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
boost::algorithm::trim(src);
using namespace dev;
bytes bytecode = fromHex(src);
if (opt_show_bytes)
std::cout << memDump(bytecode) << std::endl;
if (opt_dissassemble)
{
std::string assembly = eth::disassemble(bytecode);
std::cout << assembly << std::endl;
}
if (opt_compile || opt_interpret)
{
auto compilationStartTime = std::chrono::high_resolution_clock::now();
auto compiler = eth::jit::Compiler();
auto module = compiler.compile({bytecode.data(), bytecode.size()});
auto compilationEndTime = std::chrono::high_resolution_clock::now();
module->dump();
if (opt_verbose)
{
std::cerr << "*** Compilation time: "
<< std::chrono::duration_cast<std::chrono::microseconds>(compilationEndTime - compilationStartTime).count()
<< std::endl;
}
if (opt_dump_graph)
{
std::ofstream ofs("blocks.dot");
compiler.dumpBasicBlockGraph(ofs);
ofs.close();
std::cout << "Basic blocks graph written to block.dot\n";
}
if (opt_interpret)
{
auto engine = eth::jit::ExecutionEngine();
u256 gas = initialGas;
auto result = engine.run(std::move(module), gas);
return result;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "manageescrowdialog.h"
#include "ui_manageescrowdialog.h"
#include "guiutil.h"
#include "syscoingui.h"
#include "ui_interface.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
#include "rpcserver.h"
using namespace std;
extern const CRPCTable tableRPC;
ManageEscrowDialog::ManageEscrowDialog(const QString &escrow, const QString &buyer, const QString &seller, const QString &arbiter, const QString &status, const QString &offertitle, const QString &total,QWidget *parent) :
QDialog(parent),
ui(new Ui::ManageEscrowDialog), escrow(escrow), buyer(buyer), seller(seller), arbiter(arbiter), status(status),offertitle(offertitle), total(total)
{
ui->setupUi(this);
EscrowType escrowType = findYourEscrowRoleFromAliases(buyer, seller, arbiter);
ui->manageInfo->setText(tr("You are managing escrow ID: <b>%1</b> of an offer for <b>%2</b> totalling <b>%3</b>SYS. The buyer is <b>%4</b>, seller is <b>%5</b> and arbiter is <b>%6</b>").arg(escrow).arg(offertitle).arg(total).arg(buyer).arg(seller).arg(arbiter));
if(escrowType == None)
{
ui->manageInfo2->setText(tr("You cannot manage this escrow because you do not own one of either the buyer, seller or arbiter aliases."));
ui->releaseButton->setEnabled(false);
ui->refundButton->setEnabled(false);
}
else if(status == "in-escrow")
{
if(escrowType == Buyer)
{
ui->manageInfo2->setText(tr("You are the <b>buyer</b> of the offer held in escrow, you may release the coins to the seller once you have confirmed that you have recieved the item as per the description of the offer."));
ui->refundButton->setEnabled(false);
}
else if(escrowType == Seller)
{
ui->manageInfo2->setText(tr("You are the <b>seller</b> of the offer held in escrow, you may refund the coins back to the buyer."));
ui->releaseButton->setEnabled(false);
}
else if(escrowType == Arbiter)
{
ui->manageInfo2->setText(tr("You are the <b>arbiter</b> of the offer held in escrow, you may refund the coins back to the buyer if you have evidence that the seller did not honour the agreement to ship the offer item. You may also release the coins to the seller if the buyer has not released. You may use Syscoin messages to communicate with the buyer and seller to ensure you have adequeate proof for your decision."));
}
}
else if(status == "escrow released")
{
if(escrowType == Buyer)
{
ui->manageInfo2->setText(tr("The escrow has already been released to the seller. You may communicate with your arbiter or seller via Syscoin messages."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setEnabled(false);
}
else if(escrowType == Seller)
{
ui->manageInfo2->setText(tr("You are the <b>seller</b> of the offer held in escrow. The payment of coins have been released to you, you may claim them now."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setText(tr("Claim Payment"));
}
else if(escrowType == Arbiter)
{
ui->manageInfo2->setText(tr("The escrow has already been released to the seller. You're job is done, if you were the one to release the coins you will recieve a commission as soon as the seller claims his payment."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setEnabled(false);
}
}
else if(status == "escrow refunded")
{
if(escrowType == Buyer)
{
ui->manageInfo2->setText(tr("You are the <b>buyer</b> of the offer held in escrow. The coins have been refunded back to you, you may claim them now."));
ui->refundButton->setText(tr("Claim Refund"));
ui->releaseButton->setEnabled(false);
}
else if(escrowType == Seller)
{
ui->manageInfo2->setText(tr("The escrow has already been refunded back to the buyer."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setEnabled(false);
}
else if(escrowType == Arbiter)
{
ui->manageInfo2->setText(tr("The escrow has already been refunded back to the buyer. You're job is done, if you were the one to refund the coins you will recieve a commission as soon as the buyer claims his refund."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setEnabled(false);
}
}
else if(status == "complete")
{
ui->manageInfo2->setText(tr("The escrow has been successfully claimed by the seller. The escrow is complete."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setEnabled(false);
}
else
{
ui->manageInfo2->setText(tr("The escrow status was not recognized. Please contact the Syscoin team."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setEnabled(false);
}
}
void ManageEscrowDialog::on_cancelButton_clicked()
{
reject();
}
ManageEscrowDialog::~ManageEscrowDialog()
{
delete ui;
}
void ManageEscrowDialog::on_releaseButton_clicked()
{
UniValue params(UniValue::VARR);
string strMethod = string("escrowrelease");
params.push_back(escrow.toStdString());
try {
UniValue result = tableRPC.execute(strMethod, params);
QMessageBox::information(this, windowTitle(),
tr("Escrow released successfully!"),
QMessageBox::Ok, QMessageBox::Ok);
ManageEscrowDialog::accept();
}
catch (UniValue& objError)
{
string strError = find_value(objError, "message").get_str();
QMessageBox::critical(this, windowTitle(),
tr("Error releasing escrow: \"%1\"").arg(QString::fromStdString(strError)),
QMessageBox::Ok, QMessageBox::Ok);
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("General exception releasing escrow"),
QMessageBox::Ok, QMessageBox::Ok);
}
}
void ManageEscrowDialog::on_refundButton_clicked()
{
UniValue params(UniValue::VARR);
string strMethod = string("escrowrefund");
params.push_back(escrow.toStdString());
try {
UniValue result = tableRPC.execute(strMethod, params);
QMessageBox::information(this, windowTitle(),
tr("Escrow refunded successfully!"),
QMessageBox::Ok, QMessageBox::Ok);
ManageEscrowDialog::accept();
}
catch (UniValue& objError)
{
string strError = find_value(objError, "message").get_str();
QMessageBox::critical(this, windowTitle(),
tr("Error refunding escrow: \"%1\"").arg(QString::fromStdString(strError)),
QMessageBox::Ok, QMessageBox::Ok);
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("General exception refunding escrow"),
QMessageBox::Ok, QMessageBox::Ok);
}
}
ManageEscrowDialog::EscrowType ManageEscrowDialog::findYourEscrowRoleFromAliases(const QString &buyer, const QString &seller, const QString &arbiter)
{
if(isYourAlias(buyer))
return EscrowType::Buyer;
else if(isYourAlias(seller))
return EscrowType::Seller;
else if(isYourArbiter(arbiter))
return EscrowType::Arbiter;
else
return EscrowType::None;
}
bool ManageEscrowDialog::isYourAlias(const QString &alias)
{
string strMethod = string("aliasinfo");
UniValue params(UniValue::VARR);
UniValue result ;
string name_str;
int expired = 0;
params.push_back(alias.toStdString());
try {
result = tableRPC.execute(strMethod, params);
if (result.type() == UniValue::VOBJ)
{
const UniValue& o = result.get_obj();
const UniValue& mine_value = find_value(o, "ismine");
if (mine_value.type() == UniValue::VBOOL)
return mine_value.get_bool();
}
}
catch (UniValue& objError)
{
string strError = find_value(objError, "message").get_str();
QMessageBox::critical(this, windowTitle(),
tr("Could not refresh cert list: %1").arg(QString::fromStdString(strError)),
QMessageBox::Ok, QMessageBox::Ok);
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("There was an exception trying to refresh the cert list: ") + QString::fromStdString(e.what()),
QMessageBox::Ok, QMessageBox::Ok);
}
return false;
}
<commit_msg>typo<commit_after>#include "manageescrowdialog.h"
#include "ui_manageescrowdialog.h"
#include "guiutil.h"
#include "syscoingui.h"
#include "ui_interface.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
#include "rpcserver.h"
using namespace std;
extern const CRPCTable tableRPC;
ManageEscrowDialog::ManageEscrowDialog(const QString &escrow, const QString &buyer, const QString &seller, const QString &arbiter, const QString &status, const QString &offertitle, const QString &total,QWidget *parent) :
QDialog(parent),
ui(new Ui::ManageEscrowDialog), escrow(escrow), buyer(buyer), seller(seller), arbiter(arbiter), status(status),offertitle(offertitle), total(total)
{
ui->setupUi(this);
EscrowType escrowType = findYourEscrowRoleFromAliases(buyer, seller, arbiter);
ui->manageInfo->setText(tr("You are managing escrow ID: <b>%1</b> of an offer for <b>%2</b> totalling <b>%3</b>SYS. The buyer is <b>%4</b>, seller is <b>%5</b> and arbiter is <b>%6</b>").arg(escrow).arg(offertitle).arg(total).arg(buyer).arg(seller).arg(arbiter));
if(escrowType == None)
{
ui->manageInfo2->setText(tr("You cannot manage this escrow because you do not own one of either the buyer, seller or arbiter aliases."));
ui->releaseButton->setEnabled(false);
ui->refundButton->setEnabled(false);
}
else if(status == "in-escrow")
{
if(escrowType == Buyer)
{
ui->manageInfo2->setText(tr("You are the <b>buyer</b> of the offer held in escrow, you may release the coins to the seller once you have confirmed that you have recieved the item as per the description of the offer."));
ui->refundButton->setEnabled(false);
}
else if(escrowType == Seller)
{
ui->manageInfo2->setText(tr("You are the <b>seller</b> of the offer held in escrow, you may refund the coins back to the buyer."));
ui->releaseButton->setEnabled(false);
}
else if(escrowType == Arbiter)
{
ui->manageInfo2->setText(tr("You are the <b>arbiter</b> of the offer held in escrow, you may refund the coins back to the buyer if you have evidence that the seller did not honour the agreement to ship the offer item. You may also release the coins to the seller if the buyer has not released. You may use Syscoin messages to communicate with the buyer and seller to ensure you have adequeate proof for your decision."));
}
}
else if(status == "escrow released")
{
if(escrowType == Buyer)
{
ui->manageInfo2->setText(tr("The escrow has already been released to the seller. You may communicate with your arbiter or seller via Syscoin messages."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setEnabled(false);
}
else if(escrowType == Seller)
{
ui->manageInfo2->setText(tr("You are the <b>seller</b> of the offer held in escrow. The payment of coins have been released to you, you may claim them now."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setText(tr("Claim Payment"));
}
else if(escrowType == Arbiter)
{
ui->manageInfo2->setText(tr("The escrow has already been released to the seller. You're job is done, if you were the one to release the coins you will recieve a commission as soon as the seller claims his payment."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setEnabled(false);
}
}
else if(status == "escrow refunded")
{
if(escrowType == Buyer)
{
ui->manageInfo2->setText(tr("You are the <b>buyer</b> of the offer held in escrow. The coins have been refunded back to you, you may claim them now."));
ui->refundButton->setText(tr("Claim Refund"));
ui->releaseButton->setEnabled(false);
}
else if(escrowType == Seller)
{
ui->manageInfo2->setText(tr("The escrow has already been refunded back to the buyer."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setEnabled(false);
}
else if(escrowType == Arbiter)
{
ui->manageInfo2->setText(tr("The escrow has already been refunded back to the buyer. You're job is done, if you were the one to refund the coins you will recieve a commission as soon as the buyer claims his refund."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setEnabled(false);
}
}
else if(status == "complete")
{
ui->manageInfo2->setText(tr("The escrow has been successfully claimed by the seller. The escrow is complete."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setEnabled(false);
}
else
{
ui->manageInfo2->setText(tr("The escrow status was not recognized. Please contact the Syscoin team."));
ui->refundButton->setEnabled(false);
ui->releaseButton->setEnabled(false);
}
}
void ManageEscrowDialog::on_cancelButton_clicked()
{
reject();
}
ManageEscrowDialog::~ManageEscrowDialog()
{
delete ui;
}
void ManageEscrowDialog::on_releaseButton_clicked()
{
UniValue params(UniValue::VARR);
string strMethod = string("escrowrelease");
params.push_back(escrow.toStdString());
try {
UniValue result = tableRPC.execute(strMethod, params);
QMessageBox::information(this, windowTitle(),
tr("Escrow released successfully!"),
QMessageBox::Ok, QMessageBox::Ok);
ManageEscrowDialog::accept();
}
catch (UniValue& objError)
{
string strError = find_value(objError, "message").get_str();
QMessageBox::critical(this, windowTitle(),
tr("Error releasing escrow: \"%1\"").arg(QString::fromStdString(strError)),
QMessageBox::Ok, QMessageBox::Ok);
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("General exception releasing escrow"),
QMessageBox::Ok, QMessageBox::Ok);
}
}
void ManageEscrowDialog::on_refundButton_clicked()
{
UniValue params(UniValue::VARR);
string strMethod = string("escrowrefund");
params.push_back(escrow.toStdString());
try {
UniValue result = tableRPC.execute(strMethod, params);
QMessageBox::information(this, windowTitle(),
tr("Escrow refunded successfully!"),
QMessageBox::Ok, QMessageBox::Ok);
ManageEscrowDialog::accept();
}
catch (UniValue& objError)
{
string strError = find_value(objError, "message").get_str();
QMessageBox::critical(this, windowTitle(),
tr("Error refunding escrow: \"%1\"").arg(QString::fromStdString(strError)),
QMessageBox::Ok, QMessageBox::Ok);
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("General exception refunding escrow"),
QMessageBox::Ok, QMessageBox::Ok);
}
}
ManageEscrowDialog::EscrowType ManageEscrowDialog::findYourEscrowRoleFromAliases(const QString &buyer, const QString &seller, const QString &arbiter)
{
if(isYourAlias(buyer))
return Buyer;
else if(isYourAlias(seller))
return Seller;
else if(isYourArbiter(arbiter))
return Arbiter;
else
return None;
}
bool ManageEscrowDialog::isYourAlias(const QString &alias)
{
string strMethod = string("aliasinfo");
UniValue params(UniValue::VARR);
UniValue result ;
string name_str;
int expired = 0;
params.push_back(alias.toStdString());
try {
result = tableRPC.execute(strMethod, params);
if (result.type() == UniValue::VOBJ)
{
const UniValue& o = result.get_obj();
const UniValue& mine_value = find_value(o, "ismine");
if (mine_value.type() == UniValue::VBOOL)
return mine_value.get_bool();
}
}
catch (UniValue& objError)
{
string strError = find_value(objError, "message").get_str();
QMessageBox::critical(this, windowTitle(),
tr("Could not refresh cert list: %1").arg(QString::fromStdString(strError)),
QMessageBox::Ok, QMessageBox::Ok);
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("There was an exception trying to refresh the cert list: ") + QString::fromStdString(e.what()),
QMessageBox::Ok, QMessageBox::Ok);
}
return false;
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* 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 Willow Garage, Inc. 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 OWNER 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.
*
* $Id: boundary_estimation.cpp 1032 2011-05-18 22:43:27Z marton $
*
*/
#include <sensor_msgs/PointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/features/boundary.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
int default_k = 0;
double default_radius = 0.0;
double default_angle = M_PI/2.0;
Eigen::Vector4f translation;
Eigen::Quaternionf orientation;
void
printHelp (int argc, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -radius X = use a radius of Xm around each point to determine the neighborhood (default: ");
print_value ("%f", default_radius); print_info (")\n");
print_info (" -k X = use a fixed number of X-nearest neighbors around each point (default: ");
print_value ("%d", default_k); print_info (")\n");
print_info (" -thresh X = the decision boundary (angle threshold) that marks points as boundary or regular (default: ");
print_value ("%f", default_angle); print_info (")\n");
}
bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, cloud, translation, orientation) < 0)
return (false);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());
// Check if the dataset has normals
if (pcl::getFieldIndex (cloud, "normal_x") == -1)
{
print_error ("The input dataset does not contain normal information!\n");
return (false);
}
return (true);
}
void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
int k, double radius, double angle)
{
// Convert data to PointCloud<T>
PointCloud<PointNormal>::Ptr xyznormals (new PointCloud<PointNormal>);
fromROSMsg (*input, *xyznormals);
// Estimate
TicToc tt;
tt.tic ();
print_highlight (stderr, "Computing ");
BoundaryEstimation<pcl::PointNormal, pcl::PointNormal, pcl::Boundary> ne;
ne.setInputCloud (xyznormals);
ne.setInputNormals (xyznormals);
ne.setSearchMethod (pcl::KdTreeFLANN<pcl::PointNormal>::Ptr (new pcl::KdTreeFLANN<pcl::PointNormal>));
ne.setKSearch (k);
ne.setRadiusSearch (radius);
PointCloud<Boundary> boundaries;
ne.compute (boundaries);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", boundaries.width * boundaries.height); print_info (" points]\n");
// Convert data back
sensor_msgs::PointCloud2 output_boundaries;
toROSMsg (boundaries, output_boundaries);
concatenateFields (*input, output_boundaries, output);
}
void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
pcl::io::savePCDFile (filename, output, translation, orientation, true);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Estimate boundary points using pcl::BoundaryEstimation. For more information, use: %s -h\n", argv[0]);
bool help = false;
parse_argument (argc, argv, "-h", help);
if (argc < 3 || help)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Command line parsing
int k = default_k;
double radius = default_radius;
double angle = default_angle;
parse_argument (argc, argv, "-k", k);
parse_argument (argc, argv, "-radius", radius);
parse_argument (argc, argv, "-thresh", angle);
// Load the first file
sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud))
return (-1);
// Perform the feature estimation
sensor_msgs::PointCloud2 output;
compute (cloud, output, k, radius, angle);
// Save into the second file
saveCloud (argv[p_file_indices[1]], output);
}
<commit_msg>save as ascii in an attempt to catch a bug<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* 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 Willow Garage, Inc. 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 OWNER 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.
*
* $Id: boundary_estimation.cpp 1032 2011-05-18 22:43:27Z marton $
*
*/
#include <sensor_msgs/PointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/features/boundary.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
int default_k = 0;
double default_radius = 0.0;
double default_angle = M_PI/2.0;
Eigen::Vector4f translation;
Eigen::Quaternionf orientation;
void
printHelp (int argc, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -radius X = use a radius of Xm around each point to determine the neighborhood (default: ");
print_value ("%f", default_radius); print_info (")\n");
print_info (" -k X = use a fixed number of X-nearest neighbors around each point (default: ");
print_value ("%d", default_k); print_info (")\n");
print_info (" -thresh X = the decision boundary (angle threshold) that marks points as boundary or regular (default: ");
print_value ("%f", default_angle); print_info (")\n");
}
bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, cloud, translation, orientation) < 0)
return (false);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());
// Check if the dataset has normals
if (pcl::getFieldIndex (cloud, "normal_x") == -1)
{
print_error ("The input dataset does not contain normal information!\n");
return (false);
}
return (true);
}
void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
int k, double radius, double angle)
{
// Convert data to PointCloud<T>
PointCloud<PointNormal>::Ptr xyznormals (new PointCloud<PointNormal>);
fromROSMsg (*input, *xyznormals);
// Estimate
TicToc tt;
tt.tic ();
print_highlight (stderr, "Computing ");
BoundaryEstimation<pcl::PointNormal, pcl::PointNormal, pcl::Boundary> ne;
ne.setInputCloud (xyznormals);
ne.setInputNormals (xyznormals);
ne.setSearchMethod (pcl::KdTreeFLANN<pcl::PointNormal>::Ptr (new pcl::KdTreeFLANN<pcl::PointNormal>));
ne.setKSearch (k);
ne.setRadiusSearch (radius);
PointCloud<Boundary> boundaries;
ne.compute (boundaries);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", boundaries.width * boundaries.height); print_info (" points]\n");
// Convert data back
sensor_msgs::PointCloud2 output_boundaries;
toROSMsg (boundaries, output_boundaries);
concatenateFields (*input, output_boundaries, output);
}
void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
pcl::io::savePCDFile (filename, output, translation, orientation, false);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Estimate boundary points using pcl::BoundaryEstimation. For more information, use: %s -h\n", argv[0]);
bool help = false;
parse_argument (argc, argv, "-h", help);
if (argc < 3 || help)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Command line parsing
int k = default_k;
double radius = default_radius;
double angle = default_angle;
parse_argument (argc, argv, "-k", k);
parse_argument (argc, argv, "-radius", radius);
parse_argument (argc, argv, "-thresh", angle);
// Load the first file
sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud))
return (-1);
// Perform the feature estimation
sensor_msgs::PointCloud2 output;
compute (cloud, output, k, radius, angle);
// Save into the second file
saveCloud (argv[p_file_indices[1]], output);
}
<|endoftext|>
|
<commit_before>/*
* 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.
*
* [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
*/
#include "utils/Byte.h"
#include "utils/LuaEx.h"
#include "utils/Path.h"
#ifdef __ANDROID__
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#endif
namespace PathXS {
static int FromSystem (lua_State * L, const char * name)
{
if (lua_isnil(L, -1)) return LUA_NOREF;
lua_getfield(L, -1, name); // system, system[name]
return lua_ref(L, 1); // system
}
Directories * Directories::Instantiate (lua_State * L)
{
Directories * dirs = LuaXS::NewTyped<Directories>(L); // ..., dirs
lua_getglobal(L, "system"); // ..., dirs, system
dirs->mPathForFile = FromSystem(L, "pathForFile");
dirs->mDocumentsDir = FromSystem(L, "DocumentsDirectory");
dirs->mResourceDir = FromSystem(L, "ResourceDirectory");
lua_newtable(L);// ..., dirs, system, dlist
for (lua_pushnil(L); lua_next(L, -3); lua_pop(L, 1))
{
if (!lua_isstring(L, -2) || !lua_isuserdata(L, -1)) continue;
size_t nchars = lua_objlen(L, -2);
if (nchars <= sizeof("Directory")) continue;
if (strcmp(lua_tostring(L, -2) + nchars - sizeof("Directory") + 1, "Directory") == 0)
{
lua_pushvalue(L, -1); // ..., dirs, system, dlist, name, nonce, nonce
lua_pushboolean(L, 1); // ..., dirs, system, dlist, name, nonce, nonce, true
lua_rawset(L, -5); // ..., dirs, system, dlist = { ..., [nonce] = true }, name, nonce
}
}
dirs->mDirsList = lua_ref(L, 1); // ..., dirs, system
lua_getglobal(L, "require");// ..., dirs, system, require; n.b. io might not be loaded, e.g. in luaproc process
lua_pushliteral(L, "io"); // ..., dirs, system, require, "io"
lua_call(L, 1, 1); // ..., dirs, system, io
lua_getfield(L, -1, "open");// ..., dirs, system, io, io.open
dirs->mIO_Open = lua_ref(L, 1); // ..., dirs, system, io
lua_pop(L, 2); // ..., dirs
return dirs;
}
const char * Directories::Canonicalize (lua_State * L, bool bRead, int arg)
{
arg = CoronaLuaNormalize(L, arg);
luaL_checkstring(L, arg);
lua_getref(L, mPathForFile);// ..., str[, dir], ..., pathForFile
lua_pushvalue(L, arg); // ..., str[, dir], ..., pathForFile, str
if (IsDir(L, arg + 1))
{
lua_pushvalue(L, arg + 1); // ..., str, dir, ..., pathForFile, str, dir
lua_remove(L, arg + 1); // ..., str, ..., pathForFile, str, dir
}
else lua_getref(L, bRead ? mResourceDir : mDocumentsDir); // ..., str, ..., pathForFile, str, def_dir
lua_call(L, 2, 1); // ..., str, ..., file
if (lua_isnil(L, -1))
{
lua_pop(L, 1); // ..., str, ...
lua_pushliteral(L, ""); // ..., str, ..., ""
}
lua_replace(L, arg);// ..., file / "", ...
return lua_tostring(L, arg);
}
bool Directories::IsDir (lua_State * L, int arg)
{
lua_pushvalue(L, arg); // ..., dir?, ..., dir?
lua_getref(L, mDirsList); // ..., dir?, list
lua_insert(L, -2); // ..., dir?, ..., list, dir?
lua_rawget(L, -2); // ..., dir?, ..., list, is_dir
bool bIsDir = LuaXS::Bool(L);
lua_pop(L, 2); // ..., dir?, ...
return bIsDir;
}
#ifdef __ANDROID__
static AAssetManager * sAssets;
static jclass sAssetsRef;
void Directories::InitAssets (JavaVM * vm)
{
JNIEnv * env;
jint result = vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6);
if (result != JNI_OK) return;
// Adapted from code in:
// https://github.com/openfl/lime/blob/e511c0d2a5d616081a7826416d111aff1d428025/legacy
jclass cls = env->FindClass("com/ansca/corona/CoronaActivity");
jmethodID mid = env->GetStaticMethodID(cls, "getAssetManager", "()Landroid/content/res/AssetManager;");
if (mid)
{
jobject amgr = (jobject)env->CallStaticObjectMethod(cls, mid);
if (amgr)
{
sAssets = AAssetManager_fromJava(env, amgr);
if (sAssets) sAssetsRef = (jclass)env->NewGlobalRef(amgr);
env->DeleteLocalRef(amgr);
}
}
}
static bool InResourceDir (Directories * dirs, lua_State * L, int darg)
{
lua_getref(L, dirs->mResourceDir); // ..., dir, ..., ResourceDirectory
bool bIn = lua_equal(L, darg, -1) != 0;
lua_pop(L, 1); // ..., dir, ...
return bIn;
}
struct AssetRequest {
const char * mFilename;
std::vector<unsigned char> & mContents;
bool mOK{false};
};
static int GetAsset (lua_State * L)
{
AssetRequest * ar = LuaXS::UD<AssetRequest>(L, 1);
AAsset * asset = AAssetManager_open(sAssets, ar->mFilename, AASSET_MODE_BUFFER);
if (asset)
{
size_t len = AAsset_getLength(asset);
ar->mContents.resize(len);
AAsset_read(asset, ar->mContents.data(), len);
AAsset_close(asset);
}
return 0;
}
static bool CheckAssets (Directories * dirs, lua_State * L, std::vector<unsigned char> & contents, int arg)
{
if (!sAssets) return false;
const char * filename = luaL_checkstring(L, arg);
bool bHasDir = IsDir(L, arg + 1);
if (!bHasDir || InResourceDir(dirs, L, arg + 1))
{
AssetRequest ar{filename, contents};
LuaXS::CallInMainState(L, GetAsset, &ar);
if (bHasDir) lua_remove(L, arg + 1);// ..., str, ...
return ar->mOK;
}
return false;
}
#endif
bool Directories::ReadFileContents (lua_State * L, std::vector<unsigned char> & contents, int arg, bool bWantText)
{
arg = CoronaLuaNormalize(L, arg);
#ifdef __ANDROID__
if (CheckAssets(this, L, contents, arg)) return true;
#endif
const char * filename = Canonicalize(L, true, arg); // ..., filename, ...
lua_getref(L, mIO_Open);// ..., filename, ..., io.open
lua_pushvalue(L, arg); // ..., filename, ..., io.open, filename
lua_pushstring(L, bWantText ? "r" : "rb"); // ..., filename, ..., io.open, filename, mode
lua_call(L, 2, 1); // ..., filename, ..., file / nil
bool bOpened = !lua_isnil(L, -1);
if (bOpened)
{
lua_getfield(L, -1, "read");// ..., filename, ..., file, file.read
lua_insert(L, -2); // ..., filename, ..., file.read, file
lua_pushliteral(L, "*a"); // ..., filename, ..., file.read, file, "*a"
lua_call(L, 2, 1); // ..., filename, ..., contents
const unsigned char * uc = reinterpret_cast<const unsigned char *>(lua_tostring(L, -1));
contents.assign(uc, uc + lua_objlen(L, -1));
}
lua_pop(L, 1); // ..., filename, ...
return bOpened;
}
void LibLoader::Close (void)
{
if (IsLoaded())
{
#ifdef _WIN32
FreeLibrary(mLib);
#else
dlclose(mLib);
#endif
}
mLib = nullptr;
}
void LibLoader::Load (const char * name)
{
Close();
#ifdef _WIN32
mLib = LoadLibraryExA(name, nullptr, 0); // following nvcore/Library.h...
#else
mLib = dlopen(name, RTLD_LAZY);
#endif
}
WriteAux::WriteAux (lua_State * L, int dim, Directories * dirs)
{
if (dirs) mFilename = dirs->Canonicalize(L, false); // n.b. might remove dir
mW = luaL_checkint(L, dim);
mH = luaL_checkint(L, dim + 1);
}
WriteAuxReader::WriteAuxReader (lua_State * L, int dim, int barg, Directories * dirs) : WriteAux{L, dim, dirs}, mReader{L, barg}
{
if (!mReader.mBytes) lua_error(L);
}
}
<commit_msg>Dumb printouts<commit_after>/*
* 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.
*
* [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
*/
#include "utils/Byte.h"
#include "utils/LuaEx.h"
#include "utils/Path.h"
#ifdef __ANDROID__
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/log.h>
#endif
namespace PathXS {
static int FromSystem (lua_State * L, const char * name)
{
if (lua_isnil(L, -1)) return LUA_NOREF;
lua_getfield(L, -1, name); // system, system[name]
return lua_ref(L, 1); // system
}
Directories * Directories::Instantiate (lua_State * L)
{
Directories * dirs = LuaXS::NewTyped<Directories>(L); // ..., dirs
lua_getglobal(L, "system"); // ..., dirs, system
dirs->mPathForFile = FromSystem(L, "pathForFile");
dirs->mDocumentsDir = FromSystem(L, "DocumentsDirectory");
dirs->mResourceDir = FromSystem(L, "ResourceDirectory");
lua_newtable(L);// ..., dirs, system, dlist
for (lua_pushnil(L); lua_next(L, -3); lua_pop(L, 1))
{
if (!lua_isstring(L, -2) || !lua_isuserdata(L, -1)) continue;
size_t nchars = lua_objlen(L, -2);
if (nchars <= sizeof("Directory")) continue;
if (strcmp(lua_tostring(L, -2) + nchars - sizeof("Directory") + 1, "Directory") == 0)
{
lua_pushvalue(L, -1); // ..., dirs, system, dlist, name, nonce, nonce
lua_pushboolean(L, 1); // ..., dirs, system, dlist, name, nonce, nonce, true
lua_rawset(L, -5); // ..., dirs, system, dlist = { ..., [nonce] = true }, name, nonce
}
}
dirs->mDirsList = lua_ref(L, 1); // ..., dirs, system
lua_getglobal(L, "require");// ..., dirs, system, require; n.b. io might not be loaded, e.g. in luaproc process
lua_pushliteral(L, "io"); // ..., dirs, system, require, "io"
lua_call(L, 1, 1); // ..., dirs, system, io
lua_getfield(L, -1, "open");// ..., dirs, system, io, io.open
dirs->mIO_Open = lua_ref(L, 1); // ..., dirs, system, io
lua_pop(L, 2); // ..., dirs
return dirs;
}
const char * Directories::Canonicalize (lua_State * L, bool bRead, int arg)
{
arg = CoronaLuaNormalize(L, arg);
luaL_checkstring(L, arg);
lua_getref(L, mPathForFile);// ..., str[, dir], ..., pathForFile
lua_pushvalue(L, arg); // ..., str[, dir], ..., pathForFile, str
if (IsDir(L, arg + 1))
{
lua_pushvalue(L, arg + 1); // ..., str, dir, ..., pathForFile, str, dir
lua_remove(L, arg + 1); // ..., str, ..., pathForFile, str, dir
}
else lua_getref(L, bRead ? mResourceDir : mDocumentsDir); // ..., str, ..., pathForFile, str, def_dir
lua_call(L, 2, 1); // ..., str, ..., file
if (lua_isnil(L, -1))
{
lua_pop(L, 1); // ..., str, ...
lua_pushliteral(L, ""); // ..., str, ..., ""
}
lua_replace(L, arg);// ..., file / "", ...
return lua_tostring(L, arg);
}
bool Directories::IsDir (lua_State * L, int arg)
{
lua_pushvalue(L, arg); // ..., dir?, ..., dir?
lua_getref(L, mDirsList); // ..., dir?, list
lua_insert(L, -2); // ..., dir?, ..., list, dir?
lua_rawget(L, -2); // ..., dir?, ..., list, is_dir
bool bIsDir = LuaXS::Bool(L);
lua_pop(L, 2); // ..., dir?, ...
return bIsDir;
}
#ifdef __ANDROID__
static AAssetManager * sAssets;
static jclass sAssetsRef;
void Directories::InitAssets (JavaVM * vm)
{
JNIEnv * env;
__android_log_print(ANDROID_LOG_VERBOSE, "BYTEMAP", "InitAssets JVM: %p", vm); jint result = vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6);
__android_log_print(ANDROID_LOG_VERBOSE, "BYTEMAP", "InitAssets GetEnv(): %i", result);
if (result != JNI_OK) return;
// Adapted from code in:
// https://github.com/openfl/lime/blob/e511c0d2a5d616081a7826416d111aff1d428025/legacy
jclass cls = env->FindClass("com/ansca/corona/CoronaActivity");
__android_log_print(ANDROID_LOG_VERBOSE, "BYTEMAP", "InitAssets FindClass(): %i", (int)cls);
jmethodID mid = env->GetStaticMethodID(cls, "getAssetManager", "()Landroid/content/res/AssetManager;");
__android_log_print(ANDROID_LOG_VERBOSE, "BYTEMAP", "InitAssets getAssetManager(): %i", (int)mid);
if (mid)
{
jobject amgr = (jobject)env->CallStaticObjectMethod(cls, mid);
__android_log_print(ANDROID_LOG_VERBOSE, "BYTEMAP", "InitAssets call it: %i", (int)amgr);
if (amgr)
{
sAssets = AAssetManager_fromJava(env, amgr);
__android_log_print(ANDROID_LOG_VERBOSE, "BYTEMAP", "InitAssets assets: %p", (int)sAssets);
if (sAssets) sAssetsRef = (jclass)env->NewGlobalRef(amgr);
__android_log_print(ANDROID_LOG_VERBOSE, "BYTEMAP", "InitAssets sAssetsRef: %i", (int)sAssetsRef); env->DeleteLocalRef(amgr);
}
}
}
static bool InResourceDir (Directories * dirs, lua_State * L, int darg)
{
lua_getref(L, dirs->mResourceDir); // ..., dir, ..., ResourceDirectory
bool bIn = lua_equal(L, darg, -1) != 0;
lua_pop(L, 1); // ..., dir, ...
return bIn;
}
struct AssetRequest {
const char * mFilename;
std::vector<unsigned char> & mContents;
bool mOK{false};
AssetRequest (const char * filename, std::vector<unsigned char> & contents) : mFilename{filename}, mContents(contents)
{
}
};
static int GetAsset (lua_State * L)
{
AssetRequest * ar = LuaXS::UD<AssetRequest>(L, 1);
AAsset * asset = AAssetManager_open(sAssets, ar->mFilename, AASSET_MODE_BUFFER);
if (asset)
{
size_t len = AAsset_getLength(asset);
ar->mContents.resize(len);
AAsset_read(asset, ar->mContents.data(), len);
AAsset_close(asset);
}
return 0;
}
static bool CheckAssets (Directories * dirs, lua_State * L, std::vector<unsigned char> & contents, int arg)
{
__android_log_print(ANDROID_LOG_VERBOSE, "BYTEMAP", "CheckAssets assets: %p", sAssets);
if (!sAssets) return false;
const char * filename = luaL_checkstring(L, arg);
bool bHasDir = dirs->IsDir(L, arg + 1);
__android_log_print(ANDROID_LOG_VERBOSE, "BYTEMAP", "InitAssets file: %s", filename); if (!bHasDir || InResourceDir(dirs, L, arg + 1))
{
AssetRequest ar{filename, contents};
__android_log_print(ANDROID_LOG_VERBOSE, "BYTEMAP", "Before request"); LuaXS::CallInMainState(L, GetAsset, &ar);
__android_log_print(ANDROID_LOG_VERBOSE, "BYTEMAP", "After request"); if (bHasDir) lua_remove(L, arg + 1);// ..., str, ...
return ar.mOK;
}
return false;
}
#endif
bool Directories::ReadFileContents (lua_State * L, std::vector<unsigned char> & contents, int arg, bool bWantText)
{
arg = CoronaLuaNormalize(L, arg);
#ifdef __ANDROID__
if (CheckAssets(this, L, contents, arg)) return true;
#endif
const char * filename = Canonicalize(L, true, arg); // ..., filename, ...
lua_getref(L, mIO_Open);// ..., filename, ..., io.open
lua_pushvalue(L, arg); // ..., filename, ..., io.open, filename
lua_pushstring(L, bWantText ? "r" : "rb"); // ..., filename, ..., io.open, filename, mode
lua_call(L, 2, 1); // ..., filename, ..., file / nil
bool bOpened = !lua_isnil(L, -1);
if (bOpened)
{
lua_getfield(L, -1, "read");// ..., filename, ..., file, file.read
lua_insert(L, -2); // ..., filename, ..., file.read, file
lua_pushliteral(L, "*a"); // ..., filename, ..., file.read, file, "*a"
lua_call(L, 2, 1); // ..., filename, ..., contents
const unsigned char * uc = reinterpret_cast<const unsigned char *>(lua_tostring(L, -1));
contents.assign(uc, uc + lua_objlen(L, -1));
}
lua_pop(L, 1); // ..., filename, ...
return bOpened;
}
void LibLoader::Close (void)
{
if (IsLoaded())
{
#ifdef _WIN32
FreeLibrary(mLib);
#else
dlclose(mLib);
#endif
}
mLib = nullptr;
}
void LibLoader::Load (const char * name)
{
Close();
#ifdef _WIN32
mLib = LoadLibraryExA(name, nullptr, 0); // following nvcore/Library.h...
#else
mLib = dlopen(name, RTLD_LAZY);
#endif
}
WriteAux::WriteAux (lua_State * L, int dim, Directories * dirs)
{
if (dirs) mFilename = dirs->Canonicalize(L, false); // n.b. might remove dir
mW = luaL_checkint(L, dim);
mH = luaL_checkint(L, dim + 1);
}
WriteAuxReader::WriteAuxReader (lua_State * L, int dim, int barg, Directories * dirs) : WriteAux{L, dim, dirs}, mReader{L, barg}
{
if (!mReader.mBytes) lua_error(L);
}
}
<|endoftext|>
|
<commit_before>/*
###############################################################################
#
# EGSnrc egs++ isotropic source
# Copyright (C) 2015 National Research Council Canada
#
# This file is part of EGSnrc.
#
# EGSnrc is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# EGSnrc 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 Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with EGSnrc. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
#
# Author: Iwan Kawrakow, 2005
#
# Contributors:
#
###############################################################################
*/
/*! \file egs_isotropic_source.cpp
* \brief An isotropic source
* \IK
*/
#include "egs_isotropic_source.h"
#include "egs_input.h"
#include "egs_math.h"
EGS_IsotropicSource::EGS_IsotropicSource(EGS_Input *input,
EGS_ObjectFactory *f) : EGS_BaseSimpleSource(input,f), shape(0), geom(0),
regions(0), min_theta(0), max_theta(M_PI), min_phi(0), max_phi(2*M_PI),
gc(IncludeAll) {
vector<EGS_Float> pos;
EGS_Input *ishape = input->takeInputItem("shape");
if (ishape) {
egsWarning("EGS_IsotropicSource: trying to construct the shape\n");
shape = EGS_BaseShape::createShape(ishape);
delete ishape;
}
if (!shape) {
string sname;
int err = input->getInput("shape name",sname);
if (err)
egsWarning("EGS_IsotropicSource: missing/wrong inline shape "
"definition and missing wrong 'shape name' input\n");
else {
shape = EGS_BaseShape::getShape(sname);
if (!shape) egsWarning("EGS_IsotropicSource: a shape named %s"
" does not exist\n");
}
}
string geom_name;
int err = input->getInput("geometry",geom_name);
if (!err) {
geom = EGS_BaseGeometry::getGeometry(geom_name);
if (!geom) egsWarning("EGS_IsotropicSource: no geometry named %s\n",
geom_name.c_str());
else {
vector<string> reg_options;
reg_options.push_back("IncludeAll");
reg_options.push_back("ExcludeAll");
reg_options.push_back("IncludeSelected");
reg_options.push_back("ExcludeSelected");
gc = (GeometryConfinement) input->getInput("region selection",reg_options,0);
if (gc == IncludeSelected || gc == ExcludeSelected) {
vector<int> regs;
err = input->getInput("selected regions",regs);
if (err || regs.size() < 1) {
egsWarning("EGS_IsotropicSource: region selection %d used "
"but no 'selected regions' input found\n",gc);
gc = gc == IncludeSelected ? IncludeAll : ExcludeAll;
egsWarning(" using %d\n",gc);
}
nrs = regs.size();
regions = new int [nrs];
for (int j=0; j<nrs; j++) {
regions[j] = regs[j];
}
}
}
}
EGS_Float tmp_theta;
err = input->getInput("min theta", tmp_theta);
if (!err) {
min_theta = tmp_theta/180.0*M_PI;
}
err = input->getInput("max theta", tmp_theta);
if (!err) {
max_theta = tmp_theta/180.0*M_PI;
}
err = input->getInput("min phi", tmp_theta);
if (!err) {
min_phi = tmp_theta/180.0*M_PI;
}
err = input->getInput("max phi", tmp_theta);
if (!err) {
max_phi = tmp_theta/180.0*M_PI;
}
buf_1 = cos(min_theta);
buf_2 = cos(max_theta);
setUp();
}
void EGS_IsotropicSource::setUp() {
otype = "EGS_IsotropicSource";
if (!isValid()) {
description = "Invalid isotropic source";
}
else {
description = "Isotropic source from a shape of type ";
description += shape->getObjectType();
description += " with ";
description += s->getType();
if (q == -1) {
description += ", electrons";
}
else if (q == 0) {
description += ", photons";
}
else if (q == 1) {
description += ", positrons";
}
else {
description += ", unknown particle type";
}
if (geom) {
geom->ref();
}
}
}
extern "C" {
EGS_ISOTROPIC_SOURCE_EXPORT EGS_BaseSource *createSource(EGS_Input *input,
EGS_ObjectFactory *f) {
return
createSourceTemplate<EGS_IsotropicSource>(input,f,"isotropic source");
}
}
<commit_msg>Add missing nrs initializer.<commit_after>/*
###############################################################################
#
# EGSnrc egs++ isotropic source
# Copyright (C) 2015 National Research Council Canada
#
# This file is part of EGSnrc.
#
# EGSnrc is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# EGSnrc 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 Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with EGSnrc. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
#
# Author: Iwan Kawrakow, 2005
#
# Contributors:
#
###############################################################################
*/
/*! \file egs_isotropic_source.cpp
* \brief An isotropic source
* \IK
*/
#include "egs_isotropic_source.h"
#include "egs_input.h"
#include "egs_math.h"
EGS_IsotropicSource::EGS_IsotropicSource(EGS_Input *input,
EGS_ObjectFactory *f) : EGS_BaseSimpleSource(input,f), shape(0), geom(0),
regions(0), nrs(0), min_theta(0), max_theta(M_PI), min_phi(0), max_phi(2*M_PI),
gc(IncludeAll) {
vector<EGS_Float> pos;
EGS_Input *ishape = input->takeInputItem("shape");
if (ishape) {
egsWarning("EGS_IsotropicSource: trying to construct the shape\n");
shape = EGS_BaseShape::createShape(ishape);
delete ishape;
}
if (!shape) {
string sname;
int err = input->getInput("shape name",sname);
if (err)
egsWarning("EGS_IsotropicSource: missing/wrong inline shape "
"definition and missing wrong 'shape name' input\n");
else {
shape = EGS_BaseShape::getShape(sname);
if (!shape) egsWarning("EGS_IsotropicSource: a shape named %s"
" does not exist\n");
}
}
string geom_name;
int err = input->getInput("geometry",geom_name);
if (!err) {
geom = EGS_BaseGeometry::getGeometry(geom_name);
if (!geom) egsWarning("EGS_IsotropicSource: no geometry named %s\n",
geom_name.c_str());
else {
vector<string> reg_options;
reg_options.push_back("IncludeAll");
reg_options.push_back("ExcludeAll");
reg_options.push_back("IncludeSelected");
reg_options.push_back("ExcludeSelected");
gc = (GeometryConfinement) input->getInput("region selection",reg_options,0);
if (gc == IncludeSelected || gc == ExcludeSelected) {
vector<int> regs;
err = input->getInput("selected regions",regs);
if (err || regs.size() < 1) {
egsWarning("EGS_IsotropicSource: region selection %d used "
"but no 'selected regions' input found\n",gc);
gc = gc == IncludeSelected ? IncludeAll : ExcludeAll;
egsWarning(" using %d\n",gc);
}
nrs = regs.size();
regions = new int [nrs];
for (int j=0; j<nrs; j++) {
regions[j] = regs[j];
}
}
}
}
EGS_Float tmp_theta;
err = input->getInput("min theta", tmp_theta);
if (!err) {
min_theta = tmp_theta/180.0*M_PI;
}
err = input->getInput("max theta", tmp_theta);
if (!err) {
max_theta = tmp_theta/180.0*M_PI;
}
err = input->getInput("min phi", tmp_theta);
if (!err) {
min_phi = tmp_theta/180.0*M_PI;
}
err = input->getInput("max phi", tmp_theta);
if (!err) {
max_phi = tmp_theta/180.0*M_PI;
}
buf_1 = cos(min_theta);
buf_2 = cos(max_theta);
setUp();
}
void EGS_IsotropicSource::setUp() {
otype = "EGS_IsotropicSource";
if (!isValid()) {
description = "Invalid isotropic source";
}
else {
description = "Isotropic source from a shape of type ";
description += shape->getObjectType();
description += " with ";
description += s->getType();
if (q == -1) {
description += ", electrons";
}
else if (q == 0) {
description += ", photons";
}
else if (q == 1) {
description += ", positrons";
}
else {
description += ", unknown particle type";
}
if (geom) {
geom->ref();
}
}
}
extern "C" {
EGS_ISOTROPIC_SOURCE_EXPORT EGS_BaseSource *createSource(EGS_Input *input,
EGS_ObjectFactory *f) {
return
createSourceTemplate<EGS_IsotropicSource>(input,f,"isotropic source");
}
}
<|endoftext|>
|
<commit_before>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//$Id$
#ifndef MECHANICTRANSLATIONALMASS_HPP_INCLUDED
#define MECHANICTRANSLATIONALMASS_HPP_INCLUDED
#include <sstream>
#include <math.h>
#include "../../ComponentEssentials.h"
#include "../../ComponentUtilities.h"
namespace hopsan {
//!
//! @brief
//! @ingroup MechanicalComponents
//!
class MechanicTranslationalMass : public ComponentQ
{
private:
double m, B, k, xMin, xMax;
double mLength; //This length is not accesible by the user,
//it is set from the start values by the c-components in the ends
double *mpND_f1, *mpND_x1, *mpND_v1, *mpND_c1, *mpND_Zx1, *mpND_me1, *mpND_f2, *mpND_x2, *mpND_v2, *mpND_c2, *mpND_Zx2, *mpND_me2; //Node data pointers
double f1, x1, v1, c1, Zx1, f2, x2, v2, c2, Zx2; //Node data variables
double mNumX[3], mNumV[2];
double mDenX[3], mDenV[2];
SecondOrderTransferFunction mFilterX;
FirstOrderTransferFunction mFilterV;
Port *mpP1, *mpP2;
public:
static Component *Creator()
{
return new MechanicTranslationalMass("TranslationalMass");
}
MechanicTranslationalMass(const std::string name) : ComponentQ(name)
{
//Set member attributes
m = 100.0;
B = 10;
k = 0.0;
xMin = 0.0;
xMax = 1.0;
//Add ports to the component
mpP1 = addPowerPort("P1", "NodeMechanic");
mpP2 = addPowerPort("P2", "NodeMechanic");
//Register changable parameters to the HOPSAN++ core
registerParameter("m", "Mass", "[kg]", m);
registerParameter("B", "Viscous Friction", "[Ns/m]", B);
registerParameter("k", "Spring Coefficient", "[N/m]", k);
registerParameter("x_min", "Minimum Position", "[m]", xMin);
registerParameter("x_max", "Maximum Position", "[m]", xMax);
}
void initialize()
{
//Assign node data pointers
mpND_f1 = getSafeNodeDataPtr(mpP1, NodeMechanic::FORCE);
mpND_x1 = getSafeNodeDataPtr(mpP1, NodeMechanic::POSITION);
mpND_v1 = getSafeNodeDataPtr(mpP1, NodeMechanic::VELOCITY);
mpND_c1 = getSafeNodeDataPtr(mpP1, NodeMechanic::WAVEVARIABLE);
mpND_Zx1 = getSafeNodeDataPtr(mpP1, NodeMechanic::CHARIMP);
mpND_me1 = getSafeNodeDataPtr(mpP1, NodeMechanic::EQMASS);
mpND_f2 = getSafeNodeDataPtr(mpP2, NodeMechanic::FORCE);
mpND_x2 = getSafeNodeDataPtr(mpP2, NodeMechanic::POSITION);
mpND_v2 = getSafeNodeDataPtr(mpP2, NodeMechanic::VELOCITY);
mpND_c2 = getSafeNodeDataPtr(mpP2, NodeMechanic::WAVEVARIABLE);
mpND_Zx2 = getSafeNodeDataPtr(mpP2, NodeMechanic::CHARIMP);
mpND_me2 = getSafeNodeDataPtr(mpP2, NodeMechanic::EQMASS);
//Initialization
f1 = (*mpND_f1);
f2 = (*mpND_f2);
x1 = (*mpND_x1);
v1 = (*mpND_v1);
x2 = (*mpND_x2);
v2 = (*mpND_v2);
mLength = x1+x2;
mNumX[0] = 1.0;
mNumX[1] = 0.0;
mNumX[2] = 0.0;
mDenX[0] = k;
mDenX[1] = B;
mDenX[2] = m;
mNumV[0] = 1.0;
mNumV[1] = 0.0;
mDenV[0] = B;
mDenV[1] = m;
mFilterX.initialize(mTimestep, mNumX, mDenX, f1-f2, x2);
mFilterV.initialize(mTimestep, mNumV, mDenV, f1-f2 - k*x2, v2);
(*mpND_me1) = m;
(*mpND_me2) = m;
//Print debug message if velocities do not match
if((*mpND_v1) != -(*mpND_v2))
{
std::stringstream ss;
ss << "Start velocities does not match, {" << getName() << "::" << mpP1->getPortName() <<
"} and {" << getName() << "::" << mpP2->getPortName() << "}.";
this->addDebugMessage(ss.str());
}
}
void simulateOneTimestep()
{
//Get variable values from nodes
c1 = (*mpND_c1);
Zx1 = (*mpND_Zx1);
c2 = (*mpND_c2);
Zx2 = (*mpND_Zx2);
//Mass equations
mDenX[1] = B+Zx1+Zx2;
mDenV[0] = B+Zx1+Zx2;
mFilterX.setDen(mDenX);
mFilterV.setDen(mDenV);
x2 = mFilterX.update(c1-c2);
v2 = mFilterV.update(c1-c2 - k*x2);
if((mTime > 6) && (mTime < 6.01))
{
double apa = c1-c2;
// stringstream ss;
// ss << "t: " << mTime << " c1-c2 = " << apa << " v2 = " << v2;
// addDebugMessage(ss.str());
}
if(x2<xMin)
{
x2=xMin;
v2=0.0;
mFilterX.initializeValues(c1-c2, x2);
mFilterV.initializeValues(c1-c2, 0.0);
}
if(x2>xMax)
{
x2=xMax;
v2=0.0;
mFilterX.initializeValues(c1-c2, x2);
mFilterV.initializeValues(c1-c2, 0.0);
}
v1 = -v2;
x1 = -x2 + mLength;
f1 = c1 + Zx1*v1;
f2 = c2 + Zx2*v2;
//Write new values to nodes
(*mpND_f1) = f1;
(*mpND_x1) = x1;
(*mpND_v1) = v1;
(*mpND_f2) = f2;
(*mpND_x2) = x2;
(*mpND_v2) = v2;
(*mpND_me1) = m;
(*mpND_me2) = m;
// if((mTime>.5) && (mTime<.5001))
// {
// std::stringstream ss;
// ss << "mTime: " << mTime << " c1-c2: " << c1-c2 << " v2: " << v2 << std::endl;
// addInfoMessage(ss.str());
// }
}
};
}
#endif // MECHANICTRANSLATIONALMASS_HPP_INCLUDED
<commit_msg>removed ugly debug mess<commit_after>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//$Id$
#ifndef MECHANICTRANSLATIONALMASS_HPP_INCLUDED
#define MECHANICTRANSLATIONALMASS_HPP_INCLUDED
#include <sstream>
#include <math.h>
#include "../../ComponentEssentials.h"
#include "../../ComponentUtilities.h"
namespace hopsan {
//!
//! @brief
//! @ingroup MechanicalComponents
//!
class MechanicTranslationalMass : public ComponentQ
{
private:
double m, B, k, xMin, xMax;
double mLength; //This length is not accesible by the user,
//it is set from the start values by the c-components in the ends
double *mpND_f1, *mpND_x1, *mpND_v1, *mpND_c1, *mpND_Zx1, *mpND_me1, *mpND_f2, *mpND_x2, *mpND_v2, *mpND_c2, *mpND_Zx2, *mpND_me2; //Node data pointers
double f1, x1, v1, c1, Zx1, f2, x2, v2, c2, Zx2; //Node data variables
double mNumX[3], mNumV[2];
double mDenX[3], mDenV[2];
SecondOrderTransferFunction mFilterX;
FirstOrderTransferFunction mFilterV;
Port *mpP1, *mpP2;
public:
static Component *Creator()
{
return new MechanicTranslationalMass("TranslationalMass");
}
MechanicTranslationalMass(const std::string name) : ComponentQ(name)
{
//Set member attributes
m = 100.0;
B = 10;
k = 0.0;
xMin = 0.0;
xMax = 1.0;
//Add ports to the component
mpP1 = addPowerPort("P1", "NodeMechanic");
mpP2 = addPowerPort("P2", "NodeMechanic");
//Register changable parameters to the HOPSAN++ core
registerParameter("m", "Mass", "[kg]", m);
registerParameter("B", "Viscous Friction", "[Ns/m]", B);
registerParameter("k", "Spring Coefficient", "[N/m]", k);
registerParameter("x_min", "Minimum Position", "[m]", xMin);
registerParameter("x_max", "Maximum Position", "[m]", xMax);
}
void initialize()
{
//Assign node data pointers
mpND_f1 = getSafeNodeDataPtr(mpP1, NodeMechanic::FORCE);
mpND_x1 = getSafeNodeDataPtr(mpP1, NodeMechanic::POSITION);
mpND_v1 = getSafeNodeDataPtr(mpP1, NodeMechanic::VELOCITY);
mpND_c1 = getSafeNodeDataPtr(mpP1, NodeMechanic::WAVEVARIABLE);
mpND_Zx1 = getSafeNodeDataPtr(mpP1, NodeMechanic::CHARIMP);
mpND_me1 = getSafeNodeDataPtr(mpP1, NodeMechanic::EQMASS);
mpND_f2 = getSafeNodeDataPtr(mpP2, NodeMechanic::FORCE);
mpND_x2 = getSafeNodeDataPtr(mpP2, NodeMechanic::POSITION);
mpND_v2 = getSafeNodeDataPtr(mpP2, NodeMechanic::VELOCITY);
mpND_c2 = getSafeNodeDataPtr(mpP2, NodeMechanic::WAVEVARIABLE);
mpND_Zx2 = getSafeNodeDataPtr(mpP2, NodeMechanic::CHARIMP);
mpND_me2 = getSafeNodeDataPtr(mpP2, NodeMechanic::EQMASS);
//Initialization
f1 = (*mpND_f1);
f2 = (*mpND_f2);
x1 = (*mpND_x1);
v1 = (*mpND_v1);
x2 = (*mpND_x2);
v2 = (*mpND_v2);
mLength = x1+x2;
mNumX[0] = 1.0;
mNumX[1] = 0.0;
mNumX[2] = 0.0;
mDenX[0] = k;
mDenX[1] = B;
mDenX[2] = m;
mNumV[0] = 1.0;
mNumV[1] = 0.0;
mDenV[0] = B;
mDenV[1] = m;
mFilterX.initialize(mTimestep, mNumX, mDenX, f1-f2, x2);
mFilterV.initialize(mTimestep, mNumV, mDenV, f1-f2 - k*x2, v2);
(*mpND_me1) = m;
(*mpND_me2) = m;
//Print debug message if velocities do not match
if((*mpND_v1) != -(*mpND_v2))
{
std::stringstream ss;
ss << "Start velocities does not match, {" << getName() << "::" << mpP1->getPortName() <<
"} and {" << getName() << "::" << mpP2->getPortName() << "}.";
this->addDebugMessage(ss.str());
}
}
void simulateOneTimestep()
{
//Get variable values from nodes
c1 = (*mpND_c1);
Zx1 = (*mpND_Zx1);
c2 = (*mpND_c2);
Zx2 = (*mpND_Zx2);
//Mass equations
mDenX[1] = B+Zx1+Zx2;
mDenV[0] = B+Zx1+Zx2;
mFilterX.setDen(mDenX);
mFilterV.setDen(mDenV);
x2 = mFilterX.update(c1-c2);
v2 = mFilterV.update(c1-c2 - k*x2);
// if((mTime > 6) && (mTime < 6.01))
// {
// double apa = c1-c2;
// stringstream ss;
// ss << "t: " << mTime << " c1-c2 = " << apa << " v2 = " << v2;
// addDebugMessage(ss.str());
// }
if(x2<xMin)
{
x2=xMin;
v2=0.0;
mFilterX.initializeValues(c1-c2, x2);
mFilterV.initializeValues(c1-c2, 0.0);
}
if(x2>xMax)
{
x2=xMax;
v2=0.0;
mFilterX.initializeValues(c1-c2, x2);
mFilterV.initializeValues(c1-c2, 0.0);
}
v1 = -v2;
x1 = -x2 + mLength;
f1 = c1 + Zx1*v1;
f2 = c2 + Zx2*v2;
//Write new values to nodes
(*mpND_f1) = f1;
(*mpND_x1) = x1;
(*mpND_v1) = v1;
(*mpND_f2) = f2;
(*mpND_x2) = x2;
(*mpND_v2) = v2;
(*mpND_me1) = m;
(*mpND_me2) = m;
// if((mTime>.5) && (mTime<.5001))
// {
// std::stringstream ss;
// ss << "mTime: " << mTime << " c1-c2: " << c1-c2 << " v2: " << v2 << std::endl;
// addInfoMessage(ss.str());
// }
}
};
}
#endif // MECHANICTRANSLATIONALMASS_HPP_INCLUDED
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Foundation_Traversal_IterableFromIterator_inl_
#define _Stroika_Foundation_Traversal_IterableFromIterator_inl_
#include "../Debug/Assertions.h"
#include "DelegatedIterator.h"
namespace Stroika::Foundation::Traversal {
#if qDebug
namespace Private_ {
template <typename T>
IteratorTracker<T>::~IteratorTracker ()
{
Assert (*fCountRunning == 0);
}
template <typename T>
Iterator<T> IteratorTracker<T>::MakeDelegatedIterator (const Iterator<T>& sourceIterator)
{
return DelegatedIterator<T, shared_ptr<unsigned int>> (sourceIterator, fCountRunning);
}
}
#endif
/*
********************************************************************************
* IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep *
********************************************************************************
*/
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
inline IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::_Rep (const CONTEXT_FOR_EACH_ITERATOR& contextForEachIterator)
: _fContextForEachIterator {contextForEachIterator}
{
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::MakeIterator () const
{
#if qDebug
return fIteratorTracker_.MakeDelegatedIterator (Iterator<T>{Iterator<T>::template MakeSmartPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)});
#else
return Iterator<T>{Iterator<T>::template MakeSmartPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)};
#endif
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
size_t IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::GetLength () const
{
size_t n = 0;
for (auto i = this->MakeIterator (); not i.Done (); ++i) {
n++;
}
return n;
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
bool IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::IsEmpty () const
{
for (auto i = this->MakeIterator (); not i.Done (); ++i) {
return false;
}
return true;
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
void IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::Apply (const function<void (ArgByValueType<value_type> item)>& doToElement) const
{
this->_Apply (doToElement);
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::FindFirstThat (const function<bool (ArgByValueType<value_type> item)>& doToElement) const
{
return this->_FindFirstThat (doToElement);
}
#define qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding 1
#if qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding
template <typename T>
size_t IterableFromIterator<T, void, void>::_Rep::GetLength () const
{
size_t n = 0;
for (auto i = this->MakeIterator (); not i.Done (); ++i) {
n++;
}
return n;
}
template <typename T>
bool IterableFromIterator<T, void, void>::_Rep::IsEmpty () const
{
for (auto i = this->MakeIterator (); not i.Done ();) {
return false;
}
return true;
}
template <typename T>
void IterableFromIterator<T, void, void>::_Rep::Apply (const function<void (ArgByValueType<value_type> item)>& doToElement) const
{
this->_Apply (doToElement);
}
template <typename T>
Iterator<T> IterableFromIterator<T, void, void>::_Rep::FindFirstThat (const function<bool (ArgByValueType<value_type> item)>& doToElement) const
{
return this->_FindFirstThat (doToElement);
}
#endif
/*
********************************************************************************
**************************** MakeIterableFromIterator **************************
********************************************************************************
*/
template <typename T>
Iterable<T> MakeIterableFromIterator (const Iterator<T>& iterator)
{
struct MyIterable_ : public Iterable<T> {
struct Rep : public IterableFromIterator<T>::_Rep, public Memory::UseBlockAllocationIfAppropriate<Rep> {
using _IterableRepSharedPtr = typename Iterable<T>::_IterableRepSharedPtr;
Iterator<T> fOriginalIterator;
#if qDebug
mutable Private_::IteratorTracker<T> fIteratorTracker_{};
#endif
Rep (const Iterator<T>& originalIterator)
: fOriginalIterator{originalIterator}
{
}
virtual Iterator<T> MakeIterator () const override
{
#if qDebug
return fIteratorTracker_.MakeDelegatedIterator (fOriginalIterator);
#else
return fOriginalIterator;
#endif
}
virtual _IterableRepSharedPtr Clone () const override
{
return Iterable<T>::template MakeSmartPtr<Rep> (*this);
}
};
MyIterable_ (const Iterator<T>& originalIterator)
: Iterable<T>{Iterable<T>::template MakeSmartPtr<Rep> (originalIterator)}
{
}
};
return MyIterable_{iterator};
}
}
#endif /* _Stroika_Foundation_Traversal_IterableFromIterator_inl_ */
<commit_msg>cosmetic<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Foundation_Traversal_IterableFromIterator_inl_
#define _Stroika_Foundation_Traversal_IterableFromIterator_inl_
#include "../Debug/Assertions.h"
#include "DelegatedIterator.h"
namespace Stroika::Foundation::Traversal {
#if qDebug
namespace Private_ {
template <typename T>
IteratorTracker<T>::~IteratorTracker ()
{
Assert (*fCountRunning == 0);
}
template <typename T>
Iterator<T> IteratorTracker<T>::MakeDelegatedIterator (const Iterator<T>& sourceIterator)
{
return DelegatedIterator<T, shared_ptr<unsigned int>> (sourceIterator, fCountRunning);
}
}
#endif
/*
********************************************************************************
* IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep *
********************************************************************************
*/
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
inline IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::_Rep (const CONTEXT_FOR_EACH_ITERATOR& contextForEachIterator)
: _fContextForEachIterator{contextForEachIterator}
{
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::MakeIterator () const
{
#if qDebug
return fIteratorTracker_.MakeDelegatedIterator (Iterator<T>{Iterator<T>::template MakeSmartPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)});
#else
return Iterator<T>{Iterator<T>::template MakeSmartPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)};
#endif
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
size_t IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::GetLength () const
{
size_t n = 0;
for (auto i = this->MakeIterator (); not i.Done (); ++i) {
n++;
}
return n;
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
bool IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::IsEmpty () const
{
for (auto i = this->MakeIterator (); not i.Done (); ++i) {
return false;
}
return true;
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
void IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::Apply (const function<void (ArgByValueType<value_type> item)>& doToElement) const
{
this->_Apply (doToElement);
}
template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>
Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::FindFirstThat (const function<bool (ArgByValueType<value_type> item)>& doToElement) const
{
return this->_FindFirstThat (doToElement);
}
#define qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding 1
#if qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding
template <typename T>
size_t IterableFromIterator<T, void, void>::_Rep::GetLength () const
{
size_t n = 0;
for (auto i = this->MakeIterator (); not i.Done (); ++i) {
n++;
}
return n;
}
template <typename T>
bool IterableFromIterator<T, void, void>::_Rep::IsEmpty () const
{
for (auto i = this->MakeIterator (); not i.Done ();) {
return false;
}
return true;
}
template <typename T>
void IterableFromIterator<T, void, void>::_Rep::Apply (const function<void (ArgByValueType<value_type> item)>& doToElement) const
{
this->_Apply (doToElement);
}
template <typename T>
Iterator<T> IterableFromIterator<T, void, void>::_Rep::FindFirstThat (const function<bool (ArgByValueType<value_type> item)>& doToElement) const
{
return this->_FindFirstThat (doToElement);
}
#endif
/*
********************************************************************************
**************************** MakeIterableFromIterator **************************
********************************************************************************
*/
template <typename T>
Iterable<T> MakeIterableFromIterator (const Iterator<T>& iterator)
{
struct MyIterable_ : public Iterable<T> {
struct Rep : public IterableFromIterator<T>::_Rep, public Memory::UseBlockAllocationIfAppropriate<Rep> {
using _IterableRepSharedPtr = typename Iterable<T>::_IterableRepSharedPtr;
Iterator<T> fOriginalIterator;
#if qDebug
mutable Private_::IteratorTracker<T> fIteratorTracker_{};
#endif
Rep (const Iterator<T>& originalIterator)
: fOriginalIterator{originalIterator}
{
}
virtual Iterator<T> MakeIterator () const override
{
#if qDebug
return fIteratorTracker_.MakeDelegatedIterator (fOriginalIterator);
#else
return fOriginalIterator;
#endif
}
virtual _IterableRepSharedPtr Clone () const override
{
return Iterable<T>::template MakeSmartPtr<Rep> (*this);
}
};
MyIterable_ (const Iterator<T>& originalIterator)
: Iterable<T>{Iterable<T>::template MakeSmartPtr<Rep> (originalIterator)}
{
}
};
return MyIterable_{iterator};
}
}
#endif /* _Stroika_Foundation_Traversal_IterableFromIterator_inl_ */
<|endoftext|>
|
<commit_before>// Associated with CWE-190: Integer Overflow or Wraparound. http://cwe.mitre.org/data/definitions/190.html
typedef unsigned long size_t;
typedef struct {} FILE;
void *malloc(size_t size);
void *realloc(void *ptr, size_t size);
int atoi(const char *nptr);
struct MyStruct
{
char data[256];
};
namespace std
{
template<class charT> struct char_traits;
template <class charT, class traits = char_traits<charT> >
class basic_istream /*: virtual public basic_ios<charT,traits> - not needed for this test */ {
public:
basic_istream<charT,traits>& operator>>(int& n);
};
typedef basic_istream<char> istream;
extern istream cin;
}
int getTainted() {
int i;
std::cin >> i;
return i;
}
int main(int argc, char **argv) {
int tainted = atoi(argv[1]);
MyStruct *arr1 = (MyStruct *)malloc(sizeof(MyStruct)); // GOOD
MyStruct *arr2 = (MyStruct *)malloc(tainted); // BAD
MyStruct *arr3 = (MyStruct *)malloc(tainted * sizeof(MyStruct)); // BAD
MyStruct *arr4 = (MyStruct *)malloc(getTainted() * sizeof(MyStruct)); // BAD [NOT DETECTED]
MyStruct *arr5 = (MyStruct *)malloc(sizeof(MyStruct) + tainted); // BAD [NOT DETECTED]
int size = tainted * 8;
char *chars1 = (char *)malloc(size); // BAD
char *chars2 = new char[size]; // BA
char *chars3 = new char[8]; // GOOD
arr1 = (MyStruct *)realloc(arr1, sizeof(MyStruct) * tainted); // BAD
size = 8;
chars3 = new char[size]; // GOOD [FALSE POSITIVE]
return 0;
}
<commit_msg>CPP: Fix 'BAD'.<commit_after>// Associated with CWE-190: Integer Overflow or Wraparound. http://cwe.mitre.org/data/definitions/190.html
typedef unsigned long size_t;
typedef struct {} FILE;
void *malloc(size_t size);
void *realloc(void *ptr, size_t size);
int atoi(const char *nptr);
struct MyStruct
{
char data[256];
};
namespace std
{
template<class charT> struct char_traits;
template <class charT, class traits = char_traits<charT> >
class basic_istream /*: virtual public basic_ios<charT,traits> - not needed for this test */ {
public:
basic_istream<charT,traits>& operator>>(int& n);
};
typedef basic_istream<char> istream;
extern istream cin;
}
int getTainted() {
int i;
std::cin >> i;
return i;
}
int main(int argc, char **argv) {
int tainted = atoi(argv[1]);
MyStruct *arr1 = (MyStruct *)malloc(sizeof(MyStruct)); // GOOD
MyStruct *arr2 = (MyStruct *)malloc(tainted); // BAD
MyStruct *arr3 = (MyStruct *)malloc(tainted * sizeof(MyStruct)); // BAD
MyStruct *arr4 = (MyStruct *)malloc(getTainted() * sizeof(MyStruct)); // BAD [NOT DETECTED]
MyStruct *arr5 = (MyStruct *)malloc(sizeof(MyStruct) + tainted); // BAD [NOT DETECTED]
int size = tainted * 8;
char *chars1 = (char *)malloc(size); // BAD
char *chars2 = new char[size]; // BAD
char *chars3 = new char[8]; // GOOD
arr1 = (MyStruct *)realloc(arr1, sizeof(MyStruct) * tainted); // BAD
size = 8;
chars3 = new char[size]; // GOOD [FALSE POSITIVE]
return 0;
}
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
//Mitk
#include <mitkDataNode.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateProperty.h>
// Qmitk
#include "UltrasoundSupport.h"
#include <QTimer>
// Qt
#include <QMessageBox>
// Ultrasound
#include "mitkUSDevice.h"
#include "QmitkUSAbstractCustomWidget.h"
#include <usModuleContext.h>
#include <usGetModuleContext.h>
#include "usServiceReference.h"
#include "internal/org_mitk_gui_qt_ultrasound_Activator.h"
#include <ctkFlowLayout.h>
#include <ctkDoubleSlider.h>
const std::string UltrasoundSupport::VIEW_ID = "org.mitk.views.ultrasoundsupport";
void UltrasoundSupport::SetFocus()
{
//m_Controls.m_AddDevice->setFocus();
}
void UltrasoundSupport::CreateQtPartControl( QWidget *parent )
{
m_Timer = new QTimer(this);
// create GUI widgets from the Qt Designer's .ui file
m_Controls.setupUi( parent );
connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this, SLOT(OnClickedAddNewDevice()) ); // Change Widget Visibilities
connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this->m_Controls.m_NewVideoDeviceWidget, SLOT(CreateNewDevice()) ); // Init NewDeviceWidget
connect( m_Controls.m_NewVideoDeviceWidget, SIGNAL(Finished()), this, SLOT(OnNewDeviceWidgetDone()) ); // After NewDeviceWidget finished editing
connect( m_Controls.m_BtnView, SIGNAL(clicked()), this, SLOT(OnClickedViewDevice()) );
connect( m_Controls.m_FrameRate, SIGNAL(valueChanged(int)), this, SLOT(OnChangedFramerateLimit(int)) );
connect( m_Controls.m_FreezeButton, SIGNAL(clicked()), this, SLOT(OnClickedFreezeButton()) );
connect( m_Timer, SIGNAL(timeout()), this, SLOT(DisplayImage()));
// Initializations
m_Controls.m_NewVideoDeviceWidget->setVisible(false);
std::string filter = "(&(" + us::ServiceConstants::OBJECTCLASS() + "=" + "org.mitk.services.UltrasoundDevice)(" + mitk::USDevice::US_PROPKEY_ISACTIVE + "=true))";
m_Controls.m_ActiveVideoDevices->Initialize<mitk::USDevice>(mitk::USDevice::US_PROPKEY_LABEL ,filter);
m_Node = mitk::DataNode::New();
m_Node->SetName("US Image Stream");
this->GetDataStorage()->Add(m_Node);
m_Controls.tabWidget->setTabEnabled(1, false);
/*ctkFlowLayout* flowLayout = ctkFlowLayout::replaceLayout(m_Controls.m_WidgetDevices);
flowLayout->setAlignItems(true);
flowLayout->setOrientation(Qt::Vertical);*/
}
void UltrasoundSupport::OnClickedAddNewDevice()
{
m_Controls.m_NewVideoDeviceWidget->setVisible(true);
m_Controls.m_DeviceManagerWidget->setVisible(false);
m_Controls.m_Headline->setText("Add New Video Device:");
m_Controls.m_WidgetActiveDevices->setVisible(false);
}
void UltrasoundSupport::DisplayImage()
{
m_Device->Modified();
m_Device->UpdateOutputData(0);
mitk::Image::Pointer curOutput = m_Device->GetOutput();
if (curOutput.IsNotNull() && curOutput->IsInitialized()) { m_Node->SetData(curOutput); }
this->RequestRenderWindowUpdate();
if ( curOutput->GetDimension() > 1
&& (curOutput->GetDimension(0) != m_CurrentImageWidth
|| curOutput->GetDimension(1) != m_CurrentImageHeight) )
{
this->GlobalReinit();
m_CurrentImageWidth = curOutput->GetDimension(0);
m_CurrentImageHeight = curOutput->GetDimension(1);
}
m_FrameCounter ++;
if (m_FrameCounter == 10)
{
int nMilliseconds = m_Clock.restart();
int fps = 10000.0f / (nMilliseconds );
m_Controls.m_FramerateLabel->setText("Current Framerate: "+ QString::number(fps) +" FPS");
m_FrameCounter = 0;
}
}
void UltrasoundSupport::OnClickedViewDevice()
{
m_FrameCounter = 0;
// We use the activity state of the timer to determine whether we are currently viewing images
if ( ! m_Timer->isActive() ) // Activate Imaging
{
this->StartViewing();
}
else //deactivate imaging
{
this->StopViewing();
}
}
void UltrasoundSupport::OnChangedFramerateLimit(int value)
{
m_Timer->setInterval(1000 / value);
}
void UltrasoundSupport::OnClickedFreezeButton()
{
if ( m_Device->GetIsFreezed() )
{
m_Device->SetIsFreezed(false);
m_Controls.m_FreezeButton->setText("Freeze");
}
else
{
m_Device->SetIsFreezed(true);
m_Controls.m_FreezeButton->setText("Start Viewing Again");
}
}
void UltrasoundSupport::OnNewDeviceWidgetDone()
{
m_Controls.m_NewVideoDeviceWidget->setVisible(false);
m_Controls.m_DeviceManagerWidget->setVisible(true);
m_Controls.m_Headline->setText("Ultrasound Devices:");
m_Controls.m_WidgetActiveDevices->setVisible(true);
}
void UltrasoundSupport::GlobalReinit()
{
// get all nodes that have not set "includeInBoundingBox" to false
mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false)));
mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred);
// calculate bounding geometry of these nodes
mitk::TimeGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible");
// initialize the views to the bounding geometry
mitk::RenderingManager::GetInstance()->InitializeViews(bounds);
}
void UltrasoundSupport::StartViewing()
{
m_Controls.tabWidget->setTabEnabled(1, true);
m_Controls.tabWidget->setCurrentIndex(1);
//get device & set data node
m_Device = m_Controls.m_ActiveVideoDevices->GetSelectedService<mitk::USDevice>();
if (m_Device.IsNull())
{
m_Timer->stop();
return;
}
//start timer
int interval = (1000 / m_Controls.m_FrameRate->value());
m_Timer->setInterval(interval);
m_Timer->start();
//reinit view
//this->GlobalReinit();
//change UI elements
m_Controls.m_BtnView->setText("Stop Viewing");
this->CreateControlWidgets();
}
void UltrasoundSupport::StopViewing()
{
m_Controls.tabWidget->setTabEnabled(1, false);
this->RemoveControlWidgets();
//stop timer & release data
m_Timer->stop();
m_Node->ReleaseData();
this->RequestRenderWindowUpdate();
//change UI elements
m_Controls.m_BtnView->setText("Start Viewing");
}
void UltrasoundSupport::CreateControlWidgets()
{
m_ControlProbesWidget = new QmitkUSControlsProbesWidget(m_Device->GetControlInterfaceProbes(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.probesWidgetContainer->addWidget(m_ControlProbesWidget);
unsigned int firstEnabledControl = -1;
// create b mode widget for current device
m_ControlBModeWidget = new QmitkUSControlsBModeWidget(m_Device->GetControlInterfaceBMode(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlBModeWidget, "B Mode Controls");
if ( ! m_Device->GetControlInterfaceBMode() )
{
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
else
{
if ( firstEnabledControl == -1 ) { firstEnabledControl = 0; }
}
// create doppler widget for current device
m_ControlDopplerWidget = new QmitkUSControlsDopplerWidget(m_Device->GetControlInterfaceDoppler(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlDopplerWidget, "Doppler Controls");
if ( ! m_Device->GetControlInterfaceDoppler() )
{
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
else
{
if ( firstEnabledControl == -1 ) { firstEnabledControl = 0; }
}
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
if ( pluginContext )
{
std::string filter = "(ork.mitk.services.UltrasoundCustomWidget.deviceClass=" + m_Device->GetDeviceClass() + ")";
QString interfaceName ( us_service_interface_iid<QmitkUSAbstractCustomWidget>() );
m_CustomWidgetServiceReference = pluginContext->getServiceReferences(interfaceName, QString::fromStdString(filter));
if (m_CustomWidgetServiceReference.size() > 0)
{
m_ControlCustomWidget = pluginContext->getService<QmitkUSAbstractCustomWidget>
(m_CustomWidgetServiceReference.at(0))->CloneForQt(m_Controls.tab2);
m_ControlCustomWidget->SetDevice(m_Device);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlCustomWidget, "Custom Controls");
}
else
{
m_Controls.m_ToolBoxControlWidgets->addItem(new QWidget(m_Controls.m_ToolBoxControlWidgets), "Custom Controls");
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
}
// select first enabled control widget
for ( unsigned int n = 0; n < m_Controls.m_ToolBoxControlWidgets->count(); ++n)
{
if ( m_Controls.m_ToolBoxControlWidgets->isItemEnabled(n) )
{
m_Controls.m_ToolBoxControlWidgets->setCurrentIndex(n);
break;
}
}
}
void UltrasoundSupport::RemoveControlWidgets()
{
// remove all control widgets from the tool box widget
while (m_Controls.m_ToolBoxControlWidgets->count() > 0)
{
m_Controls.m_ToolBoxControlWidgets->removeItem(0);
}
// remove probes widget (which is not part of the tool box widget)
m_Controls.probesWidgetContainer->removeWidget(m_ControlProbesWidget);
delete m_ControlProbesWidget;
m_ControlProbesWidget = 0;
delete m_ControlBModeWidget;
m_ControlBModeWidget = 0;
delete m_ControlDopplerWidget;
m_ControlDopplerWidget = 0;
// delete custom widget if it is present
if ( m_ControlCustomWidget )
{
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
delete m_ControlCustomWidget; m_ControlCustomWidget = 0;
if ( m_CustomWidgetServiceReference.size() > 0 )
{
pluginContext->ungetService(m_CustomWidgetServiceReference.at(0));
}
}
}
void UltrasoundSupport::OnDeciveServiceEvent(const ctkServiceEvent event)
{
if ( ! m_Device || event.getType() != us::ServiceEvent::MODIFIED ) { return; }
ctkServiceReference service = event.getServiceReference();
if ( m_Device->GetDeviceManufacturer() != service.getProperty(mitk::USImageMetadata::PROP_DEV_MANUFACTURER).toString().toStdString()
&& m_Device->GetDeviceModel() != service.getProperty(mitk::USImageMetadata::PROP_DEV_MODEL).toString().toStdString() )
{
return;
}
if ( ! m_Device->GetIsActive() && m_Timer->isActive() )
{
this->StopViewing();
}
}
UltrasoundSupport::UltrasoundSupport()
: m_ControlCustomWidget(0), m_ControlBModeWidget(0),
m_ControlProbesWidget(0), m_CurrentImageWidth(0),
m_CurrentImageHeight(0)
{
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
if ( pluginContext )
{
// to be notified about service event of an USDevice
pluginContext->connectServiceListener(this, "OnDeciveServiceEvent",
QString::fromStdString("(" + us::ServiceConstants::OBJECTCLASS() + "=" + us_service_interface_iid<mitk::USDevice>() + ")"));
}
}
UltrasoundSupport::~UltrasoundSupport()
{
}
<commit_msg>Ultrasound plugin makes reinit just on image and doesn't create the image stream node anymore if it already present.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
//Mitk
#include <mitkDataNode.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateProperty.h>
#include <mitkIRenderingManager.h>
// Qmitk
#include "UltrasoundSupport.h"
#include <QTimer>
// Qt
#include <QMessageBox>
// Ultrasound
#include "mitkUSDevice.h"
#include "QmitkUSAbstractCustomWidget.h"
#include <usModuleContext.h>
#include <usGetModuleContext.h>
#include "usServiceReference.h"
#include "internal/org_mitk_gui_qt_ultrasound_Activator.h"
#include <ctkFlowLayout.h>
#include <ctkDoubleSlider.h>
const std::string UltrasoundSupport::VIEW_ID = "org.mitk.views.ultrasoundsupport";
void UltrasoundSupport::SetFocus()
{
//m_Controls.m_AddDevice->setFocus();
}
void UltrasoundSupport::CreateQtPartControl( QWidget *parent )
{
m_Timer = new QTimer(this);
// create GUI widgets from the Qt Designer's .ui file
m_Controls.setupUi( parent );
connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this, SLOT(OnClickedAddNewDevice()) ); // Change Widget Visibilities
connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this->m_Controls.m_NewVideoDeviceWidget, SLOT(CreateNewDevice()) ); // Init NewDeviceWidget
connect( m_Controls.m_NewVideoDeviceWidget, SIGNAL(Finished()), this, SLOT(OnNewDeviceWidgetDone()) ); // After NewDeviceWidget finished editing
connect( m_Controls.m_BtnView, SIGNAL(clicked()), this, SLOT(OnClickedViewDevice()) );
connect( m_Controls.m_FrameRate, SIGNAL(valueChanged(int)), this, SLOT(OnChangedFramerateLimit(int)) );
connect( m_Controls.m_FreezeButton, SIGNAL(clicked()), this, SLOT(OnClickedFreezeButton()) );
connect( m_Timer, SIGNAL(timeout()), this, SLOT(DisplayImage()));
// Initializations
m_Controls.m_NewVideoDeviceWidget->setVisible(false);
std::string filter = "(&(" + us::ServiceConstants::OBJECTCLASS() + "=" + "org.mitk.services.UltrasoundDevice)(" + mitk::USDevice::US_PROPKEY_ISACTIVE + "=true))";
m_Controls.m_ActiveVideoDevices->Initialize<mitk::USDevice>(mitk::USDevice::US_PROPKEY_LABEL ,filter);
m_Node = this->GetDataStorage()->GetNamedNode("US Image Stream");
if (m_Node.IsNull())
{
// Create Node for US Stream
m_Node = mitk::DataNode::New();
m_Node->SetName("US Image Stream");
this->GetDataStorage()->Add(m_Node);
}
m_Controls.tabWidget->setTabEnabled(1, false);
/*ctkFlowLayout* flowLayout = ctkFlowLayout::replaceLayout(m_Controls.m_WidgetDevices);
flowLayout->setAlignItems(true);
flowLayout->setOrientation(Qt::Vertical);*/
}
void UltrasoundSupport::OnClickedAddNewDevice()
{
m_Controls.m_NewVideoDeviceWidget->setVisible(true);
m_Controls.m_DeviceManagerWidget->setVisible(false);
m_Controls.m_Headline->setText("Add New Video Device:");
m_Controls.m_WidgetActiveDevices->setVisible(false);
}
void UltrasoundSupport::DisplayImage()
{
m_Device->Modified();
m_Device->UpdateOutputData(0);
mitk::Image::Pointer curOutput = m_Device->GetOutput();
if (curOutput.IsNotNull() && curOutput->IsInitialized()) { m_Node->SetData(curOutput); }
this->RequestRenderWindowUpdate();
if ( curOutput->GetDimension() > 1
&& (curOutput->GetDimension(0) != m_CurrentImageWidth
|| curOutput->GetDimension(1) != m_CurrentImageHeight) )
{
// make a reinit on the ultrasound image
mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart();
if ( renderWindow != NULL && curOutput->GetTimeGeometry()->IsValid() )
{
renderWindow->GetRenderingManager()->InitializeViews(
curOutput->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true );
renderWindow->GetRenderingManager()->RequestUpdateAll();
}
m_CurrentImageWidth = curOutput->GetDimension(0);
m_CurrentImageHeight = curOutput->GetDimension(1);
}
m_FrameCounter ++;
if (m_FrameCounter == 10)
{
int nMilliseconds = m_Clock.restart();
int fps = 10000.0f / (nMilliseconds );
m_Controls.m_FramerateLabel->setText("Current Framerate: "+ QString::number(fps) +" FPS");
m_FrameCounter = 0;
}
}
void UltrasoundSupport::OnClickedViewDevice()
{
m_FrameCounter = 0;
// We use the activity state of the timer to determine whether we are currently viewing images
if ( ! m_Timer->isActive() ) // Activate Imaging
{
this->StartViewing();
}
else //deactivate imaging
{
this->StopViewing();
}
}
void UltrasoundSupport::OnChangedFramerateLimit(int value)
{
m_Timer->setInterval(1000 / value);
}
void UltrasoundSupport::OnClickedFreezeButton()
{
if ( m_Device->GetIsFreezed() )
{
m_Device->SetIsFreezed(false);
m_Controls.m_FreezeButton->setText("Freeze");
}
else
{
m_Device->SetIsFreezed(true);
m_Controls.m_FreezeButton->setText("Start Viewing Again");
}
}
void UltrasoundSupport::OnNewDeviceWidgetDone()
{
m_Controls.m_NewVideoDeviceWidget->setVisible(false);
m_Controls.m_DeviceManagerWidget->setVisible(true);
m_Controls.m_Headline->setText("Ultrasound Devices:");
m_Controls.m_WidgetActiveDevices->setVisible(true);
}
void UltrasoundSupport::GlobalReinit()
{
// get all nodes that have not set "includeInBoundingBox" to false
mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false)));
mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred);
// calculate bounding geometry of these nodes
mitk::TimeGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible");
// initialize the views to the bounding geometry
mitk::RenderingManager::GetInstance()->InitializeViews(bounds);
}
void UltrasoundSupport::StartViewing()
{
m_Controls.tabWidget->setTabEnabled(1, true);
m_Controls.tabWidget->setCurrentIndex(1);
//get device & set data node
m_Device = m_Controls.m_ActiveVideoDevices->GetSelectedService<mitk::USDevice>();
if (m_Device.IsNull())
{
m_Timer->stop();
return;
}
//start timer
int interval = (1000 / m_Controls.m_FrameRate->value());
m_Timer->setInterval(interval);
m_Timer->start();
//reinit view
//this->GlobalReinit();
//change UI elements
m_Controls.m_BtnView->setText("Stop Viewing");
this->CreateControlWidgets();
}
void UltrasoundSupport::StopViewing()
{
m_Controls.tabWidget->setTabEnabled(1, false);
this->RemoveControlWidgets();
//stop timer & release data
m_Timer->stop();
m_Node->ReleaseData();
this->RequestRenderWindowUpdate();
//change UI elements
m_Controls.m_BtnView->setText("Start Viewing");
}
void UltrasoundSupport::CreateControlWidgets()
{
m_ControlProbesWidget = new QmitkUSControlsProbesWidget(m_Device->GetControlInterfaceProbes(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.probesWidgetContainer->addWidget(m_ControlProbesWidget);
unsigned int firstEnabledControl = -1;
// create b mode widget for current device
m_ControlBModeWidget = new QmitkUSControlsBModeWidget(m_Device->GetControlInterfaceBMode(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlBModeWidget, "B Mode Controls");
if ( ! m_Device->GetControlInterfaceBMode() )
{
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
else
{
if ( firstEnabledControl == -1 ) { firstEnabledControl = 0; }
}
// create doppler widget for current device
m_ControlDopplerWidget = new QmitkUSControlsDopplerWidget(m_Device->GetControlInterfaceDoppler(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlDopplerWidget, "Doppler Controls");
if ( ! m_Device->GetControlInterfaceDoppler() )
{
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
else
{
if ( firstEnabledControl == -1 ) { firstEnabledControl = 0; }
}
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
if ( pluginContext )
{
std::string filter = "(ork.mitk.services.UltrasoundCustomWidget.deviceClass=" + m_Device->GetDeviceClass() + ")";
QString interfaceName ( us_service_interface_iid<QmitkUSAbstractCustomWidget>() );
m_CustomWidgetServiceReference = pluginContext->getServiceReferences(interfaceName, QString::fromStdString(filter));
if (m_CustomWidgetServiceReference.size() > 0)
{
m_ControlCustomWidget = pluginContext->getService<QmitkUSAbstractCustomWidget>
(m_CustomWidgetServiceReference.at(0))->CloneForQt(m_Controls.tab2);
m_ControlCustomWidget->SetDevice(m_Device);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlCustomWidget, "Custom Controls");
}
else
{
m_Controls.m_ToolBoxControlWidgets->addItem(new QWidget(m_Controls.m_ToolBoxControlWidgets), "Custom Controls");
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
}
// select first enabled control widget
for ( unsigned int n = 0; n < m_Controls.m_ToolBoxControlWidgets->count(); ++n)
{
if ( m_Controls.m_ToolBoxControlWidgets->isItemEnabled(n) )
{
m_Controls.m_ToolBoxControlWidgets->setCurrentIndex(n);
break;
}
}
}
void UltrasoundSupport::RemoveControlWidgets()
{
// remove all control widgets from the tool box widget
while (m_Controls.m_ToolBoxControlWidgets->count() > 0)
{
m_Controls.m_ToolBoxControlWidgets->removeItem(0);
}
// remove probes widget (which is not part of the tool box widget)
m_Controls.probesWidgetContainer->removeWidget(m_ControlProbesWidget);
delete m_ControlProbesWidget;
m_ControlProbesWidget = 0;
delete m_ControlBModeWidget;
m_ControlBModeWidget = 0;
delete m_ControlDopplerWidget;
m_ControlDopplerWidget = 0;
// delete custom widget if it is present
if ( m_ControlCustomWidget )
{
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
delete m_ControlCustomWidget; m_ControlCustomWidget = 0;
if ( m_CustomWidgetServiceReference.size() > 0 )
{
pluginContext->ungetService(m_CustomWidgetServiceReference.at(0));
}
}
}
void UltrasoundSupport::OnDeciveServiceEvent(const ctkServiceEvent event)
{
if ( ! m_Device || event.getType() != us::ServiceEvent::MODIFIED ) { return; }
ctkServiceReference service = event.getServiceReference();
if ( m_Device->GetDeviceManufacturer() != service.getProperty(mitk::USImageMetadata::PROP_DEV_MANUFACTURER).toString().toStdString()
&& m_Device->GetDeviceModel() != service.getProperty(mitk::USImageMetadata::PROP_DEV_MODEL).toString().toStdString() )
{
return;
}
if ( ! m_Device->GetIsActive() && m_Timer->isActive() )
{
this->StopViewing();
}
}
UltrasoundSupport::UltrasoundSupport()
: m_ControlCustomWidget(0), m_ControlBModeWidget(0),
m_ControlProbesWidget(0), m_CurrentImageWidth(0),
m_CurrentImageHeight(0)
{
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
if ( pluginContext )
{
// to be notified about service event of an USDevice
pluginContext->connectServiceListener(this, "OnDeciveServiceEvent",
QString::fromStdString("(" + us::ServiceConstants::OBJECTCLASS() + "=" + us_service_interface_iid<mitk::USDevice>() + ")"));
}
}
UltrasoundSupport::~UltrasoundSupport()
{
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.