text stringlengths 54 60.6k |
|---|
<commit_before><commit_msg>Replace size_t -> LexStateId in LexTableBuilder::remove_duplicate_states<commit_after><|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief The base include file for a Restricted Boltzmann Machine
*/
#pragma once
// Include the dyn version
#include "dll/dyn_rbm.hpp"
#include "dll/rbm.inl"
#include "dll/trainer/rbm_training_context.hpp"
#include "dll/rbm_desc.hpp"
#include "dll/trainer/rbm_trainer.hpp"
<commit_msg>Add note<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief The base include file for a Restricted Boltzmann Machine
*/
#pragma once
// Include the dyn version (for dyn_dbn)
#include "dll/dyn_rbm.hpp"
#include "dll/rbm.inl"
#include "dll/trainer/rbm_training_context.hpp"
#include "dll/rbm_desc.hpp"
#include "dll/trainer/rbm_trainer.hpp"
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "levelset.h"
#include <algorithm>
#include <math.h>
#include <QApplication>
#include <QDir>
#include <QFileDialog>
#include <QGraphicsScene>
#include <QImage>
#include <QLabel>
#include <QPixmap>
#include <QString>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_run_button_clicked()
{
// Create output firectory
unsigned last = m_filename.find_last_of('/');
m_output_filename = m_filename.substr(0,last);
m_output_filename = m_output_filename + "/output.";
// Assign coefficients
m_level_set.m_coef_length = stof(ui->length_edit->text().toStdString());
m_level_set.m_coef_mean = stof(ui->mean_edit->text().toStdString());
m_level_set.m_coef_variance = stof(ui->variance_edit->text().toStdString());
m_level_set.m_coef_area = stof(ui->area_edit->text().toStdString());
m_level_set.m_coef_com = stof(ui->com_edit->text().toStdString());
// If outside region set to -1
// If inside region set to +1
// Magical color is: RGB = (255,0,23)
for(int i = 1; i < m_level_set.m_width-1; i++)
{
for(int j = 1; j < m_level_set.m_height-1; j++)
{
QRgb pixel = m_level_set.m_image.pixel(i-1, j-1);
if (qRed(pixel) == 255 && qGreen(pixel) == 0 && qBlue(pixel) == 0)
{
m_level_set.m_u.at(i).at(j) = 1.0;
}
else
{
m_level_set.m_u.at(i).at(j)= -1.0;
}
}
}
// Mirror image the border
m_level_set.mirror_u();
m_level_set.calculate_parameters();
float t = 0;
m_picture_num = m_picture_num+1;
std::string name = (m_filename + std::to_string(m_picture_num) + m_file_extension);
// Loop while there are still more pictures
while(FILE *file = fopen(name.c_str(), "r"))
{
m_level_set.m_image_master = QImage(QString::fromStdString(name));
// t is a measure of how fast the functional is moving
// Current scheme is to do 100 iterations
t = 0;
for(int i = 0; i < 100; i++)
{
t += m_level_set.descent_func();
}
// Refresh parameters
m_level_set.calculate_parameters();
m_level_set.paint_border();
m_level_set.m_image.save(QString::fromStdString(m_output_filename + std::to_string(m_picture_num) + m_file_extension));
QPixmap pixmap(QPixmap::fromImage(m_level_set.m_image));
QGraphicsScene* scene = new QGraphicsScene;
scene->addPixmap(pixmap);
ui->graphicsView->fitInView(scene->itemsBoundingRect() ,Qt::KeepAspectRatio);
ui->graphicsView->setScene(scene);
ui->graphicsView->repaint();
qApp->processEvents();
// Close file and prepare new file name
fclose(file);
m_picture_num += 1;
name = (m_filename + std::to_string(m_picture_num) + m_file_extension);
}
// Set the new working directory to the output directory
m_filename = m_output_filename;
}
void MainWindow::on_open_button_clicked()
{
get_picture();
}
void MainWindow::on_actionOpen_triggered()
{
get_picture();
}
void MainWindow::get_picture(){
//get a filename to open
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Image"), QDir::homePath().append("/Documents"), tr("Image Files (*.png *.jpg *.bmp *.jpeg)"));
// Remove the number and extension from picture
// Assume that the first picture starts with 1
// ~/Documents/pic.1.bmp -> ~/Documents/pic
m_filename = fileName.toStdString();
unsigned first = 0;
unsigned last = 0;
for(std::string::size_type i = 0; i < m_filename.size(); ++i) {
if(m_filename.at(i) == '.')
{
first = last;
last = i;
}
}
m_picture_num = stoi(m_filename.substr(first+1,last-first-1));
m_file_extension = m_filename.substr(last,std::string::npos);
m_filename = m_filename.substr(0,first+1);
QImage image(fileName);
QPixmap pixmap(QPixmap::fromImage(image));
QGraphicsScene* scene = new QGraphicsScene;
scene->addPixmap(pixmap);
ui->graphicsView->fitInView(scene->itemsBoundingRect() ,Qt::KeepAspectRatio);
ui->graphicsView->setScene(scene);
m_level_set = LevelSet(image);
}
void MainWindow::on_previous_button_clicked()
{
m_picture_num = std::max(m_picture_num-1,0);
// Load Image
QImage image(QString::fromStdString(m_filename + std::to_string(m_picture_num) + m_file_extension));
QPixmap pixmap(QPixmap::fromImage(image));
QGraphicsScene* scene = new QGraphicsScene;
scene->addPixmap(pixmap);
ui->graphicsView->fitInView(scene->itemsBoundingRect() ,Qt::KeepAspectRatio);
ui->graphicsView->setScene(scene);
}
void MainWindow::on_next_button_clicked()
{
m_picture_num = m_picture_num+1;
// Check if picture exists
std::string name = (m_filename + std::to_string(m_picture_num) + m_file_extension);
if (FILE *file = fopen(name.c_str(), "r"))
{
fclose(file);
}
else
{
m_picture_num = m_picture_num-1;
}
QImage image(QString::fromStdString(m_filename + std::to_string(m_picture_num) + m_file_extension));
QPixmap pixmap(QPixmap::fromImage(image));
QGraphicsScene* scene = new QGraphicsScene;
scene->addPixmap(pixmap);
ui->graphicsView->fitInView(scene->itemsBoundingRect() ,Qt::KeepAspectRatio);
ui->graphicsView->setScene(scene);
}
<commit_msg>Logic error with how the parameters are calculated for the first image<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "levelset.h"
#include <algorithm>
#include <math.h>
#include <QApplication>
#include <QDir>
#include <QFileDialog>
#include <QGraphicsScene>
#include <QImage>
#include <QLabel>
#include <QPixmap>
#include <QString>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_run_button_clicked()
{
// Create output firectory
unsigned last = m_filename.find_last_of('/');
m_output_filename = m_filename.substr(0,last);
m_output_filename = m_output_filename + "/output.";
// Assign coefficients
m_level_set.m_coef_length = stof(ui->length_edit->text().toStdString());
m_level_set.m_coef_mean = stof(ui->mean_edit->text().toStdString());
m_level_set.m_coef_variance = stof(ui->variance_edit->text().toStdString());
m_level_set.m_coef_area = stof(ui->area_edit->text().toStdString());
m_level_set.m_coef_com = stof(ui->com_edit->text().toStdString());
// If outside region set to -1
// If inside region set to +1
// Magical color is: RGB = (255,0,23)
for(int i = 1; i < m_level_set.m_width-1; i++)
{
for(int j = 1; j < m_level_set.m_height-1; j++)
{
QRgb pixel = m_level_set.m_image.pixel(i-1, j-1);
if (qRed(pixel) == 255 && qGreen(pixel) == 0 && qBlue(pixel) == 0)
{
m_level_set.m_u.at(i).at(j) = 1.0;
}
else
{
m_level_set.m_u.at(i).at(j)= -1.0;
}
}
}
// Mirror image the border
m_level_set.mirror_u();
float t = 0;
m_picture_num = m_picture_num+1;
std::string name = (m_filename + std::to_string(m_picture_num) + m_file_extension);
// Loop while there are still more pictures
while(FILE *file = fopen(name.c_str(), "r"))
{
m_level_set.m_image_master = QImage(QString::fromStdString(name));
// Refresh parameters
m_level_set.calculate_parameters();
// t is a measure of how fast the functional is moving
// Current scheme is to do 100 iterations
t = 0;
for(int i = 0; i < 100; i++)
{
t += m_level_set.descent_func();
}
m_level_set.paint_border();
m_level_set.m_image.save(QString::fromStdString(m_output_filename + std::to_string(m_picture_num) + m_file_extension));
QPixmap pixmap(QPixmap::fromImage(m_level_set.m_image));
QGraphicsScene* scene = new QGraphicsScene;
scene->addPixmap(pixmap);
ui->graphicsView->fitInView(scene->itemsBoundingRect() ,Qt::KeepAspectRatio);
ui->graphicsView->setScene(scene);
ui->graphicsView->repaint();
qApp->processEvents();
// Close file and prepare new file name
fclose(file);
m_picture_num += 1;
name = (m_filename + std::to_string(m_picture_num) + m_file_extension);
}
// Set the new working directory to the output directory
m_filename = m_output_filename;
}
void MainWindow::on_open_button_clicked()
{
get_picture();
}
void MainWindow::on_actionOpen_triggered()
{
get_picture();
}
void MainWindow::get_picture(){
//get a filename to open
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Image"), QDir::homePath().append("/Documents"), tr("Image Files (*.png *.jpg *.bmp *.jpeg)"));
// Remove the number and extension from picture
// Assume that the first picture starts with 1
// ~/Documents/pic.1.bmp -> ~/Documents/pic
m_filename = fileName.toStdString();
unsigned first = 0;
unsigned last = 0;
for(std::string::size_type i = 0; i < m_filename.size(); ++i) {
if(m_filename.at(i) == '.')
{
first = last;
last = i;
}
}
m_picture_num = stoi(m_filename.substr(first+1,last-first-1));
m_file_extension = m_filename.substr(last,std::string::npos);
m_filename = m_filename.substr(0,first+1);
QImage image(fileName);
QPixmap pixmap(QPixmap::fromImage(image));
QGraphicsScene* scene = new QGraphicsScene;
scene->addPixmap(pixmap);
ui->graphicsView->fitInView(scene->itemsBoundingRect() ,Qt::KeepAspectRatio);
ui->graphicsView->setScene(scene);
m_level_set = LevelSet(image);
}
void MainWindow::on_previous_button_clicked()
{
m_picture_num = std::max(m_picture_num-1,0);
// Load Image
QImage image(QString::fromStdString(m_filename + std::to_string(m_picture_num) + m_file_extension));
QPixmap pixmap(QPixmap::fromImage(image));
QGraphicsScene* scene = new QGraphicsScene;
scene->addPixmap(pixmap);
ui->graphicsView->fitInView(scene->itemsBoundingRect() ,Qt::KeepAspectRatio);
ui->graphicsView->setScene(scene);
}
void MainWindow::on_next_button_clicked()
{
m_picture_num = m_picture_num+1;
// Check if picture exists
std::string name = (m_filename + std::to_string(m_picture_num) + m_file_extension);
if (FILE *file = fopen(name.c_str(), "r"))
{
fclose(file);
}
else
{
m_picture_num = m_picture_num-1;
}
QImage image(QString::fromStdString(m_filename + std::to_string(m_picture_num) + m_file_extension));
QPixmap pixmap(QPixmap::fromImage(image));
QGraphicsScene* scene = new QGraphicsScene;
scene->addPixmap(pixmap);
ui->graphicsView->fitInView(scene->itemsBoundingRect() ,Qt::KeepAspectRatio);
ui->graphicsView->setScene(scene);
}
<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "datasetcollection.h"
#include "fnet_dataset.h"
#include <vespa/searchcore/fdispatch/common/search.h>
#include <vespa/fnet/fnet.h>
#include <vespa/log/log.h>
LOG_SETUP(".search.datasetcollection");
FastS_DataSetBase *
FastS_DataSetCollection::CreateDataSet(FastS_DataSetDesc *desc)
{
FastS_DataSetBase *ret = nullptr;
FNET_Transport *transport = _appCtx->GetFNETTransport();
FNET_Scheduler *scheduler = _appCtx->GetFNETScheduler();
if (transport != nullptr && scheduler != nullptr) {
ret = new FastS_FNET_DataSet(transport, scheduler, _appCtx, desc);
} else {
LOG(error, "Non-available dataset transport: FNET");
}
return ret;
}
bool
FastS_DataSetCollection::AddDataSet(FastS_DataSetDesc *desc)
{
uint32_t datasetid = desc->GetID();
if (datasetid >= _datasets_size) {
uint32_t newSize = datasetid + 1;
FastS_DataSetBase **newArray = new FastS_DataSetBase*[newSize];
FastS_assert(newArray != nullptr);
uint32_t i;
for (i = 0; i < _datasets_size; i++)
newArray[i] = _datasets[i];
for (; i < newSize; i++)
newArray[i] = nullptr;
delete [] _datasets;
_datasets = newArray;
_datasets_size = newSize;
}
FastS_assert(_datasets[datasetid] == nullptr);
FastS_DataSetBase *dataset = CreateDataSet(desc);
if (dataset == nullptr)
return false;
_datasets[datasetid] = dataset;
for (FastS_EngineDesc *engineDesc = desc->GetEngineList();
engineDesc != nullptr; engineDesc = engineDesc->GetNext()) {
dataset->AddEngine(engineDesc);
}
dataset->ConfigDone(this);
return true;
}
FastS_DataSetCollection::FastS_DataSetCollection(FastS_AppContext *appCtx)
: _nextOld(nullptr),
_configDesc(nullptr),
_appCtx(appCtx),
_datasets(nullptr),
_datasets_size(0),
_gencnt(0),
_frozen(false),
_error(false)
{
}
FastS_DataSetCollection::~FastS_DataSetCollection()
{
if (_datasets != nullptr) {
for (uint32_t i = 0; i < _datasets_size; i++) {
if (_datasets[i] != nullptr) {
_datasets[i]->Free();
_datasets[i] = nullptr;
}
}
}
delete [] _datasets;
delete _configDesc;
}
bool
FastS_DataSetCollection::Configure(FastS_DataSetCollDesc *cfgDesc,
uint32_t gencnt)
{
bool rc = false;
if (_frozen) {
delete cfgDesc;
} else {
FastS_assert(_configDesc == nullptr);
if (cfgDesc == nullptr) {
_configDesc = new FastS_DataSetCollDesc();
} else {
_configDesc = cfgDesc;
}
_gencnt = gencnt;
_frozen = true;
_error = !_configDesc->Freeze();
rc = !_error;
for (uint32_t i = 0; rc && i < _configDesc->GetMaxNumDataSets(); i++) {
FastS_DataSetDesc *datasetDesc = _configDesc->GetDataSet(i);
if (datasetDesc != nullptr) {
FastS_assert(datasetDesc->GetID() == i);
rc = AddDataSet(datasetDesc);
}
}
_error = !rc;
}
return rc;
}
uint32_t
FastS_DataSetCollection::SuggestDataSet()
{
FastS_assert(_frozen);
FastS_DataSetBase *dataset = nullptr;
for (uint32_t i = 0; i < _datasets_size; i++) {
FastS_DataSetBase *tmp = _datasets[i];
if (tmp == nullptr || tmp->_unitrefcost == 0)
continue;
// NB: cost race condition
if (dataset == nullptr ||
dataset->_totalrefcost + dataset->_unitrefcost >
tmp->_totalrefcost + tmp->_unitrefcost)
dataset = tmp;
}
return (dataset == nullptr)
? FastS_NoID32()
: dataset->GetID();
}
FastS_DataSetBase *
FastS_DataSetCollection::GetDataSet(uint32_t datasetid)
{
FastS_assert(_frozen);
FastS_DataSetBase *dataset =
(datasetid < _datasets_size) ?
_datasets[datasetid] : nullptr;
if (dataset != nullptr)
dataset->AddCost();
return dataset;
}
FastS_DataSetBase *
FastS_DataSetCollection::GetDataSet()
{
FastS_assert(_frozen);
FastS_DataSetBase *dataset = nullptr;
for (uint32_t i = 0; i < _datasets_size; i++) {
FastS_DataSetBase *tmp = _datasets[i];
if (tmp == nullptr || tmp->_unitrefcost == 0)
continue;
// NB: cost race condition
if (dataset == nullptr ||
dataset->_totalrefcost + dataset->_unitrefcost >
tmp->_totalrefcost + tmp->_unitrefcost)
dataset = tmp;
}
if (dataset != nullptr)
dataset->AddCost();
return dataset;
}
bool
FastS_DataSetCollection::AreEnginesReady()
{
bool ready = true;
for (uint32_t datasetidx = 0;
ready && (datasetidx < GetMaxNumDataSets());
datasetidx++)
{
FastS_DataSetBase *dataset = PeekDataSet(datasetidx);
ready = (dataset != nullptr && !dataset->AreEnginesReady());
}
return ready;
}
FastS_ISearch *
FastS_DataSetCollection::CreateSearch(uint32_t dataSetID,
FastS_TimeKeeper *timeKeeper)
{
FastS_ISearch *ret = nullptr;
FastS_DataSetBase *dataset;
if (dataSetID == FastS_NoID32()) {
dataset = GetDataSet();
if (dataset != nullptr)
dataSetID = dataset->GetID();
} else {
dataset = GetDataSet(dataSetID);
}
if (dataset == nullptr) {
ret = new FastS_FailedSearch(dataSetID, false,
search::engine::ECODE_ILLEGAL_DATASET, nullptr);
} else {
{
auto dsGuard(dataset->getDsGuard());
dataset->SetActiveQuery_HasLock();
}
/* XXX: Semantic change: precounted as active in dataset */
ret = dataset->CreateSearch(this, timeKeeper, /* async = */ false);
}
FastS_assert(ret != nullptr);
return ret;
}
void
FastS_DataSetCollection::CheckQueryQueues(FastS_TimeKeeper *timeKeeper)
{
for (uint32_t datasetidx(0); datasetidx < GetMaxNumDataSets(); datasetidx++) {
FastS_DataSetBase *dataset = PeekDataSet(datasetidx);
if (dataset != nullptr) {
auto dsGuard(dataset->getDsGuard());
dataset->CheckQueryQueue_HasLock(timeKeeper);
}
}
}
void
FastS_DataSetCollection::AbortQueryQueues()
{
for (uint32_t datasetidx(0); datasetidx < GetMaxNumDataSets(); datasetidx++) {
FastS_DataSetBase *dataset = PeekDataSet(datasetidx);
if (dataset != nullptr) {
auto dsGuard(dataset->getDsGuard());
dataset->AbortQueryQueue_HasLock();
}
}
}
<commit_msg>Invert the logic and simplify the loop.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "datasetcollection.h"
#include "fnet_dataset.h"
#include <vespa/searchcore/fdispatch/common/search.h>
#include <vespa/fnet/fnet.h>
#include <vespa/log/log.h>
LOG_SETUP(".search.datasetcollection");
FastS_DataSetBase *
FastS_DataSetCollection::CreateDataSet(FastS_DataSetDesc *desc)
{
FastS_DataSetBase *ret = nullptr;
FNET_Transport *transport = _appCtx->GetFNETTransport();
FNET_Scheduler *scheduler = _appCtx->GetFNETScheduler();
if (transport != nullptr && scheduler != nullptr) {
ret = new FastS_FNET_DataSet(transport, scheduler, _appCtx, desc);
} else {
LOG(error, "Non-available dataset transport: FNET");
}
return ret;
}
bool
FastS_DataSetCollection::AddDataSet(FastS_DataSetDesc *desc)
{
uint32_t datasetid = desc->GetID();
if (datasetid >= _datasets_size) {
uint32_t newSize = datasetid + 1;
FastS_DataSetBase **newArray = new FastS_DataSetBase*[newSize];
FastS_assert(newArray != nullptr);
uint32_t i;
for (i = 0; i < _datasets_size; i++)
newArray[i] = _datasets[i];
for (; i < newSize; i++)
newArray[i] = nullptr;
delete [] _datasets;
_datasets = newArray;
_datasets_size = newSize;
}
FastS_assert(_datasets[datasetid] == nullptr);
FastS_DataSetBase *dataset = CreateDataSet(desc);
if (dataset == nullptr)
return false;
_datasets[datasetid] = dataset;
for (FastS_EngineDesc *engineDesc = desc->GetEngineList();
engineDesc != nullptr; engineDesc = engineDesc->GetNext()) {
dataset->AddEngine(engineDesc);
}
dataset->ConfigDone(this);
return true;
}
FastS_DataSetCollection::FastS_DataSetCollection(FastS_AppContext *appCtx)
: _nextOld(nullptr),
_configDesc(nullptr),
_appCtx(appCtx),
_datasets(nullptr),
_datasets_size(0),
_gencnt(0),
_frozen(false),
_error(false)
{
}
FastS_DataSetCollection::~FastS_DataSetCollection()
{
if (_datasets != nullptr) {
for (uint32_t i = 0; i < _datasets_size; i++) {
if (_datasets[i] != nullptr) {
_datasets[i]->Free();
_datasets[i] = nullptr;
}
}
}
delete [] _datasets;
delete _configDesc;
}
bool
FastS_DataSetCollection::Configure(FastS_DataSetCollDesc *cfgDesc,
uint32_t gencnt)
{
bool rc = false;
if (_frozen) {
delete cfgDesc;
} else {
FastS_assert(_configDesc == nullptr);
if (cfgDesc == nullptr) {
_configDesc = new FastS_DataSetCollDesc();
} else {
_configDesc = cfgDesc;
}
_gencnt = gencnt;
_frozen = true;
_error = !_configDesc->Freeze();
rc = !_error;
for (uint32_t i = 0; rc && i < _configDesc->GetMaxNumDataSets(); i++) {
FastS_DataSetDesc *datasetDesc = _configDesc->GetDataSet(i);
if (datasetDesc != nullptr) {
FastS_assert(datasetDesc->GetID() == i);
rc = AddDataSet(datasetDesc);
}
}
_error = !rc;
}
return rc;
}
uint32_t
FastS_DataSetCollection::SuggestDataSet()
{
FastS_assert(_frozen);
FastS_DataSetBase *dataset = nullptr;
for (uint32_t i = 0; i < _datasets_size; i++) {
FastS_DataSetBase *tmp = _datasets[i];
if (tmp == nullptr || tmp->_unitrefcost == 0)
continue;
// NB: cost race condition
if (dataset == nullptr ||
dataset->_totalrefcost + dataset->_unitrefcost >
tmp->_totalrefcost + tmp->_unitrefcost)
dataset = tmp;
}
return (dataset == nullptr)
? FastS_NoID32()
: dataset->GetID();
}
FastS_DataSetBase *
FastS_DataSetCollection::GetDataSet(uint32_t datasetid)
{
FastS_assert(_frozen);
FastS_DataSetBase *dataset =
(datasetid < _datasets_size) ?
_datasets[datasetid] : nullptr;
if (dataset != nullptr)
dataset->AddCost();
return dataset;
}
FastS_DataSetBase *
FastS_DataSetCollection::GetDataSet()
{
FastS_assert(_frozen);
FastS_DataSetBase *dataset = nullptr;
for (uint32_t i = 0; i < _datasets_size; i++) {
FastS_DataSetBase *tmp = _datasets[i];
if (tmp == nullptr || tmp->_unitrefcost == 0)
continue;
// NB: cost race condition
if (dataset == nullptr ||
dataset->_totalrefcost + dataset->_unitrefcost >
tmp->_totalrefcost + tmp->_unitrefcost)
dataset = tmp;
}
if (dataset != nullptr)
dataset->AddCost();
return dataset;
}
bool
FastS_DataSetCollection::AreEnginesReady()
{
for (uint32_t datasetidx = 0; datasetidx < GetMaxNumDataSets(); datasetidx++) {
FastS_DataSetBase *dataset = PeekDataSet(datasetidx);
if ((dataset != nullptr) && !dataset->AreEnginesReady()) {
return false;
}
}
return true;
}
FastS_ISearch *
FastS_DataSetCollection::CreateSearch(uint32_t dataSetID,
FastS_TimeKeeper *timeKeeper)
{
FastS_ISearch *ret = nullptr;
FastS_DataSetBase *dataset;
if (dataSetID == FastS_NoID32()) {
dataset = GetDataSet();
if (dataset != nullptr)
dataSetID = dataset->GetID();
} else {
dataset = GetDataSet(dataSetID);
}
if (dataset == nullptr) {
ret = new FastS_FailedSearch(dataSetID, false,
search::engine::ECODE_ILLEGAL_DATASET, nullptr);
} else {
{
auto dsGuard(dataset->getDsGuard());
dataset->SetActiveQuery_HasLock();
}
/* XXX: Semantic change: precounted as active in dataset */
ret = dataset->CreateSearch(this, timeKeeper, /* async = */ false);
}
FastS_assert(ret != nullptr);
return ret;
}
void
FastS_DataSetCollection::CheckQueryQueues(FastS_TimeKeeper *timeKeeper)
{
for (uint32_t datasetidx(0); datasetidx < GetMaxNumDataSets(); datasetidx++) {
FastS_DataSetBase *dataset = PeekDataSet(datasetidx);
if (dataset != nullptr) {
auto dsGuard(dataset->getDsGuard());
dataset->CheckQueryQueue_HasLock(timeKeeper);
}
}
}
void
FastS_DataSetCollection::AbortQueryQueues()
{
for (uint32_t datasetidx(0); datasetidx < GetMaxNumDataSets(); datasetidx++) {
FastS_DataSetBase *dataset = PeekDataSet(datasetidx);
if (dataset != nullptr) {
auto dsGuard(dataset->getDsGuard());
dataset->AbortQueryQueue_HasLock();
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <unordered_map>
#include <memory>
#include <type_traits>
#include <tuple>
namespace kgr {
template<typename... Types>
struct Dependency {
using DependenciesTypes = std::tuple<Types...>;
};
using NoDependencies = Dependency<>;
struct Single {
using ParentTypes = std::tuple<>;
};
template<typename T>
struct Service;
template<typename... Types>
struct Overrides : Single {
using ParentTypes = std::tuple<Types...>;
};
namespace detail {
template <bool B, typename T>
using enable_if_t = typename std::enable_if<B, T>::type;
template<int ...>
struct seq { };
template<int N, int ...S>
struct seq_gen : seq_gen<N-1, N-1, S...> { };
template<int ...S>
struct seq_gen<0, S...> {
using type = seq<S...>;
};
struct Holder {
virtual ~Holder() {
}
};
template<typename T>
struct InstanceHolder : Holder {
explicit InstanceHolder(std::shared_ptr<T> instance) : _instance{instance} {}
std::shared_ptr<T> getInstance() const {
return _instance;
}
private:
std::shared_ptr<T> _instance;
};
template<typename T, typename... Args>
struct CallbackHolder : Holder {
using callback_t = std::function<std::shared_ptr<T>(Args...)>;
explicit CallbackHolder(callback_t callback) : _callback{callback} {}
callback_t getCallback() const {
return _callback;
}
private:
callback_t _callback;
};
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
} // namespace detail
struct Container : std::enable_shared_from_this<Container> {
private:
template<typename Condition, typename T = void> using enable_if = detail::enable_if_t<Condition::value, T>;
template<typename Condition, typename T = void> using disable_if = detail::enable_if_t<!Condition::value, T>;
template<typename T> using is_service_single = std::is_base_of<Single, Service<T>>;
template<typename T> using is_abstract = std::is_abstract<T>;
template<typename T> using is_base_of_container = std::is_base_of<Container, T>;
template<typename T> using is_container = std::is_same<T, Container>;
template<typename T> using dependency_types = typename Service<T>::DependenciesTypes;
template<typename T> using parent_types = typename Service<T>::ParentTypes;
template <typename Tuple> using tuple_seq = typename detail::seq_gen<std::tuple_size<Tuple>::value>::type;
template<int S, typename T> using parent_element = typename std::tuple_element<S, parent_types<T>>::type;
template<int S, typename Tuple> using tuple_element = typename std::tuple_element<S, Tuple>::type;
using holder_ptr = std::unique_ptr<detail::Holder>;
using holder_cont = std::unordered_map<std::string, holder_ptr>;
public:
template<typename T>
void instance(std::shared_ptr<T> service) {
static_assert(is_service_single<T>::value, "instance only accept Single Service instance.");
call_save_instance(service, tuple_seq<parent_types<T>>());
}
template<typename T>
void instance() {
static_assert(is_service_single<T>::value, "instance only accept Single Service instance.");
instance(make_service<T>());
}
template<typename T, disable_if<is_abstract<T>>..., disable_if<is_base_of_container<T>>...>
std::shared_ptr<T> service() {
return get_service<T>();
}
template<typename T, enable_if<is_container<T>>...>
std::shared_ptr<T> service() {
return shared_from_this();
}
template<typename T, disable_if<is_container<T>>..., enable_if<is_base_of_container<T>>...>
std::shared_ptr<T> service() {
return std::dynamic_pointer_cast<T>(shared_from_this());
}
template<typename T, enable_if<is_abstract<T>>...>
std::shared_ptr<T> service() {
auto it = _services.find(typeid(T).name());
if (it != _services.end()) {
auto holder = static_cast<detail::InstanceHolder<T>*>(it->second.get());
if (holder) {
return holder->getInstance();
}
}
return {};
}
template<typename T, typename U>
void callback(U callback) {
static_assert(!is_service_single<T>::value, "instance does not accept Single Service.");
save_callback<T, dependency_types<T>>(tuple_seq<dependency_types<T>>{}, callback);
}
virtual void init(){}
private:
template<typename T, enable_if<is_service_single<T>>...>
std::shared_ptr<T> get_service() {
auto it = _services.find(typeid(T).name());
if (it == _services.end()) {
auto service = make_service<T>();
instance(service);
return service;
} else {
auto holder = static_cast<detail::InstanceHolder<T>*>(it->second.get());
if (holder) {
return holder->getInstance();
}
}
return {};
}
template<typename T, disable_if<is_service_single<T>>...>
std::shared_ptr<T> get_service() {
return make_service<T>();
}
template<typename T, int ...S>
void call_save_instance(std::shared_ptr<T> service, detail::seq<S...>) {
save_instance<T, parent_element<S, T>...>(service);
}
template<typename Tuple, int ...S>
std::tuple<std::shared_ptr<tuple_element<S, Tuple>>...> dependency(detail::seq<S...>) {
return std::make_tuple(service<tuple_element<S, Tuple>>()...);
}
template<typename T, typename Tuple, int ...S>
std::shared_ptr<T> callback_make_service(detail::seq<S...> seq, Tuple dependencies) const {
auto it = _callbacks.find(typeid(T).name());
if (it != _callbacks.end()) {
auto holder = static_cast<detail::CallbackHolder<T, tuple_element<S, Tuple>...>*>(it->second.get());
if (holder) {
return holder->getCallback()(std::get<S>(dependencies)...);
}
}
return {};
}
template<typename T, typename Tuple, int ...S>
std::shared_ptr<T> make_service(detail::seq<S...> seq, Tuple dependencies) const {
auto service = callback_make_service<T, Tuple>(seq, dependencies);
if (service) {
return service;
}
return std::make_shared<T>(std::get<S>(dependencies)...);
}
template <typename T>
std::shared_ptr<T> make_service() {
auto seq = tuple_seq<dependency_types<T>>{};
return make_service<T>(seq, dependency<dependency_types<T>>(seq));
}
template<typename T, typename ...Others>
detail::enable_if_t<(sizeof...(Others) > 0), void> save_instance(std::shared_ptr<T> service) {
save_instance<T>(service);
save_instance<Others...>(service);
}
template<typename T>
void save_instance (std::shared_ptr<T> service) {
_services[typeid(T).name()] = detail::make_unique<detail::InstanceHolder<T>>(service);
}
template<typename T, typename Tuple, int ...S, typename U>
void save_callback (detail::seq<S...>, U callback) {
_callbacks[typeid(T).name()] = detail::make_unique<detail::CallbackHolder<T, std::shared_ptr<tuple_element<S, Tuple>>...>>(callback);
}
holder_cont _callbacks;
holder_cont _services;
};
template<typename T = Container, typename ...Args>
std::shared_ptr<T> make_container(Args&& ...args) {
static_assert(std::is_base_of<Container, T>::value, "make_container only accept container types.");
auto container = std::make_shared<T>(std::forward<Args>(args)...);
container->init();
return container;
}
} // namespace kgr
<commit_msg>Move instead of copy<commit_after>#pragma once
#include <unordered_map>
#include <memory>
#include <type_traits>
#include <tuple>
namespace kgr {
template<typename... Types>
struct Dependency {
using DependenciesTypes = std::tuple<Types...>;
};
using NoDependencies = Dependency<>;
struct Single {
using ParentTypes = std::tuple<>;
};
template<typename T>
struct Service;
template<typename... Types>
struct Overrides : Single {
using ParentTypes = std::tuple<Types...>;
};
namespace detail {
template <bool B, typename T>
using enable_if_t = typename std::enable_if<B, T>::type;
template<int ...>
struct seq { };
template<int N, int ...S>
struct seq_gen : seq_gen<N-1, N-1, S...> { };
template<int ...S>
struct seq_gen<0, S...> {
using type = seq<S...>;
};
struct Holder {
virtual ~Holder() {
}
};
template<typename T>
struct InstanceHolder : Holder {
explicit InstanceHolder(std::shared_ptr<T> instance) : _instance{std::move(instance)} {}
std::shared_ptr<T> getInstance() const {
return _instance;
}
private:
std::shared_ptr<T> _instance;
};
template<typename T, typename... Args>
struct CallbackHolder : Holder {
using callback_t = std::function<std::shared_ptr<T>(Args...)>;
explicit CallbackHolder(callback_t callback) : _callback{std::move(callback)} {}
callback_t getCallback() const {
return _callback;
}
private:
callback_t _callback;
};
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
} // namespace detail
struct Container : std::enable_shared_from_this<Container> {
private:
template<typename Condition, typename T = void> using enable_if = detail::enable_if_t<Condition::value, T>;
template<typename Condition, typename T = void> using disable_if = detail::enable_if_t<!Condition::value, T>;
template<typename T> using is_service_single = std::is_base_of<Single, Service<T>>;
template<typename T> using is_abstract = std::is_abstract<T>;
template<typename T> using is_base_of_container = std::is_base_of<Container, T>;
template<typename T> using is_container = std::is_same<T, Container>;
template<typename T> using dependency_types = typename Service<T>::DependenciesTypes;
template<typename T> using parent_types = typename Service<T>::ParentTypes;
template <typename Tuple> using tuple_seq = typename detail::seq_gen<std::tuple_size<Tuple>::value>::type;
template<int S, typename T> using parent_element = typename std::tuple_element<S, parent_types<T>>::type;
template<int S, typename Tuple> using tuple_element = typename std::tuple_element<S, Tuple>::type;
using holder_ptr = std::unique_ptr<detail::Holder>;
using holder_cont = std::unordered_map<std::string, holder_ptr>;
public:
template<typename T>
void instance(std::shared_ptr<T> service) {
static_assert(is_service_single<T>::value, "instance only accept Single Service instance.");
call_save_instance(std::move(service), tuple_seq<parent_types<T>>{});
}
template<typename T>
void instance() {
static_assert(is_service_single<T>::value, "instance only accept Single Service instance.");
instance(make_service<T>());
}
template<typename T, disable_if<is_abstract<T>>..., disable_if<is_base_of_container<T>>...>
std::shared_ptr<T> service() {
return get_service<T>();
}
template<typename T, enable_if<is_container<T>>...>
std::shared_ptr<T> service() {
return shared_from_this();
}
template<typename T, disable_if<is_container<T>>..., enable_if<is_base_of_container<T>>...>
std::shared_ptr<T> service() {
return std::dynamic_pointer_cast<T>(shared_from_this());
}
template<typename T, enable_if<is_abstract<T>>...>
std::shared_ptr<T> service() {
auto it = _services.find(typeid(T).name());
if (it != _services.end()) {
auto holder = static_cast<detail::InstanceHolder<T>*>(it->second.get());
if (holder) {
return holder->getInstance();
}
}
return {};
}
template<typename T, typename U>
void callback(U callback) {
static_assert(!is_service_single<T>::value, "instance does not accept Single Service.");
save_callback<T, dependency_types<T>>(tuple_seq<dependency_types<T>>{}, callback);
}
virtual void init(){}
private:
template<typename T, enable_if<is_service_single<T>>...>
std::shared_ptr<T> get_service() {
auto it = _services.find(typeid(T).name());
if (it == _services.end()) {
auto service = make_service<T>();
instance(service);
return service;
} else {
auto holder = static_cast<detail::InstanceHolder<T>*>(it->second.get());
if (holder) {
return holder->getInstance();
}
}
return {};
}
template<typename T, disable_if<is_service_single<T>>...>
std::shared_ptr<T> get_service() {
return make_service<T>();
}
template<typename T, int ...S>
void call_save_instance(std::shared_ptr<T> service, detail::seq<S...>) {
save_instance<T, parent_element<S, T>...>(std::move(service));
}
template<typename Tuple, int ...S>
std::tuple<std::shared_ptr<tuple_element<S, Tuple>>...> dependency(detail::seq<S...>) {
return std::make_tuple(service<tuple_element<S, Tuple>>()...);
}
template<typename T, typename Tuple, int ...S>
std::shared_ptr<T> callback_make_service(detail::seq<S...> seq, Tuple dependencies) const {
auto it = _callbacks.find(typeid(T).name());
if (it != _callbacks.end()) {
auto holder = static_cast<detail::CallbackHolder<T, tuple_element<S, Tuple>...>*>(it->second.get());
if (holder) {
return holder->getCallback()(std::get<S>(dependencies)...);
}
}
return {};
}
template<typename T, typename Tuple, int ...S>
std::shared_ptr<T> make_service(detail::seq<S...> seq, Tuple dependencies) const {
auto service = callback_make_service<T, Tuple>(seq, dependencies);
if (service) {
return service;
}
return std::make_shared<T>(std::get<S>(dependencies)...);
}
template <typename T>
std::shared_ptr<T> make_service() {
auto seq = tuple_seq<dependency_types<T>>{};
return make_service<T>(seq, dependency<dependency_types<T>>(seq));
}
template<typename T, typename ...Others>
detail::enable_if_t<(sizeof...(Others) > 0), void> save_instance(std::shared_ptr<T> service) {
save_instance<T>(service);
save_instance<Others...>(std::move(service));
}
template<typename T>
void save_instance (std::shared_ptr<T> service) {
_services[typeid(T).name()] = detail::make_unique<detail::InstanceHolder<T>>(service);
}
template<typename T, typename Tuple, int ...S, typename U>
void save_callback (detail::seq<S...>, U callback) {
_callbacks[typeid(T).name()] = detail::make_unique<detail::CallbackHolder<T, std::shared_ptr<tuple_element<S, Tuple>>...>>(callback);
}
holder_cont _callbacks;
holder_cont _services;
};
template<typename T = Container, typename ...Args>
std::shared_ptr<T> make_container(Args&& ...args) {
static_assert(std::is_base_of<Container, T>::value, "make_container only accept container types.");
auto container = std::make_shared<T>(std::forward<Args>(args)...);
container->init();
return container;
}
} // namespace kgr
<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "summaryengine.h"
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/log/log.h>
LOG_SETUP(".proton.summaryengine.summaryengine");
using namespace search::engine;
using namespace proton;
namespace {
class DocsumTask : public vespalib::Executor::Task {
private:
SummaryEngine & _engine;
DocsumClient & _client;
DocsumRequest::Source _request;
public:
DocsumTask(SummaryEngine & engine,
DocsumRequest::Source request,
DocsumClient & client)
: _engine(engine),
_client(client),
_request(std::move(request))
{
}
void run() override {
_client.getDocsumsDone(_engine.getDocsums(_request.release()));
}
};
} // namespace anonymous
namespace proton {
SummaryEngine::SummaryEngine(size_t numThreads)
: _lock(),
_closed(false),
_handlers(),
_executor(numThreads, 128 * 1024)
{
// empty
}
SummaryEngine::~SummaryEngine()
{
_executor.shutdown();
}
void
SummaryEngine::close()
{
LOG(debug, "Closing summary engine");
{
vespalib::LockGuard guard(_lock);
_closed = true;
}
LOG(debug, "Handshaking with task manager");
_executor.sync();
}
ISearchHandler::SP
SummaryEngine::putSearchHandler(const DocTypeName &docTypeName,
const ISearchHandler::SP & searchHandler)
{
vespalib::LockGuard guard(_lock);
return _handlers.putHandler(docTypeName, searchHandler);
}
ISearchHandler::SP
SummaryEngine::getSearchHandler(const DocTypeName &docTypeName)
{
return _handlers.getHandler(docTypeName);
}
ISearchHandler::SP
SummaryEngine::removeSearchHandler(const DocTypeName &docTypeName)
{
vespalib::LockGuard guard(_lock);
return _handlers.removeHandler(docTypeName);
}
DocsumReply::UP
SummaryEngine::getDocsums(DocsumRequest::Source request, DocsumClient & client)
{
if (_closed) {
LOG(warning, "Receiving docsumrequest after engine has been shutdown");
DocsumReply::UP ret(new DocsumReply());
// TODO: Notify closed.
return ret;
}
vespalib::Executor::Task::UP task(new DocsumTask(*this, std::move(request), client));
_executor.execute(std::move(task));
return DocsumReply::UP();
}
DocsumReply::UP
SummaryEngine::getDocsums(DocsumRequest::UP req)
{
DocsumReply::UP reply;
reply.reset(new DocsumReply());
if (req) {
ISearchHandler::SP searchHandler;
{ // try to find the summary handler corresponding to the specified search doc type
vespalib::LockGuard guard(_lock);
DocTypeName docTypeName(*req);
searchHandler = _handlers.getHandler(docTypeName);
}
if (searchHandler.get() != NULL) {
reply = searchHandler->getDocsums(*req);
} else {
vespalib::Sequence<ISearchHandler*>::UP snapshot;
{
vespalib::LockGuard guard(_lock);
snapshot = _handlers.snapshot();
}
if (snapshot->valid()) {
reply = snapshot->get()->getDocsums(*req); // use the first handler
}
}
}
reply->request = std::move(req);
return reply;
}
} // namespace proton
<commit_msg>Always hold the lock when accessing the handler map. Simplify, and avoid naked new.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "summaryengine.h"
#include <vespa/log/log.h>
LOG_SETUP(".proton.summaryengine.summaryengine");
using namespace search::engine;
using namespace proton;
namespace {
class DocsumTask : public vespalib::Executor::Task {
private:
SummaryEngine & _engine;
DocsumClient & _client;
DocsumRequest::Source _request;
public:
DocsumTask(SummaryEngine & engine, DocsumRequest::Source request, DocsumClient & client)
: _engine(engine),
_client(client),
_request(std::move(request))
{
}
void run() override {
_client.getDocsumsDone(_engine.getDocsums(_request.release()));
}
};
} // namespace anonymous
namespace proton {
SummaryEngine::SummaryEngine(size_t numThreads)
: _lock(),
_closed(false),
_handlers(),
_executor(numThreads, 128 * 1024)
{
// empty
}
SummaryEngine::~SummaryEngine()
{
_executor.shutdown();
}
void
SummaryEngine::close()
{
LOG(debug, "Closing summary engine");
{
vespalib::LockGuard guard(_lock);
_closed = true;
}
LOG(debug, "Handshaking with task manager");
_executor.sync();
}
ISearchHandler::SP
SummaryEngine::putSearchHandler(const DocTypeName &docTypeName, const ISearchHandler::SP & searchHandler)
{
vespalib::LockGuard guard(_lock);
return _handlers.putHandler(docTypeName, searchHandler);
}
ISearchHandler::SP
SummaryEngine::getSearchHandler(const DocTypeName &docTypeName)
{
vespalib::LockGuard guard(_lock);
return _handlers.getHandler(docTypeName);
}
ISearchHandler::SP
SummaryEngine::removeSearchHandler(const DocTypeName &docTypeName)
{
vespalib::LockGuard guard(_lock);
return _handlers.removeHandler(docTypeName);
}
DocsumReply::UP
SummaryEngine::getDocsums(DocsumRequest::Source request, DocsumClient & client)
{
if (_closed) {
LOG(warning, "Receiving docsumrequest after engine has been shutdown");
DocsumReply::UP ret(new DocsumReply());
// TODO: Notify closed.
return ret;
}
vespalib::Executor::Task::UP task(new DocsumTask(*this, std::move(request), client));
_executor.execute(std::move(task));
return DocsumReply::UP();
}
DocsumReply::UP
SummaryEngine::getDocsums(DocsumRequest::UP req)
{
DocsumReply::UP reply = std::make_unique<DocsumReply>();
if (req) {
ISearchHandler::SP searchHandler = getSearchHandler(DocTypeName(*req));
if (searchHandler) {
reply = searchHandler->getDocsums(*req);
} else {
vespalib::Sequence<ISearchHandler*>::UP snapshot;
{
vespalib::LockGuard guard(_lock);
snapshot = _handlers.snapshot();
}
if (snapshot->valid()) {
reply = snapshot->get()->getDocsums(*req); // use the first handler
}
}
}
reply->request = std::move(req);
return reply;
}
} // namespace proton
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLPageExport.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2005-09-09 14:35:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_XMLPAGEEXPORT_HXX
#include "XMLPageExport.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _COM_SUN_STAR_STYLE_XSTYLEFAMILIESSUPPLIER_HPP_
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_XSTYLE_HPP_
#include <com/sun/star/style/XStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_
#include <com/sun/star/container/XIndexReplace.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _XMLOFF_FAMILIES_HXX_
#include "families.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERPROPHDLFACTORY_HXX
#include "PageMasterPropHdlFactory.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include "PageMasterStyleMap.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX
#include "PageMasterPropMapper.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTEREXPORTPROPMAPPER_HXX
#include "PageMasterExportPropMapper.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTEREXPORTPROPMAPPER_HXX
#include "PageMasterExportPropMapper.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;
using namespace ::xmloff::token;
//______________________________________________________________________________
sal_Bool XMLPageExport::findPageMasterName( const OUString& rStyleName, OUString& rPMName ) const
{
for( ::std::vector< XMLPageExportNameEntry >::const_iterator pEntry = aNameVector.begin();
pEntry != aNameVector.end(); pEntry++ )
{
if( pEntry->sStyleName == rStyleName )
{
rPMName = pEntry->sPageMasterName;
return sal_True;
}
}
return sal_False;
}
void XMLPageExport::collectPageMasterAutoStyle(
const Reference < XPropertySet > & rPropSet,
OUString& rPageMasterName )
{
DBG_ASSERT( xPageMasterPropSetMapper.is(), "page master family/XMLPageMasterPropSetMapper not found" );
if( xPageMasterPropSetMapper.is() )
{
::std::vector<XMLPropertyState> xPropStates = xPageMasterExportPropMapper->Filter( rPropSet );
if(xPropStates.size())
{
OUString sParent;
rPageMasterName = rExport.GetAutoStylePool()->Find( XML_STYLE_FAMILY_PAGE_MASTER, sParent, xPropStates );
if (!rPageMasterName.getLength())
rPageMasterName = rExport.GetAutoStylePool()->Add(XML_STYLE_FAMILY_PAGE_MASTER, sParent, xPropStates);
}
}
}
void XMLPageExport::exportMasterPageContent(
const Reference < XPropertySet > & rPropSet,
sal_Bool bAutoStyles )
{
}
sal_Bool XMLPageExport::exportStyle(
const Reference< XStyle >& rStyle,
sal_Bool bAutoStyles )
{
Reference< XPropertySet > xPropSet( rStyle, UNO_QUERY );
Reference< XPropertySetInfo > xPropSetInfo = xPropSet->getPropertySetInfo();
Any aAny;
// Don't export styles that aren't existing really. This may be the
// case for StarOffice Writer's pool styles.
if( xPropSetInfo->hasPropertyByName( sIsPhysical ) )
{
aAny = xPropSet->getPropertyValue( sIsPhysical );
if( !*(sal_Bool *)aAny.getValue() )
return sal_False;
}
if( bAutoStyles )
{
XMLPageExportNameEntry aEntry;
collectPageMasterAutoStyle( xPropSet, aEntry.sPageMasterName );
aEntry.sStyleName = rStyle->getName();
aNameVector.push_back( aEntry );
exportMasterPageContent( xPropSet, sal_True );
}
else
{
OUString sName( rStyle->getName() );
sal_Bool bEncoded = sal_False;
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_NAME,
GetExport().EncodeStyleName( sName, &bEncoded ) );
if( bEncoded )
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_DISPLAY_NAME,
sName);
OUString sPMName;
if( findPageMasterName( sName, sPMName ) )
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_PAGE_LAYOUT_NAME, GetExport().EncodeStyleName( sPMName ) );
aAny = xPropSet->getPropertyValue( sFollowStyle );
OUString sNextName;
aAny >>= sNextName;
if( sName != sNextName && sNextName.getLength() )
{
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_NEXT_STYLE_NAME,
GetExport().EncodeStyleName( sNextName ) );
}
// OUString sPageMaster = GetExport().GetAutoStylePool()->Find(
// XML_STYLE_FAMILY_PAGE_MASTER,
// xPropSet );
// if( sPageMaster.getLength() )
// GetExport().AddAttribute( XML_NAMESPACE_STYLE,
// XML_PAGE_MASTER_NAME,
// sPageMaster );
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
XML_MASTER_PAGE, sal_True, sal_True );
exportMasterPageContent( xPropSet, sal_False );
}
return sal_True;
}
XMLPageExport::XMLPageExport( SvXMLExport& rExp ) :
rExport( rExp ),
sIsPhysical( RTL_CONSTASCII_USTRINGPARAM( "IsPhysical" ) ),
sFollowStyle( RTL_CONSTASCII_USTRINGPARAM( "FollowStyle" ) )
{
xPageMasterPropHdlFactory = new XMLPageMasterPropHdlFactory;
xPageMasterPropSetMapper = new XMLPageMasterPropSetMapper(
(XMLPropertyMapEntry*) aXMLPageMasterStyleMap,
xPageMasterPropHdlFactory );
xPageMasterExportPropMapper = new XMLPageMasterExportPropMapper(
xPageMasterPropSetMapper, rExp);
rExport.GetAutoStylePool()->AddFamily( XML_STYLE_FAMILY_PAGE_MASTER, OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_PAGE_MASTER_NAME ) ),
xPageMasterExportPropMapper, OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_PAGE_MASTER_PREFIX ) ), sal_False );
Reference< XStyleFamiliesSupplier > xFamiliesSupp( GetExport().GetModel(),
UNO_QUERY );
DBG_ASSERT( xFamiliesSupp.is(),
"No XStyleFamiliesSupplier from XModel for export!" );
if( xFamiliesSupp.is() )
{
Reference< XNameAccess > xFamilies( xFamiliesSupp->getStyleFamilies() );
DBG_ASSERT( xFamiliesSupp.is(),
"getStyleFamilies() from XModel failed for export!" );
if( xFamilies.is() )
{
const OUString aPageStyleName(
RTL_CONSTASCII_USTRINGPARAM( "PageStyles" ));
if( xFamilies->hasByName( aPageStyleName ) )
{
Reference < XNameContainer > xStyleCont;
xFamilies->getByName( aPageStyleName ) >>= xStyleCont;
xPageStyles = Reference< XIndexAccess >( xStyleCont,
UNO_QUERY );
DBG_ASSERT( xPageStyles.is(),
"Page Styles not found for export!" );
}
}
}
}
XMLPageExport::~XMLPageExport()
{
}
void XMLPageExport::exportStyles( sal_Bool bUsed, sal_Bool bAutoStyles )
{
if( xPageStyles.is() )
{
const sal_Int32 nStyles = xPageStyles->getCount();
for( sal_Int32 i=0; i < nStyles; i++ )
{
Reference< XStyle > xStyle;
xPageStyles->getByIndex( i ) >>= xStyle;
if( !bUsed || xStyle->isInUse() )
exportStyle( xStyle, bAutoStyles );
}
}
}
void XMLPageExport::exportAutoStyles()
{
rExport.GetAutoStylePool()->exportXML(XML_STYLE_FAMILY_PAGE_MASTER
, rExport.GetDocHandler(), rExport.GetMM100UnitConverter(),
rExport.GetNamespaceMap()
);
}
<commit_msg>INTEGRATION: CWS warnings01 (1.13.34); FILE MERGED 2005/11/16 22:47:20 pl 1.13.34.1: #i55991# removed warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLPageExport.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: hr $ $Date: 2006-06-19 18:30:11 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_XMLPAGEEXPORT_HXX
#include "XMLPageExport.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _COM_SUN_STAR_STYLE_XSTYLEFAMILIESSUPPLIER_HPP_
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_XSTYLE_HPP_
#include <com/sun/star/style/XStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_
#include <com/sun/star/container/XIndexReplace.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _XMLOFF_FAMILIES_HXX_
#include "families.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERPROPHDLFACTORY_HXX
#include "PageMasterPropHdlFactory.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include "PageMasterStyleMap.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX
#include "PageMasterPropMapper.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTEREXPORTPROPMAPPER_HXX
#include "PageMasterExportPropMapper.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTEREXPORTPROPMAPPER_HXX
#include "PageMasterExportPropMapper.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;
using namespace ::xmloff::token;
//______________________________________________________________________________
sal_Bool XMLPageExport::findPageMasterName( const OUString& rStyleName, OUString& rPMName ) const
{
for( ::std::vector< XMLPageExportNameEntry >::const_iterator pEntry = aNameVector.begin();
pEntry != aNameVector.end(); pEntry++ )
{
if( pEntry->sStyleName == rStyleName )
{
rPMName = pEntry->sPageMasterName;
return sal_True;
}
}
return sal_False;
}
void XMLPageExport::collectPageMasterAutoStyle(
const Reference < XPropertySet > & rPropSet,
OUString& rPageMasterName )
{
DBG_ASSERT( xPageMasterPropSetMapper.is(), "page master family/XMLPageMasterPropSetMapper not found" );
if( xPageMasterPropSetMapper.is() )
{
::std::vector<XMLPropertyState> xPropStates = xPageMasterExportPropMapper->Filter( rPropSet );
if(xPropStates.size())
{
OUString sParent;
rPageMasterName = rExport.GetAutoStylePool()->Find( XML_STYLE_FAMILY_PAGE_MASTER, sParent, xPropStates );
if (!rPageMasterName.getLength())
rPageMasterName = rExport.GetAutoStylePool()->Add(XML_STYLE_FAMILY_PAGE_MASTER, sParent, xPropStates);
}
}
}
void XMLPageExport::exportMasterPageContent(
const Reference < XPropertySet > &,
sal_Bool /*bAutoStyles*/ )
{
}
sal_Bool XMLPageExport::exportStyle(
const Reference< XStyle >& rStyle,
sal_Bool bAutoStyles )
{
Reference< XPropertySet > xPropSet( rStyle, UNO_QUERY );
Reference< XPropertySetInfo > xPropSetInfo = xPropSet->getPropertySetInfo();
Any aAny;
// Don't export styles that aren't existing really. This may be the
// case for StarOffice Writer's pool styles.
if( xPropSetInfo->hasPropertyByName( sIsPhysical ) )
{
aAny = xPropSet->getPropertyValue( sIsPhysical );
if( !*(sal_Bool *)aAny.getValue() )
return sal_False;
}
if( bAutoStyles )
{
XMLPageExportNameEntry aEntry;
collectPageMasterAutoStyle( xPropSet, aEntry.sPageMasterName );
aEntry.sStyleName = rStyle->getName();
aNameVector.push_back( aEntry );
exportMasterPageContent( xPropSet, sal_True );
}
else
{
OUString sName( rStyle->getName() );
sal_Bool bEncoded = sal_False;
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_NAME,
GetExport().EncodeStyleName( sName, &bEncoded ) );
if( bEncoded )
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_DISPLAY_NAME,
sName);
OUString sPMName;
if( findPageMasterName( sName, sPMName ) )
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_PAGE_LAYOUT_NAME, GetExport().EncodeStyleName( sPMName ) );
aAny = xPropSet->getPropertyValue( sFollowStyle );
OUString sNextName;
aAny >>= sNextName;
if( sName != sNextName && sNextName.getLength() )
{
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_NEXT_STYLE_NAME,
GetExport().EncodeStyleName( sNextName ) );
}
// OUString sPageMaster = GetExport().GetAutoStylePool()->Find(
// XML_STYLE_FAMILY_PAGE_MASTER,
// xPropSet );
// if( sPageMaster.getLength() )
// GetExport().AddAttribute( XML_NAMESPACE_STYLE,
// XML_PAGE_MASTER_NAME,
// sPageMaster );
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
XML_MASTER_PAGE, sal_True, sal_True );
exportMasterPageContent( xPropSet, sal_False );
}
return sal_True;
}
XMLPageExport::XMLPageExport( SvXMLExport& rExp ) :
rExport( rExp ),
sIsPhysical( RTL_CONSTASCII_USTRINGPARAM( "IsPhysical" ) ),
sFollowStyle( RTL_CONSTASCII_USTRINGPARAM( "FollowStyle" ) )
{
xPageMasterPropHdlFactory = new XMLPageMasterPropHdlFactory;
xPageMasterPropSetMapper = new XMLPageMasterPropSetMapper(
(XMLPropertyMapEntry*) aXMLPageMasterStyleMap,
xPageMasterPropHdlFactory );
xPageMasterExportPropMapper = new XMLPageMasterExportPropMapper(
xPageMasterPropSetMapper, rExp);
rExport.GetAutoStylePool()->AddFamily( XML_STYLE_FAMILY_PAGE_MASTER, OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_PAGE_MASTER_NAME ) ),
xPageMasterExportPropMapper, OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_PAGE_MASTER_PREFIX ) ), sal_False );
Reference< XStyleFamiliesSupplier > xFamiliesSupp( GetExport().GetModel(),
UNO_QUERY );
DBG_ASSERT( xFamiliesSupp.is(),
"No XStyleFamiliesSupplier from XModel for export!" );
if( xFamiliesSupp.is() )
{
Reference< XNameAccess > xFamilies( xFamiliesSupp->getStyleFamilies() );
DBG_ASSERT( xFamiliesSupp.is(),
"getStyleFamilies() from XModel failed for export!" );
if( xFamilies.is() )
{
const OUString aPageStyleName(
RTL_CONSTASCII_USTRINGPARAM( "PageStyles" ));
if( xFamilies->hasByName( aPageStyleName ) )
{
Reference < XNameContainer > xStyleCont;
xFamilies->getByName( aPageStyleName ) >>= xStyleCont;
xPageStyles = Reference< XIndexAccess >( xStyleCont,
UNO_QUERY );
DBG_ASSERT( xPageStyles.is(),
"Page Styles not found for export!" );
}
}
}
}
XMLPageExport::~XMLPageExport()
{
}
void XMLPageExport::exportStyles( sal_Bool bUsed, sal_Bool bAutoStyles )
{
if( xPageStyles.is() )
{
const sal_Int32 nStyles = xPageStyles->getCount();
for( sal_Int32 i=0; i < nStyles; i++ )
{
Reference< XStyle > xStyle;
xPageStyles->getByIndex( i ) >>= xStyle;
if( !bUsed || xStyle->isInUse() )
exportStyle( xStyle, bAutoStyles );
}
}
}
void XMLPageExport::exportAutoStyles()
{
rExport.GetAutoStylePool()->exportXML(XML_STYLE_FAMILY_PAGE_MASTER
, rExport.GetDocHandler(), rExport.GetMM100UnitConverter(),
rExport.GetNamespaceMap()
);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hfi_typetext.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-07 17:49:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef ADC_DISPLAY_HFI_TYPETEXT_HXX
#define ADC_DISPLAY_HFI_TYPETEXT_HXX
// USED SERVICES
// BASE CLASSES
#include "hi_factory.hxx"
// COMPONENTS
// PARAMETERS
class HF_IdlTypeText : public HtmlFactory_Idl
{
public:
enum E_Index { use_for_javacompatible_index };
HF_IdlTypeText(
Environment & io_rEnv,
Xml::Element & o_rOut,
bool i_bWithLink,
const client * i_pScopeGivingCe = 0 );
HF_IdlTypeText(
Environment & io_rEnv,
E_Index e );
virtual ~HF_IdlTypeText();
void Produce_byData(
ary::idl::Type_id i_idType ) const;
void Produce_byData(
ary::idl::Ce_id i_idCe ) const;
void Produce_byData(
const String & i_sFullName ) const;
void Produce_LinkInDocu(
const String & i_scope,
const String & i_name,
const String & i_member ) const;
void Produce_LocalLinkInDocu(
const String & i_member ) const;
/// Produce the first link for Java-help understood index entries.
void Produce_IndexLink(
Xml::Element & o_out,
const client & i_ce ) const;
/** Produce the second link for Java-help understood index entries.
For members this will be a link to their owner (this function is
used), else see @->Produce_IndexSecondEntryLink();
*/
void Produce_IndexOwnerLink(
Xml::Element & o_out,
const client & i_owner ) const;
/** Produce the second link for Java-help understood index entries.
For non- members this will again be a link to to the entry itself
(this function is used), else see @->Produce_IndexOwnerLink();
*/
void Produce_IndexSecondEntryLink(
Xml::Element & o_out,
const client & i_ce ) const;
private:
// Locals
enum E_Existence
{
exists_dontknow,
exists_yes,
exists_no
};
void produce_FromStd(
const StringVector &
i_module,
const String & i_ce,
const String & i_member,
int i_sequenceCount,
E_Existence i_ceExists,
ary::idl::Type_id i_nTemplateType = ary::idl::Type_id::Null_() ) const;
void produce_BuiltIn(
const String & i_type,
int i_sequenceCount ) const;
void produce_IndexLink(
const StringVector &
i_module,
const String & i_ce,
const String & i_member,
bool i_bIsOwner ) const;
int count_Sequences(
const char * i_sFullType ) const;
void start_Sequence(
int i_count ) const;
void finish_Sequence(
int i_count ) const;
void errorOut_UnresolvedLink(
const char * i_name ) const;
void errorOut_UnresolvedLink(
const StringVector &
i_module,
const String & i_ce,
const String & i_member ) const;
void errorOut_UnresolvedLink(
const String & i_module,
const String & i_ce,
const String & i_member ) const;
bool is_ExternLink(
const StringVector &
i_module ) const;
void produce_ExternLink(
const StringVector &
i_module,
const String & i_ce,
const String & i_member,
int i_sequenceCount,
ary::idl::Type_id i_nTemplateType ) const;
const ary::idl::Module *
referingModule() const;
const client * referingCe() const;
// DATA
mutable const client *
pReferingCe;
bool bWithLink;
};
// IMPLEMENTATION
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.80); FILE MERGED 2008/03/28 16:02:06 rt 1.6.80.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hfi_typetext.hxx,v $
* $Revision: 1.7 $
*
* 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.
*
************************************************************************/
#ifndef ADC_DISPLAY_HFI_TYPETEXT_HXX
#define ADC_DISPLAY_HFI_TYPETEXT_HXX
// USED SERVICES
// BASE CLASSES
#include "hi_factory.hxx"
// COMPONENTS
// PARAMETERS
class HF_IdlTypeText : public HtmlFactory_Idl
{
public:
enum E_Index { use_for_javacompatible_index };
HF_IdlTypeText(
Environment & io_rEnv,
Xml::Element & o_rOut,
bool i_bWithLink,
const client * i_pScopeGivingCe = 0 );
HF_IdlTypeText(
Environment & io_rEnv,
E_Index e );
virtual ~HF_IdlTypeText();
void Produce_byData(
ary::idl::Type_id i_idType ) const;
void Produce_byData(
ary::idl::Ce_id i_idCe ) const;
void Produce_byData(
const String & i_sFullName ) const;
void Produce_LinkInDocu(
const String & i_scope,
const String & i_name,
const String & i_member ) const;
void Produce_LocalLinkInDocu(
const String & i_member ) const;
/// Produce the first link for Java-help understood index entries.
void Produce_IndexLink(
Xml::Element & o_out,
const client & i_ce ) const;
/** Produce the second link for Java-help understood index entries.
For members this will be a link to their owner (this function is
used), else see @->Produce_IndexSecondEntryLink();
*/
void Produce_IndexOwnerLink(
Xml::Element & o_out,
const client & i_owner ) const;
/** Produce the second link for Java-help understood index entries.
For non- members this will again be a link to to the entry itself
(this function is used), else see @->Produce_IndexOwnerLink();
*/
void Produce_IndexSecondEntryLink(
Xml::Element & o_out,
const client & i_ce ) const;
private:
// Locals
enum E_Existence
{
exists_dontknow,
exists_yes,
exists_no
};
void produce_FromStd(
const StringVector &
i_module,
const String & i_ce,
const String & i_member,
int i_sequenceCount,
E_Existence i_ceExists,
ary::idl::Type_id i_nTemplateType = ary::idl::Type_id::Null_() ) const;
void produce_BuiltIn(
const String & i_type,
int i_sequenceCount ) const;
void produce_IndexLink(
const StringVector &
i_module,
const String & i_ce,
const String & i_member,
bool i_bIsOwner ) const;
int count_Sequences(
const char * i_sFullType ) const;
void start_Sequence(
int i_count ) const;
void finish_Sequence(
int i_count ) const;
void errorOut_UnresolvedLink(
const char * i_name ) const;
void errorOut_UnresolvedLink(
const StringVector &
i_module,
const String & i_ce,
const String & i_member ) const;
void errorOut_UnresolvedLink(
const String & i_module,
const String & i_ce,
const String & i_member ) const;
bool is_ExternLink(
const StringVector &
i_module ) const;
void produce_ExternLink(
const StringVector &
i_module,
const String & i_ce,
const String & i_member,
int i_sequenceCount,
ary::idl::Type_id i_nTemplateType ) const;
const ary::idl::Module *
referingModule() const;
const client * referingCe() const;
// DATA
mutable const client *
pReferingCe;
bool bWithLink;
};
// IMPLEMENTATION
#endif
<|endoftext|> |
<commit_before>#include "TwitterApp.h"
#include "ofxXmlSettings.h"
ofEvent<TwitterAppEvent> twitter_app_dispatcher;
// Init
// -------------------------------------
TwitterApp::TwitterApp()
:stream(twitter)
,uploader(*this)
,image_writer(*this)
,initialized(false)
{
}
TwitterApp::~TwitterApp() {
onTwitterStreamDisconnected();
}
void TwitterApp::init(int oscPort) {
initDB();
initTwitter();
initOSC(oscPort);
initStoredSearchTerms();
uploader.startThread(true, false);
image_writer.startThread(true, false);
initialized = true;
}
void TwitterApp::initTwitter() {
// @todo set to correct dewarshub consumer key + secret
twitter.setConsumerKey("kyw8bCAWKbkP6e1HMMdAvw");
twitter.setConsumerSecret("PwVuyjLeUdVZbi4ER6yRAo0byF55AIureauV6UhLRw");
//string token_file = ofToDataPath("twitter_roxlu.txt", true);
//string token_file = ofToDataPath("twitter_roxlutest.txt", true);
string token_file = ofToDataPath("twitter_dewarshub.txt", true);
//string token_file = ofToDataPath("twitter.txt", true);
if(!twitter.loadTokens(token_file)) {
string auth_url;
twitter.requestToken(auth_url);
twitter.handlePin(auth_url);
twitter.accessToken();
twitter.saveTokens(token_file);
}
// We listen to "connection" events of the stream.
stream.addEventListener(this);
mentions.setup(twitter.getConsumerKey(), twitter.getConsumerSecret(), token_file);
mentions.startThread(true,false);
//removeTweetsFromConnectedAccount();
}
// removes 20 tweets per times!
void TwitterApp::removeTweetsFromConnectedAccount() {
twitter.statusesUserTimeline();
vector<rtt::Tweet> result;
twitter.getJSON().parseStatusArray(twitter.getResponse(), result);
for(int i = 0; i < result.size(); ++i) {
rtt::Tweet& tweet = result[i];
printf("> %s %s\n", tweet.getText().c_str(), tweet.getTweetID().c_str());
twitter.statusesDestroy(tweet.getTweetID());
}
}
void TwitterApp::initOSC(int port) {
osc_receiver.setup(port);
osc_receiver.addListener(this);
}
void TwitterApp::initDB() {
//grant all on dewarscube_admin.* to dewarscube_admin@"%" identified by "dewarscube_admin"
if(!mysql.connect("localhost" , "dewarshub_admin", "dewarshub_admin", "dewarshub_admin", "/tmp/mysql.sock")) {
//if(!mysql.connect("localhost" , "dewarshub_admin", "dewarshub_admin", "dewarshub_admin")) {
//if(!mysql.connect("dewarshub.demo.apollomedia.nl" , "dewarscube_admin", "dewarscube_admin", "dewarscube_admin")) {
//if(!mysql.connect("dewarshub.demo.apollomedia.nl" , "dewarshub_admin", "dewarshub_admin", "dewarshub_admin")) {
exit(0);
}
db_thread.startThread(true, false);
reloadHashTags();
reloadBadWords();
}
// load search terms which are saved on disk.
void TwitterApp::initStoredSearchTerms() {
search_queue.setup(ofToDataPath("twitter_search_terms.bin",true));
search_queue.load();
}
// OSC
// -------------------------------------
// OSC event: bad words handling
void TwitterApp::onUpdateBadWordList() {
reloadBadWords();
}
// Reloads the badwords from MySQL DB.
bool TwitterApp::reloadBadWords() {
vector<string> w;
if(!mysql.getBadWords(w)) {
return false;
}
bad_words.setBadWords(w);
return true;
}
// only used to make testing everything a bit more easy.
void TwitterApp::simulateSearch(const string& term) {
printf("> simulate search.\n");
rtt::Tweet tweet;
tweet.setScreenName("roxlu");
tweet.setText("@dewarshub " +term);
vector<roxlu::twitter::IEventListener*>& listeners = twitter.getEventListeners();
for(int i = 0; i < listeners.size(); ++i) {
listeners[i]->onStatusUpdate(tweet);
}
}
// Bad words & hash tags
// -------------------------------------
bool TwitterApp::containsBadWord(const string& text, string& foundWord) {
return bad_words.containsBadWord(text, foundWord);
}
// OSC event: reload hashtags
void TwitterApp::onUpdateHashTags() {
reloadHashTags();
if(stream.isConnected()) {
stream.disconnect();
}
connect();
}
// Update the stream connection with new tags to track.
void TwitterApp::reloadHashTags() {
stream.clearTrackList();
vector<string> tags;
if(mysql.getTrackList(tags)) {
vector<string>::iterator it = tags.begin();
while(it != tags.end()) {
stream.track((*it));
++it;
}
}
}
// Twitter
// -------------------------------------
bool TwitterApp::connect(){
if(!stream.connect(URL_STREAM_USER)) {
printf("Error: cannot connect to user stream.\n");
return false;
}
return true;
}
void TwitterApp::addCustomStreamListener(rt::IEventListener& listener){
twitter.addEventListener(listener);
}
void TwitterApp::update() {
if(!initialized) {
printf("TwitterApp: make sure to call init() first!\n");
exit(0);
}
if(stream.isConnected()) {
stream.update();
}
osc_receiver.update();
// Check for new search terms from the thread which poll mentions
vector<TwitterMentionSearchTerm> new_search_terms;
if(mentions.getSearchTerms(new_search_terms)) {
vector<TwitterMentionSearchTerm>::iterator it = new_search_terms.begin();
while(it != new_search_terms.end()) {
TwitterMentionSearchTerm& st = *it;
// check if the search term or username contains a bad word.
string found_badword;
if(containsBadWord(st.search_term, found_badword)) {
printf("[search with bad word] %s %s\n", st.search_term.c_str(), found_badword.c_str());
++it;
continue;
}
found_badword.clear();
if(containsBadWord(st.tweet.getScreenName(), found_badword)) {
printf("[search user with bad word] %s %s\n", st.tweet.getScreenName().c_str(), found_badword.c_str());
++it;
continue;
}
onNewSearchTerm(st.tweet, st.search_term);
++it;
}
}
}
// TODO make sure new search terms are added to the search_queue....
// but only if that's still necessary (?) we can use twitter as a store?
void TwitterApp::onNewSearchTerm(rtt::Tweet tweet, const string& term) {
// When we added a new search term to the queue, pass it through!
if(search_queue.addSearchTerm(tweet.getScreenName(), term)) {
TwitterAppEvent ev(tweet, term);
ofNotifyEvent(twitter_app_dispatcher, ev);
}
}
// TODO: remove this; not used in Wailwall
// get the list of people to follow, separated by comma
bool TwitterApp::getFollowers(vector<string>& result) {
// TODO: fix db
// return db.getFollowers(result);
}
void TwitterApp::onTwitterStreamDisconnected() {
mysql.setSetting("twitter_connected", "n");
}
void TwitterApp::onTwitterStreamConnected() {
mysql.setSetting("twitter_connected", "y");
}
// Just for testing.
void TwitterApp::executeSearchTest() {
int start = ofGetElapsedTimeMillis();
vector<rtt::Tweet> found;
db_thread.getTweetsWithSearchTerm("love", 99999, 100, found);
int end = ofGetElapsedTimeMillis();
int diff = end - start;
printf("Testing search, found %zu item in %d millis\n", found.size(), diff );
}<commit_msg>Stuff<commit_after>#include "TwitterApp.h"
#include "ofxXmlSettings.h"
ofEvent<TwitterAppEvent> twitter_app_dispatcher;
// Init
// -------------------------------------
TwitterApp::TwitterApp()
:stream(twitter)
,uploader(*this)
,image_writer(*this)
,initialized(false)
{
}
TwitterApp::~TwitterApp() {
onTwitterStreamDisconnected();
}
void TwitterApp::init(int oscPort) {
initDB();
initTwitter();
initOSC(oscPort);
initStoredSearchTerms();
uploader.startThread(true, false);
image_writer.startThread(true, false);
initialized = true;
}
void TwitterApp::initTwitter() {
// @todo set to correct dewarshub consumer key + secret
twitter.setConsumerKey("kyw8bCAWKbkP6e1HMMdAvw");
twitter.setConsumerSecret("PwVuyjLeUdVZbi4ER6yRAo0byF55AIureauV6UhLRw");
//string token_file = ofToDataPath("twitter_roxlu.txt", true);
//string token_file = ofToDataPath("twitter_roxlutest.txt", true);
string token_file = ofToDataPath("twitter_dewarshub.txt", true);
//string token_file = ofToDataPath("twitter.txt", true);
if(!twitter.loadTokens(token_file)) {
string auth_url;
twitter.requestToken(auth_url);
twitter.handlePin(auth_url);
twitter.accessToken();
twitter.saveTokens(token_file);
}
// We listen to "connection" events of the stream.
stream.addEventListener(this);
mentions.setup(twitter.getConsumerKey(), twitter.getConsumerSecret(), token_file);
mentions.startThread(true,false);
//removeTweetsFromConnectedAccount();
}
// removes 20 tweets per times!
void TwitterApp::removeTweetsFromConnectedAccount() {
twitter.statusesUserTimeline();
vector<rtt::Tweet> result;
twitter.getJSON().parseStatusArray(twitter.getResponse(), result);
for(int i = 0; i < result.size(); ++i) {
rtt::Tweet& tweet = result[i];
printf("> %s %s\n", tweet.getText().c_str(), tweet.getTweetID().c_str());
twitter.statusesDestroy(tweet.getTweetID());
}
}
void TwitterApp::initOSC(int port) {
osc_receiver.setup(port);
osc_receiver.addListener(this);
}
void TwitterApp::initDB() {
//grant all on dewarscube_admin.* to dewarscube_admin@"%" identified by "dewarscube_admin"
if(!mysql.connect("localhost" , "dewarshub_admin", "dewarshub_admin", "dewarshub_admin", "/Applications/MAMP/tmp/mysql/mysql.sock")) {
//if(!mysql.connect("localhost" , "dewarshub_admin", "dewarshub_admin", "dewarshub_admin")) {
//if(!mysql.connect("dewarshub.demo.apollomedia.nl" , "dewarscube_admin", "dewarscube_admin", "dewarscube_admin")) {
//if(!mysql.connect("dewarshub.demo.apollomedia.nl" , "dewarshub_admin", "dewarshub_admin", "dewarshub_admin")) {
exit(0);
}
db_thread.startThread(true, false);
reloadHashTags();
reloadBadWords();
}
// load search terms which are saved on disk.
void TwitterApp::initStoredSearchTerms() {
search_queue.setup(ofToDataPath("twitter_search_terms.bin",true));
search_queue.load();
}
// OSC
// -------------------------------------
// OSC event: bad words handling
void TwitterApp::onUpdateBadWordList() {
reloadBadWords();
}
// Reloads the badwords from MySQL DB.
bool TwitterApp::reloadBadWords() {
vector<string> w;
if(!mysql.getBadWords(w)) {
return false;
}
bad_words.setBadWords(w);
return true;
}
// only used to make testing everything a bit more easy.
void TwitterApp::simulateSearch(const string& term) {
printf("> simulate search.\n");
rtt::Tweet tweet;
tweet.setScreenName("roxlu");
tweet.setText("@dewarshub " +term);
vector<roxlu::twitter::IEventListener*>& listeners = twitter.getEventListeners();
for(int i = 0; i < listeners.size(); ++i) {
listeners[i]->onStatusUpdate(tweet);
}
}
// Bad words & hash tags
// -------------------------------------
bool TwitterApp::containsBadWord(const string& text, string& foundWord) {
return bad_words.containsBadWord(text, foundWord);
}
// OSC event: reload hashtags
void TwitterApp::onUpdateHashTags() {
reloadHashTags();
if(stream.isConnected()) {
stream.disconnect();
}
connect();
}
// Update the stream connection with new tags to track.
void TwitterApp::reloadHashTags() {
stream.clearTrackList();
vector<string> tags;
if(mysql.getTrackList(tags)) {
vector<string>::iterator it = tags.begin();
while(it != tags.end()) {
stream.track((*it));
++it;
}
}
}
// Twitter
// -------------------------------------
bool TwitterApp::connect(){
if(!stream.connect(URL_STREAM_USER)) {
printf("Error: cannot connect to user stream.\n");
return false;
}
return true;
}
void TwitterApp::addCustomStreamListener(rt::IEventListener& listener){
twitter.addEventListener(listener);
}
void TwitterApp::update() {
if(!initialized) {
printf("TwitterApp: make sure to call init() first!\n");
exit(0);
}
if(stream.isConnected()) {
stream.update();
}
osc_receiver.update();
// Check for new search terms from the thread which poll mentions
vector<TwitterMentionSearchTerm> new_search_terms;
if(mentions.getSearchTerms(new_search_terms)) {
vector<TwitterMentionSearchTerm>::iterator it = new_search_terms.begin();
while(it != new_search_terms.end()) {
TwitterMentionSearchTerm& st = *it;
// check if the search term or username contains a bad word.
string found_badword;
if(containsBadWord(st.search_term, found_badword)) {
printf("[search with bad word] %s %s\n", st.search_term.c_str(), found_badword.c_str());
++it;
continue;
}
found_badword.clear();
if(containsBadWord(st.tweet.getScreenName(), found_badword)) {
printf("[search user with bad word] %s %s\n", st.tweet.getScreenName().c_str(), found_badword.c_str());
++it;
continue;
}
onNewSearchTerm(st.tweet, st.search_term);
++it;
}
}
}
// TODO make sure new search terms are added to the search_queue....
// but only if that's still necessary (?) we can use twitter as a store?
void TwitterApp::onNewSearchTerm(rtt::Tweet tweet, const string& term) {
// When we added a new search term to the queue, pass it through!
if(search_queue.addSearchTerm(tweet.getScreenName(), term)) {
TwitterAppEvent ev(tweet, term);
ofNotifyEvent(twitter_app_dispatcher, ev);
}
}
// TODO: remove this; not used in Wailwall
// get the list of people to follow, separated by comma
bool TwitterApp::getFollowers(vector<string>& result) {
// TODO: fix db
// return db.getFollowers(result);
}
void TwitterApp::onTwitterStreamDisconnected() {
mysql.setSetting("twitter_connected", "n");
}
void TwitterApp::onTwitterStreamConnected() {
mysql.setSetting("twitter_connected", "y");
}
// Just for testing.
void TwitterApp::executeSearchTest() {
int start = ofGetElapsedTimeMillis();
vector<rtt::Tweet> found;
db_thread.getTweetsWithSearchTerm("love", 99999, 100, found);
int end = ofGetElapsedTimeMillis();
int diff = end - start;
printf("Testing search, found %zu item in %d millis\n", found.size(), diff );
}<|endoftext|> |
<commit_before>/*
This file is part of kdepim.
Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>
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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qbuttongroup.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qradiobutton.h>
#include <kaccelmanager.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kpushbutton.h>
#include <kstdguiitem.h>
#include "egroupwarewizard.h"
//#include "kolabwizard.h"
#include "sloxwizard.h"
#include "overviewpage.h"
OverViewPage::OverViewPage( QWidget *parent, const char *name )
: QWidget( parent, name )
{
QGridLayout *layout = new QGridLayout( this, 7, 4, KDialog::marginHint(),
KDialog::spacingHint() );
const QString msg = i18n( "KDE Groupware Wizard" );
QLabel *label = new QLabel( "<qt><b><u><h2>" + msg + "</h2></u></b></qt>" , this );
layout->addMultiCellWidget( label, 0, 0, 0, 2 );
label = new QLabel( this );
label->setPixmap( KGlobal::iconLoader()->loadIcon( "network", KIcon::Desktop ) );
layout->addWidget( label, 0, 3 );
label = new QLabel( "", this );
layout->addWidget( label, 1, 0 );
layout->setRowSpacing( 1, 20 );
label = new QLabel( i18n( "Select the type of server you want connect your KDE to:" ), this );
layout->addMultiCellWidget( label, 2, 2, 0, 3 );
QPushButton *button = new QPushButton( i18n("eGroupware"), this );
layout->addMultiCellWidget( button, 3, 3, 0, 3 );
connect( button, SIGNAL( clicked() ), SLOT( showWizardEGroupware() ) );
// FIXME: Maybe hyperlinks would be better than buttons.
button = new QPushButton( i18n("Kolab"), this );
layout->addMultiCellWidget( button, 4, 4, 0, 3 );
connect( button, SIGNAL( clicked() ), SLOT( showWizardKolab() ) );
button = new QPushButton( i18n("SLOX"), this );
layout->addMultiCellWidget( button, 5, 5, 0, 3 );
connect( button, SIGNAL( clicked() ), SLOT( showWizardSlox() ) );
QFrame *frame = new QFrame( this );
frame->setFrameStyle( QFrame::HLine | QFrame::Sunken );
layout->addMultiCellWidget( frame, 6, 6, 0, 3 );
QPushButton *cancelButton = new KPushButton( KStdGuiItem::close(), this );
layout->addWidget( cancelButton, 8, 3 );
connect( cancelButton, SIGNAL( clicked() ), this, SIGNAL( cancel() ) );
layout->setRowStretch( 7, 1 );
KAcceleratorManager::manage( this );
}
OverViewPage::~OverViewPage()
{
}
void OverViewPage::showWizardEGroupware()
{
EGroupwareWizard wizard;
wizard.exec();
}
void OverViewPage::showWizardKolab()
{
KolabWizard wizard;
wizard.exec();
}
void OverViewPage::showWizardSlox()
{
SloxWizard wizard;
wizard.exec();
}
#include "overviewpage.moc"
<commit_msg>Cleaning up behind danimo.<commit_after>/*
This file is part of kdepim.
Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>
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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qbuttongroup.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qradiobutton.h>
#include <kaccelmanager.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kpushbutton.h>
#include <kstdguiitem.h>
#include "egroupwarewizard.h"
#include "kolabwizard.h"
#include "sloxwizard.h"
#include "overviewpage.h"
OverViewPage::OverViewPage( QWidget *parent, const char *name )
: QWidget( parent, name )
{
QGridLayout *layout = new QGridLayout( this, 7, 4, KDialog::marginHint(),
KDialog::spacingHint() );
const QString msg = i18n( "KDE Groupware Wizard" );
QLabel *label = new QLabel( "<qt><b><u><h2>" + msg + "</h2></u></b></qt>" , this );
layout->addMultiCellWidget( label, 0, 0, 0, 2 );
label = new QLabel( this );
label->setPixmap( KGlobal::iconLoader()->loadIcon( "network", KIcon::Desktop ) );
layout->addWidget( label, 0, 3 );
label = new QLabel( "", this );
layout->addWidget( label, 1, 0 );
layout->setRowSpacing( 1, 20 );
label = new QLabel( i18n( "Select the type of server you want connect your KDE to:" ), this );
layout->addMultiCellWidget( label, 2, 2, 0, 3 );
QPushButton *button = new QPushButton( i18n("eGroupware"), this );
layout->addMultiCellWidget( button, 3, 3, 0, 3 );
connect( button, SIGNAL( clicked() ), SLOT( showWizardEGroupware() ) );
// FIXME: Maybe hyperlinks would be better than buttons.
button = new QPushButton( i18n("Kolab"), this );
layout->addMultiCellWidget( button, 4, 4, 0, 3 );
connect( button, SIGNAL( clicked() ), SLOT( showWizardKolab() ) );
button = new QPushButton( i18n("SLOX"), this );
layout->addMultiCellWidget( button, 5, 5, 0, 3 );
connect( button, SIGNAL( clicked() ), SLOT( showWizardSlox() ) );
QFrame *frame = new QFrame( this );
frame->setFrameStyle( QFrame::HLine | QFrame::Sunken );
layout->addMultiCellWidget( frame, 6, 6, 0, 3 );
QPushButton *cancelButton = new KPushButton( KStdGuiItem::close(), this );
layout->addWidget( cancelButton, 8, 3 );
connect( cancelButton, SIGNAL( clicked() ), this, SIGNAL( cancel() ) );
layout->setRowStretch( 7, 1 );
KAcceleratorManager::manage( this );
}
OverViewPage::~OverViewPage()
{
}
void OverViewPage::showWizardEGroupware()
{
EGroupwareWizard wizard;
wizard.exec();
}
void OverViewPage::showWizardKolab()
{
KolabWizard wizard;
wizard.exec();
}
void OverViewPage::showWizardSlox()
{
SloxWizard wizard;
wizard.exec();
}
#include "overviewpage.moc"
<|endoftext|> |
<commit_before>#pragma once
#include <cc/node.hpp>
namespace pip
{
// The kinds of types.
enum type_kind : int
{
tk_int,
tk_range,
tk_wild,
tk_miss,
tk_port,
tk_loc,
};
/// Represents a type.
struct type : cc::node
{
type(type_kind k)
: cc::node(k, {})
{ }
};
/// The type of integer values.
///
/// TODO: I think we also need to represent integer encoding.
struct int_type : type
{
int_type(int w)
: type(tk_int), width(w)
{ }
/// The width (precision) of integer values.
int width;
};
/// A range over an integer type.
struct range_type : type
{
range_type(type* t)
: type(tk_range), value(t)
{ }
/// The underlying integer type.
type* value;
};
/// The type of wildcard values.
struct wild_type : type
{
wild_type(int w)
: type(tk_wild), width(w)
{ }
/// The width (precision) of wildcard values.
int width;
};
/// The type of a miss expression; this is temporary.
/// miss expressions may change to have the type of
/// the key that was missed, or unit type
struct miss_type : type
{
miss_type()
: type(tk_miss)
{}
};
/// The type of a port expression
struct port_type : type
{
port_type()
: type(tk_port)
{}
};
/// The type of a location or field
struct loc_type : type
{
loc_type()
: type(tk_loc)
{}
};
// -------------------------------------------------------------------------- //
// Operations
/// Returns the name of a type node.
const char* get_node_name(type_kind k);
// Returns the kind of a type.
inline type_kind
get_type_kind(const type* t)
{
return static_cast<type_kind>(t->kind);
}
/// Returns the node name of a program.
inline const char*
get_node_name(const type* t)
{
return get_node_name(get_type_kind(t));
}
} // namespace pip
<commit_msg>implement get_node_name(type_kind k)<commit_after>#pragma once
#include <cc/node.hpp>
namespace pip
{
// The kinds of types.
enum type_kind : int
{
tk_int,
tk_range,
tk_wild,
tk_miss,
tk_port,
tk_loc,
};
/// Represents a type.
struct type : cc::node
{
type(type_kind k)
: cc::node(k, {})
{ }
};
/// The type of integer values.
///
/// TODO: I think we also need to represent integer encoding.
struct int_type : type
{
int_type(int w)
: type(tk_int), width(w)
{ }
/// The width (precision) of integer values.
int width;
};
/// A range over an integer type.
struct range_type : type
{
range_type(type* t)
: type(tk_range), value(t)
{ }
/// The underlying integer type.
type* value;
};
/// The type of wildcard values.
struct wild_type : type
{
wild_type(int w)
: type(tk_wild), width(w)
{ }
/// The width (precision) of wildcard values.
int width;
};
/// The type of a miss expression; this is temporary.
/// miss expressions may change to have the type of
/// the key that was missed, or unit type
struct miss_type : type
{
miss_type()
: type(tk_miss)
{}
};
/// The type of a port expression
struct port_type : type
{
port_type()
: type(tk_port)
{}
};
/// The type of a location or field
struct loc_type : type
{
loc_type()
: type(tk_loc)
{}
};
// -------------------------------------------------------------------------- //
// Operations
/// Returns the name of a type node.
inline const char* get_node_name(type_kind k)
{
switch(k)
{
case tk_int:
return "tk_int";
case tk_range:
return "tk_range";
case tk_wild:
return "tk_wild";
case tk_miss:
return "tk_miss";
case tk_port:
return "tk_port";
case tk_loc:
return "tk_loc";
}
}
// Returns the kind of a type.
inline type_kind
get_type_kind(const type* t)
{
return static_cast<type_kind>(t->kind);
}
/// Returns the node name of a program.
inline const char*
get_node_name(const type* t)
{
return get_node_name(get_type_kind(t));
}
} // namespace pip
<|endoftext|> |
<commit_before>#include "pch.h"
#include "Monster.h"
bool Arthas::Monster::init()
{
if (!Component::init())
{
return false;
}
return true;
}
void Arthas::Monster::update(float dTime)
{
}
void Arthas::Monster::enter()
{
}
void Arthas::Monster::exit()
{
}
<commit_msg>Monster 타입 추가<commit_after>#include "pch.h"
#include "Monster.h"
bool Arthas::Monster::init()
{
if (!Component::init())
{
return false;
}
m_Type = OT_MONSTER;
return true;
}
void Arthas::Monster::update(float dTime)
{
}
void Arthas::Monster::enter()
{
}
void Arthas::Monster::exit()
{
}
<|endoftext|> |
<commit_before>// Scalable cached reference counts
//
// This implements space-efficient, scalable reference counting using
// per-core reference delta caches. Increment and decrement
// operations are expected to be core-local, especially for workloads
// with good locality. In contrast with most scalable reference
// counting mechanisms, refcache requires space proportional to the
// sum of the number of reference counted objects and the number of
// cores, rather than the product, and the per-core overhead can be
// adjusted to trade off space and scalability by controlling the
// reference cache eviction rate. Finally, this mechanism guarantees
// that objects will be garbage collected within an adjustable time
// bound of when their reference count drops to zero.
//
// In refcache, each reference counted object has a global reference
// count (much like a regular reference count) and each core also
// maintains a local, fixed-size cache of deltas to object's reference
// counts. Incrementing or decrementing an object's reference count
// modifies only the local, cached delta and this delta is
// periodically flushed to the object's global reference count. The
// true reference count of an object is thus the sum of its global
// count and any local deltas for that object found in the per-core
// caches. The value of the true count is generally unknown, but we
// assume that once it drops to zero, it will remain zero. We depend
// on this stability to detect a zero true count after some delay.
//
// To detect a zero true reference count, refcache divides time into
// periodic *epochs* during which each core flushes all of the
// reference count deltas in its cache, applying these updates to the
// global reference count of each object. The last core in an epoch
// to finish flushing its cache ends the epoch and after some delay
// (our implementation uses 10ms) all of the cores repeat this
// process. Since these flushes occur in no particular order and the
// caches batch reference count changes, updates to the reference
// count can be reordered. As a result, a zero global reference count
// does not imply a zero true reference count. However, once the true
// count *is* zero, there will be no more updates, so if the global
// reference count of an object drops to zero and *remains* zero for
// an entire epoch, then the refcache can guarantee that the true
// count is zero and free the object.
//
// This lag between the true reference count and the global reference
// count of an object is the main complication for refcache. For
// example, consider the following sequence of increments, decrements,
// and flushes for a single object:
//
// t ->
// core 0 - * | * * + | * + |
// 1 + * * | * | - * |
// 2 * | * | * * |
// 3 * | * | - * *
// global 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 0 0
// true 1 2 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 2 1 1 1
// epoch ^----1-----^---2---^-----3-----^-----4-----^
//
// Because of flush order, the two updates in epoch 1 are applied to
// the global reference count in the opposite order of how they
// actually occurred. As a result, core 0 observes the global count
// temporarily drop to zero when it flushes in epoch 1, even though
// the true count is non-zero. This is remedied as soon as core 1
// flushes its increment delta, and when core 0 reexamines the object
// at the end of epoch 2, after all cores have again flushed their
// reference caches, it can see that the global count is non-zero and
// hence the zero count it observed was not a true zero and the object
// should not be freed.
//
// It is not enough for the global reference count to be zero when an
// object is reexamined; rather, it must have been zero for the entire
// epoch. For example, core 0 will observe a zero global reference
// count at the end of epoch 3, and again when it reexamines the
// object at the end of epoch 4. However, the true count is not zero,
// and the global reference count was temporarily non-zero during the
// epoch. We call this a *dirty* zero and in this situation the
// refcache will queue the object to be examined again after another
// epoch.
//
// The pseudocode for refcache is given below. Each core maintains a
// hash table storing its reference delta cache and a "review" queue
// that tracks objects whose global reference counts reached zero. A
// core reviews an object once it can guarantee that all cores have
// flushed their reference caches after it put the object in its
// review queue.
//
// flush():
// evict all cache entries
// update the current epoch
//
// evict(object, delta):
// object.refcnt <- object.refcnt + delta
// if object.refcnt = 0:
// if object is not on any review queue:
// object.dirty <- false
// add (object, epoch) to the local review queue
// else:
// object.dirty <- true
//
// review():
// for each (object, oepoch) in local review queue:
// if oepoch <= epoch + 2:
// remove object from the review queue
// if object.refcnt = 0:
// if object.dirty:
// object.dirty <- false
// add (object, epoch) to the review queue
// else:
// free object
//
// For epoch management, our current implementation uses a simple
// barrier scheme that tracks a global epoch counter, per-core epochs,
// and a count of how many per-core epochs have reached the current
// global epoch. This scheme suffices for our benchmarks, but more
// scalable schemes are possible, such as the tree-based quiescent
// state detection scheme used by Linux's hierarchical RCU
// implementation [http://lwn.net/Articles/305782/].
#pragma once
#include "spinlock.h"
#include "ilist.hh"
#include "percpu.hh"
#include "kstats.hh"
#include "condvar.h"
#ifndef REFCACHE_DEBUG
#define REFCACHE_DEBUG 1
#endif
namespace refcache {
enum {
CACHE_SLOTS = 4096
};
// Base class for an object that's reference counted using the
// refcaching scheme.
class referenced
{
private:
friend class cache;
// XXX This can all be packed into three words
// This lock protects all of the following fields.
spinlock lock_;
// Global reference count. This object's true reference count is
// the sum of this and each core's cached reference delta for this
// object. In general, we don't know what the true reference
// count is except in one situation: when it's been zero for long
// enough, we know it's zero (and will stay zero).
//
// Since the global count can go negative, this must be signed.
int64_t refcount_;
// Link used to track this object in the per-core review list.
islink<referenced> next_;
typedef isqueue<referenced, &referenced::next_> list;
// If this object is on a review list, the epoch in which this
// object can be reviewed. 0 if this object is not on a review
// list.
uint64_t review_epoch_;
// True if this object's refcount was non-zero and then zero again
// since it was last reviewed.
bool dirty_;
public:
constexpr referenced(uint64_t refcount = 1)
: lock_("refcache::referenced"),
refcount_(refcount),
next_(),
review_epoch_(0),
dirty_(false) { }
referenced(const referenced &o) = delete;
referenced(referenced &&o) = delete;
referenced &operator=(const referenced &o) = delete;
referenced &operator=(referenced &&o) = delete;
void inc();
void dec();
protected:
// We could eliminate these virtual methods and the vtable
// altogether with a somewhat more complicated template-based
// scheme in which referenced is a template over the type T being
// referenced-counted. referenced would have a static member
// storing a "manager" object specialized for each type. This
// manager would statically call the appropriate methods of T.
// This would require storing a pointer to the manager alongside
// *generic* pointers to referenced objects (such as in the
// cache's hash table), but wouldn't require the vtable pointer in
// each object or the overhead of virtual method calls.
virtual ~referenced() { };
virtual void onzero() { delete this; }
};
// The reference delta cache. There is one instance of class cache
// per core.
class cache
{
friend class referenced;
struct way
{
referenced *obj;
// XXX Deltas could be much smaller (say int8_t). There are
// several advantages to this, especially if we have higher
// associativity, because we can pack more of them into a cache
// line and find used or unused slots faster. If the delta
// overflows or underflows, we can simply evict it.
int64_t delta;
constexpr way() : obj(), delta() { }
};
// The ways of the cache. This must be accessed with interrupts
// disabled to prevent interference between a review process and
// capacity evictions.
way ways_[CACHE_SLOTS];
// The list of objects to review in increasing epoch order. This
// must be accessed only by the local core and there must be at
// most one reviewer at a time per core.
referenced::list review_;
// The list of objects whose onzero() method should be called. Call
// onzero() from a separate thread, instead of the timer interrupt,
// to avoid deadlock with the thread preempted by the timer.
referenced::list reap_;
spinlock reap_lock_;
condvar reap_cv_;
// The last global epoch number observed by this core.
uint64_t local_epoch;
// Place obj in the cache if necessary and return its assigned
// way. Interrupts must be disabled.
way *get_way(referenced *obj)
{
// XXX Hash pointer better? This isn't bad: it's very fast and
// shouldn't suffer from small alignments.
std::size_t wayno = (((uintptr_t)obj) | ((uintptr_t)obj / CACHE_SLOTS))
% CACHE_SLOTS;
struct way *way = &ways_[wayno];
// XXX More associativity. Since this is in the critical path
// of every reference operation, perhaps we should do something
// like hash-rehash caching?
if (way->obj != obj) {
// This object is not in the cache
if (way->delta) {
// Need to evict to free up an entry. Since this is a
// capacity eviction, local_epoch may be behind
// global_epoch.
evict(way, false);
kstats::inc(&kstats::refcache_conflict_count);
}
// Take this entry
way->obj = obj;
}
return way;
}
// Evict the object from way, freeing up this slot. way must have
// a non-zero delta and interrupts must be disabled. If
// local_epoch_is_exact, then we assume that local_epoch equals
// global_epoch. Otherwise, local_epoch may be global_epoch or
// global_epoch - 1.
void evict(struct way *way, bool local_epoch_is_exact);
// Flush this core's refcache.
void flush();
// Scan this core's review list. The calling thread must be
// pinned (but interrupts may be enabled). At most one review
// call may be active at a time per core.
void review();
public:
cache() = default;
cache(const cache &o) = delete;
cache(cache &&o) = delete;
cache &operator=(const cache &o) = delete;
cache &operator=(cache &&o) = delete;
// Periodic tick handler. Flushes the refcache and scans review
// lists. The latency of garbage collection is between two and
// three times the delay between calls to tic.
void tick();
// Reap dead objects. This is done in a dedicated thread to
// avoid deadlock with threads preempted by the timer interrupt.
void reaper() __attribute__((noreturn));
};
// Per-CPU reference delta cache. In general this has to be
// accessed with interrupts disabled or by a pinned process to
// prevent migration. Some fields of cache specifically require
// interrupts to be disabled to prevent concurrent access.
// XXX Allocation of this should be NUMA-aware
extern percpu<cache> mycache;
inline void
referenced::inc()
{
pushcli();
++mycache->get_way(this)->delta;
popcli();
}
inline void
referenced::dec()
{
pushcli();
--mycache->get_way(this)->delta;
popcli();
}
}
<commit_msg>refcache: Use scoped_cli instead of pushcli/popcli<commit_after>// Scalable cached reference counts
//
// This implements space-efficient, scalable reference counting using
// per-core reference delta caches. Increment and decrement
// operations are expected to be core-local, especially for workloads
// with good locality. In contrast with most scalable reference
// counting mechanisms, refcache requires space proportional to the
// sum of the number of reference counted objects and the number of
// cores, rather than the product, and the per-core overhead can be
// adjusted to trade off space and scalability by controlling the
// reference cache eviction rate. Finally, this mechanism guarantees
// that objects will be garbage collected within an adjustable time
// bound of when their reference count drops to zero.
//
// In refcache, each reference counted object has a global reference
// count (much like a regular reference count) and each core also
// maintains a local, fixed-size cache of deltas to object's reference
// counts. Incrementing or decrementing an object's reference count
// modifies only the local, cached delta and this delta is
// periodically flushed to the object's global reference count. The
// true reference count of an object is thus the sum of its global
// count and any local deltas for that object found in the per-core
// caches. The value of the true count is generally unknown, but we
// assume that once it drops to zero, it will remain zero. We depend
// on this stability to detect a zero true count after some delay.
//
// To detect a zero true reference count, refcache divides time into
// periodic *epochs* during which each core flushes all of the
// reference count deltas in its cache, applying these updates to the
// global reference count of each object. The last core in an epoch
// to finish flushing its cache ends the epoch and after some delay
// (our implementation uses 10ms) all of the cores repeat this
// process. Since these flushes occur in no particular order and the
// caches batch reference count changes, updates to the reference
// count can be reordered. As a result, a zero global reference count
// does not imply a zero true reference count. However, once the true
// count *is* zero, there will be no more updates, so if the global
// reference count of an object drops to zero and *remains* zero for
// an entire epoch, then the refcache can guarantee that the true
// count is zero and free the object.
//
// This lag between the true reference count and the global reference
// count of an object is the main complication for refcache. For
// example, consider the following sequence of increments, decrements,
// and flushes for a single object:
//
// t ->
// core 0 - * | * * + | * + |
// 1 + * * | * | - * |
// 2 * | * | * * |
// 3 * | * | - * *
// global 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 0 0
// true 1 2 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 2 1 1 1
// epoch ^----1-----^---2---^-----3-----^-----4-----^
//
// Because of flush order, the two updates in epoch 1 are applied to
// the global reference count in the opposite order of how they
// actually occurred. As a result, core 0 observes the global count
// temporarily drop to zero when it flushes in epoch 1, even though
// the true count is non-zero. This is remedied as soon as core 1
// flushes its increment delta, and when core 0 reexamines the object
// at the end of epoch 2, after all cores have again flushed their
// reference caches, it can see that the global count is non-zero and
// hence the zero count it observed was not a true zero and the object
// should not be freed.
//
// It is not enough for the global reference count to be zero when an
// object is reexamined; rather, it must have been zero for the entire
// epoch. For example, core 0 will observe a zero global reference
// count at the end of epoch 3, and again when it reexamines the
// object at the end of epoch 4. However, the true count is not zero,
// and the global reference count was temporarily non-zero during the
// epoch. We call this a *dirty* zero and in this situation the
// refcache will queue the object to be examined again after another
// epoch.
//
// The pseudocode for refcache is given below. Each core maintains a
// hash table storing its reference delta cache and a "review" queue
// that tracks objects whose global reference counts reached zero. A
// core reviews an object once it can guarantee that all cores have
// flushed their reference caches after it put the object in its
// review queue.
//
// flush():
// evict all cache entries
// update the current epoch
//
// evict(object, delta):
// object.refcnt <- object.refcnt + delta
// if object.refcnt = 0:
// if object is not on any review queue:
// object.dirty <- false
// add (object, epoch) to the local review queue
// else:
// object.dirty <- true
//
// review():
// for each (object, oepoch) in local review queue:
// if oepoch <= epoch + 2:
// remove object from the review queue
// if object.refcnt = 0:
// if object.dirty:
// object.dirty <- false
// add (object, epoch) to the review queue
// else:
// free object
//
// For epoch management, our current implementation uses a simple
// barrier scheme that tracks a global epoch counter, per-core epochs,
// and a count of how many per-core epochs have reached the current
// global epoch. This scheme suffices for our benchmarks, but more
// scalable schemes are possible, such as the tree-based quiescent
// state detection scheme used by Linux's hierarchical RCU
// implementation [http://lwn.net/Articles/305782/].
#pragma once
#include "spinlock.h"
#include "ilist.hh"
#include "percpu.hh"
#include "kstats.hh"
#include "condvar.h"
#ifndef REFCACHE_DEBUG
#define REFCACHE_DEBUG 1
#endif
namespace refcache {
enum {
CACHE_SLOTS = 4096
};
// Base class for an object that's reference counted using the
// refcaching scheme.
class referenced
{
private:
friend class cache;
// XXX This can all be packed into three words
// This lock protects all of the following fields.
spinlock lock_;
// Global reference count. This object's true reference count is
// the sum of this and each core's cached reference delta for this
// object. In general, we don't know what the true reference
// count is except in one situation: when it's been zero for long
// enough, we know it's zero (and will stay zero).
//
// Since the global count can go negative, this must be signed.
int64_t refcount_;
// Link used to track this object in the per-core review list.
islink<referenced> next_;
typedef isqueue<referenced, &referenced::next_> list;
// If this object is on a review list, the epoch in which this
// object can be reviewed. 0 if this object is not on a review
// list.
uint64_t review_epoch_;
// True if this object's refcount was non-zero and then zero again
// since it was last reviewed.
bool dirty_;
public:
constexpr referenced(uint64_t refcount = 1)
: lock_("refcache::referenced"),
refcount_(refcount),
next_(),
review_epoch_(0),
dirty_(false) { }
referenced(const referenced &o) = delete;
referenced(referenced &&o) = delete;
referenced &operator=(const referenced &o) = delete;
referenced &operator=(referenced &&o) = delete;
void inc();
void dec();
protected:
// We could eliminate these virtual methods and the vtable
// altogether with a somewhat more complicated template-based
// scheme in which referenced is a template over the type T being
// referenced-counted. referenced would have a static member
// storing a "manager" object specialized for each type. This
// manager would statically call the appropriate methods of T.
// This would require storing a pointer to the manager alongside
// *generic* pointers to referenced objects (such as in the
// cache's hash table), but wouldn't require the vtable pointer in
// each object or the overhead of virtual method calls.
virtual ~referenced() { };
virtual void onzero() { delete this; }
};
// The reference delta cache. There is one instance of class cache
// per core.
class cache
{
friend class referenced;
struct way
{
referenced *obj;
// XXX Deltas could be much smaller (say int8_t). There are
// several advantages to this, especially if we have higher
// associativity, because we can pack more of them into a cache
// line and find used or unused slots faster. If the delta
// overflows or underflows, we can simply evict it.
int64_t delta;
constexpr way() : obj(), delta() { }
};
// The ways of the cache. This must be accessed with interrupts
// disabled to prevent interference between a review process and
// capacity evictions.
way ways_[CACHE_SLOTS];
// The list of objects to review in increasing epoch order. This
// must be accessed only by the local core and there must be at
// most one reviewer at a time per core.
referenced::list review_;
// The list of objects whose onzero() method should be called. Call
// onzero() from a separate thread, instead of the timer interrupt,
// to avoid deadlock with the thread preempted by the timer.
referenced::list reap_;
spinlock reap_lock_;
condvar reap_cv_;
// The last global epoch number observed by this core.
uint64_t local_epoch;
// Place obj in the cache if necessary and return its assigned
// way. Interrupts must be disabled.
way *get_way(referenced *obj)
{
// XXX Hash pointer better? This isn't bad: it's very fast and
// shouldn't suffer from small alignments.
std::size_t wayno = (((uintptr_t)obj) | ((uintptr_t)obj / CACHE_SLOTS))
% CACHE_SLOTS;
struct way *way = &ways_[wayno];
// XXX More associativity. Since this is in the critical path
// of every reference operation, perhaps we should do something
// like hash-rehash caching?
if (way->obj != obj) {
// This object is not in the cache
if (way->delta) {
// Need to evict to free up an entry. Since this is a
// capacity eviction, local_epoch may be behind
// global_epoch.
evict(way, false);
kstats::inc(&kstats::refcache_conflict_count);
}
// Take this entry
way->obj = obj;
}
return way;
}
// Evict the object from way, freeing up this slot. way must have
// a non-zero delta and interrupts must be disabled. If
// local_epoch_is_exact, then we assume that local_epoch equals
// global_epoch. Otherwise, local_epoch may be global_epoch or
// global_epoch - 1.
void evict(struct way *way, bool local_epoch_is_exact);
// Flush this core's refcache.
void flush();
// Scan this core's review list. The calling thread must be
// pinned (but interrupts may be enabled). At most one review
// call may be active at a time per core.
void review();
public:
cache() = default;
cache(const cache &o) = delete;
cache(cache &&o) = delete;
cache &operator=(const cache &o) = delete;
cache &operator=(cache &&o) = delete;
// Periodic tick handler. Flushes the refcache and scans review
// lists. The latency of garbage collection is between two and
// three times the delay between calls to tic.
void tick();
// Reap dead objects. This is done in a dedicated thread to
// avoid deadlock with threads preempted by the timer interrupt.
void reaper() __attribute__((noreturn));
};
// Per-CPU reference delta cache. In general this has to be
// accessed with interrupts disabled or by a pinned process to
// prevent migration. Some fields of cache specifically require
// interrupts to be disabled to prevent concurrent access.
// XXX Allocation of this should be NUMA-aware
extern percpu<cache> mycache;
inline void
referenced::inc()
{
// Disable interrupts to prevent review from running on this core
// in the middle of us updating the local reference cache.
scoped_cli cli;
++mycache->get_way(this)->delta;
}
inline void
referenced::dec()
{
scoped_cli cli;
--mycache->get_way(this)->delta;
}
}
<|endoftext|> |
<commit_before>/* This source file is part of the Tomviz project, https://tomviz.org/.
It is released under the 3-Clause BSD License, see "LICENSE". */
#include "ctvlib.h"
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "eigenConversion.h"
namespace py = pybind11;
PYBIND11_PLUGIN(ctvlib)
{
py::module m("ctvlib", "C++ Tomography Reconstruction Scripts");
py::class_<ctvlib>(m, "ctvlib")
.def(pybind11::init<int, int, int>())
.def("Nslice", &ctvlib::get_Nslice, "Get Nslice")
.def("Nray", &ctvlib::get_Nray, "Get Nray")
.def("set_tilt_series", &ctvlib::set_tilt_series,
"Pass the Projections to C++ Object")
.def("initialize_recon_copy", &ctvlib::initialize_recon_copy,
"Initialize Recon Copy")
.def("initialize_tv_recon", &ctvlib::initialize_tv_recon,
"Initialize TV Recon")
.def("update_proj_angles", &ctvlib::update_proj_angles,
"Update Algorithm with New projections")
.def("get_recon", &ctvlib::get_recon, "Return the Reconstruction to Python")
.def("ART", &ctvlib::ART, "ART Reconstruction")
.def("randART", &ctvlib::randART, "Stochastic ART Reconstruction")
.def("SIRT", &ctvlib::SIRT, "SIRT Reconstruction")
.def("lipschits", &ctvlib::lipschits, "Calculate Lipschitz Constant")
.def("row_inner_product", &ctvlib::normalization,
"Calculate the Row Inner Product for Measurement Matrix")
.def("positivity", &ctvlib::positivity, "Remove Negative Elements")
.def("forward_projection", &ctvlib::forward_projection,
"Forward Projection")
.def("load_A", &ctvlib::loadA, "Load Measurement Matrix Created By Python")
.def("copy_recon", &ctvlib::copy_recon, "Copy the reconstruction")
.def("matrix_2norm", &ctvlib::matrix_2norm,
"Calculate L2-Norm of Reconstruction")
.def("data_distance", &ctvlib::data_distance,
"Calculate L2-Norm of Projection (aka Vectors)")
.def("tv_gd", &ctvlib::tv_gd_3D, "3D TV Gradient Descent")
.def("get_projections", &ctvlib::get_projections,
"Return the projection matrix to python")
.def("restart_recon", &ctvlib::restart_recon,
"Set all the Slices Equal to Zero");
return m.ptr();
}
<commit_msg>fix clang formatting<commit_after>/* This source file is part of the Tomviz project, https://tomviz.org/.
It is released under the 3-Clause BSD License, see "LICENSE". */
#include "ctvlib.h"
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "eigenConversion.h"
namespace py = pybind11;
PYBIND11_PLUGIN(ctvlib)
{
py::module m("ctvlib", "C++ Tomography Reconstruction Scripts");
py::class_<ctvlib>(m, "ctvlib")
.def(pybind11::init<int, int, int>())
.def("Nslice", &ctvlib::get_Nslice, "Get Nslice")
.def("Nray", &ctvlib::get_Nray, "Get Nray")
.def("set_tilt_series", &ctvlib::set_tilt_series,
"Pass the Projections to C++ Object")
.def("initialize_recon_copy", &ctvlib::initialize_recon_copy,
"Initialize Recon Copy")
.def("initialize_tv_recon", &ctvlib::initialize_tv_recon,
"Initialize TV Recon")
.def("update_proj_angles", &ctvlib::update_proj_angles,
"Update Algorithm with New projections")
.def("get_recon", &ctvlib::get_recon, "Return the Reconstruction to Python")
.def("ART", &ctvlib::ART, "ART Reconstruction")
.def("randART", &ctvlib::randART, "Stochastic ART Reconstruction")
.def("SIRT", &ctvlib::SIRT, "SIRT Reconstruction")
.def("lipschits", &ctvlib::lipschits, "Calculate Lipschitz Constant")
.def("row_inner_product", &ctvlib::normalization,
"Calculate the Row Inner Product for Measurement Matrix")
.def("positivity", &ctvlib::positivity, "Remove Negative Elements")
.def("forward_projection", &ctvlib::forward_projection,
"Forward Projection")
.def("load_A", &ctvlib::loadA, "Load Measurement Matrix Created By Python")
.def("copy_recon", &ctvlib::copy_recon, "Copy the reconstruction")
.def("matrix_2norm", &ctvlib::matrix_2norm,
"Calculate L2-Norm of Reconstruction")
.def("data_distance", &ctvlib::data_distance,
"Calculate L2-Norm of Projection (aka Vectors)")
.def("tv_gd", &ctvlib::tv_gd_3D, "3D TV Gradient Descent")
.def("get_projections", &ctvlib::get_projections,
"Return the projection matrix to python")
.def("restart_recon", &ctvlib::restart_recon,
"Set all the Slices Equal to Zero");
return m.ptr();
}
<|endoftext|> |
<commit_before>#if defined(_WIN64) || defined(__MINGW32__)
#include "callingconvention.h"
#include "../compiler/callingconvention.h"
#include "../compiler/jit.h"
#include "../core/function.h"
#include "../type/type.h"
#include <iostream>
namespace {
//The maximum number of register for argument passing
const int NUM_NONE_FLOAT_ARGUMENT_REGISTERS = 4;
const int NUM_FLOAT_ARGUMENT_REGISTERS = 4;
//Returns the float argument index for the given argument index
int getFloatArgIndex(const std::vector<const Type*>& parameters, int argIndex) {
return argIndex;
}
//Returns the none float arg for the given argument index
int getNoneFloatArgIndex(const std::vector<const Type*>& parameters, int argIndex) {
return argIndex;
}
//Calculates the number of arguments that are passed via the stack
int numStackArguments(const std::vector<const Type*>& parameters) {
int stackArgs = 0;
int argIndex = 0;
for (auto param : parameters) {
if (TypeSystem::isPrimitiveType(param, PrimitiveTypes::Float)) {
if (getFloatArgIndex(parameters, argIndex) >= NUM_FLOAT_ARGUMENT_REGISTERS) {
stackArgs++;
}
} else {
if (getNoneFloatArgIndex(parameters, argIndex) >= NUM_NONE_FLOAT_ARGUMENT_REGISTERS) {
stackArgs++;
}
}
argIndex++;
}
return stackArgs;
}
//Returns the stack argument index for the given argument
int getStackArgumentIndex(FunctionCompilationData& functionData, int argIndex) {
int stackArgIndex = 0;
auto& parameters = functionData.function.def().parameters();
int index = 0;
for (auto param : parameters) {
if (index == argIndex) {
break;
}
if (TypeSystem::isPrimitiveType(param, PrimitiveTypes::Float)) {
if (getFloatArgIndex(parameters, index) >= NUM_FLOAT_ARGUMENT_REGISTERS) {
stackArgIndex++;
}
} else {
if (getNoneFloatArgIndex(parameters, index) >= NUM_NONE_FLOAT_ARGUMENT_REGISTERS) {
stackArgIndex++;
}
}
index++;
}
return stackArgIndex;
}
//Moves a relative none float argument to the stack. The argument is relative to the type of the register.
void moveNoneFloatArgToStack(FunctionCompilationData& functionData, int argIndex, int relativeArgIndex) {
auto& function = functionData.function;
int argStackOffset = -(1 + argIndex) * Amd64Backend::REG_SIZE;
if (relativeArgIndex >= NUM_NONE_FLOAT_ARGUMENT_REGISTERS) {
int stackArgIndex = getStackArgumentIndex(functionData, argIndex);
Amd64Backend::moveMemoryRegWithOffsetToReg(
function.generatedCode(),
Registers::AX,
Registers::BP,
Amd64Backend::REG_SIZE * (stackArgIndex + 6)); //mov rax, [rbp+REG_SIZE*<arg offset>]
Amd64Backend::moveRegToMemoryRegWithOffset(
function.generatedCode(),
Registers::BP, argStackOffset, Registers::AX); //mov [rbp+<arg offset>], rax
}
if (relativeArgIndex == 3) {
Amd64Backend::moveRegToMemoryRegWithOffset(
function.generatedCode(),
Registers::BP, argStackOffset, RegisterCallArguments::Arg3); //mov [rbp+<arg offset>], rcx
}
if (relativeArgIndex == 2) {
Amd64Backend::moveRegToMemoryRegWithOffset(
function.generatedCode(),
Registers::BP, argStackOffset, RegisterCallArguments::Arg2); //mov [rbp+<arg offset>], rdx
}
if (relativeArgIndex == 1) {
Amd64Backend::moveRegToMemoryRegWithOffset(
function.generatedCode(),
Registers::BP, argStackOffset, RegisterCallArguments::Arg1); //mov [rbp+<arg offset>], rsi
}
if (relativeArgIndex == 0) {
Amd64Backend::moveRegToMemoryRegWithOffset(
function.generatedCode(),
Registers::BP, argStackOffset, RegisterCallArguments::Arg0); //mov [rbp+<arg offset>], rdi
}
}
//Moves a relative float argument to the stack. The argument is relative to the type of the register.
void moveFloatArgToStack(FunctionCompilationData& functionData, int argIndex, int relativeArgIndex) {
auto& function = functionData.function;
int argStackOffset = -(1 + argIndex) * Amd64Backend::REG_SIZE;
if (relativeArgIndex >= NUM_FLOAT_ARGUMENT_REGISTERS) {
int stackArgIndex = getStackArgumentIndex(functionData, argIndex);
Amd64Backend::moveMemoryRegWithOffsetToReg(
function.generatedCode(),
Registers::AX,
Registers::BP,
Amd64Backend::REG_SIZE * (stackArgIndex + 6)); //mov rax, [rbp+REG_SIZE*<arg offset>]
Amd64Backend::moveRegToMemoryRegWithOffset(
function.generatedCode(),
Registers::BP, argStackOffset, Registers::AX); //mov [rbp+<arg offset>], rax
}
if (relativeArgIndex == 3) {
Amd64Backend::moveRegToMemoryRegWithOffset(
function.generatedCode(),
Registers::BP, argStackOffset, FloatRegisterCallArguments::Arg3); //movss [rbp+<arg offset>], xmm3
}
if (relativeArgIndex == 2) {
Amd64Backend::moveRegToMemoryRegWithOffset(
function.generatedCode(),
Registers::BP, argStackOffset, FloatRegisterCallArguments::Arg2); //movss [rbp+<arg offset>], xmm2
}
if (relativeArgIndex == 1) {
Amd64Backend::moveRegToMemoryRegWithOffset(
function.generatedCode(),
Registers::BP, argStackOffset, FloatRegisterCallArguments::Arg1); //movss [rbp+<arg offset>], xmm1
}
if (relativeArgIndex == 0) {
Amd64Backend::moveRegToMemoryRegWithOffset(
function.generatedCode(),
Registers::BP, argStackOffset, FloatRegisterCallArguments::Arg0); //movss [rbp+<arg offset>], xmm0
}
}
}
void CallingConvention::moveArgsToStack(FunctionCompilationData& functionData) const {
auto& function = functionData.function;
auto& parameters = function.def().parameters();
for (int arg = (int)function.def().numParams() - 1; arg >= 0; arg--) {
if (TypeSystem::isPrimitiveType(function.def().parameters()[arg], PrimitiveTypes::Float)) {
moveFloatArgToStack(functionData, arg, getFloatArgIndex(parameters, arg));
} else {
moveNoneFloatArgToStack(functionData, arg, getNoneFloatArgIndex(parameters, arg));
}
}
}
void CallingConvention::callFunctionArgument(FunctionCompilationData& functionData,
int argIndex, const Type* argType, const FunctionDefinition& funcToCall) const {
auto& generatedCode = functionData.function.generatedCode();
auto& operandStack = functionData.operandStack;
if (TypeSystem::isPrimitiveType(argType, PrimitiveTypes::Float)) {
//Arguments of index >= 4 are passed via the stack.
int relativeIndex = getFloatArgIndex(funcToCall.parameters(), argIndex);
if (relativeIndex >= 4) {
//Move from the operand stack to the normal stack
operandStack.popReg(Registers::AX);
Amd64Backend::pushReg(generatedCode, Registers::AX);
}
if (relativeIndex == 3) {
operandStack.popReg(FloatRegisterCallArguments::Arg3);
}
if (relativeIndex == 2) {
operandStack.popReg(FloatRegisterCallArguments::Arg2);
}
if (relativeIndex == 1) {
operandStack.popReg(FloatRegisterCallArguments::Arg1);
}
if (relativeIndex == 0) {
operandStack.popReg(FloatRegisterCallArguments::Arg0);
}
} else {
//Arguments of index >= 4 are passed via the stack
int relativeIndex = getNoneFloatArgIndex(funcToCall.parameters(), argIndex);
if (relativeIndex >= 4) {
//Move from the operand stack to the normal stack
operandStack.popReg(Registers::AX);
Amd64Backend::pushReg(generatedCode, Registers::AX);
}
if (relativeIndex == 3) {
operandStack.popReg(RegisterCallArguments::Arg3);
}
if (relativeIndex == 2) {
operandStack.popReg(RegisterCallArguments::Arg2);
}
if (relativeIndex == 1) {
operandStack.popReg(RegisterCallArguments::Arg1);
}
if (relativeIndex == 0) {
operandStack.popReg(RegisterCallArguments::Arg0);
}
}
}
void CallingConvention::callFunctionArguments(FunctionCompilationData& functionData, const FunctionDefinition& funcToCall) const {
int numArgs = (int)funcToCall.parameters().size();
//Set the function arguments
for (int arg = numArgs - 1; arg >= 0; arg--) {
callFunctionArgument(functionData, arg, funcToCall.parameters().at(arg), funcToCall);
}
}
int CallingConvention::calculateStackAlignment(FunctionCompilationData& functionData, const FunctionDefinition& funcToCall) const {
int numStackArgs = numStackArguments(funcToCall.parameters());
return (numStackArgs % 2) * Amd64Backend::REG_SIZE;
}
int CallingConvention::calculateShadowStackSize() const {
return 4 * Amd64Backend::REG_SIZE;
}
void CallingConvention::makeReturnValue(FunctionCompilationData& functionData) const {
auto& function = functionData.function;
auto& operandStack = functionData.operandStack;
if (!TypeSystem::isPrimitiveType(function.def().returnType(), PrimitiveTypes::Void)) {
//Pop the return value
if (TypeSystem::isPrimitiveType(function.def().returnType(), PrimitiveTypes::Float)) {
operandStack.popReg(FloatRegisters::XMM0);
} else {
operandStack.popReg( Registers::AX);
}
}
}
void CallingConvention::handleReturnValue(FunctionCompilationData& functionData,
const FunctionDefinition& funcToCall) const {
auto& generatedCode = functionData.function.generatedCode();
auto& operandStack = functionData.operandStack;
//If we have passed arguments via the stack, adjust the stack pointer.
int numStackArgs = numStackArguments(funcToCall.parameters());
if (numStackArgs > 0) {
Amd64Backend::addConstantToReg(generatedCode, Registers::SP, numStackArgs * Amd64Backend::REG_SIZE);
}
if (!TypeSystem::isPrimitiveType(funcToCall.returnType(), PrimitiveTypes::Void)) {
if (TypeSystem::isPrimitiveType(funcToCall.returnType(), PrimitiveTypes::Float)) {
operandStack.pushReg(FloatRegisters::XMM0);
} else {
operandStack.pushReg(Registers::AX);
}
}
}
#endif
<commit_msg>Implemented new assembler for calling conventions on Windows.<commit_after>#if defined(_WIN64) || defined(__MINGW32__)
#include "callingconvention.h"
#include "../compiler/callingconvention.h"
#include "../compiler/jit.h"
#include "../core/function.h"
#include "../type/type.h"
#include "../compiler/amd64assembler.h"
#include <iostream>
namespace {
//The maximum number of register for argument passing
const int NUM_NONE_FLOAT_ARGUMENT_REGISTERS = 4;
const int NUM_FLOAT_ARGUMENT_REGISTERS = 4;
const std::vector<IntRegister> INT_CALL_REGISTERS = {
RegisterCallArguments::Arg0,
RegisterCallArguments::Arg1,
RegisterCallArguments::Arg2,
RegisterCallArguments::Arg3
};
const std::vector<FloatRegisters> FLOAT_CALL_REGISTERS = {
FloatRegisterCallArguments::Arg0,
FloatRegisterCallArguments::Arg1,
FloatRegisterCallArguments::Arg2,
FloatRegisterCallArguments::Arg3
};
//Returns the float argument index for the given argument index
int getFloatArgIndex(const std::vector<const Type*>& parameters, int argIndex) {
return argIndex;
}
//Returns the none float arg for the given argument index
int getNoneFloatArgIndex(const std::vector<const Type*>& parameters, int argIndex) {
return argIndex;
}
//Calculates the number of arguments that are passed via the stack
int numStackArguments(const std::vector<const Type*>& parameters) {
int stackArgs = 0;
int argIndex = 0;
for (auto param : parameters) {
if (TypeSystem::isPrimitiveType(param, PrimitiveTypes::Float)) {
if (getFloatArgIndex(parameters, argIndex) >= NUM_FLOAT_ARGUMENT_REGISTERS) {
stackArgs++;
}
} else {
if (getNoneFloatArgIndex(parameters, argIndex) >= NUM_NONE_FLOAT_ARGUMENT_REGISTERS) {
stackArgs++;
}
}
argIndex++;
}
return stackArgs;
}
//Returns the stack argument index for the given argument
int getStackArgumentIndex(FunctionCompilationData& functionData, int argIndex) {
int stackArgIndex = 0;
auto& parameters = functionData.function.def().parameters();
int index = 0;
for (auto param : parameters) {
if (index == argIndex) {
break;
}
if (TypeSystem::isPrimitiveType(param, PrimitiveTypes::Float)) {
if (getFloatArgIndex(parameters, index) >= NUM_FLOAT_ARGUMENT_REGISTERS) {
stackArgIndex++;
}
} else {
if (getNoneFloatArgIndex(parameters, index) >= NUM_NONE_FLOAT_ARGUMENT_REGISTERS) {
stackArgIndex++;
}
}
index++;
}
return stackArgIndex;
}
//Moves a relative none float argument to the stack. The argument is relative to the type of the register.
void moveNoneFloatArgToStack(FunctionCompilationData& functionData, int argIndex, int relativeArgIndex) {
auto& function = functionData.function;
Amd64Assembler assembler(function.generatedCode());
int argStackOffset = -(1 + argIndex) * Amd64Backend::REG_SIZE;
if (relativeArgIndex >= NUM_NONE_FLOAT_ARGUMENT_REGISTERS) {
int stackArgIndex = getStackArgumentIndex(functionData, argIndex);
assembler.move(Registers::AX, { Registers::BP, Amd64Backend::REG_SIZE * (stackArgIndex + 6) }); //mov rax, [rbp+REG_SIZE*<arg offset>]
assembler.move({ Registers::BP, argStackOffset }, Registers::AX); //mov [rbp+<arg offset>], rax
} else {
assembler.move({ Registers::BP, argStackOffset }, INT_CALL_REGISTERS[relativeArgIndex]); //mov [rbp+<arg offset>], <call reg>
}
}
//Moves a relative float argument to the stack. The argument is relative to the type of the register.
void moveFloatArgToStack(FunctionCompilationData& functionData, int argIndex, int relativeArgIndex) {
auto& function = functionData.function;
Amd64Assembler assembler(function.generatedCode());
int argStackOffset = -(1 + argIndex) * Amd64Backend::REG_SIZE;
if (relativeArgIndex >= NUM_FLOAT_ARGUMENT_REGISTERS) {
int stackArgIndex = getStackArgumentIndex(functionData, argIndex);
assembler.move(Registers::AX, { Registers::BP, Amd64Backend::REG_SIZE * (stackArgIndex + 6) }); //mov rax, [rbp+REG_SIZE*<arg offset>]
assembler.move({ Registers::BP, argStackOffset }, Registers::AX); //mov [rbp+<arg offset>], rax
} else {
assembler.move({ Registers::BP, argStackOffset }, FLOAT_CALL_REGISTERS[relativeArgIndex]); //mov [rbp+<arg offset>], <call reg>
}
}
}
void CallingConvention::moveArgsToStack(FunctionCompilationData& functionData) const {
auto& function = functionData.function;
auto& parameters = function.def().parameters();
for (int arg = (int)function.def().numParams() - 1; arg >= 0; arg--) {
if (TypeSystem::isPrimitiveType(function.def().parameters()[arg], PrimitiveTypes::Float)) {
moveFloatArgToStack(functionData, arg, getFloatArgIndex(parameters, arg));
} else {
moveNoneFloatArgToStack(functionData, arg, getNoneFloatArgIndex(parameters, arg));
}
}
}
void CallingConvention::callFunctionArgument(FunctionCompilationData& functionData,
int argIndex, const Type* argType, const FunctionDefinition& funcToCall) const {
auto& generatedCode = functionData.function.generatedCode();
auto& operandStack = functionData.operandStack;
Amd64Assembler assembler(generatedCode);
if (TypeSystem::isPrimitiveType(argType, PrimitiveTypes::Float)) {
//Arguments of index >= 4 are passed via the stack.
int relativeIndex = getFloatArgIndex(funcToCall.parameters(), argIndex);
if (relativeIndex >= 4) {
//Move from the operand stack to the normal stack
operandStack.popReg(Registers::AX);
assembler.push(Registers::AX);
} else {
operandStack.popReg(FLOAT_CALL_REGISTERS[relativeIndex]);
}
} else {
//Arguments of index >= 4 are passed via the stack
int relativeIndex = getNoneFloatArgIndex(funcToCall.parameters(), argIndex);
if (relativeIndex >= 4) {
//Move from the operand stack to the normal stack
operandStack.popReg(Registers::AX);
assembler.push(Registers::AX);
} else {
operandStack.popReg(INT_CALL_REGISTERS[relativeIndex]);
}
}
}
void CallingConvention::callFunctionArguments(FunctionCompilationData& functionData, const FunctionDefinition& funcToCall) const {
int numArgs = (int)funcToCall.parameters().size();
//Set the function arguments
for (int arg = numArgs - 1; arg >= 0; arg--) {
callFunctionArgument(functionData, arg, funcToCall.parameters().at(arg), funcToCall);
}
}
int CallingConvention::calculateStackAlignment(FunctionCompilationData& functionData, const FunctionDefinition& funcToCall) const {
int numStackArgs = numStackArguments(funcToCall.parameters());
return (numStackArgs % 2) * Amd64Backend::REG_SIZE;
}
int CallingConvention::calculateShadowStackSize() const {
return 4 * Amd64Backend::REG_SIZE;
}
void CallingConvention::makeReturnValue(FunctionCompilationData& functionData) const {
auto& function = functionData.function;
auto& operandStack = functionData.operandStack;
if (!TypeSystem::isPrimitiveType(function.def().returnType(), PrimitiveTypes::Void)) {
//Pop the return value
if (TypeSystem::isPrimitiveType(function.def().returnType(), PrimitiveTypes::Float)) {
operandStack.popReg(FloatRegisters::XMM0);
} else {
operandStack.popReg(Registers::AX);
}
}
}
void CallingConvention::handleReturnValue(FunctionCompilationData& functionData,
const FunctionDefinition& funcToCall) const {
auto& generatedCode = functionData.function.generatedCode();
auto& operandStack = functionData.operandStack;
Amd64Assembler assembler(generatedCode);
//If we have passed arguments via the stack, adjust the stack pointer.
int numStackArgs = numStackArguments(funcToCall.parameters());
if (numStackArgs > 0) {
assembler.add(Registers::SP, numStackArgs * Amd64Backend::REG_SIZE);
}
if (!TypeSystem::isPrimitiveType(funcToCall.returnType(), PrimitiveTypes::Void)) {
if (TypeSystem::isPrimitiveType(funcToCall.returnType(), PrimitiveTypes::Float)) {
operandStack.pushReg(FloatRegisters::XMM0);
} else {
operandStack.pushReg(Registers::AX);
}
}
}
#endif
<|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.
// A general interface for filtering and only acting on classes in Chromium C++
// code.
#include "ChromeClassTester.h"
#include <sys/param.h>
using namespace clang;
namespace {
bool starts_with(const std::string& one, const std::string& two) {
return one.substr(0, two.size()) == two;
}
bool ends_with(const std::string& one, const std::string& two) {
if (two.size() > one.size())
return false;
return one.substr(one.size() - two.size(), two.size()) == two;
}
} // namespace
ChromeClassTester::ChromeClassTester(CompilerInstance& instance)
: instance_(instance),
diagnostic_(instance.getDiagnostics()) {
FigureOutSrcRoot();
BuildBannedLists();
}
void ChromeClassTester::FigureOutSrcRoot() {
char c_cwd[MAXPATHLEN];
if (getcwd(c_cwd, MAXPATHLEN) > 0) {
size_t pos = 1;
std::string cwd = c_cwd;
// Add a trailing '/' because the search below requires it.
if (cwd[cwd.size() - 1] != '/')
cwd += '/';
// Search the directory tree downwards until we find a path that contains
// "build/common.gypi" and assume that that is our srcroot.
size_t next_slash = cwd.find('/', pos);
while (next_slash != std::string::npos) {
next_slash++;
std::string candidate = cwd.substr(0, next_slash);
if (ends_with(candidate, "src/")) {
std::string common = candidate + "build/common.gypi";
if (access(common.c_str(), F_OK) != -1) {
src_root_ = candidate;
break;
}
}
pos = next_slash;
next_slash = cwd.find('/', pos);
}
}
if (src_root_.empty()) {
unsigned id = diagnostic().getCustomDiagID(
Diagnostic::Error,
"WARNING: Can't figure out srcroot!\n");
diagnostic().Report(id);
}
}
void ChromeClassTester::BuildBannedLists() {
banned_namespaces_.push_back("std");
banned_namespaces_.push_back("__gnu_cxx");
banned_directories_.push_back("third_party");
banned_directories_.push_back("native_client");
banned_directories_.push_back("breakpad");
banned_directories_.push_back("courgette");
banned_directories_.push_back("ppapi");
banned_directories_.push_back("/usr");
banned_directories_.push_back("testing");
banned_directories_.push_back("googleurl");
banned_directories_.push_back("v8");
banned_directories_.push_back("sdch");
// Don't check autogenerated headers.
banned_directories_.push_back("out");
// You are standing in a mazy of twisty dependencies, all resolved by
// putting everything in the header.
banned_directories_.push_back("chrome/test/automation");
// Used in really low level threading code that probably shouldn't be out of
// lined.
ignored_record_names_.push_back("ThreadLocalBoolean");
// A complicated pickle derived struct that is all packed integers.
ignored_record_names_.push_back("Header");
// Part of the GPU system that uses multiple included header
// weirdness. Never getting this right.
ignored_record_names_.push_back("Validators");
// RAII class that's simple enough (media/base/callback.h).
ignored_record_names_.push_back("AutoTaskRunner");
ignored_record_names_.push_back("AutoCallbackRunner");
// Has a UNIT_TEST only constructor. Isn't *terribly* complex...
ignored_record_names_.push_back("AutocompleteController");
ignored_record_names_.push_back("HistoryURLProvider");
// Because of chrome frame
ignored_record_names_.push_back("ReliabilityTestSuite");
// Used over in the net unittests. A large enough bundle of integers with 1
// non-pod class member. Probably harmless.
ignored_record_names_.push_back("MockTransaction");
// Used heavily in app_unittests and once in views_unittests. Fixing this
// isn't worth the overhead of an additional library.
ignored_record_names_.push_back("TestAnimationDelegate");
// Part of our public interface that nacl and friends use. (Arguably, this
// should mean that this is a higher priority but fixing this looks hard.)
ignored_record_names_.push_back("PluginVersionInfo");
}
ChromeClassTester::~ChromeClassTester() {}
void ChromeClassTester::HandleTagDeclDefinition(TagDecl* tag) {
if (CXXRecordDecl* record = dyn_cast<CXXRecordDecl>(tag)) {
// If this is a POD or a class template or a type dependent on a
// templated class, assume there's no ctor/dtor/virtual method
// optimization that we can do.
if (record->isPOD() ||
record->getDescribedClassTemplate() ||
record->getTemplateSpecializationKind() ||
record->isDependentType())
return;
if (InBannedNamespace(record))
return;
SourceLocation record_location = record->getInnerLocStart();
if (InBannedDirectory(record_location))
return;
// We sadly need to maintain a blacklist of types that violate these
// rules, but do so for good reason or due to limitations of this
// checker (i.e., we don't handle extern templates very well).
std::string base_name = record->getNameAsString();
if (IsIgnoredType(base_name))
return;
// We ignore all classes that end with "Matcher" because they're probably
// GMock artifacts.
if (ends_with(base_name, "Matcher"))
return;
CheckChromeClass(record_location, record);
}
}
void ChromeClassTester::emitWarning(SourceLocation loc, const char* raw_error) {
FullSourceLoc full(loc, instance().getSourceManager());
std::string err;
err = "[chromium-style] ";
err += raw_error;
Diagnostic::Level level =
diagnostic().getWarningsAsErrors() ?
Diagnostic::Error :
Diagnostic::Warning;
unsigned id = diagnostic().getCustomDiagID(level, err);
DiagnosticBuilder B = diagnostic().Report(full, id);
}
bool ChromeClassTester::InTestingNamespace(Decl* record) {
return GetNamespace(record).find("testing") != std::string::npos;
}
bool ChromeClassTester::InBannedNamespace(Decl* record) {
std::string n = GetNamespace(record);
if (n != "") {
return std::find(banned_namespaces_.begin(), banned_namespaces_.end(), n)
!= banned_namespaces_.end();
}
return false;
}
std::string ChromeClassTester::GetNamespace(Decl* record) {
return GetNamespaceImpl(record->getDeclContext(), "");
}
std::string ChromeClassTester::GetNamespaceImpl(const DeclContext* context,
std::string candidate) {
switch (context->getDeclKind()) {
case Decl::TranslationUnit: {
return candidate;
}
case Decl::Namespace: {
const NamespaceDecl* decl = dyn_cast<NamespaceDecl>(context);
std::string name_str;
llvm::raw_string_ostream OS(name_str);
if (decl->isAnonymousNamespace())
OS << "<anonymous namespace>";
else
OS << decl;
return GetNamespaceImpl(context->getParent(),
OS.str());
}
default: {
return GetNamespaceImpl(context->getParent(), candidate);
}
}
}
bool ChromeClassTester::InBannedDirectory(const SourceLocation& loc) {
if (loc.isFileID() && loc.isValid()) {
bool invalid = false;
const char* buffer_name = instance_.getSourceManager().getBufferName(
loc, &invalid);
if (!invalid && buffer_name) {
std::string b(buffer_name);
// Don't complain about these things in implementation files.
if (ends_with(b, ".cc") || ends_with(b, ".cpp") || ends_with(b, ".mm")) {
return true;
}
// Don't complain about autogenerated protobuf files.
if (ends_with(b, ".pb.h")) {
return true;
}
// We need to munge the paths so that they are relative to the repository
// srcroot. We first resolve the symlinktastic relative path and then
// remove our known srcroot from it if needed.
char resolvedPath[MAXPATHLEN];
if (realpath(b.c_str(), resolvedPath)) {
std::string resolved = resolvedPath;
if (starts_with(resolved, src_root_)) {
b = resolved.substr(src_root_.size());
}
}
for (std::vector<std::string>::const_iterator it =
banned_directories_.begin();
it != banned_directories_.end(); ++it) {
if (starts_with(b, *it))
return true;
}
}
}
return false;
}
bool ChromeClassTester::IsIgnoredType(const std::string& base_name) {
for (std::vector<std::string>::const_iterator it =
ignored_record_names_.begin();
it != ignored_record_names_.end(); ++it) {
if (base_name == *it)
return true;
}
return false;
}
<commit_msg>Ignore autogenerated headers in clang on the mac.<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.
// A general interface for filtering and only acting on classes in Chromium C++
// code.
#include "ChromeClassTester.h"
#include <sys/param.h>
using namespace clang;
namespace {
bool starts_with(const std::string& one, const std::string& two) {
return one.substr(0, two.size()) == two;
}
bool ends_with(const std::string& one, const std::string& two) {
if (two.size() > one.size())
return false;
return one.substr(one.size() - two.size(), two.size()) == two;
}
} // namespace
ChromeClassTester::ChromeClassTester(CompilerInstance& instance)
: instance_(instance),
diagnostic_(instance.getDiagnostics()) {
FigureOutSrcRoot();
BuildBannedLists();
}
void ChromeClassTester::FigureOutSrcRoot() {
char c_cwd[MAXPATHLEN];
if (getcwd(c_cwd, MAXPATHLEN) > 0) {
size_t pos = 1;
std::string cwd = c_cwd;
// Add a trailing '/' because the search below requires it.
if (cwd[cwd.size() - 1] != '/')
cwd += '/';
// Search the directory tree downwards until we find a path that contains
// "build/common.gypi" and assume that that is our srcroot.
size_t next_slash = cwd.find('/', pos);
while (next_slash != std::string::npos) {
next_slash++;
std::string candidate = cwd.substr(0, next_slash);
if (ends_with(candidate, "src/")) {
std::string common = candidate + "build/common.gypi";
if (access(common.c_str(), F_OK) != -1) {
src_root_ = candidate;
break;
}
}
pos = next_slash;
next_slash = cwd.find('/', pos);
}
}
if (src_root_.empty()) {
unsigned id = diagnostic().getCustomDiagID(
Diagnostic::Error,
"WARNING: Can't figure out srcroot!\n");
diagnostic().Report(id);
}
}
void ChromeClassTester::BuildBannedLists() {
banned_namespaces_.push_back("std");
banned_namespaces_.push_back("__gnu_cxx");
banned_directories_.push_back("third_party");
banned_directories_.push_back("native_client");
banned_directories_.push_back("breakpad");
banned_directories_.push_back("courgette");
banned_directories_.push_back("ppapi");
banned_directories_.push_back("/usr");
banned_directories_.push_back("testing");
banned_directories_.push_back("googleurl");
banned_directories_.push_back("v8");
banned_directories_.push_back("sdch");
// Don't check autogenerated headers.
banned_directories_.push_back("out");
banned_directories_.push_back("xcodebuild");
// You are standing in a mazy of twisty dependencies, all resolved by
// putting everything in the header.
banned_directories_.push_back("chrome/test/automation");
// Used in really low level threading code that probably shouldn't be out of
// lined.
ignored_record_names_.push_back("ThreadLocalBoolean");
// A complicated pickle derived struct that is all packed integers.
ignored_record_names_.push_back("Header");
// Part of the GPU system that uses multiple included header
// weirdness. Never getting this right.
ignored_record_names_.push_back("Validators");
// RAII class that's simple enough (media/base/callback.h).
ignored_record_names_.push_back("AutoTaskRunner");
ignored_record_names_.push_back("AutoCallbackRunner");
// Has a UNIT_TEST only constructor. Isn't *terribly* complex...
ignored_record_names_.push_back("AutocompleteController");
ignored_record_names_.push_back("HistoryURLProvider");
// Because of chrome frame
ignored_record_names_.push_back("ReliabilityTestSuite");
// Used over in the net unittests. A large enough bundle of integers with 1
// non-pod class member. Probably harmless.
ignored_record_names_.push_back("MockTransaction");
// Used heavily in app_unittests and once in views_unittests. Fixing this
// isn't worth the overhead of an additional library.
ignored_record_names_.push_back("TestAnimationDelegate");
// Part of our public interface that nacl and friends use. (Arguably, this
// should mean that this is a higher priority but fixing this looks hard.)
ignored_record_names_.push_back("PluginVersionInfo");
}
ChromeClassTester::~ChromeClassTester() {}
void ChromeClassTester::HandleTagDeclDefinition(TagDecl* tag) {
if (CXXRecordDecl* record = dyn_cast<CXXRecordDecl>(tag)) {
// If this is a POD or a class template or a type dependent on a
// templated class, assume there's no ctor/dtor/virtual method
// optimization that we can do.
if (record->isPOD() ||
record->getDescribedClassTemplate() ||
record->getTemplateSpecializationKind() ||
record->isDependentType())
return;
if (InBannedNamespace(record))
return;
SourceLocation record_location = record->getInnerLocStart();
if (InBannedDirectory(record_location))
return;
// We sadly need to maintain a blacklist of types that violate these
// rules, but do so for good reason or due to limitations of this
// checker (i.e., we don't handle extern templates very well).
std::string base_name = record->getNameAsString();
if (IsIgnoredType(base_name))
return;
// We ignore all classes that end with "Matcher" because they're probably
// GMock artifacts.
if (ends_with(base_name, "Matcher"))
return;
CheckChromeClass(record_location, record);
}
}
void ChromeClassTester::emitWarning(SourceLocation loc, const char* raw_error) {
FullSourceLoc full(loc, instance().getSourceManager());
std::string err;
err = "[chromium-style] ";
err += raw_error;
Diagnostic::Level level =
diagnostic().getWarningsAsErrors() ?
Diagnostic::Error :
Diagnostic::Warning;
unsigned id = diagnostic().getCustomDiagID(level, err);
DiagnosticBuilder B = diagnostic().Report(full, id);
}
bool ChromeClassTester::InTestingNamespace(Decl* record) {
return GetNamespace(record).find("testing") != std::string::npos;
}
bool ChromeClassTester::InBannedNamespace(Decl* record) {
std::string n = GetNamespace(record);
if (n != "") {
return std::find(banned_namespaces_.begin(), banned_namespaces_.end(), n)
!= banned_namespaces_.end();
}
return false;
}
std::string ChromeClassTester::GetNamespace(Decl* record) {
return GetNamespaceImpl(record->getDeclContext(), "");
}
std::string ChromeClassTester::GetNamespaceImpl(const DeclContext* context,
std::string candidate) {
switch (context->getDeclKind()) {
case Decl::TranslationUnit: {
return candidate;
}
case Decl::Namespace: {
const NamespaceDecl* decl = dyn_cast<NamespaceDecl>(context);
std::string name_str;
llvm::raw_string_ostream OS(name_str);
if (decl->isAnonymousNamespace())
OS << "<anonymous namespace>";
else
OS << decl;
return GetNamespaceImpl(context->getParent(),
OS.str());
}
default: {
return GetNamespaceImpl(context->getParent(), candidate);
}
}
}
bool ChromeClassTester::InBannedDirectory(const SourceLocation& loc) {
if (loc.isFileID() && loc.isValid()) {
bool invalid = false;
const char* buffer_name = instance_.getSourceManager().getBufferName(
loc, &invalid);
if (!invalid && buffer_name) {
std::string b(buffer_name);
// Don't complain about these things in implementation files.
if (ends_with(b, ".cc") || ends_with(b, ".cpp") || ends_with(b, ".mm")) {
return true;
}
// Don't complain about autogenerated protobuf files.
if (ends_with(b, ".pb.h")) {
return true;
}
// We need to munge the paths so that they are relative to the repository
// srcroot. We first resolve the symlinktastic relative path and then
// remove our known srcroot from it if needed.
char resolvedPath[MAXPATHLEN];
if (realpath(b.c_str(), resolvedPath)) {
std::string resolved = resolvedPath;
if (starts_with(resolved, src_root_)) {
b = resolved.substr(src_root_.size());
}
}
for (std::vector<std::string>::const_iterator it =
banned_directories_.begin();
it != banned_directories_.end(); ++it) {
if (starts_with(b, *it))
return true;
}
}
}
return false;
}
bool ChromeClassTester::IsIgnoredType(const std::string& base_name) {
for (std::vector<std::string>::const_iterator it =
ignored_record_names_.begin();
it != ignored_record_names_.end(); ++it) {
if (base_name == *it)
return true;
}
return false;
}
<|endoftext|> |
<commit_before>/**
* @file typedef.hpp
* @brief COSSB Type definitions
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details
*/
#ifndef _COSSB_TYPEDEF_HPP_
#define _COSSB_TYPEDEF_HPP_
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
using namespace boost;
namespace cossb {
namespace process {
typedef boost::shared_ptr<boost::thread> task;
#define task_register(fnptr) boost::thread(boost::bind(fnptr, this))
#define create_task(fnptr) boost::shared_ptr<boost::thread>(new task_register(&fnptr))
#define destroy_task(instance) if(instance){ instance->interrupt(); instance->join(); }
}
namespace types {
enum class status : unsigned int { READY = 0, RUNNING, STOPPED };
enum class returntype : int { EXIST=-1, FAIL=0, SUCCESS=1 };
} /* namespace types */
} /* namespace cossb */
#endif /* _COSSB_TYPEDEF_HPP_ */
<commit_msg>delete status type, it moves to the component interface<commit_after>/**
* @file typedef.hpp
* @brief COSSB Type definitions
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details
*/
#ifndef _COSSB_TYPEDEF_HPP_
#define _COSSB_TYPEDEF_HPP_
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
using namespace boost;
namespace cossb {
namespace process {
typedef boost::shared_ptr<boost::thread> task;
#define task_register(fnptr) boost::thread(boost::bind(fnptr, this))
#define create_task(fnptr) boost::shared_ptr<boost::thread>(new task_register(&fnptr))
#define destroy_task(instance) if(instance){ instance->interrupt(); instance->join(); }
}
namespace types {
enum class returntype : int { EXIST=-1, FAIL=0, SUCCESS=1 };
} /* namespace types */
} /* namespace cossb */
#endif /* _COSSB_TYPEDEF_HPP_ */
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkFEMSolverCrankNicolson.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif
#include "itkFEMSolverCrankNicolson.h"
#include "itkFEMLoadNode.h"
#include "itkFEMLoadElementBase.h"
#include "itkFEMLoadBC.h"
#include "itkFEMLoadBCMFC.h"
namespace itk {
namespace fem {
void SolverCrankNicolson::InitializeForSolution()
{
m_ls->SetSystemOrder(NGFN+NMFC);
m_ls->SetNumberOfVectors(5);
m_ls->SetNumberOfSolutions(2);
m_ls->SetNumberOfMatrices(2);
m_ls->InitializeMatrix(SumMatrixIndex);
m_ls->InitializeMatrix(DifferenceMatrixIndex);
m_ls->InitializeVector(ForceTIndex);
m_ls->InitializeVector(ForceTMinus1Index);
m_ls->InitializeVector(SolutionTMinus1Index);
m_ls->InitializeVector(DiffMatrixBySolutionTMinus1Index);
m_ls->InitializeSolution(SolutionTIndex);
m_ls->InitializeSolution(TotalSolutionIndex);
}
/*
* Assemble the master stiffness matrix (also apply the MFCs to K)
*/
void SolverCrankNicolson::AssembleKandM()
{
// if no DOFs exist in a system, we have nothing to do
if (NGFN<=0) return;
NMFC=0; // number of MFC in a system
// temporary storage for pointers to LoadBCMFC objects
typedef std::vector<LoadBCMFC::Pointer> MFCArray;
MFCArray mfcLoads;
/*
* Before we can start the assembly procedure, we need to know,
* how many boundary conditions (MFCs) there are in a system.
*/
mfcLoads.clear();
// search for MFC's in Loads array, because they affect the master stiffness matrix
for(LoadArray::iterator l=load.begin(); l!=load.end(); l++) {
if ( LoadBCMFC::Pointer l1=dynamic_cast<LoadBCMFC*>( &(*(*l))) ) {
// store the index of an LoadBCMFC object for later
l1->Index=NMFC;
// store the pointer to a LoadBCMFC object for later
mfcLoads.push_back(l1);
// increase the number of MFC
NMFC++;
}
}
/*
* Now we can assemble the master stiffness matrix
* from element stiffness matrices
*/
InitializeForSolution();
std::cout << "Begin Assembly." << std::endl;
/*
* Step over all elements
*/
for(ElementArray::iterator e=el.begin(); e!=el.end(); e++)
{
vnl_matrix<Float> Ke;
(*e)->GetStiffnessMatrix(Ke); /*Copy the element stiffness matrix for faster access. */
vnl_matrix<Float> Me;
(*e)->GetMassMatrix(Me); /*Copy the element mass matrix for faster access. */
int Ne=(*e)->GetNumberOfDegreesOfFreedom(); /*... same for element DOF */
Me=Me*m_rho;
/* step over all rows in in element matrix */
for(int j=0; j<Ne; j++)
{
/* step over all columns in in element matrix */
for(int k=0; k<Ne; k++)
{
/* error checking. all GFN should be =>0 and <NGFN */
if ( (*e)->GetDegreeOfFreedom(j) >= NGFN ||
(*e)->GetDegreeOfFreedom(k) >= NGFN )
{
throw FEMExceptionSolution(__FILE__,__LINE__,"SolverCrankNicolson::AssembleK()","Illegal GFN!");
}
/* Here we finaly update the corresponding element
* in the master stiffness matrix. We first check if
* element in Ke is zero, to prevent zeros from being
* allocated in sparse matrix.
*/
if ( Ke(j,k)!=Float(0.0) || Me(j,k) != Float(0.0) )
{
// left hand side matrix
Float lhsval=(Me(j,k) + m_alpha*m_deltaT*Ke(j,k));
m_ls->AddMatrixValue( (*e)->GetDegreeOfFreedom(j) ,
(*e)->GetDegreeOfFreedom(k),
lhsval, SumMatrixIndex );
// right hand side matrix
Float rhsval=(Me(j,k) - (1.-m_alpha)*m_deltaT*Ke(j,k));
m_ls->AddMatrixValue( (*e)->GetDegreeOfFreedom(j) ,
(*e)->GetDegreeOfFreedom(k),
rhsval, DifferenceMatrixIndex );
// if (k == 0 && j == 0) std::cout << " ke " << Ke(j,k) << " me " << Me(j,k) << std::endl;
}
}
}
}
/* step over all types of BCs */
this->ApplyBC(); // BUG -- are BCs applied appropriately to the problem?
std::cout << "Done Assembling." << std::endl;
}
/*
* Assemble the master force vector
*/
void SolverCrankNicolson::AssembleFforTimeStep(int dim) {
/* if no DOFs exist in a system, we have nothing to do */
if (NGFN<=0) return;
AssembleF(dim); // assuming assemblef uses index 0 in vector!
typedef std::map<Element::DegreeOfFreedomIDType,Float> BCTermType;
BCTermType bcterm;
/* Step over all Loads */
for(LoadArray::iterator l=load.begin(); l!=load.end(); l++)
{
Load::Pointer l0=*l;
if ( LoadBC::Pointer l1=dynamic_cast<LoadBC*>(&*l0) )
{
bcterm[ l1->m_element->GetDegreeOfFreedom(l1->m_dof) ]=l1->m_value[dim];
}
} // end for LoadArray::iterator l
// Now set the solution t_minus1 vector to fit the BCs
for( BCTermType::iterator q=bcterm.begin(); q!=bcterm.end(); q++)
{
m_ls->SetVectorValue(q->first,0.0,SolutionTMinus1Index); //FIXME?
}
m_ls->MultiplyMatrixVector(DiffMatrixBySolutionTMinus1Index,
DifferenceMatrixIndex,SolutionTMinus1Index);
for (unsigned int index=0; index<NGFN; index++) RecomputeForceVector(index);
// Now set the solution and force vector to fit the BCs
for( BCTermType::iterator q=bcterm.begin(); q!=bcterm.end(); q++)
{
m_ls->SetVectorValue(q->first,q->second,ForceTIndex);
}
}
void SolverCrankNicolson::RecomputeForceVector(unsigned int index)
{//
Float ft = m_ls->GetVectorValue(index,ForceTIndex);
Float ftm1 = m_ls->GetVectorValue(index,ForceTMinus1Index);
Float utm1 = m_ls->GetVectorValue(index,DiffMatrixBySolutionTMinus1Index);
m_ls->SetVectorValue(index , m_deltaT*(m_alpha*ft+(1.-m_alpha)*ftm1)+utm1 , ForceTIndex);
m_ls->SetVectorValue(index ,ft,ForceTMinus1Index); // now set t minus one force vector correctly
}
/*
* Solve for the displacement vector u
*/
void SolverCrankNicolson::Solve()
{
std::cout << " begin solve " << std::endl;
/* FIXME - must verify that this is correct use of wrapper */
/* FIXME Initialize the solution vector */
m_ls->InitializeSolution(SolutionTIndex);
m_ls->Solve();
// call this externally AddToDisplacements();
}
/*
* Copy solution vector u to the corresponding nodal values, which are
* stored in node objects). This is standard post processing of the solution.
*/
void SolverCrankNicolson::AddToDisplacements(Float optimum)
{
/*
* Copy the resulting displacements from
* solution vector back to node objects.
*/
Float mins=0.0, maxs=0.0;
Float mins2=0.0, maxs2=0.0;
for(unsigned int i=0;i<NGFN;i++)
{
Float CurrentSolution=optimum*m_ls->GetSolutionValue(i,SolutionTIndex);
if (CurrentSolution < mins2 ) mins2=CurrentSolution;
else if (CurrentSolution > maxs2 ) maxs2=CurrentSolution;
// note: set rather than add - i.e. last solution of system not total solution
m_ls->SetVectorValue(i,CurrentSolution,SolutionTMinus1Index);
m_ls->AddSolutionValue(i,CurrentSolution,TotalSolutionIndex);
// m_ls->SetVectorValue(i,m_ls->GetSolutionValue(i,TotalSolutionIndex),SolutionTMinus1Index);
CurrentSolution=m_ls->GetSolutionValue(i,TotalSolutionIndex);
if (CurrentSolution < mins ) mins=CurrentSolution;
else if (CurrentSolution > maxs ) maxs=CurrentSolution;
}
std::cout << " min cur solution val " << mins2 << std::endl;
std::cout << " max cur solution val " << maxs2 << std::endl;
std::cout << " min tot solution val " << mins << std::endl;
std::cout << " max tot solution val " << maxs << std::endl;
}
/*
* Copy solution vector u to the corresponding nodal values, which are
* stored in node objects). This is standard post processing of the solution.
*/
void SolverCrankNicolson::AverageLastTwoDisplacements(Float t)
{
Float maxs=0.0;
for(unsigned int i=0;i<NGFN;i++)
{
Float temp=m_ls->GetSolutionValue(i,SolutionTIndex);
Float temp2=m_ls->GetVectorValue(i,SolutionTMinus1Index);
Float newsol=t*(temp)+(1.-t)*temp2;
m_ls->SetVectorValue(i,newsol,SolutionTMinus1Index);
m_ls->SetSolutionValue(i,newsol,SolutionTIndex);
if ( newsol > maxs ) maxs=newsol;
}
std::cout << " max cur solution val " << maxs << std::endl;
}
void SolverCrankNicolson::ZeroVector(int which)
{
for(unsigned int i=0;i<NGFN;i++)
{
m_ls->SetVectorValue(i,0.0,which);
}
}
void SolverCrankNicolson::PrintDisplacements()
{
std::cout << " printing current displacements " << std::endl;
for(unsigned int i=0;i<NGFN;i++)
{
std::cout << m_ls->GetVectorValue(i,SolutionTMinus1Index) << std::endl;
}
}
void SolverCrankNicolson::PrintForce()
{
std::cout << " printing current forces " << std::endl;
for(unsigned int i=0;i<NGFN;i++)
{
std::cout << m_ls->GetVectorValue(i,ForceTIndex) << std::endl;
}
}
}} // end namespace itk::fem
<commit_msg>no change<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkFEMSolverCrankNicolson.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif
#include "itkFEMSolverCrankNicolson.h"
#include "itkFEMLoadNode.h"
#include "itkFEMLoadElementBase.h"
#include "itkFEMLoadBC.h"
#include "itkFEMLoadBCMFC.h"
namespace itk {
namespace fem {
void SolverCrankNicolson::InitializeForSolution()
{
m_ls->SetSystemOrder(NGFN+NMFC);
m_ls->SetNumberOfVectors(5);
m_ls->SetNumberOfSolutions(2);
m_ls->SetNumberOfMatrices(2);
m_ls->InitializeMatrix(SumMatrixIndex);
m_ls->InitializeMatrix(DifferenceMatrixIndex);
m_ls->InitializeVector(ForceTIndex);
m_ls->InitializeVector(ForceTMinus1Index);
m_ls->InitializeVector(SolutionTMinus1Index);
m_ls->InitializeVector(DiffMatrixBySolutionTMinus1Index);
m_ls->InitializeSolution(SolutionTIndex);
m_ls->InitializeSolution(TotalSolutionIndex);
}
/*
* Assemble the master stiffness matrix (also apply the MFCs to K)
*/
void SolverCrankNicolson::AssembleKandM()
{
// if no DOFs exist in a system, we have nothing to do
if (NGFN<=0) return;
NMFC=0; // number of MFC in a system
// temporary storage for pointers to LoadBCMFC objects
typedef std::vector<LoadBCMFC::Pointer> MFCArray;
MFCArray mfcLoads;
/*
* Before we can start the assembly procedure, we need to know,
* how many boundary conditions (MFCs) there are in a system.
*/
mfcLoads.clear();
// search for MFC's in Loads array, because they affect the master stiffness matrix
for(LoadArray::iterator l=load.begin(); l!=load.end(); l++) {
if ( LoadBCMFC::Pointer l1=dynamic_cast<LoadBCMFC*>( &(*(*l))) ) {
// store the index of an LoadBCMFC object for later
l1->Index=NMFC;
// store the pointer to a LoadBCMFC object for later
mfcLoads.push_back(l1);
// increase the number of MFC
NMFC++;
}
}
/*
* Now we can assemble the master stiffness matrix
* from element stiffness matrices
*/
InitializeForSolution();
std::cout << "Begin Assembly." << std::endl;
/*
* Step over all elements
*/
for(ElementArray::iterator e=el.begin(); e!=el.end(); e++)
{
vnl_matrix<Float> Ke;
(*e)->GetStiffnessMatrix(Ke); /*Copy the element stiffness matrix for faster access. */
vnl_matrix<Float> Me;
(*e)->GetMassMatrix(Me); /*Copy the element mass matrix for faster access. */
int Ne=(*e)->GetNumberOfDegreesOfFreedom(); /*... same for element DOF */
Me=Me*m_rho;
/* step over all rows in in element matrix */
for(int j=0; j<Ne; j++)
{
/* step over all columns in in element matrix */
for(int k=0; k<Ne; k++)
{
/* error checking. all GFN should be =>0 and <NGFN */
if ( (*e)->GetDegreeOfFreedom(j) >= NGFN ||
(*e)->GetDegreeOfFreedom(k) >= NGFN )
{
throw FEMExceptionSolution(__FILE__,__LINE__,"SolverCrankNicolson::AssembleK()","Illegal GFN!");
}
/* Here we finaly update the corresponding element
* in the master stiffness matrix. We first check if
* element in Ke is zero, to prevent zeros from being
* allocated in sparse matrix.
*/
if ( Ke(j,k)!=Float(0.0) || Me(j,k) != Float(0.0) )
{
// left hand side matrix
Float lhsval=(Me(j,k) + m_alpha*m_deltaT*Ke(j,k));
m_ls->AddMatrixValue( (*e)->GetDegreeOfFreedom(j) ,
(*e)->GetDegreeOfFreedom(k),
lhsval, SumMatrixIndex );
// right hand side matrix
Float rhsval=(Me(j,k) - (1.-m_alpha)*m_deltaT*Ke(j,k));
m_ls->AddMatrixValue( (*e)->GetDegreeOfFreedom(j) ,
(*e)->GetDegreeOfFreedom(k),
rhsval, DifferenceMatrixIndex );
//if (k == 0 && j == 0) std::cout << " ke " << Ke(j,k) << " me " << Me(j,k) << std::endl;
}
}
}
}
/* step over all types of BCs */
this->ApplyBC(); // BUG -- are BCs applied appropriately to the problem?
std::cout << "Done Assembling." << std::endl;
}
/*
* Assemble the master force vector
*/
void SolverCrankNicolson::AssembleFforTimeStep(int dim) {
/* if no DOFs exist in a system, we have nothing to do */
if (NGFN<=0) return;
AssembleF(dim); // assuming assemblef uses index 0 in vector!
typedef std::map<Element::DegreeOfFreedomIDType,Float> BCTermType;
BCTermType bcterm;
/* Step over all Loads */
for(LoadArray::iterator l=load.begin(); l!=load.end(); l++)
{
Load::Pointer l0=*l;
if ( LoadBC::Pointer l1=dynamic_cast<LoadBC*>(&*l0) )
{
bcterm[ l1->m_element->GetDegreeOfFreedom(l1->m_dof) ]=l1->m_value[dim];
}
} // end for LoadArray::iterator l
// Now set the solution t_minus1 vector to fit the BCs
for( BCTermType::iterator q=bcterm.begin(); q!=bcterm.end(); q++)
{
m_ls->SetVectorValue(q->first,0.0,SolutionTMinus1Index); //FIXME?
}
m_ls->MultiplyMatrixVector(DiffMatrixBySolutionTMinus1Index,
DifferenceMatrixIndex,SolutionTMinus1Index);
for (unsigned int index=0; index<NGFN; index++) RecomputeForceVector(index);
// Now set the solution and force vector to fit the BCs
for( BCTermType::iterator q=bcterm.begin(); q!=bcterm.end(); q++)
{
m_ls->SetVectorValue(q->first,q->second,ForceTIndex);
}
}
void SolverCrankNicolson::RecomputeForceVector(unsigned int index)
{//
Float ft = m_ls->GetVectorValue(index,ForceTIndex);
Float ftm1 = m_ls->GetVectorValue(index,ForceTMinus1Index);
Float utm1 = m_ls->GetVectorValue(index,DiffMatrixBySolutionTMinus1Index);
m_ls->SetVectorValue(index , m_deltaT*(m_alpha*ft+(1.-m_alpha)*ftm1)+utm1 , ForceTIndex);
m_ls->SetVectorValue(index ,ft,ForceTMinus1Index); // now set t minus one force vector correctly
}
/*
* Solve for the displacement vector u
*/
void SolverCrankNicolson::Solve()
{
std::cout << " begin solve " << std::endl;
/* FIXME - must verify that this is correct use of wrapper */
/* FIXME Initialize the solution vector */
m_ls->InitializeSolution(SolutionTIndex);
m_ls->Solve();
// call this externally AddToDisplacements();
}
/*
* Copy solution vector u to the corresponding nodal values, which are
* stored in node objects). This is standard post processing of the solution.
*/
void SolverCrankNicolson::AddToDisplacements(Float optimum)
{
/*
* Copy the resulting displacements from
* solution vector back to node objects.
*/
Float mins=0.0, maxs=0.0;
Float mins2=0.0, maxs2=0.0;
for(unsigned int i=0;i<NGFN;i++)
{
Float CurrentSolution=optimum*m_ls->GetSolutionValue(i,SolutionTIndex);
if (CurrentSolution < mins2 ) mins2=CurrentSolution;
else if (CurrentSolution > maxs2 ) maxs2=CurrentSolution;
// note: set rather than add - i.e. last solution of system not total solution
m_ls->SetVectorValue(i,CurrentSolution,SolutionTMinus1Index);
m_ls->AddSolutionValue(i,CurrentSolution,TotalSolutionIndex);
// m_ls->SetVectorValue(i,m_ls->GetSolutionValue(i,TotalSolutionIndex),SolutionTMinus1Index);
CurrentSolution=m_ls->GetSolutionValue(i,TotalSolutionIndex);
if (CurrentSolution < mins ) mins=CurrentSolution;
else if (CurrentSolution > maxs ) maxs=CurrentSolution;
}
std::cout << " min cur solution val " << mins2 << std::endl;
std::cout << " max cur solution val " << maxs2 << std::endl;
std::cout << " min tot solution val " << mins << std::endl;
std::cout << " max tot solution val " << maxs << std::endl;
}
/*
* Copy solution vector u to the corresponding nodal values, which are
* stored in node objects). This is standard post processing of the solution.
*/
void SolverCrankNicolson::AverageLastTwoDisplacements(Float t)
{
Float maxs=0.0;
for(unsigned int i=0;i<NGFN;i++)
{
Float temp=m_ls->GetSolutionValue(i,SolutionTIndex);
Float temp2=m_ls->GetVectorValue(i,SolutionTMinus1Index);
Float newsol=t*(temp)+(1.-t)*temp2;
m_ls->SetVectorValue(i,newsol,SolutionTMinus1Index);
m_ls->SetSolutionValue(i,newsol,SolutionTIndex);
if ( newsol > maxs ) maxs=newsol;
}
std::cout << " max cur solution val " << maxs << std::endl;
}
void SolverCrankNicolson::ZeroVector(int which)
{
for(unsigned int i=0;i<NGFN;i++)
{
m_ls->SetVectorValue(i,0.0,which);
}
}
void SolverCrankNicolson::PrintDisplacements()
{
std::cout << " printing current displacements " << std::endl;
for(unsigned int i=0;i<NGFN;i++)
{
std::cout << m_ls->GetVectorValue(i,SolutionTMinus1Index) << std::endl;
}
}
void SolverCrankNicolson::PrintForce()
{
std::cout << " printing current forces " << std::endl;
for(unsigned int i=0;i<NGFN;i++)
{
std::cout << m_ls->GetVectorValue(i,ForceTIndex) << std::endl;
}
}
}} // end namespace itk::fem
<|endoftext|> |
<commit_before><commit_msg>cppcheck: variableScope<commit_after><|endoftext|> |
<commit_before>/**
* @file Cosa/IOBuffer.hh
* @version 1.0
*
* @section License
* Copyright (C) 2013, Mikael Patel
*
* 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, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*
* This file is part of the Arduino Che Cosa project.
*/
#ifndef __COSA_IOBUFFER_HH__
#define __COSA_IOBUFFER_HH__
#include "Cosa/Types.h"
#include "Cosa/IOStream.hh"
#include "Cosa/Power.hh"
/**
* Circular buffer template class for IOStreams. Size must be
* Power(2). May be used as a string buffer device, or to connect
* different IOStreams. See UART.hh for an example. Buffer size should
* be power of 2.
* @param[in] size number of bytes in buffer.
*/
template <uint8_t size>
class IOBuffer : public IOStream::Device {
private:
volatile uint8_t m_head;
volatile uint8_t m_tail;
char m_buffer[size];
public:
/**
* Allocate buffer object for iostream operations.
*/
IOBuffer() :
IOStream::Device(),
m_head(0),
m_tail(0)
{
}
/**
* Return true(1) if the buffer is empty, otherwise false(0).
* @return bool
*/
bool is_empty()
{
return (m_head == m_tail);
}
/**
* Return true(1) if the buffer is full, otherwise false(0).
* @return bool
*/
bool is_full()
{
return (((m_head + 1) & (size - 1)) == m_tail);
}
/**
* @override
* Number of bytes available in buffer.
* @return bytes.
*/
virtual int available()
{
return (((size - 1) + m_head - m_tail) % (size - 1));
}
/**
* @override
* Write character to buffer.
* @param[in] c character to write.
* @return character written or EOF(-1).
*/
virtual int putchar(char c);
/**
* @override
* Peek at the next character from buffer.
* @return character or EOF(-1).
*/
virtual int peekchar();
/**
* @override
* Read character from buffer.
* @return character or EOF(-1).
*/
virtual int getchar();
/**
* @override
* Wait for the buffer to become empty.
* @param[in] mode sleep mode on flush wait.
* @return zero(0) or negative error code.
*/
virtual int flush(uint8_t mode = SLEEP_MODE_IDLE);
};
template <uint8_t size>
int
IOBuffer<size>::putchar(char c)
{
uint8_t next = (m_head + 1) & (size - 1);
if (next == m_tail) return (-1);
m_buffer[next] = c;
m_head = next;
return (c & 0xff);
}
template <uint8_t size>
int
IOBuffer<size>::peekchar()
{
if (m_head == m_tail) return (-1);
uint8_t next = (m_tail + 1) & (size - 1);
return (m_buffer[next]);
}
template <uint8_t size>
int
IOBuffer<size>::getchar()
{
if (m_head == m_tail) return (-1);
uint8_t next = (m_tail + 1) & (size - 1);
m_tail = next;
return (m_buffer[next]);
}
template <uint8_t size>
int
IOBuffer<size>::flush(uint8_t mode)
{
while (m_head != m_tail) Power::sleep(mode);
return (0);
}
#endif
<commit_msg>Fixing documentation.<commit_after>/**
* @file Cosa/IOBuffer.hh
* @version 1.0
*
* @section License
* Copyright (C) 2013, Mikael Patel
*
* 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, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*
* This file is part of the Arduino Che Cosa project.
*/
#ifndef __COSA_IOBUFFER_HH__
#define __COSA_IOBUFFER_HH__
#include "Cosa/Types.h"
#include "Cosa/IOStream.hh"
#include "Cosa/Power.hh"
/**
* Circular buffer template class for IOStreams. Size must be
* Power(2). May be used as a string buffer device, or to connect
* different IOStreams. See UART.hh for an example. Buffer size should
* be power of 2 and max 256.
* @param[in] size number of bytes in buffer.
*/
template <uint8_t size>
class IOBuffer : public IOStream::Device {
private:
volatile uint8_t m_head;
volatile uint8_t m_tail;
char m_buffer[size];
public:
/**
* Allocate buffer object for iostream operations.
*/
IOBuffer() :
IOStream::Device(),
m_head(0),
m_tail(0)
{
}
/**
* Return true(1) if the buffer is empty, otherwise false(0).
* @return bool
*/
bool is_empty()
{
return (m_head == m_tail);
}
/**
* Return true(1) if the buffer is full, otherwise false(0).
* @return bool
*/
bool is_full()
{
return (((m_head + 1) & (size - 1)) == m_tail);
}
/**
* @override
* Number of bytes available in buffer.
* @return bytes.
*/
virtual int available()
{
return (((size - 1) + m_head - m_tail) % (size - 1));
}
/**
* @override
* Write character to buffer.
* @param[in] c character to write.
* @return character written or EOF(-1).
*/
virtual int putchar(char c);
/**
* @override
* Peek at the next character from buffer.
* @return character or EOF(-1).
*/
virtual int peekchar();
/**
* @override
* Read character from buffer.
* @return character or EOF(-1).
*/
virtual int getchar();
/**
* @override
* Wait for the buffer to become empty.
* @param[in] mode sleep mode on flush wait.
* @return zero(0) or negative error code.
*/
virtual int flush(uint8_t mode = SLEEP_MODE_IDLE);
};
template <uint8_t size>
int
IOBuffer<size>::putchar(char c)
{
uint8_t next = (m_head + 1) & (size - 1);
if (next == m_tail) return (-1);
m_buffer[next] = c;
m_head = next;
return (c & 0xff);
}
template <uint8_t size>
int
IOBuffer<size>::peekchar()
{
if (m_head == m_tail) return (-1);
uint8_t next = (m_tail + 1) & (size - 1);
return (m_buffer[next]);
}
template <uint8_t size>
int
IOBuffer<size>::getchar()
{
if (m_head == m_tail) return (-1);
uint8_t next = (m_tail + 1) & (size - 1);
m_tail = next;
return (m_buffer[next]);
}
template <uint8_t size>
int
IOBuffer<size>::flush(uint8_t mode)
{
while (m_head != m_tail) Power::sleep(mode);
return (0);
}
#endif
<|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 "quic/tools/quic_memory_cache_backend.h"
#include <vector>
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "quic/platform/api/quic_test.h"
#include "quic/tools/quic_backend_response.h"
#include "common/platform/api/quiche_file_utils.h"
namespace quic {
namespace test {
namespace {
using Response = QuicBackendResponse;
using ServerPushInfo = QuicBackendResponse::ServerPushInfo;
} // namespace
class QuicMemoryCacheBackendTest : public QuicTest {
protected:
void CreateRequest(std::string host, std::string path,
spdy::Http2HeaderBlock* headers) {
(*headers)[":method"] = "GET";
(*headers)[":path"] = path;
(*headers)[":authority"] = host;
(*headers)[":scheme"] = "https";
}
std::string CacheDirectory() { return QuicGetTestMemoryCachePath(); }
QuicMemoryCacheBackend cache_;
};
TEST_F(QuicMemoryCacheBackendTest, GetResponseNoMatch) {
const Response* response =
cache_.GetResponse("mail.google.com", "/index.html");
ASSERT_FALSE(response);
}
TEST_F(QuicMemoryCacheBackendTest, AddSimpleResponseGetResponse) {
std::string response_body("hello response");
cache_.AddSimpleResponse("www.google.com", "/", 200, response_body);
spdy::Http2HeaderBlock request_headers;
CreateRequest("www.google.com", "/", &request_headers);
const Response* response = cache_.GetResponse("www.google.com", "/");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("200", response->headers().find(":status")->second);
EXPECT_EQ(response_body.size(), response->body().length());
}
TEST_F(QuicMemoryCacheBackendTest, AddResponse) {
const std::string kRequestHost = "www.foo.com";
const std::string kRequestPath = "/";
const std::string kResponseBody("hello response");
spdy::Http2HeaderBlock response_headers;
response_headers[":status"] = "200";
response_headers["content-length"] = absl::StrCat(kResponseBody.size());
spdy::Http2HeaderBlock response_trailers;
response_trailers["key-1"] = "value-1";
response_trailers["key-2"] = "value-2";
response_trailers["key-3"] = "value-3";
cache_.AddResponse(kRequestHost, "/", response_headers.Clone(), kResponseBody,
response_trailers.Clone());
const Response* response = cache_.GetResponse(kRequestHost, kRequestPath);
EXPECT_EQ(response->headers(), response_headers);
EXPECT_EQ(response->body(), kResponseBody);
EXPECT_EQ(response->trailers(), response_trailers);
}
TEST_F(QuicMemoryCacheBackendTest, ReadsCacheDir) {
cache_.InitializeBackend(CacheDirectory());
const Response* response =
cache_.GetResponse("test.example.com", "/index.html");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("200", response->headers().find(":status")->second);
// Connection headers are not valid in HTTP/2.
EXPECT_FALSE(response->headers().contains("connection"));
EXPECT_LT(0U, response->body().length());
}
TEST_F(QuicMemoryCacheBackendTest, ReadsCacheDirWithServerPushResource) {
cache_.InitializeBackend(CacheDirectory() + "_with_push");
std::list<ServerPushInfo> resources =
cache_.GetServerPushResources("test.example.com/");
ASSERT_EQ(1UL, resources.size());
}
TEST_F(QuicMemoryCacheBackendTest, ReadsCacheDirWithServerPushResources) {
cache_.InitializeBackend(CacheDirectory() + "_with_push");
std::list<ServerPushInfo> resources =
cache_.GetServerPushResources("test.example.com/index2.html");
ASSERT_EQ(2UL, resources.size());
}
TEST_F(QuicMemoryCacheBackendTest, UsesOriginalUrl) {
cache_.InitializeBackend(CacheDirectory());
const Response* response =
cache_.GetResponse("test.example.com", "/site_map.html");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("200", response->headers().find(":status")->second);
// Connection headers are not valid in HTTP/2.
EXPECT_FALSE(response->headers().contains("connection"));
EXPECT_LT(0U, response->body().length());
}
TEST_F(QuicMemoryCacheBackendTest, UsesOriginalUrlOnly) {
// Tests that if the URL cannot be inferred correctly from the path
// because the directory does not include the hostname, that the
// X-Original-Url header's value will be used.
std::string dir;
std::string path = "map.html";
std::vector<std::string> files;
ASSERT_TRUE(quiche::EnumerateDirectoryRecursively(CacheDirectory(), files));
for (const std::string& file : files) {
if (absl::EndsWithIgnoreCase(file, "map.html")) {
dir = file;
dir.erase(dir.length() - path.length() - 1);
break;
}
}
ASSERT_NE("", dir);
cache_.InitializeBackend(dir);
const Response* response =
cache_.GetResponse("test.example.com", "/site_map.html");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("200", response->headers().find(":status")->second);
// Connection headers are not valid in HTTP/2.
EXPECT_FALSE(response->headers().contains("connection"));
EXPECT_LT(0U, response->body().length());
}
TEST_F(QuicMemoryCacheBackendTest, DefaultResponse) {
// Verify GetResponse returns nullptr when no default is set.
const Response* response = cache_.GetResponse("www.google.com", "/");
ASSERT_FALSE(response);
// Add a default response.
spdy::Http2HeaderBlock response_headers;
response_headers[":status"] = "200";
response_headers["content-length"] = "0";
Response* default_response = new Response;
default_response->set_headers(std::move(response_headers));
cache_.AddDefaultResponse(default_response);
// Now we should get the default response for the original request.
response = cache_.GetResponse("www.google.com", "/");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("200", response->headers().find(":status")->second);
// Now add a set response for / and make sure it is returned
cache_.AddSimpleResponse("www.google.com", "/", 302, "");
response = cache_.GetResponse("www.google.com", "/");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("302", response->headers().find(":status")->second);
// We should get the default response for other requests.
response = cache_.GetResponse("www.google.com", "/asd");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("200", response->headers().find(":status")->second);
}
TEST_F(QuicMemoryCacheBackendTest, AddSimpleResponseWithServerPushResources) {
std::string request_host = "www.foo.com";
std::string response_body("hello response");
const size_t kNumResources = 5;
int NumResources = 5;
std::list<ServerPushInfo> push_resources;
std::string scheme = "http";
for (int i = 0; i < NumResources; ++i) {
std::string path = absl::StrCat("/server_push_src", i);
std::string url = scheme + "://" + request_host + path;
QuicUrl resource_url(url);
std::string body =
absl::StrCat("This is server push response body for ", path);
spdy::Http2HeaderBlock response_headers;
response_headers[":status"] = "200";
response_headers["content-length"] = absl::StrCat(body.size());
push_resources.push_back(
ServerPushInfo(resource_url, response_headers.Clone(), i, body));
}
cache_.AddSimpleResponseWithServerPushResources(
request_host, "/", 200, response_body, push_resources);
std::string request_url = request_host + "/";
std::list<ServerPushInfo> resources =
cache_.GetServerPushResources(request_url);
ASSERT_EQ(kNumResources, resources.size());
for (const auto& push_resource : push_resources) {
ServerPushInfo resource = resources.front();
EXPECT_EQ(resource.request_url.ToString(),
push_resource.request_url.ToString());
EXPECT_EQ(resource.priority, push_resource.priority);
resources.pop_front();
}
}
TEST_F(QuicMemoryCacheBackendTest, GetServerPushResourcesAndPushResponses) {
std::string request_host = "www.foo.com";
std::string response_body("hello response");
const size_t kNumResources = 4;
int NumResources = 4;
std::string scheme = "http";
std::string push_response_status[kNumResources] = {"200", "200", "301",
"404"};
std::list<ServerPushInfo> push_resources;
for (int i = 0; i < NumResources; ++i) {
std::string path = absl::StrCat("/server_push_src", i);
std::string url = scheme + "://" + request_host + path;
QuicUrl resource_url(url);
std::string body = "This is server push response body for " + path;
spdy::Http2HeaderBlock response_headers;
response_headers[":status"] = push_response_status[i];
response_headers["content-length"] = absl::StrCat(body.size());
push_resources.push_back(
ServerPushInfo(resource_url, response_headers.Clone(), i, body));
}
cache_.AddSimpleResponseWithServerPushResources(
request_host, "/", 200, response_body, push_resources);
std::string request_url = request_host + "/";
std::list<ServerPushInfo> resources =
cache_.GetServerPushResources(request_url);
ASSERT_EQ(kNumResources, resources.size());
int i = 0;
for (const auto& push_resource : push_resources) {
QuicUrl url = resources.front().request_url;
std::string host = url.host();
std::string path = url.path();
const Response* response = cache_.GetResponse(host, path);
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ(push_response_status[i++],
response->headers().find(":status")->second);
EXPECT_EQ(push_resource.body, response->body());
resources.pop_front();
}
}
} // namespace test
} // namespace quic
<commit_msg>Disable some tests in QuicMemoryCacheBackendTest on iOS<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 "quic/tools/quic_memory_cache_backend.h"
#include <vector>
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "quic/platform/api/quic_test.h"
#include "quic/tools/quic_backend_response.h"
#include "common/platform/api/quiche_file_utils.h"
namespace quic {
namespace test {
namespace {
using Response = QuicBackendResponse;
using ServerPushInfo = QuicBackendResponse::ServerPushInfo;
} // namespace
class QuicMemoryCacheBackendTest : public QuicTest {
protected:
void CreateRequest(std::string host, std::string path,
spdy::Http2HeaderBlock* headers) {
(*headers)[":method"] = "GET";
(*headers)[":path"] = path;
(*headers)[":authority"] = host;
(*headers)[":scheme"] = "https";
}
std::string CacheDirectory() { return QuicGetTestMemoryCachePath(); }
QuicMemoryCacheBackend cache_;
};
TEST_F(QuicMemoryCacheBackendTest, GetResponseNoMatch) {
const Response* response =
cache_.GetResponse("mail.google.com", "/index.html");
ASSERT_FALSE(response);
}
TEST_F(QuicMemoryCacheBackendTest, AddSimpleResponseGetResponse) {
std::string response_body("hello response");
cache_.AddSimpleResponse("www.google.com", "/", 200, response_body);
spdy::Http2HeaderBlock request_headers;
CreateRequest("www.google.com", "/", &request_headers);
const Response* response = cache_.GetResponse("www.google.com", "/");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("200", response->headers().find(":status")->second);
EXPECT_EQ(response_body.size(), response->body().length());
}
TEST_F(QuicMemoryCacheBackendTest, AddResponse) {
const std::string kRequestHost = "www.foo.com";
const std::string kRequestPath = "/";
const std::string kResponseBody("hello response");
spdy::Http2HeaderBlock response_headers;
response_headers[":status"] = "200";
response_headers["content-length"] = absl::StrCat(kResponseBody.size());
spdy::Http2HeaderBlock response_trailers;
response_trailers["key-1"] = "value-1";
response_trailers["key-2"] = "value-2";
response_trailers["key-3"] = "value-3";
cache_.AddResponse(kRequestHost, "/", response_headers.Clone(), kResponseBody,
response_trailers.Clone());
const Response* response = cache_.GetResponse(kRequestHost, kRequestPath);
EXPECT_EQ(response->headers(), response_headers);
EXPECT_EQ(response->body(), kResponseBody);
EXPECT_EQ(response->trailers(), response_trailers);
}
// TODO(crbug.com/1249712) This test is failing on iOS.
#if defined(OS_IOS)
#define MAYBE_ReadsCacheDir DISABLED_ReadsCacheDir
#else
#define MAYBE_ReadsCacheDir ReadsCacheDir
#endif
TEST_F(QuicMemoryCacheBackendTest, MAYBE_ReadsCacheDir) {
cache_.InitializeBackend(CacheDirectory());
const Response* response =
cache_.GetResponse("test.example.com", "/index.html");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("200", response->headers().find(":status")->second);
// Connection headers are not valid in HTTP/2.
EXPECT_FALSE(response->headers().contains("connection"));
EXPECT_LT(0U, response->body().length());
}
// TODO(crbug.com/1249712) This test is failing on iOS.
#if defined(OS_IOS)
#define MAYBE_ReadsCacheDirWithServerPushResource \
DISABLED_ReadsCacheDirWithServerPushResource
#else
#define MAYBE_ReadsCacheDirWithServerPushResource \
ReadsCacheDirWithServerPushResource
#endif
TEST_F(QuicMemoryCacheBackendTest, MAYBE_ReadsCacheDirWithServerPushResource) {
cache_.InitializeBackend(CacheDirectory() + "_with_push");
std::list<ServerPushInfo> resources =
cache_.GetServerPushResources("test.example.com/");
ASSERT_EQ(1UL, resources.size());
}
// TODO(crbug.com/1249712) This test is failing on iOS.
#if defined(OS_IOS)
#define MAYBE_ReadsCacheDirWithServerPushResources \
DISABLED_ReadsCacheDirWithServerPushResources
#else
#define MAYBE_ReadsCacheDirWithServerPushResources \
ReadsCacheDirWithServerPushResources
#endif
TEST_F(QuicMemoryCacheBackendTest, MAYBE_ReadsCacheDirWithServerPushResources) {
cache_.InitializeBackend(CacheDirectory() + "_with_push");
std::list<ServerPushInfo> resources =
cache_.GetServerPushResources("test.example.com/index2.html");
ASSERT_EQ(2UL, resources.size());
}
// TODO(crbug.com/1249712) This test is failing on iOS.
#if defined(OS_IOS)
#define MAYBE_UsesOriginalUrl DISABLED_UsesOriginalUrl
#else
#define MAYBE_UsesOriginalUrl UsesOriginalUrl
#endif
TEST_F(QuicMemoryCacheBackendTest, MAYBE_UsesOriginalUrl) {
cache_.InitializeBackend(CacheDirectory());
const Response* response =
cache_.GetResponse("test.example.com", "/site_map.html");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("200", response->headers().find(":status")->second);
// Connection headers are not valid in HTTP/2.
EXPECT_FALSE(response->headers().contains("connection"));
EXPECT_LT(0U, response->body().length());
}
// TODO(crbug.com/1249712) This test is failing on iOS.
#if defined(OS_IOS)
#define MAYBE_UsesOriginalUrlOnly DISABLED_UsesOriginalUrlOnly
#else
#define MAYBE_UsesOriginalUrlOnly UsesOriginalUrlOnly
#endif
TEST_F(QuicMemoryCacheBackendTest, MAYBE_UsesOriginalUrlOnly) {
// Tests that if the URL cannot be inferred correctly from the path
// because the directory does not include the hostname, that the
// X-Original-Url header's value will be used.
std::string dir;
std::string path = "map.html";
std::vector<std::string> files;
ASSERT_TRUE(quiche::EnumerateDirectoryRecursively(CacheDirectory(), files));
for (const std::string& file : files) {
if (absl::EndsWithIgnoreCase(file, "map.html")) {
dir = file;
dir.erase(dir.length() - path.length() - 1);
break;
}
}
ASSERT_NE("", dir);
cache_.InitializeBackend(dir);
const Response* response =
cache_.GetResponse("test.example.com", "/site_map.html");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("200", response->headers().find(":status")->second);
// Connection headers are not valid in HTTP/2.
EXPECT_FALSE(response->headers().contains("connection"));
EXPECT_LT(0U, response->body().length());
}
TEST_F(QuicMemoryCacheBackendTest, DefaultResponse) {
// Verify GetResponse returns nullptr when no default is set.
const Response* response = cache_.GetResponse("www.google.com", "/");
ASSERT_FALSE(response);
// Add a default response.
spdy::Http2HeaderBlock response_headers;
response_headers[":status"] = "200";
response_headers["content-length"] = "0";
Response* default_response = new Response;
default_response->set_headers(std::move(response_headers));
cache_.AddDefaultResponse(default_response);
// Now we should get the default response for the original request.
response = cache_.GetResponse("www.google.com", "/");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("200", response->headers().find(":status")->second);
// Now add a set response for / and make sure it is returned
cache_.AddSimpleResponse("www.google.com", "/", 302, "");
response = cache_.GetResponse("www.google.com", "/");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("302", response->headers().find(":status")->second);
// We should get the default response for other requests.
response = cache_.GetResponse("www.google.com", "/asd");
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ("200", response->headers().find(":status")->second);
}
TEST_F(QuicMemoryCacheBackendTest, AddSimpleResponseWithServerPushResources) {
std::string request_host = "www.foo.com";
std::string response_body("hello response");
const size_t kNumResources = 5;
int NumResources = 5;
std::list<ServerPushInfo> push_resources;
std::string scheme = "http";
for (int i = 0; i < NumResources; ++i) {
std::string path = absl::StrCat("/server_push_src", i);
std::string url = scheme + "://" + request_host + path;
QuicUrl resource_url(url);
std::string body =
absl::StrCat("This is server push response body for ", path);
spdy::Http2HeaderBlock response_headers;
response_headers[":status"] = "200";
response_headers["content-length"] = absl::StrCat(body.size());
push_resources.push_back(
ServerPushInfo(resource_url, response_headers.Clone(), i, body));
}
cache_.AddSimpleResponseWithServerPushResources(
request_host, "/", 200, response_body, push_resources);
std::string request_url = request_host + "/";
std::list<ServerPushInfo> resources =
cache_.GetServerPushResources(request_url);
ASSERT_EQ(kNumResources, resources.size());
for (const auto& push_resource : push_resources) {
ServerPushInfo resource = resources.front();
EXPECT_EQ(resource.request_url.ToString(),
push_resource.request_url.ToString());
EXPECT_EQ(resource.priority, push_resource.priority);
resources.pop_front();
}
}
TEST_F(QuicMemoryCacheBackendTest, GetServerPushResourcesAndPushResponses) {
std::string request_host = "www.foo.com";
std::string response_body("hello response");
const size_t kNumResources = 4;
int NumResources = 4;
std::string scheme = "http";
std::string push_response_status[kNumResources] = {"200", "200", "301",
"404"};
std::list<ServerPushInfo> push_resources;
for (int i = 0; i < NumResources; ++i) {
std::string path = absl::StrCat("/server_push_src", i);
std::string url = scheme + "://" + request_host + path;
QuicUrl resource_url(url);
std::string body = "This is server push response body for " + path;
spdy::Http2HeaderBlock response_headers;
response_headers[":status"] = push_response_status[i];
response_headers["content-length"] = absl::StrCat(body.size());
push_resources.push_back(
ServerPushInfo(resource_url, response_headers.Clone(), i, body));
}
cache_.AddSimpleResponseWithServerPushResources(
request_host, "/", 200, response_body, push_resources);
std::string request_url = request_host + "/";
std::list<ServerPushInfo> resources =
cache_.GetServerPushResources(request_url);
ASSERT_EQ(kNumResources, resources.size());
int i = 0;
for (const auto& push_resource : push_resources) {
QuicUrl url = resources.front().request_url;
std::string host = url.host();
std::string path = url.path();
const Response* response = cache_.GetResponse(host, path);
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers().contains(":status"));
EXPECT_EQ(push_response_status[i++],
response->headers().find(":status")->second);
EXPECT_EQ(push_resource.body, response->body());
resources.pop_front();
}
}
} // namespace test
} // namespace quic
<|endoftext|> |
<commit_before>/****** Run RDataFrame tests both with and without IMT enabled *******/
#include <gtest/gtest.h>
#include <ROOT/RDataFrame.hxx>
using namespace ROOT;
using namespace ROOT::RDF;
using namespace ROOT::VecOps;
static const std::string DisplayPrintDefaultRows(
"b1 | b2 | b3 | \n0 | 1 | 2.0000000 | \n | ... | | \n | 3 | | \n0 | 1 | "
"2.0000000 | \n | ... | | \n | 3 | | \n0 | 1 | 2.0000000 | \n | ... | | \n "
" | 3 | | \n0 | 1 | 2.0000000 | \n | ... | | \n | 3 | | \n0 | 1 | "
"2.0000000 | \n | ... | | \n | 3 | | \n");
static const std::string DisplayAsStringDefaultRows(
"b1 | b2 | b3 | \n0 | 1 | 2.0000000 | \n | 2 | | \n | 3 | | \n0 | 1 | "
"2.0000000 | \n | 2 | | \n | 3 | | \n0 | 1 | 2.0000000 | \n | 2 | | \n "
" | 3 | | \n0 | 1 | 2.0000000 | \n | 2 | | \n | 3 | | \n0 | 1 | "
"2.0000000 | \n | 2 | | \n | 3 | | \n | | | \n");
TEST(RDFDisplayTests, DisplayNoJitDefaultRows)
{
RDataFrame rd1(10);
auto dd = rd1.Define("b1", []() { return 0; })
.Define("b2",
[]() {
return std::vector<int>({1, 2, 3});
})
.Define("b3", []() { return 2.; })
.Display<int, std::vector<int>, double>({"b1", "b2", "b3"});
// Testing the std output printing
std::cout << std::flush;
// Redirect cout.
std::streambuf *oldCoutStreamBuf = std::cout.rdbuf();
std::ostringstream strCout;
std::cout.rdbuf(strCout.rdbuf());
dd->Print();
// Restore old cout.
std::cout.rdbuf(oldCoutStreamBuf);
EXPECT_EQ(strCout.str(), DisplayPrintDefaultRows);
// Testing the string returned
EXPECT_EQ(dd->AsString(), DisplayAsStringDefaultRows);
}
TEST(RDFDisplayTests, DisplayJitDefaultRows)
{
RDataFrame rd1(10);
auto dd = rd1.Define("b1", []() { return 0; })
.Define("b2",
[]() {
return std::vector<int>({1, 2, 3});
})
.Define("b3", []() { return 2.; })
.Display({"b1", "b2", "b3"});
// Testing the std output printing
std::cout << std::flush;
// Redirect cout.
std::streambuf *oldCoutStreamBuf = std::cout.rdbuf();
std::ostringstream strCout;
std::cout.rdbuf(strCout.rdbuf());
dd->Print();
// Restore old cout.
std::cout.rdbuf(oldCoutStreamBuf);
EXPECT_EQ(strCout.str(), DisplayPrintDefaultRows);
// Testing the string returned
EXPECT_EQ(dd->AsString(), DisplayAsStringDefaultRows);
}
TEST(RDFDisplayTests, DisplayRegexDefaultRows)
{
RDataFrame rd1(10);
auto dd = rd1.Define("b1", []() { return 0; })
.Define("b2",
[]() {
return std::vector<int>({1, 2, 3});
})
.Define("b3", []() { return 2.; })
.Display("");
// Testing the std output printing
std::cout << std::flush;
// Redirect cout.
std::streambuf *oldCoutStreamBuf = std::cout.rdbuf();
std::ostringstream strCout;
std::cout.rdbuf(strCout.rdbuf());
dd->Print();
// Restore old cout.
std::cout.rdbuf(oldCoutStreamBuf);
EXPECT_EQ(strCout.str(), DisplayPrintDefaultRows);
// Testing the string returned
EXPECT_EQ(dd->AsString(), DisplayAsStringDefaultRows);
}
static const std::string
DisplayPrintTwoRows("b1 | b2 | b3 | \n0 | 1 | 2.0000000 | \n | ... | | \n | 3 | "
" | \n0 | 1 | 2.0000000 | \n | ... | | \n | 3 | | \n");
static const std::string DisplayAsStringTwoRows(
"b1 | b2 | b3 | \n0 | 1 | 2.0000000 | \n | 2 | | \n | 3 | | \n0 | 1 | "
"2.0000000 | \n | 2 | | \n | 3 | | \n | | | \n");
TEST(RDFDisplayTests, DisplayJitTwoRows)
{
RDataFrame rd1(10);
auto dd = rd1.Define("b1", []() { return 0; })
.Define("b2",
[]() {
return std::vector<int>({1, 2, 3});
})
.Define("b3", []() { return 2.; })
.Display({"b1", "b2", "b3"}, 2);
// Testing the std output printing
std::cout << std::flush;
// Redirect cout.
std::streambuf *oldCoutStreamBuf = std::cout.rdbuf();
std::ostringstream strCout;
std::cout.rdbuf(strCout.rdbuf());
dd->Print();
// Restore old cout.
std::cout.rdbuf(oldCoutStreamBuf);
EXPECT_EQ(strCout.str(), DisplayPrintTwoRows);
// Testing the string returned
EXPECT_EQ(dd->AsString(), DisplayAsStringTwoRows);
}
static const std::string DisplayAsStringOneColumn("b1 | \n0 | \n0 | \n0 | \n0 | \n0 | \n | \n");
static const std::string DisplayAsStringTwoColumns(
"b1 | b2 | \n0 | 1 | \n | 2 | \n | 3 | \n0 | 1 | \n | 2 | \n | 3 | \n0 | 1 | \n | 2 | "
"\n | 3 | \n0 | 1 | \n | 2 | \n | 3 | \n0 | 1 | \n | 2 | \n | 3 | \n | | \n");
TEST(RDFDisplayTests, DisplayAmbiguity)
{
// This test verifies that the correct method is called and there is no ambiguity between the JIT call to Display
// using a column list as a parameter and the JIT call to Display using the Regexp.
RDataFrame rd1(10);
auto dd = rd1.Define("b1", []() { return 0; }).Define("b2", []() { return std::vector<int>({1, 2, 3}); });
auto display_1 = dd.Display({"b1"});
auto display_2 = dd.Display({"b1", "b2"});
EXPECT_EQ(display_1->AsString(), DisplayAsStringOneColumn);
EXPECT_EQ(display_2->AsString(), DisplayAsStringTwoColumns);
}
static const std::string DisplayAsStringString("b1 | \n\"foo\" | \n\"foo\" | \n | \n");
TEST(RDFDisplayTests, DisplayPrintString)
{
RDataFrame rd1(2);
auto dd = rd1.Define("b1", []() { return std::string("foo"); })
.Display({"b1"});
// Testing the std output printing
std::cout << std::flush;
// Redirect cout.
std::streambuf *oldCoutStreamBuf = std::cout.rdbuf();
std::ostringstream strCout;
std::cout.rdbuf(strCout.rdbuf());
dd->Print();
// Restore old cout.
std::cout.rdbuf(oldCoutStreamBuf);
// Testing the string returned
EXPECT_EQ(dd->AsString(), DisplayAsStringString);
}
TEST(RDFDisplayTests, CharArray)
{
{
TFile f("chararray.root", "recreate");
TTree t("t", "t");
char str[4] = "asd";
t.Branch("str", str, "str[4]/C");
t.Fill();
char otherstr[4] = "bar";
std::copy(otherstr, otherstr + 4, str);
t.Fill();
f.Write();
}
const auto str = ROOT::RDataFrame("t", "chararray.root").Display()->AsString();
EXPECT_EQ(str, "str | \nasd | \nbar | \n | \n");
}
TEST(RDFDisplayTests, BoolArray)
{
auto r = ROOT::RDataFrame(3)
.Define("v", [] { return ROOT::RVec<bool>{true,false}; })
.Display<ROOT::RVec<bool>>({"v"});
const auto expected = "v | \ntrue | \nfalse | \ntrue | \nfalse | \ntrue | \nfalse | \ntrue | \nfalse | "
"\ntrue | \nfalse | \ntrue | \nfalse | \n | \n";
EXPECT_EQ(r->AsString(), expected);
}
TEST(RDFDisplayTests, UniquePtr)
{
auto r = ROOT::RDataFrame(1)
.Define("uptr", []() -> std::unique_ptr<int> { return nullptr; })
.Display<std::unique_ptr<int>>({"uptr"});
const auto expected =
"uptr | \nstd::unique_ptr -> nullptr | \n | \n";
EXPECT_EQ(r->AsString(), expected);
}
<commit_msg>[DF] Add test for issue #6371, Display regex and sub-branches<commit_after>/****** Run RDataFrame tests both with and without IMT enabled *******/
#include <gtest/gtest.h>
#include <ROOT/RDataFrame.hxx>
#include <TTree.h>
#include <utility> // std::pair
using namespace ROOT;
using namespace ROOT::RDF;
using namespace ROOT::VecOps;
static const std::string DisplayPrintDefaultRows(
"b1 | b2 | b3 | \n0 | 1 | 2.0000000 | \n | ... | | \n | 3 | | \n0 | 1 | "
"2.0000000 | \n | ... | | \n | 3 | | \n0 | 1 | 2.0000000 | \n | ... | | \n "
" | 3 | | \n0 | 1 | 2.0000000 | \n | ... | | \n | 3 | | \n0 | 1 | "
"2.0000000 | \n | ... | | \n | 3 | | \n");
static const std::string DisplayAsStringDefaultRows(
"b1 | b2 | b3 | \n0 | 1 | 2.0000000 | \n | 2 | | \n | 3 | | \n0 | 1 | "
"2.0000000 | \n | 2 | | \n | 3 | | \n0 | 1 | 2.0000000 | \n | 2 | | \n "
" | 3 | | \n0 | 1 | 2.0000000 | \n | 2 | | \n | 3 | | \n0 | 1 | "
"2.0000000 | \n | 2 | | \n | 3 | | \n | | | \n");
TEST(RDFDisplayTests, DisplayNoJitDefaultRows)
{
RDataFrame rd1(10);
auto dd = rd1.Define("b1", []() { return 0; })
.Define("b2",
[]() {
return std::vector<int>({1, 2, 3});
})
.Define("b3", []() { return 2.; })
.Display<int, std::vector<int>, double>({"b1", "b2", "b3"});
// Testing the std output printing
std::cout << std::flush;
// Redirect cout.
std::streambuf *oldCoutStreamBuf = std::cout.rdbuf();
std::ostringstream strCout;
std::cout.rdbuf(strCout.rdbuf());
dd->Print();
// Restore old cout.
std::cout.rdbuf(oldCoutStreamBuf);
EXPECT_EQ(strCout.str(), DisplayPrintDefaultRows);
// Testing the string returned
EXPECT_EQ(dd->AsString(), DisplayAsStringDefaultRows);
}
TEST(RDFDisplayTests, DisplayJitDefaultRows)
{
RDataFrame rd1(10);
auto dd = rd1.Define("b1", []() { return 0; })
.Define("b2",
[]() {
return std::vector<int>({1, 2, 3});
})
.Define("b3", []() { return 2.; })
.Display({"b1", "b2", "b3"});
// Testing the std output printing
std::cout << std::flush;
// Redirect cout.
std::streambuf *oldCoutStreamBuf = std::cout.rdbuf();
std::ostringstream strCout;
std::cout.rdbuf(strCout.rdbuf());
dd->Print();
// Restore old cout.
std::cout.rdbuf(oldCoutStreamBuf);
EXPECT_EQ(strCout.str(), DisplayPrintDefaultRows);
// Testing the string returned
EXPECT_EQ(dd->AsString(), DisplayAsStringDefaultRows);
}
TEST(RDFDisplayTests, DisplayRegexDefaultRows)
{
RDataFrame rd1(10);
auto dd = rd1.Define("b1", []() { return 0; })
.Define("b2",
[]() {
return std::vector<int>({1, 2, 3});
})
.Define("b3", []() { return 2.; })
.Display("");
// Testing the std output printing
std::cout << std::flush;
// Redirect cout.
std::streambuf *oldCoutStreamBuf = std::cout.rdbuf();
std::ostringstream strCout;
std::cout.rdbuf(strCout.rdbuf());
dd->Print();
// Restore old cout.
std::cout.rdbuf(oldCoutStreamBuf);
EXPECT_EQ(strCout.str(), DisplayPrintDefaultRows);
// Testing the string returned
EXPECT_EQ(dd->AsString(), DisplayAsStringDefaultRows);
}
static const std::string
DisplayPrintTwoRows("b1 | b2 | b3 | \n0 | 1 | 2.0000000 | \n | ... | | \n | 3 | "
" | \n0 | 1 | 2.0000000 | \n | ... | | \n | 3 | | \n");
static const std::string DisplayAsStringTwoRows(
"b1 | b2 | b3 | \n0 | 1 | 2.0000000 | \n | 2 | | \n | 3 | | \n0 | 1 | "
"2.0000000 | \n | 2 | | \n | 3 | | \n | | | \n");
TEST(RDFDisplayTests, DisplayJitTwoRows)
{
RDataFrame rd1(10);
auto dd = rd1.Define("b1", []() { return 0; })
.Define("b2",
[]() {
return std::vector<int>({1, 2, 3});
})
.Define("b3", []() { return 2.; })
.Display({"b1", "b2", "b3"}, 2);
// Testing the std output printing
std::cout << std::flush;
// Redirect cout.
std::streambuf *oldCoutStreamBuf = std::cout.rdbuf();
std::ostringstream strCout;
std::cout.rdbuf(strCout.rdbuf());
dd->Print();
// Restore old cout.
std::cout.rdbuf(oldCoutStreamBuf);
EXPECT_EQ(strCout.str(), DisplayPrintTwoRows);
// Testing the string returned
EXPECT_EQ(dd->AsString(), DisplayAsStringTwoRows);
}
static const std::string DisplayAsStringOneColumn("b1 | \n0 | \n0 | \n0 | \n0 | \n0 | \n | \n");
static const std::string DisplayAsStringTwoColumns(
"b1 | b2 | \n0 | 1 | \n | 2 | \n | 3 | \n0 | 1 | \n | 2 | \n | 3 | \n0 | 1 | \n | 2 | "
"\n | 3 | \n0 | 1 | \n | 2 | \n | 3 | \n0 | 1 | \n | 2 | \n | 3 | \n | | \n");
TEST(RDFDisplayTests, DisplayAmbiguity)
{
// This test verifies that the correct method is called and there is no ambiguity between the JIT call to Display
// using a column list as a parameter and the JIT call to Display using the Regexp.
RDataFrame rd1(10);
auto dd = rd1.Define("b1", []() { return 0; }).Define("b2", []() { return std::vector<int>({1, 2, 3}); });
auto display_1 = dd.Display({"b1"});
auto display_2 = dd.Display({"b1", "b2"});
EXPECT_EQ(display_1->AsString(), DisplayAsStringOneColumn);
EXPECT_EQ(display_2->AsString(), DisplayAsStringTwoColumns);
}
static const std::string DisplayAsStringString("b1 | \n\"foo\" | \n\"foo\" | \n | \n");
TEST(RDFDisplayTests, DisplayPrintString)
{
RDataFrame rd1(2);
auto dd = rd1.Define("b1", []() { return std::string("foo"); })
.Display({"b1"});
// Testing the std output printing
std::cout << std::flush;
// Redirect cout.
std::streambuf *oldCoutStreamBuf = std::cout.rdbuf();
std::ostringstream strCout;
std::cout.rdbuf(strCout.rdbuf());
dd->Print();
// Restore old cout.
std::cout.rdbuf(oldCoutStreamBuf);
// Testing the string returned
EXPECT_EQ(dd->AsString(), DisplayAsStringString);
}
TEST(RDFDisplayTests, CharArray)
{
{
TFile f("chararray.root", "recreate");
TTree t("t", "t");
char str[4] = "asd";
t.Branch("str", str, "str[4]/C");
t.Fill();
char otherstr[4] = "bar";
std::copy(otherstr, otherstr + 4, str);
t.Fill();
f.Write();
}
const auto str = ROOT::RDataFrame("t", "chararray.root").Display()->AsString();
EXPECT_EQ(str, "str | \nasd | \nbar | \n | \n");
}
TEST(RDFDisplayTests, BoolArray)
{
auto r = ROOT::RDataFrame(3)
.Define("v", [] { return ROOT::RVec<bool>{true,false}; })
.Display<ROOT::RVec<bool>>({"v"});
const auto expected = "v | \ntrue | \nfalse | \ntrue | \nfalse | \ntrue | \nfalse | \ntrue | \nfalse | "
"\ntrue | \nfalse | \ntrue | \nfalse | \n | \n";
EXPECT_EQ(r->AsString(), expected);
}
TEST(RDFDisplayTests, UniquePtr)
{
auto r = ROOT::RDataFrame(1)
.Define("uptr", []() -> std::unique_ptr<int> { return nullptr; })
.Display<std::unique_ptr<int>>({"uptr"});
const auto expected =
"uptr | \nstd::unique_ptr -> nullptr | \n | \n";
EXPECT_EQ(r->AsString(), expected);
}
// GitHub issue #6371
TEST(RDFDisplayTests, SubBranch)
{
auto p = std::make_pair(42, 84);
TTree t("t", "t");
t.Branch("p", &p, "a/I:b/I");
t.Fill();
ROOT::RDataFrame df(t);
const auto res = df.Display()->AsString();
const auto expected = "p.a | p.b | \n42 | 84 | \n | | \n";
EXPECT_EQ(res, expected);
}
<|endoftext|> |
<commit_before>#include "ROOT/RDataFrame.hxx"
#include "ROOT/TSeq.hxx"
#include "TROOT.h"
#include "TSystem.h"
#include "TFile.h"
#include "TChain.h"
#include "TTree.h"
#include "gtest/gtest.h"
// fixture that creates two files with two trees of 10 events each. One has branch `x`, the other branch `y`, both ints.
class RDFAndFriends : public ::testing::Test {
protected:
constexpr static auto kFile1 = "test_tdfandfriends.root";
constexpr static auto kFile2 = "test_tdfandfriends2.root";
constexpr static auto kFile3 = "test_tdfandfriends3.root";
constexpr static auto kFile4 = "test_tdfandfriends4.root";
constexpr static auto kFile5 = "test_tdfandfriends5.root";
constexpr static ULong64_t kSizeSmall = 4;
constexpr static ULong64_t kSizeBig = 10000;
static void SetUpTestCase()
{
ROOT::RDataFrame d(kSizeSmall);
d.Define("x", [] { return 1; }).Snapshot<int>("t", kFile1, {"x"});
d.Define("y", [] { return 2; }).Snapshot<int>("t2", kFile2, {"y"});
TFile f(kFile3, "RECREATE");
TTree t("t3", "t3");
float arr[4];
t.Branch("arr", arr, "arr[4]/F");
for (auto i : ROOT::TSeqU(4)) {
for (auto j : ROOT::TSeqU(4)) {
arr[j] = i + j;
}
t.Fill();
}
t.Write();
ROOT::RDataFrame d2(kSizeBig);
d2.Define("x", [] { return 4; }).Snapshot<int>("t", kFile4, {"x"});
d2.Define("y", [] { return 5; }).Snapshot<int>("t2", kFile5, {"y"});
}
static void TearDownTestCase()
{
for (auto fileName : {kFile1, kFile2, kFile3, kFile4, kFile5})
gSystem->Unlink(fileName);
}
};
TEST_F(RDFAndFriends, FriendByFile)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
t1->AddFriend("t2", kFile2);
ROOT::RDataFrame d(*t1);
auto x = d.Min<int>("x");
auto t = d.Take<int>("y");
EXPECT_EQ(*x, 1);
for (auto v : t)
EXPECT_EQ(v, 2);
}
TEST_F(RDFAndFriends, FriendByPointer)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
TFile f2(kFile2);
auto t2 = f2.Get<TTree>("t2");
t1->AddFriend(t2);
ROOT::RDataFrame d(*t1);
auto x = d.Min<int>("x");
auto t = d.Take<int>("y");
EXPECT_EQ(*x, 1);
for (auto v : t)
EXPECT_EQ(v, 2);
}
TEST_F(RDFAndFriends, FriendArrayByFile)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
t1->AddFriend("t3", kFile3);
ROOT::RDataFrame d(*t1);
int i(0);
auto checkArr = [&i](ROOT::VecOps::RVec<float> av) {
auto ifloat = float(i);
EXPECT_EQ(ifloat, av[0]);
EXPECT_EQ(ifloat + 1, av[1]);
EXPECT_EQ(ifloat + 2, av[2]);
EXPECT_EQ(ifloat + 3, av[3]);
i++;
};
d.Foreach(checkArr, {"arr"});
}
TEST_F(RDFAndFriends, FriendArrayByPointer)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
TFile f3(kFile3);
auto t3 = f3.Get<TTree>("t3");
t1->AddFriend(t3);
ROOT::RDataFrame d(*t1);
int i(0);
auto checkArr = [&i](ROOT::VecOps::RVec<float> av) {
auto ifloat = float(i);
EXPECT_EQ(ifloat, av[0]);
EXPECT_EQ(ifloat + 1, av[1]);
EXPECT_EQ(ifloat + 2, av[2]);
EXPECT_EQ(ifloat + 3, av[3]);
i++;
};
d.Foreach(checkArr, {"arr"});
}
TEST_F(RDFAndFriends, QualifiedBranchName)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
t1->AddFriend("t2", kFile2);
ROOT::RDataFrame d(*t1);
auto x = d.Min<int>("x");
EXPECT_EQ(*x, 1);
auto t = d.Take<int>("t2.y");
for (auto v : t)
EXPECT_EQ(v, 2);
}
TEST_F(RDFAndFriends, FromDefine)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
t1->AddFriend("t2", kFile2);
ROOT::RDataFrame d(*t1);
auto m = d.Define("yy", [](int y) { return y * y; }, {"y"}).Mean("yy");
EXPECT_DOUBLE_EQ(*m, 4.);
}
TEST_F(RDFAndFriends, FromJittedDefine)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
t1->AddFriend("t2", kFile2);
ROOT::RDataFrame d(*t1);
auto m = d.Define("yy", "y * y").Mean("yy");
EXPECT_DOUBLE_EQ(*m, 4.);
}
// NOW MT!-------------
#ifdef R__USE_IMT
TEST_F(RDFAndFriends, FriendMT)
{
ROOT::EnableImplicitMT(4u);
TFile f1(kFile4);
auto t1 = f1.Get<TTree>("t");
t1->AddFriend("t2", kFile5);
ROOT::RDataFrame d(*t1);
auto x = d.Min<int>("x");
auto t = d.Take<int>("y");
EXPECT_EQ(*x, 4);
for (auto v : t)
EXPECT_EQ(v, 5);
ROOT::DisableImplicitMT();
}
TEST_F(RDFAndFriends, FriendAliasMT)
{
ROOT::EnableImplicitMT(4u);
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
TFile f2(kFile4);
auto t2 = f2.Get<TTree>("t");
t1->AddFriend(t2, "myfriend");
ROOT::RDataFrame d(*t1);
auto x = d.Min<int>("x");
auto t = d.Take<int>("myfriend.x");
EXPECT_EQ(*x, 1);
for (auto v : t)
EXPECT_EQ(v, 4);
ROOT::DisableImplicitMT();
}
TEST_F(RDFAndFriends, FriendChainMT)
{
ROOT::EnableImplicitMT(4u);
TChain c1("t");
c1.AddFile(kFile1);
c1.AddFile(kFile4);
c1.AddFile(kFile1);
c1.AddFile(kFile4);
TChain c2("t2");
c2.AddFile(kFile2);
c2.AddFile(kFile5);
c2.AddFile(kFile2);
c2.AddFile(kFile5);
c1.AddFriend(&c2);
ROOT::RDataFrame d(c1);
auto c = d.Count();
EXPECT_EQ(*c, 2 * (kSizeSmall + kSizeBig));
auto x = d.Min<int>("x");
auto y = d.Max<int>("y");
EXPECT_EQ(*x, 1);
EXPECT_EQ(*y, 5);
ROOT::DisableImplicitMT();
}
// ROOT-9559
void FillIndexedFriend(const char *mainfile, const char *auxfile)
{
// Start by creating main Tree
TFile f(mainfile, "RECREATE");
TTree mainTree("mainTree", "mainTree");
int idx;
mainTree.Branch("idx", &idx);
float x;
mainTree.Branch("x", &x);
idx = 1;
x = 0.5;
mainTree.Fill();
idx = 1;
x = 2;
mainTree.Fill();
idx = 1;
x = 5;
mainTree.Fill();
idx = 2;
x = 1;
mainTree.Fill();
idx = 2;
x = 8;
mainTree.Fill();
mainTree.Write();
f.Close();
// And aux tree
TFile f2(auxfile, "RECREATE");
TTree auxTree("auxTree", "auxTree");
auxTree.Branch("idx", &idx);
float y;
auxTree.Branch("y", &y);
idx = 1;
y = 5;
auxTree.Fill();
idx = 2;
y = 7;
auxTree.Fill();
auxTree.Write();
f2.Close();
}
TEST(RDFAndFriendsNoFixture, IndexedFriend)
{
auto mainFile = "IndexedFriend_main.root";
auto auxFile = "IndexedFriend_aux.root";
FillIndexedFriend(mainFile, auxFile);
TChain mainChain("mainTree", "mainTree");
mainChain.Add(mainFile);
TChain auxChain("auxTree", "auxTree");
auxChain.Add(auxFile);
auxChain.BuildIndex("idx");
mainChain.AddFriend(&auxChain);
auto op = [&](){
auto df = ROOT::RDataFrame(mainChain);
*df.Min<int>("x");
};
EXPECT_ANY_THROW(op());
gSystem->Unlink(mainFile);
gSystem->Unlink(auxFile);
}
// Test for https://github.com/root-project/root/issues/6741
TEST(RDFAndFriendsNoFixture, AutomaticFriendsLoad)
{
const auto fname = "rdf_automaticfriendsloadtest.root";
{
// write a TTree and its friend to the same file
TFile f(fname, "recreate");
TTree t1("t1", "t1");
TTree t2("t2", "t2");
int x = 42;
t2.Branch("x", &x);
t1.Fill();
t2.Fill();
t1.AddFriend(&t2);
t1.Write();
t2.Write();
f.Close();
}
EXPECT_EQ(ROOT::RDataFrame("t1", fname).Max<int>("t2.x").GetValue(), 42);
gSystem->Unlink(fname);
}
#endif // R__USE_IMT
<commit_msg>[DF] Test reading of indexed friend trees<commit_after>#include "ROOT/RDataFrame.hxx"
#include "ROOT/TSeq.hxx"
#include "TROOT.h"
#include "TSystem.h"
#include "TFile.h"
#include "TChain.h"
#include "TTree.h"
#include "gtest/gtest.h"
#include <algorithm> // std::equal
// fixture that creates two files with two trees of 10 events each. One has branch `x`, the other branch `y`, both ints.
class RDFAndFriends : public ::testing::Test {
protected:
constexpr static auto kFile1 = "test_tdfandfriends.root";
constexpr static auto kFile2 = "test_tdfandfriends2.root";
constexpr static auto kFile3 = "test_tdfandfriends3.root";
constexpr static auto kFile4 = "test_tdfandfriends4.root";
constexpr static auto kFile5 = "test_tdfandfriends5.root";
constexpr static ULong64_t kSizeSmall = 4;
constexpr static ULong64_t kSizeBig = 10000;
static void SetUpTestCase()
{
ROOT::RDataFrame d(kSizeSmall);
d.Define("x", [] { return 1; }).Snapshot<int>("t", kFile1, {"x"});
d.Define("y", [] { return 2; }).Snapshot<int>("t2", kFile2, {"y"});
TFile f(kFile3, "RECREATE");
TTree t("t3", "t3");
float arr[4];
t.Branch("arr", arr, "arr[4]/F");
for (auto i : ROOT::TSeqU(4)) {
for (auto j : ROOT::TSeqU(4)) {
arr[j] = i + j;
}
t.Fill();
}
t.Write();
ROOT::RDataFrame d2(kSizeBig);
d2.Define("x", [] { return 4; }).Snapshot<int>("t", kFile4, {"x"});
d2.Define("y", [] { return 5; }).Snapshot<int>("t2", kFile5, {"y"});
}
static void TearDownTestCase()
{
for (auto fileName : {kFile1, kFile2, kFile3, kFile4, kFile5})
gSystem->Unlink(fileName);
}
};
TEST_F(RDFAndFriends, FriendByFile)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
t1->AddFriend("t2", kFile2);
ROOT::RDataFrame d(*t1);
auto x = d.Min<int>("x");
auto t = d.Take<int>("y");
EXPECT_EQ(*x, 1);
for (auto v : t)
EXPECT_EQ(v, 2);
}
TEST_F(RDFAndFriends, FriendByPointer)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
TFile f2(kFile2);
auto t2 = f2.Get<TTree>("t2");
t1->AddFriend(t2);
ROOT::RDataFrame d(*t1);
auto x = d.Min<int>("x");
auto t = d.Take<int>("y");
EXPECT_EQ(*x, 1);
for (auto v : t)
EXPECT_EQ(v, 2);
}
TEST_F(RDFAndFriends, FriendArrayByFile)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
t1->AddFriend("t3", kFile3);
ROOT::RDataFrame d(*t1);
int i(0);
auto checkArr = [&i](ROOT::VecOps::RVec<float> av) {
auto ifloat = float(i);
EXPECT_EQ(ifloat, av[0]);
EXPECT_EQ(ifloat + 1, av[1]);
EXPECT_EQ(ifloat + 2, av[2]);
EXPECT_EQ(ifloat + 3, av[3]);
i++;
};
d.Foreach(checkArr, {"arr"});
}
TEST_F(RDFAndFriends, FriendArrayByPointer)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
TFile f3(kFile3);
auto t3 = f3.Get<TTree>("t3");
t1->AddFriend(t3);
ROOT::RDataFrame d(*t1);
int i(0);
auto checkArr = [&i](ROOT::VecOps::RVec<float> av) {
auto ifloat = float(i);
EXPECT_EQ(ifloat, av[0]);
EXPECT_EQ(ifloat + 1, av[1]);
EXPECT_EQ(ifloat + 2, av[2]);
EXPECT_EQ(ifloat + 3, av[3]);
i++;
};
d.Foreach(checkArr, {"arr"});
}
TEST_F(RDFAndFriends, QualifiedBranchName)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
t1->AddFriend("t2", kFile2);
ROOT::RDataFrame d(*t1);
auto x = d.Min<int>("x");
EXPECT_EQ(*x, 1);
auto t = d.Take<int>("t2.y");
for (auto v : t)
EXPECT_EQ(v, 2);
}
TEST_F(RDFAndFriends, FromDefine)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
t1->AddFriend("t2", kFile2);
ROOT::RDataFrame d(*t1);
auto m = d.Define("yy", [](int y) { return y * y; }, {"y"}).Mean("yy");
EXPECT_DOUBLE_EQ(*m, 4.);
}
TEST_F(RDFAndFriends, FromJittedDefine)
{
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
t1->AddFriend("t2", kFile2);
ROOT::RDataFrame d(*t1);
auto m = d.Define("yy", "y * y").Mean("yy");
EXPECT_DOUBLE_EQ(*m, 4.);
}
// NOW MT!-------------
#ifdef R__USE_IMT
TEST_F(RDFAndFriends, FriendMT)
{
ROOT::EnableImplicitMT(4u);
TFile f1(kFile4);
auto t1 = f1.Get<TTree>("t");
t1->AddFriend("t2", kFile5);
ROOT::RDataFrame d(*t1);
auto x = d.Min<int>("x");
auto t = d.Take<int>("y");
EXPECT_EQ(*x, 4);
for (auto v : t)
EXPECT_EQ(v, 5);
ROOT::DisableImplicitMT();
}
TEST_F(RDFAndFriends, FriendAliasMT)
{
ROOT::EnableImplicitMT(4u);
TFile f1(kFile1);
auto t1 = f1.Get<TTree>("t");
TFile f2(kFile4);
auto t2 = f2.Get<TTree>("t");
t1->AddFriend(t2, "myfriend");
ROOT::RDataFrame d(*t1);
auto x = d.Min<int>("x");
auto t = d.Take<int>("myfriend.x");
EXPECT_EQ(*x, 1);
for (auto v : t)
EXPECT_EQ(v, 4);
ROOT::DisableImplicitMT();
}
TEST_F(RDFAndFriends, FriendChainMT)
{
ROOT::EnableImplicitMT(4u);
TChain c1("t");
c1.AddFile(kFile1);
c1.AddFile(kFile4);
c1.AddFile(kFile1);
c1.AddFile(kFile4);
TChain c2("t2");
c2.AddFile(kFile2);
c2.AddFile(kFile5);
c2.AddFile(kFile2);
c2.AddFile(kFile5);
c1.AddFriend(&c2);
ROOT::RDataFrame d(c1);
auto c = d.Count();
EXPECT_EQ(*c, 2 * (kSizeSmall + kSizeBig));
auto x = d.Min<int>("x");
auto y = d.Max<int>("y");
EXPECT_EQ(*x, 1);
EXPECT_EQ(*y, 5);
ROOT::DisableImplicitMT();
}
// ROOT-9559
void FillIndexedFriend(const char *mainfile, const char *auxfile)
{
// Start by creating main Tree
TFile f(mainfile, "RECREATE");
TTree mainTree("mainTree", "mainTree");
int idx;
mainTree.Branch("idx", &idx);
int x;
mainTree.Branch("x", &x);
idx = 1;
x = 1;
mainTree.Fill();
idx = 1;
x = 2;
mainTree.Fill();
idx = 1;
x = 3;
mainTree.Fill();
idx = 2;
x = 4;
mainTree.Fill();
idx = 2;
x = 5;
mainTree.Fill();
mainTree.Write();
f.Close();
// And aux tree
TFile f2(auxfile, "RECREATE");
TTree auxTree("auxTree", "auxTree");
auxTree.Branch("idx", &idx);
int y;
auxTree.Branch("y", &y);
idx = 2;
y = 5;
auxTree.Fill();
idx = 1;
y = 7;
auxTree.Fill();
auxTree.Write();
f2.Close();
}
TEST(RDFAndFriendsNoFixture, IndexedFriend)
{
auto mainFile = "IndexedFriend_main.root";
auto auxFile = "IndexedFriend_aux.root";
FillIndexedFriend(mainFile, auxFile);
TChain mainChain("mainTree", "mainTree");
mainChain.Add(mainFile);
TChain auxChain("auxTree", "auxTree");
auxChain.Add(auxFile);
auxChain.BuildIndex("idx");
mainChain.AddFriend(&auxChain);
auto df = ROOT::RDataFrame(mainChain);
auto x = df.Take<int>("x");
auto y = df.Take<int>("auxTree.y");
std::vector<int> refx{{1,2,3,4,5}};
EXPECT_TRUE(std::equal(x->begin(), x->end(), refx.begin()));
std::vector<int> refy{{7,7,7,5,5}};
EXPECT_TRUE(std::equal(y->begin(), y->end(), refy.begin()));
gSystem->Unlink(mainFile);
gSystem->Unlink(auxFile);
}
// Test for https://github.com/root-project/root/issues/6741
TEST(RDFAndFriendsNoFixture, AutomaticFriendsLoad)
{
const auto fname = "rdf_automaticfriendsloadtest.root";
{
// write a TTree and its friend to the same file
TFile f(fname, "recreate");
TTree t1("t1", "t1");
TTree t2("t2", "t2");
int x = 42;
t2.Branch("x", &x);
t1.Fill();
t2.Fill();
t1.AddFriend(&t2);
t1.Write();
t2.Write();
f.Close();
}
EXPECT_EQ(ROOT::RDataFrame("t1", fname).Max<int>("t2.x").GetValue(), 42);
gSystem->Unlink(fname);
}
#endif // R__USE_IMT
<|endoftext|> |
<commit_before>#include "game.hpp"
int Game::startGame() {
std::string str;
uciHandler("position startpos");
while(true) {
std::getline(std::cin, str);
if(!uciHandler(str)) {
return 0;
};
}
}
int64_t Game::mtdf(int64_t f, int depth) {
int64_t bound[2] = {-WHITE_WIN, +WHITE_WIN};
do {
double beta = f + (f == bound[0]);
f = negamax(game_board, beta - 1, beta, depth, 0, FIXED_DEPTH, false, true);
bound[f < beta] = f;
} while (bound[0] < bound[1]);
return f;
}
void Game::goFixedDepth() {
if(option.UCI_AnalyseMode) {
clearCash();
}
stopped = false;
variant.clear();
variant.resize(max_depth);
std::vector<uint64_t>hash;
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
nodesCounter = 0;
int max_depth_global = max_depth;
max_depth = 1;
start_timer = clock();
hasBestMove = false;
BitMove moveCritical = game_board.getRandomMove();
bestMove = moveCritical;
hasBestMove = true;
bestScore = 0;
//int64_t f = 0;
//int64_t current_alpha = -WHITE_WIN, current_beta = WHITE_WIN, win_size = 50;
for(; max_depth <= max_depth_global; ++max_depth) {
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
flattenHistory();
//negamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);
/*if(max_depth > 1) {
current_alpha = bestScore - 30;
current_beta = bestScore + 30;
}*/
negamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);
/*std::cout << "!";
if(bestScore <= current_alpha) {
std::cout << "!";
negamax(game_board, -WHITE_WIN, current_beta, max_depth, 0, FIXED_DEPTH, false, true);
} else if(bestScore >= current_beta) {
std::cout << "!";
negamax(game_board, current_alpha, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);
}*/
//f = mtdf(f, max_depth);
hasBestMove = true;
if((abs(bestScore) >= (WHITE_WIN - 100) && max_depth_global < 99) || stopped) {
break;
}
}
end_timer = clock();
if(hasBestMove) {
std::cout << "bestmove " << bestMove.getMoveString() << std::endl;
}
}
void Game::goFixedTime(int tm) {
stopped = false;
/*if(tm >= 200) {
tm -= 100;
}*/
time = tm;
timer.start();
if(option.UCI_AnalyseMode) {
clearCash();
}
variant.clear();
variant.resize(max_depth);
std::vector<uint64_t>hash;
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
nodesCounter = 0;
start_timer = clock();
hasBestMove = false;
BitMove moveCritical = game_board.getRandomMove();
bestMove = moveCritical;
bestScore = 0;
hasBestMove = true;
max_depth = 1;
std::vector<BitMove> bestPV;
for(; timer.getTime() < time; ) {
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
flattenHistory();
negamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_TIME, false, true);
if(/*abs(bestScore) >= (WHITE_WIN - 100) ||*/ stopped) {
break;
}
hasBestMove = true;
++max_depth;
}
end_timer = clock();
if(hasBestMove) {
std::cout << "bestmove " << bestMove.getMoveString() << std::endl;
}
}
void Game::goTournament() {
double tm, inc;
if(game_board.whiteMove) {
tm = wtime;
inc = winc;
} else {
tm = btime;
inc = binc;
}
double k = 50;
if(movestogoEnable) {
k = movestogo;
goFixedTime(tm / k + inc);
} else {
goFixedTime(tm / k + inc - 100);
}
}
bool Game::move(std::string mv) {
MoveArray moves;
game_board.bitBoardMoveGenerator(moves, stress);
for(unsigned int i = 0; i < moves.count; ++i) {
if(moves.moveArray[i].getMoveString() == mv) {
game_board.move(moves.moveArray[i]);
uint8_t color;
if(game_board.whiteMove) {
color = BLACK;
} else {
color = WHITE;
}
if(game_board.inCheck(color)) {
game_board.goBack();
continue;
}
++hash_decrement;
++hashAge;
return true;
}
}
return false;
}
<commit_msg>Чистка хеша при обнаружении мата (возможно, временная мера)<commit_after>#include "game.hpp"
int Game::startGame() {
std::string str;
uciHandler("position startpos");
while(true) {
std::getline(std::cin, str);
if(!uciHandler(str)) {
return 0;
};
}
}
int64_t Game::mtdf(int64_t f, int depth) {
int64_t bound[2] = {-WHITE_WIN, +WHITE_WIN};
do {
double beta = f + (f == bound[0]);
f = negamax(game_board, beta - 1, beta, depth, 0, FIXED_DEPTH, false, true);
bound[f < beta] = f;
} while (bound[0] < bound[1]);
return f;
}
void Game::goFixedDepth() {
if(option.UCI_AnalyseMode || abs(bestScore) >= (WHITE_WIN - 100)) {
clearCash();
}
stopped = false;
variant.clear();
variant.resize(max_depth);
std::vector<uint64_t>hash;
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
nodesCounter = 0;
int max_depth_global = max_depth;
max_depth = 1;
start_timer = clock();
hasBestMove = false;
BitMove moveCritical = game_board.getRandomMove();
bestMove = moveCritical;
hasBestMove = true;
bestScore = 0;
//int64_t f = 0;
//int64_t current_alpha = -WHITE_WIN, current_beta = WHITE_WIN, win_size = 50;
for(; max_depth <= max_depth_global; ++max_depth) {
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
flattenHistory();
//negamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);
/*if(max_depth > 1) {
current_alpha = bestScore - 30;
current_beta = bestScore + 30;
}*/
negamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);
/*std::cout << "!";
if(bestScore <= current_alpha) {
std::cout << "!";
negamax(game_board, -WHITE_WIN, current_beta, max_depth, 0, FIXED_DEPTH, false, true);
} else if(bestScore >= current_beta) {
std::cout << "!";
negamax(game_board, current_alpha, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);
}*/
//f = mtdf(f, max_depth);
hasBestMove = true;
if((abs(bestScore) >= (WHITE_WIN - 100) && max_depth_global < 99) || stopped) {
break;
}
}
end_timer = clock();
if(hasBestMove) {
std::cout << "bestmove " << bestMove.getMoveString() << std::endl;
}
}
void Game::goFixedTime(int tm) {
stopped = false;
/*if(tm >= 200) {
tm -= 100;
}*/
time = tm;
timer.start();
if(option.UCI_AnalyseMode || abs(bestScore) >= (WHITE_WIN - 100)) {
clearCash();
}
variant.clear();
variant.resize(max_depth);
std::vector<uint64_t>hash;
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
nodesCounter = 0;
start_timer = clock();
hasBestMove = false;
BitMove moveCritical = game_board.getRandomMove();
bestMove = moveCritical;
bestScore = 0;
hasBestMove = true;
max_depth = 1;
std::vector<BitMove> bestPV;
for(; timer.getTime() < time; ) {
whiteUp = BLACK_WIN;
blackUp = WHITE_WIN;
flattenHistory();
negamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_TIME, false, true);
if(/*abs(bestScore) >= (WHITE_WIN - 100) ||*/ stopped) {
break;
}
hasBestMove = true;
++max_depth;
}
end_timer = clock();
if(hasBestMove) {
std::cout << "bestmove " << bestMove.getMoveString() << std::endl;
}
}
void Game::goTournament() {
double tm, inc;
if(game_board.whiteMove) {
tm = wtime;
inc = winc;
} else {
tm = btime;
inc = binc;
}
double k = 50;
if(movestogoEnable) {
k = movestogo;
goFixedTime(tm / k + inc);
} else {
goFixedTime(tm / k + inc - 100);
}
}
bool Game::move(std::string mv) {
MoveArray moves;
game_board.bitBoardMoveGenerator(moves, stress);
for(unsigned int i = 0; i < moves.count; ++i) {
if(moves.moveArray[i].getMoveString() == mv) {
game_board.move(moves.moveArray[i]);
uint8_t color;
if(game_board.whiteMove) {
color = BLACK;
} else {
color = WHITE;
}
if(game_board.inCheck(color)) {
game_board.goBack();
continue;
}
++hash_decrement;
++hashAge;
return true;
}
}
return false;
}
<|endoftext|> |
<commit_before>#include "dataset.h"
#include <cmath>
#include <vector>
#include <Eigen/Dense>
#include "eigen_wrappers.h"
namespace InSituFTCalibration {
/**
* Structure representing a joint ft
* and accelerometer measurement.
*/
struct ForceTorqueAccelerometerMeasurement
{
Eigen::Matrix<double,6,1> ft_measure;
Eigen::Vector3d acc_measure;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
struct ForceTorqueAccelerometerDataset::ForceTorqueAccelerometerDatasetPrivateAttributes
{
std::vector<ForceTorqueAccelerometerMeasurement> samples; //< storage of the time series of measurements of the dataset
};
ForceTorqueAccelerometerDataset::ForceTorqueAccelerometerDataset():
pimpl(new ForceTorqueAccelerometerDatasetPrivateAttributes)
{
}
ForceTorqueAccelerometerDataset::ForceTorqueAccelerometerDataset(const ForceTorqueAccelerometerDataset& other)
: pimpl(new ForceTorqueAccelerometerDatasetPrivateAttributes(*(other.pimpl)))
{
}
/*
ForceTorqueAccelerometerDataset::ForceTorqueAccelerometerDataset(ForceTorqueAccelerometerDataset&& other)
: pimpl(0)
{
std::swap(pimpl, other.pimpl);
}*/
ForceTorqueAccelerometerDataset& ForceTorqueAccelerometerDataset::operator=(const ForceTorqueAccelerometerDataset &other) {
if(this != &other) {
*pimpl = *(other.pimpl);
}
return *this;
}
ForceTorqueAccelerometerDataset::~ForceTorqueAccelerometerDataset()
{
delete pimpl;
this->pimpl = 0;
}
void ForceTorqueAccelerometerDataset::reset()
{
this->pimpl->samples.resize(0);
}
int ForceTorqueAccelerometerDataset::getNrOfSamples() const
{
return (int)this->pimpl->samples.size();
}
bool ForceTorqueAccelerometerDataset::addMeasurements(const VecWrapper _ft_measure,
const VecWrapper _acc_measure)
{
ForceTorqueAccelerometerMeasurement sample;
sample.ft_measure = toEigen(_ft_measure);
sample.acc_measure = toEigen(_acc_measure);
this->pimpl->samples.push_back(sample);
return true;
}
bool ForceTorqueAccelerometerDataset::getMeasurements(const int sample,
const VecWrapper ft_measure,
const VecWrapper acc_measure)
{
if( !(sample >= 0 && sample < this->getNrOfSamples()) )
{
return false;
}
toEigen(ft_measure) = this->pimpl->samples[sample].ft_measure;
toEigen(acc_measure) = this->pimpl->samples[sample].acc_measure;
return true;
}
}<commit_msg>More Eigen allignment fixes<commit_after>#include "dataset.h"
#include <cmath>
#include <vector>
#include <Eigen/Dense>
#include "eigen_wrappers.h"
namespace InSituFTCalibration {
/**
* Structure representing a joint ft
* and accelerometer measurement.
*/
struct ForceTorqueAccelerometerMeasurement
{
Eigen::Matrix<double,6,1> ft_measure;
Eigen::Vector3d acc_measure;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
struct ForceTorqueAccelerometerDataset::ForceTorqueAccelerometerDatasetPrivateAttributes
{
std::vector<ForceTorqueAccelerometerMeasurement,Eigen::aligned_allocator<ForceTorqueAccelerometerMeasurement> > samples; //< storage of the time series of measurements of the dataset
};
ForceTorqueAccelerometerDataset::ForceTorqueAccelerometerDataset():
pimpl(new ForceTorqueAccelerometerDatasetPrivateAttributes)
{
}
ForceTorqueAccelerometerDataset::ForceTorqueAccelerometerDataset(const ForceTorqueAccelerometerDataset& other)
: pimpl(new ForceTorqueAccelerometerDatasetPrivateAttributes(*(other.pimpl)))
{
}
/*
ForceTorqueAccelerometerDataset::ForceTorqueAccelerometerDataset(ForceTorqueAccelerometerDataset&& other)
: pimpl(0)
{
std::swap(pimpl, other.pimpl);
}*/
ForceTorqueAccelerometerDataset& ForceTorqueAccelerometerDataset::operator=(const ForceTorqueAccelerometerDataset &other) {
if(this != &other) {
*pimpl = *(other.pimpl);
}
return *this;
}
ForceTorqueAccelerometerDataset::~ForceTorqueAccelerometerDataset()
{
delete pimpl;
this->pimpl = 0;
}
void ForceTorqueAccelerometerDataset::reset()
{
this->pimpl->samples.resize(0);
}
int ForceTorqueAccelerometerDataset::getNrOfSamples() const
{
return (int)this->pimpl->samples.size();
}
bool ForceTorqueAccelerometerDataset::addMeasurements(const VecWrapper _ft_measure,
const VecWrapper _acc_measure)
{
ForceTorqueAccelerometerMeasurement sample;
sample.ft_measure = toEigen(_ft_measure);
sample.acc_measure = toEigen(_acc_measure);
this->pimpl->samples.push_back(sample);
return true;
}
bool ForceTorqueAccelerometerDataset::getMeasurements(const int sample,
const VecWrapper ft_measure,
const VecWrapper acc_measure)
{
if( !(sample >= 0 && sample < this->getNrOfSamples()) )
{
return false;
}
toEigen(ft_measure) = this->pimpl->samples[sample].ft_measure;
toEigen(acc_measure) = this->pimpl->samples[sample].acc_measure;
return true;
}
}<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(PLATFORMDEFINITIONS_HEADER_GUARD_1357924680)
#define PLATFORMDEFINITIONS_HEADER_GUARD_1357924680
#if defined(_MSC_VER)
#include "VCPPDefinitions.hpp"
#elif defined(__GNUC__)
#include "GCCDefinitions.hpp"
#elif defined(_AIX)
#include "AIXDefinitions.hpp"
#elif defined(__hpux)
#include "HPUXDefinitions.hpp"
#elif defined(SOLARIS)
#include "SolarisDefinitions.hpp"
#elif defined(OS390)
#include "OS390Definitions.hpp"
#elif defined(__DECCXX)
#include "TRU64Definitions.hpp"
#elif defined(__INTEL_COMPILER)
#include "IntelDefinitions.hpp"
#else
#error Unknown compiler!
#endif
#include "XalanVersion.hpp"
#if defined(__cplusplus)
// ---------------------------------------------------------------------------
// Define namespace symbols if the compiler supports it.
// ---------------------------------------------------------------------------
#if defined(XALAN_HAS_CPP_NAMESPACE)
#define XALAN_CPP_NAMESPACE_BEGIN namespace XALAN_CPP_NAMESPACE {
#define XALAN_CPP_NAMESPACE_END }
#define XALAN_CPP_NAMESPACE_USE using namespace XALAN_CPP_NAMESPACE;
#define XALAN_CPP_NAMESPACE_QUALIFIER XALAN_CPP_NAMESPACE::
#define XALAN_USING(NAMESPACE,NAME) using NAMESPACE :: NAME;
#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) namespace NAMESPACE { class NAME; }
#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) namespace NAMESPACE { struct NAME; }
namespace XALAN_CPP_NAMESPACE { }
namespace xalanc = XALAN_CPP_NAMESPACE;
#else
#define XALAN_CPP_NAMESPACE_BEGIN
#define XALAN_CPP_NAMESPACE_END
#define XALAN_CPP_NAMESPACE_USE
#define XALAN_CPP_NAMESPACE_QUALIFIER
#define XALAN_USING(NAMESPACE,NAME)
#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) class NAME;
#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) struct NAME;
#if !defined(XALAN_NO_STD_NAMESPACE)
#define XALAN_NO_STD_NAMESPACE
#endif
#endif
#if defined(XALAN_NO_STD_NAMESPACE)
#define XALAN_USING_STD(NAME)
#define XALAN_STD_QUALIFIER
#else
#define XALAN_USING_STD(NAME) using std :: NAME;
#define XALAN_STD_QUALIFIER std ::
#endif
#define XALAN_DECLARE_XALAN_CLASS(NAME) class XALAN_CPP_NAMESPACE_QUALIFIER NAME;
#define XALAN_DECLARE_XALAN_STRUCT(NAME) struct XALAN_CPP_NAMESPACE_QUALIFIER NAME;
#define XALAN_USING_XALAN(NAME) XALAN_USING(xalanc, NAME);
#define XALAN_USING_XERCES(NAME) XALAN_USING(xercesc, NAME)
// Yuck!!!! Have to include this here because there's no way to handle
// the new namespace macros without it!
#include "xercesc/util/XercesDefs.hpp"
#if _XERCES_VERSION < 20200
#define XERCES_CPP_NAMESPACE_QUALIFIER
#define XERCES_CPP_NAMESPACE_BEGIN
#define XERCES_CPP_NAMESPACE_END
#endif
#define XALAN_DECLARE_XERCES_CLASS(NAME) XALAN_DECLARE_CLASS(xercesc, NAME)
#define XALAN_DECLARE_XERCES_STRUCT(NAME) XALAN_DECLARE_STRUCT(xercesc, NAME)
#endif // __cplusplus
#endif // PLATFORMDEFINITIONS_HEADER_GUARD_1357924680
<commit_msg>Fixed some macros.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(PLATFORMDEFINITIONS_HEADER_GUARD_1357924680)
#define PLATFORMDEFINITIONS_HEADER_GUARD_1357924680
#if defined(_MSC_VER)
#include "VCPPDefinitions.hpp"
#elif defined(__GNUC__)
#include "GCCDefinitions.hpp"
#elif defined(_AIX)
#include "AIXDefinitions.hpp"
#elif defined(__hpux)
#include "HPUXDefinitions.hpp"
#elif defined(SOLARIS)
#include "SolarisDefinitions.hpp"
#elif defined(OS390)
#include "OS390Definitions.hpp"
#elif defined(__DECCXX)
#include "TRU64Definitions.hpp"
#elif defined(__INTEL_COMPILER)
#include "IntelDefinitions.hpp"
#else
#error Unknown compiler!
#endif
#include "XalanVersion.hpp"
#if defined(__cplusplus)
// ---------------------------------------------------------------------------
// Define namespace symbols if the compiler supports it.
// ---------------------------------------------------------------------------
#if defined(XALAN_HAS_CPP_NAMESPACE)
#define XALAN_CPP_NAMESPACE_BEGIN namespace XALAN_CPP_NAMESPACE {
#define XALAN_CPP_NAMESPACE_END }
#define XALAN_CPP_NAMESPACE_USE using namespace XALAN_CPP_NAMESPACE;
#define XALAN_CPP_NAMESPACE_QUALIFIER XALAN_CPP_NAMESPACE::
#define XALAN_USING(NAMESPACE,NAME) using NAMESPACE :: NAME;
#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) namespace NAMESPACE { class NAME; }
#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) namespace NAMESPACE { struct NAME; }
namespace XALAN_CPP_NAMESPACE { }
namespace xalanc = XALAN_CPP_NAMESPACE;
#else
#define XALAN_CPP_NAMESPACE_BEGIN
#define XALAN_CPP_NAMESPACE_END
#define XALAN_CPP_NAMESPACE_USE
#define XALAN_CPP_NAMESPACE_QUALIFIER
#define XALAN_USING(NAMESPACE,NAME)
#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) class NAME;
#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) struct NAME;
#if !defined(XALAN_NO_STD_NAMESPACE)
#define XALAN_NO_STD_NAMESPACE
#endif
#endif
#if defined(XALAN_NO_STD_NAMESPACE)
#define XALAN_USING_STD(NAME)
#define XALAN_STD_QUALIFIER
#else
#define XALAN_USING_STD(NAME) using std :: NAME;
#define XALAN_STD_QUALIFIER std ::
#endif
#define XALAN_DECLARE_XALAN_CLASS(NAME) class XALAN_CPP_NAMESPACE_QUALIFIER NAME;
#define XALAN_DECLARE_XALAN_STRUCT(NAME) struct XALAN_CPP_NAMESPACE_QUALIFIER NAME;
#define XALAN_USING_XALAN(NAME) XALAN_USING(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_USING_XERCES(NAME) XALAN_USING(XALAN_CPP_NAMESPACE, NAME)
// Yuck!!!! Have to include this here because there's no way to handle
// the new namespace macros without it!
#include "xercesc/util/XercesDefs.hpp"
#if _XERCES_VERSION < 20200
#define XERCES_CPP_NAMESPACE_QUALIFIER
#define XERCES_CPP_NAMESPACE_BEGIN
#define XERCES_CPP_NAMESPACE_END
#endif
#define XALAN_DECLARE_XERCES_CLASS(NAME) XALAN_DECLARE_CLASS(XERCES_CPP_NAMESPACE, NAME)
#define XALAN_DECLARE_XERCES_STRUCT(NAME) XALAN_DECLARE_STRUCT(XERCES_CPP_NAMESPACE, NAME)
#endif // __cplusplus
#endif // PLATFORMDEFINITIONS_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
This program 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 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreRenderQueueSortingGrouping.h"
#include "OgreException.h"
namespace Ogre {
// Init statics
RadixSort<QueuedRenderableCollection::RenderablePassList,
RenderablePass, uint32> QueuedRenderableCollection::msRadixSorter1;
RadixSort<QueuedRenderableCollection::RenderablePassList,
RenderablePass, float> QueuedRenderableCollection::msRadixSorter2;
//-----------------------------------------------------------------------
RenderPriorityGroup::RenderPriorityGroup(RenderQueueGroup* parent,
bool splitPassesByLightingType,
bool splitNoShadowPasses,
bool shadowCastersNotReceivers)
: mParent(parent)
, mSplitPassesByLightingType(splitPassesByLightingType)
, mSplitNoShadowPasses(splitNoShadowPasses)
, mShadowCastersNotReceivers(shadowCastersNotReceivers)
{
// Initialise collection sorting options
// this can become dynamic according to invocation later
defaultOrganisationMode();
// Transparents will always be sorted this way
mTransparents.addOrganisationMode(QueuedRenderableCollection::OM_SORT_DESCENDING);
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::resetOrganisationModes(void)
{
mSolidsBasic.resetOrganisationModes();
mSolidsDiffuseSpecular.resetOrganisationModes();
mSolidsDecal.resetOrganisationModes();
mSolidsNoShadowReceive.resetOrganisationModes();
mTransparentsUnsorted.resetOrganisationModes();
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::addOrganisationMode(QueuedRenderableCollection::OrganisationMode om)
{
mSolidsBasic.addOrganisationMode(om);
mSolidsDiffuseSpecular.addOrganisationMode(om);
mSolidsDecal.addOrganisationMode(om);
mSolidsNoShadowReceive.addOrganisationMode(om);
mTransparentsUnsorted.addOrganisationMode(om);
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::defaultOrganisationMode(void)
{
resetOrganisationModes();
addOrganisationMode(QueuedRenderableCollection::OM_PASS_GROUP);
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::addRenderable(Renderable* rend, Technique* pTech)
{
// Transparent and depth/colour settings mean depth sorting is required?
// Note: colour write disabled with depth check/write enabled means
// setup depth buffer for other passes use.
if (pTech->isTransparent() &&
(!pTech->isDepthWriteEnabled() ||
!pTech->isDepthCheckEnabled() ||
pTech->hasColourWriteDisabled()))
{
if (pTech->isTransparentSortingEnabled())
addTransparentRenderable(pTech, rend);
else
addUnsortedTransparentRenderable(pTech, rend);
}
else
{
if (mSplitNoShadowPasses &&
mParent->getShadowsEnabled() &&
(!pTech->getParent()->getReceiveShadows() ||
rend->getCastsShadows() && mShadowCastersNotReceivers))
{
// Add solid renderable and add passes to no-shadow group
addSolidRenderable(pTech, rend, true);
}
else
{
if (mSplitPassesByLightingType && mParent->getShadowsEnabled())
{
addSolidRenderableSplitByLightType(pTech, rend);
}
else
{
addSolidRenderable(pTech, rend, false);
}
}
}
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::addSolidRenderable(Technique* pTech,
Renderable* rend, bool addToNoShadow)
{
Technique::PassIterator pi = pTech->getPassIterator();
QueuedRenderableCollection* collection;
if (addToNoShadow)
{
collection = &mSolidsNoShadowReceive;
}
else
{
collection = &mSolidsBasic;
}
while (pi.hasMoreElements())
{
// Insert into solid list
Pass* p = pi.getNext();
collection->addRenderable(p, rend);
}
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::addSolidRenderableSplitByLightType(Technique* pTech,
Renderable* rend)
{
// Divide the passes into the 3 categories
Technique::IlluminationPassIterator pi =
pTech->getIlluminationPassIterator();
while (pi.hasMoreElements())
{
// Insert into solid list
IlluminationPass* p = pi.getNext();
QueuedRenderableCollection* collection;
switch(p->stage)
{
case IS_AMBIENT:
collection = &mSolidsBasic;
break;
case IS_PER_LIGHT:
collection = &mSolidsDiffuseSpecular;
break;
case IS_DECAL:
collection = &mSolidsDecal;
break;
default:
assert(false); // should never happen
};
collection->addRenderable(p->pass, rend);
}
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::addUnsortedTransparentRenderable(Technique* pTech, Renderable* rend)
{
Technique::PassIterator pi = pTech->getPassIterator();
while (pi.hasMoreElements())
{
// Insert into transparent list
mTransparentsUnsorted.addRenderable(pi.getNext(), rend);
}
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::addTransparentRenderable(Technique* pTech, Renderable* rend)
{
Technique::PassIterator pi = pTech->getPassIterator();
while (pi.hasMoreElements())
{
// Insert into transparent list
mTransparents.addRenderable(pi.getNext(), rend);
}
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::removePassEntry(Pass* p)
{
mSolidsBasic.removePassGroup(p);
mSolidsDiffuseSpecular.removePassGroup(p);
mSolidsNoShadowReceive.removePassGroup(p);
mSolidsDecal.removePassGroup(p);
mTransparentsUnsorted.removePassGroup(p);
mTransparents.removePassGroup(p); // shouldn't be any, but for completeness
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::clear(void)
{
// Delete queue groups which are using passes which are to be
// deleted, we won't need these any more and they clutter up
// the list and can cause problems with future clones
{
// Hmm, a bit hacky but least obtrusive for now
OGRE_LOCK_MUTEX(Pass::msPassGraveyardMutex)
const Pass::PassSet& graveyardList = Pass::getPassGraveyard();
Pass::PassSet::const_iterator gi, giend;
giend = graveyardList.end();
for (gi = graveyardList.begin(); gi != giend; ++gi)
{
removePassEntry(*gi);
}
}
// Now remove any dirty passes, these will have their hashes recalculated
// by the parent queue after all groups have been processed
// If we don't do this, the std::map will become inconsistent for new insterts
{
// Hmm, a bit hacky but least obtrusive for now
OGRE_LOCK_MUTEX(Pass::msDirtyHashListMutex)
const Pass::PassSet& dirtyList = Pass::getDirtyHashList();
Pass::PassSet::const_iterator di, diend;
diend = dirtyList.end();
for (di = dirtyList.begin(); di != diend; ++di)
{
removePassEntry(*di);
}
}
// NB we do NOT clear the graveyard or the dirty list here, because
// it needs to be acted on for all groups, the parent queue takes
// care of this afterwards
// Now empty the remaining collections
// Note that groups don't get deleted, just emptied hence the difference
// between the pass groups which are removed above, and clearing done
// here
mSolidsBasic.clear();
mSolidsDecal.clear();
mSolidsDiffuseSpecular.clear();
mSolidsNoShadowReceive.clear();
mTransparentsUnsorted.clear();
mTransparents.clear();
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::sort(const Camera* cam)
{
mSolidsBasic.sort(cam);
mSolidsDecal.sort(cam);
mSolidsDiffuseSpecular.sort(cam);
mSolidsNoShadowReceive.sort(cam);
mTransparentsUnsorted.sort(cam);
mTransparents.sort(cam);
}
//-----------------------------------------------------------------------
QueuedRenderableCollection::QueuedRenderableCollection(void)
:mOrganisationMode(0)
{
}
//-----------------------------------------------------------------------
QueuedRenderableCollection::~QueuedRenderableCollection(void)
{
// destroy all the pass map entries (rather than clearing)
PassGroupRenderableMap::iterator i, iend;
iend = mGrouped.end();
for (i = mGrouped.begin(); i != iend; ++i)
{
// Free the list associated with this pass
OGRE_DELETE_T(i->second, RenderableList, MEMCATEGORY_SCENE_CONTROL);
}
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::clear(void)
{
PassGroupRenderableMap::iterator i, iend;
iend = mGrouped.end();
for (i = mGrouped.begin(); i != iend; ++i)
{
// Clear the list associated with this pass, but leave the pass entry
i->second->clear();
}
// Clear sorted list
mSortedDescending.clear();
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::removePassGroup(Pass* p)
{
PassGroupRenderableMap::iterator i;
i = mGrouped.find(p);
if (i != mGrouped.end())
{
// free memory
OGRE_DELETE i->second;
// erase from map
mGrouped.erase(i);
}
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::sort(const Camera* cam)
{
// ascending and descending sort both set bit 1
if (mOrganisationMode & OM_SORT_DESCENDING)
{
// We can either use a stable_sort and the 'less' implementation,
// or a 2-pass radix sort (once by pass, then by distance, since
// radix sorting is inherently stable this will work)
// We use stable_sort if the number of items is 512 or less, since
// the complexity of the radix sort is approximately O(10N), since
// each sort is O(5N) (1 pass histograms, 4 passes sort)
// Since stable_sort has a worst-case performance of O(N(logN)^2)
// the performance tipping point is from about 1500 items, but in
// stable_sorts best-case scenario O(NlogN) it would be much higher.
// Take a stab at 2000 items.
if (mSortedDescending.size() > 2000)
{
// sort by pass
msRadixSorter1.sort(mSortedDescending, RadixSortFunctorPass());
// sort by depth
msRadixSorter2.sort(mSortedDescending, RadixSortFunctorDistance(cam));
}
else
{
std::stable_sort(
mSortedDescending.begin(), mSortedDescending.end(),
DepthSortDescendingLess(cam));
}
}
// Nothing needs to be done for pass groups, they auto-organise
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::addRenderable(Pass* pass, Renderable* rend)
{
// ascending and descending sort both set bit 1
if (mOrganisationMode & OM_SORT_DESCENDING)
{
mSortedDescending.push_back(RenderablePass(rend, pass));
}
if (mOrganisationMode & OM_PASS_GROUP)
{
PassGroupRenderableMap::iterator i = mGrouped.find(pass);
if (i == mGrouped.end())
{
std::pair<PassGroupRenderableMap::iterator, bool> retPair;
// Create new pass entry, build a new list
// Note that this pass and list are never destroyed until the
// engine shuts down, or a pass is destroyed or has it's hash
// recalculated, although the lists will be cleared
retPair = mGrouped.insert(
PassGroupRenderableMap::value_type(
pass, OGRE_NEW_T(RenderableList, MEMCATEGORY_SCENE_CONTROL)() ));
assert(retPair.second &&
"Error inserting new pass entry into PassGroupRenderableMap");
i = retPair.first;
}
// Insert renderable
i->second->push_back(rend);
}
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::acceptVisitor(
QueuedRenderableVisitor* visitor, OrganisationMode om) const
{
if ((om & mOrganisationMode) == 0)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Organisation mode requested in acceptVistor was not notified "
"to this class ahead of time, therefore may not be supported.",
"QueuedRenderableCollection::acceptVisitor");
}
switch(om)
{
case OM_PASS_GROUP:
acceptVisitorGrouped(visitor);
break;
case OM_SORT_DESCENDING:
acceptVisitorDescending(visitor);
break;
case OM_SORT_ASCENDING:
acceptVisitorAscending(visitor);
break;
}
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::acceptVisitorGrouped(
QueuedRenderableVisitor* visitor) const
{
PassGroupRenderableMap::const_iterator ipass, ipassend;
ipassend = mGrouped.end();
for (ipass = mGrouped.begin(); ipass != ipassend; ++ipass)
{
// Fast bypass if this group is now empty
if (ipass->second->empty()) continue;
// Visit Pass - allow skip
if (!visitor->visit(ipass->first))
continue;
RenderableList* rendList = ipass->second;
RenderableList::const_iterator irend, irendend;
irendend = rendList->end();
for (irend = rendList->begin(); irend != irendend; ++irend)
{
// Visit Renderable
visitor->visit(const_cast<Renderable*>(*irend));
}
}
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::acceptVisitorDescending(
QueuedRenderableVisitor* visitor) const
{
// List is already in descending order, so iterate forward
RenderablePassList::const_iterator i, iend;
iend = mSortedDescending.end();
for (i = mSortedDescending.begin(); i != iend; ++i)
{
visitor->visit(const_cast<RenderablePass*>(&(*i)));
}
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::acceptVisitorAscending(
QueuedRenderableVisitor* visitor) const
{
// List is in descending order, so iterate in reverse
RenderablePassList::const_reverse_iterator i, iend;
iend = mSortedDescending.rend();
for (i = mSortedDescending.rbegin(); i != iend; ++i)
{
visitor->visit(const_cast<RenderablePass*>(&(*i)));
}
}
}
<commit_msg>Fixed mismatch deallocation in QueuedRenderableCollection::removePassGroup<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
This program 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 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreRenderQueueSortingGrouping.h"
#include "OgreException.h"
namespace Ogre {
// Init statics
RadixSort<QueuedRenderableCollection::RenderablePassList,
RenderablePass, uint32> QueuedRenderableCollection::msRadixSorter1;
RadixSort<QueuedRenderableCollection::RenderablePassList,
RenderablePass, float> QueuedRenderableCollection::msRadixSorter2;
//-----------------------------------------------------------------------
RenderPriorityGroup::RenderPriorityGroup(RenderQueueGroup* parent,
bool splitPassesByLightingType,
bool splitNoShadowPasses,
bool shadowCastersNotReceivers)
: mParent(parent)
, mSplitPassesByLightingType(splitPassesByLightingType)
, mSplitNoShadowPasses(splitNoShadowPasses)
, mShadowCastersNotReceivers(shadowCastersNotReceivers)
{
// Initialise collection sorting options
// this can become dynamic according to invocation later
defaultOrganisationMode();
// Transparents will always be sorted this way
mTransparents.addOrganisationMode(QueuedRenderableCollection::OM_SORT_DESCENDING);
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::resetOrganisationModes(void)
{
mSolidsBasic.resetOrganisationModes();
mSolidsDiffuseSpecular.resetOrganisationModes();
mSolidsDecal.resetOrganisationModes();
mSolidsNoShadowReceive.resetOrganisationModes();
mTransparentsUnsorted.resetOrganisationModes();
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::addOrganisationMode(QueuedRenderableCollection::OrganisationMode om)
{
mSolidsBasic.addOrganisationMode(om);
mSolidsDiffuseSpecular.addOrganisationMode(om);
mSolidsDecal.addOrganisationMode(om);
mSolidsNoShadowReceive.addOrganisationMode(om);
mTransparentsUnsorted.addOrganisationMode(om);
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::defaultOrganisationMode(void)
{
resetOrganisationModes();
addOrganisationMode(QueuedRenderableCollection::OM_PASS_GROUP);
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::addRenderable(Renderable* rend, Technique* pTech)
{
// Transparent and depth/colour settings mean depth sorting is required?
// Note: colour write disabled with depth check/write enabled means
// setup depth buffer for other passes use.
if (pTech->isTransparent() &&
(!pTech->isDepthWriteEnabled() ||
!pTech->isDepthCheckEnabled() ||
pTech->hasColourWriteDisabled()))
{
if (pTech->isTransparentSortingEnabled())
addTransparentRenderable(pTech, rend);
else
addUnsortedTransparentRenderable(pTech, rend);
}
else
{
if (mSplitNoShadowPasses &&
mParent->getShadowsEnabled() &&
(!pTech->getParent()->getReceiveShadows() ||
rend->getCastsShadows() && mShadowCastersNotReceivers))
{
// Add solid renderable and add passes to no-shadow group
addSolidRenderable(pTech, rend, true);
}
else
{
if (mSplitPassesByLightingType && mParent->getShadowsEnabled())
{
addSolidRenderableSplitByLightType(pTech, rend);
}
else
{
addSolidRenderable(pTech, rend, false);
}
}
}
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::addSolidRenderable(Technique* pTech,
Renderable* rend, bool addToNoShadow)
{
Technique::PassIterator pi = pTech->getPassIterator();
QueuedRenderableCollection* collection;
if (addToNoShadow)
{
collection = &mSolidsNoShadowReceive;
}
else
{
collection = &mSolidsBasic;
}
while (pi.hasMoreElements())
{
// Insert into solid list
Pass* p = pi.getNext();
collection->addRenderable(p, rend);
}
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::addSolidRenderableSplitByLightType(Technique* pTech,
Renderable* rend)
{
// Divide the passes into the 3 categories
Technique::IlluminationPassIterator pi =
pTech->getIlluminationPassIterator();
while (pi.hasMoreElements())
{
// Insert into solid list
IlluminationPass* p = pi.getNext();
QueuedRenderableCollection* collection;
switch(p->stage)
{
case IS_AMBIENT:
collection = &mSolidsBasic;
break;
case IS_PER_LIGHT:
collection = &mSolidsDiffuseSpecular;
break;
case IS_DECAL:
collection = &mSolidsDecal;
break;
default:
assert(false); // should never happen
};
collection->addRenderable(p->pass, rend);
}
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::addUnsortedTransparentRenderable(Technique* pTech, Renderable* rend)
{
Technique::PassIterator pi = pTech->getPassIterator();
while (pi.hasMoreElements())
{
// Insert into transparent list
mTransparentsUnsorted.addRenderable(pi.getNext(), rend);
}
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::addTransparentRenderable(Technique* pTech, Renderable* rend)
{
Technique::PassIterator pi = pTech->getPassIterator();
while (pi.hasMoreElements())
{
// Insert into transparent list
mTransparents.addRenderable(pi.getNext(), rend);
}
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::removePassEntry(Pass* p)
{
mSolidsBasic.removePassGroup(p);
mSolidsDiffuseSpecular.removePassGroup(p);
mSolidsNoShadowReceive.removePassGroup(p);
mSolidsDecal.removePassGroup(p);
mTransparentsUnsorted.removePassGroup(p);
mTransparents.removePassGroup(p); // shouldn't be any, but for completeness
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::clear(void)
{
// Delete queue groups which are using passes which are to be
// deleted, we won't need these any more and they clutter up
// the list and can cause problems with future clones
{
// Hmm, a bit hacky but least obtrusive for now
OGRE_LOCK_MUTEX(Pass::msPassGraveyardMutex)
const Pass::PassSet& graveyardList = Pass::getPassGraveyard();
Pass::PassSet::const_iterator gi, giend;
giend = graveyardList.end();
for (gi = graveyardList.begin(); gi != giend; ++gi)
{
removePassEntry(*gi);
}
}
// Now remove any dirty passes, these will have their hashes recalculated
// by the parent queue after all groups have been processed
// If we don't do this, the std::map will become inconsistent for new insterts
{
// Hmm, a bit hacky but least obtrusive for now
OGRE_LOCK_MUTEX(Pass::msDirtyHashListMutex)
const Pass::PassSet& dirtyList = Pass::getDirtyHashList();
Pass::PassSet::const_iterator di, diend;
diend = dirtyList.end();
for (di = dirtyList.begin(); di != diend; ++di)
{
removePassEntry(*di);
}
}
// NB we do NOT clear the graveyard or the dirty list here, because
// it needs to be acted on for all groups, the parent queue takes
// care of this afterwards
// Now empty the remaining collections
// Note that groups don't get deleted, just emptied hence the difference
// between the pass groups which are removed above, and clearing done
// here
mSolidsBasic.clear();
mSolidsDecal.clear();
mSolidsDiffuseSpecular.clear();
mSolidsNoShadowReceive.clear();
mTransparentsUnsorted.clear();
mTransparents.clear();
}
//-----------------------------------------------------------------------
void RenderPriorityGroup::sort(const Camera* cam)
{
mSolidsBasic.sort(cam);
mSolidsDecal.sort(cam);
mSolidsDiffuseSpecular.sort(cam);
mSolidsNoShadowReceive.sort(cam);
mTransparentsUnsorted.sort(cam);
mTransparents.sort(cam);
}
//-----------------------------------------------------------------------
QueuedRenderableCollection::QueuedRenderableCollection(void)
:mOrganisationMode(0)
{
}
//-----------------------------------------------------------------------
QueuedRenderableCollection::~QueuedRenderableCollection(void)
{
// destroy all the pass map entries (rather than clearing)
PassGroupRenderableMap::iterator i, iend;
iend = mGrouped.end();
for (i = mGrouped.begin(); i != iend; ++i)
{
// Free the list associated with this pass
OGRE_DELETE_T(i->second, RenderableList, MEMCATEGORY_SCENE_CONTROL);
}
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::clear(void)
{
PassGroupRenderableMap::iterator i, iend;
iend = mGrouped.end();
for (i = mGrouped.begin(); i != iend; ++i)
{
// Clear the list associated with this pass, but leave the pass entry
i->second->clear();
}
// Clear sorted list
mSortedDescending.clear();
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::removePassGroup(Pass* p)
{
PassGroupRenderableMap::iterator i;
i = mGrouped.find(p);
if (i != mGrouped.end())
{
// free memory
OGRE_DELETE_T(i->second, RenderableList, MEMCATEGORY_SCENE_CONTROL);
// erase from map
mGrouped.erase(i);
}
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::sort(const Camera* cam)
{
// ascending and descending sort both set bit 1
if (mOrganisationMode & OM_SORT_DESCENDING)
{
// We can either use a stable_sort and the 'less' implementation,
// or a 2-pass radix sort (once by pass, then by distance, since
// radix sorting is inherently stable this will work)
// We use stable_sort if the number of items is 512 or less, since
// the complexity of the radix sort is approximately O(10N), since
// each sort is O(5N) (1 pass histograms, 4 passes sort)
// Since stable_sort has a worst-case performance of O(N(logN)^2)
// the performance tipping point is from about 1500 items, but in
// stable_sorts best-case scenario O(NlogN) it would be much higher.
// Take a stab at 2000 items.
if (mSortedDescending.size() > 2000)
{
// sort by pass
msRadixSorter1.sort(mSortedDescending, RadixSortFunctorPass());
// sort by depth
msRadixSorter2.sort(mSortedDescending, RadixSortFunctorDistance(cam));
}
else
{
std::stable_sort(
mSortedDescending.begin(), mSortedDescending.end(),
DepthSortDescendingLess(cam));
}
}
// Nothing needs to be done for pass groups, they auto-organise
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::addRenderable(Pass* pass, Renderable* rend)
{
// ascending and descending sort both set bit 1
if (mOrganisationMode & OM_SORT_DESCENDING)
{
mSortedDescending.push_back(RenderablePass(rend, pass));
}
if (mOrganisationMode & OM_PASS_GROUP)
{
PassGroupRenderableMap::iterator i = mGrouped.find(pass);
if (i == mGrouped.end())
{
std::pair<PassGroupRenderableMap::iterator, bool> retPair;
// Create new pass entry, build a new list
// Note that this pass and list are never destroyed until the
// engine shuts down, or a pass is destroyed or has it's hash
// recalculated, although the lists will be cleared
retPair = mGrouped.insert(
PassGroupRenderableMap::value_type(
pass, OGRE_NEW_T(RenderableList, MEMCATEGORY_SCENE_CONTROL)() ));
assert(retPair.second &&
"Error inserting new pass entry into PassGroupRenderableMap");
i = retPair.first;
}
// Insert renderable
i->second->push_back(rend);
}
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::acceptVisitor(
QueuedRenderableVisitor* visitor, OrganisationMode om) const
{
if ((om & mOrganisationMode) == 0)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Organisation mode requested in acceptVistor was not notified "
"to this class ahead of time, therefore may not be supported.",
"QueuedRenderableCollection::acceptVisitor");
}
switch(om)
{
case OM_PASS_GROUP:
acceptVisitorGrouped(visitor);
break;
case OM_SORT_DESCENDING:
acceptVisitorDescending(visitor);
break;
case OM_SORT_ASCENDING:
acceptVisitorAscending(visitor);
break;
}
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::acceptVisitorGrouped(
QueuedRenderableVisitor* visitor) const
{
PassGroupRenderableMap::const_iterator ipass, ipassend;
ipassend = mGrouped.end();
for (ipass = mGrouped.begin(); ipass != ipassend; ++ipass)
{
// Fast bypass if this group is now empty
if (ipass->second->empty()) continue;
// Visit Pass - allow skip
if (!visitor->visit(ipass->first))
continue;
RenderableList* rendList = ipass->second;
RenderableList::const_iterator irend, irendend;
irendend = rendList->end();
for (irend = rendList->begin(); irend != irendend; ++irend)
{
// Visit Renderable
visitor->visit(const_cast<Renderable*>(*irend));
}
}
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::acceptVisitorDescending(
QueuedRenderableVisitor* visitor) const
{
// List is already in descending order, so iterate forward
RenderablePassList::const_iterator i, iend;
iend = mSortedDescending.end();
for (i = mSortedDescending.begin(); i != iend; ++i)
{
visitor->visit(const_cast<RenderablePass*>(&(*i)));
}
}
//-----------------------------------------------------------------------
void QueuedRenderableCollection::acceptVisitorAscending(
QueuedRenderableVisitor* visitor) const
{
// List is in descending order, so iterate in reverse
RenderablePassList::const_reverse_iterator i, iend;
iend = mSortedDescending.rend();
for (i = mSortedDescending.rbegin(); i != iend; ++i)
{
visitor->visit(const_cast<RenderablePass*>(&(*i)));
}
}
}
<|endoftext|> |
<commit_before>#include <map>
#include <iostream>
#include "Shell.h"
#include "PadCommand.h"
#include "joystick/Joystick.h"
#include <json/json.h>
static std::string file_get_contents(std::string path)
{
std::ifstream ifs(path.c_str());
std::string content((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
return content;
}
namespace RhIO
{
std::string PadCommand::getName()
{
return "pad";
}
std::string PadCommand::getDesc()
{
return "Dump/Use the joystick";
}
void PadCommand::process(std::vector<std::string> args)
{
Joystick js;
if (js.open()) {
if (args.size() == 0) {
// Mode dump
Terminal::setColor("white", true);
std::cout << "Dumping joystick events" << std::endl;
Terminal::clear();
while (!shell->hasInput()) {
Joystick::JoystickEvent evt;
if (js.getEvent(&evt)) {
if (evt.number != 24 && evt.number != 25 && evt.number != 26) {
if (evt.type == JS_EVENT_AXIS) {
std::cout << "AXIS: " << (int)evt.number << " -> " << evt.getValue() << std::endl;
} else {
std::cout << "BTN: " << (int)evt.number << " -> " << evt.isPressed() << std::endl;
}
}
}
}
} else {
std::map<int, PadIO> pads = import(args[0]);
while (!shell->hasInput()) {
Joystick::JoystickEvent evt;
if (js.getEvent(&evt)) {
int id = evt.number;
if (evt.type == JS_EVENT_AXIS) {
id += 100;
}
if (pads.count(id)) {
auto &pad = pads[id];
if (pad.type == PAD_AXIS || pad.type == PAD_BUTTON) {
pad.value = evt.value;
if (pad.type == PAD_AXIS) {
pad.fvalue = evt.getValue();
float delta = (pad.max-pad.min)/2;
pad.fvalue *= delta;
pad.fvalue += (pad.min+pad.max)/2.0;
}
update(pad);
} else if (evt.value == 1) {
if (pad.type == PAD_TOGGLE) {
pad.value = !pad.value;
}
shell->getFromServer(pad.node);
pad.fvalue = Node::toNumber(pad.node.value);
if (pad.type == PAD_INCREMENT) {
pad.fvalue += pad.step;
}
if (pad.type == PAD_DECREMENT) {
pad.fvalue -= pad.step;
}
update(pad);
}
}
}
}
}
} else {
throw std::runtime_error("Can't open the joypad");
}
js.close();
}
void PadCommand::update(PadIO &pad)
{
if (pad.type == PAD_AXIS || pad.type == PAD_INCREMENT || pad.type == PAD_DECREMENT) {
shell->setFromNumber(pad.node, pad.fvalue);
} else {
shell->setFromNumber(pad.node, pad.value);
}
}
std::map<int, PadIO> PadCommand::import(std::string name)
{
std::map<int, PadIO> pads;
// Loading file
char *homedir;
std::string path;
if ((homedir = getenv("HOME")) != NULL) {
path = homedir;
path += "/.rhio/";
path += name;
}
Json::Value value;
Json::Reader reader;
if (reader.parse(file_get_contents(path), value)) {
if (value.isArray()) {
for (unsigned int k=0; k<value.size(); k++) {
auto entry = value[k];
if (entry.isObject()) {
if (entry.isMember("type") && entry.isMember("number") && entry.isMember("param")) {
PadIO pad;
pad.value = 0;
pad.fvalue = 0;
pad.step = 1;
pad.id = entry["number"].asInt();
pad.param = entry["param"].asString();
pad.node = shell->getNodeValue(pad.param);
if (pad.node.value == NULL) {
std::stringstream ss;
ss << "Can't find node " << pad.param;
throw std::runtime_error(ss.str());
}
std::string type = entry["type"].asString();
if (type == "axis") {
pad.type = PAD_AXIS;
pad.id += 100;
} else if (type == "toggle") {
pad.type = PAD_TOGGLE;
} else if (type == "increment") {
pad.type = PAD_INCREMENT;
} else if (type == "decrement") {
pad.type = PAD_DECREMENT;
} else {
pad.type = PAD_BUTTON;
}
if (entry.isMember("range") && entry["range"].isArray() && entry["range"].size()==2) {
pad.min = entry["range"][0].asFloat();
pad.max = entry["range"][1].asFloat();
}
if (entry.isMember("step") && entry["step"].isNumeric()) {
pad.step = entry["step"].asFloat();
}
pads[pad.id] = pad;
}
}
}
}
} else {
std::stringstream ss;
ss << "Error while loading " << path << std::endl;
ss << reader.getFormatedErrorMessages();
throw std::runtime_error(ss.str());
}
return pads;
}
}
<commit_msg>[Joystick] Ignoring other events<commit_after>#include <map>
#include <iostream>
#include "Shell.h"
#include "PadCommand.h"
#include "joystick/Joystick.h"
#include <json/json.h>
static std::string file_get_contents(std::string path)
{
std::ifstream ifs(path.c_str());
std::string content((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
return content;
}
namespace RhIO
{
std::string PadCommand::getName()
{
return "pad";
}
std::string PadCommand::getDesc()
{
return "Dump/Use the joystick";
}
void PadCommand::process(std::vector<std::string> args)
{
Joystick js;
if (js.open()) {
if (args.size() == 0) {
// Mode dump
Terminal::setColor("white", true);
std::cout << "Dumping joystick events" << std::endl;
Terminal::clear();
while (!shell->hasInput()) {
Joystick::JoystickEvent evt;
if (js.getEvent(&evt)) {
if (evt.number != 24 && evt.number != 25 && evt.number != 26) {
if (evt.type == JS_EVENT_AXIS) {
std::cout << "AXIS: " << (int)evt.number << " -> " << evt.getValue() << std::endl;
} else {
std::cout << "BTN: " << (int)evt.number << " -> " << evt.isPressed() << std::endl;
}
}
}
}
} else {
std::map<int, PadIO> pads = import(args[0]);
while (!shell->hasInput()) {
Joystick::JoystickEvent evt;
if (js.getEvent(&evt)) {
int id = evt.number;
if (evt.type != JS_EVENT_AXIS && evt.type != JS_EVENT_BUTTON) {
continue;
}
if (evt.type == JS_EVENT_AXIS) {
id += 100;
}
if (pads.count(id)) {
auto &pad = pads[id];
if (pad.type == PAD_AXIS || pad.type == PAD_BUTTON) {
pad.value = evt.value;
if (pad.type == PAD_AXIS) {
pad.fvalue = evt.getValue();
float delta = (pad.max-pad.min)/2;
pad.fvalue *= delta;
pad.fvalue += (pad.min+pad.max)/2.0;
}
update(pad);
} else if (evt.value == 1) {
if (pad.type == PAD_TOGGLE) {
pad.value = !pad.value;
}
shell->getFromServer(pad.node);
pad.fvalue = Node::toNumber(pad.node.value);
if (pad.type == PAD_INCREMENT) {
pad.fvalue += pad.step;
}
if (pad.type == PAD_DECREMENT) {
pad.fvalue -= pad.step;
}
update(pad);
}
}
}
}
}
} else {
throw std::runtime_error("Can't open the joypad");
}
js.close();
}
void PadCommand::update(PadIO &pad)
{
if (pad.type == PAD_AXIS || pad.type == PAD_INCREMENT || pad.type == PAD_DECREMENT) {
shell->setFromNumber(pad.node, pad.fvalue);
} else {
shell->setFromNumber(pad.node, pad.value);
}
}
std::map<int, PadIO> PadCommand::import(std::string name)
{
std::map<int, PadIO> pads;
// Loading file
char *homedir;
std::string path;
if ((homedir = getenv("HOME")) != NULL) {
path = homedir;
path += "/.rhio/";
path += name;
}
Json::Value value;
Json::Reader reader;
if (reader.parse(file_get_contents(path), value)) {
if (value.isArray()) {
for (unsigned int k=0; k<value.size(); k++) {
auto entry = value[k];
if (entry.isObject()) {
if (entry.isMember("type") && entry.isMember("number") && entry.isMember("param")) {
PadIO pad;
pad.value = 0;
pad.fvalue = 0;
pad.step = 1;
pad.id = entry["number"].asInt();
pad.param = entry["param"].asString();
pad.node = shell->getNodeValue(pad.param);
if (pad.node.value == NULL) {
std::stringstream ss;
ss << "Can't find node " << pad.param;
throw std::runtime_error(ss.str());
}
std::string type = entry["type"].asString();
if (type == "axis") {
pad.type = PAD_AXIS;
pad.id += 100;
} else if (type == "toggle") {
pad.type = PAD_TOGGLE;
} else if (type == "increment") {
pad.type = PAD_INCREMENT;
} else if (type == "decrement") {
pad.type = PAD_DECREMENT;
} else {
pad.type = PAD_BUTTON;
}
if (entry.isMember("range") && entry["range"].isArray() && entry["range"].size()==2) {
pad.min = entry["range"][0].asFloat();
pad.max = entry["range"][1].asFloat();
}
if (entry.isMember("step") && entry["step"].isNumeric()) {
pad.step = entry["step"].asFloat();
}
pads[pad.id] = pad;
}
}
}
}
} else {
std::stringstream ss;
ss << "Error while loading " << path << std::endl;
ss << reader.getFormatedErrorMessages();
throw std::runtime_error(ss.str());
}
return pads;
}
}
<|endoftext|> |
<commit_before>/*
使用蒙特卡罗算法计算出的π的值
*/
#include <stdlib.h>
#include <stdio.h>
#define BITS 2000
int a=10000,b,c=BITS*7/2,d,e,f[BITS*7/2+1],g;
int main()
{
for(;b-c;)
f[b++]=a/5;
for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)
for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);
//getchar();
return 0;
} <commit_msg>给圆周率加上文章来源<commit_after>/**
* 使用蒙特卡罗算法计算出的π的值
* 文章来源: http://blog.csdn.net/himulakensin/article/details/8478224
*/
#include <stdlib.h>
#include <stdio.h>
#define BITS 2000
int a=10000,b,c=BITS*7/2,d,e,f[BITS*7/2+1],g;
int main()
{
for(;b-c;)
f[b++]=a/5;
for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)
for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);
//getchar();
return 0;
} <|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "uniformpixelrenderer.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/global/globaltypes.h"
#include "renderer/kernel/aov/imagestack.h"
#include "renderer/kernel/aov/spectrumstack.h"
#include "renderer/kernel/rendering/final/pixelsampler.h"
#include "renderer/kernel/rendering/isamplerenderer.h"
#include "renderer/kernel/rendering/pixelcontext.h"
#include "renderer/kernel/rendering/pixelrendererbase.h"
#include "renderer/kernel/rendering/shadingresultframebuffer.h"
#include "renderer/kernel/shading/shadingresult.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/utility/settingsparsing.h"
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/image.h"
#include "foundation/math/aabb.h"
#include "foundation/math/hash.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/platform/types.h"
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/statistics.h"
// Standard headers.
#include <cmath>
// Forward declarations.
namespace foundation { class Tile; }
namespace renderer { class TileStack; }
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Uniform pixel renderer.
//
class UniformPixelRenderer
: public PixelRendererBase
{
public:
UniformPixelRenderer(
ISampleRendererFactory* factory,
const ParamArray& params,
const size_t thread_index)
: m_params(params)
, m_sample_renderer(factory->create(thread_index))
, m_sample_count(m_params.m_samples)
, m_sqrt_sample_count(round<int>(sqrt(static_cast<double>(m_params.m_samples))))
{
if (!m_params.m_decorrelate)
{
m_pixel_sampler.initialize(m_sqrt_sample_count);
if (thread_index == 0)
{
if (params.get_optional<size_t>("passes", 1) > 1)
RENDERER_LOG_WARNING("doing multipass rendering with pixel decorrelation off.");
RENDERER_LOG_INFO(
"effective max subpixel grid size: %d x %d",
m_sqrt_sample_count,
m_sqrt_sample_count);
}
}
}
virtual void release() APPLESEED_OVERRIDE
{
delete this;
}
virtual void render_pixel(
const Frame& frame,
Tile& tile,
TileStack& aov_tiles,
const AABB2i& tile_bbox,
const size_t pass_hash,
const Vector2i& pi,
const Vector2i& pt,
SamplingContext::RNGType& rng,
ShadingResultFrameBuffer& framebuffer) APPLESEED_OVERRIDE
{
const size_t aov_count = frame.aov_images().size();
on_pixel_begin();
if (m_params.m_decorrelate)
{
// Create a sampling context.
const size_t frame_width = frame.image().properties().m_canvas_width;
const size_t instance = hash_uint32(static_cast<uint32>(pass_hash + pi.y * frame_width + pi.x));
SamplingContext sampling_context(
rng,
m_params.m_sampling_mode,
2, // number of dimensions
0, // number of samples -- unknown
instance); // initial instance number
for (size_t i = 0; i < m_sample_count; ++i)
{
// Generate a uniform sample in [0,1)^2.
const Vector2d s =
m_sample_count > 1 || m_params.m_force_aa
? sampling_context.next2<Vector2d>()
: Vector2d(0.5);
// Compute the sample position in NDC.
const Vector2d sample_position = frame.get_sample_position(pi.x + s.x, pi.y + s.y);
// Create a pixel context that identifies the pixel and sample currently being rendered.
const PixelContext pixel_context(pi, sample_position);
// Render the sample.
ShadingResult shading_result(aov_count);
SamplingContext child_sampling_context(sampling_context);
m_sample_renderer->render_sample(
child_sampling_context,
pixel_context,
sample_position,
shading_result);
// Merge the sample into the framebuffer.
if (shading_result.is_valid_linear_rgb())
{
framebuffer.add(
static_cast<float>(pt.x + s.x),
static_cast<float>(pt.y + s.y),
shading_result);
}
else signal_invalid_sample();
}
}
else
{
const int base_sx = pi.x * m_sqrt_sample_count;
const int base_sy = pi.y * m_sqrt_sample_count;
for (int sy = 0; sy < m_sqrt_sample_count; ++sy)
{
for (int sx = 0; sx < m_sqrt_sample_count; ++sx)
{
// Compute the sample position (in continuous image space) and the instance number.
Vector2d s;
size_t instance;
m_pixel_sampler.sample(base_sx + sx, base_sy + sy, s, instance);
// Compute the sample position in NDC.
const Vector2d sample_position = frame.get_sample_position(s.x, s.y);
// Create a pixel context that identifies the pixel and sample currently being rendered.
const PixelContext pixel_context(pi, sample_position);
// Create a sampling context. We start with an initial dimension of 1,
// as this seems to give less correlation artifacts than when the
// initial dimension is set to 0 or 2.
SamplingContext sampling_context(
rng,
m_params.m_sampling_mode,
1, // number of dimensions
instance, // number of samples
instance); // initial instance number -- end of sequence
// Render the sample.
ShadingResult shading_result(aov_count);
m_sample_renderer->render_sample(
sampling_context,
pixel_context,
sample_position,
shading_result);
// Merge the sample into the framebuffer.
if (shading_result.is_valid_linear_rgb())
{
framebuffer.add(
static_cast<float>(s.x - pi.x + pt.x),
static_cast<float>(s.y - pi.y + pt.y),
shading_result);
}
else signal_invalid_sample();
}
}
}
on_pixel_end(pi);
}
virtual StatisticsVector get_statistics() const APPLESEED_OVERRIDE
{
return m_sample_renderer->get_statistics();
}
private:
struct Parameters
{
const SamplingContext::Mode m_sampling_mode;
const size_t m_samples;
const bool m_force_aa;
const bool m_decorrelate;
explicit Parameters(const ParamArray& params)
: m_sampling_mode(get_sampling_context_mode(params))
, m_samples(params.get_required<size_t>("samples", 1))
, m_force_aa(params.get_optional<bool>("force_antialiasing", false))
, m_decorrelate(params.get_optional<bool>("decorrelate_pixels", true))
{
}
};
const Parameters m_params;
auto_release_ptr<ISampleRenderer> m_sample_renderer;
const size_t m_sample_count;
const int m_sqrt_sample_count;
PixelSampler m_pixel_sampler;
};
}
//
// UniformPixelRendererFactory class implementation.
//
UniformPixelRendererFactory::UniformPixelRendererFactory(
ISampleRendererFactory* factory,
const ParamArray& params)
: m_factory(factory)
, m_params(params)
{
}
void UniformPixelRendererFactory::release()
{
delete this;
}
IPixelRenderer* UniformPixelRendererFactory::create(
const size_t thread_index)
{
return new UniformPixelRenderer(m_factory, m_params, thread_index);
}
Dictionary UniformPixelRendererFactory::get_params_metadata()
{
Dictionary metadata;
metadata.dictionaries().insert(
"samples",
Dictionary()
.insert("type", "int")
.insert("default", "64")
.insert("label", "Samples")
.insert("help", "Number of anti-aliasing samples"));
metadata.dictionaries().insert(
"force_antialiasing",
Dictionary()
.insert("type", "bool")
.insert("default", "false")
.insert("label", "Force Anti-Aliasing")
.insert(
"help",
"When using 1 sample/pixel and force_antialiasing is disabled, samples are placed in the middle of the pixels"));
return metadata;
}
} // namespace renderer
<commit_msg>Tweak parameter metadata help string<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "uniformpixelrenderer.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/global/globaltypes.h"
#include "renderer/kernel/aov/imagestack.h"
#include "renderer/kernel/aov/spectrumstack.h"
#include "renderer/kernel/rendering/final/pixelsampler.h"
#include "renderer/kernel/rendering/isamplerenderer.h"
#include "renderer/kernel/rendering/pixelcontext.h"
#include "renderer/kernel/rendering/pixelrendererbase.h"
#include "renderer/kernel/rendering/shadingresultframebuffer.h"
#include "renderer/kernel/shading/shadingresult.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/utility/settingsparsing.h"
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/image.h"
#include "foundation/math/aabb.h"
#include "foundation/math/hash.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/platform/types.h"
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/statistics.h"
// Standard headers.
#include <cmath>
// Forward declarations.
namespace foundation { class Tile; }
namespace renderer { class TileStack; }
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Uniform pixel renderer.
//
class UniformPixelRenderer
: public PixelRendererBase
{
public:
UniformPixelRenderer(
ISampleRendererFactory* factory,
const ParamArray& params,
const size_t thread_index)
: m_params(params)
, m_sample_renderer(factory->create(thread_index))
, m_sample_count(m_params.m_samples)
, m_sqrt_sample_count(round<int>(sqrt(static_cast<double>(m_params.m_samples))))
{
if (!m_params.m_decorrelate)
{
m_pixel_sampler.initialize(m_sqrt_sample_count);
if (thread_index == 0)
{
if (params.get_optional<size_t>("passes", 1) > 1)
RENDERER_LOG_WARNING("doing multipass rendering with pixel decorrelation off.");
RENDERER_LOG_INFO(
"effective max subpixel grid size: %d x %d",
m_sqrt_sample_count,
m_sqrt_sample_count);
}
}
}
virtual void release() APPLESEED_OVERRIDE
{
delete this;
}
virtual void render_pixel(
const Frame& frame,
Tile& tile,
TileStack& aov_tiles,
const AABB2i& tile_bbox,
const size_t pass_hash,
const Vector2i& pi,
const Vector2i& pt,
SamplingContext::RNGType& rng,
ShadingResultFrameBuffer& framebuffer) APPLESEED_OVERRIDE
{
const size_t aov_count = frame.aov_images().size();
on_pixel_begin();
if (m_params.m_decorrelate)
{
// Create a sampling context.
const size_t frame_width = frame.image().properties().m_canvas_width;
const size_t instance = hash_uint32(static_cast<uint32>(pass_hash + pi.y * frame_width + pi.x));
SamplingContext sampling_context(
rng,
m_params.m_sampling_mode,
2, // number of dimensions
0, // number of samples -- unknown
instance); // initial instance number
for (size_t i = 0; i < m_sample_count; ++i)
{
// Generate a uniform sample in [0,1)^2.
const Vector2d s =
m_sample_count > 1 || m_params.m_force_aa
? sampling_context.next2<Vector2d>()
: Vector2d(0.5);
// Compute the sample position in NDC.
const Vector2d sample_position = frame.get_sample_position(pi.x + s.x, pi.y + s.y);
// Create a pixel context that identifies the pixel and sample currently being rendered.
const PixelContext pixel_context(pi, sample_position);
// Render the sample.
ShadingResult shading_result(aov_count);
SamplingContext child_sampling_context(sampling_context);
m_sample_renderer->render_sample(
child_sampling_context,
pixel_context,
sample_position,
shading_result);
// Merge the sample into the framebuffer.
if (shading_result.is_valid_linear_rgb())
{
framebuffer.add(
static_cast<float>(pt.x + s.x),
static_cast<float>(pt.y + s.y),
shading_result);
}
else signal_invalid_sample();
}
}
else
{
const int base_sx = pi.x * m_sqrt_sample_count;
const int base_sy = pi.y * m_sqrt_sample_count;
for (int sy = 0; sy < m_sqrt_sample_count; ++sy)
{
for (int sx = 0; sx < m_sqrt_sample_count; ++sx)
{
// Compute the sample position (in continuous image space) and the instance number.
Vector2d s;
size_t instance;
m_pixel_sampler.sample(base_sx + sx, base_sy + sy, s, instance);
// Compute the sample position in NDC.
const Vector2d sample_position = frame.get_sample_position(s.x, s.y);
// Create a pixel context that identifies the pixel and sample currently being rendered.
const PixelContext pixel_context(pi, sample_position);
// Create a sampling context. We start with an initial dimension of 1,
// as this seems to give less correlation artifacts than when the
// initial dimension is set to 0 or 2.
SamplingContext sampling_context(
rng,
m_params.m_sampling_mode,
1, // number of dimensions
instance, // number of samples
instance); // initial instance number -- end of sequence
// Render the sample.
ShadingResult shading_result(aov_count);
m_sample_renderer->render_sample(
sampling_context,
pixel_context,
sample_position,
shading_result);
// Merge the sample into the framebuffer.
if (shading_result.is_valid_linear_rgb())
{
framebuffer.add(
static_cast<float>(s.x - pi.x + pt.x),
static_cast<float>(s.y - pi.y + pt.y),
shading_result);
}
else signal_invalid_sample();
}
}
}
on_pixel_end(pi);
}
virtual StatisticsVector get_statistics() const APPLESEED_OVERRIDE
{
return m_sample_renderer->get_statistics();
}
private:
struct Parameters
{
const SamplingContext::Mode m_sampling_mode;
const size_t m_samples;
const bool m_force_aa;
const bool m_decorrelate;
explicit Parameters(const ParamArray& params)
: m_sampling_mode(get_sampling_context_mode(params))
, m_samples(params.get_required<size_t>("samples", 1))
, m_force_aa(params.get_optional<bool>("force_antialiasing", false))
, m_decorrelate(params.get_optional<bool>("decorrelate_pixels", true))
{
}
};
const Parameters m_params;
auto_release_ptr<ISampleRenderer> m_sample_renderer;
const size_t m_sample_count;
const int m_sqrt_sample_count;
PixelSampler m_pixel_sampler;
};
}
//
// UniformPixelRendererFactory class implementation.
//
UniformPixelRendererFactory::UniformPixelRendererFactory(
ISampleRendererFactory* factory,
const ParamArray& params)
: m_factory(factory)
, m_params(params)
{
}
void UniformPixelRendererFactory::release()
{
delete this;
}
IPixelRenderer* UniformPixelRendererFactory::create(
const size_t thread_index)
{
return new UniformPixelRenderer(m_factory, m_params, thread_index);
}
Dictionary UniformPixelRendererFactory::get_params_metadata()
{
Dictionary metadata;
metadata.dictionaries().insert(
"samples",
Dictionary()
.insert("type", "int")
.insert("default", "64")
.insert("label", "Samples")
.insert("help", "Number of anti-aliasing samples"));
metadata.dictionaries().insert(
"force_antialiasing",
Dictionary()
.insert("type", "bool")
.insert("default", "false")
.insert("label", "Force Anti-Aliasing")
.insert(
"help",
"When using 1 sample/pixel and Force Anti-Aliasing is disabled, samples are placed at the center of pixels"));
return metadata;
}
} // namespace renderer
<|endoftext|> |
<commit_before>//----------------------------------------------------------------------------//
// _ _ ____ ___ ____ //
// | \ | |___ \ / _ \| __ ) ___ _ _ ____ //
// | \| | __) | | | | _ \ / _ \| | | |_ / //
// | |\ |/ __/| |_| | |_) | (_) | |_| |/ / //
// |_| \_|_____|\___/|____/ \___/ \__, /___| //
// |___/ //
// //
// N2OMatt //
// N2OMatt@N2OBoyz.com //
// www.N2OBoyz.com/N2OMatt //
// //
// Copyright (C) 2015 N2OBoyz. //
// //
// This software is provided 'as-is', without any express or implied //
// warranty. In no event will the authors be held liable for any damages //
// arising from the use of this software. //
// //
// Permission is granted to anyone to use this software for any purpose, //
// including commercial applications, and to alter it and redistribute it //
// freely, subject to the following restrictions: //
// //
// 1. The origin of this software must not be misrepresented; //
// you must not claim that you wrote the original software. //
// 2. If you use this software in a product, an acknowledgment in the //
// product IS HIGHLY APPRECIATED, both in source and binary forms. //
// (See opensource.N2OBoyz.com/acknowledgment.html for details). //
// If you will not acknowledge, just send us a email. We'll be //
// *VERY* happy to see our work being used by other people. :) //
// The email is: acknowledgment.opensource@N2OBoyz.com //
// 3. Altered source versions must be plainly marked as such, //
// and must notbe misrepresented as being the original software. //
// 4. This notice may not be removed or altered from any source //
// distribution. //
// 5. Most important, you must have fun. ;) //
// //
// Visit OpenSource.N2OBoyz.com for more open-source projects. //
// //
// Enjoy :) //
//----------------------------------------------------------------------------//
//Header
#include "MonsterFramework/include/Localization/StringsManager.h"
//MonsterFramework
//Usings
USING_NS_STD_CC_CD_MF
// Public Methods //
void StringsManager::loadStringsFile(const std::string &filename)
{
}
const std::string StringsManager::getString(const std::string &path)
{
}
// Private Methods //
string StringsManager::getLocalizedFilename(const std::string &filename)
{
return filename + "_en.plist";
}
<commit_msg>Just a minor fix<commit_after>//----------------------------------------------------------------------------//
// _ _ ____ ___ ____ //
// | \ | |___ \ / _ \| __ ) ___ _ _ ____ //
// | \| | __) | | | | _ \ / _ \| | | |_ / //
// | |\ |/ __/| |_| | |_) | (_) | |_| |/ / //
// |_| \_|_____|\___/|____/ \___/ \__, /___| //
// |___/ //
// //
// N2OMatt //
// N2OMatt@N2OBoyz.com //
// www.N2OBoyz.com/N2OMatt //
// //
// Copyright (C) 2015 N2OBoyz. //
// //
// This software is provided 'as-is', without any express or implied //
// warranty. In no event will the authors be held liable for any damages //
// arising from the use of this software. //
// //
// Permission is granted to anyone to use this software for any purpose, //
// including commercial applications, and to alter it and redistribute it //
// freely, subject to the following restrictions: //
// //
// 1. The origin of this software must not be misrepresented; //
// you must not claim that you wrote the original software. //
// 2. If you use this software in a product, an acknowledgment in the //
// product IS HIGHLY APPRECIATED, both in source and binary forms. //
// (See opensource.N2OBoyz.com/acknowledgment.html for details). //
// If you will not acknowledge, just send us a email. We'll be //
// *VERY* happy to see our work being used by other people. :) //
// The email is: acknowledgment.opensource@N2OBoyz.com //
// 3. Altered source versions must be plainly marked as such, //
// and must notbe misrepresented as being the original software. //
// 4. This notice may not be removed or altered from any source //
// distribution. //
// 5. Most important, you must have fun. ;) //
// //
// Visit OpenSource.N2OBoyz.com for more open-source projects. //
// //
// Enjoy :) //
//----------------------------------------------------------------------------//
//Header
#include "MonsterFramework/include/Localization/StringsManager.h"
//MonsterFramework
//Usings
USING_NS_STD_CC_CD_MF
// Public Methods //
void StringsManager::loadStringsFile(const std::string &filename)
{
}
const std::string StringsManager::getString(const std::string &path)
{
}
// Private Methods //
string StringsManager::getLocalizedFilename(const std::string &filename)
{
return filename + "_en.plist";
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016, oasi-adamay
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 glsCV 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.
*/
// glsCam.cpp : R\[ AvP[ṼGg |Cg`܂B
//
#include "stdafx.h"
#include "glsCV.h"
//Lib
#pragma comment (lib, "opengl32.lib")
#pragma comment (lib, "glew32.lib")
#pragma comment (lib, "glfw3dll.lib")
#pragma comment (lib, "glsCV.lib")
enum E_CAM_MODE {
NORMAL,
GRAY,
FFT,
FFT_RECT,
};
void controls(GLFWwindow* window, int& mode){
if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS) mode = E_CAM_MODE::FFT;
if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS) mode = E_CAM_MODE::FFT_RECT;
if (glfwGetKey(window, GLFW_KEY_9) == GLFW_PRESS) mode = E_CAM_MODE::GRAY;
if (glfwGetKey(window, GLFW_KEY_0) == GLFW_PRESS) mode = E_CAM_MODE::NORMAL;
}
int _tmain(int argc, _TCHAR* argv[])
{
// const GLsizei captureWidth(640);
// const GLsizei captureHeight(480);
const GLsizei captureWidth(1280);
const GLsizei captureHeight(720);
GLFWwindow* window = glsCvInit(captureWidth, captureHeight);
// OpenCV ɂrfILv`
cv::VideoCapture camera(CV_CAP_ANY);
if (!camera.isOpened())
{
std::cerr << "cannot open input" << std::endl;
exit(-1);
}
// J̏ݒ
camera.grab();
camera.set(CV_CAP_PROP_FRAME_WIDTH, double(captureWidth));
camera.set(CV_CAP_PROP_FRAME_HEIGHT, double(captureHeight));
// Size sizeFft(256, 256);
Size sizeFft(512, 512);
Mat fftwin;
cv::createHanningWindow(fftwin, sizeFft, CV_32F);
GlsMat glsFftWin(fftwin);
GlsMat glsZero(Mat::zeros(sizeFft, CV_32FC1));
Rect rectFft((captureWidth - sizeFft.width) / 2, (captureHeight - sizeFft.height) / 2 , sizeFft.width, sizeFft.height);
int camMode = E_CAM_MODE::FFT;
do{
cv::Mat frame;
camera >> frame; // Lv`f摜o
imshow("[OCV]", frame.clone());
cv::flip(frame, frame, 0); // ㉺]
GlsMat glsFrame;
switch (camMode){
case(E_CAM_MODE::FFT) : {
#if 0
Mat roi = Mat(frame, rect).clone();
cv::cvtColor(roi,roi,CV_BGR2GRAY);
roi.convertTo(roi, CV_32FC1,1.0/256.0);
Mat zero = Mat::zeros(roi.size(),roi.type());
vector<Mat> pln(2);
pln[0] = roi;
pln[1] = zero;
Mat img;
cv::merge(pln, img);
cv::dft(img, img);
cv::split(img, pln);
Mat mag;
cv::magnitude(pln[0], pln[1], mag);
cv::log(mag+1,mag);
cv::normalize(mag, mag, 0, 1, CV_MINMAX);
cv::imshow("[CV MAG]",mag);
#else
Mat roi = Mat(frame, rectFft);
glsFrame = roi;
gls::convert(glsFrame, glsFrame, 1.0f / 256.0f);
gls::cvtColor(glsFrame, glsFrame, CV_BGR2GRAY);
gls::multiply(glsFftWin, glsFrame, glsFrame);
vector<GlsMat> plnGls(2);
plnGls[0] = glsFrame;
plnGls[1] = glsZero;
GlsMat glsComplx;
gls::merge(plnGls, glsComplx);
gls::fft(glsComplx, glsComplx, GLS_FFT_SHIFT);
gls::logMagSpectrums(glsComplx, glsFrame, 1.0);
gls::normalize(glsFrame, glsFrame, 0, 1, NORM_MINMAX);
#endif
}break;
case(E_CAM_MODE::FFT_RECT) : {
Mat roi = Mat(frame, rectFft);
glsFrame = roi;
gls::convert(glsFrame, glsFrame, 1.0f / 256.0f);
gls::cvtColor(glsFrame, glsFrame, CV_BGR2GRAY);
gls::multiply(glsFftWin, glsFrame, glsFrame);
} break;
case(E_CAM_MODE::GRAY) : {
glsFrame = frame;
gls::convert(glsFrame, glsFrame, 1.0f / 256.0f);
gls::cvtColor(glsFrame, glsFrame, CV_BGR2GRAY);
}break;
case(E_CAM_MODE::NORMAL):
default:{
glsFrame = frame;
gls::convert(glsFrame, glsFrame, 1.0f / 256.0f);
gls::cvtColor(glsFrame, glsFrame, CV_BGR2RGB);
}break;
}
glfwSetWindowSize(window, glsFrame.size().width, glsFrame.size().height);
gls::draw(glsFrame);
glfwSwapBuffers(window); // Swap buffers
glfwPollEvents();
controls(window, camMode); // key check
}
while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
glfwWindowShouldClose(window) == 0);
glsCvTerminate();
return 0;
}
<commit_msg>glsCamにフィルタエフェクト追加<commit_after>/*
Copyright (c) 2016, oasi-adamay
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 glsCV 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.
*/
// glsCam.cpp : R\[ AvP[ṼGg |Cg`܂B
//
#include "stdafx.h"
#include "glsCV.h"
//Lib
#pragma comment (lib, "opengl32.lib")
#pragma comment (lib, "glew32.lib")
#pragma comment (lib, "glfw3dll.lib")
#pragma comment (lib, "glsCV.lib")
enum E_CAM_MODE {
NORMAL,
GRAY,
GAUSS,
SOBEL_H,
SOBEL_V,
FFT,
FFT_RECT,
};
void controls(GLFWwindow* window, int& mode ,int& ocvwin){
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) ocvwin = 1- ocvwin;
if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS) mode = E_CAM_MODE::NORMAL;
if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS) mode = E_CAM_MODE::GRAY;
if (glfwGetKey(window, GLFW_KEY_3) == GLFW_PRESS) mode = E_CAM_MODE::GAUSS;
if (glfwGetKey(window, GLFW_KEY_4) == GLFW_PRESS) mode = E_CAM_MODE::SOBEL_H;
if (glfwGetKey(window, GLFW_KEY_5) == GLFW_PRESS) mode = E_CAM_MODE::SOBEL_V;
if (glfwGetKey(window, GLFW_KEY_9) == GLFW_PRESS) mode = E_CAM_MODE::FFT;
if (glfwGetKey(window, GLFW_KEY_0) == GLFW_PRESS) mode = E_CAM_MODE::FFT_RECT;
}
int _tmain(int argc, _TCHAR* argv[])
{
// const GLsizei captureWidth(640);
// const GLsizei captureHeight(480);
const GLsizei captureWidth(1280);
const GLsizei captureHeight(720);
GLFWwindow* window = glsCvInit(captureWidth, captureHeight);
// OpenCV ɂrfILv`
cv::VideoCapture camera(CV_CAP_ANY);
if (!camera.isOpened())
{
std::cerr << "cannot open input" << std::endl;
exit(-1);
}
// J̏ݒ
camera.grab();
camera.set(CV_CAP_PROP_FRAME_WIDTH, double(captureWidth));
camera.set(CV_CAP_PROP_FRAME_HEIGHT, double(captureHeight));
// Size sizeFft(256, 256);
Size sizeFft(512, 512);
Mat fftwin;
cv::createHanningWindow(fftwin, sizeFft, CV_32F);
GlsMat glsFftWin(fftwin);
GlsMat glsZero(Mat::zeros(sizeFft, CV_32FC1));
Rect rectFft((captureWidth - sizeFft.width) / 2, (captureHeight - sizeFft.height) / 2 , sizeFft.width, sizeFft.height);
int camMode = E_CAM_MODE::FFT;
int ocvwin = 0;
do{
cv::Mat frame;
camera >> frame; // Lv`f摜o
if (ocvwin) cv::imshow("[OCV]", frame.clone());
else cv::destroyWindow("[OCV]");
cv::flip(frame, frame, 0); // ㉺]
GlsMat glsFrame;
switch (camMode){
case(E_CAM_MODE::FFT) : {
#if 0
Mat roi = Mat(frame, rect).clone();
cv::cvtColor(roi,roi,CV_BGR2GRAY);
roi.convertTo(roi, CV_32FC1,1.0/256.0);
Mat zero = Mat::zeros(roi.size(),roi.type());
vector<Mat> pln(2);
pln[0] = roi;
pln[1] = zero;
Mat img;
cv::merge(pln, img);
cv::dft(img, img);
cv::split(img, pln);
Mat mag;
cv::magnitude(pln[0], pln[1], mag);
cv::log(mag+1,mag);
cv::normalize(mag, mag, 0, 1, CV_MINMAX);
cv::imshow("[CV MAG]",mag);
#else
Mat roi = Mat(frame, rectFft);
glsFrame = roi;
gls::convert(glsFrame, glsFrame, 1.0f / 256.0f);
gls::cvtColor(glsFrame, glsFrame, CV_BGR2GRAY);
gls::multiply(glsFftWin, glsFrame, glsFrame);
vector<GlsMat> plnGls(2);
plnGls[0] = glsFrame;
plnGls[1] = glsZero;
GlsMat glsComplx;
gls::merge(plnGls, glsComplx);
gls::fft(glsComplx, glsComplx, GLS_FFT_SHIFT);
gls::logMagSpectrums(glsComplx, glsFrame, 1.0);
gls::normalize(glsFrame, glsFrame, 0, 1, NORM_MINMAX);
#endif
}break;
case(E_CAM_MODE::FFT_RECT) : {
Mat roi = Mat(frame, rectFft);
glsFrame = roi;
gls::convert(glsFrame, glsFrame, 1.0f / 256.0f);
gls::cvtColor(glsFrame, glsFrame, CV_BGR2GRAY);
gls::multiply(glsFftWin, glsFrame, glsFrame);
} break;
case(E_CAM_MODE::SOBEL_V) : {
glsFrame = frame;
gls::convert(glsFrame, glsFrame, 1.0f / 256.0f);
gls::cvtColor(glsFrame, glsFrame, CV_BGR2GRAY);
gls::Sobel(glsFrame, glsFrame, -1, 0,1);
gls::add(vec4(0.5), glsFrame, glsFrame);
}break;
case(E_CAM_MODE::SOBEL_H) : {
glsFrame = frame;
gls::convert(glsFrame, glsFrame, 1.0f / 256.0f);
gls::cvtColor(glsFrame, glsFrame, CV_BGR2GRAY);
gls::Sobel(glsFrame, glsFrame, -1, 1, 0);
gls::add(vec4(0.5), glsFrame, glsFrame);
}break;
case(E_CAM_MODE::GAUSS) : {
glsFrame = frame;
gls::convert(glsFrame, glsFrame, 1.0f / 256.0f);
gls::cvtColor(glsFrame, glsFrame, CV_BGR2RGB);
gls::GaussianBlur(glsFrame, glsFrame, Size(9, 9), 0, 0);
}break;
case(E_CAM_MODE::GRAY) : {
glsFrame = frame;
gls::convert(glsFrame, glsFrame, 1.0f / 256.0f);
gls::cvtColor(glsFrame, glsFrame, CV_BGR2GRAY);
}break;
case(E_CAM_MODE::NORMAL):
default:{
glsFrame = frame;
gls::convert(glsFrame, glsFrame, 1.0f / 256.0f);
gls::cvtColor(glsFrame, glsFrame, CV_BGR2RGB);
}break;
}
glfwSetWindowSize(window, glsFrame.size().width, glsFrame.size().height);
gls::draw(glsFrame);
glfwSwapBuffers(window); // Swap buffers
glfwPollEvents();
controls(window, camMode,ocvwin); // key check
}
while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
glfwWindowShouldClose(window) == 0);
glsCvTerminate();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef TCL_EXECUTE_HPP
#define TCL_EXECUTE_HPP
#include <typeinfo>
#include "CLInformation.hpp"
#include "CLSourceArray.hpp"
#include "CLExecuteProperty.hpp"
#include "CLDeviceInformation.hpp"
#include "CLWorkGroupSettings.hpp"
#include "CLBuffer.hpp"
namespace tcl
{
class CLExecute
{
private:
CLExecuteProperty executeProperty;
unsigned argCount;
private:
void TestKernelArg(const cl_int& result) const
{
if (result != CL_SUCCESS)
{
switch (result)
{
case CL_INVALID_KERNEL:
throw CLException("ȃJ[lw肳Ă܂");
case CL_INVALID_ARG_INDEX:
throw CLException("̃CfbNXsł");
case CL_INVALID_ARG_VALUE:
throw CLException("̒lsł");
case CL_INVALID_MEM_OBJECT:
throw CLException("IuWFNgsł");
case CL_INVALID_SAMPLER:
throw CLException("Tv[IuWFNgsł");
case CL_INVALID_ARG_SIZE:
throw CLException("Ŏw肵TCYsł");
case CL_OUT_OF_RESOURCES:
throw CLException("foCX̃\[Xmۂł܂ł");
case CL_OUT_OF_HOST_MEMORY:
throw CLException("zXg̃\[Xmۂł܂ł");
}
}
}
void TestEnqueueTask(const cl_int& result) const
{
if (result != CL_SUCCESS)
throw CLException("G[Nă^XNsł܂ł", result);
}
void TestNDRange(const cl_int& result) const
{
if (result != CL_SUCCESS)
{
switch (result)
{
case CL_INVALID_PROGRAM_EXECUTABLE:
throw CLException("R}hL[Ɋ֘AtꂽɃrhꂽvO݂܂");
case CL_INVALID_COMMAND_QUEUE:
throw CLException("R}hL[ł");
case CL_INVALID_KERNEL:
throw CLException("J[lł");
case CL_INVALID_CONTEXT:
throw CLException("ReLXgł");
case CL_INVALID_KERNEL_ARGS:
throw CLException("J[lw肳Ă܂");
case CL_INVALID_WORK_DIMENSION:
throw CLException("J[l̕Kł͂܂");
case CL_INVALID_GLOBAL_OFFSET:
throw CLException("ItZbg̒l[NTCYĂ܂");
case CL_INVALID_WORK_GROUP_SIZE:
throw CLException("[NO[v̑傫sł");
case CL_INVALID_WORK_ITEM_SIZE:
throw CLException("[NACesł");
case CL_MISALIGNED_SUB_BUFFER_OFFSET:
throw CLException("Tuobt@ItZbg̃ACgsł");
case CL_INVALID_IMAGE_SIZE:
throw CLException("J[lɎw肵C[WIuWFNgfoCXŃT|[gĂ܂");
case CL_OUT_OF_RESOURCES:
throw CLException("J[l̎sɕKvȃ\[XsĂ܂");
case CL_MEM_OBJECT_ALLOCATION_FAILURE:
throw CLException("IuWFNg̗̈mۂ̂Ɏs܂");
case CL_INVALID_EVENT_WAIT_LIST:
throw CLException("Cxg҂Xgsł");
case CL_OUT_OF_HOST_MEMORY:
throw CLException("zXg̃̃\[XmۂɎs܂");
}
}
}
public:
inline cl_command_queue& CommandQueue() {
return executeProperty.commandQueue;
}
inline cl_program& Program() {
return executeProperty.program;
}
inline cl_kernel& Kernel() {
return executeProperty.kernel;
}
public:
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] source \[XR[h
* \param[in] useDeviceIdpfoCXID
*/
CLExecute(CLSource& source, const cl_device_id& useDeviceId)
: executeProperty(source, useDeviceId), argCount(0)
{
}
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] sourceArray \[XR[h̔zNX
* \param[in] useDeviceId pfoCXID
*/
CLExecute(CLSourceArray& sourceArray, const cl_device_id& useDeviceId)
: executeProperty(sourceArray, useDeviceId), argCount(0)
{
}
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] source \[XR[h
* \param[in] device foCX̃CX^X
*/
CLExecute(CLSource& source, const CLDeviceInformation& device)
: executeProperty(source, device.DeviceId()), argCount(0)
{
}
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] sourceArray \[XR[h̔zNX
* \param[in] device foCX̃CX^X
*/
CLExecute(CLSourceArray& sourceArray, const CLDeviceInformation& device)
: executeProperty(sourceArray, device.DeviceId()), argCount(0)
{
}
/**
* J[lɓn߂̈ݒ肷
* \param[in] buffer J[lŗp邽߂̃obt@
*/
template <typename T>
void SetArg(T& buffer)
{
#define TEST_BUFFER(X) typeid(buffer)==typeid(X)
// CLBufferpĂ邩ǂ
// @ΒNācc
if (
TEST_BUFFER(CLReadWriteBuffer) ||
TEST_BUFFER(CLReadBuffer) ||
TEST_BUFFER(CLWriteBuffer) ||
TEST_BUFFER(CLBuffer) ||
TEST_BUFFER(CLHostCopyBuffer) ||
TEST_BUFFER(CLAllocHostBuffer) ||
TEST_BUFFER(CLUseHostBuffer))
#undef TEST_BUFFER
{
SetBuffer(buffer);
}
else
{
cl_int resultArg;
resultArg = clSetKernelArg(Kernel(), argCount, sizeof(T), &buffer);
TestKernelArg(resultArg);
}
}
/**
* J[lɓn߂̈ւorݒ肷
* \param argIndex ̃CfbNX
* \param buffer J[lŗpobt@
*/
template <typename T>
void SetArg(const cl_uint argIndex, T& buffer)
{
const auto resultArg = clSetKernelArg(Kernel(), argIndex, sizeof(T), &buffer);
TestKernelArg(resultArg);
}
/**
* J[lɓn߂̈ݒ肷
* \param[in] buffer J[lŗp邽߂̃obt@
* \param[in] otherBuffers ϒ
*/
template <typename T, typename... Args>
void SetArg(T& buffer, Args&... otherBuffers)
{
if (typeid(buffer) == typeid(CLReadWriteBuffer))
SetBuffer(buffer);
else
SetArg(buffer);
argCount++;
SetArg(otherBuffers...);
argCount = 0;
}
/**
* J[lɓn߂̃obt@ݒ肷
* \param[in] buffer CLBuffer̃CX^X
*/
template <typename T = CLBuffer>
void SetBuffer(T& buffer)
{
const auto resultArg = clSetKernelArg(Kernel(), argCount, sizeof(cl_mem), &buffer.Memory());
TestKernelArg(resultArg);
}
/**
* J[lɓn߂̃obt@ԍw肵Đݒ肷
* \param[in] argIndex ԍ
* \param[in] buffer CLBuffer̃CX^X
*/
void SetBuffer(const cl_uint argIndex, CLBuffer& buffer)
{
const auto resultArg = clSetKernelArg(Kernel(), argIndex, sizeof(cl_mem), &buffer.Memory());
TestKernelArg(resultArg);
}
/**
* J[lɓn߂̃obt@ݒ肷
* \param[in] buffer CLBuffer̃CX^X
* \param[in] otherBuffers CCLBuffer̃CX^X
*/
template <typename... Args>
void SetBuffer(CLBuffer& buffer, Args&... otherBuffers)
{
SetBuffer(buffer);
argCount++;
SetBuffer(otherBuffers...)
argCount = 0;
}
/**
* P̃J[ls
* \param[in] wait sI܂ő҂ǂ
*/
void Run(const bool wait = true)
{
cl_event event;
auto resultTask = clEnqueueTask(CommandQueue(), Kernel(), 0, NULL, &event);
if (wait)
clWaitForEvents(1, &event);
TestEnqueueTask(resultTask);
}
/**
* ͈͎w肵ăJ[ls
* \param[in] setting s͈͂w肷NX̃CX^X
* \param[in] wait sI܂ő҂ǂ
*/
void Run(CLWorkGroupSettings& setting, const bool wait = true)
{
cl_event event;
auto result = clEnqueueNDRangeKernel(
CommandQueue(), Kernel(), setting.Dimension(),
setting.Offset(), setting.WorkerRange(), setting.SplitSize(),
0, NULL, &event);
if (wait)
clWaitForEvents(1, &event);
TestNDRange(result);
}
};
}
#endif<commit_msg>SetArgで自身のポインタを返すようにした<commit_after>#ifndef TCL_EXECUTE_HPP
#define TCL_EXECUTE_HPP
#include <typeinfo>
#include "CLInformation.hpp"
#include "CLSourceArray.hpp"
#include "CLExecuteProperty.hpp"
#include "CLDeviceInformation.hpp"
#include "CLWorkGroupSettings.hpp"
#include "CLBuffer.hpp"
namespace tcl
{
class CLExecute
{
private:
CLExecuteProperty executeProperty;
unsigned argCount;
private:
void TestKernelArg(const cl_int& result) const
{
if (result != CL_SUCCESS)
{
switch (result)
{
case CL_INVALID_KERNEL:
throw CLException("ȃJ[lw肳Ă܂");
case CL_INVALID_ARG_INDEX:
throw CLException("̃CfbNXsł");
case CL_INVALID_ARG_VALUE:
throw CLException("̒lsł");
case CL_INVALID_MEM_OBJECT:
throw CLException("IuWFNgsł");
case CL_INVALID_SAMPLER:
throw CLException("Tv[IuWFNgsł");
case CL_INVALID_ARG_SIZE:
throw CLException("Ŏw肵TCYsł");
case CL_OUT_OF_RESOURCES:
throw CLException("foCX̃\[Xmۂł܂ł");
case CL_OUT_OF_HOST_MEMORY:
throw CLException("zXg̃\[Xmۂł܂ł");
}
}
}
void TestEnqueueTask(const cl_int& result) const
{
if (result != CL_SUCCESS)
throw CLException("G[Nă^XNsł܂ł", result);
}
void TestNDRange(const cl_int& result) const
{
if (result != CL_SUCCESS)
{
switch (result)
{
case CL_INVALID_PROGRAM_EXECUTABLE:
throw CLException("R}hL[Ɋ֘AtꂽɃrhꂽvO݂܂");
case CL_INVALID_COMMAND_QUEUE:
throw CLException("R}hL[ł");
case CL_INVALID_KERNEL:
throw CLException("J[lł");
case CL_INVALID_CONTEXT:
throw CLException("ReLXgł");
case CL_INVALID_KERNEL_ARGS:
throw CLException("J[lw肳Ă܂");
case CL_INVALID_WORK_DIMENSION:
throw CLException("J[l̕Kł͂܂");
case CL_INVALID_GLOBAL_OFFSET:
throw CLException("ItZbg̒l[NTCYĂ܂");
case CL_INVALID_WORK_GROUP_SIZE:
throw CLException("[NO[v̑傫sł");
case CL_INVALID_WORK_ITEM_SIZE:
throw CLException("[NACesł");
case CL_MISALIGNED_SUB_BUFFER_OFFSET:
throw CLException("Tuobt@ItZbg̃ACgsł");
case CL_INVALID_IMAGE_SIZE:
throw CLException("J[lɎw肵C[WIuWFNgfoCXŃT|[gĂ܂");
case CL_OUT_OF_RESOURCES:
throw CLException("J[l̎sɕKvȃ\[XsĂ܂");
case CL_MEM_OBJECT_ALLOCATION_FAILURE:
throw CLException("IuWFNg̗̈mۂ̂Ɏs܂");
case CL_INVALID_EVENT_WAIT_LIST:
throw CLException("Cxg҂Xgsł");
case CL_OUT_OF_HOST_MEMORY:
throw CLException("zXg̃̃\[XmۂɎs܂");
}
}
}
public:
inline cl_command_queue& CommandQueue() {
return executeProperty.commandQueue;
}
inline cl_program& Program() {
return executeProperty.program;
}
inline cl_kernel& Kernel() {
return executeProperty.kernel;
}
public:
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] source \[XR[h
* \param[in] useDeviceIdpfoCXID
*/
CLExecute(CLSource& source, const cl_device_id& useDeviceId)
: executeProperty(source, useDeviceId), argCount(0)
{
}
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] sourceArray \[XR[h̔zNX
* \param[in] useDeviceId pfoCXID
*/
CLExecute(CLSourceArray& sourceArray, const cl_device_id& useDeviceId)
: executeProperty(sourceArray, useDeviceId), argCount(0)
{
}
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] source \[XR[h
* \param[in] device foCX̃CX^X
*/
CLExecute(CLSource& source, const CLDeviceInformation& device)
: executeProperty(source, device.DeviceId()), argCount(0)
{
}
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] sourceArray \[XR[h̔zNX
* \param[in] device foCX̃CX^X
*/
CLExecute(CLSourceArray& sourceArray, const CLDeviceInformation& device)
: executeProperty(sourceArray, device.DeviceId()), argCount(0)
{
}
/**
* J[lɓn߂̈ݒ肷
* \param[in] buffer J[lŗp邽߂̃obt@
*/
template <typename T>
CLExecute& SetArg(T& buffer)
{
#define TEST_BUFFER(X) typeid(buffer)==typeid(X)
// CLBufferpĂ邩ǂ
// @ΒNācc
if (
TEST_BUFFER(CLReadWriteBuffer) ||
TEST_BUFFER(CLReadBuffer) ||
TEST_BUFFER(CLWriteBuffer) ||
TEST_BUFFER(CLBuffer) ||
TEST_BUFFER(CLHostCopyBuffer) ||
TEST_BUFFER(CLAllocHostBuffer) ||
TEST_BUFFER(CLUseHostBuffer))
#undef TEST_BUFFER
{
SetBuffer(buffer);
}
else
{
cl_int resultArg;
resultArg = clSetKernelArg(Kernel(), argCount, sizeof(T), &buffer);
TestKernelArg(resultArg);
}
return *this;
}
/**
* J[lɓn߂̈ւorݒ肷
* \param argIndex ̃CfbNX
* \param buffer J[lŗpobt@
*/
template <typename T>
CLExecute& SetArg(const cl_uint argIndex, T& buffer)
{
const auto resultArg = clSetKernelArg(Kernel(), argIndex, sizeof(T), &buffer);
TestKernelArg(resultArg);
return *this;
}
/**
* J[lɓn߂̈ݒ肷
* \param[in] buffer J[lŗp邽߂̃obt@
* \param[in] otherBuffers ϒ
*/
template <typename T, typename... Args>
CLExecute& SetArg(T& buffer, Args&... otherBuffers)
{
if (typeid(buffer) == typeid(CLReadWriteBuffer))
SetBuffer(buffer);
else
SetArg(buffer);
argCount++;
SetArg(otherBuffers...);
argCount = 0;
return *this;
}
/**
* J[lɓn߂̃obt@ݒ肷
* \param[in] buffer CLBuffer̃CX^X
*/
template <typename T = CLBuffer>
CLExecute& SetBuffer(T& buffer)
{
const auto resultArg = clSetKernelArg(Kernel(), argCount, sizeof(cl_mem), &buffer.Memory());
TestKernelArg(resultArg);
return *this;
}
/**
* J[lɓn߂̃obt@ԍw肵Đݒ肷
* \param[in] argIndex ԍ
* \param[in] buffer CLBuffer̃CX^X
*/
CLExecute& SetBuffer(const cl_uint argIndex, CLBuffer& buffer)
{
const auto resultArg = clSetKernelArg(Kernel(), argIndex, sizeof(cl_mem), &buffer.Memory());
TestKernelArg(resultArg);
return *this;
}
/**
* J[lɓn߂̃obt@ݒ肷
* \param[in] buffer CLBuffer̃CX^X
* \param[in] otherBuffers CCLBuffer̃CX^X
*/
template <typename... Args>
CLExecute& SetBuffer(CLBuffer& buffer, Args&... otherBuffers)
{
SetBuffer(buffer);
argCount++;
SetBuffer(otherBuffers...)
argCount = 0;
return *this;
}
/**
* P̃J[ls
* \param[in] wait sI܂ő҂ǂ
*/
CLExecute& Run(const bool wait = true)
{
cl_event event;
auto resultTask = clEnqueueTask(CommandQueue(), Kernel(), 0, NULL, &event);
if (wait)
clWaitForEvents(1, &event);
TestEnqueueTask(resultTask);
return *this;
}
/**
* ͈͎w肵ăJ[ls
* \param[in] setting s͈͂w肷NX̃CX^X
* \param[in] wait sI܂ő҂ǂ
*/
CLExecute& Run(CLWorkGroupSettings& setting, const bool wait = true)
{
cl_event event;
auto result = clEnqueueNDRangeKernel(
CommandQueue(), Kernel(), setting.Dimension(),
setting.Offset(), setting.WorkerRange(), setting.SplitSize(),
0, NULL, &event);
if (wait)
clWaitForEvents(1, &event);
TestNDRange(result);
return *this;
}
};
}
#endif<|endoftext|> |
<commit_before>/*
* WIN32 Events for POSIX
* Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net>
* Copyright (C) 2011 by NeoSmart Technologies
* This code is released under the terms of the MIT License
*/
#include "pevents.h"
#include <sys/time.h>
#ifdef WFMO
#include <vector>
#endif
namespace neosmart
{
#ifdef WFMO
struct neosmart_wfmo_t_
{
pthread_mutex_t Mutex;
pthread_cond_t CVariable;
std::vector<bool> EventStatus;
bool StillWaiting;
int RefCount;
bool WaitAll;
void Destroy()
{
pthread_mutex_destroy(&Mutex);
pthread_cond_destroy(&CVariable);
}
};
typedef neosmart_wfmo_t_ *neosmart_wfmo_t;
struct neosmart_wfmo_info_t_
{
neosmart_wfmo_t Waiter;
int WaitIndex;
};
typedef neosmart_wfmo_info_t_ *neosmart_wfmo_info_t;
#endif
struct neosmart_event_t_
{
bool AutoReset;
pthread_cond_t CVariable;
pthread_mutex_t Mutex;
bool State;
#ifdef WFMO
std::vector<neosmart_wfmo_info_t_> RegisteredWaits;
#endif
};
neosmart_event_t CreateEvent(bool manualReset, bool initialState)
{
neosmart_event_t event = new neosmart_event_t_;
int result = pthread_cond_init(&event->CVariable, 0);
if(result != 0)
return NULL;
result = pthread_mutex_init(&event->Mutex, 0);
if(result != 0)
return NULL;
event->State = false;
event->AutoReset = !manualReset;
if(initialState && SetEvent(event) != 0)
return NULL; //Shouldn't ever happen
return event;
}
int WaitForEvent(neosmart_event_t event, uint64_t milliseconds)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
if(!event->State)
{
timespec ts;
if(milliseconds != -1)
{
timeval tv;
gettimeofday(&tv, NULL);
uint64_t nanoseconds = tv.tv_sec * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + tv.tv_usec * 1000;
ts.tv_sec = nanoseconds / 1000 / 1000 / 1000;
ts.tv_nsec = (nanoseconds - ts.tv_sec * 1000 * 1000 * 1000);
}
do
{
//Regardless of whether it's an auto-reset or manual-reset event:
//wait to obtain the event, then lock anyone else out
if(milliseconds != -1)
{
result = pthread_cond_timedwait(&event->CVariable, &event->Mutex, &ts);
}
else
{
result = pthread_cond_wait(&event->CVariable, &event->Mutex);
}
} while(result == 0 && !event->State);
if(result == 0)
{
//We've only accquired the event if the wait succeeded
event->State = false;
}
}
else if(event->AutoReset)
{
//It's an auto-reset event that's currently available;
//we need to stop anyone else from using it
result = 0;
event->State = false;
}
//Else we're trying to obtain a manual reset event with a signalled state;
//don't do anything
pthread_mutex_unlock(&event->Mutex);
return result;
}
#ifdef WFMO
int WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds, int &waitIndex)
{
neosmart_wfmo_t wfmo = new neosmart_wfmo_t_;
int result = pthread_mutex_init(&wfmo->Mutex, 0);
if(result != 0)
return result;
result = pthread_cond_init(&wfmo->CVariable, 0);
if(result != 0)
return result;
neosmart_wfmo_info_t_ waitInfo;
waitInfo.Waiter = wfmo;
waitInfo.WaitIndex = -1;
wfmo->WaitAll = waitAll;
wfmo->StillWaiting = true;
wfmo->RefCount = count + 1;
wfmo->EventStatus.resize(count, false);
pthread_mutex_lock(&wfmo->Mutex);
for(int i = 0; i < count; ++i)
{
int result = pthread_mutex_lock(&events[i]->Mutex);
if(result != 0)
return result;
waitInfo.WaitIndex++;
events[i]->RegisteredWaits.push_back(waitInfo);
pthread_mutex_unlock(&events[i]->Mutex);
}
timespec ts;
if(milliseconds != -1)
{
timeval tv;
gettimeofday(&tv, NULL);
uint64_t nanoseconds = tv.tv_sec * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + tv.tv_usec * 1000;
ts.tv_sec = nanoseconds / 1000 / 1000 / 1000;
ts.tv_nsec = (nanoseconds - ts.tv_sec * 1000 * 1000 * 1000);
}
bool done = false;
while(!done)
{
if(milliseconds != -1)
{
result = pthread_cond_timedwait(&wfmo->CVariable, &wfmo->Mutex, &ts);
}
else
{
result = pthread_cond_wait(&wfmo->CVariable, &wfmo->Mutex);
}
if(result != 0)
break;
//One (or more) of the events we're monitoring has been triggered
for(int i = 0; i < count; ++i)
{
if(!waitAll && wfmo->EventStatus[i])
{
done = true;
waitIndex = i;
break;
}
if(waitAll && !wfmo->EventStatus[i])
{
break;
}
}
}
--wfmo->RefCount;
if(wfmo->RefCount == 0)
{
wfmo->Destroy();
delete wfmo;
}
else
{
pthread_mutex_unlock(&wfmo->Mutex);
}
return result;
}
#endif
int DestroyEvent(neosmart_event_t event)
{
int result = pthread_cond_destroy(&event->CVariable);
if(result != 0)
return result;
result = pthread_mutex_destroy(&event->Mutex);
if(result != 0)
return result;
delete event;
return 0;
}
int SetEvent(neosmart_event_t event)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
event->State = true;
//Depending on the event type, we either trigger everyone or only one
if(event->AutoReset)
{
#ifdef WFMO
bool skipCV = false;
while(!event->RegisteredWaits.empty())
{
neosmart_wfmo_info_t i = &event->RegisteredWaits.back();
pthread_mutex_lock(&i->Waiter->Mutex);
--i->Waiter->RefCount;
if(!i->Waiter->StillWaiting)
{
if(i->Waiter->RefCount == 0)
{
i->Waiter->Destroy();
delete i->Waiter;
}
else
{
pthread_mutex_unlock(&i->Waiter->Mutex);
}
event->RegisteredWaits.pop_back();
continue;
}
skipCV = true;
i->Waiter->EventStatus[i->WaitIndex] = true;
if(!i->Waiter->WaitAll)
i->Waiter->StillWaiting = false;
result = pthread_cond_signal(&i->Waiter->CVariable);
pthread_mutex_unlock(&i->Waiter->Mutex);
event->RegisteredWaits.pop_back();
break;
}
if(!skipCV)
#endif
result = pthread_cond_signal(&event->CVariable);
}
else
{
#ifdef WFMO
for(int i = 0; i < event->RegisteredWaits.size(); ++i)
{
neosmart_wfmo_info_t info = &event->RegisteredWaits[i];
pthread_mutex_lock(&info->Waiter->Mutex);
--info->Waiter->RefCount;
if(!info->Waiter->StillWaiting)
{
if(info->Waiter->RefCount == 0)
{
info->Waiter->Destroy();
delete info->Waiter;
}
else
{
pthread_mutex_unlock(&info->Waiter->Mutex);
}
continue;
}
info->Waiter->EventStatus[info->WaitIndex] = true;
pthread_cond_signal(&info->Waiter->CVariable);
pthread_mutex_unlock(&info->Waiter->Mutex);
}
event->RegisteredWaits.clear();
#endif
result = pthread_cond_broadcast(&event->CVariable);
}
pthread_mutex_unlock(&event->Mutex);
return result;
}
int ResetEvent(neosmart_event_t event)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
event->State = false;
pthread_mutex_unlock(&event->Mutex);
return result;
}
}
<commit_msg>WaitForMultipleEvents now checks event state before entering wait<commit_after>/*
* WIN32 Events for POSIX
* Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net>
* Copyright (C) 2011 by NeoSmart Technologies
* This code is released under the terms of the MIT License
*/
#include "pevents.h"
#include <sys/time.h>
#ifdef WFMO
#include <vector>
#endif
namespace neosmart
{
#ifdef WFMO
struct neosmart_wfmo_t_
{
pthread_mutex_t Mutex;
pthread_cond_t CVariable;
std::vector<bool> EventStatus;
bool StillWaiting;
int RefCount;
bool WaitAll;
void Destroy()
{
pthread_mutex_destroy(&Mutex);
pthread_cond_destroy(&CVariable);
}
};
typedef neosmart_wfmo_t_ *neosmart_wfmo_t;
struct neosmart_wfmo_info_t_
{
neosmart_wfmo_t Waiter;
int WaitIndex;
};
typedef neosmart_wfmo_info_t_ *neosmart_wfmo_info_t;
#endif
struct neosmart_event_t_
{
bool AutoReset;
pthread_cond_t CVariable;
pthread_mutex_t Mutex;
bool State;
#ifdef WFMO
std::vector<neosmart_wfmo_info_t_> RegisteredWaits;
#endif
};
neosmart_event_t CreateEvent(bool manualReset, bool initialState)
{
neosmart_event_t event = new neosmart_event_t_;
int result = pthread_cond_init(&event->CVariable, 0);
if(result != 0)
return NULL;
result = pthread_mutex_init(&event->Mutex, 0);
if(result != 0)
return NULL;
event->State = false;
event->AutoReset = !manualReset;
if(initialState && SetEvent(event) != 0)
return NULL; //Shouldn't ever happen
return event;
}
int WaitForEvent(neosmart_event_t event, uint64_t milliseconds)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
if(!event->State)
{
timespec ts;
if(milliseconds != -1)
{
timeval tv;
gettimeofday(&tv, NULL);
uint64_t nanoseconds = tv.tv_sec * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + tv.tv_usec * 1000;
ts.tv_sec = nanoseconds / 1000 / 1000 / 1000;
ts.tv_nsec = (nanoseconds - ts.tv_sec * 1000 * 1000 * 1000);
}
do
{
//Regardless of whether it's an auto-reset or manual-reset event:
//wait to obtain the event, then lock anyone else out
if(milliseconds != -1)
{
result = pthread_cond_timedwait(&event->CVariable, &event->Mutex, &ts);
}
else
{
result = pthread_cond_wait(&event->CVariable, &event->Mutex);
}
} while(result == 0 && !event->State);
if(result == 0)
{
//We've only accquired the event if the wait succeeded
event->State = false;
}
}
else if(event->AutoReset)
{
//It's an auto-reset event that's currently available;
//we need to stop anyone else from using it
result = 0;
event->State = false;
}
//Else we're trying to obtain a manual reset event with a signalled state;
//don't do anything
pthread_mutex_unlock(&event->Mutex);
return result;
}
#ifdef WFMO
int WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds, int &waitIndex)
{
neosmart_wfmo_t wfmo = new neosmart_wfmo_t_;
int result = pthread_mutex_init(&wfmo->Mutex, 0);
if(result != 0)
return result;
result = pthread_cond_init(&wfmo->CVariable, 0);
if(result != 0)
return result;
neosmart_wfmo_info_t_ waitInfo;
waitInfo.Waiter = wfmo;
waitInfo.WaitIndex = -1;
wfmo->WaitAll = waitAll;
wfmo->StillWaiting = true;
wfmo->RefCount = count + 1;
wfmo->EventStatus.resize(count, false);
pthread_mutex_lock(&wfmo->Mutex);
for(int i = 0; i < count; ++i)
{
int result = pthread_mutex_lock(&events[i]->Mutex);
if(result != 0)
return result;
waitInfo.WaitIndex++;
events[i]->RegisteredWaits.push_back(waitInfo);
pthread_mutex_unlock(&events[i]->Mutex);
}
timespec ts;
if(milliseconds != -1)
{
timeval tv;
gettimeofday(&tv, NULL);
uint64_t nanoseconds = tv.tv_sec * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + tv.tv_usec * 1000;
ts.tv_sec = nanoseconds / 1000 / 1000 / 1000;
ts.tv_nsec = (nanoseconds - ts.tv_sec * 1000 * 1000 * 1000);
}
bool done = false;
while(!done)
{
//One (or more) of the events we're monitoring has been triggered?
for(int i = 0; i < count; ++i)
{
if(!waitAll && wfmo->EventStatus[i])
{
done = true;
waitIndex = i;
break;
}
if(waitAll && !wfmo->EventStatus[i])
{
break;
}
}
if(!done)
{
if(milliseconds != -1)
{
result = pthread_cond_timedwait(&wfmo->CVariable, &wfmo->Mutex, &ts);
}
else
{
result = pthread_cond_wait(&wfmo->CVariable, &wfmo->Mutex);
}
if(result != 0)
break;
}
}
--wfmo->RefCount;
if(wfmo->RefCount == 0)
{
wfmo->Destroy();
delete wfmo;
}
else
{
pthread_mutex_unlock(&wfmo->Mutex);
}
return result;
}
#endif
int DestroyEvent(neosmart_event_t event)
{
int result = pthread_cond_destroy(&event->CVariable);
if(result != 0)
return result;
result = pthread_mutex_destroy(&event->Mutex);
if(result != 0)
return result;
delete event;
return 0;
}
int SetEvent(neosmart_event_t event)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
event->State = true;
//Depending on the event type, we either trigger everyone or only one
if(event->AutoReset)
{
#ifdef WFMO
bool skipCV = false;
while(!event->RegisteredWaits.empty())
{
neosmart_wfmo_info_t i = &event->RegisteredWaits.back();
pthread_mutex_lock(&i->Waiter->Mutex);
--i->Waiter->RefCount;
if(!i->Waiter->StillWaiting)
{
if(i->Waiter->RefCount == 0)
{
i->Waiter->Destroy();
delete i->Waiter;
}
else
{
pthread_mutex_unlock(&i->Waiter->Mutex);
}
event->RegisteredWaits.pop_back();
continue;
}
skipCV = true;
i->Waiter->EventStatus[i->WaitIndex] = true;
if(!i->Waiter->WaitAll)
i->Waiter->StillWaiting = false;
result = pthread_cond_signal(&i->Waiter->CVariable);
pthread_mutex_unlock(&i->Waiter->Mutex);
event->RegisteredWaits.pop_back();
break;
}
if(!skipCV)
#endif
result = pthread_cond_signal(&event->CVariable);
}
else
{
#ifdef WFMO
for(int i = 0; i < event->RegisteredWaits.size(); ++i)
{
neosmart_wfmo_info_t info = &event->RegisteredWaits[i];
pthread_mutex_lock(&info->Waiter->Mutex);
--info->Waiter->RefCount;
if(!info->Waiter->StillWaiting)
{
if(info->Waiter->RefCount == 0)
{
info->Waiter->Destroy();
delete info->Waiter;
}
else
{
pthread_mutex_unlock(&info->Waiter->Mutex);
}
continue;
}
info->Waiter->EventStatus[info->WaitIndex] = true;
pthread_cond_signal(&info->Waiter->CVariable);
pthread_mutex_unlock(&info->Waiter->Mutex);
}
event->RegisteredWaits.clear();
#endif
result = pthread_cond_broadcast(&event->CVariable);
}
pthread_mutex_unlock(&event->Mutex);
return result;
}
int ResetEvent(neosmart_event_t event)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
event->State = false;
pthread_mutex_unlock(&event->Mutex);
return result;
}
}
<|endoftext|> |
<commit_before>#ifdef WITH_BASISU
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wunknown-warning-option"
#pragma GCC diagnostic ignored "-Wuninitialized-const-reference"
#endif
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wclass-memaccess"
#pragma GCC diagnostic ignored "-Wdeprecated-copy"
#pragma GCC diagnostic ignored "-Wextra"
#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#pragma GCC diagnostic ignored "-Wmisleading-indentation"
#pragma GCC diagnostic ignored "-Wparentheses"
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wunused-value"
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#pragma GCC diagnostic ignored "-Wstrict-aliasing" // TODO: https://github.com/BinomialLLC/basis_universal/pull/275
#pragma GCC diagnostic ignored "-Wstringop-overflow"
#endif
#ifdef _MSC_VER
#pragma warning(disable : 4702) // unreachable code
#pragma warning(disable : 4005) // macro redefinition
#endif
#define BASISU_NO_ITERATOR_DEBUG_LEVEL
#if defined(_MSC_VER) && !defined(__clang__) && (defined(_M_IX86) || defined(_M_X64))
#define BASISU_SUPPORT_SSE 1
#endif
#if defined(__SSE4_1__)
#define BASISU_SUPPORT_SSE 1
#endif
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#endif
#include "encoder/basisu_backend.cpp"
#include "encoder/basisu_basis_file.cpp"
#include "encoder/basisu_bc7enc.cpp"
#include "encoder/basisu_comp.cpp"
#include "encoder/basisu_enc.cpp"
#include "encoder/basisu_etc.cpp"
#include "encoder/basisu_frontend.cpp"
#include "encoder/basisu_gpu_texture.cpp"
#include "encoder/basisu_kernels_sse.cpp"
#include "encoder/basisu_opencl.cpp"
#include "encoder/basisu_pvrtc1_4.cpp"
#include "encoder/basisu_resample_filters.cpp"
#include "encoder/basisu_resampler.cpp"
#include "encoder/basisu_ssim.cpp"
#include "encoder/basisu_uastc_enc.cpp"
#include "encoder/jpgd.cpp"
#include "encoder/pvpngreader.cpp"
#include "transcoder/basisu_transcoder.cpp"
#undef CLAMP
#include "zstd/zstd.c"
#endif
<commit_msg>gltfpack: Fix clang warning on new macOS/Xcode<commit_after>#ifdef WITH_BASISU
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wunknown-warning-option"
#pragma GCC diagnostic ignored "-Wuninitialized-const-reference"
#endif
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wclass-memaccess"
#pragma GCC diagnostic ignored "-Wdeprecated-copy"
#pragma GCC diagnostic ignored "-Wextra"
#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#pragma GCC diagnostic ignored "-Wmisleading-indentation"
#pragma GCC diagnostic ignored "-Wparentheses"
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wunused-value"
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#pragma GCC diagnostic ignored "-Wstrict-aliasing" // TODO: https://github.com/BinomialLLC/basis_universal/pull/275
#pragma GCC diagnostic ignored "-Wstringop-overflow"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#endif
#ifdef _MSC_VER
#pragma warning(disable : 4702) // unreachable code
#pragma warning(disable : 4005) // macro redefinition
#endif
#define BASISU_NO_ITERATOR_DEBUG_LEVEL
#if defined(_MSC_VER) && !defined(__clang__) && (defined(_M_IX86) || defined(_M_X64))
#define BASISU_SUPPORT_SSE 1
#endif
#if defined(__SSE4_1__)
#define BASISU_SUPPORT_SSE 1
#endif
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#endif
#include "encoder/basisu_backend.cpp"
#include "encoder/basisu_basis_file.cpp"
#include "encoder/basisu_bc7enc.cpp"
#include "encoder/basisu_comp.cpp"
#include "encoder/basisu_enc.cpp"
#include "encoder/basisu_etc.cpp"
#include "encoder/basisu_frontend.cpp"
#include "encoder/basisu_gpu_texture.cpp"
#include "encoder/basisu_kernels_sse.cpp"
#include "encoder/basisu_opencl.cpp"
#include "encoder/basisu_pvrtc1_4.cpp"
#include "encoder/basisu_resample_filters.cpp"
#include "encoder/basisu_resampler.cpp"
#include "encoder/basisu_ssim.cpp"
#include "encoder/basisu_uastc_enc.cpp"
#include "encoder/jpgd.cpp"
#include "encoder/pvpngreader.cpp"
#include "transcoder/basisu_transcoder.cpp"
#undef CLAMP
#include "zstd/zstd.c"
#endif
<|endoftext|> |
<commit_before>#ifndef POWERSET_HPP_
#define POWERSET_HPP_
#include "iterbase.hpp"
#include "combinations.hpp"
#include <vector>
#include <initializer_list>
#include <utility>
#include <iterator>
namespace iter {
template <typename Container,
typename CombinatorType=
decltype(combinations(std::declval<Container&>(), 0))>
class Powersetter {
private:
Container container;
std::vector<CombinatorType> combinators;
public:
Powersetter(Container container)
: container(std::forward<Container>(container))
{
for (std::size_t i = 0; i <= this->container.size(); ++i) {
combinators.push_back(combinations(this->container, i));
}
}
class Iterator {
private:
std::size_t container_size;
std::size_t list_size = 0;
bool not_done = true;
std::vector<CombinatorType>& combinators;
std::vector<iterator_type<CombinatorType>> inner_iters;
public:
Iterator(Container& container,
std::vector<CombinatorType>& combs)
: container_size{container.size()},
combinators(combs)
{
for (auto& comb : combinators) {
inner_iters.push_back(std::begin(comb));
}
}
Iterator& operator++() {
++inner_iters[list_size];
if (!(inner_iters[list_size] != inner_iters[list_size])) {
++list_size;
}
if (container_size < list_size) {
not_done = false;
}
return *this;
}
auto operator*() -> decltype(*inner_iters[0]) {
return *(inner_iters[list_size]);
}
bool operator != (const Iterator&) {
return not_done;
}
};
Iterator begin() {
return {this->container, this->combinators};
}
Iterator end() {
return {this->container, this->combinators};
}
};
template <typename Container>
Powersetter<Container> powerset(Container&& container) {
return {std::forward<Container>(container)};
}
template <typename T>
Powersetter<std::initializer_list<T>> powerset(
std::initializer_list<T> il) {
return {il};
}
}
#endif // #ifndef POWERSET_HPP_
<commit_msg>Removes .size() requirement from powerset argument<commit_after>#ifndef POWERSET_HPP_
#define POWERSET_HPP_
#include "iterbase.hpp"
#include "combinations.hpp"
#include "enumerate.hpp"
#include <cassert>
#include <vector>
#include <initializer_list>
#include <utility>
#include <iterator>
namespace iter {
template <typename Container,
typename CombinatorType=
decltype(combinations(std::declval<Container&>(), 0))>
class Powersetter {
private:
Container container;
std::vector<CombinatorType> combinators;
public:
Powersetter(Container in_container)
: container(std::forward<Container>(in_container))
{
std::size_t i = 0;
for (auto iter = std::begin(this->container),
end = std::end(this->container);
iter != end;
++iter, ++i) {
combinators.push_back(combinations(this->container, i));
}
combinators.push_back(combinations(this->container, i));
}
class Iterator {
private:
std::size_t container_size;
std::size_t list_size = 0;
bool not_done = true;
std::vector<CombinatorType>& combinators;
std::vector<iterator_type<CombinatorType>> inner_iters;
public:
Iterator(std::vector<CombinatorType>& combs)
: container_size{combs.size() - 1},
combinators(combs)
{
for (auto& comb : combinators) {
inner_iters.push_back(std::begin(comb));
}
}
Iterator& operator++() {
++inner_iters[list_size];
if (!(inner_iters[list_size] != inner_iters[list_size])) {
++list_size;
}
if (container_size < list_size) {
not_done = false;
}
return *this;
}
auto operator*() -> decltype(*inner_iters[0]) {
return *(inner_iters[list_size]);
}
bool operator != (const Iterator&) {
return not_done;
}
};
Iterator begin() {
return {this->combinators};
}
Iterator end() {
return {this->combinators};
}
};
template <typename Container>
Powersetter<Container> powerset(Container&& container) {
return {std::forward<Container>(container)};
}
template <typename T>
Powersetter<std::initializer_list<T>> powerset(
std::initializer_list<T> il) {
return {il};
}
}
#endif // #ifndef POWERSET_HPP_
<|endoftext|> |
<commit_before>/*
* WIN32 Events for POSIX
* Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net>
* Copyright (C) 2011 - 2012 by NeoSmart Technologies
* This code is released under the terms of the MIT License
*/
#include "pevents.h"
#include <assert.h>
#include <errno.h>
#include <sys/time.h>
#ifdef WFMO
#include <vector>
#include <deque>
#endif
namespace neosmart
{
#ifdef WFMO
struct neosmart_wfmo_t_
{
pthread_mutex_t Mutex;
pthread_cond_t CVariable;
std::vector<bool> EventStatus;
bool StillWaiting;
int RefCount;
bool WaitAll;
void Destroy()
{
pthread_mutex_destroy(&Mutex);
pthread_cond_destroy(&CVariable);
}
};
typedef neosmart_wfmo_t_ *neosmart_wfmo_t;
struct neosmart_wfmo_info_t_
{
neosmart_wfmo_t Waiter;
int WaitIndex;
};
typedef neosmart_wfmo_info_t_ *neosmart_wfmo_info_t;
#endif
struct neosmart_event_t_
{
bool AutoReset;
pthread_cond_t CVariable;
pthread_mutex_t Mutex;
bool State;
#ifdef WFMO
std::deque<neosmart_wfmo_info_t_> RegisteredWaits;
#endif
};
neosmart_event_t CreateEvent(bool manualReset, bool initialState)
{
neosmart_event_t event = new neosmart_event_t_;
int result = pthread_cond_init(&event->CVariable, 0);
if(result != 0)
return NULL;
result = pthread_mutex_init(&event->Mutex, 0);
if(result != 0)
return NULL;
event->State = false;
event->AutoReset = !manualReset;
if(initialState && SetEvent(event) != 0)
return NULL; //Shouldn't ever happen
return event;
}
int UnlockedWaitForEvent(neosmart_event_t event, uint64_t milliseconds)
{
int result = 0;
if(!event->State)
{
//Zero-timeout event state check optimization
if(milliseconds == 0)
{
return ETIMEDOUT;
}
timespec ts;
if(milliseconds != (uint64_t) -1)
{
timeval tv;
gettimeofday(&tv, NULL);
uint64_t nanoseconds = ((uint64_t) tv.tv_sec) * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + ((uint64_t) tv.tv_usec) * 1000;
ts.tv_sec = nanoseconds / 1000 / 1000 / 1000;
ts.tv_nsec = (nanoseconds - ((uint64_t) ts.tv_sec) * 1000 * 1000 * 1000);
}
do
{
//Regardless of whether it's an auto-reset or manual-reset event:
//wait to obtain the event, then lock anyone else out
if(milliseconds != (uint64_t) -1)
{
result = pthread_cond_timedwait(&event->CVariable, &event->Mutex, &ts);
}
else
{
result = pthread_cond_wait(&event->CVariable, &event->Mutex);
}
} while(result == 0 && !event->State);
if(result == 0 && event->AutoReset)
{
//We've only accquired the event if the wait succeeded
event->State = false;
}
}
else if(event->AutoReset)
{
//It's an auto-reset event that's currently available;
//we need to stop anyone else from using it
result = 0;
event->State = false;
}
//Else we're trying to obtain a manual reset event with a signalled state;
//don't do anything
return result;
}
int WaitForEvent(neosmart_event_t event, uint64_t milliseconds)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
result = UnlockedWaitForEvent(event, milliseconds);
pthread_mutex_unlock(&event->Mutex);
return result;
}
#ifdef WFMO
int WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds)
{
int unused;
return WaitForMultipleEvents(events, count, waitAll, milliseconds, unused);
}
int WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds, int &waitIndex)
{
neosmart_wfmo_t wfmo = new neosmart_wfmo_t_;
int result = pthread_mutex_init(&wfmo->Mutex, 0);
if(result != 0)
{
delete wfmo;
return result;
}
result = pthread_cond_init(&wfmo->CVariable, 0);
if(result != 0)
{
delete wfmo;
return result;
}
neosmart_wfmo_info_t_ waitInfo;
waitInfo.Waiter = wfmo;
waitInfo.WaitIndex = -1;
wfmo->WaitAll = waitAll;
wfmo->StillWaiting = true;
wfmo->RefCount = 1;
wfmo->EventStatus.resize(count, false);
pthread_mutex_lock(&wfmo->Mutex);
bool done = false;
waitIndex = -1;
for(int i = 0; i < count; ++i)
{
waitInfo.WaitIndex = i;
//Must not release lock until RegisteredWait is potentially added
int result = pthread_mutex_lock(&events[i]->Mutex);
if(result != 0)
{
delete wfmo;
return result;
}
if(UnlockedWaitForEvent(events[i], 0) == 0)
{
result = pthread_mutex_unlock(&events[i]->Mutex);
if(result != 0)
{
delete wfmo;
return result;
}
wfmo->EventStatus[i] = true;
if(!waitAll)
{
waitIndex = i;
done = true;
break;
}
}
else
{
events[i]->RegisteredWaits.push_back(waitInfo);
++wfmo->RefCount;
pthread_mutex_unlock(&events[i]->Mutex);
}
}
timespec ts;
if(!done)
{
if(milliseconds == 0)
{
result = ETIMEDOUT;
done = true;
}
else if(milliseconds != (uint64_t) -1)
{
timeval tv;
gettimeofday(&tv, NULL);
uint64_t nanoseconds = ((uint64_t) tv.tv_sec) * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + ((uint64_t) tv.tv_usec) * 1000;
ts.tv_sec = nanoseconds / 1000 / 1000 / 1000;
ts.tv_nsec = (nanoseconds - ((uint64_t) ts.tv_sec) * 1000 * 1000 * 1000);
}
}
while(!done)
{
//One (or more) of the events we're monitoring has been triggered?
//If we're waiting for all events, assume we're done and check if there's an event that hasn't fired
//But if we're waiting for just one event, assume we're not done until we find a fired event
done = waitAll;
for(int i = 0; i < count; ++i)
{
if(!waitAll && wfmo->EventStatus[i])
{
done = true;
waitIndex = i;
break;
}
if(waitAll && !wfmo->EventStatus[i])
{
done = false;
break;
}
}
if(!done)
{
if(milliseconds != (uint64_t) -1)
{
result = pthread_cond_timedwait(&wfmo->CVariable, &wfmo->Mutex, &ts);
}
else
{
result = pthread_cond_wait(&wfmo->CVariable, &wfmo->Mutex);
}
if(result != 0)
break;
}
}
wfmo->StillWaiting = false;
--wfmo->RefCount;
if(wfmo->RefCount == 0)
{
wfmo->Destroy();
delete wfmo;
}
else
{
pthread_mutex_unlock(&wfmo->Mutex);
}
return result;
}
#endif
int DestroyEvent(neosmart_event_t event)
{
int result = pthread_cond_destroy(&event->CVariable);
if(result != 0)
return result;
result = pthread_mutex_destroy(&event->Mutex);
if(result != 0)
return result;
delete event;
return 0;
}
int SetEvent(neosmart_event_t event)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
event->State = true;
//Depending on the event type, we either trigger everyone or only one
if(event->AutoReset)
{
#ifdef WFMO
while(!event->RegisteredWaits.empty())
{
neosmart_wfmo_info_t i = &event->RegisteredWaits.front();
pthread_mutex_lock(&i->Waiter->Mutex);
--i->Waiter->RefCount;
if(!i->Waiter->StillWaiting)
{
if(i->Waiter->RefCount == 0)
{
i->Waiter->Destroy();
delete i->Waiter;
}
else
{
pthread_mutex_unlock(&i->Waiter->Mutex);
}
event->RegisteredWaits.pop_front();
continue;
}
event->State = false;
i->Waiter->EventStatus[i->WaitIndex] = true;
if(!i->Waiter->WaitAll)
i->Waiter->StillWaiting = false;
result = pthread_cond_signal(&i->Waiter->CVariable);
pthread_mutex_unlock(&i->Waiter->Mutex);
event->RegisteredWaits.pop_front();
break;
}
#endif
//event->State can be false if compiled with WFMO support
if(event->State)
{
result = pthread_cond_signal(&event->CVariable);
}
}
else
{
#ifdef WFMO
for(size_t i = 0; i < event->RegisteredWaits.size(); ++i)
{
neosmart_wfmo_info_t info = &event->RegisteredWaits[i];
pthread_mutex_lock(&info->Waiter->Mutex);
--info->Waiter->RefCount;
if(!info->Waiter->StillWaiting)
{
if(info->Waiter->RefCount == 0)
{
info->Waiter->Destroy();
delete info->Waiter;
}
else
{
pthread_mutex_unlock(&info->Waiter->Mutex);
}
continue;
}
info->Waiter->EventStatus[info->WaitIndex] = true;
pthread_cond_signal(&info->Waiter->CVariable);
pthread_mutex_unlock(&info->Waiter->Mutex);
}
event->RegisteredWaits.clear();
#endif
result = pthread_cond_broadcast(&event->CVariable);
}
pthread_mutex_unlock(&event->Mutex);
return result;
}
int ResetEvent(neosmart_event_t event)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
event->State = false;
pthread_mutex_unlock(&event->Mutex);
return result;
}
}
<commit_msg>Performance improvements by unlocking before signalling CVariables<commit_after>/*
* WIN32 Events for POSIX
* Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net>
* Copyright (C) 2011 - 2012 by NeoSmart Technologies
* This code is released under the terms of the MIT License
*/
#include "pevents.h"
#include <assert.h>
#include <errno.h>
#include <sys/time.h>
#ifdef WFMO
#include <vector>
#include <deque>
#endif
namespace neosmart
{
#ifdef WFMO
struct neosmart_wfmo_t_
{
pthread_mutex_t Mutex;
pthread_cond_t CVariable;
std::vector<bool> EventStatus;
bool StillWaiting;
int RefCount;
bool WaitAll;
void Destroy()
{
pthread_mutex_destroy(&Mutex);
pthread_cond_destroy(&CVariable);
}
};
typedef neosmart_wfmo_t_ *neosmart_wfmo_t;
struct neosmart_wfmo_info_t_
{
neosmart_wfmo_t Waiter;
int WaitIndex;
};
typedef neosmart_wfmo_info_t_ *neosmart_wfmo_info_t;
#endif
struct neosmart_event_t_
{
bool AutoReset;
pthread_cond_t CVariable;
pthread_mutex_t Mutex;
bool State;
#ifdef WFMO
std::deque<neosmart_wfmo_info_t_> RegisteredWaits;
#endif
};
neosmart_event_t CreateEvent(bool manualReset, bool initialState)
{
neosmart_event_t event = new neosmart_event_t_;
int result = pthread_cond_init(&event->CVariable, 0);
if(result != 0)
return NULL;
result = pthread_mutex_init(&event->Mutex, 0);
if(result != 0)
return NULL;
event->State = false;
event->AutoReset = !manualReset;
if(initialState && SetEvent(event) != 0)
return NULL; //Shouldn't ever happen
return event;
}
int UnlockedWaitForEvent(neosmart_event_t event, uint64_t milliseconds)
{
int result = 0;
if(!event->State)
{
//Zero-timeout event state check optimization
if(milliseconds == 0)
{
return ETIMEDOUT;
}
timespec ts;
if(milliseconds != (uint64_t) -1)
{
timeval tv;
gettimeofday(&tv, NULL);
uint64_t nanoseconds = ((uint64_t) tv.tv_sec) * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + ((uint64_t) tv.tv_usec) * 1000;
ts.tv_sec = nanoseconds / 1000 / 1000 / 1000;
ts.tv_nsec = (nanoseconds - ((uint64_t) ts.tv_sec) * 1000 * 1000 * 1000);
}
do
{
//Regardless of whether it's an auto-reset or manual-reset event:
//wait to obtain the event, then lock anyone else out
if(milliseconds != (uint64_t) -1)
{
result = pthread_cond_timedwait(&event->CVariable, &event->Mutex, &ts);
}
else
{
result = pthread_cond_wait(&event->CVariable, &event->Mutex);
}
} while(result == 0 && !event->State);
if(result == 0 && event->AutoReset)
{
//We've only accquired the event if the wait succeeded
event->State = false;
}
}
else if(event->AutoReset)
{
//It's an auto-reset event that's currently available;
//we need to stop anyone else from using it
result = 0;
event->State = false;
}
//Else we're trying to obtain a manual reset event with a signalled state;
//don't do anything
return result;
}
int WaitForEvent(neosmart_event_t event, uint64_t milliseconds)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
result = UnlockedWaitForEvent(event, milliseconds);
pthread_mutex_unlock(&event->Mutex);
return result;
}
#ifdef WFMO
int WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds)
{
int unused;
return WaitForMultipleEvents(events, count, waitAll, milliseconds, unused);
}
int WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds, int &waitIndex)
{
neosmart_wfmo_t wfmo = new neosmart_wfmo_t_;
int result = pthread_mutex_init(&wfmo->Mutex, 0);
if(result != 0)
{
delete wfmo;
return result;
}
result = pthread_cond_init(&wfmo->CVariable, 0);
if(result != 0)
{
delete wfmo;
return result;
}
neosmart_wfmo_info_t_ waitInfo;
waitInfo.Waiter = wfmo;
waitInfo.WaitIndex = -1;
wfmo->WaitAll = waitAll;
wfmo->StillWaiting = true;
wfmo->RefCount = 1;
wfmo->EventStatus.resize(count, false);
pthread_mutex_lock(&wfmo->Mutex);
bool done = false;
waitIndex = -1;
for(int i = 0; i < count; ++i)
{
waitInfo.WaitIndex = i;
//Must not release lock until RegisteredWait is potentially added
int result = pthread_mutex_lock(&events[i]->Mutex);
if(result != 0)
{
delete wfmo;
return result;
}
if(UnlockedWaitForEvent(events[i], 0) == 0)
{
result = pthread_mutex_unlock(&events[i]->Mutex);
if(result != 0)
{
delete wfmo;
return result;
}
wfmo->EventStatus[i] = true;
if(!waitAll)
{
waitIndex = i;
done = true;
break;
}
}
else
{
events[i]->RegisteredWaits.push_back(waitInfo);
++wfmo->RefCount;
pthread_mutex_unlock(&events[i]->Mutex);
}
}
timespec ts;
if(!done)
{
if(milliseconds == 0)
{
result = ETIMEDOUT;
done = true;
}
else if(milliseconds != (uint64_t) -1)
{
timeval tv;
gettimeofday(&tv, NULL);
uint64_t nanoseconds = ((uint64_t) tv.tv_sec) * 1000 * 1000 * 1000 + milliseconds * 1000 * 1000 + ((uint64_t) tv.tv_usec) * 1000;
ts.tv_sec = nanoseconds / 1000 / 1000 / 1000;
ts.tv_nsec = (nanoseconds - ((uint64_t) ts.tv_sec) * 1000 * 1000 * 1000);
}
}
while(!done)
{
//One (or more) of the events we're monitoring has been triggered?
//If we're waiting for all events, assume we're done and check if there's an event that hasn't fired
//But if we're waiting for just one event, assume we're not done until we find a fired event
done = waitAll;
for(int i = 0; i < count; ++i)
{
if(!waitAll && wfmo->EventStatus[i])
{
done = true;
waitIndex = i;
break;
}
if(waitAll && !wfmo->EventStatus[i])
{
done = false;
break;
}
}
if(!done)
{
if(milliseconds != (uint64_t) -1)
{
result = pthread_cond_timedwait(&wfmo->CVariable, &wfmo->Mutex, &ts);
}
else
{
result = pthread_cond_wait(&wfmo->CVariable, &wfmo->Mutex);
}
if(result != 0)
break;
}
}
wfmo->StillWaiting = false;
--wfmo->RefCount;
if(wfmo->RefCount == 0)
{
wfmo->Destroy();
delete wfmo;
}
else
{
pthread_mutex_unlock(&wfmo->Mutex);
}
return result;
}
#endif
int DestroyEvent(neosmart_event_t event)
{
int result = pthread_cond_destroy(&event->CVariable);
if(result != 0)
return result;
result = pthread_mutex_destroy(&event->Mutex);
if(result != 0)
return result;
delete event;
return 0;
}
int SetEvent(neosmart_event_t event)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
event->State = true;
//Depending on the event type, we either trigger everyone or only one
if(event->AutoReset)
{
#ifdef WFMO
while(!event->RegisteredWaits.empty())
{
neosmart_wfmo_info_t i = &event->RegisteredWaits.front();
pthread_mutex_lock(&i->Waiter->Mutex);
--i->Waiter->RefCount;
if(!i->Waiter->StillWaiting)
{
if(i->Waiter->RefCount == 0)
{
i->Waiter->Destroy();
delete i->Waiter;
}
else
{
pthread_mutex_unlock(&i->Waiter->Mutex);
}
event->RegisteredWaits.pop_front();
continue;
}
event->State = false;
i->Waiter->EventStatus[i->WaitIndex] = true;
if(!i->Waiter->WaitAll)
i->Waiter->StillWaiting = false;
pthread_mutex_unlock(&i->Waiter->Mutex);
result = pthread_cond_signal(&i->Waiter->CVariable);
event->RegisteredWaits.pop_front();
pthread_mutex_unlock(&event->Mutex);
return result;
}
#endif
//event->State can be false if compiled with WFMO support
if(event->State)
{
pthread_mutex_unlock(&event->Mutex);
result = pthread_cond_signal(&event->CVariable);
return result;
}
}
else
{
#ifdef WFMO
for(size_t i = 0; i < event->RegisteredWaits.size(); ++i)
{
neosmart_wfmo_info_t info = &event->RegisteredWaits[i];
pthread_mutex_lock(&info->Waiter->Mutex);
--info->Waiter->RefCount;
if(!info->Waiter->StillWaiting)
{
if(info->Waiter->RefCount == 0)
{
info->Waiter->Destroy();
delete info->Waiter;
}
else
{
pthread_mutex_unlock(&info->Waiter->Mutex);
}
continue;
}
info->Waiter->EventStatus[info->WaitIndex] = true;
pthread_mutex_unlock(&info->Waiter->Mutex);
pthread_cond_signal(&info->Waiter->CVariable);
}
event->RegisteredWaits.clear();
#endif
pthread_mutex_unlock(&event->Mutex);
result = pthread_cond_broadcast(&event->CVariable);
}
return result;
}
int ResetEvent(neosmart_event_t event)
{
int result = pthread_mutex_lock(&event->Mutex);
if(result != 0)
return result;
event->State = false;
pthread_mutex_unlock(&event->Mutex);
return result;
}
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
static void make_bitmap(SkBitmap* bitmap) {
bitmap->setConfig(SkBitmap::kARGB_8888_Config, 64, 64);
bitmap->allocPixels();
SkCanvas canvas(*bitmap);
canvas.drawColor(SK_ColorRED);
SkPaint paint;
paint.setAntiAlias(true);
const SkPoint pts[] = { { 0, 0 }, { 64, 64 } };
const SkColor colors[] = { SK_ColorWHITE, SK_ColorBLUE };
paint.setShader(SkGradientShader::CreateLinear(pts, colors, NULL, 2,
SkShader::kClamp_TileMode))->unref();
canvas.drawCircle(32, 32, 32, paint);
}
class DrawBitmapRect2 : public skiagm::GM {
bool fUseIRect;
public:
DrawBitmapRect2(bool useIRect) : fUseIRect(useIRect) {
}
protected:
virtual SkString onShortName() SK_OVERRIDE {
SkString str;
str.printf("bitmaprect_%s", fUseIRect ? "i" : "s");
return str;
}
virtual SkISize onISize() SK_OVERRIDE {
return SkISize::Make(640, 480);
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
canvas->drawColor(0xFFCCCCCC);
const SkIRect src[] = {
{ 0, 0, 32, 32 },
{ 0, 0, 80, 80 },
{ 32, 32, 96, 96 },
{ -32, -32, 32, 32, }
};
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
// paint.setColor(SK_ColorGREEN);
SkBitmap bitmap;
make_bitmap(&bitmap);
SkRect dstR = { 0, 200, 128, 380 };
canvas->translate(16, 40);
for (size_t i = 0; i < SK_ARRAY_COUNT(src); i++) {
SkRect srcR;
srcR.set(src[i]);
canvas->drawBitmap(bitmap, 0, 0, &paint);
if (fUseIRect) {
canvas->drawBitmapRectToRect(bitmap, &srcR, dstR, &paint);
} else {
canvas->drawBitmapRect(bitmap, &src[i], dstR, &paint);
}
canvas->drawRect(dstR, paint);
canvas->drawRect(srcR, paint);
canvas->translate(160, 0);
}
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static skiagm::GM* MyFactory0(void*) { return new DrawBitmapRect2(false); }
static skiagm::GM* MyFactory1(void*) { return new DrawBitmapRect2(true); }
static skiagm::GMRegistry reg0(MyFactory0);
static skiagm::GMRegistry reg1(MyFactory1);
<commit_msg>Added more drawBitmapRectToRect tests<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
static void make_bitmap(SkBitmap* bitmap) {
bitmap->setConfig(SkBitmap::kARGB_8888_Config, 64, 64);
bitmap->allocPixels();
SkCanvas canvas(*bitmap);
canvas.drawColor(SK_ColorRED);
SkPaint paint;
paint.setAntiAlias(true);
const SkPoint pts[] = { { 0, 0 }, { 64, 64 } };
const SkColor colors[] = { SK_ColorWHITE, SK_ColorBLUE };
paint.setShader(SkGradientShader::CreateLinear(pts, colors, NULL, 2,
SkShader::kClamp_TileMode))->unref();
canvas.drawCircle(32, 32, 32, paint);
}
class DrawBitmapRect2 : public skiagm::GM {
bool fUseIRect;
public:
DrawBitmapRect2(bool useIRect) : fUseIRect(useIRect) {
}
protected:
virtual SkString onShortName() SK_OVERRIDE {
SkString str;
str.printf("bitmaprect_%s", fUseIRect ? "i" : "s");
return str;
}
virtual SkISize onISize() SK_OVERRIDE {
return SkISize::Make(640, 480);
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
canvas->drawColor(0xFFCCCCCC);
const SkIRect src[] = {
{ 0, 0, 32, 32 },
{ 0, 0, 80, 80 },
{ 32, 32, 96, 96 },
{ -32, -32, 32, 32, }
};
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
SkBitmap bitmap;
make_bitmap(&bitmap);
SkRect dstR = { 0, 200, 128, 380 };
canvas->translate(16, 40);
for (size_t i = 0; i < SK_ARRAY_COUNT(src); i++) {
SkRect srcR;
srcR.set(src[i]);
canvas->drawBitmap(bitmap, 0, 0, &paint);
if (!fUseIRect) {
canvas->drawBitmapRectToRect(bitmap, &srcR, dstR, &paint);
} else {
canvas->drawBitmapRect(bitmap, &src[i], dstR, &paint);
}
canvas->drawRect(dstR, paint);
canvas->drawRect(srcR, paint);
canvas->translate(160, 0);
}
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static void make_3x3_bitmap(SkBitmap* bitmap) {
static const int gXSize = 3;
static const int gYSize = 3;
SkColor textureData[gXSize][gYSize] = {
SK_ColorRED, SK_ColorWHITE, SK_ColorBLUE,
SK_ColorGREEN, SK_ColorBLACK, SK_ColorCYAN,
SK_ColorYELLOW, SK_ColorGRAY, SK_ColorMAGENTA
};
bitmap->setConfig(SkBitmap::kARGB_8888_Config, gXSize, gYSize);
bitmap->allocPixels();
SkAutoLockPixels lock(*bitmap);
for (int y = 0; y < gYSize; y++) {
for (int x = 0; x < gXSize; x++) {
*bitmap->getAddr32(x, y) = textureData[x][y];
}
}
}
// This GM attempts to make visible any issues drawBitmapRectToRect may have
// with partial source rects. In this case the eight pixels on the border
// should be half the width/height of the central pixel, i.e.:
// __|____|__
// | |
// __|____|__
// | |
class DrawBitmapRect3 : public skiagm::GM {
public:
DrawBitmapRect3() {
this->setBGColor(SK_ColorBLACK);
}
protected:
virtual SkString onShortName() SK_OVERRIDE {
SkString str;
str.printf("3x3bitmaprect");
return str;
}
virtual SkISize onISize() SK_OVERRIDE {
return SkISize::Make(640, 480);
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
SkBitmap bitmap;
make_3x3_bitmap(&bitmap);
SkRect srcR = { 0.5f, 0.5f, 2.5f, 2.5f };
SkRect dstR = { 100, 100, 300, 200 };
canvas->drawBitmapRectToRect(bitmap, &srcR, dstR, NULL);
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static void make_big_bitmap(SkBitmap* bitmap) {
static const int gXSize = 4096;
static const int gYSize = 4096;
static const int gBorderWidth = 10;
bitmap->setConfig(SkBitmap::kARGB_8888_Config, gXSize, gYSize);
bitmap->allocPixels();
SkAutoLockPixels lock(*bitmap);
for (int y = 0; y < gYSize; ++y) {
for (int x = 0; x < gXSize; ++x) {
if (x <= gBorderWidth || x >= gXSize-gBorderWidth ||
y <= gBorderWidth || y >= gYSize-gBorderWidth) {
*bitmap->getAddr32(x, y) = 0x88FFFFFF;
} else {
*bitmap->getAddr32(x, y) = 0x88FF0000;
}
}
}
}
// This GM attempts to reveal any issues we may have when the GPU has to
// break up a large texture in order to draw it. The XOR transfer mode will
// create stripes in the image if there is imprecision in the destination
// tile placement.
class DrawBitmapRect4 : public skiagm::GM {
bool fUseIRect;
public:
DrawBitmapRect4(bool useIRect) : fUseIRect(useIRect) {
this->setBGColor(0x88444444);
}
protected:
virtual SkString onShortName() SK_OVERRIDE {
SkString str;
str.printf("bigbitmaprect_%s", fUseIRect ? "i" : "s");
return str;
}
virtual SkISize onISize() SK_OVERRIDE {
return SkISize::Make(640, 480);
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
SkXfermode* mode = SkXfermode::Create(SkXfermode::kXor_Mode);
SkPaint paint;
paint.setAlpha(128);
paint.setXfermode(mode);
SkBitmap bitmap;
make_big_bitmap(&bitmap);
SkRect srcR = { 0.0f, 0.0f, 4096.0f, 2040.0f };
SkRect dstR = { 10.1f, 10.1f, 629.9f, 469.9f };
if (!fUseIRect) {
canvas->drawBitmapRectToRect(bitmap, &srcR, dstR, &paint);
} else {
canvas->drawBitmapRect(bitmap, NULL, dstR, &paint);
}
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static skiagm::GM* MyFactory0(void*) { return new DrawBitmapRect2(false); }
static skiagm::GM* MyFactory1(void*) { return new DrawBitmapRect2(true); }
static skiagm::GM* MyFactory2(void*) { return new DrawBitmapRect3(); }
static skiagm::GM* MyFactory3(void*) { return new DrawBitmapRect4(false); }
static skiagm::GM* MyFactory4(void*) { return new DrawBitmapRect4(true); }
static skiagm::GMRegistry reg0(MyFactory0);
static skiagm::GMRegistry reg1(MyFactory1);
static skiagm::GMRegistry reg2(MyFactory2);
static skiagm::GMRegistry reg3(MyFactory3);
static skiagm::GMRegistry reg4(MyFactory4);
<|endoftext|> |
<commit_before>// $Id$
//
// Copyright (C) 2003-2010 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#define NO_IMPORT_ARRAY
#include <boost/python.hpp>
#include <string>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/QueryAtom.h>
#include <RDGeneral/types.h>
#include <Geometry/point.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/SmilesParse/SmartsWrite.h>
#include "seqs.hpp"
#include <algorithm>
namespace python = boost::python;
namespace RDKit{
namespace {
std::string qhelper(Atom::QUERYATOM_QUERY *q,int depth){
std::string res="";
if(q){
for (unsigned int i=0;i<depth;++i) res+=" ";
res += q->getDescription()+"\n";
for(Atom::QUERYATOM_QUERY::CHILD_VECT_CI ci=q->beginChildren();
ci!=q->endChildren();++ci){
res += qhelper((*ci).get(),depth+1);
}
}
return res;
}
} // end of local namespace
std::string describeQuery(const Atom*atom){
std::string res="";
if(atom->hasQuery()){
res=qhelper(atom->getQuery(),0);
}
return res;
}
void AtomSetProp(const Atom *atom, const char *key,std::string val) {
//std::cerr<<"asp: "<<atom<<" " << key<<" - " << val << std::endl;
atom->setProp(key, val);
}
int AtomHasProp(const Atom *atom, const char *key) {
//std::cerr<<"ahp: "<<atom<<" " << key<< std::endl;
int res = atom->hasProp(key);
return res;
}
std::string AtomGetProp(const Atom *atom, const char *key) {
if (!atom->hasProp(key)) {
PyErr_SetString(PyExc_KeyError,key);
throw python::error_already_set();
}
std::string res;
atom->getProp(key, res);
return res;
}
python::tuple AtomGetNeighbors(Atom *atom){
python::list res;
const ROMol *parent = &atom->getOwningMol();
ROMol::ADJ_ITER begin,end;
boost::tie(begin,end) = parent->getAtomNeighbors(atom);
while(begin!=end){
res.append(python::ptr(parent->getAtomWithIdx(*begin)));
begin++;
}
return python::tuple(res);
}
python::tuple AtomGetBonds(Atom *atom){
python::list res;
const ROMol *parent = &atom->getOwningMol();
ROMol::OEDGE_ITER begin,end;
boost::tie(begin,end) = parent->getAtomBonds(atom);
while(begin!=end){
Bond *tmpB = (*parent)[*begin].get();
res.append(python::ptr(tmpB));
begin++;
}
return python::tuple(res);
}
bool AtomIsInRing(const Atom *atom){
if(!atom->getOwningMol().getRingInfo()->isInitialized()){
MolOps::findSSSR(atom->getOwningMol());
}
return atom->getOwningMol().getRingInfo()->numAtomRings(atom->getIdx())!=0;
}
bool AtomIsInRingSize(const Atom *atom,int size){
if(!atom->getOwningMol().getRingInfo()->isInitialized()){
MolOps::findSSSR(atom->getOwningMol());
}
return atom->getOwningMol().getRingInfo()->isAtomInRingOfSize(atom->getIdx(),size);
}
std::string AtomGetSmarts(const Atom *atom){
std::string res;
if(atom->hasQuery()){
res=SmartsWrite::GetAtomSmarts(static_cast<const QueryAtom *>(atom));
} else {
res = SmilesWrite::GetAtomSmiles(atom);
}
return res;
}
// FIX: is there any reason at all to not just prevent the construction of Atoms?
std::string atomClassDoc="The class to store Atoms.\n\
Note that, though it is possible to create one, having an Atom on its own\n\
(i.e not associated with a molecule) is not particularly useful.\n";
struct atom_wrapper {
static void wrap(){
python::class_<Atom>("Atom",atomClassDoc.c_str(),python::init<std::string>())
.def(python::init<unsigned int>("Constructor, takes either an int (atomic number) or a string (atomic symbol).\n"))
.def("GetAtomicNum",&Atom::getAtomicNum,
"Returns the atomic number.")
.def("SetAtomicNum",&Atom::setAtomicNum,
"Sets the atomic number, takes an integer value as an argument")
.def("GetSymbol",&Atom::getSymbol,
"Returns the atomic number (a string)\n")
.def("GetIdx",&Atom::getIdx,
"Returns the atom's index (ordering in the molecule)\n")
.def("GetDegree",&Atom::getDegree,
"Returns the degree of the atom in the molecule.\n\n"
" The degree of an atom is defined to be its number of\n"
" directly-bonded neighbors.\n"
" The degree is independent of bond orders, but is dependent\n"
" on whether or not Hs are explicit in the graph.\n"
)
.def("GetTotalDegree",&Atom::getTotalDegree,
"Returns the degree of the atom in the molecule including Hs.\n\n"
" The degree of an atom is defined to be its number of\n"
" directly-bonded neighbors.\n"
" The degree is independent of bond orders.\n")
.def("GetTotalNumHs",&Atom::getTotalNumHs,
(python::arg("self"),python::arg("includeNeighbors")=false),
"Returns the total number of Hs (explicit and implicit) on the atom.\n\n"
" ARGUMENTS:\n\n"
" - includeNeighbors: (optional) toggles inclusion of neighboring H atoms in the sum.\n"
" Defaults to 0.\n")
.def("GetNumImplicitHs",&Atom::getNumImplicitHs,
"Returns the total number of implicit Hs on the atom.\n")
.def("GetExplicitValence",&Atom::getExplicitValence,
"Returns the number of explicit Hs on the atom.\n")
.def("GetImplicitValence",&Atom::getImplicitValence,
"Returns the number of implicit Hs on the atom.\n")
.def("GetFormalCharge",&Atom::getFormalCharge)
.def("SetFormalCharge",&Atom::setFormalCharge)
.def("SetNoImplicit",&Atom::setNoImplicit,
"Sets a marker on the atom that *disallows* implicit Hs.\n"
" This holds even if the atom would otherwise have implicit Hs added.\n")
.def("GetNoImplicit",&Atom::getNoImplicit,
"Returns whether or not the atom is *allowed* to have implicit Hs.\n")
.def("SetNumExplicitHs",&Atom::setNumExplicitHs)
.def("GetNumExplicitHs",&Atom::getNumExplicitHs)
.def("SetIsAromatic",&Atom::setIsAromatic)
.def("GetIsAromatic",&Atom::getIsAromatic)
.def("SetMass",&Atom::setMass)
.def("GetMass",&Atom::getMass)
.def("SetNumRadicalElectrons",&Atom::setNumRadicalElectrons)
.def("GetNumRadicalElectrons",&Atom::getNumRadicalElectrons)
// NOTE: these may be used at some point in the future, but they
// aren't now, so there's no point in confusing things.
//.def("SetDativeFlag",&Atom::setDativeFlag)
//.def("GetDativeFlag",&Atom::getDativeFlag)
//.def("ClearDativeFlag",&Atom::clearDativeFlag)
.def("SetChiralTag",&Atom::setChiralTag)
.def("InvertChirality",&Atom::invertChirality)
.def("GetChiralTag",&Atom::getChiralTag)
.def("SetHybridization",&Atom::setHybridization,
"Sets the hybridization of the atom.\n"
" The argument should be a HybridizationType\n")
.def("GetHybridization",&Atom::getHybridization,
"Returns the atom's hybridization.\n")
.def("GetOwningMol",&Atom::getOwningMol,
"Returns the Mol that owns this atom.\n",
python::return_value_policy<python::reference_existing_object>())
.def("GetNeighbors",AtomGetNeighbors,
"Returns a read-only sequence of the atom's neighbors\n")
.def("GetBonds",AtomGetBonds,
"Returns a read-only sequence of the atom's bonds\n")
.def("Match",(bool (Atom::*)(const Atom *) const)&Atom::Match,
"Returns whether or not this atom matches another Atom.\n\n"
" Each Atom (or query Atom) has a query function which is\n"
" used for this type of matching.\n\n"
" ARGUMENTS:\n"
" - other: the other Atom to which to compare\n")
.def("IsInRingSize",AtomIsInRingSize,
"Returns whether or not the atom is in a ring of a particular size.\n\n"
" ARGUMENTS:\n"
" - size: the ring size to look for\n")
.def("IsInRing",AtomIsInRing,
"Returns whether or not the atom is in a ring\n\n")
.def("HasQuery",&Atom::hasQuery,
"Returns whether or not the atom has an associated query\n\n")
.def("DescribeQuery",describeQuery,
"returns a text description of the query. Primarily intended for debugging purposes.\n\n")
.def("GetSmarts",AtomGetSmarts,
"returns the SMARTS (or SMILES) string for an Atom\n\n")
// properties
.def("SetProp",AtomSetProp,
(python::arg("self"), python::arg("key"),
python::arg("val")),
"Sets an atomic property\n\n"
" ARGUMENTS:\n"
" - key: the name of the property to be set (a string).\n"
" - value: the property value (a string).\n\n"
)
.def("GetProp", AtomGetProp,
"Returns the value of the property.\n\n"
" ARGUMENTS:\n"
" - key: the name of the property to return (a string).\n\n"
" RETURNS: a string\n\n"
" NOTE:\n"
" - If the property has not been set, a KeyError exception will be raised.\n")
.def("HasProp", AtomHasProp,
"Queries a Atom to see if a particular property has been assigned.\n\n"
" ARGUMENTS:\n"
" - key: the name of the property to check for (a string).\n")
.def("GetPropNames",&Atom::getPropList,
(python::arg("self")),
"Returns a list of the properties set on the Atom.\n\n"
)
;
python::enum_<Atom::HybridizationType>("HybridizationType")
.value("UNSPECIFIED",Atom::UNSPECIFIED)
.value("SP",Atom::SP)
.value("SP2",Atom::SP2)
.value("SP3",Atom::SP3)
.value("SP3D",Atom::SP3D)
.value("SP3D2",Atom::SP3D2)
.value("OTHER",Atom::OTHER)
;
python::enum_<Atom::ChiralType>("ChiralType")
.value("CHI_UNSPECIFIED",Atom::CHI_UNSPECIFIED)
.value("CHI_TETRAHEDRAL_CW",Atom::CHI_TETRAHEDRAL_CW)
.value("CHI_TETRAHEDRAL_CCW",Atom::CHI_TETRAHEDRAL_CCW)
.value("CHI_OTHER",Atom::CHI_OTHER)
;
};
};
}// end of namespace
void wrap_atom() {
RDKit::atom_wrapper::wrap();
}
<commit_msg>fix sf.net issue 3495619<commit_after>// $Id$
//
// Copyright (C) 2003-2010 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#define NO_IMPORT_ARRAY
#include <boost/python.hpp>
#include <string>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/QueryAtom.h>
#include <RDGeneral/types.h>
#include <Geometry/point.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/SmilesParse/SmartsWrite.h>
#include "seqs.hpp"
#include <algorithm>
namespace python = boost::python;
namespace RDKit{
namespace {
std::string qhelper(Atom::QUERYATOM_QUERY *q,int depth){
std::string res="";
if(q){
for (unsigned int i=0;i<depth;++i) res+=" ";
res += q->getDescription()+"\n";
for(Atom::QUERYATOM_QUERY::CHILD_VECT_CI ci=q->beginChildren();
ci!=q->endChildren();++ci){
res += qhelper((*ci).get(),depth+1);
}
}
return res;
}
} // end of local namespace
std::string describeQuery(const Atom*atom){
std::string res="";
if(atom->hasQuery()){
res=qhelper(atom->getQuery(),0);
}
return res;
}
void AtomSetProp(const Atom *atom, const char *key,std::string val) {
//std::cerr<<"asp: "<<atom<<" " << key<<" - " << val << std::endl;
atom->setProp(key, val);
}
int AtomHasProp(const Atom *atom, const char *key) {
//std::cerr<<"ahp: "<<atom<<" " << key<< std::endl;
int res = atom->hasProp(key);
return res;
}
std::string AtomGetProp(const Atom *atom, const char *key) {
if (!atom->hasProp(key)) {
PyErr_SetString(PyExc_KeyError,key);
throw python::error_already_set();
}
std::string res;
atom->getProp(key, res);
return res;
}
python::tuple AtomGetNeighbors(Atom *atom){
python::list res;
const ROMol *parent = &atom->getOwningMol();
ROMol::ADJ_ITER begin,end;
boost::tie(begin,end) = parent->getAtomNeighbors(atom);
while(begin!=end){
res.append(python::ptr(parent->getAtomWithIdx(*begin)));
begin++;
}
return python::tuple(res);
}
python::tuple AtomGetBonds(Atom *atom){
python::list res;
const ROMol *parent = &atom->getOwningMol();
ROMol::OEDGE_ITER begin,end;
boost::tie(begin,end) = parent->getAtomBonds(atom);
while(begin!=end){
Bond *tmpB = (*parent)[*begin].get();
res.append(python::ptr(tmpB));
begin++;
}
return python::tuple(res);
}
bool AtomIsInRing(const Atom *atom){
if(!atom->getOwningMol().getRingInfo()->isInitialized()){
MolOps::findSSSR(atom->getOwningMol());
}
return atom->getOwningMol().getRingInfo()->numAtomRings(atom->getIdx())!=0;
}
bool AtomIsInRingSize(const Atom *atom,int size){
if(!atom->getOwningMol().getRingInfo()->isInitialized()){
MolOps::findSSSR(atom->getOwningMol());
}
return atom->getOwningMol().getRingInfo()->isAtomInRingOfSize(atom->getIdx(),size);
}
std::string AtomGetSmarts(const Atom *atom){
std::string res;
if(atom->hasQuery()){
res=SmartsWrite::GetAtomSmarts(static_cast<const QueryAtom *>(atom));
} else {
res = SmilesWrite::GetAtomSmiles(atom);
}
return res;
}
// FIX: is there any reason at all to not just prevent the construction of Atoms?
std::string atomClassDoc="The class to store Atoms.\n\
Note that, though it is possible to create one, having an Atom on its own\n\
(i.e not associated with a molecule) is not particularly useful.\n";
struct atom_wrapper {
static void wrap(){
python::class_<Atom>("Atom",atomClassDoc.c_str(),python::init<std::string>())
.def(python::init<unsigned int>("Constructor, takes either an int (atomic number) or a string (atomic symbol).\n"))
.def("GetAtomicNum",&Atom::getAtomicNum,
"Returns the atomic number.")
.def("SetAtomicNum",&Atom::setAtomicNum,
"Sets the atomic number, takes an integer value as an argument")
.def("GetSymbol",&Atom::getSymbol,
"Returns the atomic symbol (a string)\n")
.def("GetIdx",&Atom::getIdx,
"Returns the atom's index (ordering in the molecule)\n")
.def("GetDegree",&Atom::getDegree,
"Returns the degree of the atom in the molecule.\n\n"
" The degree of an atom is defined to be its number of\n"
" directly-bonded neighbors.\n"
" The degree is independent of bond orders, but is dependent\n"
" on whether or not Hs are explicit in the graph.\n"
)
.def("GetTotalDegree",&Atom::getTotalDegree,
"Returns the degree of the atom in the molecule including Hs.\n\n"
" The degree of an atom is defined to be its number of\n"
" directly-bonded neighbors.\n"
" The degree is independent of bond orders.\n")
.def("GetTotalNumHs",&Atom::getTotalNumHs,
(python::arg("self"),python::arg("includeNeighbors")=false),
"Returns the total number of Hs (explicit and implicit) on the atom.\n\n"
" ARGUMENTS:\n\n"
" - includeNeighbors: (optional) toggles inclusion of neighboring H atoms in the sum.\n"
" Defaults to 0.\n")
.def("GetNumImplicitHs",&Atom::getNumImplicitHs,
"Returns the total number of implicit Hs on the atom.\n")
.def("GetExplicitValence",&Atom::getExplicitValence,
"Returns the number of explicit Hs on the atom.\n")
.def("GetImplicitValence",&Atom::getImplicitValence,
"Returns the number of implicit Hs on the atom.\n")
.def("GetFormalCharge",&Atom::getFormalCharge)
.def("SetFormalCharge",&Atom::setFormalCharge)
.def("SetNoImplicit",&Atom::setNoImplicit,
"Sets a marker on the atom that *disallows* implicit Hs.\n"
" This holds even if the atom would otherwise have implicit Hs added.\n")
.def("GetNoImplicit",&Atom::getNoImplicit,
"Returns whether or not the atom is *allowed* to have implicit Hs.\n")
.def("SetNumExplicitHs",&Atom::setNumExplicitHs)
.def("GetNumExplicitHs",&Atom::getNumExplicitHs)
.def("SetIsAromatic",&Atom::setIsAromatic)
.def("GetIsAromatic",&Atom::getIsAromatic)
.def("SetMass",&Atom::setMass)
.def("GetMass",&Atom::getMass)
.def("SetNumRadicalElectrons",&Atom::setNumRadicalElectrons)
.def("GetNumRadicalElectrons",&Atom::getNumRadicalElectrons)
// NOTE: these may be used at some point in the future, but they
// aren't now, so there's no point in confusing things.
//.def("SetDativeFlag",&Atom::setDativeFlag)
//.def("GetDativeFlag",&Atom::getDativeFlag)
//.def("ClearDativeFlag",&Atom::clearDativeFlag)
.def("SetChiralTag",&Atom::setChiralTag)
.def("InvertChirality",&Atom::invertChirality)
.def("GetChiralTag",&Atom::getChiralTag)
.def("SetHybridization",&Atom::setHybridization,
"Sets the hybridization of the atom.\n"
" The argument should be a HybridizationType\n")
.def("GetHybridization",&Atom::getHybridization,
"Returns the atom's hybridization.\n")
.def("GetOwningMol",&Atom::getOwningMol,
"Returns the Mol that owns this atom.\n",
python::return_value_policy<python::reference_existing_object>())
.def("GetNeighbors",AtomGetNeighbors,
"Returns a read-only sequence of the atom's neighbors\n")
.def("GetBonds",AtomGetBonds,
"Returns a read-only sequence of the atom's bonds\n")
.def("Match",(bool (Atom::*)(const Atom *) const)&Atom::Match,
"Returns whether or not this atom matches another Atom.\n\n"
" Each Atom (or query Atom) has a query function which is\n"
" used for this type of matching.\n\n"
" ARGUMENTS:\n"
" - other: the other Atom to which to compare\n")
.def("IsInRingSize",AtomIsInRingSize,
"Returns whether or not the atom is in a ring of a particular size.\n\n"
" ARGUMENTS:\n"
" - size: the ring size to look for\n")
.def("IsInRing",AtomIsInRing,
"Returns whether or not the atom is in a ring\n\n")
.def("HasQuery",&Atom::hasQuery,
"Returns whether or not the atom has an associated query\n\n")
.def("DescribeQuery",describeQuery,
"returns a text description of the query. Primarily intended for debugging purposes.\n\n")
.def("GetSmarts",AtomGetSmarts,
"returns the SMARTS (or SMILES) string for an Atom\n\n")
// properties
.def("SetProp",AtomSetProp,
(python::arg("self"), python::arg("key"),
python::arg("val")),
"Sets an atomic property\n\n"
" ARGUMENTS:\n"
" - key: the name of the property to be set (a string).\n"
" - value: the property value (a string).\n\n"
)
.def("GetProp", AtomGetProp,
"Returns the value of the property.\n\n"
" ARGUMENTS:\n"
" - key: the name of the property to return (a string).\n\n"
" RETURNS: a string\n\n"
" NOTE:\n"
" - If the property has not been set, a KeyError exception will be raised.\n")
.def("HasProp", AtomHasProp,
"Queries a Atom to see if a particular property has been assigned.\n\n"
" ARGUMENTS:\n"
" - key: the name of the property to check for (a string).\n")
.def("GetPropNames",&Atom::getPropList,
(python::arg("self")),
"Returns a list of the properties set on the Atom.\n\n"
)
;
python::enum_<Atom::HybridizationType>("HybridizationType")
.value("UNSPECIFIED",Atom::UNSPECIFIED)
.value("SP",Atom::SP)
.value("SP2",Atom::SP2)
.value("SP3",Atom::SP3)
.value("SP3D",Atom::SP3D)
.value("SP3D2",Atom::SP3D2)
.value("OTHER",Atom::OTHER)
;
python::enum_<Atom::ChiralType>("ChiralType")
.value("CHI_UNSPECIFIED",Atom::CHI_UNSPECIFIED)
.value("CHI_TETRAHEDRAL_CW",Atom::CHI_TETRAHEDRAL_CW)
.value("CHI_TETRAHEDRAL_CCW",Atom::CHI_TETRAHEDRAL_CCW)
.value("CHI_OTHER",Atom::CHI_OTHER)
;
};
};
}// end of namespace
void wrap_atom() {
RDKit::atom_wrapper::wrap();
}
<|endoftext|> |
<commit_before>// Natron
//
/* 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/. */
/*
*Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
*contact: immarespond at gmail dot com
*
*/
#include "Curve.h"
#include <algorithm>
#include "Engine/CurvePrivate.h"
#include "Engine/Interpolation.h"
/************************************KEYFRAME************************************/
KeyFrame::KeyFrame()
: _imp(new KeyFramePrivate)
{}
KeyFrame::KeyFrame(double time, const Variant& initialValue)
: _imp(new KeyFramePrivate(time,initialValue))
{
}
KeyFrame::KeyFrame(const KeyFrame& other)
: _imp(new KeyFramePrivate(*(other._imp)))
{
}
void KeyFrame::operator=(const KeyFrame& o)
{
_imp->time = o._imp->time;
_imp->value = o._imp->value;
_imp->leftTangent = o._imp->leftTangent;
_imp->rightTangent = o._imp->rightTangent;
_imp->interpolation = o._imp->interpolation;
}
KeyFrame::~KeyFrame(){}
bool KeyFrame::operator==(const KeyFrame& o) const {
return _imp->value == o._imp->value &&
_imp->time == o._imp->time;
}
void KeyFrame::setLeftTangent(const Variant& v){
_imp->leftTangent = v;
}
void KeyFrame::setRightTangent(const Variant& v){
_imp->rightTangent = v;
}
void KeyFrame::setValue(const Variant& v){
_imp->value = v;
}
void KeyFrame::setTime(double time){
_imp->time = time;
}
void KeyFrame::setInterpolation(Natron::KeyframeType interp) { _imp->interpolation = interp; }
Natron::KeyframeType KeyFrame::getInterpolation() const { return _imp->interpolation; }
const Variant& KeyFrame::getValue() const { return _imp->value; }
double KeyFrame::getTime() const { return _imp->time; }
const Variant& KeyFrame::getLeftTangent() const { return _imp->leftTangent; }
const Variant& KeyFrame::getRightTangent() const { return _imp->rightTangent; }
/************************************CURVEPATH************************************/
Curve::Curve()
: _imp(new CurvePrivate)
{
}
Curve::Curve(Knob *owner)
: _imp(new CurvePrivate)
{
_imp->owner = owner;
}
Curve::~Curve(){ clearKeyFrames(); }
void Curve::clearKeyFrames(){
_imp->keyFrames.clear();
}
void Curve::clone(const Curve& other){
clearKeyFrames();
const KeyFrames& otherKeys = other.getKeyFrames();
for(KeyFrames::const_iterator it = otherKeys.begin();it!=otherKeys.end();++it){
_imp->keyFrames.push_back(boost::shared_ptr<KeyFrame>(new KeyFrame((*it)->getTime(),(*it)->getValue())));
}
}
double Curve::getMinimumTimeCovered() const{
assert(!_imp->keyFrames.empty());
return _imp->keyFrames.front()->getTime();
}
double Curve::getMaximumTimeCovered() const{
assert(!_imp->keyFrames.empty());
return _imp->keyFrames.back()->getTime();
}
void Curve::addKeyFrame(boost::shared_ptr<KeyFrame> cp)
{
KeyFrames::iterator newKeyIt = _imp->keyFrames.end();
if(_imp->keyFrames.empty()){
newKeyIt = _imp->keyFrames.insert(_imp->keyFrames.end(),cp);
}else{
//finding a matching or the first greater key
KeyFrames::iterator upper = _imp->keyFrames.end();
for(KeyFrames::iterator it = _imp->keyFrames.begin();it!=_imp->keyFrames.end();++it){
if((*it)->getTime() > cp->getTime()){
upper = it;
break;
}else if((*it)->getTime() == cp->getTime()){
//if the key already exists at this time, just modify it.
(*it)->setValue(cp->getValue());
return;
}
}
if(upper == _imp->keyFrames.end()){
//if we found no key that has a greater time, just append the key
newKeyIt = _imp->keyFrames.insert(_imp->keyFrames.end(),cp);
}else if(upper == _imp->keyFrames.begin()){
//if all the keys have a greater time, just insert this key at the begining
newKeyIt = _imp->keyFrames.insert(_imp->keyFrames.begin(),cp);
}else{
newKeyIt = _imp->keyFrames.insert(upper,cp);
}
}
refreshTangents(KEYFRAME_CHANGED,newKeyIt);
}
void Curve::removeKeyFrame(boost::shared_ptr<KeyFrame> cp){
KeyFrames::iterator it = std::find(_imp->keyFrames.begin(),_imp->keyFrames.end(),cp);
KeyFrames::iterator prev = it;
boost::shared_ptr<KeyFrame> prevCp;
boost::shared_ptr<KeyFrame> nextCp;
if(it != _imp->keyFrames.begin()){
--prev;
prevCp = (*prev);
}
KeyFrames::iterator next = it;
++next;
if(next != _imp->keyFrames.end()){
nextCp = (*next);
}
_imp->keyFrames.erase(it);
if(prevCp){
refreshTangents(TANGENT_CHANGED,prevCp);
}
if(nextCp){
refreshTangents(TANGENT_CHANGED,nextCp);
}
}
void Curve::removeKeyFrame(double time){
for(KeyFrames::iterator it = _imp->keyFrames.begin();it!=_imp->keyFrames.end();++it){
if((*it)->getTime() == time){
removeKeyFrame(*it);
break;
}
}
}
Variant Curve::getValueAt(double t) const {
assert(!_imp->keyFrames.empty());
if (_imp->keyFrames.size() == 1) {
//if there's only 1 keyframe, don't bother interpolating
return (*_imp->keyFrames.begin())->getValue();
}
double tcur,tnext;
double vcurDerivRight ,vnextDerivLeft ,vcur ,vnext ;
Natron::KeyframeType interp ,interpNext;
KeyFrames::const_iterator upper = _imp->keyFrames.end();
for(KeyFrames::const_iterator it = _imp->keyFrames.begin();it!=_imp->keyFrames.end();++it){
if((*it)->getTime() > t){
upper = it;
break;
}else if((*it)->getTime() == t){
//if the time is exactly the time of a keyframe, return its value
return (*it)->getValue();
}
}
//if all keys have a greater time (i.e: we search after the last keyframe)
KeyFrames::const_iterator prev = upper;
--prev;
//if we found no key that has a greater time (i.e: we search before the 1st keyframe)
if (upper == _imp->keyFrames.begin()) {
tnext = (*upper)->getTime();
vnext = (*upper)->getValue().value<double>();
vnextDerivLeft = (*upper)->getLeftTangent().value<double>();
interpNext = (*upper)->getInterpolation();
tcur = tnext - 1.;
vcur = vnext;
vcurDerivRight = 0.;
interp = Natron::KEYFRAME_NONE;
} else if (upper == _imp->keyFrames.end()) {
tcur = (*prev)->getTime();
vcur = (*prev)->getValue().value<double>();
vcurDerivRight = (*prev)->getRightTangent().value<double>();
interp = (*prev)->getInterpolation();
tnext = tcur + 1.;
vnext = vcur;
vnextDerivLeft = 0.;
interpNext = Natron::KEYFRAME_NONE;
} else {
tcur = (*prev)->getTime();
vcur = (*prev)->getValue().value<double>();
vcurDerivRight = (*prev)->getRightTangent().value<double>();
interp = (*prev)->getInterpolation();
tnext = (*upper)->getTime();
vnext = (*upper)->getValue().value<double>();
vnextDerivLeft = (*upper)->getLeftTangent().value<double>();
interpNext = (*upper)->getInterpolation();
}
double v = Natron::interpolate<double>(tcur,vcur,
vcurDerivRight,
vnextDerivLeft,
tnext,vnext,
t,
interp,
interpNext);
const Variant& firstKeyValue = _imp->keyFrames.front()->getValue();
switch(firstKeyValue.type()){
case QVariant::Int :
return Variant((int)std::floor(v+0.5));
case QVariant::Double :
return Variant(v);
case QVariant::Bool:
return Variant((bool)std::floor(v+0.5));
default:
std::string exc("The type requested ( ");
exc.append(firstKeyValue.typeName());
exc.append(") is not interpolable, it cannot animate!");
throw std::invalid_argument(exc);
}
}
bool Curve::isAnimated() const { return _imp->keyFrames.size() > 1; }
int Curve::keyFramesCount() const { return (int)_imp->keyFrames.size(); }
const KeyFrames& Curve::getKeyFrames() const { return _imp->keyFrames; }
void Curve::setKeyFrameValue(const Variant& value,boost::shared_ptr<KeyFrame> k){
if(value.toDouble() != k->getValue().toDouble()){
k->setValue(value);
evaluateCurveChanged(KEYFRAME_CHANGED,k);
}
}
void Curve::setKeyFrameTime(double time,boost::shared_ptr<KeyFrame> k){
if(time != k->getTime()){
k->setTime(time);
evaluateCurveChanged(KEYFRAME_CHANGED,k);
}
}
void Curve::setKeyFrameValueAndTime(double time,const Variant& value,boost::shared_ptr<KeyFrame> k){
if(time != k->getTime() || value.toDouble() != k->getValue().toDouble()){
k->setTime(time);
k->setValue(value);
evaluateCurveChanged(KEYFRAME_CHANGED,k);
}
}
void Curve::setKeyFrameLeftTangent(const Variant& value,boost::shared_ptr<KeyFrame> k){
if(value.toDouble() != k->getRightTangent().toDouble()){
k->setLeftTangent(value);
evaluateCurveChanged(TANGENT_CHANGED,k);
}
}
void Curve::setKeyFrameRightTangent(const Variant& value,boost::shared_ptr<KeyFrame> k){
if(k->getLeftTangent().toDouble() != value.toDouble()){
k->setRightTangent(value);
evaluateCurveChanged(TANGENT_CHANGED,k);
}
}
void Curve::setKeyFrameTangents(const Variant& left,const Variant& right,boost::shared_ptr<KeyFrame> k){
if(k->getLeftTangent().toDouble() != left.toDouble() || right.toDouble() != k->getRightTangent().toDouble()){
k->setLeftTangent(left);
k->setRightTangent(right);
evaluateCurveChanged(TANGENT_CHANGED,k);
}
}
void Curve::setKeyFrameInterpolation(Natron::KeyframeType interp,boost::shared_ptr<KeyFrame> k){
if(k->getInterpolation() != interp){
k->setInterpolation(interp);
evaluateCurveChanged(KEYFRAME_CHANGED,k);
}
}
void Curve::refreshTangents(Curve::CurveChangedReason reason, KeyFrames::iterator key){
double tcur = (*key)->getTime();
double vcur = (*key)->getValue().value<double>();
double tprev, vprev, tnext, vnext, vprevDerivRight, vnextDerivLeft;
Natron::KeyframeType prevType, nextType;
if (key == _imp->keyFrames.begin()) {
tprev = tcur;
vprev = vcur;
vprevDerivRight = 0.;
prevType = Natron::KEYFRAME_NONE;
} else {
KeyFrames::const_iterator prev = key;
--prev;
tprev = (*prev)->getTime();
vprev = (*prev)->getValue().value<double>();
vprevDerivRight = (*prev)->getRightTangent().value<double>();
prevType = (*prev)->getInterpolation();
//if prev is the first keyframe, and not edited by the user then interpolate linearly
if(prev == _imp->keyFrames.begin() && prevType != Natron::KEYFRAME_FREE &&
prevType != Natron::KEYFRAME_BROKEN){
prevType = Natron::KEYFRAME_LINEAR;
}
}
KeyFrames::const_iterator next = key;
++next;
if (next == _imp->keyFrames.end()) {
tnext = tcur;
vnext = vcur;
vnextDerivLeft = 0.;
nextType = Natron::KEYFRAME_NONE;
} else {
tnext = (*next)->getTime();
vnext = (*next)->getValue().value<double>();
vnextDerivLeft = (*next)->getLeftTangent().value<double>();
nextType = (*next)->getInterpolation();
KeyFrames::const_iterator nextnext = next;
++nextnext;
//if next is thelast keyframe, and not edited by the user then interpolate linearly
if(nextnext == _imp->keyFrames.end() && nextType != Natron::KEYFRAME_FREE &&
nextType != Natron::KEYFRAME_BROKEN){
nextType = Natron::KEYFRAME_LINEAR;
}
}
double vcurDerivLeft,vcurDerivRight;
try{
Natron::autoComputeTangents<double>(prevType,
(*key)->getInterpolation(),
nextType,
tprev, vprev,
tcur, vcur,
tnext, vnext,
vprevDerivRight,
vnextDerivLeft,
&vcurDerivLeft, &vcurDerivRight);
}catch(const std::exception& e){
std::cout << e.what() << std::endl;
assert(false);
}
(*key)->setLeftTangent(Variant(vcurDerivLeft));
(*key)->setRightTangent(Variant(vcurDerivRight));
if(reason != TANGENT_CHANGED){
evaluateCurveChanged(TANGENT_CHANGED,*key);
}
}
void Curve::refreshTangents(CurveChangedReason reason, boost::shared_ptr<KeyFrame> k){
KeyFrames::iterator it = std::find(_imp->keyFrames.begin(),_imp->keyFrames.end(),k);
assert(it!=_imp->keyFrames.end());
refreshTangents(reason,it);
}
void Curve::evaluateCurveChanged(CurveChangedReason reason,boost::shared_ptr<KeyFrame> k){
KeyFrames::iterator found = _imp->keyFrames.end();
for(KeyFrames::iterator it = _imp->keyFrames.begin();it!=_imp->keyFrames.end();++it){
if((*it) == k){
found = it;
break;
}
}
assert(found!=_imp->keyFrames.end());
if(k->getInterpolation()!= Natron::KEYFRAME_BROKEN && k->getInterpolation() != Natron::KEYFRAME_FREE
&& reason != TANGENT_CHANGED ){
refreshTangents(TANGENT_CHANGED,found);
}
KeyFrames::iterator prev = found;
if(found != _imp->keyFrames.begin()){
--prev;
if((*prev)->getInterpolation()!= Natron::KEYFRAME_BROKEN &&
(*prev)->getInterpolation()!= Natron::KEYFRAME_FREE){
refreshTangents(TANGENT_CHANGED,prev);
}
}
KeyFrames::iterator next = found;
++next;
if(next != _imp->keyFrames.end()){
if((*next)->getInterpolation()!= Natron::KEYFRAME_BROKEN &&
(*next)->getInterpolation()!= Natron::KEYFRAME_FREE){
refreshTangents(TANGENT_CHANGED,next);
}
}
_imp->owner->evaluateAnimationChange();
}
<commit_msg>use std::find_if<commit_after>// Natron
//
/* 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/. */
/*
*Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
*contact: immarespond at gmail dot com
*
*/
#include "Curve.h"
#include <algorithm>
#include "Engine/CurvePrivate.h"
#include "Engine/Interpolation.h"
/************************************KEYFRAME************************************/
KeyFrame::KeyFrame()
: _imp(new KeyFramePrivate)
{}
KeyFrame::KeyFrame(double time, const Variant& initialValue)
: _imp(new KeyFramePrivate(time,initialValue))
{
}
KeyFrame::KeyFrame(const KeyFrame& other)
: _imp(new KeyFramePrivate(*(other._imp)))
{
}
void KeyFrame::operator=(const KeyFrame& o)
{
_imp->time = o._imp->time;
_imp->value = o._imp->value;
_imp->leftTangent = o._imp->leftTangent;
_imp->rightTangent = o._imp->rightTangent;
_imp->interpolation = o._imp->interpolation;
}
KeyFrame::~KeyFrame(){}
bool KeyFrame::operator==(const KeyFrame& o) const {
return _imp->value == o._imp->value &&
_imp->time == o._imp->time;
}
void KeyFrame::setLeftTangent(const Variant& v){
_imp->leftTangent = v;
}
void KeyFrame::setRightTangent(const Variant& v){
_imp->rightTangent = v;
}
void KeyFrame::setValue(const Variant& v){
_imp->value = v;
}
void KeyFrame::setTime(double time){
_imp->time = time;
}
void KeyFrame::setInterpolation(Natron::KeyframeType interp) { _imp->interpolation = interp; }
Natron::KeyframeType KeyFrame::getInterpolation() const { return _imp->interpolation; }
const Variant& KeyFrame::getValue() const { return _imp->value; }
double KeyFrame::getTime() const { return _imp->time; }
const Variant& KeyFrame::getLeftTangent() const { return _imp->leftTangent; }
const Variant& KeyFrame::getRightTangent() const { return _imp->rightTangent; }
/************************************CURVEPATH************************************/
Curve::Curve()
: _imp(new CurvePrivate)
{
}
Curve::Curve(Knob *owner)
: _imp(new CurvePrivate)
{
_imp->owner = owner;
}
Curve::~Curve(){ clearKeyFrames(); }
void Curve::clearKeyFrames(){
_imp->keyFrames.clear();
}
void Curve::clone(const Curve& other){
clearKeyFrames();
const KeyFrames& otherKeys = other.getKeyFrames();
for(KeyFrames::const_iterator it = otherKeys.begin();it!=otherKeys.end();++it){
_imp->keyFrames.push_back(boost::shared_ptr<KeyFrame>(new KeyFrame((*it)->getTime(),(*it)->getValue())));
}
}
double Curve::getMinimumTimeCovered() const{
assert(!_imp->keyFrames.empty());
return _imp->keyFrames.front()->getTime();
}
double Curve::getMaximumTimeCovered() const{
assert(!_imp->keyFrames.empty());
return _imp->keyFrames.back()->getTime();
}
void Curve::addKeyFrame(boost::shared_ptr<KeyFrame> cp)
{
KeyFrames::iterator newKeyIt = _imp->keyFrames.end();
if(_imp->keyFrames.empty()){
newKeyIt = _imp->keyFrames.insert(_imp->keyFrames.end(),cp);
}else{
//finding a matching or the first greater key
KeyFrames::iterator upper = _imp->keyFrames.end();
for(KeyFrames::iterator it = _imp->keyFrames.begin();it!=_imp->keyFrames.end();++it){
if((*it)->getTime() > cp->getTime()){
upper = it;
break;
}else if((*it)->getTime() == cp->getTime()){
//if the key already exists at this time, just modify it.
(*it)->setValue(cp->getValue());
return;
}
}
if(upper == _imp->keyFrames.end()){
//if we found no key that has a greater time, just append the key
newKeyIt = _imp->keyFrames.insert(_imp->keyFrames.end(),cp);
}else if(upper == _imp->keyFrames.begin()){
//if all the keys have a greater time, just insert this key at the begining
newKeyIt = _imp->keyFrames.insert(_imp->keyFrames.begin(),cp);
}else{
newKeyIt = _imp->keyFrames.insert(upper,cp);
}
}
refreshTangents(KEYFRAME_CHANGED,newKeyIt);
}
void Curve::removeKeyFrame(boost::shared_ptr<KeyFrame> cp){
KeyFrames::iterator it = std::find(_imp->keyFrames.begin(),_imp->keyFrames.end(),cp);
KeyFrames::iterator prev = it;
boost::shared_ptr<KeyFrame> prevCp;
boost::shared_ptr<KeyFrame> nextCp;
if(it != _imp->keyFrames.begin()){
--prev;
prevCp = (*prev);
}
KeyFrames::iterator next = it;
++next;
if(next != _imp->keyFrames.end()){
nextCp = (*next);
}
_imp->keyFrames.erase(it);
if(prevCp){
refreshTangents(TANGENT_CHANGED,prevCp);
}
if(nextCp){
refreshTangents(TANGENT_CHANGED,nextCp);
}
}
class KeyFrameTimePredicate
{
public:
KeyFrameTimePredicate(double t) : _t(t) {};
bool operator()(const boost::shared_ptr<KeyFrame>& f) { return (f->getTime() == _t); }
private:
double _t;
};
void Curve::removeKeyFrame(double time) {
KeyFrames::iterator it = std::find_if(_imp->keyFrames.begin(), _imp->keyFrames.end(), KeyFrameTimePredicate(time));
if (it != _imp->keyFrames.end()) {
removeKeyFrame(*it);
}
}
Variant Curve::getValueAt(double t) const {
assert(!_imp->keyFrames.empty());
if (_imp->keyFrames.size() == 1) {
//if there's only 1 keyframe, don't bother interpolating
return (*_imp->keyFrames.begin())->getValue();
}
double tcur,tnext;
double vcurDerivRight ,vnextDerivLeft ,vcur ,vnext ;
Natron::KeyframeType interp ,interpNext;
KeyFrames::const_iterator upper = _imp->keyFrames.end();
for(KeyFrames::const_iterator it = _imp->keyFrames.begin();it!=_imp->keyFrames.end();++it){
if((*it)->getTime() > t){
upper = it;
break;
}else if((*it)->getTime() == t){
//if the time is exactly the time of a keyframe, return its value
return (*it)->getValue();
}
}
//if all keys have a greater time (i.e: we search after the last keyframe)
KeyFrames::const_iterator prev = upper;
--prev;
//if we found no key that has a greater time (i.e: we search before the 1st keyframe)
if (upper == _imp->keyFrames.begin()) {
tnext = (*upper)->getTime();
vnext = (*upper)->getValue().value<double>();
vnextDerivLeft = (*upper)->getLeftTangent().value<double>();
interpNext = (*upper)->getInterpolation();
tcur = tnext - 1.;
vcur = vnext;
vcurDerivRight = 0.;
interp = Natron::KEYFRAME_NONE;
} else if (upper == _imp->keyFrames.end()) {
tcur = (*prev)->getTime();
vcur = (*prev)->getValue().value<double>();
vcurDerivRight = (*prev)->getRightTangent().value<double>();
interp = (*prev)->getInterpolation();
tnext = tcur + 1.;
vnext = vcur;
vnextDerivLeft = 0.;
interpNext = Natron::KEYFRAME_NONE;
} else {
tcur = (*prev)->getTime();
vcur = (*prev)->getValue().value<double>();
vcurDerivRight = (*prev)->getRightTangent().value<double>();
interp = (*prev)->getInterpolation();
tnext = (*upper)->getTime();
vnext = (*upper)->getValue().value<double>();
vnextDerivLeft = (*upper)->getLeftTangent().value<double>();
interpNext = (*upper)->getInterpolation();
}
double v = Natron::interpolate<double>(tcur,vcur,
vcurDerivRight,
vnextDerivLeft,
tnext,vnext,
t,
interp,
interpNext);
const Variant& firstKeyValue = _imp->keyFrames.front()->getValue();
switch(firstKeyValue.type()){
case QVariant::Int :
return Variant((int)std::floor(v+0.5));
case QVariant::Double :
return Variant(v);
case QVariant::Bool:
return Variant((bool)std::floor(v+0.5));
default:
std::string exc("The type requested ( ");
exc.append(firstKeyValue.typeName());
exc.append(") is not interpolable, it cannot animate!");
throw std::invalid_argument(exc);
}
}
bool Curve::isAnimated() const { return _imp->keyFrames.size() > 1; }
int Curve::keyFramesCount() const { return (int)_imp->keyFrames.size(); }
const KeyFrames& Curve::getKeyFrames() const { return _imp->keyFrames; }
void Curve::setKeyFrameValue(const Variant& value,boost::shared_ptr<KeyFrame> k){
if(value.toDouble() != k->getValue().toDouble()){
k->setValue(value);
evaluateCurveChanged(KEYFRAME_CHANGED,k);
}
}
void Curve::setKeyFrameTime(double time,boost::shared_ptr<KeyFrame> k){
if(time != k->getTime()){
k->setTime(time);
evaluateCurveChanged(KEYFRAME_CHANGED,k);
}
}
void Curve::setKeyFrameValueAndTime(double time,const Variant& value,boost::shared_ptr<KeyFrame> k){
if(time != k->getTime() || value.toDouble() != k->getValue().toDouble()){
k->setTime(time);
k->setValue(value);
evaluateCurveChanged(KEYFRAME_CHANGED,k);
}
}
void Curve::setKeyFrameLeftTangent(const Variant& value,boost::shared_ptr<KeyFrame> k){
if(value.toDouble() != k->getRightTangent().toDouble()){
k->setLeftTangent(value);
evaluateCurveChanged(TANGENT_CHANGED,k);
}
}
void Curve::setKeyFrameRightTangent(const Variant& value,boost::shared_ptr<KeyFrame> k){
if(k->getLeftTangent().toDouble() != value.toDouble()){
k->setRightTangent(value);
evaluateCurveChanged(TANGENT_CHANGED,k);
}
}
void Curve::setKeyFrameTangents(const Variant& left,const Variant& right,boost::shared_ptr<KeyFrame> k){
if(k->getLeftTangent().toDouble() != left.toDouble() || right.toDouble() != k->getRightTangent().toDouble()){
k->setLeftTangent(left);
k->setRightTangent(right);
evaluateCurveChanged(TANGENT_CHANGED,k);
}
}
void Curve::setKeyFrameInterpolation(Natron::KeyframeType interp,boost::shared_ptr<KeyFrame> k){
if(k->getInterpolation() != interp){
k->setInterpolation(interp);
evaluateCurveChanged(KEYFRAME_CHANGED,k);
}
}
void Curve::refreshTangents(Curve::CurveChangedReason reason, KeyFrames::iterator key){
double tcur = (*key)->getTime();
double vcur = (*key)->getValue().value<double>();
double tprev, vprev, tnext, vnext, vprevDerivRight, vnextDerivLeft;
Natron::KeyframeType prevType, nextType;
if (key == _imp->keyFrames.begin()) {
tprev = tcur;
vprev = vcur;
vprevDerivRight = 0.;
prevType = Natron::KEYFRAME_NONE;
} else {
KeyFrames::const_iterator prev = key;
--prev;
tprev = (*prev)->getTime();
vprev = (*prev)->getValue().value<double>();
vprevDerivRight = (*prev)->getRightTangent().value<double>();
prevType = (*prev)->getInterpolation();
//if prev is the first keyframe, and not edited by the user then interpolate linearly
if(prev == _imp->keyFrames.begin() && prevType != Natron::KEYFRAME_FREE &&
prevType != Natron::KEYFRAME_BROKEN){
prevType = Natron::KEYFRAME_LINEAR;
}
}
KeyFrames::const_iterator next = key;
++next;
if (next == _imp->keyFrames.end()) {
tnext = tcur;
vnext = vcur;
vnextDerivLeft = 0.;
nextType = Natron::KEYFRAME_NONE;
} else {
tnext = (*next)->getTime();
vnext = (*next)->getValue().value<double>();
vnextDerivLeft = (*next)->getLeftTangent().value<double>();
nextType = (*next)->getInterpolation();
KeyFrames::const_iterator nextnext = next;
++nextnext;
//if next is thelast keyframe, and not edited by the user then interpolate linearly
if(nextnext == _imp->keyFrames.end() && nextType != Natron::KEYFRAME_FREE &&
nextType != Natron::KEYFRAME_BROKEN){
nextType = Natron::KEYFRAME_LINEAR;
}
}
double vcurDerivLeft,vcurDerivRight;
try{
Natron::autoComputeTangents<double>(prevType,
(*key)->getInterpolation(),
nextType,
tprev, vprev,
tcur, vcur,
tnext, vnext,
vprevDerivRight,
vnextDerivLeft,
&vcurDerivLeft, &vcurDerivRight);
}catch(const std::exception& e){
std::cout << e.what() << std::endl;
assert(false);
}
(*key)->setLeftTangent(Variant(vcurDerivLeft));
(*key)->setRightTangent(Variant(vcurDerivRight));
if(reason != TANGENT_CHANGED){
evaluateCurveChanged(TANGENT_CHANGED,*key);
}
}
void Curve::refreshTangents(CurveChangedReason reason, boost::shared_ptr<KeyFrame> k){
KeyFrames::iterator it = std::find(_imp->keyFrames.begin(),_imp->keyFrames.end(),k);
assert(it!=_imp->keyFrames.end());
refreshTangents(reason,it);
}
void Curve::evaluateCurveChanged(CurveChangedReason reason,boost::shared_ptr<KeyFrame> k){
KeyFrames::iterator found = _imp->keyFrames.end();
for(KeyFrames::iterator it = _imp->keyFrames.begin();it!=_imp->keyFrames.end();++it){
if((*it) == k){
found = it;
break;
}
}
assert(found!=_imp->keyFrames.end());
if(k->getInterpolation()!= Natron::KEYFRAME_BROKEN && k->getInterpolation() != Natron::KEYFRAME_FREE
&& reason != TANGENT_CHANGED ){
refreshTangents(TANGENT_CHANGED,found);
}
KeyFrames::iterator prev = found;
if(found != _imp->keyFrames.begin()){
--prev;
if((*prev)->getInterpolation()!= Natron::KEYFRAME_BROKEN &&
(*prev)->getInterpolation()!= Natron::KEYFRAME_FREE){
refreshTangents(TANGENT_CHANGED,prev);
}
}
KeyFrames::iterator next = found;
++next;
if(next != _imp->keyFrames.end()){
if((*next)->getInterpolation()!= Natron::KEYFRAME_BROKEN &&
(*next)->getInterpolation()!= Natron::KEYFRAME_FREE){
refreshTangents(TANGENT_CHANGED,next);
}
}
_imp->owner->evaluateAnimationChange();
}
<|endoftext|> |
<commit_before>#ifndef __AIRSCHED_BOM_SEGMENTPATHPERIODKEY_HPP
#define __AIRSCHED_BOM_SEGMENTPATHPERIODKEY_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <iosfwd>
#include <string>
// StdAir
#include <stdair/stdair_basic_types.hpp>
#include <stdair/stdair_date_time_types.hpp>
#include <stdair/bom/KeyAbstract.hpp>
#include <stdair/bom/PeriodStruct.hpp>
// AirSched
#include <airsched/bom/SegmentPathPeriodTypes.hpp>
/// Forward declarations
namespace boost {
namespace serialization {
class access;
}
}
namespace AIRSCHED {
/**
* @brief Structure representing the key of a segment/path.
*
* That key specifies a travel solution from a geographical point
* (origin airport) to another (destination airport).
*/
struct SegmentPathPeriodKey : public stdair::KeyAbstract {
friend class boost::serialization::access;
// /////////// Constructors and destructors ///////////
public:
/**
* Constructor.
*/
SegmentPathPeriodKey (const stdair::PeriodStruct&,
const stdair::Duration_T& iBoardingTime,
const stdair::Duration_T& iElapsed,
const DateOffsetList_T&,
const stdair::NbOfAirlines_T&);
/**
* Default constructor.
*/
SegmentPathPeriodKey();
/**
* Copy constructor.
*/
SegmentPathPeriodKey (const SegmentPathPeriodKey&);
/**
* Destructor.
*/
~SegmentPathPeriodKey();
public:
// /////////// Getters //////////
/**
* Get the active days-of-week.
*/
const stdair::PeriodStruct& getPeriod() const {
return _period;
}
/**
* Get the list of boarding date off-sets.
*/
const DateOffsetList_T& getBoardingDateOffsetList() const {
return _boardingDateOffsetList;
}
/**
* Get the number of segments.
*/
const stdair::NbOfSegments_T& getNbOfSegments() const {
return _boardingDateOffsetList.size();
}
/**
* Get the number of airlines.
*/
const stdair::NbOfAirlines_T& getNbOfAirlines() const {
return _nbOfAirlines;
}
/**
* Get the elapsed time.
*/
const stdair::Duration_T& getElapsedTime() const {
return _elapsed;
}
/**
* Get the boarding time.
*/
const stdair::Duration_T& getBoardingTime() const {
return _boardingTime;
}
public:
// /////////// Setters //////////
/** Set the active days-of-week. */
void setPeriod (const stdair::PeriodStruct& iPeriod) {
_period = iPeriod;
}
void setBoardingDateOffsetList (const DateOffsetList_T& iList) {
_boardingDateOffsetList = iList;
}
/** Set the number of airlines. */
void setNbOfAirlines (const stdair::NbOfAirlines_T& iNbOfAirlines) {
_nbOfAirlines = iNbOfAirlines;
}
/** Set the elapsed time. */
void setElapsedTime (const stdair::Duration_T& iElapsed) {
_elapsed = iElapsed;
}
/** Set the boarding time. */
void setBoardingTime (const stdair::Duration_T& iBoardingTime) {
_boardingTime = iBoardingTime;
}
public:
// /////////// Business methods ////////////
/** Check if the key is valid (i.e. the departure period is valid). */
const bool isValid () const {
return _period.isValid ();
}
public:
// /////////// Display support methods /////////
/**
* Dump a Business Object Key into an output stream.
*
* @param ostream& the output stream.
*/
void toStream (std::ostream& ioOut) const;
/**
* Read a Business Object Key from an input stream.
*
* @param istream& the input stream.
*/
void fromStream (std::istream& ioIn);
/**
* Get the serialised version of the Business Object Key.
*
* That string is unique, at the level of a given Business Object,
* when among children of a given parent Business Object.
*
* For instance, "H" and "K" allow to differentiate among two
* marketing classes for the same segment-date.
*/
const std::string toString() const;
public:
// /////////// (Boost) Serialisation support methods /////////
/**
* Serialisation.
*/
template<class Archive>
void serialize (Archive& ar, const unsigned int iFileVersion);
private:
/**
* Serialisation helper (allows to be sure the template method is
* instantiated).
*/
void serialisationImplementation();
private:
// ///////////////// Attributes ///////////////
/**
* Departure period.
*/
stdair::PeriodStruct _period;
/**
* The boarding time.
*/
stdair::Duration_T _boardingTime;
/**
* The elapsed time of the path.
*/
stdair::Duration_T _elapsed;
/**
* The list of boarding date offsets of the segments compare to
* the first one.
*/
DateOffsetList_T _boardingDateOffsetList;
/**
* Number of airlines included in the path.
*/
stdair::NbOfAirlines_T _nbOfAirlines;
};
}
#endif // __AIRSCHED_BOM_SEGMENTPATHPERIODKEY_HPP
<commit_msg>[airsched] Removed a returned reference of a temporary object.<commit_after>#ifndef __AIRSCHED_BOM_SEGMENTPATHPERIODKEY_HPP
#define __AIRSCHED_BOM_SEGMENTPATHPERIODKEY_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <iosfwd>
#include <string>
// StdAir
#include <stdair/stdair_basic_types.hpp>
#include <stdair/stdair_date_time_types.hpp>
#include <stdair/bom/KeyAbstract.hpp>
#include <stdair/bom/PeriodStruct.hpp>
// AirSched
#include <airsched/bom/SegmentPathPeriodTypes.hpp>
/// Forward declarations
namespace boost {
namespace serialization {
class access;
}
}
namespace AIRSCHED {
/**
* @brief Structure representing the key of a segment/path.
*
* That key specifies a travel solution from a geographical point
* (origin airport) to another (destination airport).
*/
struct SegmentPathPeriodKey : public stdair::KeyAbstract {
friend class boost::serialization::access;
// /////////// Constructors and destructors ///////////
public:
/**
* Constructor.
*/
SegmentPathPeriodKey (const stdair::PeriodStruct&,
const stdair::Duration_T& iBoardingTime,
const stdair::Duration_T& iElapsed,
const DateOffsetList_T&,
const stdair::NbOfAirlines_T&);
/**
* Default constructor.
*/
SegmentPathPeriodKey();
/**
* Copy constructor.
*/
SegmentPathPeriodKey (const SegmentPathPeriodKey&);
/**
* Destructor.
*/
~SegmentPathPeriodKey();
public:
// /////////// Getters //////////
/**
* Get the active days-of-week.
*/
const stdair::PeriodStruct& getPeriod() const {
return _period;
}
/**
* Get the list of boarding date off-sets.
*/
const DateOffsetList_T& getBoardingDateOffsetList() const {
return _boardingDateOffsetList;
}
/**
* Get the number of segments.
*/
const stdair::NbOfSegments_T getNbOfSegments() const {
return _boardingDateOffsetList.size();
}
/**
* Get the number of airlines.
*/
const stdair::NbOfAirlines_T& getNbOfAirlines() const {
return _nbOfAirlines;
}
/**
* Get the elapsed time.
*/
const stdair::Duration_T& getElapsedTime() const {
return _elapsed;
}
/**
* Get the boarding time.
*/
const stdair::Duration_T& getBoardingTime() const {
return _boardingTime;
}
public:
// /////////// Setters //////////
/** Set the active days-of-week. */
void setPeriod (const stdair::PeriodStruct& iPeriod) {
_period = iPeriod;
}
void setBoardingDateOffsetList (const DateOffsetList_T& iList) {
_boardingDateOffsetList = iList;
}
/** Set the number of airlines. */
void setNbOfAirlines (const stdair::NbOfAirlines_T& iNbOfAirlines) {
_nbOfAirlines = iNbOfAirlines;
}
/** Set the elapsed time. */
void setElapsedTime (const stdair::Duration_T& iElapsed) {
_elapsed = iElapsed;
}
/** Set the boarding time. */
void setBoardingTime (const stdair::Duration_T& iBoardingTime) {
_boardingTime = iBoardingTime;
}
public:
// /////////// Business methods ////////////
/** Check if the key is valid (i.e. the departure period is valid). */
const bool isValid () const {
return _period.isValid ();
}
public:
// /////////// Display support methods /////////
/**
* Dump a Business Object Key into an output stream.
*
* @param ostream& the output stream.
*/
void toStream (std::ostream& ioOut) const;
/**
* Read a Business Object Key from an input stream.
*
* @param istream& the input stream.
*/
void fromStream (std::istream& ioIn);
/**
* Get the serialised version of the Business Object Key.
*
* That string is unique, at the level of a given Business Object,
* when among children of a given parent Business Object.
*
* For instance, "H" and "K" allow to differentiate among two
* marketing classes for the same segment-date.
*/
const std::string toString() const;
public:
// /////////// (Boost) Serialisation support methods /////////
/**
* Serialisation.
*/
template<class Archive>
void serialize (Archive& ar, const unsigned int iFileVersion);
private:
/**
* Serialisation helper (allows to be sure the template method is
* instantiated).
*/
void serialisationImplementation();
private:
// ///////////////// Attributes ///////////////
/**
* Departure period.
*/
stdair::PeriodStruct _period;
/**
* The boarding time.
*/
stdair::Duration_T _boardingTime;
/**
* The elapsed time of the path.
*/
stdair::Duration_T _elapsed;
/**
* The list of boarding date offsets of the segments compare to
* the first one.
*/
DateOffsetList_T _boardingDateOffsetList;
/**
* Number of airlines included in the path.
*/
stdair::NbOfAirlines_T _nbOfAirlines;
};
}
#endif // __AIRSCHED_BOM_SEGMENTPATHPERIODKEY_HPP
<|endoftext|> |
<commit_before>#include "types.h"
#include "stat.h"
#include "fcntl.h"
#include "user.h"
#include "lib.h"
#include "amd64.h"
#include "ipc.h"
// XXX(sbw) add a memlayout.h?
#define KSHARED 0xFFFFF00000000000ull
#define FSIZE (64 << 10)
#define BSIZE 4096
#define PSIZE (4*BSIZE)
static char buf[BSIZE];
struct ipcctl *ipcctl = (struct ipcctl*)KSHARED;
static void
kernlet_pread(int fd, size_t count, off_t off)
{
ipcctl->done = 0;
if (kernlet(fd, count, off) != 0)
die("kernlet");
}
static ssize_t
xpread(int fd, void *buf, size_t count, off_t off)
{
if (ipcctl->submitted) {
while (ipcctl->done == 0)
nop_pause();
if (ipcctl->result == -1)
goto slow;
if (off < ipcctl->off)
goto slow;
if (off > ipcctl->off + ipcctl->result)
goto slow;
char *kbuf = (char*) (KSHARED+4096);
off_t kbufoff = off - ipcctl->off;
size_t kbufcount = MIN(count, ipcctl->result - kbufoff);
memmove(buf, kbuf+kbufoff, kbufcount);
return kbufcount;
}
slow:
return pread(fd, buf, count, off);
}
int
main(int ac, char **av)
{
u64 t0, t1;
int i, k;
int fd;
fd = open("preadtest.x", O_CREATE|O_RDWR);
if (fd < 0)
die("open failed");
for (i = 0; i < FSIZE/BSIZE; i++)
if (write(fd, buf, BSIZE) != BSIZE)
die("write failed");
t0 = rdtsc();
for (k = 0; k < FSIZE; k+=PSIZE) {
kernlet_pread(fd, PSIZE, k);
for (i = k; i < k+PSIZE; i+=BSIZE)
if (xpread(fd, buf, BSIZE, i) != BSIZE)
die("pread failed");
}
t1 = rdtsc();
printf(1, "cycles %lu\n", t1 - t0);
exit();
}
<commit_msg>preadtest command-line option to enable syscall hacks<commit_after>#include "types.h"
#include "stat.h"
#include "fcntl.h"
#include "user.h"
#include "lib.h"
#include "amd64.h"
#include "ipc.h"
// XXX(sbw) add a memlayout.h?
#define KSHARED 0xFFFFF00000000000ull
#define FSIZE (64 << 10)
#define BSIZE 4096
#define PSIZE (4*BSIZE)
static int usekernlet;
static char buf[BSIZE];
struct ipcctl *ipcctl = (struct ipcctl*)KSHARED;
static void
kernlet_pread(int fd, size_t count, off_t off)
{
ipcctl->done = 0;
if (kernlet(fd, count, off) != 0)
die("kernlet");
}
static ssize_t
xpread(int fd, void *buf, size_t count, off_t off)
{
if (ipcctl->submitted) {
while (ipcctl->done == 0)
nop_pause();
if (ipcctl->result == -1)
goto slow;
if (off < ipcctl->off)
goto slow;
if (off > ipcctl->off + ipcctl->result)
goto slow;
char *kbuf = (char*) (KSHARED+4096);
off_t kbufoff = off - ipcctl->off;
size_t kbufcount = MIN(count, ipcctl->result - kbufoff);
memmove(buf, kbuf+kbufoff, kbufcount);
return kbufcount;
}
slow:
return pread(fd, buf, count, off);
}
int
main(int ac, char **av)
{
u64 t0, t1;
int i, k;
int fd;
if (ac > 1)
usekernlet = av[1][0] == 'k';
fd = open("preadtest.x", O_CREATE|O_RDWR);
if (fd < 0)
die("open failed");
for (i = 0; i < FSIZE/BSIZE; i++)
if (write(fd, buf, BSIZE) != BSIZE)
die("write failed");
t0 = rdtsc();
for (k = 0; k < FSIZE; k+=PSIZE) {
kernlet_pread(fd, PSIZE, k);
for (i = k; i < k+PSIZE; i+=BSIZE)
if (xpread(fd, buf, BSIZE, i) != BSIZE)
die("pread failed");
}
t1 = rdtsc();
printf(1, "usekernlet %u\n", usekernlet);
printf(1, "cycles %lu\n", t1 - t0);
exit();
}
<|endoftext|> |
<commit_before><commit_msg>Fix wrong variable name in Smooth filter parameters class.<commit_after><|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.
*/
/************************************ | *************************************
* *
* Please see header file for description. *
* *
************************************* | ************************************/
#include "TransformLogicalShortCircuit.h"
#include "build.h"
#include "expr.h"
#include "stmt.h"
TransformLogicalShortCircuit::TransformLogicalShortCircuit(Expr* insertionPoint)
{
mInsertionPoint = insertionPoint;
}
TransformLogicalShortCircuit::~TransformLogicalShortCircuit()
{
}
void TransformLogicalShortCircuit::exitCallExpr(CallExpr* call)
{
if (call->primitive == 0)
{
if (UnresolvedSymExpr* expr = toUnresolvedSymExpr(call->baseExpr))
{
bool isLogicalAnd = strcmp(expr->unresolved, "&&") == 0;
bool isLogicalOr = strcmp(expr->unresolved, "||") == 0;
if (isLogicalAnd || isLogicalOr)
{
SET_LINENO(call);
Expr* left = call->get(1);
Expr* right = call->get(2);
VarSymbol* lvar = newTemp();
VarSymbol* eMsg = NULL;
FnSymbol* ifFn = NULL;
left->remove();
right->remove();
lvar->addFlag(FLAG_MAYBE_PARAM);
if (isLogicalAnd)
{
eMsg = new_StringSymbol("cannot promote short-circuiting && operator");
ifFn = buildIfExpr(new CallExpr("isTrue", lvar),
new CallExpr("isTrue", right),
new SymExpr(gFalse));
}
else
{
eMsg = new_StringSymbol("cannot promote short-circuiting || operator");
ifFn = buildIfExpr(new CallExpr("isTrue", lvar),
new SymExpr(gTrue),
new CallExpr("isTrue", right));
}
ifFn->insertAtHead(new CondStmt(new CallExpr("_cond_invalid", lvar),
new CallExpr("compilerError", eMsg)));
ifFn->insertAtHead(new CallExpr(PRIM_MOVE, lvar, left));
ifFn->insertAtHead(new DefExpr(lvar));
call->baseExpr->replace(new UnresolvedSymExpr(ifFn->name));
mInsertionPoint->insertBefore(new DefExpr(ifFn));
}
}
}
}
<commit_msg>Disambiguate nested statements that include boolean && or ||<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.
*/
/************************************ | *************************************
* *
* Please see header file for description. *
* *
************************************* | ************************************/
#include "TransformLogicalShortCircuit.h"
#include "build.h"
#include "expr.h"
#include "stmt.h"
TransformLogicalShortCircuit::TransformLogicalShortCircuit(Expr* insertionPoint)
{
mInsertionPoint = insertionPoint;
}
TransformLogicalShortCircuit::~TransformLogicalShortCircuit()
{
}
void TransformLogicalShortCircuit::exitCallExpr(CallExpr* call)
{
if (call->primitive == 0)
{
if (UnresolvedSymExpr* expr = toUnresolvedSymExpr(call->baseExpr))
{
bool isLogicalAnd = strcmp(expr->unresolved, "&&") == 0;
bool isLogicalOr = strcmp(expr->unresolved, "||") == 0;
if (isLogicalAnd || isLogicalOr)
{
SET_LINENO(call);
if (call->getStmtExpr() == mInsertionPoint)
{
Expr* left = call->get(1);
Expr* right = call->get(2);
VarSymbol* lvar = newTemp();
VarSymbol* eMsg = NULL;
FnSymbol* ifFn = NULL;
left->remove();
right->remove();
lvar->addFlag(FLAG_MAYBE_PARAM);
if (isLogicalAnd)
{
eMsg = new_StringSymbol("cannot promote short-circuiting && operator");
ifFn = buildIfExpr(new CallExpr("isTrue", lvar),
new CallExpr("isTrue", right),
new SymExpr(gFalse));
}
else
{
eMsg = new_StringSymbol("cannot promote short-circuiting || operator");
ifFn = buildIfExpr(new CallExpr("isTrue", lvar),
new SymExpr(gTrue),
new CallExpr("isTrue", right));
}
ifFn->insertAtHead(new CondStmt(new CallExpr("_cond_invalid", lvar),
new CallExpr("compilerError", eMsg)));
ifFn->insertAtHead(new CallExpr(PRIM_MOVE, lvar, left));
ifFn->insertAtHead(new DefExpr(lvar));
call->baseExpr->replace(new UnresolvedSymExpr(ifFn->name));
mInsertionPoint->insertBefore(new DefExpr(ifFn));
}
}
}
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps *
* Copyright (C) 2015, IGG Group, ICube, University of Strasbourg, France *
* *
* 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, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
* *
* Web site: http://cgogn.unistra.fr/ *
* Contact information: cgogn@unistra.fr *
* *
*******************************************************************************/
#include <gtest/gtest.h>
#include <cgogn/core/utils/type_traits.h>
#include <vector>
#include <string>
namespace // unnamed namespace for internal linkage
{
struct A1
{
public:
int operator()(int x) const { return x;}
static std::string cgogn_name_of_type() { return "A1"; }
};
auto lambda = [](double) -> float { return 0.0f; };
struct Vec
{
const int& operator[](std::size_t i) const { return data[i]; }
int& operator[](std::size_t i) { return data[i]; }
int data[4];
int size() const { return 4; }
};
struct Mat
{
const int& operator()(std::size_t i, std::size_t j) const { return data[i][j]; }
int& operator()(std::size_t i, std::size_t j) { return data[i][j]; }
int rows() const { return 4; }
int cols() const { return 4; }
int data[4][4];
};
TEST(TypeTraitsTest, function_traits)
{
{
const auto arity = cgogn::func_arity<decltype (lambda)>::value;
EXPECT_EQ(arity, 1u);
}
{
const auto arity = cgogn::func_arity<A1>::value;
EXPECT_EQ(arity, 1u);
}
{
const bool expected_true = cgogn::is_func_parameter_same<A1, int>::value;
const bool expected_false = cgogn::is_func_parameter_same<A1, void>::value;
const bool expected_true_return = cgogn::is_func_return_same<A1,int>::value;
const bool expected_false_return = cgogn::is_func_return_same<A1,float>::value;
EXPECT_TRUE(expected_true);
EXPECT_FALSE(expected_false);
EXPECT_TRUE(expected_true_return);
EXPECT_FALSE(expected_false_return);
}
{
const bool expected_true = cgogn::is_func_parameter_same<decltype (lambda), double>::value;
const bool expected_false = cgogn::is_func_parameter_same<decltype (lambda), void>::value;
const bool expected_true_return = cgogn::is_func_return_same<decltype (lambda),float>::value;
const bool expected_false_return = cgogn::is_func_return_same<decltype (lambda),double>::value;
EXPECT_TRUE(expected_true);
EXPECT_FALSE(expected_false);
EXPECT_TRUE(expected_true_return);
EXPECT_FALSE(expected_false_return);
}
}
TEST(TypeTraitsTest, operator_parenthesis)
{
{
const bool expected_false0 = cgogn::has_operator_parenthesis_0<A1>::value;
const bool expected_true = cgogn::has_operator_parenthesis_1<A1>::value;
const bool expected_false2 = cgogn::has_operator_parenthesis_2<A1>::value;
EXPECT_FALSE(expected_false0);
EXPECT_TRUE(expected_true);
EXPECT_FALSE(expected_false2);
}
{
const bool expected_false0 = cgogn::has_operator_parenthesis_0<decltype (lambda)>::value;
const bool expected_true = cgogn::has_operator_parenthesis_1<decltype (lambda)>::value;
const bool expected_false2 = cgogn::has_operator_parenthesis_2<decltype (lambda)>::value;
EXPECT_FALSE(expected_false0);
EXPECT_TRUE(expected_true);
EXPECT_FALSE(expected_false2);
}
{
const bool expected_true = cgogn::has_operator_parenthesis_2<Mat>::value;
EXPECT_TRUE(expected_true);
}
}
TEST(TypeTraitsTest, operator_brackets)
{
{
const bool expected_false = cgogn::has_operator_brackets<A1>::value;
EXPECT_FALSE(expected_false);
}
{
const bool expected_false = cgogn::has_operator_brackets<decltype (lambda)>::value;
EXPECT_FALSE(expected_false);
}
{
const bool expected_true = cgogn::has_operator_brackets<Vec>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_false = cgogn::has_operator_brackets<Mat>::value;
EXPECT_FALSE(expected_false);
}
}
TEST(TypeTraitsTest, size_method)
{
{
const bool expected_true = cgogn::has_size_method<Vec>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_true = cgogn::has_size_method<std::vector<int>>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_false = cgogn::has_size_method<Mat>::value;
EXPECT_FALSE(expected_false);
}
}
TEST(TypeTraitsTest, rows_cols_methods)
{
{
const bool expected_true = cgogn::has_rows_method<Mat>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_true = cgogn::has_cols_method<Mat>::value;
EXPECT_TRUE(expected_true);
}
}
TEST(TypeTraitsTest, is_iterable)
{
{
const bool expected_true = cgogn::is_iterable<std::vector<float>>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_false = cgogn::is_iterable<Mat>::value;
EXPECT_FALSE(expected_false);
}
}
TEST(TypeTraitsTest, nb_components)
{
std::vector<int> v;
Mat mat;
Vec vec;
EXPECT_EQ(cgogn::nb_components(v), 0u);
v.resize(4);
EXPECT_EQ(cgogn::nb_components(v), 4u);
EXPECT_EQ(cgogn::nb_components(mat), 16u);
}
TEST(TypeTraitsTest, nested_type)
{
std::vector<int> v;
Mat mat;
Vec vec;
{
const bool expected_true = std::is_same<int, cgogn::nested_type<std::vector<int>>>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_true = std::is_same<int, cgogn::nested_type<Vec>>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_true = std::is_same<int, cgogn::nested_type<Mat>>::value;
EXPECT_TRUE(expected_true);
}
}
TEST(TypeTraitsTest, has_cgogn_name_of_type)
{
{
const bool expected_true = cgogn::has_cgogn_name_of_type<A1>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_false = cgogn::has_cgogn_name_of_type<std::vector<float>>::value;
EXPECT_FALSE(expected_false);
}
}
}
<commit_msg>fixed some warnings.<commit_after>/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps *
* Copyright (C) 2015, IGG Group, ICube, University of Strasbourg, France *
* *
* 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, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
* *
* Web site: http://cgogn.unistra.fr/ *
* Contact information: cgogn@unistra.fr *
* *
*******************************************************************************/
#include <gtest/gtest.h>
#include <cgogn/core/utils/type_traits.h>
#include <vector>
#include <string>
namespace // unnamed namespace for internal linkage
{
struct A1
{
public:
int operator()(int x) const { return x;}
static std::string cgogn_name_of_type() { return "A1"; }
};
auto lambda = [](double) -> float { return 0.0f; };
struct Vec
{
const int& operator[](std::size_t i) const { return data[i]; }
int& operator[](std::size_t i) { return data[i]; }
int data[4];
int size() const { return 4; }
};
struct Mat
{
const int& operator()(std::size_t i, std::size_t j) const { return data[i][j]; }
int& operator()(std::size_t i, std::size_t j) { return data[i][j]; }
int rows() const { return 4; }
int cols() const { return 4; }
int data[4][4];
};
TEST(TypeTraitsTest, function_traits)
{
{
const auto arity = cgogn::func_arity<decltype (lambda)>::value;
EXPECT_EQ(arity, 1u);
}
{
const auto arity = cgogn::func_arity<A1>::value;
EXPECT_EQ(arity, 1u);
}
{
const bool expected_true = cgogn::is_func_parameter_same<A1, int>::value;
const bool expected_false = cgogn::is_func_parameter_same<A1, void>::value;
const bool expected_true_return = cgogn::is_func_return_same<A1,int>::value;
const bool expected_false_return = cgogn::is_func_return_same<A1,float>::value;
EXPECT_TRUE(expected_true);
EXPECT_FALSE(expected_false);
EXPECT_TRUE(expected_true_return);
EXPECT_FALSE(expected_false_return);
}
{
const bool expected_true = cgogn::is_func_parameter_same<decltype (lambda), double>::value;
const bool expected_false = cgogn::is_func_parameter_same<decltype (lambda), void>::value;
const bool expected_true_return = cgogn::is_func_return_same<decltype (lambda),float>::value;
const bool expected_false_return = cgogn::is_func_return_same<decltype (lambda),double>::value;
EXPECT_TRUE(expected_true);
EXPECT_FALSE(expected_false);
EXPECT_TRUE(expected_true_return);
EXPECT_FALSE(expected_false_return);
}
}
TEST(TypeTraitsTest, operator_parenthesis)
{
{
const bool expected_false0 = cgogn::has_operator_parenthesis_0<A1>::value;
const bool expected_true = cgogn::has_operator_parenthesis_1<A1>::value;
const bool expected_false2 = cgogn::has_operator_parenthesis_2<A1>::value;
EXPECT_FALSE(expected_false0);
EXPECT_TRUE(expected_true);
EXPECT_FALSE(expected_false2);
}
{
const bool expected_false0 = cgogn::has_operator_parenthesis_0<decltype (lambda)>::value;
const bool expected_true = cgogn::has_operator_parenthesis_1<decltype (lambda)>::value;
const bool expected_false2 = cgogn::has_operator_parenthesis_2<decltype (lambda)>::value;
EXPECT_FALSE(expected_false0);
EXPECT_TRUE(expected_true);
EXPECT_FALSE(expected_false2);
}
{
const bool expected_true = cgogn::has_operator_parenthesis_2<Mat>::value;
EXPECT_TRUE(expected_true);
}
}
TEST(TypeTraitsTest, operator_brackets)
{
{
const bool expected_false = cgogn::has_operator_brackets<A1>::value;
EXPECT_FALSE(expected_false);
}
{
const bool expected_false = cgogn::has_operator_brackets<decltype (lambda)>::value;
EXPECT_FALSE(expected_false);
}
{
const bool expected_true = cgogn::has_operator_brackets<Vec>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_false = cgogn::has_operator_brackets<Mat>::value;
EXPECT_FALSE(expected_false);
}
}
TEST(TypeTraitsTest, size_method)
{
{
const bool expected_true = cgogn::has_size_method<Vec>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_true = cgogn::has_size_method<std::vector<int>>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_false = cgogn::has_size_method<Mat>::value;
EXPECT_FALSE(expected_false);
}
}
TEST(TypeTraitsTest, rows_cols_methods)
{
{
const bool expected_true = cgogn::has_rows_method<Mat>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_true = cgogn::has_cols_method<Mat>::value;
EXPECT_TRUE(expected_true);
}
}
TEST(TypeTraitsTest, is_iterable)
{
{
const bool expected_true = cgogn::is_iterable<std::vector<float>>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_false = cgogn::is_iterable<Mat>::value;
EXPECT_FALSE(expected_false);
}
}
TEST(TypeTraitsTest, nb_components)
{
std::vector<int> v;
EXPECT_EQ(cgogn::nb_components(v), 0u);
Vec vec;
EXPECT_EQ(cgogn::nb_components(vec), 4u);
Mat mat;
EXPECT_EQ(cgogn::nb_components(mat), 16u);
v.resize(4);
EXPECT_EQ(cgogn::nb_components(v), 4u);
}
TEST(TypeTraitsTest, nested_type)
{
{
const bool expected_true = std::is_same<int, cgogn::nested_type<std::vector<int>>>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_true = std::is_same<int, cgogn::nested_type<Vec>>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_true = std::is_same<int, cgogn::nested_type<Mat>>::value;
EXPECT_TRUE(expected_true);
}
}
TEST(TypeTraitsTest, has_cgogn_name_of_type)
{
{
const bool expected_true = cgogn::has_cgogn_name_of_type<A1>::value;
EXPECT_TRUE(expected_true);
}
{
const bool expected_false = cgogn::has_cgogn_name_of_type<std::vector<float>>::value;
EXPECT_FALSE(expected_false);
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unotunnelhelper.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-09 09:40:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _UNOTOOLS_UNOTUNNELHLP_HXX
#define _UNOTOOLS_UNOTUNNELHLP_HXX
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _RTL_MEMORY_H_
#include <rtl/memory.h>
#endif
#ifndef _CPPUHELPER_EXTRACT_HXX_
#include <cppuhelper/extract.hxx>
#endif
namespace utl
{
namespace staruno = ::com::sun::star::uno;
namespace starlang = ::com::sun::star::lang;
//-----------------------------------------------------------------------------------------------------------
// to use the following, define
// sal_Bool getTunneledImplementation(Classname*& pObjImpl, staruno::Reference<starlang::XUnoTunnel> const& xObj);
template <class Classname>
sal_Bool getImplementation(Classname*& pImpl, staruno::Reference<starlang::XUnoTunnel> const& xTunnel)
throw(staruno::RuntimeException)
{
if (xTunnel.is())
return getTunneledImplementation(pImpl, xTunnel);
pImpl = 0;
return sal_False;
}
template <class Classname>
sal_Bool getImplementation(Classname*& pImpl, staruno::Reference<staruno::XInterface> const& xObj)
throw(staruno::RuntimeException)
{
staruno::Reference<starlang::XUnoTunnel> xTunnel(xObj,staruno::UNO_QUERY);
if (xTunnel.is())
return getTunneledImplementation(pImpl, xTunnel);
pImpl = 0;
return sal_False;
}
template <class Classname>
sal_Bool getImplementation(Classname*& pImpl, staruno::Any const& aObj)
throw(staruno::RuntimeException)
{
staruno::Reference<starlang::XUnoTunnel> xTunnel;
if (cppu::extractInterface(xTunnel, aObj))
getTunneledImplementation(pImpl, xTunnel);
pImpl = 0;
return sal_False;
}
template <class Classname>
sal_Bool getImplementation(Classname*& pImpl, starlang::XUnoTunnel* pObj)
throw(staruno::RuntimeException)
{
if (pObj)
{
staruno::Reference<starlang::XUnoTunnel> xTunnel(pObj);
return getTunneledImplementation(pImpl, xTunnel);
}
pImpl = 0;
return sal_False;
}
//-----------------------------------------------------------------------------------------------------------
class UnoTunnelId
{
sal_Int8 tunnelId[16];
public:
UnoTunnelId(sal_Bool bUseMAC = sal_True) throw()
{
rtl_createUuid(reinterpret_cast<sal_uInt8*>(tunnelId),0,bUseMAC);
}
staruno::Sequence<sal_Int8> getId() const throw(staruno::RuntimeException)
{
return staruno::Sequence<sal_Int8>(tunnelId, sizeof(tunnelId));
}
sal_Bool equalTo(staruno::Sequence<sal_Int8> const& rIdentifier) throw()
{
return rIdentifier.getLength() == sizeof(tunnelId) &&
rtl_compareMemory(tunnelId, rIdentifier.getConstArray(), sizeof(tunnelId)) == 0;
}
sal_Int8 const (&getIdBytes() const)[16] { return tunnelId; }
};
//-----------------------------------------------------------------------------------------------------------
template<class Classname>
class UnoTunnelImplBase
{
protected:
Classname* ThisImplementation() throw() { return static_cast<Classname*>(this); }
sal_Int64 makeUnoSomething() throw()
{
return reinterpret_cast<sal_Int64>(static_cast<void*>(ThisImplementation()));
}
static Classname* extractUnoSomething(sal_Int64 nSomething) throw()
{
if (nSomething != sal_Int64())
return static_cast<Classname*>(reinterpret_cast<void*>(nSomething));
return NULL;
}
#ifdef LINUX
public:
#endif
static Classname*
extractUnoSomething(
staruno::Reference<starlang::XUnoTunnel> const& xObj,
staruno::Sequence<sal_Int8> const& rMyTunnelId
)
throw(staruno::RuntimeException)
{
return xObj.is() ? extractUnoSomething(xObj->getSomething(rMyTunnelId)) : NULL;
}
};
//-----------------------------------------------------------------------------------------------------------
template<class Classname>
class UnoTunnelHelper : public UnoTunnelImplBase<Classname>
{
protected:
static UnoTunnelId s_aTunnelId;
sal_Int64 getSomething(staruno::Sequence<sal_Int8> const& rTunnelId) throw()
{
if (s_aTunnelId.equalTo(rTunnelId))
return makeUnoSomething();
else
return sal_Int64();
}
public:
static staruno::Sequence<sal_Int8> getImplementationTunnelId()
throw(staruno::RuntimeException)
{
return s_aTunnelId.getId();
}
#ifndef LINUX
friend sal_Bool getTunneledImplementation(Classname*& pImpl, staruno::Reference<starlang::XUnoTunnel> const& xObj)
throw(staruno::RuntimeException)
{
pImpl = UnoTunnelHelper<Classname>::UnoTunnelHelper<Classname>::extractUnoSomething( xObj, UnoTunnelHelper<Classname>::getImplementationTunnelId() );
return pImpl != 0;
}
#endif
};
template<class Classname>
UnoTunnelId UnoTunnelHelper<Classname>::s_aTunnelId;
//-----------------------------------------------------------------------------------------------------------
} // namespace utl
#endif // _UNOTOOLS_UNOTUNNELHLP_HXX
<commit_msg>INTEGRATION: CWS warnings01 (1.2.16); FILE MERGED 2005/10/21 09:48:49 dbo 1.2.16.1: #i53898# warning free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unotunnelhelper.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-19 14:03:46 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _UNOTOOLS_UNOTUNNELHLP_HXX
#define _UNOTOOLS_UNOTUNNELHLP_HXX
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _RTL_MEMORY_H_
#include <rtl/memory.h>
#endif
#ifndef _CPPUHELPER_EXTRACT_HXX_
#include <cppuhelper/extract.hxx>
#endif
namespace utl
{
namespace staruno = ::com::sun::star::uno;
namespace starlang = ::com::sun::star::lang;
//-----------------------------------------------------------------------------------------------------------
// to use the following, define
// sal_Bool getTunneledImplementation(Classname*& pObjImpl, staruno::Reference<starlang::XUnoTunnel> const& xObj);
template <class Classname>
sal_Bool getImplementation(Classname*& pImpl, staruno::Reference<starlang::XUnoTunnel> const& xTunnel)
throw(staruno::RuntimeException)
{
if (xTunnel.is())
return getTunneledImplementation(pImpl, xTunnel);
pImpl = 0;
return sal_False;
}
template <class Classname>
sal_Bool getImplementation(Classname*& pImpl, staruno::Reference<staruno::XInterface> const& xObj)
throw(staruno::RuntimeException)
{
staruno::Reference<starlang::XUnoTunnel> xTunnel(xObj,staruno::UNO_QUERY);
if (xTunnel.is())
return getTunneledImplementation(pImpl, xTunnel);
pImpl = 0;
return sal_False;
}
template <class Classname>
sal_Bool getImplementation(Classname*& pImpl, staruno::Any const& aObj)
throw(staruno::RuntimeException)
{
staruno::Reference<starlang::XUnoTunnel> xTunnel;
if (cppu::extractInterface(xTunnel, aObj))
getTunneledImplementation(pImpl, xTunnel);
pImpl = 0;
return sal_False;
}
template <class Classname>
sal_Bool getImplementation(Classname*& pImpl, starlang::XUnoTunnel* pObj)
throw(staruno::RuntimeException)
{
if (pObj)
{
staruno::Reference<starlang::XUnoTunnel> xTunnel(pObj);
return getTunneledImplementation(pImpl, xTunnel);
}
pImpl = 0;
return sal_False;
}
//-----------------------------------------------------------------------------------------------------------
class UnoTunnelId
{
sal_Int8 tunnelId[16];
public:
UnoTunnelId(sal_Bool bUseMAC = sal_True) throw()
{
rtl_createUuid(reinterpret_cast<sal_uInt8*>(tunnelId),0,bUseMAC);
}
staruno::Sequence<sal_Int8> getId() const throw(staruno::RuntimeException)
{
return staruno::Sequence<sal_Int8>(tunnelId, sizeof(tunnelId));
}
sal_Bool equalTo(staruno::Sequence<sal_Int8> const& rIdentifier) throw()
{
return rIdentifier.getLength() == sizeof(tunnelId) &&
rtl_compareMemory(tunnelId, rIdentifier.getConstArray(), sizeof(tunnelId)) == 0;
}
sal_Int8 const (&getIdBytes() const)[16] { return tunnelId; }
};
//-----------------------------------------------------------------------------------------------------------
template<class Classname>
class UnoTunnelImplBase
{
protected:
Classname* ThisImplementation() throw() { return static_cast<Classname*>(this); }
sal_Int64 makeUnoSomething() throw()
{
return reinterpret_cast<sal_Int64>(static_cast<void*>(ThisImplementation()));
}
static Classname* extractUnoSomething(sal_Int64 nSomething) throw()
{
if (nSomething != sal_Int64())
return static_cast<Classname*>(reinterpret_cast<void*>(nSomething));
return NULL;
}
#ifdef LINUX
public:
#endif
static Classname*
extractUnoSomething(
staruno::Reference<starlang::XUnoTunnel> const& xObj,
staruno::Sequence<sal_Int8> const& rMyTunnelId
)
throw(staruno::RuntimeException)
{
return xObj.is() ? extractUnoSomething(xObj->getSomething(rMyTunnelId)) : NULL;
}
};
//-----------------------------------------------------------------------------------------------------------
template<class Classname>
class UnoTunnelHelper : public UnoTunnelImplBase<Classname>
{
protected:
static UnoTunnelId s_aTunnelId;
sal_Int64 getSomething(staruno::Sequence<sal_Int8> const& rTunnelId) throw()
{
if (s_aTunnelId.equalTo(rTunnelId))
return this->makeUnoSomething();
else
return sal_Int64();
}
public:
static staruno::Sequence<sal_Int8> getImplementationTunnelId()
throw(staruno::RuntimeException)
{
return s_aTunnelId.getId();
}
#ifndef LINUX
friend sal_Bool getTunneledImplementation(Classname*& pImpl, staruno::Reference<starlang::XUnoTunnel> const& xObj)
throw(staruno::RuntimeException)
{
pImpl = UnoTunnelHelper<Classname>::UnoTunnelHelper<Classname>::extractUnoSomething( xObj, UnoTunnelHelper<Classname>::getImplementationTunnelId() );
return pImpl != 0;
}
#endif
};
template<class Classname>
UnoTunnelId UnoTunnelHelper<Classname>::s_aTunnelId;
//-----------------------------------------------------------------------------------------------------------
} // namespace utl
#endif // _UNOTOOLS_UNOTUNNELHLP_HXX
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////
//
// NAME
// FeatureAlign.cpp -- image registration using feature matching
//
// SEE ALSO
// FeatureAlign.h longer description
//
// Based on code by Richard Szeliski, 2001.
// (modified for CSE576 Spring 2005, and for CS4670, Fall 2012-2013)
//
///////////////////////////////////////////////////////////////////////////
#include "ImageLib/ImageLib.h"
#include "FeatureAlign.h"
#include "SVD.h"
#include <math.h>
#include <time.h>
#include <iostream>
CTransform3x3 ComputeHomography(const FeatureSet &f1, const FeatureSet &f2,
const vector<FeatureMatch> &matches)
{
int numMatches = (int) matches.size();
// first, we will compute the A matrix in the homogeneous linear equations Ah = 0
int numRows = 2 * numMatches; // number of rows of A
const int numCols = 9; // number of columns of A
// this allocates space for the A matrix
AMatrixType A = AMatrixType::Zero(numRows, numCols);
for (int i = 0; i < numMatches; i++) {
const FeatureMatch &m = matches[i];
const Feature &a = f1[m.id1];
const Feature &b = f2[m.id2];
// BEGIN TODO
// fill in the matrix A in this loop.
// To access an element of A, use parentheses, e.g. A(0,0)
// Note that A is a (2n x 9) matrix
// We can easily fill in A according to the lecture
// Row 2i
A(2*i, 0) = a.x;
A(2*i, 1) = a.y;
A(2*i, 2) = 1;
A(2*i, 3) = 0;
A(2*i, 4) = 0;
A(2*i, 5) = 0;
A(2*i, 6) = -b.x * a.x;
A(2*i, 7) = -b.x * a.y;
A(2*i, 8) = -b.x;
// Row 2i+1
A(2*i+1, 0) = 0;
A(2*i+1, 1) = 0;
A(2*i+1, 2) = 0;
A(2*i+1, 3) = a.x;
A(2*i+1, 4) = a.y;
A(2*i+1, 5) = 1;
A(2*i+1, 6) = -b.y * a.x;
A(2*i+1, 7) = -b.y * a.y;
A(2*i+1, 8) = -b.y;
// END TODO
}
// Compute the SVD of the A matrix and get out the matrix V^T and the vector of singular values
AMatrixType Vt;
VectorXd sv;
SVD(A, Vt, sv);
CTransform3x3 H;
// BEGIN TODO
// fill the homography H with the appropriate elements of the SVD
// To extract, for instance, the V matrix, use svd.matrixV()
// Find the smallest sv first
// minSv: smallest sv value
// minSvIdx: smallest sv index
double minSv = sv[0];
int minSvIdx = 0;
for (int i = 1; i < (int)sv.size(); i++) {
if (sv[i] < minSv && sv[i] > 0) {
minSv = sv[i];
minSvIdx = i;
}
}
// Rank(A) = 8 => H = a v_n (a is a constant)
// v_n corresponds to the smallest sv
H[0][0] = Vt(minSvIdx,0) / Vt(minSvIdx,8);
H[0][1] = Vt(minSvIdx,1) / Vt(minSvIdx,8);
H[0][2] = Vt(minSvIdx,2) / Vt(minSvIdx,8);
H[1][0] = Vt(minSvIdx,3) / Vt(minSvIdx,8);
H[1][1] = Vt(minSvIdx,4) / Vt(minSvIdx,8);
H[1][2] = Vt(minSvIdx,5) / Vt(minSvIdx,8);
H[2][0] = Vt(minSvIdx,6) / Vt(minSvIdx,8);
H[2][1] = Vt(minSvIdx,7) / Vt(minSvIdx,8);
H[2][2] = Vt(minSvIdx,8) / Vt(minSvIdx,8);
// END TODO
return H;
}
/******************* TO DO *********************
* alignPair:
* INPUT:
* f1, f2: source feature sets
* matches: correspondences between f1 and f2
* Each match in 'matches' contains two feature ids of
* matching features, id1 (in f1) and id2 (in f2).
* m: motion model
* nRANSAC: number of RANSAC iterations
* RANSACthresh: RANSAC distance threshold
* M: transformation matrix (output)
*
* OUTPUT:
* repeat for nRANSAC iterations:
* choose a minimal set of feature matches
* estimate the transformation implied by these matches
* count the number of inliers
* for the transformation with the maximum number of inliers,
* compute the least squares motion estimate using the inliers,
* and store it in M
*/
int alignPair(const FeatureSet &f1, const FeatureSet &f2,
const vector<FeatureMatch> &matches, MotionModel m,
int nRANSAC, double RANSACthresh, CTransform3x3& M)
{
// BEGIN TODO
// Write this entire method. You need to handle two types of
// motion models, pure translations (m == eTranslation) and
// full homographies (m == eHomography). However, you should
// only have one outer loop to perform the RANSAC code, as
// the use of RANSAC is almost identical for both cases.
//
// Your homography handling code should call ComputeHomography.
// This function should also call countInliers and, at the end,
// leastSquaresFit.
// Generate a random seed
srand(unsigned int(time(NULL)));
// Save maximum inliers
// maxInlierCnt: maximum number of inliers
// maxInliers: inlier IDs
int maxInlierCnt = 0;
vector<int> maxInliers;
// Number of features
int numF = matches.size();
// Number of samples
int numS;
switch (m) {
case eTranslate: {
numS = 1;
break;
}
case eHomography: {
numS = 4;
break;
}
}
for (int i = 0; i < nRANSAC; i++) {
// Random samples
vector<FeatureMatch> randMatches;
randMatches.clear();
int cnt = 0;
while (cnt < numS) {
// Randomly pick a pair from the feature list that isn't in the list
int rnd = rand() % numF;
FeatureMatch curFeature = matches[rnd];
// Check if this match is already selected
bool selected = false;
for (int j = 0; j < (int)randMatches.size(); j++) {
if (randMatches[j].id1 == curFeature.id1 && randMatches[j].id2 == curFeature.id2) {
selected = true;
}
}
// If not, push it to the sample space
if (!selected) {
randMatches.push_back(curFeature);
cnt++;
}
}
// Get the transform
CTransform3x3 H;
// Translation
if (numS == 1) {
FeatureMatch match = randMatches[0];
H[0][0] = 1;
H[0][1] = 0;
H[0][2] = f2[match.id2].x - f1[match.id1].x;
H[1][0] = 0;
H[1][1] = 1;
H[1][2] = f2[match.id2].y - f1[match.id1].y;
H[2][0] = 0;
H[2][1] = 0;
H[2][2] = 1;
}
// Homography
else if (numS == 4) {
H = ComputeHomography(f1, f2, randMatches);
}
// Count inliers matching this homography
vector<int> curInliers;
int numInliers = countInliers(f1, f2, matches, m, H, RANSACthresh, curInliers);
// Update maximum inliers
if (numInliers > maxInlierCnt) {
maxInlierCnt = numInliers;
maxInliers.clear();
for (int k = 0; k < maxInlierCnt; k++) {
maxInliers.push_back(curInliers[k]);
}
}
}
cout << "num_inliers: " << maxInlierCnt << " / " << matches.size() << endl;
//////////////////////////DEBUG//////////////////////////
/*if (maxInlierCnt < 10) {
for (int ii = 0; ii < maxInlierCnt; ii++) {
cout << ii << endl;
cout << matches[maxInliers[ii]].id1 << " " << matches[maxInliers[ii]].id2 << endl;
cout << f1[matches[maxInliers[ii]].id1].x << " " << f1[matches[maxInliers[ii]].id1].y << endl;
cout << f2[matches[maxInliers[ii]].id2].x << " " << f2[matches[maxInliers[ii]].id2].y << endl;
}
}*/
// Call leastSquaresFit
leastSquaresFit(f1, f2, matches, m, maxInliers, M);
// END TODO
return 0;
}
/******************* TO DO *********************
* countInliers:
* INPUT:
* f1, f2: source feature sets
* matches: correspondences between f1 and f2
* m: motion model
* Each match in 'matches' contains two feature ids of
* matching features, id1 (in f1) and id2 (in f2).
* M: transformation matrix
* RANSACthresh: RANSAC distance threshold
* inliers: inlier feature IDs
* OUTPUT:
* transform the features in f1 by M
*
* count the number of features in f1 for which the transformed
* feature is within Euclidean distance RANSACthresh of its match
* in f2
*
* store these features IDs in inliers
*
*/
int countInliers(const FeatureSet &f1, const FeatureSet &f2,
const vector<FeatureMatch> &matches, MotionModel m,
CTransform3x3 M, double RANSACthresh, vector<int> &inliers)
{
inliers.clear();
for (unsigned int i = 0; i < matches.size(); i++) {
// BEGIN TODO
// determine if the ith matched feature f1[id1-1], when transformed by M,
// is within RANSACthresh of its match in f2
//
// if so, append i to inliers
// Get the features
const FeatureMatch &m = matches[i];
const Feature &a = f1[m.id1];
const Feature &b = f2[m.id2];
// Transform f1[m.id1] by M
CVector3 p;
p[0] = a.x;
p[1] = a.y;
p[2] = 1;
CVector3 pt = M * p;
// Transformed f1[m.id1]
double xt = pt[0];
double yt = pt[1];
// Compute Euclidean distance from xt,yt to b.x,b.y
// and check if within RANSACthresh
double distance = sqrt((b.x-xt)*(b.x-xt) + (b.y-yt)*(b.y-yt));
if (distance <= RANSACthresh) {
// Append i to inliers
inliers.push_back(i);
}
// END TODO
}
return (int) inliers.size();
}
/******************* TO DO *********************
* leastSquaresFit:
* INPUT:
* f1, f2: source feature sets
* matches: correspondences between f1 and f2
* m: motion model
* inliers: inlier match indices (indexes into 'matches' array)
* M: transformation matrix (output)
* OUTPUT:
* compute the transformation from f1 to f2 using only the inliers
* and return it in M
*/
int leastSquaresFit(const FeatureSet &f1, const FeatureSet &f2,
const vector<FeatureMatch> &matches, MotionModel m,
const vector<int> &inliers, CTransform3x3& M)
{
// This function needs to handle two possible motion models,
// pure translations and full homographies.
switch (m) {
case eTranslate: {
// for spherically warped images, the transformation is a
// translation and only has two degrees of freedom
//
// therefore, we simply compute the average translation vector
// between the feature in f1 and its match in f2 for all inliers
double u = 0;
double v = 0;
for (int i=0; i < (int) inliers.size(); i++) {
// BEGIN TODO
// use this loop to compute the average translation vector
// over all inliers
FeatureMatch m = matches[inliers[i]];
Feature a = f1[m.id1];
Feature b = f2[m.id2];
// Sum the differences
u += b.x - a.x;
v += b.y - a.y;
// END TODO
}
u /= inliers.size();
v /= inliers.size();
M = CTransform3x3::Translation((float) u, (float) v);
break;
}
case eHomography: {
M = CTransform3x3();
// BEGIN TODO
// Compute a homography M using all inliers.
// This should call ComputeHomography.
// Put the matches specified by inliers into a new FeatureMatch vector
vector<FeatureMatch> inlierMatches;
inlierMatches.clear();
for (int i = 0; i < (int)inliers.size(); i++) {
FeatureMatch m = matches[inliers[i]];
inlierMatches.push_back(m);
}
// Compute the homography using all inliers
M = ComputeHomography(f1, f2, inlierMatches);
// END TODO
break;
}
}
return 0;
}
<commit_msg>homography to my best knowledge<commit_after>///////////////////////////////////////////////////////////////////////////
//
// NAME
// FeatureAlign.cpp -- image registration using feature matching
//
// SEE ALSO
// FeatureAlign.h longer description
//
// Based on code by Richard Szeliski, 2001.
// (modified for CSE576 Spring 2005, and for CS4670, Fall 2012-2013)
//
///////////////////////////////////////////////////////////////////////////
#include "ImageLib/ImageLib.h"
#include "FeatureAlign.h"
#include "SVD.h"
#include <math.h>
#include <time.h>
#include <iostream>
CTransform3x3 ComputeHomography(const FeatureSet &f1, const FeatureSet &f2,
const vector<FeatureMatch> &matches)
{
int numMatches = (int) matches.size();
// first, we will compute the A matrix in the homogeneous linear equations Ah = 0
int numRows = 2 * numMatches; // number of rows of A
const int numCols = 9; // number of columns of A
// this allocates space for the A matrix
AMatrixType A = AMatrixType::Zero(numRows, numCols);
for (int i = 0; i < numMatches; i++) {
const FeatureMatch &m = matches[i];
const Feature &a = f1[m.id1];
const Feature &b = f2[m.id2];
// BEGIN TODO
// fill in the matrix A in this loop.
// To access an element of A, use parentheses, e.g. A(0,0)
// Note that A is a (2n x 9) matrix
// We can easily fill in A according to the lecture
// Row 2i
A(2*i, 0) = a.x;
A(2*i, 1) = a.y;
A(2*i, 2) = 1;
A(2*i, 3) = 0;
A(2*i, 4) = 0;
A(2*i, 5) = 0;
A(2*i, 6) = -b.x * a.x;
A(2*i, 7) = -b.x * a.y;
A(2*i, 8) = -b.x;
// Row 2i+1
A(2*i+1, 0) = 0;
A(2*i+1, 1) = 0;
A(2*i+1, 2) = 0;
A(2*i+1, 3) = a.x;
A(2*i+1, 4) = a.y;
A(2*i+1, 5) = 1;
A(2*i+1, 6) = -b.y * a.x;
A(2*i+1, 7) = -b.y * a.y;
A(2*i+1, 8) = -b.y;
// END TODO
}
// Compute the SVD of the A matrix and get out the matrix V^T and the vector of singular values
AMatrixType Vt;
VectorXd sv;
SVD(A, Vt, sv);
CTransform3x3 H;
// BEGIN TODO
// fill the homography H with the appropriate elements of the SVD
// To extract, for instance, the V matrix, use svd.matrixV()
// Find the smallest sv first
// minSv: smallest sv value
// minSvIdx: smallest sv index
double minSv = sv[0];
int minSvIdx = 0;
for (int i = 1; i < (int)sv.size(); i++) {
if (sv[i] < minSv && sv[i] > 0) {
minSv = sv[i];
minSvIdx = i;
}
}
//minSvIdx = 8;
// Rank(A) = 8 => H = a v_n (a is a constant)
// v_n corresponds to the smallest sv
H[0][0] = Vt(minSvIdx,0) / Vt(minSvIdx,8);
H[0][1] = Vt(minSvIdx,1) / Vt(minSvIdx,8);
H[0][2] = Vt(minSvIdx,2) / Vt(minSvIdx,8);
H[1][0] = Vt(minSvIdx,3) / Vt(minSvIdx,8);
H[1][1] = Vt(minSvIdx,4) / Vt(minSvIdx,8);
H[1][2] = Vt(minSvIdx,5) / Vt(minSvIdx,8);
H[2][0] = Vt(minSvIdx,6) / Vt(minSvIdx,8);
H[2][1] = Vt(minSvIdx,7) / Vt(minSvIdx,8);
H[2][2] = Vt(minSvIdx,8) / Vt(minSvIdx,8);
/*for (int a = 0; a < 9; a++)
{
for (int b = 0; b < 9; b++)
{
cout << Vt(a,b) << " ";
}
cout << endl;
}*/
// END TODO
return H;
}
/******************* TO DO *********************
* alignPair:
* INPUT:
* f1, f2: source feature sets
* matches: correspondences between f1 and f2
* Each match in 'matches' contains two feature ids of
* matching features, id1 (in f1) and id2 (in f2).
* m: motion model
* nRANSAC: number of RANSAC iterations
* RANSACthresh: RANSAC distance threshold
* M: transformation matrix (output)
*
* OUTPUT:
* repeat for nRANSAC iterations:
* choose a minimal set of feature matches
* estimate the transformation implied by these matches
* count the number of inliers
* for the transformation with the maximum number of inliers,
* compute the least squares motion estimate using the inliers,
* and store it in M
*/
int alignPair(const FeatureSet &f1, const FeatureSet &f2,
const vector<FeatureMatch> &matches, MotionModel m,
int nRANSAC, double RANSACthresh, CTransform3x3& M)
{
// BEGIN TODO
// Write this entire method. You need to handle two types of
// motion models, pure translations (m == eTranslation) and
// full homographies (m == eHomography). However, you should
// only have one outer loop to perform the RANSAC code, as
// the use of RANSAC is almost identical for both cases.
//
// Your homography handling code should call ComputeHomography.
// This function should also call countInliers and, at the end,
// leastSquaresFit.
// Generate a random seed
//srand(unsigned int(time(NULL)));
// Save maximum inliers
// maxInlierCnt: maximum number of inliers
// maxInliers: inlier IDs
int maxInlierCnt = 0;
vector<int> maxInliers;
// Number of features
int numF = matches.size();
// Number of samples
int numS;
switch (m) {
case eTranslate: {
numS = 1;
break;
}
case eHomography: {
numS = 4;
break;
}
}
for (int i = 0; i < nRANSAC; i++) {
// Random samples
vector<FeatureMatch> randMatches;
//vector<int> randMatches;
randMatches.clear();
int cnt = 0;
while (cnt < numS) {
// Randomly pick a pair from the feature list that isn't in the list
int rnd = rand() % numF;
//cout << i << " " << rnd << endl;
FeatureMatch curFeature = matches[rnd];
// Check if this match is already selected
bool selected = false;
for (int j = 0; j < (int)randMatches.size(); j++) {
if (randMatches[j].id1 == curFeature.id1 && randMatches[j].id2 == curFeature.id2) {
selected = true;
}
}
// If not, push it to the sample space
if (!selected) {
randMatches.push_back(curFeature);
cnt++;
}
}
/*randMatches.push_back(0);
randMatches.push_back(1);
randMatches.push_back(2);
randMatches.push_back(3);*/
// Get the transform
CTransform3x3 H;
// Translation
if (numS == 1) {
FeatureMatch match = randMatches[0];
H[0][0] = 1;
H[0][1] = 0;
H[0][2] = f2[match.id2].x - f1[match.id1].x;
H[1][0] = 0;
H[1][1] = 1;
H[1][2] = f2[match.id2].y - f1[match.id1].y;
H[2][0] = 0;
H[2][1] = 0;
H[2][2] = 1;
}
// Homography
else if (numS == 4) {
H = ComputeHomography(f1, f2, randMatches);
}
//leastSquaresFit(f1, f2, matches, m, randMatches, H);
// Count inliers matching this homography
vector<int> curInliers;
int numInliers = countInliers(f1, f2, matches, m, H, RANSACthresh, curInliers);
// Update maximum inliers
if (numInliers > maxInlierCnt) {
maxInlierCnt = numInliers;
maxInliers.clear();
for (int k = 0; k < maxInlierCnt; k++) {
maxInliers.push_back(curInliers[k]);
}
}
}
cout << "num_inliers: " << maxInlierCnt << " / " << matches.size() << endl;
//////////////////////////DEBUG//////////////////////////
/*if (maxInlierCnt < 10) {
for (int ii = 0; ii < maxInlierCnt; ii++) {
cout << ii << endl;
cout << matches[maxInliers[ii]].id1 << " " << matches[maxInliers[ii]].id2 << endl;
cout << f1[matches[maxInliers[ii]].id1].x << " " << f1[matches[maxInliers[ii]].id1].y << endl;
cout << f2[matches[maxInliers[ii]].id2].x << " " << f2[matches[maxInliers[ii]].id2].y << endl;
}
}*/
// Call leastSquaresFit
leastSquaresFit(f1, f2, matches, m, maxInliers, M);
// END TODO
return 0;
}
/******************* TO DO *********************
* countInliers:
* INPUT:
* f1, f2: source feature sets
* matches: correspondences between f1 and f2
* m: motion model
* Each match in 'matches' contains two feature ids of
* matching features, id1 (in f1) and id2 (in f2).
* M: transformation matrix
* RANSACthresh: RANSAC distance threshold
* inliers: inlier feature IDs
* OUTPUT:
* transform the features in f1 by M
*
* count the number of features in f1 for which the transformed
* feature is within Euclidean distance RANSACthresh of its match
* in f2
*
* store these features IDs in inliers
*
*/
int countInliers(const FeatureSet &f1, const FeatureSet &f2,
const vector<FeatureMatch> &matches, MotionModel m,
CTransform3x3 M, double RANSACthresh, vector<int> &inliers)
{
inliers.clear();
for (unsigned int i = 0; i < matches.size(); i++) {
// BEGIN TODO
// determine if the ith matched feature f1[id1-1], when transformed by M,
// is within RANSACthresh of its match in f2
//
// if so, append i to inliers
// Get the features
const FeatureMatch &m = matches[i];
const Feature &a = f1[m.id1];
const Feature &b = f2[m.id2];
// Transform f1[m.id1] by M
CVector3 p;
p[0] = a.x;
p[1] = a.y;
p[2] = 1;
CVector3 pt = M * p;
//cout << pt[2] << endl;
// Transformed f1[m.id1]
double xt = pt[0] / pt[2];
double yt = pt[1] / pt[2];
// Compute Euclidean distance from xt,yt to b.x,b.y
// and check if within RANSACthresh
double distance = sqrt((b.x-xt)*(b.x-xt) + (b.y-yt)*(b.y-yt));
if (distance <= RANSACthresh) {
// Append i to inliers
inliers.push_back(i);
}
// END TODO
}
return (int) inliers.size();
}
/******************* TO DO *********************
* leastSquaresFit:
* INPUT:
* f1, f2: source feature sets
* matches: correspondences between f1 and f2
* m: motion model
* inliers: inlier match indices (indexes into 'matches' array)
* M: transformation matrix (output)
* OUTPUT:
* compute the transformation from f1 to f2 using only the inliers
* and return it in M
*/
int leastSquaresFit(const FeatureSet &f1, const FeatureSet &f2,
const vector<FeatureMatch> &matches, MotionModel m,
const vector<int> &inliers, CTransform3x3& M)
{
// This function needs to handle two possible motion models,
// pure translations and full homographies.
switch (m) {
case eTranslate: {
// for spherically warped images, the transformation is a
// translation and only has two degrees of freedom
//
// therefore, we simply compute the average translation vector
// between the feature in f1 and its match in f2 for all inliers
double u = 0;
double v = 0;
for (int i=0; i < (int) inliers.size(); i++) {
// BEGIN TODO
// use this loop to compute the average translation vector
// over all inliers
FeatureMatch m = matches[inliers[i]];
Feature a = f1[m.id1];
Feature b = f2[m.id2];
// Sum the differences
u += b.x - a.x;
v += b.y - a.y;
// END TODO
}
u /= inliers.size();
v /= inliers.size();
M = CTransform3x3::Translation((float) u, (float) v);
break;
}
case eHomography: {
M = CTransform3x3();
// BEGIN TODO
// Compute a homography M using all inliers.
// This should call ComputeHomography.
// Put the matches specified by inliers into a new FeatureMatch vector
vector<FeatureMatch> inlierMatches;
inlierMatches.clear();
for (int i = 0; i < (int)inliers.size(); i++) {
FeatureMatch m = matches[inliers[i]];
inlierMatches.push_back(m);
}
// Compute the homography using all inliers
M = ComputeHomography(f1, f2, inlierMatches);
// END TODO
break;
}
}
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>One line docu to save me code reading the next time ;-)<commit_after><|endoftext|> |
<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2016 Intel Corporation. All Rights Reserved.
#include "rs_sdk_version.h"
#include "rs/utils/log_utils.h"
#include "rs/core/status.h"
#include "fstream"
#include "stdio.h"
#include <string>
#include <iostream>
#include <string.h>
#ifdef WIN32
#include <shlobj.h>
#else
#include <pwd.h>
#include "dlfcn.h"
#include <sys/types.h>
#include <unistd.h>
#endif
using namespace std;
using namespace rs::core;
DLL_EXPORT rs::utils::log_util logger;
namespace rs
{
namespace utils
{
log_util::log_util(wchar_t* name)
{
#ifdef WIN32
m_logger = &m_empty_logger;
std::string nameStr;
if (name)
{
char buffer[1024];
wcstombs(buffer, name, sizeof(buffer));
std::string tmp(buffer);
nameStr = tmp;
}
if (!name || !name[0]) //if the name of the logger is not hardcoded specified
{
string tmp("/proc/self/comm");
std::ifstream comm(tmp.c_str());
if (comm.is_open()) //get our process name
{
char buffer[1024];
comm.getline(buffer, 1024);
string tmp(buffer);
nameStr = tmp;
}
}
// try to open shared library with RSLogger object
char path[1024];
HRESULT res = SHGetFolderPathA(NULL, CSIDL_PROFILE, NULL, 0, path);
if (res != S_OK)
{
cerr << res << endl;
return;
}
HINSTANCE handle = LoadLibrary("librs_logger.dll");
if (!handle)
{
cerr << GetLastError() << endl;
return;
}
string tmp(path);
status(*func)(logging_service**);
func = (status(*)(logging_service**))GetProcAddress(handle, "get_logger_instance");
//now try to get logger instance
logging_service* new_logger;
status sts = (*func)(&new_logger);
if (sts != status_no_error)
{
return;
}
m_logger = new_logger;
string configFile = tmp + "/RSLogs/rslog.properties";
// Check if logger configured (need to configure only first logger in process)
if (!m_logger->is_configured())
{
const size_t cSize = configFile.length() + 1;
wchar_t* wc = new wchar_t[cSize];
memset(wc, 0, sizeof(wchar_t)*(cSize));
mbstowcs(wc, configFile.c_str(), cSize);
m_logger->configure(logging_service::config_property_file_log4j, wc, 0);
delete[] wc;
if (!m_logger->is_configured()) // init on config file failed
{
delete m_logger;
m_logger = &m_empty_logger;
}
}
const size_t cSize = nameStr.length() + 1;
wchar_t* wc = new wchar_t[cSize];
memset(wc, 0, sizeof(wchar_t)*(cSize));
mbstowcs(wc, nameStr.c_str(), cSize);
m_logger->set_logger_name(wc);
delete[] wc;
FreeLibrary(handle);
#else
m_logger = &m_empty_logger;
std::string name_string;
if (name)
{
char buffer[1024];
wcstombs(buffer, name, sizeof(buffer));
std::string tmp(buffer);
name_string = tmp;
}
if (!name || !name[0]) //if the name of the logger is not hardcoded specified
{
string tmp("/proc/self/comm");
std::ifstream comm(tmp.c_str());
if (comm.is_open()) //get our process name
{
char buffer[1024];
comm.getline(buffer, 1024);
string tmp(buffer);
name_string = tmp;
}
}
// try to open shared library with RSLogger object
void *handle;
struct passwd *pw = getpwuid(getuid());
string rs_logger_lib_name = "librealsense_logger.so";
handle = dlopen(rs_logger_lib_name.c_str(), RTLD_NOW);
if (!handle)
{
char* error_message = dlerror();
if (error_message)
fputs(error_message, stderr);
return;
}
else
{
cout << "Logger library successfully loaded: " << rs_logger_lib_name << std::endl;
}
status(*get_logger_instance_func)(logging_service**);
void(*check_version_func)(int*, int*);
check_version_func = (void(*)(int*, int*))dlsym(handle, "get_lib_major_minor_version");
if (!check_version_func)
{
fputs("realsense_logger version does not match - logging disabled\n", stderr);
return;
}
int maj = -1, min = -1;
(*check_version_func)(&maj, &min);
if ((maj != SDK_VER_MAJOR) ||
(maj == 0 && min != SDK_VER_MINOR))
{
fputs("realsense_logger version does not match - logging disabled\n", stderr);
return;
}
/* Resolve the method from the shared library */
get_logger_instance_func = (status(*)(logging_service**))dlsym(handle, "get_logger_instance");
if (!get_logger_instance_func)
{
char* error_message = dlerror();
if (error_message)
fputs(error_message, stderr);
return;
}
//now try to get logger instance
logging_service* new_logger;
status sts = (*get_logger_instance_func)(&new_logger);
if (sts != status_no_error)
{
return;
}
m_logger = new_logger;
char* properties_location = getenv("REALSENSE_SDK_LOG_PATH");
string config_file_path;
if (properties_location)
{
config_file_path = properties_location;
}
else
{
const char *homedir = pw->pw_dir;
string home_directory(homedir);
config_file_path = home_directory + "/realsense/logs/";
}
config_file_path += "/rslog.properties";
// Check if logger configured (need to configure only first logger in process)
if (!m_logger->is_configured())
{
const size_t cSize = config_file_path.length() + 1;
wchar_t* wc = new wchar_t[cSize];
memset(wc, 0, sizeof(wchar_t)*(cSize));
mbstowcs(wc, config_file_path.c_str(), cSize);
m_logger->configure(logging_service::config_property_file_log4j, wc, 0);
delete[] wc;
if (!m_logger->is_configured()) // init on config file failed
{
delete m_logger;
m_logger = &m_empty_logger;
}
else
{
cout << "Logger configuration file found, logging enabled." << std::endl;
}
}
const size_t cSize = name_string.length() + 1;
wchar_t* wc = new wchar_t[cSize];
memset(wc, 0, sizeof(wchar_t)*(cSize));
mbstowcs(wc, name_string.c_str(), cSize);
m_logger->set_logger_name(wc);
delete[] wc;
#endif
}
log_util::~log_util()
{
if (m_logger != &m_empty_logger)
{
m_logger = &m_empty_logger;
}
}
}
}
<commit_msg>Revert "enable logger fail to load logger so message"<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2016 Intel Corporation. All Rights Reserved.
#include "rs_sdk_version.h"
#include "rs/utils/log_utils.h"
#include "rs/core/status.h"
#include "fstream"
#include "stdio.h"
#include <string>
#include <iostream>
#include <string.h>
#ifdef WIN32
#include <shlobj.h>
#else
#include <pwd.h>
#include "dlfcn.h"
#include <sys/types.h>
#include <unistd.h>
#endif
using namespace std;
using namespace rs::core;
DLL_EXPORT rs::utils::log_util logger;
namespace rs
{
namespace utils
{
log_util::log_util(wchar_t* name)
{
#ifdef WIN32
m_logger = &m_empty_logger;
std::string nameStr;
if (name)
{
char buffer[1024];
wcstombs(buffer, name, sizeof(buffer));
std::string tmp(buffer);
nameStr = tmp;
}
if (!name || !name[0]) //if the name of the logger is not hardcoded specified
{
string tmp("/proc/self/comm");
std::ifstream comm(tmp.c_str());
if (comm.is_open()) //get our process name
{
char buffer[1024];
comm.getline(buffer, 1024);
string tmp(buffer);
nameStr = tmp;
}
}
// try to open shared library with RSLogger object
char path[1024];
HRESULT res = SHGetFolderPathA(NULL, CSIDL_PROFILE, NULL, 0, path);
if (res != S_OK)
{
cerr << res << endl;
return;
}
HINSTANCE handle = LoadLibrary("librs_logger.dll");
if (!handle)
{
cerr << GetLastError() << endl;
return;
}
string tmp(path);
status(*func)(logging_service**);
func = (status(*)(logging_service**))GetProcAddress(handle, "get_logger_instance");
//now try to get logger instance
logging_service* new_logger;
status sts = (*func)(&new_logger);
if (sts != status_no_error)
{
return;
}
m_logger = new_logger;
string configFile = tmp + "/RSLogs/rslog.properties";
// Check if logger configured (need to configure only first logger in process)
if (!m_logger->is_configured())
{
const size_t cSize = configFile.length() + 1;
wchar_t* wc = new wchar_t[cSize];
memset(wc, 0, sizeof(wchar_t)*(cSize));
mbstowcs(wc, configFile.c_str(), cSize);
m_logger->configure(logging_service::config_property_file_log4j, wc, 0);
delete[] wc;
if (!m_logger->is_configured()) // init on config file failed
{
delete m_logger;
m_logger = &m_empty_logger;
}
}
const size_t cSize = nameStr.length() + 1;
wchar_t* wc = new wchar_t[cSize];
memset(wc, 0, sizeof(wchar_t)*(cSize));
mbstowcs(wc, nameStr.c_str(), cSize);
m_logger->set_logger_name(wc);
delete[] wc;
FreeLibrary(handle);
#else
m_logger = &m_empty_logger;
std::string name_string;
if (name)
{
char buffer[1024];
wcstombs(buffer, name, sizeof(buffer));
std::string tmp(buffer);
name_string = tmp;
}
if (!name || !name[0]) //if the name of the logger is not hardcoded specified
{
string tmp("/proc/self/comm");
std::ifstream comm(tmp.c_str());
if (comm.is_open()) //get our process name
{
char buffer[1024];
comm.getline(buffer, 1024);
string tmp(buffer);
name_string = tmp;
}
}
// try to open shared library with RSLogger object
void *handle;
struct passwd *pw = getpwuid(getuid());
string rs_logger_lib_name = "librealsense_logger.so";
handle = dlopen(rs_logger_lib_name.c_str(), RTLD_NOW);
if (!handle)
{
//char* error_message = dlerror();
/*if (error_message)
fputs(error_message, stderr);*/
return;
}
else
{
cout << "Logger library successfully loaded: " << rs_logger_lib_name << std::endl;
}
status(*get_logger_instance_func)(logging_service**);
void(*check_version_func)(int*, int*);
check_version_func = (void(*)(int*, int*))dlsym(handle, "get_lib_major_minor_version");
if (!check_version_func)
{
fputs("realsense_logger version does not match - logging disabled\n", stderr);
return;
}
int maj = -1, min = -1;
(*check_version_func)(&maj, &min);
if ((maj != SDK_VER_MAJOR) ||
(maj == 0 && min != SDK_VER_MINOR))
{
fputs("realsense_logger version does not match - logging disabled\n", stderr);
return;
}
/* Resolve the method from the shared library */
get_logger_instance_func = (status(*)(logging_service**))dlsym(handle, "get_logger_instance");
if (!get_logger_instance_func)
{
char* error_message = dlerror();
if (error_message)
fputs(error_message, stderr);
return;
}
//now try to get logger instance
logging_service* new_logger;
status sts = (*get_logger_instance_func)(&new_logger);
if (sts != status_no_error)
{
return;
}
m_logger = new_logger;
char* properties_location = getenv("REALSENSE_SDK_LOG_PATH");
string config_file_path;
if (properties_location)
{
config_file_path = properties_location;
}
else
{
const char *homedir = pw->pw_dir;
string home_directory(homedir);
config_file_path = home_directory + "/realsense/logs/";
}
config_file_path += "/rslog.properties";
// Check if logger configured (need to configure only first logger in process)
if (!m_logger->is_configured())
{
const size_t cSize = config_file_path.length() + 1;
wchar_t* wc = new wchar_t[cSize];
memset(wc, 0, sizeof(wchar_t)*(cSize));
mbstowcs(wc, config_file_path.c_str(), cSize);
m_logger->configure(logging_service::config_property_file_log4j, wc, 0);
delete[] wc;
if (!m_logger->is_configured()) // init on config file failed
{
delete m_logger;
m_logger = &m_empty_logger;
}
else
{
cout << "Logger configuration file found, logging enabled." << std::endl;
}
}
const size_t cSize = name_string.length() + 1;
wchar_t* wc = new wchar_t[cSize];
memset(wc, 0, sizeof(wchar_t)*(cSize));
mbstowcs(wc, name_string.c_str(), cSize);
m_logger->set_logger_name(wc);
delete[] wc;
#endif
}
log_util::~log_util()
{
if (m_logger != &m_empty_logger)
{
m_logger = &m_empty_logger;
}
}
}
}
<|endoftext|> |
<commit_before>#include "LinuxContainer.h"
void LinuxContainer::mainContainer(int argc, char** argv)
{
Singleton<ObserverDirector>::get().init();
WindowGL* glWindow = new WindowGL(argc, argv);
RendererGL* glRenderer = new RendererGL();
InputGL* input = new InputGL();
CameraGL* camGL = new CameraGL(
(float)F_O_V,
(float)SCREEN_WIDTH / (float)SCREEN_HEIGHT,
(float)Z_NEAR,
(float)Z_FAR);
initLinux(
glWindow,
glRenderer,
input,
camGL);
GameEntity* pacman = initPacman();
Game* game = new Game(
camGL,
glWindow,
glRenderer,
pacman);
game->run();
//Clean up
delete game;
}
void LinuxContainer::initLinux(
WindowGL* windowGL,
RendererGL* rendererGL,
InputGL* inputGL,
CameraGL* cameraGL)
{
windowGL->init();
rendererGL->init();
cameraGL->init();
inputGL->init();
}
GameEntity* LinuxContainer::initPacman()
{
GameEntity* gameEntity = new GameEntity(VecF3(0.0f, 0.0f, 0.0f), VecF3(0.0f, 0.0f, 0.0f), VecF3(1.0f, 1.0f, 1.0f));
vector<PosNormTex>* vertices = new vector<PosNormTex>;
vertices->push_back(PosNormTex(VecF3(-1.0f, 1.0f, 1.0f), VecF3(0.0f, 0.0f, 1.0f), VecF2(0.0f, 0.0f)));
vertices->push_back(PosNormTex(VecF3(1.0f, 1.0f, 1.0f), VecF3(0.0f, 0.0f, 1.0f), VecF2(1.0f, 0.0f)));
vertices->push_back(PosNormTex(VecF3(-1.0f, -1.0f, 1.0f), VecF3(0.0f, 0.0f, 1.0f), VecF2(0.0f, 1.0f)));
vertices->push_back(PosNormTex(VecF3(1.0f, -1.0f, 1.0f), VecF3(0.0f, 0.0f, 1.0f), VecF2(1.0f, 1.0f)));
std::vector<unsigned int>* indices = new std::vector<unsigned int>();
indices->push_back(0);
indices->push_back(1);
indices->push_back(2);
indices->push_back(2);
indices->push_back(1);
indices->push_back(3);
GraphicsContainer* graphicsContainer = new GraphicsContainerGL(
VERTEX_SHADER_DEFAULT,
PIXEL_SHADER_DEFAULT,
vertices,
indices,
vertices->size(),
indices->size(),
8,
sizeof(PosNormTex),
0);
gameEntity->setGraphicsContainer(graphicsContainer);
MoveBehaviour* moveBehaviour = new MoveBehaviourPlayer();
moveBehaviour->init();
gameEntity->setMoveBehaviour(moveBehaviour);
return gameEntity;
}
<commit_msg>Fixed minor mem-leak<commit_after>#include "LinuxContainer.h"
void LinuxContainer::mainContainer(int argc, char** argv)
{
Singleton<ObserverDirector>::get().init();
WindowGL* glWindow = new WindowGL(argc, argv);
RendererGL* glRenderer = new RendererGL();
InputGL* input = new InputGL();
CameraGL* camGL = new CameraGL(
(float)F_O_V,
(float)SCREEN_WIDTH / (float)SCREEN_HEIGHT,
(float)Z_NEAR,
(float)Z_FAR);
initLinux(
glWindow,
glRenderer,
input,
camGL);
GameEntity* pacman = initPacman();
Game* game = new Game(
camGL,
glWindow,
glRenderer,
pacman);
game->run();
DELETE_NULL(input); //handled via callbacks outside of game
DELETE_NULL(game);
}
void LinuxContainer::initLinux(
WindowGL* windowGL,
RendererGL* rendererGL,
InputGL* inputGL,
CameraGL* cameraGL)
{
windowGL->init();
rendererGL->init();
cameraGL->init();
inputGL->init();
}
GameEntity* LinuxContainer::initPacman()
{
GameEntity* gameEntity = new GameEntity(VecF3(0.0f, 0.0f, 0.0f), VecF3(0.0f, 0.0f, 0.0f), VecF3(1.0f, 1.0f, 1.0f));
vector<PosNormTex>* vertices = new vector<PosNormTex>;
vertices->push_back(PosNormTex(VecF3(-1.0f, 1.0f, 1.0f), VecF3(0.0f, 0.0f, 1.0f), VecF2(0.0f, 0.0f)));
vertices->push_back(PosNormTex(VecF3(1.0f, 1.0f, 1.0f), VecF3(0.0f, 0.0f, 1.0f), VecF2(1.0f, 0.0f)));
vertices->push_back(PosNormTex(VecF3(-1.0f, -1.0f, 1.0f), VecF3(0.0f, 0.0f, 1.0f), VecF2(0.0f, 1.0f)));
vertices->push_back(PosNormTex(VecF3(1.0f, -1.0f, 1.0f), VecF3(0.0f, 0.0f, 1.0f), VecF2(1.0f, 1.0f)));
std::vector<unsigned int>* indices = new std::vector<unsigned int>();
indices->push_back(0);
indices->push_back(1);
indices->push_back(2);
indices->push_back(2);
indices->push_back(1);
indices->push_back(3);
GraphicsContainer* graphicsContainer = new GraphicsContainerGL(
VERTEX_SHADER_DEFAULT,
PIXEL_SHADER_DEFAULT,
TEXTURE_PACMAN,
vertices,
indices,
vertices->size(),
indices->size(),
8,
sizeof(PosNormTex),
0);
gameEntity->setGraphicsContainer(graphicsContainer);
MoveBehaviour* moveBehaviour = new MoveBehaviourPlayer();
moveBehaviour->init();
gameEntity->setMoveBehaviour(moveBehaviour);
return gameEntity;
}
<|endoftext|> |
<commit_before>#include "xchainer/routines/creation.h"
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <type_traits>
#include <utility>
#include "xchainer/array.h"
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/scalar.h"
#include "xchainer/shape.h"
#include "xchainer/strides.h"
namespace xchainer {
namespace internal {
size_t GetRequiredBytes(const Shape& shape, const Strides& strides, size_t element_size) {
assert(shape.ndim() == strides.ndim());
if (shape.GetTotalSize() == 0) {
return 0;
}
// Calculate the distance between the first and the last element, plus single element size.
size_t total_bytes = element_size;
for (int8_t i = 0; i < shape.ndim(); ++i) {
total_bytes += (shape[i] - 1) * std::abs(strides[i]);
}
return total_bytes;
}
Array FromHostData(const Shape& shape, Dtype dtype, const std::shared_ptr<void>& data, const Strides& strides, Device& device) {
auto bytesize = GetRequiredBytes(shape, strides, GetElementSize(dtype));
std::shared_ptr<void> device_data = device.FromHostMemory(data, bytesize);
return MakeArray(shape, strides, dtype, device, device_data);
}
Array Empty(const Shape& shape, Dtype dtype, const Strides& strides, Device& device) {
auto bytesize = GetRequiredBytes(shape, strides, GetElementSize(dtype));
std::shared_ptr<void> data = device.Allocate(bytesize);
return MakeArray(shape, strides, dtype, device, data);
}
} // namespace internal
Array Empty(const Shape& shape, Dtype dtype, Device& device) {
auto bytesize = static_cast<size_t>(shape.GetTotalSize() * GetElementSize(dtype));
std::shared_ptr<void> data = device.Allocate(bytesize);
return internal::MakeArray(shape, Strides{shape, dtype}, dtype, device, data);
}
Array Full(const Shape& shape, Scalar fill_value, Dtype dtype, Device& device) {
Array array = Empty(shape, dtype, device);
array.Fill(fill_value);
return array;
}
Array Full(const Shape& shape, Scalar fill_value, Device& device) { return Full(shape, fill_value, fill_value.dtype(), device); }
Array Zeros(const Shape& shape, Dtype dtype, Device& device) { return Full(shape, 0, dtype, device); }
Array Ones(const Shape& shape, Dtype dtype, Device& device) { return Full(shape, 1, dtype, device); }
Array Arange(Scalar start, Scalar stop, Scalar step, Dtype dtype, Device& device) {
// TODO(hvy): Simplify comparison if Scalar::operator== supports dtype conversion.
if (step == Scalar{0, step.dtype()}) {
throw XchainerError("Cannot create an arange array with 0 step size.");
}
// Compute the size of the output.
auto t_start = static_cast<double>(start);
auto t_stop = static_cast<double>(stop);
auto t_step = static_cast<double>(step);
if (t_step < 0) {
std::swap(t_start, t_stop);
t_step *= -1;
}
auto size = std::max(int64_t{0}, static_cast<int64_t>(std::ceil((t_stop - t_start) / t_step)));
if (size > 2 && dtype == Dtype::kBool) {
throw DtypeError("Cannot create an arange array of booleans with size larger than 2.");
}
Array out = Empty({size}, dtype, device);
device.Arange(start, step, out);
return out;
}
Array Arange(Scalar start, Scalar stop, Scalar step, Device& device) {
// step may be passed by the default value 1, in which case type promotion is allowed.
// TODO(hvy): Revisit after supporting type promotion.
bool start_stop_any_float = GetKind(start.dtype()) == DtypeKind::kFloat || GetKind(stop.dtype()) == DtypeKind::kFloat;
return Arange(start, stop, step, start_stop_any_float ? Dtype::kFloat64 : step.dtype(), device);
}
Array Arange(Scalar start, Scalar stop, Dtype dtype, Device& device) { return Arange(start, stop, 1, dtype, device); }
Array Arange(Scalar stop, Dtype dtype, Device& device) { return Arange(0, stop, 1, dtype, device); }
Array Arange(Scalar stop, Device& device) { return Arange(0, stop, 1, stop.dtype(), device); }
Array EmptyLike(const Array& a, Device& device) { return Empty(a.shape(), a.dtype(), device); }
Array FullLike(const Array& a, Scalar fill_value, Device& device) { return Full(a.shape(), fill_value, a.dtype(), device); }
Array ZerosLike(const Array& a, Device& device) { return Zeros(a.shape(), a.dtype(), device); }
Array OnesLike(const Array& a, Device& device) { return Ones(a.shape(), a.dtype(), device); }
Array Copy(const Array& a) {
// No graph will be disconnected.
Array out = a.AsConstant({}, CopyKind::kCopy);
assert(out.IsContiguous());
return out;
}
} // namespace xchainer
<commit_msg>Do not use reserved prefix<commit_after>#include "xchainer/routines/creation.h"
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <type_traits>
#include <utility>
#include "xchainer/array.h"
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/scalar.h"
#include "xchainer/shape.h"
#include "xchainer/strides.h"
namespace xchainer {
namespace internal {
size_t GetRequiredBytes(const Shape& shape, const Strides& strides, size_t element_size) {
assert(shape.ndim() == strides.ndim());
if (shape.GetTotalSize() == 0) {
return 0;
}
// Calculate the distance between the first and the last element, plus single element size.
size_t total_bytes = element_size;
for (int8_t i = 0; i < shape.ndim(); ++i) {
total_bytes += (shape[i] - 1) * std::abs(strides[i]);
}
return total_bytes;
}
Array FromHostData(const Shape& shape, Dtype dtype, const std::shared_ptr<void>& data, const Strides& strides, Device& device) {
auto bytesize = GetRequiredBytes(shape, strides, GetElementSize(dtype));
std::shared_ptr<void> device_data = device.FromHostMemory(data, bytesize);
return MakeArray(shape, strides, dtype, device, device_data);
}
Array Empty(const Shape& shape, Dtype dtype, const Strides& strides, Device& device) {
auto bytesize = GetRequiredBytes(shape, strides, GetElementSize(dtype));
std::shared_ptr<void> data = device.Allocate(bytesize);
return MakeArray(shape, strides, dtype, device, data);
}
} // namespace internal
Array Empty(const Shape& shape, Dtype dtype, Device& device) {
auto bytesize = static_cast<size_t>(shape.GetTotalSize() * GetElementSize(dtype));
std::shared_ptr<void> data = device.Allocate(bytesize);
return internal::MakeArray(shape, Strides{shape, dtype}, dtype, device, data);
}
Array Full(const Shape& shape, Scalar fill_value, Dtype dtype, Device& device) {
Array array = Empty(shape, dtype, device);
array.Fill(fill_value);
return array;
}
Array Full(const Shape& shape, Scalar fill_value, Device& device) { return Full(shape, fill_value, fill_value.dtype(), device); }
Array Zeros(const Shape& shape, Dtype dtype, Device& device) { return Full(shape, 0, dtype, device); }
Array Ones(const Shape& shape, Dtype dtype, Device& device) { return Full(shape, 1, dtype, device); }
Array Arange(Scalar start, Scalar stop, Scalar step, Dtype dtype, Device& device) {
// TODO(hvy): Simplify comparison if Scalar::operator== supports dtype conversion.
if (step == Scalar{0, step.dtype()}) {
throw XchainerError("Cannot create an arange array with 0 step size.");
}
// Compute the size of the output.
auto d_start = static_cast<double>(start);
auto d_stop = static_cast<double>(stop);
auto d_step = static_cast<double>(step);
if (d_step < 0) {
std::swap(d_start, d_stop);
d_step *= -1;
}
auto size = std::max(int64_t{0}, static_cast<int64_t>(std::ceil((d_stop - d_start) / d_step)));
if (size > 2 && dtype == Dtype::kBool) {
throw DtypeError("Cannot create an arange array of booleans with size larger than 2.");
}
Array out = Empty({size}, dtype, device);
device.Arange(start, step, out);
return out;
}
Array Arange(Scalar start, Scalar stop, Scalar step, Device& device) {
// step may be passed by the default value 1, in which case type promotion is allowed.
// TODO(hvy): Revisit after supporting type promotion.
bool start_stop_any_float = GetKind(start.dtype()) == DtypeKind::kFloat || GetKind(stop.dtype()) == DtypeKind::kFloat;
return Arange(start, stop, step, start_stop_any_float ? Dtype::kFloat64 : step.dtype(), device);
}
Array Arange(Scalar start, Scalar stop, Dtype dtype, Device& device) { return Arange(start, stop, 1, dtype, device); }
Array Arange(Scalar stop, Dtype dtype, Device& device) { return Arange(0, stop, 1, dtype, device); }
Array Arange(Scalar stop, Device& device) { return Arange(0, stop, 1, stop.dtype(), device); }
Array EmptyLike(const Array& a, Device& device) { return Empty(a.shape(), a.dtype(), device); }
Array FullLike(const Array& a, Scalar fill_value, Device& device) { return Full(a.shape(), fill_value, a.dtype(), device); }
Array ZerosLike(const Array& a, Device& device) { return Zeros(a.shape(), a.dtype(), device); }
Array OnesLike(const Array& a, Device& device) { return Ones(a.shape(), a.dtype(), device); }
Array Copy(const Array& a) {
// No graph will be disconnected.
Array out = a.AsConstant({}, CopyKind::kCopy);
assert(out.IsContiguous());
return out;
}
} // namespace xchainer
<|endoftext|> |
<commit_before>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by J-Donald Tournier, 27/06/08.
This file is part of MRtrix.
MRtrix 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 3 of the License, or
(at your option) any later version.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "progressbar.h"
#include "image/buffer.h"
#include "image/buffer_preload.h"
#include "image/voxel.h"
#include "math/matrix.h"
#include "math/SH.h"
#include "dwi/gradient.h"
#include "dwi/shells.h"
#include "image/threaded_loop.h"
using namespace MR;
using namespace App;
void usage ()
{
DESCRIPTION
+ "convert a set of amplitudes (defined along a set of corresponding directions) "
"to their spherical harmonic representation. The spherical harmonic decomposition is "
"calculated by least-squares linear fitting."
+ "The directions can be defined either as a DW gradient scheme (for example to compute "
"the SH representation of the DW signal) or a set of [az el] pairs as output by the gendir "
"command. The DW gradient scheme or direction set can be supplied within the input "
"image header or using the -gradient or -directions option. Note that if a direction set "
"and DW gradient scheme can be found, the direction set will be used by default."
+ "Note that this program makes use of implied symmetries in the diffusion "
"profile. First, the fact the signal attenuation profile is real implies "
"that it has conjugate symmetry, i.e. Y(l,-m) = Y(l,m)* (where * denotes the "
"complex conjugate). Second, the diffusion profile should be antipodally "
"symmetric (i.e. S(x) = S(-x)), implying that all odd l components should be "
"zero. Therefore, this program only computes the even elements."
+ "Note that the spherical harmonics equations used here differ slightly from "
"those conventionally used, in that the (-1)^m factor has been omitted. This "
"should be taken into account in all subsequent calculations."
+ Math::SH::encoding_description;
ARGUMENTS
+ Argument ("amp", "the input amplitude image.").type_image_in ()
+ Argument ("SH", "the output spherical harmonics coefficients image.").type_image_out ();
OPTIONS
+ Option ("lmax",
"set the maximum harmonic order for the output series. By default, the "
"program will use the highest possible lmax given the number of "
"diffusion-weighted images.")
+ Argument ("order").type_integer (0, 8, 30)
+ Option ("normalise", "normalise the DW signal to the b=0 image")
+ Option ("directions", "the directions corresponding to the input amplitude image used to sample AFD. "
"By default this option is not required providing the direction set is supplied "
"in the amplitude image.")
+ Argument ("file", "a list of directions [az el] generated using the gendir command.").type_file_in()
+ DWI::GradImportOptions()
+ DWI::ShellOption
+ Image::Stride::StrideOption;
}
typedef float value_type;
class Amp2SHCommon {
public:
Amp2SHCommon (const Math::Matrix<value_type>& sh2amp,
const std::vector<size_t>& bzeros,
const std::vector<size_t>& dwis,
bool normalise_to_bzero) :
amp2sh (Math::pinv (sh2amp)),
bzeros (bzeros),
dwis (dwis),
normalise (normalise_to_bzero) { }
Math::Matrix<value_type> amp2sh;
const std::vector<size_t>& bzeros;
const std::vector<size_t>& dwis;
bool normalise;
};
class Amp2SH {
public:
Amp2SH (const Amp2SHCommon& common) :
C (common),
a (common.amp2sh.columns()),
c (common.amp2sh.rows())
{ }
template <class SHVoxelType, class AmpVoxelType>
void operator() (SHVoxelType& SH, AmpVoxelType& amp)
{
double norm = 1.0;
if (C.normalise) {
for (size_t n = 0; n < C.bzeros.size(); n++) {
amp[3] = C.bzeros[n];
norm += amp.value ();
}
norm = C.bzeros.size() / norm;
}
for (size_t n = 0; n < a.size(); n++) {
amp[3] = C.dwis.size() ? C.dwis[n] : n;
a[n] = amp.value() * norm;
}
mult (c, C.amp2sh, a);
for (SH[3] = 0; SH[3] < SH.dim (3); ++SH[3])
SH.value() = c[SH[3]];
}
protected:
const Amp2SHCommon& C;
Math::Vector<value_type> a, c;
};
void run ()
{
Image::BufferPreload<value_type> amp_data (argument[0], Image::Stride::contiguous_along_axis (3));
Image::Header header (amp_data);
std::vector<size_t> bzeros, dwis;
Math::Matrix<value_type> dirs;
Options opt = get_options ("directions");
if (opt.size()) {
dirs.load(opt[0][0]);
}
else {
if (header["directions"].size()) {
std::vector<value_type> dir_vector;
std::vector<std::string > lines = split (header["directions"], "\n", true);
for (size_t l = 0; l < lines.size(); l++) {
std::vector<value_type> v (parse_floats (lines[l]));
dir_vector.insert (dir_vector.end(), v.begin(), v.end());
}
dirs.resize(dir_vector.size() / 2, 2);
for (size_t i = 0; i < dir_vector.size(); i += 2) {
dirs(i / 2, 0) = dir_vector[i];
dirs(i / 2, 1) = dir_vector[i + 1];
}
}
else {
Math::Matrix<value_type> grad = DWI::get_valid_DW_scheme<value_type> (amp_data);
DWI::Shells shells (grad);
shells.select_shells (true, true);
bzeros = shells.smallest().get_volumes();
dwis = shells.largest().get_volumes();
dirs = DWI::gen_direction_matrix (grad, dwis);
}
}
Math::Matrix<value_type> sh2amp = DWI::compute_SH2amp_mapping (dirs, true, 8);
bool normalise = get_options ("normalise").size();
if (normalise && !bzeros.size())
throw Exception ("the normalise option is only available if the input data contains b=0 images.");
header.dim (3) = sh2amp.columns();
header.datatype() = DataType::Float32;
Image::Stride::set_from_command_line (header);
Image::Buffer<value_type> SH_data (argument[1], header);
auto amp_vox = amp_data.voxel();
auto SH_vox = SH_data.voxel();
Amp2SHCommon common (sh2amp, bzeros, dwis, normalise);
Image::ThreadedLoop ("mapping amplitudes to SH coefficients...", amp_vox)
.run (Amp2SH (common), SH_vox, amp_vox);
}
<commit_msg>amp2sh: add -rician option to correct for Rician bias<commit_after>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by J-Donald Tournier, 27/06/08.
This file is part of MRtrix.
MRtrix 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 3 of the License, or
(at your option) any later version.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "progressbar.h"
#include "image/buffer.h"
#include "image/buffer_preload.h"
#include "image/voxel.h"
#include "math/matrix.h"
#include "math/SH.h"
#include "dwi/gradient.h"
#include "dwi/shells.h"
#include "image/threaded_loop.h"
using namespace MR;
using namespace App;
void usage ()
{
DESCRIPTION
+ "convert a set of amplitudes (defined along a set of corresponding directions) "
"to their spherical harmonic representation. The spherical harmonic decomposition is "
"calculated by least-squares linear fitting."
+ "The directions can be defined either as a DW gradient scheme (for example to compute "
"the SH representation of the DW signal) or a set of [az el] pairs as output by the gendir "
"command. The DW gradient scheme or direction set can be supplied within the input "
"image header or using the -gradient or -directions option. Note that if a direction set "
"and DW gradient scheme can be found, the direction set will be used by default."
+ "Note that this program makes use of implied symmetries in the diffusion "
"profile. First, the fact the signal attenuation profile is real implies "
"that it has conjugate symmetry, i.e. Y(l,-m) = Y(l,m)* (where * denotes the "
"complex conjugate). Second, the diffusion profile should be antipodally "
"symmetric (i.e. S(x) = S(-x)), implying that all odd l components should be "
"zero. Therefore, this program only computes the even elements."
+ "Note that the spherical harmonics equations used here differ slightly from "
"those conventionally used, in that the (-1)^m factor has been omitted. This "
"should be taken into account in all subsequent calculations."
+ Math::SH::encoding_description;
ARGUMENTS
+ Argument ("amp", "the input amplitude image.").type_image_in ()
+ Argument ("SH", "the output spherical harmonics coefficients image.").type_image_out ();
OPTIONS
+ Option ("lmax",
"set the maximum harmonic order for the output series. By default, the "
"program will use the highest possible lmax given the number of "
"diffusion-weighted images.")
+ Argument ("order").type_integer (0, 8, 30)
+ Option ("normalise", "normalise the DW signal to the b=0 image")
+ Option ("directions", "the directions corresponding to the input amplitude image used to sample AFD. "
"By default this option is not required providing the direction set is supplied "
"in the amplitude image. This should be supplied as a list of directions [az el], "
"as generated using the gendir command")
+ Argument ("file").type_file_in()
+ Option ("rician", "correct for Rician noise induced bias, using noise map supplied")
+ Argument ("noise").type_image_in()
+ DWI::GradImportOptions()
+ DWI::ShellOption
+ Image::Stride::StrideOption;
}
#define RICIAN_POWER 2.25
typedef float value_type;
class Amp2SHCommon {
public:
Amp2SHCommon (const Math::Matrix<value_type>& sh2amp,
const std::vector<size_t>& bzeros,
const std::vector<size_t>& dwis,
bool normalise_to_bzero) :
sh2amp (sh2amp),
amp2sh (Math::pinv (sh2amp)),
bzeros (bzeros),
dwis (dwis),
normalise (normalise_to_bzero) { }
Math::Matrix<value_type> sh2amp, amp2sh;
const std::vector<size_t>& bzeros;
const std::vector<size_t>& dwis;
bool normalise;
};
class Amp2SH {
public:
Amp2SH (const Amp2SHCommon& common) :
C (common),
a (common.amp2sh.columns()),
c (common.amp2sh.rows()) { }
template <class SHVoxelType, class AmpVoxelType>
void operator() (SHVoxelType& SH, AmpVoxelType& amp)
{
get_amps (amp);
mult (c, C.amp2sh, a);
write_SH (SH);
}
// Rician-corrected version:
template <class SHVoxelType, class AmpVoxelType, class NoiseVoxelType>
void operator() (SHVoxelType& SH, AmpVoxelType& amp, const NoiseVoxelType& noise)
{
w.allocate (C.sh2amp.rows());
w = value_type(1.0);
get_amps (amp);
mult (c, C.amp2sh, a);
for (size_t iter = 0; iter < 20; ++iter) {
sh2amp = C.sh2amp;
if (get_rician_bias (sh2amp, noise.value()))
break;
for (size_t n = 0; n < sh2amp.rows(); ++n)
sh2amp.row (n) *= w[n];
Math::mult (c, value_type(1.0), CblasTrans, sh2amp, ap);
Math::mult (Q, value_type(1.0), CblasTrans, sh2amp, CblasNoTrans, sh2amp);
Math::Cholesky::decomp (Q);
Math::Cholesky::solve (c, Q);
}
write_SH (SH);
}
protected:
const Amp2SHCommon& C;
Math::Vector<value_type> a, c, w, ap;
Math::Matrix<value_type> Q, sh2amp;
template <class AmpVoxelType>
void get_amps (AmpVoxelType& amp) {
double norm = 1.0;
if (C.normalise) {
for (size_t n = 0; n < C.bzeros.size(); n++) {
amp[3] = C.bzeros[n];
norm += amp.value ();
}
norm = C.bzeros.size() / norm;
}
for (size_t n = 0; n < a.size(); n++) {
amp[3] = C.dwis.size() ? C.dwis[n] : n;
a[n] = amp.value() * norm;
}
}
template <class SHVoxelType>
void write_SH (SHVoxelType& SH) {
for (SH[3] = 0; SH[3] < SH.dim (3); ++SH[3])
SH.value() = c[SH[3]];
}
bool get_rician_bias (const Math::Matrix<value_type>& sh2amp, value_type noise) {
Math::mult (ap, sh2amp, c);
value_type norm_diff = 0.0;
value_type norm_amp = 0.0;
for (size_t n = 0; n < ap.size() ; ++n) {
ap[n] = std::max (ap[n], value_type(0.0));
value_type t = std::pow (ap[n]/noise, value_type(RICIAN_POWER));
w[n] = Math::pow2 ((t + 1.7)/(t + 1.12));
value_type diff = a[n] - noise * std::pow (t + 1.65, 1.0/RICIAN_POWER);
norm_diff += Math::pow2 (diff);
norm_amp += Math::pow2 (a[n]);
ap[n] += diff;
}
return norm_diff/norm_amp < 1.0e-8;
}
};
void run ()
{
Image::BufferPreload<value_type> amp_data (argument[0], Image::Stride::contiguous_along_axis (3));
Image::Header header (amp_data);
std::vector<size_t> bzeros, dwis;
Math::Matrix<value_type> dirs;
Options opt = get_options ("directions");
if (opt.size()) {
dirs.load(opt[0][0]);
}
else {
if (header["directions"].size()) {
std::vector<value_type> dir_vector;
std::vector<std::string > lines = split (header["directions"], "\n", true);
for (size_t l = 0; l < lines.size(); l++) {
std::vector<value_type> v (parse_floats (lines[l]));
dir_vector.insert (dir_vector.end(), v.begin(), v.end());
}
dirs.resize(dir_vector.size() / 2, 2);
for (size_t i = 0; i < dir_vector.size(); i += 2) {
dirs(i / 2, 0) = dir_vector[i];
dirs(i / 2, 1) = dir_vector[i + 1];
}
}
else {
Math::Matrix<value_type> grad = DWI::get_valid_DW_scheme<value_type> (amp_data);
DWI::Shells shells (grad);
shells.select_shells (true, true);
if (shells.smallest().is_bzero())
bzeros = shells.smallest().get_volumes();
dwis = shells.largest().get_volumes();
dirs = DWI::gen_direction_matrix (grad, dwis);
}
}
Math::Matrix<value_type> sh2amp = DWI::compute_SH2amp_mapping (dirs, true, 8);
bool normalise = get_options ("normalise").size();
if (normalise && !bzeros.size())
throw Exception ("the normalise option is only available if the input data contains b=0 images.");
header.dim (3) = sh2amp.columns();
header.datatype() = DataType::Float32;
Image::Stride::set_from_command_line (header);
Image::Buffer<value_type> SH_data (argument[1], header);
auto amp_vox = amp_data.voxel();
auto SH_vox = SH_data.voxel();
Amp2SHCommon common (sh2amp, bzeros, dwis, normalise);
opt = get_options ("rician");
if (opt.size()) {
Image::BufferPreload<value_type> noise_data (opt[0][0]);
Image::BufferPreload<value_type>::voxel_type noise_vox (noise_data);
Image::ThreadedLoop ("mapping amplitudes to SH coefficients...", amp_vox, 0, 3)
.run (Amp2SH (common), SH_vox, amp_vox, noise_vox);
}
else {
Image::ThreadedLoop ("mapping amplitudes to SH coefficients...", amp_vox, 0, 3)
.run (Amp2SH (common), SH_vox, amp_vox);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 <stdlib.h>
#include "CppUTest/TestHarness.h"
#undef malloc
#undef free
#undef calloc
#undef realloc
#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#include <stdarg.h>
#include <setjmp.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <unistd.h>
#ifndef __MINGW32__
#include <sys/wait.h>
#endif
#include <pthread.h>
#include "CppUTest/PlatformSpecificFunctions.h"
static jmp_buf test_exit_jmp_buf[10];
static int jmp_buf_index = 0;
#ifdef __MINGW32__
static void GccNoPThreadPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result)
{
result->addFailure(TestFailure(shell, "-p doesn't work on MinGW as it is lacking fork.\b"));
}
void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) =
GccNoPThreadPlatformSpecificRunTestInASeperateProcess;
#else
static void GccCygwinPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result)
{
pid_t cpid, w;
int status;
cpid = PlatformSpecificFork();
if (cpid == -1) {
result->addFailure(TestFailure(shell, "Call to fork() failed"));
return;
}
if (cpid == 0) { /* Code executed by child */
shell->runOneTestInCurrentProcess(plugin, *result); // LCOV_EXCL_LINE
_exit(result->getFailureCount()); // LCOV_EXCL_LINE
} else { /* Code executed by parent */
do {
w = PlatformSpecificWaitPid(cpid, &status, WUNTRACED);
if (w == -1) {
result->addFailure(TestFailure(shell, "Call to waitpid() failed"));
return;
}
if (WIFEXITED(status) && WEXITSTATUS(status) > result->getFailureCount()) {
result->addFailure(TestFailure(shell, "Failed in separate process"));
} else if (WIFSIGNALED(status)) {
SimpleString signal(StringFrom(WTERMSIG(status)));
{
SimpleString message("Failed in separate process - killed by signal ");
message += signal;
result->addFailure(TestFailure(shell, message));
}
} else if (WIFSTOPPED(status)) {
result->addFailure(TestFailure(shell, "Stopped in separate process"));
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
}
void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) =
GccCygwinPlatformSpecificRunTestInASeperateProcess;
#endif
pid_t PlatformSpecificForkImplementation(void)
{
return fork();
}
int (*PlatformSpecificFork)(void) = PlatformSpecificForkImplementation;
int PlatformSpecificWaitPidImplementation(int pid, int* status, int options)
{
return waitpid(pid, status, options);
}
int (*PlatformSpecificWaitPid)(int, int*, int) = PlatformSpecificWaitPidImplementation;
TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()
{
return TestOutput::eclipse;
}
extern "C" {
int PlatformSpecificSetJmp(void (*function) (void* data), void* data)
{
if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {
jmp_buf_index++;
function(data);
jmp_buf_index--;
return 1;
}
return 0;
}
/*
* MacOSX clang 3.0 doesn't seem to recognize longjmp and thus complains about __no_return_.
* The later clang compilers complain when it isn't there. So only way is to check the clang compiler here :(
*/
#if !((__clang_major__ == 3) && (__clang_minor__ == 0))
__no_return__
#endif
void PlatformSpecificLongJmp()
{
jmp_buf_index--;
longjmp(test_exit_jmp_buf[jmp_buf_index], 1);
}
void PlatformSpecificRestoreJumpBuffer()
{
jmp_buf_index--;
}
///////////// Time in millis
static long TimeInMillisImplementation()
{
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001);
}
long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation;
static const char* TimeStringImplementation()
{
time_t tm = time(NULL);
static char dateTime[80];
struct tm *tmp = localtime(&tm);
strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", tmp);
return dateTime;
}
const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation;
/* Wish we could add an attribute to the format for discovering mis-use... but the __attribute__(format) seems to not work on va_list */
#ifdef __clang__
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif
int PlatformSpecificVSNprintf(char *str, size_t size, const char* format, va_list args)
{
return vsnprintf( str, size, format, args);
}
PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag)
{
return fopen(filename, flag);
}
void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file)
{
fputs(str, (FILE*)file);
}
void PlatformSpecificFClose(PlatformSpecificFile file)
{
fclose((FILE*)file);
}
void PlatformSpecificFlush()
{
fflush(stdout);
}
int PlatformSpecificPutchar(int c)
{
return putchar(c);
}
void* PlatformSpecificMalloc(size_t size)
{
return malloc(size);
}
void* PlatformSpecificRealloc (void* memory, size_t size)
{
return realloc(memory, size);
}
void PlatformSpecificFree(void* memory)
{
free(memory);
}
void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size)
{
return memcpy(s1, s2, size);
}
void* PlatformSpecificMemset(void* mem, int c, size_t size)
{
return memset(mem, c, size);
}
double PlatformSpecificFabs(double d)
{
return fabs(d);
}
static int IsNanImplementation(double d)
{
return isnan((float)d);
}
int (*PlatformSpecificIsNan)(double) = IsNanImplementation;
static PlatformSpecificMutex PThreadMutexCreate(void)
{
pthread_mutex_t *mutex = new pthread_mutex_t;
pthread_mutex_init(mutex, NULL);
return (PlatformSpecificMutex)mutex;
}
static void PThreadMutexLock(PlatformSpecificMutex mtx)
{
pthread_mutex_lock((pthread_mutex_t *)mtx);
}
static void PThreadMutexUnlock(PlatformSpecificMutex mtx)
{
pthread_mutex_unlock((pthread_mutex_t *)mtx);
}
static void PThreadMutexDestroy(PlatformSpecificMutex mtx)
{
pthread_mutex_t *mutex = (pthread_mutex_t *)mtx;
pthread_mutex_destroy(mutex);
delete mutex;
}
PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = PThreadMutexCreate;
void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = PThreadMutexLock;
void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = PThreadMutexUnlock;
void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = PThreadMutexDestroy;
}
<commit_msg>Not again....<commit_after>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 <stdlib.h>
#include "CppUTest/TestHarness.h"
#undef malloc
#undef free
#undef calloc
#undef realloc
#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#include <stdarg.h>
#include <setjmp.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <unistd.h>
#ifndef __MINGW32__
#include <sys/wait.h>
#endif
#include <pthread.h>
#include "CppUTest/PlatformSpecificFunctions.h"
static jmp_buf test_exit_jmp_buf[10];
static int jmp_buf_index = 0;
#ifdef __MINGW32__
static void GccNoPThreadPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result)
{
result->addFailure(TestFailure(shell, "-p doesn't work on MinGW as it is lacking fork.\b"));
}
void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) =
GccNoPThreadPlatformSpecificRunTestInASeperateProcess;
#else
static void GccCygwinPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result)
{
pid_t cpid, w;
int status;
cpid = PlatformSpecificFork();
if (cpid == -1) {
result->addFailure(TestFailure(shell, "Call to fork() failed"));
return;
}
if (cpid == 0) { /* Code executed by child */
shell->runOneTestInCurrentProcess(plugin, *result); // LCOV_EXCL_LINE
_exit(result->getFailureCount()); // LCOV_EXCL_LINE
} else { /* Code executed by parent */
do {
w = PlatformSpecificWaitPid(cpid, &status, WUNTRACED);
if (w == -1) {
result->addFailure(TestFailure(shell, "Call to waitpid() failed"));
return;
}
if (WIFEXITED(status) && WEXITSTATUS(status) > result->getFailureCount()) {
result->addFailure(TestFailure(shell, "Failed in separate process"));
} else if (WIFSIGNALED(status)) {
SimpleString signal(StringFrom(WTERMSIG(status)));
{
SimpleString message("Failed in separate process - killed by signal ");
message += signal;
result->addFailure(TestFailure(shell, message));
}
} else if (WIFSTOPPED(status)) {
result->addFailure(TestFailure(shell, "Stopped in separate process"));
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
}
void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) =
GccCygwinPlatformSpecificRunTestInASeperateProcess;
#endif
static pid_t PlatformSpecificForkImplementation(void)
{
return fork();
}
int (*PlatformSpecificFork)(void) = PlatformSpecificForkImplementation;
static int PlatformSpecificWaitPidImplementation(int pid, int* status, int options)
{
return waitpid(pid, status, options);
}
int (*PlatformSpecificWaitPid)(int, int*, int) = PlatformSpecificWaitPidImplementation;
TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()
{
return TestOutput::eclipse;
}
extern "C" {
int PlatformSpecificSetJmp(void (*function) (void* data), void* data)
{
if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {
jmp_buf_index++;
function(data);
jmp_buf_index--;
return 1;
}
return 0;
}
/*
* MacOSX clang 3.0 doesn't seem to recognize longjmp and thus complains about __no_return_.
* The later clang compilers complain when it isn't there. So only way is to check the clang compiler here :(
*/
#if !((__clang_major__ == 3) && (__clang_minor__ == 0))
__no_return__
#endif
void PlatformSpecificLongJmp()
{
jmp_buf_index--;
longjmp(test_exit_jmp_buf[jmp_buf_index], 1);
}
void PlatformSpecificRestoreJumpBuffer()
{
jmp_buf_index--;
}
///////////// Time in millis
static long TimeInMillisImplementation()
{
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001);
}
long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation;
static const char* TimeStringImplementation()
{
time_t tm = time(NULL);
static char dateTime[80];
struct tm *tmp = localtime(&tm);
strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", tmp);
return dateTime;
}
const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation;
/* Wish we could add an attribute to the format for discovering mis-use... but the __attribute__(format) seems to not work on va_list */
#ifdef __clang__
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif
int PlatformSpecificVSNprintf(char *str, size_t size, const char* format, va_list args)
{
return vsnprintf( str, size, format, args);
}
PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag)
{
return fopen(filename, flag);
}
void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file)
{
fputs(str, (FILE*)file);
}
void PlatformSpecificFClose(PlatformSpecificFile file)
{
fclose((FILE*)file);
}
void PlatformSpecificFlush()
{
fflush(stdout);
}
int PlatformSpecificPutchar(int c)
{
return putchar(c);
}
void* PlatformSpecificMalloc(size_t size)
{
return malloc(size);
}
void* PlatformSpecificRealloc (void* memory, size_t size)
{
return realloc(memory, size);
}
void PlatformSpecificFree(void* memory)
{
free(memory);
}
void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size)
{
return memcpy(s1, s2, size);
}
void* PlatformSpecificMemset(void* mem, int c, size_t size)
{
return memset(mem, c, size);
}
double PlatformSpecificFabs(double d)
{
return fabs(d);
}
static int IsNanImplementation(double d)
{
return isnan((float)d);
}
int (*PlatformSpecificIsNan)(double) = IsNanImplementation;
static PlatformSpecificMutex PThreadMutexCreate(void)
{
pthread_mutex_t *mutex = new pthread_mutex_t;
pthread_mutex_init(mutex, NULL);
return (PlatformSpecificMutex)mutex;
}
static void PThreadMutexLock(PlatformSpecificMutex mtx)
{
pthread_mutex_lock((pthread_mutex_t *)mtx);
}
static void PThreadMutexUnlock(PlatformSpecificMutex mtx)
{
pthread_mutex_unlock((pthread_mutex_t *)mtx);
}
static void PThreadMutexDestroy(PlatformSpecificMutex mtx)
{
pthread_mutex_t *mutex = (pthread_mutex_t *)mtx;
pthread_mutex_destroy(mutex);
delete mutex;
}
PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = PThreadMutexCreate;
void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = PThreadMutexLock;
void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = PThreadMutexUnlock;
void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = PThreadMutexDestroy;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: componentdefn.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 04:13:55 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONFIGMGR_BACKEND_SYSTEMINTEGRATIONMANAGER_HXX_
#include "systemintegrationmanager.hxx"
#endif //CONFIGMGR_BACKEND_SYSTEMINTEGRATIONMANAGER_HXX_
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif // _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
using namespace configmgr::backend ;
//==============================================================================
static uno::Reference<uno::XInterface> SAL_CALL createSystemIntegrationManager(
const uno::Reference<uno::XComponentContext>& aContext) {
return * new SystemIntegrationManager(aContext) ;
}
//==============================================================================
//------------------------------------------------------------------------------
static const cppu::ImplementationEntry kImplementations_entries[] =
{
{
createSystemIntegrationManager,
SystemIntegrationManager::getSystemIntegrationManagerName,
SystemIntegrationManager::getServiceNames,
cppu::createSingleComponentFactory,
NULL,
0
},
{ NULL }
} ;
//------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **aEnvTypeName,
uno_Environment **aEnvironment) {
*aEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}
//------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(void *aServiceManager,
void *aRegistryKey) {
return cppu::component_writeInfoHelper(aServiceManager,
aRegistryKey,
kImplementations_entries) ;
}
//------------------------------------------------------------------------------
extern "C" void *component_getFactory(const sal_Char *aImplementationName,
void *aServiceManager,
void *aRegistryKey) {
return cppu::component_getFactoryHelper(aImplementationName,
aServiceManager,
aRegistryKey,
kImplementations_entries) ;
}
//------------------------------------------------------------------------------<commit_msg>INTEGRATION: CWS warnings01 (1.2.94); FILE MERGED 2006/02/14 10:17:37 cd 1.2.94.5: #i55991# Fix warnings for ms c++ compiler 2005/11/09 18:02:41 pl 1.2.94.4: #i53898# removed warnings 2005/11/01 12:47:28 cd 1.2.94.3: #i53898# Warning free code for sun solaris compiler 2005/09/22 17:26:49 sb 1.2.94.2: RESYNC: (1.2-1.3); FILE MERGED 2005/09/06 12:27:44 cd 1.2.94.1: #i53898# Make code warning free<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: componentdefn.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-19 23:28:18 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONFIGMGR_BACKEND_SYSTEMINTEGRATIONMANAGER_HXX_
#include "systemintegrationmanager.hxx"
#endif //CONFIGMGR_BACKEND_SYSTEMINTEGRATIONMANAGER_HXX_
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif // _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
using namespace configmgr::backend ;
//==============================================================================
static uno::Reference<uno::XInterface> SAL_CALL createSystemIntegrationManager(
const uno::Reference<uno::XComponentContext>& aContext) {
return * new SystemIntegrationManager(aContext) ;
}
//==============================================================================
//------------------------------------------------------------------------------
static const cppu::ImplementationEntry kImplementations_entries[] =
{
{
createSystemIntegrationManager,
SystemIntegrationManager::getSystemIntegrationManagerName,
SystemIntegrationManager::getServiceNames,
cppu::createSingleComponentFactory,
NULL,
0
},
{ NULL, NULL, NULL, NULL, NULL, 0 }
} ;
//------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **ppEnvTypeName,
uno_Environment ** /* ppEnv */
)
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(void *aServiceManager,
void *aRegistryKey) {
return cppu::component_writeInfoHelper(aServiceManager,
aRegistryKey,
kImplementations_entries) ;
}
//------------------------------------------------------------------------------
extern "C" void *component_getFactory(const sal_Char *aImplementationName,
void *aServiceManager,
void *aRegistryKey) {
return cppu::component_getFactoryHelper(aImplementationName,
aServiceManager,
aRegistryKey,
kImplementations_entries) ;
}
//------------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 2008 Thomas Thrainer <tom_t@gmx.at>
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 "kotododelegates.h"
#include "koprefs.h"
#include <kcolorscheme.h>
#include <kdebug.h>
#include <QApplication>
#include <QSlider>
#include <QComboBox>
#include <QPainter>
#include <QPen>
#include <QBrush>
#include <QColor>
#include <QStyle>
#include <QStyleOptionViewItem>
#include <QStyleOptionProgressBar>
#include <QSize>
// ---------------- COMPLETION DELEGATE --------------------------
// ---------------------------------------------------------------
KOTodoCompleteDelegate::KOTodoCompleteDelegate( QObject *parent )
: QItemDelegate( parent )
{
}
KOTodoCompleteDelegate::~KOTodoCompleteDelegate()
{
}
void KOTodoCompleteDelegate::paint( QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
QRect rect = option.rect;
if ( option.state & QStyle::State_Selected ) {
painter->fillRect( rect, option.palette.highlight() );
} else {
painter->fillRect( rect, option.palette.base() );
}
rect.adjust( 4, 3, -6, -3 );
QStyle *style = QApplication::style();
QStyleOptionProgressBar pbOption;
pbOption.palette = option.palette;
pbOption.state = option.state;
pbOption.direction = option.direction;
pbOption.fontMetrics = option.fontMetrics;
pbOption.rect = rect;
pbOption.maximum = 100;
pbOption.minimum = 0;
pbOption.progress = index.data().toInt();
pbOption.text = index.data().toString() + QString::fromAscii( "%" );
pbOption.textAlignment = Qt::AlignCenter;
pbOption.textVisible = true;
style->drawControl( QStyle::CE_ProgressBar, &pbOption, painter );
}
QSize KOTodoCompleteDelegate::sizeHint( const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
return QSize( 80, 20 );
}
QWidget *KOTodoCompleteDelegate::createEditor( QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
QSlider *slider = new QSlider( parent );
slider->setRange( 0, 100 );
slider->setOrientation( Qt::Horizontal );
QPalette palette = slider->palette();
palette.setColor( QPalette::Base, palette.highlight().color() );
slider->setPalette( palette );
slider->setAutoFillBackground( true );
return slider;
}
void KOTodoCompleteDelegate::setEditorData( QWidget *editor,
const QModelIndex &index ) const
{
QSlider *slider = static_cast<QSlider *>( editor );
slider->setValue( index.data( Qt::EditRole ).toInt() );
}
void KOTodoCompleteDelegate::setModelData( QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index ) const
{
QSlider *slider = static_cast<QSlider *>( editor );
model->setData( index, slider->value() );
}
void KOTodoCompleteDelegate::updateEditorGeometry( QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
editor->setGeometry( option.rect );
}
// ---------------- PRIORITY DELEGATE ----------------------------
// ---------------------------------------------------------------
KOTodoPriorityDelegate::KOTodoPriorityDelegate( QObject *parent )
: QItemDelegate( parent )
{
}
KOTodoPriorityDelegate::~KOTodoPriorityDelegate()
{
}
void KOTodoPriorityDelegate::paint( QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
//TODO paint different priorities differently
QItemDelegate::paint( painter, option, index );
}
QSize KOTodoPriorityDelegate::sizeHint( const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
return QItemDelegate::sizeHint( option, index );
}
QWidget *KOTodoPriorityDelegate::createEditor( QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
//TODO use a KComboBox???????????
QComboBox *combo = new QComboBox( parent );
combo->addItem( i18nc( "@action:inmenu Unspecified priority", "unspecified" ) );
combo->addItem( i18nc( "@action:inmenu highest priority", "1 (highest)" ) );
combo->addItem( i18nc( "@action:inmenu", "2" ) );
combo->addItem( i18nc( "@action:inmenu", "3" ) );
combo->addItem( i18nc( "@action:inmenu", "4" ) );
combo->addItem( i18nc( "@action:inmenu medium priority", "5 (medium)" ) );
combo->addItem( i18nc( "@action:inmenu", "6" ) );
combo->addItem( i18nc( "@action:inmenu", "7" ) );
combo->addItem( i18nc( "@action:inmenu", "8" ) );
combo->addItem( i18nc( "@action:inmenu lowest priority", "9 (lowest)" ) );
return combo;
}
void KOTodoPriorityDelegate::setEditorData( QWidget *editor,
const QModelIndex &index ) const
{
QComboBox *combo = static_cast<QComboBox *>( editor );
combo->setCurrentIndex( index.data( Qt::EditRole ).toInt() );
}
void KOTodoPriorityDelegate::setModelData( QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index ) const
{
QComboBox *combo = static_cast<QComboBox *>( editor );
model->setData( index, combo->currentIndex() );
}
void KOTodoPriorityDelegate::updateEditorGeometry( QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
editor->setGeometry( option.rect );
}
#include "kotododelegates.moc"
<commit_msg>yes, use a KComboBox instead of a QComboBox<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 2008 Thomas Thrainer <tom_t@gmx.at>
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 "kotododelegates.h"
#include "koprefs.h"
#include <kcolorscheme.h>
#include <kcombobox.h>
#include <kdebug.h>
#include <QApplication>
#include <QSlider>
#include <QPainter>
#include <QPen>
#include <QBrush>
#include <QColor>
#include <QStyle>
#include <QStyleOptionViewItem>
#include <QStyleOptionProgressBar>
#include <QSize>
// ---------------- COMPLETION DELEGATE --------------------------
// ---------------------------------------------------------------
KOTodoCompleteDelegate::KOTodoCompleteDelegate( QObject *parent )
: QItemDelegate( parent )
{
}
KOTodoCompleteDelegate::~KOTodoCompleteDelegate()
{
}
void KOTodoCompleteDelegate::paint( QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
QRect rect = option.rect;
if ( option.state & QStyle::State_Selected ) {
painter->fillRect( rect, option.palette.highlight() );
} else {
painter->fillRect( rect, option.palette.base() );
}
rect.adjust( 4, 3, -6, -3 );
QStyle *style = QApplication::style();
QStyleOptionProgressBar pbOption;
pbOption.palette = option.palette;
pbOption.state = option.state;
pbOption.direction = option.direction;
pbOption.fontMetrics = option.fontMetrics;
pbOption.rect = rect;
pbOption.maximum = 100;
pbOption.minimum = 0;
pbOption.progress = index.data().toInt();
pbOption.text = index.data().toString() + QString::fromAscii( "%" );
pbOption.textAlignment = Qt::AlignCenter;
pbOption.textVisible = true;
style->drawControl( QStyle::CE_ProgressBar, &pbOption, painter );
}
QSize KOTodoCompleteDelegate::sizeHint( const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
return QSize( 80, 20 );
}
QWidget *KOTodoCompleteDelegate::createEditor( QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
QSlider *slider = new QSlider( parent );
slider->setRange( 0, 100 );
slider->setOrientation( Qt::Horizontal );
QPalette palette = slider->palette();
palette.setColor( QPalette::Base, palette.highlight().color() );
slider->setPalette( palette );
slider->setAutoFillBackground( true );
return slider;
}
void KOTodoCompleteDelegate::setEditorData( QWidget *editor,
const QModelIndex &index ) const
{
QSlider *slider = static_cast<QSlider *>( editor );
slider->setValue( index.data( Qt::EditRole ).toInt() );
}
void KOTodoCompleteDelegate::setModelData( QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index ) const
{
QSlider *slider = static_cast<QSlider *>( editor );
model->setData( index, slider->value() );
}
void KOTodoCompleteDelegate::updateEditorGeometry( QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
editor->setGeometry( option.rect );
}
// ---------------- PRIORITY DELEGATE ----------------------------
// ---------------------------------------------------------------
KOTodoPriorityDelegate::KOTodoPriorityDelegate( QObject *parent )
: QItemDelegate( parent )
{
}
KOTodoPriorityDelegate::~KOTodoPriorityDelegate()
{
}
void KOTodoPriorityDelegate::paint( QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
//TODO paint different priorities differently
QItemDelegate::paint( painter, option, index );
}
QSize KOTodoPriorityDelegate::sizeHint( const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
return QItemDelegate::sizeHint( option, index );
}
QWidget *KOTodoPriorityDelegate::createEditor( QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
KComboBox *combo = new KComboBox( parent );
combo->addItem( i18nc( "@action:inmenu Unspecified priority", "unspecified" ) );
combo->addItem( i18nc( "@action:inmenu highest priority", "1 (highest)" ) );
combo->addItem( i18nc( "@action:inmenu", "2" ) );
combo->addItem( i18nc( "@action:inmenu", "3" ) );
combo->addItem( i18nc( "@action:inmenu", "4" ) );
combo->addItem( i18nc( "@action:inmenu medium priority", "5 (medium)" ) );
combo->addItem( i18nc( "@action:inmenu", "6" ) );
combo->addItem( i18nc( "@action:inmenu", "7" ) );
combo->addItem( i18nc( "@action:inmenu", "8" ) );
combo->addItem( i18nc( "@action:inmenu lowest priority", "9 (lowest)" ) );
return combo;
}
void KOTodoPriorityDelegate::setEditorData( QWidget *editor,
const QModelIndex &index ) const
{
KComboBox *combo = static_cast<KComboBox *>( editor );
combo->setCurrentIndex( index.data( Qt::EditRole ).toInt() );
}
void KOTodoPriorityDelegate::setModelData( QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index ) const
{
KComboBox *combo = static_cast<KComboBox *>( editor );
model->setData( index, combo->currentIndex() );
}
void KOTodoPriorityDelegate::updateEditorGeometry( QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
editor->setGeometry( option.rect );
}
#include "kotododelegates.moc"
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief ファイル書き込みクラス@n
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdio>
#include <cstring>
#include "main.hpp"
#include "common/format.hpp"
// #define WRITE_FILE_DEBUG
namespace seeda {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief write_file class
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class write_file {
#ifdef WRITE_FILE_DEBUG
typedef utils::format debug_format;
#else
typedef utils::null_format debug_format;
#endif
/// uint32_t limit_;
uint32_t count_;
char path_[128];
bool enable_;
bool state_;
bool req_close_;
FILE *fp_;
uint32_t ch_loop_;
enum class task : uint8_t {
wait_request,
make_filename,
make_dir_path,
open_file,
write_header,
make_data,
write_body,
next_data,
next_file,
};
task task_;
bool last_channel_;
uint8_t second_;
char filename_[256];
char data_[512];
uint32_t data_len_;
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
write_file() : count_(0), path_{ "00000" },
enable_(false), state_(false), req_close_(false),
fp_(nullptr),
ch_loop_(0),
task_(task::wait_request), last_channel_(false), second_(0) { }
//-----------------------------------------------------------------//
/*!
@brief 書き込み許可
*/
//-----------------------------------------------------------------//
void enable(bool ena = true) {
enable_ = ena;
count_ = 0;
}
//-----------------------------------------------------------------//
/*!
@brief 書き込み許可取得
@return 書き込み許可
*/
//-----------------------------------------------------------------//
bool get_enable() const { return enable_; }
//-----------------------------------------------------------------//
/*!
@brief 書き込みパス設定
@param[in] path ファイルパス
*/
//-----------------------------------------------------------------//
void set_path(const char* path)
{
if(path == nullptr) return;
if(path[0] == '/') ++path;
utils::sformat("/%s", path_, sizeof(path_)) % path;
}
//-----------------------------------------------------------------//
/*!
@brief 書き込みパス取得
@param[in] path ファイルパス
*/
//-----------------------------------------------------------------//
const char* get_path() const { return path_; }
#if 0
//-----------------------------------------------------------------//
/*!
@brief 書き込み回数の設定
@param[in] limit 書き込み回数
*/
//-----------------------------------------------------------------//
void set_limit(uint32_t limit)
{
limit_ = limit;
}
//-----------------------------------------------------------------//
/*!
@brief 書き込み時間設定
@return 書き込み時間(秒)
*/
//-----------------------------------------------------------------//
uint32_t get_limit() const { return limit_; }
#endif
//-----------------------------------------------------------------//
/*!
@brief 経過時間の取得
@return 経過時間
*/
//-----------------------------------------------------------------//
uint32_t get_resume() const { return count_; }
//-----------------------------------------------------------------//
/*!
@brief サービス
@param[in] cycle サービス・サイクル(通常100Hz)
*/
//-----------------------------------------------------------------//
void service(uint32_t cycle)
{
bool back = state_;
state_ = enable_;
if(back && !state_ && fp_ != nullptr) {
req_close_ = true;
}
switch(task_) {
case task::wait_request: // 書き込みトリガー検出
if(enable_ && !back) {
task_ = task::make_filename;
reset_wf_fifo();
}
break;
case task::make_filename:
if(get_wf_fifo().length() > 0) {
time_t t = get_wf_fifo().get_at().time_;
struct tm *m = localtime(&t);
utils::sformat("%s_%04d%02d%02d%02d%02d.csv", filename_, sizeof(filename_))
% path_
% static_cast<uint32_t>(m->tm_year + 1900)
% static_cast<uint32_t>(m->tm_mon + 1)
% static_cast<uint32_t>(m->tm_mday)
% static_cast<uint32_t>(m->tm_hour)
% static_cast<uint32_t>(m->tm_min);
last_channel_ = false;
second_ = 0;
task_ = task::make_dir_path;
}
break;
case task::make_dir_path:
at_sdc().build_dir_path(filename_);
task_ = task::open_file;
break;
case task::open_file:
fp_ = fopen(filename_, "wb");
if(fp_ == nullptr) { // error then disable write.
char tmp[64];
utils::sformat("File open error: '%s'", tmp, sizeof(tmp)) % filename_;
at_logs().add(get_time(), "WOP");
debug_format("%s\n") % tmp;
set_restart_delay(60 * 1);
enable_ = false;
task_ = task::wait_request;
} else {
/// at_logs().add(get_time(), "WOP"); // for log test
debug_format("Start write file: '%s'\n") % filename_;
task_ = task::write_header;
}
break;
case task::write_header:
{
char data[1024];
utils::sformat("DATE,TIME", data, sizeof(data));
for(uint32_t i = 0; i < get_channel_num(); ++i) {
utils::sformat(",CH,MAX,MIN,AVE,MEDIAN,COUNTUP", data, sizeof(data), true);
}
utils::sformat("\n", data, sizeof(data), true);
uint32_t sz = utils::sformat::chaout().size();
if(fwrite(data, 1, sz, fp_) != sz) {
char tmp[64];
utils::sformat("File write error (header): '%s'", tmp, sizeof(tmp))
% filename_;
at_logs().add(get_time(), "WR");
debug_format("%s\n") % tmp;
set_restart_delay(60 * 1);
enable_ = false;
task_ = task::wait_request;
break;
}
task_ = task::make_data;
ch_loop_ = 0;
}
break;
case task::make_data:
if(get_wf_fifo().length() > 0) {
time_t t = get_wf_fifo().get_at().time_;
if(ch_loop_ == 0) {
struct tm *m = localtime(&t);
utils::sformat("%04d/%02d/%02d,%02d:%02d:%02d,", data_, sizeof(data_))
% static_cast<uint32_t>(m->tm_year + 1900)
% static_cast<uint32_t>(m->tm_mon + 1)
% static_cast<uint32_t>(m->tm_mday)
% static_cast<uint32_t>(m->tm_hour)
% static_cast<uint32_t>(m->tm_min)
% static_cast<uint32_t>(m->tm_sec);
second_ = m->tm_sec;
} else {
utils::sformat(",", data_, sizeof(data_));
}
const sample_t& smp = get_wf_fifo().get_at().smp_[ch_loop_];
smp.make_csv2(data_, sizeof(data_), true);
++ch_loop_;
if(ch_loop_ >= get_channel_num()) {
utils::sformat("\n", data_, sizeof(data_), true);
ch_loop_ = 0;
last_channel_ = true;
} else {
last_channel_ = false;
}
data_len_ = utils::sformat::chaout().size();
task_ = task::write_body;
}
break;
case task::write_body:
if(get_wf_fifo().length() > 0) {
if(fwrite(data_, 1, data_len_, fp_) != data_len_) {
char tmp[64];
utils::sformat("File write error (body): '%s'", tmp, sizeof(tmp))
% filename_;
at_logs().add(get_time(), "WR");
debug_format("%s\n") % tmp;
set_restart_delay(60 * 1);
enable_ = false;
task_ = task::wait_request;
break;
}
if(last_channel_) {
at_wf_fifo().get_go();
// 書き込みがキャンセルされた場合。
if(req_close_) {
req_close_ = false;
debug_format("Write file aborted\n");
fclose(fp_);
fp_ = nullptr;
task_ = task::wait_request;
break;
}
if(second_ == 59) { // change file.
task_ = task::next_file;
} else {
task_ = task::make_data;
}
} else {
task_ = task::make_data;
}
}
break;
case task::next_file:
fclose(fp_);
fp_ = nullptr;
++count_;
/// 書き込み数制限を廃止
/// if(count_ >= limit_) {
/// debug_format("Fin write file: %d files\n")
/// % count_;
/// enable_ = false;
/// task_ = task::wait_request;
/// } else {
task_ = task::make_filename;
/// }
break;
default:
break;
}
}
};
}
<commit_msg>update: initial path<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief ファイル書き込みクラス@n
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdio>
#include <cstring>
#include "main.hpp"
#include "common/format.hpp"
// #define WRITE_FILE_DEBUG
namespace seeda {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief write_file class
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class write_file {
#ifdef WRITE_FILE_DEBUG
typedef utils::format debug_format;
#else
typedef utils::null_format debug_format;
#endif
/// uint32_t limit_;
uint32_t count_;
char path_[128];
bool enable_;
bool state_;
bool req_close_;
FILE *fp_;
uint32_t ch_loop_;
enum class task : uint8_t {
wait_request,
make_filename,
make_dir_path,
open_file,
write_header,
make_data,
write_body,
next_data,
next_file,
};
task task_;
bool last_channel_;
uint8_t second_;
char filename_[256];
char data_[512];
uint32_t data_len_;
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
write_file() : count_(0), path_{ "/00000" },
enable_(false), state_(false), req_close_(false),
fp_(nullptr),
ch_loop_(0),
task_(task::wait_request), last_channel_(false), second_(0) { }
//-----------------------------------------------------------------//
/*!
@brief 書き込み許可
*/
//-----------------------------------------------------------------//
void enable(bool ena = true) {
enable_ = ena;
count_ = 0;
}
//-----------------------------------------------------------------//
/*!
@brief 書き込み許可取得
@return 書き込み許可
*/
//-----------------------------------------------------------------//
bool get_enable() const { return enable_; }
//-----------------------------------------------------------------//
/*!
@brief 書き込みパス設定
@param[in] path ファイルパス
*/
//-----------------------------------------------------------------//
void set_path(const char* path)
{
if(path == nullptr) return;
if(path[0] == '/') ++path;
utils::sformat("/%s", path_, sizeof(path_)) % path;
}
//-----------------------------------------------------------------//
/*!
@brief 書き込みパス取得
@param[in] path ファイルパス
*/
//-----------------------------------------------------------------//
const char* get_path() const { return path_; }
#if 0
//-----------------------------------------------------------------//
/*!
@brief 書き込み回数の設定
@param[in] limit 書き込み回数
*/
//-----------------------------------------------------------------//
void set_limit(uint32_t limit)
{
limit_ = limit;
}
//-----------------------------------------------------------------//
/*!
@brief 書き込み時間設定
@return 書き込み時間(秒)
*/
//-----------------------------------------------------------------//
uint32_t get_limit() const { return limit_; }
#endif
//-----------------------------------------------------------------//
/*!
@brief 経過時間の取得
@return 経過時間
*/
//-----------------------------------------------------------------//
uint32_t get_resume() const { return count_; }
//-----------------------------------------------------------------//
/*!
@brief サービス
@param[in] cycle サービス・サイクル(通常100Hz)
*/
//-----------------------------------------------------------------//
void service(uint32_t cycle)
{
bool back = state_;
state_ = enable_;
if(back && !state_ && fp_ != nullptr) {
req_close_ = true;
}
switch(task_) {
case task::wait_request: // 書き込みトリガー検出
if(enable_ && !back) {
task_ = task::make_filename;
reset_wf_fifo();
}
break;
case task::make_filename:
if(get_wf_fifo().length() > 0) {
time_t t = get_wf_fifo().get_at().time_;
struct tm *m = localtime(&t);
utils::sformat("%s_%04d%02d%02d%02d%02d.csv", filename_, sizeof(filename_))
% path_
% static_cast<uint32_t>(m->tm_year + 1900)
% static_cast<uint32_t>(m->tm_mon + 1)
% static_cast<uint32_t>(m->tm_mday)
% static_cast<uint32_t>(m->tm_hour)
% static_cast<uint32_t>(m->tm_min);
last_channel_ = false;
second_ = 0;
task_ = task::make_dir_path;
}
break;
case task::make_dir_path:
at_sdc().build_dir_path(filename_);
task_ = task::open_file;
break;
case task::open_file:
fp_ = fopen(filename_, "wb");
if(fp_ == nullptr) { // error then disable write.
char tmp[64];
utils::sformat("File open error: '%s'", tmp, sizeof(tmp)) % filename_;
at_logs().add(get_time(), "WOP");
debug_format("%s\n") % tmp;
set_restart_delay(60 * 1);
enable_ = false;
task_ = task::wait_request;
} else {
/// at_logs().add(get_time(), "WOP"); // for log test
debug_format("Start write file: '%s'\n") % filename_;
task_ = task::write_header;
}
break;
case task::write_header:
{
char data[1024];
utils::sformat("DATE,TIME", data, sizeof(data));
for(uint32_t i = 0; i < get_channel_num(); ++i) {
utils::sformat(",CH,MAX,MIN,AVE,MEDIAN,COUNTUP", data, sizeof(data), true);
}
utils::sformat("\n", data, sizeof(data), true);
uint32_t sz = utils::sformat::chaout().size();
if(fwrite(data, 1, sz, fp_) != sz) {
char tmp[64];
utils::sformat("File write error (header): '%s'", tmp, sizeof(tmp))
% filename_;
at_logs().add(get_time(), "WR");
debug_format("%s\n") % tmp;
set_restart_delay(60 * 1);
enable_ = false;
task_ = task::wait_request;
break;
}
task_ = task::make_data;
ch_loop_ = 0;
}
break;
case task::make_data:
if(get_wf_fifo().length() > 0) {
time_t t = get_wf_fifo().get_at().time_;
if(ch_loop_ == 0) {
struct tm *m = localtime(&t);
utils::sformat("%04d/%02d/%02d,%02d:%02d:%02d,", data_, sizeof(data_))
% static_cast<uint32_t>(m->tm_year + 1900)
% static_cast<uint32_t>(m->tm_mon + 1)
% static_cast<uint32_t>(m->tm_mday)
% static_cast<uint32_t>(m->tm_hour)
% static_cast<uint32_t>(m->tm_min)
% static_cast<uint32_t>(m->tm_sec);
second_ = m->tm_sec;
} else {
utils::sformat(",", data_, sizeof(data_));
}
const sample_t& smp = get_wf_fifo().get_at().smp_[ch_loop_];
smp.make_csv2(data_, sizeof(data_), true);
++ch_loop_;
if(ch_loop_ >= get_channel_num()) {
utils::sformat("\n", data_, sizeof(data_), true);
ch_loop_ = 0;
last_channel_ = true;
} else {
last_channel_ = false;
}
data_len_ = utils::sformat::chaout().size();
task_ = task::write_body;
}
break;
case task::write_body:
if(get_wf_fifo().length() > 0) {
if(fwrite(data_, 1, data_len_, fp_) != data_len_) {
char tmp[64];
utils::sformat("File write error (body): '%s'", tmp, sizeof(tmp))
% filename_;
at_logs().add(get_time(), "WR");
debug_format("%s\n") % tmp;
set_restart_delay(60 * 1);
enable_ = false;
task_ = task::wait_request;
break;
}
if(last_channel_) {
at_wf_fifo().get_go();
// 書き込みがキャンセルされた場合。
if(req_close_) {
req_close_ = false;
debug_format("Write file aborted\n");
fclose(fp_);
fp_ = nullptr;
task_ = task::wait_request;
break;
}
if(second_ == 59) { // change file.
task_ = task::next_file;
} else {
task_ = task::make_data;
}
} else {
task_ = task::make_data;
}
}
break;
case task::next_file:
fclose(fp_);
fp_ = nullptr;
++count_;
/// 書き込み数制限を廃止
/// if(count_ >= limit_) {
/// debug_format("Fin write file: %d files\n")
/// % count_;
/// enable_ = false;
/// task_ = task::wait_request;
/// } else {
task_ = task::make_filename;
/// }
break;
default:
break;
}
}
};
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2004-2006 MySQL AB
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; version 2 of the License.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#if defined(__GNUC__) && defined(USE_PRAGMA_IMPLEMENTATION)
#pragma implementation
#endif
#include "thread_registry.h"
#include <thr_alarm.h>
#include <signal.h>
#include "log.h"
#ifndef __WIN__
/* Kick-off signal handler */
enum { THREAD_KICK_OFF_SIGNAL= SIGUSR2 };
extern "C" void handle_signal(int);
void handle_signal(int __attribute__((unused)) sig_no)
{
}
#endif
/* Thread_info initializer methods */
void Thread_info::init(bool send_signal_on_shutdown_arg)
{
thread_id= pthread_self();
send_signal_on_shutdown= send_signal_on_shutdown_arg;
}
/*
TODO: think about moving signal information (now it's shutdown_in_progress)
to Thread_info. It will reduce contention and allow signal deliverence to
a particular thread, not to the whole worker crew
*/
Thread_registry::Thread_registry() :
shutdown_in_progress(FALSE)
,sigwait_thread_pid(pthread_self())
,error_status(FALSE)
{
pthread_mutex_init(&LOCK_thread_registry, 0);
pthread_cond_init(&COND_thread_registry_is_empty, 0);
/* head is used by-value to simplify nodes inserting */
head.next= head.prev= &head;
}
Thread_registry::~Thread_registry()
{
/* Check that no one uses the repository. */
pthread_mutex_lock(&LOCK_thread_registry);
for (Thread_info *ti= head.next; ti != &head; ti= ti->next)
{
log_error("Thread_registry: unregistered thread: %lu.",
(unsigned long) ti->thread_id);
}
/* All threads must unregister */
DBUG_ASSERT(head.next == &head);
pthread_mutex_unlock(&LOCK_thread_registry);
pthread_cond_destroy(&COND_thread_registry_is_empty);
pthread_mutex_destroy(&LOCK_thread_registry);
}
/*
Set signal handler for kick-off thread, and insert a thread info to the
repository. New node is appended to the end of the list; head.prev always
points to the last node.
*/
void Thread_registry::register_thread(Thread_info *info,
bool send_signal_on_shutdown)
{
info->init(send_signal_on_shutdown);
DBUG_PRINT("info", ("Thread_registry: registering thread %lu...",
(unsigned long) info->thread_id));
#ifndef __WIN__
struct sigaction sa;
sa.sa_handler= handle_signal;
sa.sa_flags= 0;
sigemptyset(&sa.sa_mask);
sigaction(THREAD_KICK_OFF_SIGNAL, &sa, 0);
#endif
info->current_cond= 0;
pthread_mutex_lock(&LOCK_thread_registry);
info->next= &head;
info->prev= head.prev;
head.prev->next= info;
head.prev= info;
pthread_mutex_unlock(&LOCK_thread_registry);
}
/*
Unregister a thread from the repository and free Thread_info structure.
Every registered thread must unregister. Unregistering should be the last
thing a thread is doing, otherwise it could have no time to finalize.
*/
void Thread_registry::unregister_thread(Thread_info *info)
{
DBUG_PRINT("info", ("Thread_registry: unregistering thread %lu...",
(unsigned long) info->thread_id));
pthread_mutex_lock(&LOCK_thread_registry);
info->prev->next= info->next;
info->next->prev= info->prev;
if (head.next == &head)
{
DBUG_PRINT("info", ("Thread_registry: thread registry is empty!"));
pthread_cond_signal(&COND_thread_registry_is_empty);
}
pthread_mutex_unlock(&LOCK_thread_registry);
}
/*
Check whether shutdown is in progress, and if yes, return immediately.
Else set info->current_cond and call pthread_cond_wait. When
pthread_cond_wait returns, unregister current cond and check the shutdown
status again.
RETURN VALUE
return value from pthread_cond_wait
*/
int Thread_registry::cond_wait(Thread_info *info, pthread_cond_t *cond,
pthread_mutex_t *mutex)
{
pthread_mutex_lock(&LOCK_thread_registry);
if (shutdown_in_progress)
{
pthread_mutex_unlock(&LOCK_thread_registry);
return 0;
}
info->current_cond= cond;
pthread_mutex_unlock(&LOCK_thread_registry);
/* sic: race condition here, cond can be signaled in deliver_shutdown */
int rc= pthread_cond_wait(cond, mutex);
pthread_mutex_lock(&LOCK_thread_registry);
info->current_cond= 0;
pthread_mutex_unlock(&LOCK_thread_registry);
return rc;
}
int Thread_registry::cond_timedwait(Thread_info *info, pthread_cond_t *cond,
pthread_mutex_t *mutex,
struct timespec *wait_time)
{
int rc;
pthread_mutex_lock(&LOCK_thread_registry);
if (shutdown_in_progress)
{
pthread_mutex_unlock(&LOCK_thread_registry);
return 0;
}
info->current_cond= cond;
pthread_mutex_unlock(&LOCK_thread_registry);
/* sic: race condition here, cond can be signaled in deliver_shutdown */
if ((rc= pthread_cond_timedwait(cond, mutex, wait_time)) == ETIME)
rc= ETIMEDOUT; // For easier usage
pthread_mutex_lock(&LOCK_thread_registry);
info->current_cond= 0;
pthread_mutex_unlock(&LOCK_thread_registry);
return rc;
}
/*
Deliver shutdown message to the workers crew.
As it's impossible to avoid all race conditions, signal latecomers
again.
*/
void Thread_registry::deliver_shutdown()
{
pthread_mutex_lock(&LOCK_thread_registry);
shutdown_in_progress= TRUE;
#ifndef __WIN__
/* to stop reading from the network we need to flush alarm queue */
end_thr_alarm(0);
/*
We have to deliver final alarms this way, as the main thread has already
stopped alarm processing.
*/
process_alarm(THR_SERVER_ALARM);
#endif
/*
sic: race condition here, the thread may not yet fall into
pthread_cond_wait.
*/
interrupt_threads();
wait_for_threads_to_unregister();
/*
If previous signals did not reach some threads, they must be sleeping
in pthread_cond_wait or in a blocking syscall. Wake them up:
every thread shall check signal variables after each syscall/cond_wait,
so this time everybody should be informed (presumably each worker can
get CPU during shutdown_time.)
*/
interrupt_threads();
/* Get the last chance to threads to stop. */
wait_for_threads_to_unregister();
#ifndef DBUG_OFF
/*
Print out threads, that didn't stopped. Thread_registry destructor will
probably abort the program if there is still any alive thread.
*/
if (head.next != &head)
{
DBUG_PRINT("info", ("Thread_registry: non-stopped threads:"));
for (Thread_info *info= head.next; info != &head; info= info->next)
DBUG_PRINT("info", (" - %lu", (unsigned long) info->thread_id));
}
else
{
DBUG_PRINT("info", ("Thread_registry: all threads stopped."));
}
#endif // DBUG_OFF
pthread_mutex_unlock(&LOCK_thread_registry);
}
void Thread_registry::request_shutdown()
{
pthread_kill(sigwait_thread_pid, SIGTERM);
}
void Thread_registry::interrupt_threads()
{
for (Thread_info *info= head.next; info != &head; info= info->next)
{
if (!info->send_signal_on_shutdown)
continue;
pthread_kill(info->thread_id, THREAD_KICK_OFF_SIGNAL);
if (info->current_cond)
pthread_cond_signal(info->current_cond);
}
}
void Thread_registry::wait_for_threads_to_unregister()
{
struct timespec shutdown_time;
set_timespec(shutdown_time, 1);
DBUG_PRINT("info", ("Thread_registry: joining threads..."));
while (true)
{
if (head.next == &head)
{
DBUG_PRINT("info", ("Thread_registry: emptied."));
return;
}
int error= pthread_cond_timedwait(&COND_thread_registry_is_empty,
&LOCK_thread_registry,
&shutdown_time);
if (error == ETIMEDOUT || error == ETIME)
{
DBUG_PRINT("info", ("Thread_registry: threads shutdown timed out."));
return;
}
}
}
/*********************************************************************
class Thread
*********************************************************************/
#if defined(__ia64__) || defined(__ia64)
/*
We can live with 32K, but reserve 64K. Just to be safe.
On ia64 we need to reserve double of the size.
*/
#define IM_THREAD_STACK_SIZE (128*1024L)
#else
#define IM_THREAD_STACK_SIZE (64*1024)
#endif
/*
Change the stack size and start a thread. Return an error if either
pthread_attr_setstacksize or pthread_create fails.
Arguments are the same as for pthread_create().
*/
static
int set_stacksize_and_create_thread(pthread_t *thread, pthread_attr_t *attr,
void *(*start_routine)(void *), void *arg)
{
int rc= 0;
#ifndef __WIN__
#ifndef PTHREAD_STACK_MIN
#define PTHREAD_STACK_MIN 32768
#endif
/*
Set stack size to be safe on the platforms with too small
default thread stack.
*/
rc= pthread_attr_setstacksize(attr,
(size_t) (PTHREAD_STACK_MIN +
IM_THREAD_STACK_SIZE));
#endif
if (!rc)
rc= pthread_create(thread, attr, start_routine, arg);
return rc;
}
Thread::~Thread()
{
}
void *Thread::thread_func(void *arg)
{
Thread *thread= (Thread *) arg;
my_thread_init();
thread->run();
my_thread_end();
return NULL;
}
bool Thread::start(enum_thread_type thread_type)
{
pthread_attr_t attr;
int rc;
pthread_attr_init(&attr);
if (thread_type == DETACHED)
{
detached = TRUE;
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
}
else
{
detached = FALSE;
}
rc= set_stacksize_and_create_thread(&id, &attr, Thread::thread_func, this);
pthread_attr_destroy(&attr);
return rc != 0;
}
bool Thread::join()
{
DBUG_ASSERT(!detached);
return pthread_join(id, NULL) != 0;
}
int Thread_registry::get_error_status()
{
int ret_error_status;
pthread_mutex_lock(&LOCK_thread_registry);
ret_error_status= error_status;
pthread_mutex_unlock(&LOCK_thread_registry);
return ret_error_status;
}
void Thread_registry::set_error_status()
{
pthread_mutex_lock(&LOCK_thread_registry);
error_status= TRUE;
pthread_mutex_unlock(&LOCK_thread_registry);
}
<commit_msg>fix compilation failure<commit_after>/* Copyright (C) 2004-2006 MySQL AB
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; version 2 of the License.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#if defined(__GNUC__) && defined(USE_PRAGMA_IMPLEMENTATION)
#pragma implementation
#endif
#include "thread_registry.h"
#include <thr_alarm.h>
#include <signal.h>
#include "log.h"
#include <my_sys.h>
#ifndef __WIN__
/* Kick-off signal handler */
enum { THREAD_KICK_OFF_SIGNAL= SIGUSR2 };
extern "C" void handle_signal(int);
void handle_signal(int __attribute__((unused)) sig_no)
{
}
#endif
/* Thread_info initializer methods */
void Thread_info::init(bool send_signal_on_shutdown_arg)
{
thread_id= pthread_self();
send_signal_on_shutdown= send_signal_on_shutdown_arg;
}
/*
TODO: think about moving signal information (now it's shutdown_in_progress)
to Thread_info. It will reduce contention and allow signal deliverence to
a particular thread, not to the whole worker crew
*/
Thread_registry::Thread_registry() :
shutdown_in_progress(FALSE)
,sigwait_thread_pid(pthread_self())
,error_status(FALSE)
{
pthread_mutex_init(&LOCK_thread_registry, 0);
pthread_cond_init(&COND_thread_registry_is_empty, 0);
/* head is used by-value to simplify nodes inserting */
head.next= head.prev= &head;
}
Thread_registry::~Thread_registry()
{
/* Check that no one uses the repository. */
pthread_mutex_lock(&LOCK_thread_registry);
for (Thread_info *ti= head.next; ti != &head; ti= ti->next)
{
log_error("Thread_registry: unregistered thread: %lu.",
(unsigned long) ti->thread_id);
}
/* All threads must unregister */
DBUG_ASSERT(head.next == &head);
pthread_mutex_unlock(&LOCK_thread_registry);
pthread_cond_destroy(&COND_thread_registry_is_empty);
pthread_mutex_destroy(&LOCK_thread_registry);
}
/*
Set signal handler for kick-off thread, and insert a thread info to the
repository. New node is appended to the end of the list; head.prev always
points to the last node.
*/
void Thread_registry::register_thread(Thread_info *info,
bool send_signal_on_shutdown)
{
info->init(send_signal_on_shutdown);
DBUG_PRINT("info", ("Thread_registry: registering thread %lu...",
(unsigned long) info->thread_id));
#ifndef __WIN__
struct sigaction sa;
sa.sa_handler= handle_signal;
sa.sa_flags= 0;
sigemptyset(&sa.sa_mask);
sigaction(THREAD_KICK_OFF_SIGNAL, &sa, 0);
#endif
info->current_cond= 0;
pthread_mutex_lock(&LOCK_thread_registry);
info->next= &head;
info->prev= head.prev;
head.prev->next= info;
head.prev= info;
pthread_mutex_unlock(&LOCK_thread_registry);
}
/*
Unregister a thread from the repository and free Thread_info structure.
Every registered thread must unregister. Unregistering should be the last
thing a thread is doing, otherwise it could have no time to finalize.
*/
void Thread_registry::unregister_thread(Thread_info *info)
{
DBUG_PRINT("info", ("Thread_registry: unregistering thread %lu...",
(unsigned long) info->thread_id));
pthread_mutex_lock(&LOCK_thread_registry);
info->prev->next= info->next;
info->next->prev= info->prev;
if (head.next == &head)
{
DBUG_PRINT("info", ("Thread_registry: thread registry is empty!"));
pthread_cond_signal(&COND_thread_registry_is_empty);
}
pthread_mutex_unlock(&LOCK_thread_registry);
}
/*
Check whether shutdown is in progress, and if yes, return immediately.
Else set info->current_cond and call pthread_cond_wait. When
pthread_cond_wait returns, unregister current cond and check the shutdown
status again.
RETURN VALUE
return value from pthread_cond_wait
*/
int Thread_registry::cond_wait(Thread_info *info, pthread_cond_t *cond,
pthread_mutex_t *mutex)
{
pthread_mutex_lock(&LOCK_thread_registry);
if (shutdown_in_progress)
{
pthread_mutex_unlock(&LOCK_thread_registry);
return 0;
}
info->current_cond= cond;
pthread_mutex_unlock(&LOCK_thread_registry);
/* sic: race condition here, cond can be signaled in deliver_shutdown */
int rc= pthread_cond_wait(cond, mutex);
pthread_mutex_lock(&LOCK_thread_registry);
info->current_cond= 0;
pthread_mutex_unlock(&LOCK_thread_registry);
return rc;
}
int Thread_registry::cond_timedwait(Thread_info *info, pthread_cond_t *cond,
pthread_mutex_t *mutex,
struct timespec *wait_time)
{
int rc;
pthread_mutex_lock(&LOCK_thread_registry);
if (shutdown_in_progress)
{
pthread_mutex_unlock(&LOCK_thread_registry);
return 0;
}
info->current_cond= cond;
pthread_mutex_unlock(&LOCK_thread_registry);
/* sic: race condition here, cond can be signaled in deliver_shutdown */
if ((rc= pthread_cond_timedwait(cond, mutex, wait_time)) == ETIME)
rc= ETIMEDOUT; // For easier usage
pthread_mutex_lock(&LOCK_thread_registry);
info->current_cond= 0;
pthread_mutex_unlock(&LOCK_thread_registry);
return rc;
}
/*
Deliver shutdown message to the workers crew.
As it's impossible to avoid all race conditions, signal latecomers
again.
*/
void Thread_registry::deliver_shutdown()
{
pthread_mutex_lock(&LOCK_thread_registry);
shutdown_in_progress= TRUE;
#ifndef __WIN__
/* to stop reading from the network we need to flush alarm queue */
end_thr_alarm(0);
/*
We have to deliver final alarms this way, as the main thread has already
stopped alarm processing.
*/
process_alarm(THR_SERVER_ALARM);
#endif
/*
sic: race condition here, the thread may not yet fall into
pthread_cond_wait.
*/
interrupt_threads();
wait_for_threads_to_unregister();
/*
If previous signals did not reach some threads, they must be sleeping
in pthread_cond_wait or in a blocking syscall. Wake them up:
every thread shall check signal variables after each syscall/cond_wait,
so this time everybody should be informed (presumably each worker can
get CPU during shutdown_time.)
*/
interrupt_threads();
/* Get the last chance to threads to stop. */
wait_for_threads_to_unregister();
#ifndef DBUG_OFF
/*
Print out threads, that didn't stopped. Thread_registry destructor will
probably abort the program if there is still any alive thread.
*/
if (head.next != &head)
{
DBUG_PRINT("info", ("Thread_registry: non-stopped threads:"));
for (Thread_info *info= head.next; info != &head; info= info->next)
DBUG_PRINT("info", (" - %lu", (unsigned long) info->thread_id));
}
else
{
DBUG_PRINT("info", ("Thread_registry: all threads stopped."));
}
#endif // DBUG_OFF
pthread_mutex_unlock(&LOCK_thread_registry);
}
void Thread_registry::request_shutdown()
{
pthread_kill(sigwait_thread_pid, SIGTERM);
}
void Thread_registry::interrupt_threads()
{
for (Thread_info *info= head.next; info != &head; info= info->next)
{
if (!info->send_signal_on_shutdown)
continue;
pthread_kill(info->thread_id, THREAD_KICK_OFF_SIGNAL);
if (info->current_cond)
pthread_cond_signal(info->current_cond);
}
}
void Thread_registry::wait_for_threads_to_unregister()
{
struct timespec shutdown_time;
set_timespec(shutdown_time, 1);
DBUG_PRINT("info", ("Thread_registry: joining threads..."));
while (true)
{
if (head.next == &head)
{
DBUG_PRINT("info", ("Thread_registry: emptied."));
return;
}
int error= pthread_cond_timedwait(&COND_thread_registry_is_empty,
&LOCK_thread_registry,
&shutdown_time);
if (error == ETIMEDOUT || error == ETIME)
{
DBUG_PRINT("info", ("Thread_registry: threads shutdown timed out."));
return;
}
}
}
/*********************************************************************
class Thread
*********************************************************************/
#if defined(__ia64__) || defined(__ia64)
/*
We can live with 32K, but reserve 64K. Just to be safe.
On ia64 we need to reserve double of the size.
*/
#define IM_THREAD_STACK_SIZE (128*1024L)
#else
#define IM_THREAD_STACK_SIZE (64*1024)
#endif
/*
Change the stack size and start a thread. Return an error if either
pthread_attr_setstacksize or pthread_create fails.
Arguments are the same as for pthread_create().
*/
static
int set_stacksize_and_create_thread(pthread_t *thread, pthread_attr_t *attr,
void *(*start_routine)(void *), void *arg)
{
int rc= 0;
#ifndef __WIN__
#ifndef PTHREAD_STACK_MIN
#define PTHREAD_STACK_MIN 32768
#endif
/*
Set stack size to be safe on the platforms with too small
default thread stack.
*/
rc= pthread_attr_setstacksize(attr,
(size_t) (PTHREAD_STACK_MIN +
IM_THREAD_STACK_SIZE));
#endif
if (!rc)
rc= pthread_create(thread, attr, start_routine, arg);
return rc;
}
Thread::~Thread()
{
}
void *Thread::thread_func(void *arg)
{
Thread *thread= (Thread *) arg;
my_thread_init();
thread->run();
my_thread_end();
return NULL;
}
bool Thread::start(enum_thread_type thread_type)
{
pthread_attr_t attr;
int rc;
pthread_attr_init(&attr);
if (thread_type == DETACHED)
{
detached = TRUE;
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
}
else
{
detached = FALSE;
}
rc= set_stacksize_and_create_thread(&id, &attr, Thread::thread_func, this);
pthread_attr_destroy(&attr);
return rc != 0;
}
bool Thread::join()
{
DBUG_ASSERT(!detached);
return pthread_join(id, NULL) != 0;
}
int Thread_registry::get_error_status()
{
int ret_error_status;
pthread_mutex_lock(&LOCK_thread_registry);
ret_error_status= error_status;
pthread_mutex_unlock(&LOCK_thread_registry);
return ret_error_status;
}
void Thread_registry::set_error_status()
{
pthread_mutex_lock(&LOCK_thread_registry);
error_status= TRUE;
pthread_mutex_unlock(&LOCK_thread_registry);
}
<|endoftext|> |
<commit_before>//=- ClangSACheckersEmitter.cpp - Generate Clang SA checkers tables -*- C++ -*-
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend emits Clang Static Analyzer checkers tables.
//
//===----------------------------------------------------------------------===//
#include "ClangSACheckersEmitter.h"
#include "Record.h"
#include "llvm/ADT/DenseSet.h"
#include <map>
#include <string>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Static Analyzer Checkers Tables generation
//===----------------------------------------------------------------------===//
/// \brief True if it is specified hidden or a parent package is specified
/// as hidden, otherwise false.
static bool isHidden(const Record &R) {
if (R.getValueAsBit("Hidden"))
return true;
// Not declared as hidden, check the parent package if it is hidden.
if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("ParentPackage")))
return isHidden(*DI->getDef());
return false;
}
static bool isCheckerNamed(const Record *R) {
return !R->getValueAsString("CheckerName").empty();
}
static std::string getPackageFullName(const Record *R);
static std::string getParentPackageFullName(const Record *R) {
std::string name;
if (DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("ParentPackage")))
name = getPackageFullName(DI->getDef());
return name;
}
static std::string getPackageFullName(const Record *R) {
std::string name = getParentPackageFullName(R);
if (!name.empty()) name += ".";
return name + R->getValueAsString("PackageName");
}
static std::string getCheckerFullName(const Record *R) {
std::string name = getParentPackageFullName(R);
if (isCheckerNamed(R)) {
if (!name.empty()) name += ".";
name += R->getValueAsString("CheckerName");
}
return name;
}
static std::string getStringValue(const Record &R, StringRef field) {
if (StringInit *
SI = dynamic_cast<StringInit*>(R.getValueInit(field)))
return SI->getValue();
return std::string();
}
namespace {
struct GroupInfo {
llvm::DenseSet<const Record*> Checkers;
llvm::DenseSet<const Record *> SubGroups;
bool Hidden;
unsigned Index;
GroupInfo() : Hidden(false) { }
};
}
static void addPackageToCheckerGroup(const Record *package, const Record *group,
llvm::DenseMap<const Record *, GroupInfo *> &recordGroupMap) {
llvm::DenseSet<const Record *> &checkers = recordGroupMap[package]->Checkers;
for (llvm::DenseSet<const Record *>::iterator
I = checkers.begin(), E = checkers.end(); I != E; ++I)
recordGroupMap[group]->Checkers.insert(*I);
llvm::DenseSet<const Record *> &subGroups = recordGroupMap[package]->SubGroups;
for (llvm::DenseSet<const Record *>::iterator
I = subGroups.begin(), E = subGroups.end(); I != E; ++I)
addPackageToCheckerGroup(*I, group, recordGroupMap);
}
void ClangSACheckersEmitter::run(raw_ostream &OS) {
std::vector<Record*> checkers = Records.getAllDerivedDefinitions("Checker");
llvm::DenseMap<const Record *, unsigned> checkerRecIndexMap;
for (unsigned i = 0, e = checkers.size(); i != e; ++i)
checkerRecIndexMap[checkers[i]] = i;
OS << "\n#ifdef GET_CHECKERS\n";
for (unsigned i = 0, e = checkers.size(); i != e; ++i) {
const Record &R = *checkers[i];
OS << "CHECKER(" << "\"";
std::string name;
if (isCheckerNamed(&R))
name = getCheckerFullName(&R);
OS.write_escaped(name) << "\", ";
OS << R.getName() << ", ";
OS << getStringValue(R, "DescFile") << ", ";
OS << "\"";
OS.write_escaped(getStringValue(R, "HelpText")) << "\", ";
// Hidden bit
if (isHidden(R))
OS << "true";
else
OS << "false";
OS << ")\n";
}
OS << "#endif // GET_CHECKERS\n\n";
// Invert the mapping of checkers to package/group into a one to many
// mapping of packages/groups to checkers.
std::map<std::string, GroupInfo> groupInfoByName;
llvm::DenseMap<const Record *, GroupInfo *> recordGroupMap;
std::vector<Record*> packages = Records.getAllDerivedDefinitions("Package");
for (unsigned i = 0, e = packages.size(); i != e; ++i) {
Record *R = packages[i];
std::string fullName = getPackageFullName(R);
if (!fullName.empty()) {
GroupInfo &info = groupInfoByName[fullName];
info.Hidden = isHidden(*R);
recordGroupMap[R] = &info;
}
}
std::vector<Record*>
checkerGroups = Records.getAllDerivedDefinitions("CheckerGroup");
for (unsigned i = 0, e = checkerGroups.size(); i != e; ++i) {
Record *R = checkerGroups[i];
std::string name = R->getValueAsString("GroupName");
if (!name.empty()) {
GroupInfo &info = groupInfoByName[name];
recordGroupMap[R] = &info;
}
}
typedef std::map<std::string, const Record *> SortedRecords;
OS << "\n#ifdef GET_PACKAGES\n";
{
SortedRecords sortedPackages;
for (unsigned i = 0, e = packages.size(); i != e; ++i)
sortedPackages[getPackageFullName(packages[i])] = packages[i];
for (SortedRecords::iterator
I = sortedPackages.begin(), E = sortedPackages.end(); I != E; ++I) {
const Record &R = *I->second;
OS << "PACKAGE(" << "\"";
OS.write_escaped(getPackageFullName(&R)) << "\", ";
// Hidden bit
if (isHidden(R))
OS << "true";
else
OS << "false";
OS << ")\n";
}
}
OS << "#endif // GET_PACKAGES\n\n";
OS << "\n#ifdef GET_GROUPS\n";
{
SortedRecords sortedGroups;
for (unsigned i = 0, e = checkerGroups.size(); i != e; ++i)
sortedGroups[checkerGroups[i]->getValueAsString("GroupName")]
= checkerGroups[i];
for (SortedRecords::iterator
I = sortedGroups.begin(), E = sortedGroups.end(); I != E; ++I) {
const Record &R = *I->second;
OS << "GROUP(" << "\"";
OS.write_escaped(R.getValueAsString("GroupName")) << "\"";
OS << ")\n";
}
}
OS << "#endif // GET_GROUPS\n\n";
for (unsigned i = 0, e = checkers.size(); i != e; ++i) {
Record *R = checkers[i];
Record *package = 0;
if (DefInit *
DI = dynamic_cast<DefInit*>(R->getValueInit("ParentPackage")))
package = DI->getDef();
if (!isCheckerNamed(R) && !package)
throw "Checker '" + R->getName() + "' is neither named, nor in a package!";
if (isCheckerNamed(R)) {
// Create a pseudo-group to hold this checker.
std::string fullName = getCheckerFullName(R);
GroupInfo &info = groupInfoByName[fullName];
info.Hidden = R->getValueAsBit("Hidden");
recordGroupMap[R] = &info;
info.Checkers.insert(R);
} else {
recordGroupMap[package]->Checkers.insert(R);
}
Record *currR = isCheckerNamed(R) ? R : package;
// Insert the checker and its parent packages into the subgroups set of
// the corresponding parent package.
while (DefInit *DI
= dynamic_cast<DefInit*>(currR->getValueInit("ParentPackage"))) {
Record *parentPackage = DI->getDef();
recordGroupMap[parentPackage]->SubGroups.insert(currR);
currR = parentPackage;
}
// Insert the checker into the set of its group.
if (DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group")))
recordGroupMap[DI->getDef()]->Checkers.insert(R);
}
// If a package is in group, add all its checkers and its sub-packages
// checkers into the group.
for (unsigned i = 0, e = packages.size(); i != e; ++i)
if (DefInit *DI = dynamic_cast<DefInit*>(packages[i]->getValueInit("Group")))
addPackageToCheckerGroup(packages[i], DI->getDef(), recordGroupMap);
unsigned index = 0;
for (std::map<std::string, GroupInfo>::iterator
I = groupInfoByName.begin(), E = groupInfoByName.end(); I != E; ++I)
I->second.Index = index++;
// Walk through the packages/groups/checkers emitting an array for each
// set of checkers and an array for each set of subpackages.
OS << "\n#ifdef GET_MEMBER_ARRAYS\n";
unsigned maxLen = 0;
for (std::map<std::string, GroupInfo>::iterator
I = groupInfoByName.begin(), E = groupInfoByName.end(); I != E; ++I) {
maxLen = std::max(maxLen, (unsigned)I->first.size());
llvm::DenseSet<const Record *> &checkers = I->second.Checkers;
if (!checkers.empty()) {
OS << "static const short CheckerArray" << I->second.Index << "[] = { ";
// Make the output order deterministic.
std::map<int, const Record *> sorted;
for (llvm::DenseSet<const Record *>::iterator
I = checkers.begin(), E = checkers.end(); I != E; ++I)
sorted[(*I)->getID()] = *I;
for (std::map<int, const Record *>::iterator
I = sorted.begin(), E = sorted.end(); I != E; ++I)
OS << checkerRecIndexMap[I->second] << ", ";
OS << "-1 };\n";
}
llvm::DenseSet<const Record *> &subGroups = I->second.SubGroups;
if (!subGroups.empty()) {
OS << "static const short SubPackageArray" << I->second.Index << "[] = { ";
// Make the output order deterministic.
std::map<int, const Record *> sorted;
for (llvm::DenseSet<const Record *>::iterator
I = subGroups.begin(), E = subGroups.end(); I != E; ++I)
sorted[(*I)->getID()] = *I;
for (std::map<int, const Record *>::iterator
I = sorted.begin(), E = sorted.end(); I != E; ++I) {
OS << recordGroupMap[I->second]->Index << ", ";
}
OS << "-1 };\n";
}
}
OS << "#endif // GET_MEMBER_ARRAYS\n\n";
OS << "\n#ifdef GET_CHECKNAME_TABLE\n";
for (std::map<std::string, GroupInfo>::iterator
I = groupInfoByName.begin(), E = groupInfoByName.end(); I != E; ++I) {
// Group option string.
OS << " { \"";
OS.write_escaped(I->first) << "\","
<< std::string(maxLen-I->first.size()+1, ' ');
if (I->second.Checkers.empty())
OS << "0, ";
else
OS << "CheckerArray" << I->second.Index << ", ";
// Subgroups.
if (I->second.SubGroups.empty())
OS << "0, ";
else
OS << "SubPackageArray" << I->second.Index << ", ";
OS << (I->second.Hidden ? "true" : "false");
OS << " },\n";
}
OS << "#endif // GET_CHECKNAME_TABLE\n\n";
}
<commit_msg>ClangSAEmClangSACheckersEmitter, emit info about groups.<commit_after>//=- ClangSACheckersEmitter.cpp - Generate Clang SA checkers tables -*- C++ -*-
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend emits Clang Static Analyzer checkers tables.
//
//===----------------------------------------------------------------------===//
#include "ClangSACheckersEmitter.h"
#include "Record.h"
#include "llvm/ADT/DenseSet.h"
#include <map>
#include <string>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Static Analyzer Checkers Tables generation
//===----------------------------------------------------------------------===//
/// \brief True if it is specified hidden or a parent package is specified
/// as hidden, otherwise false.
static bool isHidden(const Record &R) {
if (R.getValueAsBit("Hidden"))
return true;
// Not declared as hidden, check the parent package if it is hidden.
if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("ParentPackage")))
return isHidden(*DI->getDef());
return false;
}
static bool isCheckerNamed(const Record *R) {
return !R->getValueAsString("CheckerName").empty();
}
static std::string getPackageFullName(const Record *R);
static std::string getParentPackageFullName(const Record *R) {
std::string name;
if (DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("ParentPackage")))
name = getPackageFullName(DI->getDef());
return name;
}
static std::string getPackageFullName(const Record *R) {
std::string name = getParentPackageFullName(R);
if (!name.empty()) name += ".";
return name + R->getValueAsString("PackageName");
}
static std::string getCheckerFullName(const Record *R) {
std::string name = getParentPackageFullName(R);
if (isCheckerNamed(R)) {
if (!name.empty()) name += ".";
name += R->getValueAsString("CheckerName");
}
return name;
}
static std::string getStringValue(const Record &R, StringRef field) {
if (StringInit *
SI = dynamic_cast<StringInit*>(R.getValueInit(field)))
return SI->getValue();
return std::string();
}
namespace {
struct GroupInfo {
llvm::DenseSet<const Record*> Checkers;
llvm::DenseSet<const Record *> SubGroups;
bool Hidden;
unsigned Index;
GroupInfo() : Hidden(false) { }
};
}
static void addPackageToCheckerGroup(const Record *package, const Record *group,
llvm::DenseMap<const Record *, GroupInfo *> &recordGroupMap) {
llvm::DenseSet<const Record *> &checkers = recordGroupMap[package]->Checkers;
for (llvm::DenseSet<const Record *>::iterator
I = checkers.begin(), E = checkers.end(); I != E; ++I)
recordGroupMap[group]->Checkers.insert(*I);
llvm::DenseSet<const Record *> &subGroups = recordGroupMap[package]->SubGroups;
for (llvm::DenseSet<const Record *>::iterator
I = subGroups.begin(), E = subGroups.end(); I != E; ++I)
addPackageToCheckerGroup(*I, group, recordGroupMap);
}
void ClangSACheckersEmitter::run(raw_ostream &OS) {
std::vector<Record*> checkers = Records.getAllDerivedDefinitions("Checker");
llvm::DenseMap<const Record *, unsigned> checkerRecIndexMap;
for (unsigned i = 0, e = checkers.size(); i != e; ++i)
checkerRecIndexMap[checkers[i]] = i;
// Invert the mapping of checkers to package/group into a one to many
// mapping of packages/groups to checkers.
std::map<std::string, GroupInfo> groupInfoByName;
llvm::DenseMap<const Record *, GroupInfo *> recordGroupMap;
std::vector<Record*> packages = Records.getAllDerivedDefinitions("Package");
for (unsigned i = 0, e = packages.size(); i != e; ++i) {
Record *R = packages[i];
std::string fullName = getPackageFullName(R);
if (!fullName.empty()) {
GroupInfo &info = groupInfoByName[fullName];
info.Hidden = isHidden(*R);
recordGroupMap[R] = &info;
}
}
std::vector<Record*>
checkerGroups = Records.getAllDerivedDefinitions("CheckerGroup");
for (unsigned i = 0, e = checkerGroups.size(); i != e; ++i) {
Record *R = checkerGroups[i];
std::string name = R->getValueAsString("GroupName");
if (!name.empty()) {
GroupInfo &info = groupInfoByName[name];
recordGroupMap[R] = &info;
}
}
for (unsigned i = 0, e = checkers.size(); i != e; ++i) {
Record *R = checkers[i];
Record *package = 0;
if (DefInit *
DI = dynamic_cast<DefInit*>(R->getValueInit("ParentPackage")))
package = DI->getDef();
if (!isCheckerNamed(R) && !package)
throw "Checker '" + R->getName() + "' is neither named, nor in a package!";
if (isCheckerNamed(R)) {
// Create a pseudo-group to hold this checker.
std::string fullName = getCheckerFullName(R);
GroupInfo &info = groupInfoByName[fullName];
info.Hidden = R->getValueAsBit("Hidden");
recordGroupMap[R] = &info;
info.Checkers.insert(R);
} else {
recordGroupMap[package]->Checkers.insert(R);
}
Record *currR = isCheckerNamed(R) ? R : package;
// Insert the checker and its parent packages into the subgroups set of
// the corresponding parent package.
while (DefInit *DI
= dynamic_cast<DefInit*>(currR->getValueInit("ParentPackage"))) {
Record *parentPackage = DI->getDef();
recordGroupMap[parentPackage]->SubGroups.insert(currR);
currR = parentPackage;
}
// Insert the checker into the set of its group.
if (DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group")))
recordGroupMap[DI->getDef()]->Checkers.insert(R);
}
// If a package is in group, add all its checkers and its sub-packages
// checkers into the group.
for (unsigned i = 0, e = packages.size(); i != e; ++i)
if (DefInit *DI = dynamic_cast<DefInit*>(packages[i]->getValueInit("Group")))
addPackageToCheckerGroup(packages[i], DI->getDef(), recordGroupMap);
typedef std::map<std::string, const Record *> SortedRecords;
typedef llvm::DenseMap<const Record *, unsigned> RecToSortIndex;
SortedRecords sortedGroups;
RecToSortIndex groupToSortIndex;
OS << "\n#ifdef GET_GROUPS\n";
{
for (unsigned i = 0, e = checkerGroups.size(); i != e; ++i)
sortedGroups[checkerGroups[i]->getValueAsString("GroupName")]
= checkerGroups[i];
unsigned sortIndex = 0;
for (SortedRecords::iterator
I = sortedGroups.begin(), E = sortedGroups.end(); I != E; ++I) {
const Record *R = I->second;
OS << "GROUP(" << "\"";
OS.write_escaped(R->getValueAsString("GroupName")) << "\"";
OS << ")\n";
groupToSortIndex[R] = sortIndex++;
}
}
OS << "#endif // GET_GROUPS\n\n";
OS << "\n#ifdef GET_PACKAGES\n";
{
SortedRecords sortedPackages;
for (unsigned i = 0, e = packages.size(); i != e; ++i)
sortedPackages[getPackageFullName(packages[i])] = packages[i];
for (SortedRecords::iterator
I = sortedPackages.begin(), E = sortedPackages.end(); I != E; ++I) {
const Record &R = *I->second;
OS << "PACKAGE(" << "\"";
OS.write_escaped(getPackageFullName(&R)) << "\", ";
// Group index
if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("Group")))
OS << groupToSortIndex[DI->getDef()] << ", ";
else
OS << "-1, ";
// Hidden bit
if (isHidden(R))
OS << "true";
else
OS << "false";
OS << ")\n";
}
}
OS << "#endif // GET_PACKAGES\n\n";
OS << "\n#ifdef GET_CHECKERS\n";
for (unsigned i = 0, e = checkers.size(); i != e; ++i) {
const Record &R = *checkers[i];
OS << "CHECKER(" << "\"";
std::string name;
if (isCheckerNamed(&R))
name = getCheckerFullName(&R);
OS.write_escaped(name) << "\", ";
OS << R.getName() << ", ";
OS << getStringValue(R, "DescFile") << ", ";
OS << "\"";
OS.write_escaped(getStringValue(R, "HelpText")) << "\", ";
// Group index
if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("Group")))
OS << groupToSortIndex[DI->getDef()] << ", ";
else
OS << "-1, ";
// Hidden bit
if (isHidden(R))
OS << "true";
else
OS << "false";
OS << ")\n";
}
OS << "#endif // GET_CHECKERS\n\n";
unsigned index = 0;
for (std::map<std::string, GroupInfo>::iterator
I = groupInfoByName.begin(), E = groupInfoByName.end(); I != E; ++I)
I->second.Index = index++;
// Walk through the packages/groups/checkers emitting an array for each
// set of checkers and an array for each set of subpackages.
OS << "\n#ifdef GET_MEMBER_ARRAYS\n";
unsigned maxLen = 0;
for (std::map<std::string, GroupInfo>::iterator
I = groupInfoByName.begin(), E = groupInfoByName.end(); I != E; ++I) {
maxLen = std::max(maxLen, (unsigned)I->first.size());
llvm::DenseSet<const Record *> &checkers = I->second.Checkers;
if (!checkers.empty()) {
OS << "static const short CheckerArray" << I->second.Index << "[] = { ";
// Make the output order deterministic.
std::map<int, const Record *> sorted;
for (llvm::DenseSet<const Record *>::iterator
I = checkers.begin(), E = checkers.end(); I != E; ++I)
sorted[(*I)->getID()] = *I;
for (std::map<int, const Record *>::iterator
I = sorted.begin(), E = sorted.end(); I != E; ++I)
OS << checkerRecIndexMap[I->second] << ", ";
OS << "-1 };\n";
}
llvm::DenseSet<const Record *> &subGroups = I->second.SubGroups;
if (!subGroups.empty()) {
OS << "static const short SubPackageArray" << I->second.Index << "[] = { ";
// Make the output order deterministic.
std::map<int, const Record *> sorted;
for (llvm::DenseSet<const Record *>::iterator
I = subGroups.begin(), E = subGroups.end(); I != E; ++I)
sorted[(*I)->getID()] = *I;
for (std::map<int, const Record *>::iterator
I = sorted.begin(), E = sorted.end(); I != E; ++I) {
OS << recordGroupMap[I->second]->Index << ", ";
}
OS << "-1 };\n";
}
}
OS << "#endif // GET_MEMBER_ARRAYS\n\n";
OS << "\n#ifdef GET_CHECKNAME_TABLE\n";
for (std::map<std::string, GroupInfo>::iterator
I = groupInfoByName.begin(), E = groupInfoByName.end(); I != E; ++I) {
// Group option string.
OS << " { \"";
OS.write_escaped(I->first) << "\","
<< std::string(maxLen-I->first.size()+1, ' ');
if (I->second.Checkers.empty())
OS << "0, ";
else
OS << "CheckerArray" << I->second.Index << ", ";
// Subgroups.
if (I->second.SubGroups.empty())
OS << "0, ";
else
OS << "SubPackageArray" << I->second.Index << ", ";
OS << (I->second.Hidden ? "true" : "false");
OS << " },\n";
}
OS << "#endif // GET_CHECKNAME_TABLE\n\n";
}
<|endoftext|> |
<commit_before><commit_msg>The ODG should have office:drawing after office:body, not office:graphics<commit_after><|endoftext|> |
<commit_before>#include <stdint.h>
#include <stdlib.h>
#include <unwind.h>
#include <string.h>
#include <stdio.h>
#include "llvm/Support/Dwarf.h"
#include "RuntimeType.h"
struct ExceptionType
{
RuntimeTypeInfo* runtimeTypeInfo;
struct _Unwind_Exception unwindException;
};
int64_t exceptionBaseFromUnwindOffset = ((uintptr_t) (((ExceptionType*) (NULL)))) - ((uintptr_t) &(((ExceptionType*) (NULL))->unwindException));
/// Read a uleb128 encoded value and advance pointer
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @returns decoded value
static uintptr_t readULEB128(const uint8_t **data) {
uintptr_t result = 0;
uintptr_t shift = 0;
unsigned char byte;
const uint8_t *p = *data;
do {
byte = *p++;
result |= (byte & 0x7f) << shift;
shift += 7;
} while (byte & 0x80);
*data = p;
return result;
}
/// Read a sleb128 encoded value and advance pointer
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @returns decoded value
static uintptr_t readSLEB128(const uint8_t **data) {
uintptr_t result = 0;
uintptr_t shift = 0;
unsigned char byte;
const uint8_t *p = *data;
do {
byte = *p++;
result |= (byte & 0x7f) << shift;
shift += 7;
} while (byte & 0x80);
*data = p;
if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
result |= (~0 << shift);
}
return result;
}
unsigned getEncodingSize(uint8_t Encoding) {
if (Encoding == llvm::dwarf::DW_EH_PE_omit)
return 0;
switch (Encoding & 0x0F) {
case llvm::dwarf::DW_EH_PE_absptr:
return sizeof(uintptr_t);
case llvm::dwarf::DW_EH_PE_udata2:
return sizeof(uint16_t);
case llvm::dwarf::DW_EH_PE_udata4:
return sizeof(uint32_t);
case llvm::dwarf::DW_EH_PE_udata8:
return sizeof(uint64_t);
case llvm::dwarf::DW_EH_PE_sdata2:
return sizeof(int16_t);
case llvm::dwarf::DW_EH_PE_sdata4:
return sizeof(int32_t);
case llvm::dwarf::DW_EH_PE_sdata8:
return sizeof(int64_t);
default:
// not supported
abort();
}
}
/// Read a pointer encoded value and advance pointer
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @param encoding dwarf encoding type
/// @returns decoded value
static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
uintptr_t result = 0;
const uint8_t *p = *data;
if (encoding == llvm::dwarf::DW_EH_PE_omit)
return(result);
// first get value
switch (encoding & 0x0F) {
case llvm::dwarf::DW_EH_PE_absptr:
result = *((uintptr_t*) p);
p += sizeof(uintptr_t);
break;
case llvm::dwarf::DW_EH_PE_uleb128:
result = readULEB128(&p);
break;
// Note: This case has not been tested
case llvm::dwarf::DW_EH_PE_sleb128:
result = readSLEB128(&p);
break;
case llvm::dwarf::DW_EH_PE_udata2:
result = *((uint16_t*) p);
p += sizeof(uint16_t);
break;
case llvm::dwarf::DW_EH_PE_udata4:
result = *((uint32_t*) p);
p += sizeof(uint32_t);
break;
case llvm::dwarf::DW_EH_PE_udata8:
result = *((uint64_t*) p);
p += sizeof(uint64_t);
break;
case llvm::dwarf::DW_EH_PE_sdata2:
result = *((int16_t*) p);
p += sizeof(int16_t);
break;
case llvm::dwarf::DW_EH_PE_sdata4:
result = *((int32_t*) p);
p += sizeof(int32_t);
break;
case llvm::dwarf::DW_EH_PE_sdata8:
result = *((int64_t*) p);
p += sizeof(int64_t);
break;
default:
// not supported
abort();
break;
}
// then add relative offset
switch (encoding & 0x70) {
case llvm::dwarf::DW_EH_PE_absptr:
// do nothing
break;
case llvm::dwarf::DW_EH_PE_pcrel:
result += (uintptr_t) (*data);
break;
case llvm::dwarf::DW_EH_PE_textrel:
case llvm::dwarf::DW_EH_PE_datarel:
case llvm::dwarf::DW_EH_PE_funcrel:
case llvm::dwarf::DW_EH_PE_aligned:
default:
// not supported
abort();
break;
}
// then apply indirection
if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
result = *((uintptr_t*) result);
}
*data = p;
return result;
}
static bool handleActionValue(int64_t *resultAction,
uint8_t TTypeEncoding,
const uint8_t *classInfo,
uintptr_t actionEntry,
uint64_t exceptionClass,
struct _Unwind_Exception *exceptionObject)
{
const uint8_t *actionPos = (uint8_t*)actionEntry;
for (int i = 0; true; ++i)
{
// Each emitted dwarf action corresponds to a 2 tuple of
// type info address offset, and action offset to the next
// emitted action.
int64_t typeOffset = readSLEB128(&actionPos);
const uint8_t* tempActionPos = actionPos;
int64_t actionOffset = readSLEB128(&tempActionPos);
// Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
// argument has been matched.
if (typeOffset > 0)
{
unsigned EncSize = getEncodingSize(TTypeEncoding);
const uint8_t *EntryP = classInfo - typeOffset * EncSize;
uintptr_t P = readEncodedPointer(&EntryP, TTypeEncoding);
// Expected exception type
struct RuntimeTypeInfo* expectedExceptionType = reinterpret_cast<struct RuntimeTypeInfo*>(P);
// Actual exception
struct ExceptionType* exception = (struct ExceptionType*)((char*)exceptionObject + exceptionBaseFromUnwindOffset);
struct RuntimeTypeInfo* exceptionType = exception->runtimeTypeInfo;
// Check if they match (by testing each class in hierarchy)
while (exceptionType != NULL)
{
if (exceptionType == expectedExceptionType)
{
*resultAction = typeOffset;
return true;
}
exceptionType = exceptionType->base;
}
}
if (!actionOffset)
break;
actionPos += actionOffset;
}
// No match
return false;
}
extern "C" _Unwind_Reason_Code sharpPersonality(int version, _Unwind_Action actions, uint64_t exceptionClass, struct _Unwind_Exception* exceptionObject, struct _Unwind_Context* context)
{
const uint8_t *lsda = (const uint8_t*)_Unwind_GetLanguageSpecificData(context);
uintptr_t pc = _Unwind_GetIP(context) - 1;
_Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
// Get beginning current frame's code (as defined by the
// emitted dwarf code)
uintptr_t funcStart = _Unwind_GetRegionStart(context);
uintptr_t pcOffset = pc - funcStart;
const uint8_t *classInfo = NULL;
// Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
// dwarf emission
// Parse LSDA header.
uint8_t lpStartEncoding = *lsda++;
if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
readEncodedPointer(&lsda, lpStartEncoding);
}
uint8_t ttypeEncoding = *lsda++;
uintptr_t classInfoOffset;
if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
// Calculate type info locations in emitted dwarf code which
// were flagged by type info arguments to llvm.eh.selector
// intrinsic
classInfoOffset = readULEB128(&lsda);
classInfo = lsda + classInfoOffset;
}
// Walk call-site table looking for range that
// includes current PC.
uint8_t callSiteEncoding = *lsda++;
uint32_t callSiteTableLength = readULEB128(&lsda);
const uint8_t *callSiteTableStart = lsda;
const uint8_t *callSiteTableEnd = callSiteTableStart +
callSiteTableLength;
const uint8_t *actionTableStart = callSiteTableEnd;
const uint8_t *callSitePtr = callSiteTableStart;
while (callSitePtr < callSiteTableEnd) {
uintptr_t start = readEncodedPointer(&callSitePtr,
callSiteEncoding);
uintptr_t length = readEncodedPointer(&callSitePtr,
callSiteEncoding);
uintptr_t landingPad = readEncodedPointer(&callSitePtr,
callSiteEncoding);
// Note: Action value
uintptr_t actionEntry = readULEB128(&callSitePtr);
//if (exceptionClass != ourBaseExceptionClass) {
// // We have been notified of a foreign exception being thrown,
// // and we therefore need to execute cleanup landing pads
// actionEntry = 0;
//}
if (landingPad == 0) {
continue; // no landing pad for this entry
}
if (actionEntry) {
actionEntry += ((uintptr_t) actionTableStart) - 1;
}
bool exceptionMatched = false;
if ((start <= pcOffset) && (pcOffset < (start + length))) {
int64_t actionValue = 0;
if (actionEntry) {
exceptionMatched = handleActionValue(&actionValue,
ttypeEncoding,
classInfo,
actionEntry,
exceptionClass,
exceptionObject);
}
if (!(actions & _UA_SEARCH_PHASE)) {
// Found landing pad for the PC.
// Set Instruction Pointer to so we re-enter function
// at landing pad. The landing pad is created by the
// compiler to take two parameters in registers.
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(0),
(uintptr_t) exceptionObject);
// Note: this virtual register directly corresponds
// to the return of the llvm.eh.selector intrinsic
if (!actionEntry || !exceptionMatched) {
// We indicate cleanup only
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(1),
0);
}
else {
// Matched type info index of llvm.eh.selector intrinsic
// passed here.
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(1),
actionValue);
}
// To execute landing pad set here
_Unwind_SetIP(context, funcStart + landingPad);
ret = _URC_INSTALL_CONTEXT;
}
else if (exceptionMatched) {
ret = _URC_HANDLER_FOUND;
}
else {
// Note: Only non-clean up handlers are marked as
// found. Otherwise the clean up handlers will be
// re-found and executed during the clean up
// phase.
}
break;
}
}
return(ret);
}
void cleanupException(_Unwind_Reason_Code reason, struct _Unwind_Exception* ex)
{
if (ex != NULL)
{
// TODO: Check exception class
free((char*) ex + exceptionBaseFromUnwindOffset);
}
}
extern "C" void throwException(Object* obj)
{
struct ExceptionType* ex = (struct ExceptionType*)malloc(sizeof(struct ExceptionType));
memset(ex, 0, sizeof(*ex));
ex->runtimeTypeInfo = obj->runtimeTypeInfo;
ex->unwindException.exception_class = 0; // TODO
ex->unwindException.exception_cleanup = cleanupException;
_Unwind_RaiseException(&ex->unwindException);
__builtin_unreachable();
}<commit_msg>[Runtime] Exception: Align ExceptionType and its alloc (to avoid exception). Also add few headers to avoid compilation warnings.<commit_after>#include <cstdint>
#include <cstdlib>
#include <unwind.h>
#include <cstring>
#include <cstdio>
#include "llvm/Support/Dwarf.h"
#include "RuntimeType.h"
struct ExceptionType
{
RuntimeTypeInfo* runtimeTypeInfo;
struct _Unwind_Exception unwindException;
} __attribute__((__aligned__));
int64_t exceptionBaseFromUnwindOffset = ((uintptr_t) (((ExceptionType*) (NULL)))) - ((uintptr_t) &(((ExceptionType*) (NULL))->unwindException));
/// Read a uleb128 encoded value and advance pointer
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @returns decoded value
static uintptr_t readULEB128(const uint8_t **data) {
uintptr_t result = 0;
uintptr_t shift = 0;
unsigned char byte;
const uint8_t *p = *data;
do {
byte = *p++;
result |= (byte & 0x7f) << shift;
shift += 7;
} while (byte & 0x80);
*data = p;
return result;
}
/// Read a sleb128 encoded value and advance pointer
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @returns decoded value
static uintptr_t readSLEB128(const uint8_t **data) {
uintptr_t result = 0;
uintptr_t shift = 0;
unsigned char byte;
const uint8_t *p = *data;
do {
byte = *p++;
result |= (byte & 0x7f) << shift;
shift += 7;
} while (byte & 0x80);
*data = p;
if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
result |= (~0 << shift);
}
return result;
}
unsigned getEncodingSize(uint8_t Encoding) {
if (Encoding == llvm::dwarf::DW_EH_PE_omit)
return 0;
switch (Encoding & 0x0F) {
case llvm::dwarf::DW_EH_PE_absptr:
return sizeof(uintptr_t);
case llvm::dwarf::DW_EH_PE_udata2:
return sizeof(uint16_t);
case llvm::dwarf::DW_EH_PE_udata4:
return sizeof(uint32_t);
case llvm::dwarf::DW_EH_PE_udata8:
return sizeof(uint64_t);
case llvm::dwarf::DW_EH_PE_sdata2:
return sizeof(int16_t);
case llvm::dwarf::DW_EH_PE_sdata4:
return sizeof(int32_t);
case llvm::dwarf::DW_EH_PE_sdata8:
return sizeof(int64_t);
default:
// not supported
abort();
}
}
/// Read a pointer encoded value and advance pointer
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @param encoding dwarf encoding type
/// @returns decoded value
static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
uintptr_t result = 0;
const uint8_t *p = *data;
if (encoding == llvm::dwarf::DW_EH_PE_omit)
return(result);
// first get value
switch (encoding & 0x0F) {
case llvm::dwarf::DW_EH_PE_absptr:
result = *((uintptr_t*) p);
p += sizeof(uintptr_t);
break;
case llvm::dwarf::DW_EH_PE_uleb128:
result = readULEB128(&p);
break;
// Note: This case has not been tested
case llvm::dwarf::DW_EH_PE_sleb128:
result = readSLEB128(&p);
break;
case llvm::dwarf::DW_EH_PE_udata2:
result = *((uint16_t*) p);
p += sizeof(uint16_t);
break;
case llvm::dwarf::DW_EH_PE_udata4:
result = *((uint32_t*) p);
p += sizeof(uint32_t);
break;
case llvm::dwarf::DW_EH_PE_udata8:
result = *((uint64_t*) p);
p += sizeof(uint64_t);
break;
case llvm::dwarf::DW_EH_PE_sdata2:
result = *((int16_t*) p);
p += sizeof(int16_t);
break;
case llvm::dwarf::DW_EH_PE_sdata4:
result = *((int32_t*) p);
p += sizeof(int32_t);
break;
case llvm::dwarf::DW_EH_PE_sdata8:
result = *((int64_t*) p);
p += sizeof(int64_t);
break;
default:
// not supported
abort();
break;
}
// then add relative offset
switch (encoding & 0x70) {
case llvm::dwarf::DW_EH_PE_absptr:
// do nothing
break;
case llvm::dwarf::DW_EH_PE_pcrel:
result += (uintptr_t) (*data);
break;
case llvm::dwarf::DW_EH_PE_textrel:
case llvm::dwarf::DW_EH_PE_datarel:
case llvm::dwarf::DW_EH_PE_funcrel:
case llvm::dwarf::DW_EH_PE_aligned:
default:
// not supported
abort();
break;
}
// then apply indirection
if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
result = *((uintptr_t*) result);
}
*data = p;
return result;
}
static bool handleActionValue(int64_t *resultAction,
uint8_t TTypeEncoding,
const uint8_t *classInfo,
uintptr_t actionEntry,
uint64_t exceptionClass,
struct _Unwind_Exception *exceptionObject)
{
const uint8_t *actionPos = (uint8_t*)actionEntry;
for (int i = 0; true; ++i)
{
// Each emitted dwarf action corresponds to a 2 tuple of
// type info address offset, and action offset to the next
// emitted action.
int64_t typeOffset = readSLEB128(&actionPos);
const uint8_t* tempActionPos = actionPos;
int64_t actionOffset = readSLEB128(&tempActionPos);
// Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
// argument has been matched.
if (typeOffset > 0)
{
unsigned EncSize = getEncodingSize(TTypeEncoding);
const uint8_t *EntryP = classInfo - typeOffset * EncSize;
uintptr_t P = readEncodedPointer(&EntryP, TTypeEncoding);
// Expected exception type
struct RuntimeTypeInfo* expectedExceptionType = reinterpret_cast<struct RuntimeTypeInfo*>(P);
// Actual exception
struct ExceptionType* exception = (struct ExceptionType*)((char*)exceptionObject + exceptionBaseFromUnwindOffset);
struct RuntimeTypeInfo* exceptionType = exception->runtimeTypeInfo;
// Check if they match (by testing each class in hierarchy)
while (exceptionType != NULL)
{
if (exceptionType == expectedExceptionType)
{
*resultAction = typeOffset;
return true;
}
exceptionType = exceptionType->base;
}
}
if (!actionOffset)
break;
actionPos += actionOffset;
}
// No match
return false;
}
extern "C" _Unwind_Reason_Code sharpPersonality(int version, _Unwind_Action actions, uint64_t exceptionClass, struct _Unwind_Exception* exceptionObject, struct _Unwind_Context* context)
{
const uint8_t *lsda = (const uint8_t*)_Unwind_GetLanguageSpecificData(context);
uintptr_t pc = _Unwind_GetIP(context) - 1;
_Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
// Get beginning current frame's code (as defined by the
// emitted dwarf code)
uintptr_t funcStart = _Unwind_GetRegionStart(context);
uintptr_t pcOffset = pc - funcStart;
const uint8_t *classInfo = NULL;
// Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
// dwarf emission
// Parse LSDA header.
uint8_t lpStartEncoding = *lsda++;
if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
readEncodedPointer(&lsda, lpStartEncoding);
}
uint8_t ttypeEncoding = *lsda++;
uintptr_t classInfoOffset;
if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
// Calculate type info locations in emitted dwarf code which
// were flagged by type info arguments to llvm.eh.selector
// intrinsic
classInfoOffset = readULEB128(&lsda);
classInfo = lsda + classInfoOffset;
}
// Walk call-site table looking for range that
// includes current PC.
uint8_t callSiteEncoding = *lsda++;
uint32_t callSiteTableLength = readULEB128(&lsda);
const uint8_t *callSiteTableStart = lsda;
const uint8_t *callSiteTableEnd = callSiteTableStart +
callSiteTableLength;
const uint8_t *actionTableStart = callSiteTableEnd;
const uint8_t *callSitePtr = callSiteTableStart;
while (callSitePtr < callSiteTableEnd) {
uintptr_t start = readEncodedPointer(&callSitePtr,
callSiteEncoding);
uintptr_t length = readEncodedPointer(&callSitePtr,
callSiteEncoding);
uintptr_t landingPad = readEncodedPointer(&callSitePtr,
callSiteEncoding);
// Note: Action value
uintptr_t actionEntry = readULEB128(&callSitePtr);
//if (exceptionClass != ourBaseExceptionClass) {
// // We have been notified of a foreign exception being thrown,
// // and we therefore need to execute cleanup landing pads
// actionEntry = 0;
//}
if (landingPad == 0) {
continue; // no landing pad for this entry
}
if (actionEntry) {
actionEntry += ((uintptr_t) actionTableStart) - 1;
}
bool exceptionMatched = false;
if ((start <= pcOffset) && (pcOffset < (start + length))) {
int64_t actionValue = 0;
if (actionEntry) {
exceptionMatched = handleActionValue(&actionValue,
ttypeEncoding,
classInfo,
actionEntry,
exceptionClass,
exceptionObject);
}
if (!(actions & _UA_SEARCH_PHASE)) {
// Found landing pad for the PC.
// Set Instruction Pointer to so we re-enter function
// at landing pad. The landing pad is created by the
// compiler to take two parameters in registers.
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(0),
(uintptr_t) exceptionObject);
// Note: this virtual register directly corresponds
// to the return of the llvm.eh.selector intrinsic
if (!actionEntry || !exceptionMatched) {
// We indicate cleanup only
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(1),
0);
}
else {
// Matched type info index of llvm.eh.selector intrinsic
// passed here.
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(1),
actionValue);
}
// To execute landing pad set here
_Unwind_SetIP(context, funcStart + landingPad);
ret = _URC_INSTALL_CONTEXT;
}
else if (exceptionMatched) {
ret = _URC_HANDLER_FOUND;
}
else {
// Note: Only non-clean up handlers are marked as
// found. Otherwise the clean up handlers will be
// re-found and executed during the clean up
// phase.
}
break;
}
}
return(ret);
}
void cleanupException(_Unwind_Reason_Code reason, struct _Unwind_Exception* ex)
{
if (ex != NULL)
{
// TODO: Check exception class
free((char*) ex + exceptionBaseFromUnwindOffset);
}
}
extern "C" void throwException(Object* obj)
{
struct ExceptionType* ex = (struct ExceptionType*)_aligned_malloc(sizeof(struct ExceptionType), 16);
memset(ex, 0, sizeof(*ex));
ex->runtimeTypeInfo = obj->runtimeTypeInfo;
ex->unwindException.exception_class = 0; // TODO
ex->unwindException.exception_cleanup = cleanupException;
_Unwind_RaiseException(&ex->unwindException);
__builtin_unreachable();
}<|endoftext|> |
<commit_before>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/core/log/log.hpp>
#include <togo/core/collection/array.hpp>
#include <togo/core/string/string.hpp>
#include <togo/core/io/memory_stream.hpp>
#include <togo/core/io/io.hpp>
#include <quanta/core/object/object.hpp>
#include <togo/support/test.hpp>
#include <cmath>
using namespace quanta;
#define M_TSN(d) {true, false, d, {}},
#define M_TSE(d, e) {true, false, d, e},
#define M_TSS(d) {true, false, d, d},
#define M_TF(d) {false, false, d, {}},
#define S_TSN(d) {true, true, d, {}},
#define S_TSE(d, e) {true, true, d, e},
#define S_TSS(d) {true, true, d, d},
#define S_TF(d) {false, true, d, {}},
#define TSN(d) M_TSN(d) S_TSN(d)
#define TSE(d, e) M_TSE(d, e) S_TSE(d, e)
#define TSS(d) M_TSS(d) S_TSS(d)
#define TF(d) M_TF(d) S_TF(d)
struct Test {
bool success;
bool single_value;
StringRef data;
StringRef expected_output;
} const tests[]{
// whitespace
TSN("")
TSN(" ")
TSN("\n")
TSN(" \t\n")
// comments
TF("\\")
TF("\\*")
TSN("\\\\")
TSN("\\**\\")
TSN("\\*\nblah\n*\\")
M_TSE("x\\\\\ny", "x\ny")
S_TF("x\\\\\ny")
// nested
TF("\\* \\* *\\")
TSN("\\* \\**\\ *\\")
// constants
TSE("null", "null")
TSE("false", "false")
TSE("true", "true")
// identifiers
TSE("a", "a")
TSE("á", "á")
TSE(".á", ".á")
TSE("_", "_")
M_TSE("a\nb", "a\nb")
S_TSE("\n\\**\\a\n", "a")
S_TSE("a\n", "a")
S_TF("a\nb")
// markers
TSE("~", "~")
TSE("~x", "~x")
TSE("~~x", "~~x")
TSE("~~~x", "~~~x")
TSE("^", "^")
TSE("^x", "^x")
TSE("^^x", "^^x")
TSE("^^^x", "^^^x")
TSE("G~~x", "G~~x")
TSE(" G~x", "G~x")
TSE("G~^x", "G~^x")
TSE("?", "?")
TSE("?~x", "?~x")
TSE(" ?x", "?x")
TSE("?^x", "?^x")
// source
TSE("x$0", "x")
TSE("x$0$0", "x")
TSE("x$0$1", "x")
TSE("x$0$?", "x")
TSE("x$1", "x$1")
TSE("x$1$0", "x$1")
TSE("x$1$?", "x$1$?")
TSE("x$1$2", "x$1$2")
TSE("x$?1", "x$?1")
TSE("x$?1$0", "x$?1")
TSE("x$?1$?", "x$?1$?")
TSE("x$?1$2", "x$?1$2")
TSE("x$?$?", "x$?$?")
// integer & decimal
TSE(" 1", "1")
TSE("+1", "1")
TSE("-1", "-1")
TSE("+.1", "0.1")
TSE("-.1", "-0.1")
TSE(" 1.1", "1.1")
TSE("+1.1", "1.1")
TSE("-1.1", "-1.1")
TSE(" 1.1e1", "11")
TSE("+1.1e1", "11")
TSE("-1.1e1", "-11")
TSE(" 1.1e+1", "11")
TSE("+1.1e+1", "11")
TSE("-1.1e+1", "-11")
TSE(" 1.1e-1", "0.11")
TSE("+1.1e-1", "0.11")
TSE("-1.1e-1", "-0.11")
// units
TSE("1a", "1a")
TSE("1µg", "1µg")
// times
TF("2-")
TF("201-")
TF("2015-")
TF("2015-01")
TF("2015-01-")
TF("2015-01-02-")
TSS("2015-01-02")
TSE("2015-01-02T", "2015-01-02")
TSS("01-02")
TSE("01-02T", "01-02")
TSS("02T")
TF("01:0")
TF("01:02:")
TF("01:02:0")
TF("01:02:03:")
TF("01:02:03:00")
TSE("01:02", "01:02:00")
TSS("01:02:03")
TF("01T02")
TSS("2015-01-02T03:04:05")
TSE("2015-01-02T03:04", "2015-01-02T03:04:00")
TSS("01-02T03:04:05")
TSE("01-02T03:04", "01-02T03:04:00")
TSS("02T03:04:05")
TSE("02T03:04", "02T03:04:00")
// strings
TSE("\"\"", "\"\"")
TSS("\"a\"")
TSE("``````", "\"\"")
TSE("```a```", "\"a\"")
TSE("```a b```", "\"a b\"")
TSE("```a\"b```", "```a\"b```")
TSE("```\na\n```", "```\na\n```")
TSE("\"\\t\"", "\"\t\"")
TSE("\"\\n\"", "```\n```")
// names
TF("=")
TF("a=")
TF("=,")
TF("=;")
TF("=\n")
TSE("a=1", "a = 1")
TSE("a=b", "a = b")
TSE("a = 1", "a = 1")
TSE("a = b", "a = b")
TSE("a = +1", "a = 1")
TSS("a = -1")
TSE("a=\"\"", "a = \"\"")
TSE("a=\"ab\"", "a = \"ab\"")
TSE("a=\"a b\"", "a = \"a b\"")
TF("a=\"\n")
TSE("a=```ab```", "a = \"ab\"")
TSE("a=```a b```", "a = \"a b\"")
TSE("a=```a\nb```", "a = ```a\nb```")
// tags
TF(":")
TF("::")
TF(":,")
TF(":;")
TF(":\n")
TF(":\"a\"")
TF(":```a```")
TF(":1")
TSE(":x", ":x")
TF(":x:")
TF(":x=")
TF("x=:")
TSE("x:y", "x:y")
TSE(":x:y", ":x:y")
TSE(":?x", ":?x")
TSE(":G~x", ":G~x")
TSE(":~x", ":~x")
TSE(":~~x", ":~~x")
TSE(":~~~x", ":~~~x")
TSE(":^x", ":^x")
TSE(":^^x", ":^^x")
TSE(":^^^x", ":^^^x")
TSE(":?~x", ":?~x")
TSE(":?~~x", ":?~~x")
TSE(":?~~~x", ":?~~~x")
TSE(":?^x", ":?^x")
TSE(":?^^x", ":?^^x")
TSE(":?^^^x", ":?^^^x")
TSE(":G~~x", ":G~~x")
TSE(":G~~~x", ":G~~~x")
TSE(":G~~~~x", ":G~~~~x")
TSE(":G~^x", ":G~^x")
TSE(":G~^^x", ":G~^^x")
TSE(":G~^^^x", ":G~^^^x")
TF(":x(")
TSE(":x()", ":x")
TSE(":x( )", ":x")
TSE(":x(\t)", ":x")
TSE(":x(\n)", ":x")
TSE(":x(1)", ":x(1)")
TSE(":x(y)", ":x(y)")
TSE(":x(y,z)", ":x(y, z)")
TSE(":x(y;z)", ":x(y, z)")
TSE(":x(y\nz)", ":x(y, z)")
// scopes
TF("{")
TF("(")
TF("[")
TF("x[+")
TF("x[,")
TF("x[;")
TF("x[\n")
TSE("{}", "null")
TSE("{{}}", "{\n\tnull\n}")
TSE("x{}", "x")
TSE("x[]", "x")
TSE("x[1]", "x[1]")
TSE("x[y]", "x[y]")
TSE("x[y:a(1){2}, b]", "x[y:a(1){\n\t2\n}, b]")
// expressions
TF("x + ")
TF("x - ,")
TF("x * ;")
TF("{x / }")
TSS("x + y")
TSS("x = y + z")
TSS("a[x - y]")
TSS("a[x - y, 1 * 2, z]")
TSS(":a(x * y)")
TSS("x + y - z")
TSE("{x / y}", "{\n\tx / y\n}")
M_TSS("x\nz + w")
S_TF("x\nz + w")
M_TSE("x + y, z / w", "x + y\nz / w")
S_TF("x + y, z / w")
TSS("x[y] + z")
};
void check(Test const& test) {
TOGO_LOGF(
"reading (%3u): <%.*s>\n",
test.data.size, test.data.size, test.data.data
);
Object root;
MemoryReader in_stream{test.data};
ObjectParserInfo pinfo;
if (object::read_text(root, in_stream, pinfo, test.single_value)) {
MemoryStream out_stream{memory::default_allocator(), test.expected_output.size + 1};
TOGO_ASSERTE(object::write_text(root, out_stream, test.single_value));
StringRef output{
reinterpret_cast<char*>(array::begin(out_stream.data())),
static_cast<unsigned>(out_stream.size())
};
TOGO_LOGF(
"rewritten (%3u): <%.*s>\n",
output.size, output.size, output.data
);
TOGO_ASSERT(test.success, "read succeeded when it should have failed");
TOGO_ASSERT(
string::compare_equal(
test.single_value && test.expected_output.empty()
? StringRef{"null"}
: test.expected_output,
output
),
"output does not match"
);
} else {
TOGO_LOGF(
"failed to read%s: [%2u,%2u]: %s\n",
test.success ? " (UNEXPECTED)" : "",
pinfo.line,
pinfo.column,
pinfo.message
);
TOGO_ASSERT(!test.success, "read failed when it should have succeeded");
}
TOGO_LOG("\n");
}
bool rewrite_file(MemoryStream& out_stream, StringRef path) {
Object root;
if (!object::read_text_file(root, path)) {
TOGO_LOG("\\\\ failed to read\n");
return false;
}
if (!object::write_text(root, out_stream)) {
TOGO_LOG("\\\\ failed to rewrite\n");
return false;
}
io::seek_to(out_stream, 0);
if (!object::read_text(root, out_stream)) {
TOGO_LOG("\\\\ failed to reread\n");
return false;
}
return true;
}
signed main(signed argc, char* argv[]) {
memory_init();
if (argc > 1) {
bool print = true;
signed i = 1;
if (string::compare_equal({argv[i], cstr_tag{}}, "--noprint")) {
print = false;
++i;
}
MemoryStream out_stream{memory::default_allocator(), 4096 * 16};
for (; i < argc; ++i) {
StringRef path{argv[i], cstr_tag{}};
TOGO_LOGF("\n\\\\ file: %.*s\n", path.size, path.data);
if (rewrite_file(out_stream, path) && print) {
TOGO_LOGF("%.*s",
static_cast<unsigned>(out_stream.size()),
reinterpret_cast<char*>(array::begin(out_stream.data()))
);
}
out_stream.clear();
}
} else {
for (auto& test : tests) {
check(test);
}
}
return 0;
}
<commit_msg>lib/core/test/object/io_text: added scoped expression tests; tidy.<commit_after>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/core/log/log.hpp>
#include <togo/core/collection/array.hpp>
#include <togo/core/string/string.hpp>
#include <togo/core/io/memory_stream.hpp>
#include <togo/core/io/io.hpp>
#include <quanta/core/object/object.hpp>
#include <togo/support/test.hpp>
#include <cmath>
using namespace quanta;
#define M_TSN(d) {true, false, d, {}},
#define M_TSE(d, e) {true, false, d, e},
#define M_TSS(d) {true, false, d, d},
#define M_TF(d) {false, false, d, {}},
#define S_TSN(d) {true, true, d, {}},
#define S_TSE(d, e) {true, true, d, e},
#define S_TSS(d) {true, true, d, d},
#define S_TF(d) {false, true, d, {}},
#define TSN(d) M_TSN(d) S_TSN(d)
#define TSE(d, e) M_TSE(d, e) S_TSE(d, e)
#define TSS(d) M_TSS(d) S_TSS(d)
#define TF(d) M_TF(d) S_TF(d)
struct Test {
bool success;
bool single_value;
StringRef data;
StringRef expected_output;
} const tests[]{
// whitespace
TSN("")
TSN(" ")
TSN("\n")
TSN(" \t\n")
// comments
TF("\\")
TF("\\*")
TSN("\\\\")
TSN("\\**\\")
TSN("\\*\nblah\n*\\")
M_TSE("x\\\\\ny", "x\ny")
S_TF("x\\\\\ny")
// nested
TF("\\* \\* *\\")
TSN("\\* \\**\\ *\\")
// constants
TSE("null", "null")
TSE("false", "false")
TSE("true", "true")
// identifiers
TSE("a", "a")
TSE("á", "á")
TSE(".á", ".á")
TSE("_", "_")
M_TSE("a\nb", "a\nb")
S_TSE("\n\\**\\a\n", "a")
S_TSE("a\n", "a")
S_TF("a\nb")
// markers
TSE("~", "~")
TSE("~x", "~x")
TSE("~~x", "~~x")
TSE("~~~x", "~~~x")
TSE("^", "^")
TSE("^x", "^x")
TSE("^^x", "^^x")
TSE("^^^x", "^^^x")
TSE("G~~x", "G~~x")
TSE(" G~x", "G~x")
TSE("G~^x", "G~^x")
TSE("?", "?")
TSE("?~x", "?~x")
TSE(" ?x", "?x")
TSE("?^x", "?^x")
// source
TSE("x$0", "x")
TSE("x$0$0", "x")
TSE("x$0$1", "x")
TSE("x$0$?", "x")
TSE("x$1", "x$1")
TSE("x$1$0", "x$1")
TSE("x$1$?", "x$1$?")
TSE("x$1$2", "x$1$2")
TSE("x$?1", "x$?1")
TSE("x$?1$0", "x$?1")
TSE("x$?1$?", "x$?1$?")
TSE("x$?1$2", "x$?1$2")
TSE("x$?$?", "x$?$?")
// integer & decimal
TSE(" 1", "1")
TSE("+1", "1")
TSE("-1", "-1")
TSE("+.1", "0.1")
TSE("-.1", "-0.1")
TSE(" 1.1", "1.1")
TSE("+1.1", "1.1")
TSE("-1.1", "-1.1")
TSE(" 1.1e1", "11")
TSE("+1.1e1", "11")
TSE("-1.1e1", "-11")
TSE(" 1.1e+1", "11")
TSE("+1.1e+1", "11")
TSE("-1.1e+1", "-11")
TSE(" 1.1e-1", "0.11")
TSE("+1.1e-1", "0.11")
TSE("-1.1e-1", "-0.11")
// units
TSE("1a", "1a")
TSE("1µg", "1µg")
// times
TF("2-")
TF("201-")
TF("2015-")
TF("2015-01")
TF("2015-01-")
TF("2015-01-02-")
TSS("2015-01-02")
TSE("2015-01-02T", "2015-01-02")
TSS("01-02")
TSE("01-02T", "01-02")
TSS("02T")
TF("01:0")
TF("01:02:")
TF("01:02:0")
TF("01:02:03:")
TF("01:02:03:00")
TSE("01:02", "01:02:00")
TSS("01:02:03")
TF("01T02")
TSS("2015-01-02T03:04:05")
TSE("2015-01-02T03:04", "2015-01-02T03:04:00")
TSS("01-02T03:04:05")
TSE("01-02T03:04", "01-02T03:04:00")
TSS("02T03:04:05")
TSE("02T03:04", "02T03:04:00")
// strings
TSE("\"\"", "\"\"")
TSS("\"a\"")
TSE("``````", "\"\"")
TSE("```a```", "\"a\"")
TSE("```a b```", "\"a b\"")
TSE("```a\"b```", "```a\"b```")
TSE("```\na\n```", "```\na\n```")
TSE("\"\\t\"", "\"\t\"")
TSE("\"\\n\"", "```\n```")
// names
TF("=")
TF("a=")
TF("=,")
TF("=;")
TF("=\n")
TSE("a=1", "a = 1")
TSE("a=b", "a = b")
TSE("a = 1", "a = 1")
TSE("a = b", "a = b")
TSE("a = +1", "a = 1")
TSS("a = -1")
TSE("a=\"\"", "a = \"\"")
TSE("a=\"ab\"", "a = \"ab\"")
TSE("a=\"a b\"", "a = \"a b\"")
TF("a=\"\n")
TSE("a=```ab```", "a = \"ab\"")
TSE("a=```a b```", "a = \"a b\"")
TSE("a=```a\nb```", "a = ```a\nb```")
// tags
TF(":")
TF("::")
TF(":,")
TF(":;")
TF(":\n")
TF(":\"a\"")
TF(":```a```")
TF(":1")
TF(":x:")
TF(":x=")
TF("x=:")
TSS(":x")
TSE("x:y", "x:y")
TSE(":x:y", ":x:y")
TSE(":?x", ":?x")
TSE(":G~x", ":G~x")
TSE(":~x", ":~x")
TSE(":~~x", ":~~x")
TSE(":~~~x", ":~~~x")
TSE(":^x", ":^x")
TSE(":^^x", ":^^x")
TSE(":^^^x", ":^^^x")
TSE(":?~x", ":?~x")
TSE(":?~~x", ":?~~x")
TSE(":?~~~x", ":?~~~x")
TSE(":?^x", ":?^x")
TSE(":?^^x", ":?^^x")
TSE(":?^^^x", ":?^^^x")
TSE(":G~~x", ":G~~x")
TSE(":G~~~x", ":G~~~x")
TSE(":G~~~~x", ":G~~~~x")
TSE(":G~^x", ":G~^x")
TSE(":G~^^x", ":G~^^x")
TSE(":G~^^^x", ":G~^^^x")
TF(":x(")
TSE(":x()", ":x")
TSE(":x( )", ":x")
TSE(":x(\t)", ":x")
TSE(":x(\n)", ":x")
TSE(":x(1)", ":x(1)")
TSE(":x(y)", ":x(y)")
TSE(":x(y,z)", ":x(y, z)")
TSE(":x(y;z)", ":x(y, z)")
TSE(":x(y\nz)", ":x(y, z)")
// scopes
TF("{")
TF("(")
TF("[")
TF("x[+")
TF("x[,")
TF("x[;")
TF("x[\n")
TSE("{}", "null")
TSE("{{}}", "{\n\tnull\n}")
TSE("x{}", "x")
TSE("x[]", "x")
TSE("x[1]", "x[1]")
TSE("x[y]", "x[y]")
TSE("x[y:a(1){2}, b]", "x[y:a(1){\n\t2\n}, b]")
// expressions
TF("x + ")
TF("x - ,")
TF("x * ;")
TF("{x / }")
TSS("x + y")
TSS("x = y + z")
TSS("a[x - y]")
TSS("a[x - y, 1 * 2, z]")
TSS(":a(x * y)")
TSS("x + y - z")
TSE("{x / y}", "{\n\tx / y\n}")
M_TSS("x\nz + w")
S_TF("x\nz + w")
M_TSE("x + y, z / w", "x + y\nz / w")
S_TF("x + y, z / w")
TSS("x[y] + z")
// scoped expressions
TF("(")
TF("(x + )")
TF("(x + y + )")
TF("(x,)")
TF("(x;)")
TF("(x + y,)")
TF("(x + y;)")
TSS("()")
TSE("(\n)", "()")
TSE("(\\*blargh*\\)", "()")
TSE("(x\n)", "(x)")
TSE("(x + y)", "x + y")
TSE("(\\**\\x\\**\\ + y)", "x + y")
TSE("(x + y):a", ":a()(x + y)")
TSS(":a()()")
TSE(":a:b()(x)", ":a:b()(x)")
TSE(":a()(x + y):b", ":a:b()(x + y)")
};
void check(Test const& test) {
TOGO_LOGF(
"reading (%3u): <%.*s>\n",
test.data.size, test.data.size, test.data.data
);
Object root;
MemoryReader in_stream{test.data};
ObjectParserInfo pinfo;
if (object::read_text(root, in_stream, pinfo, test.single_value)) {
MemoryStream out_stream{memory::default_allocator(), test.expected_output.size + 1};
TOGO_ASSERTE(object::write_text(root, out_stream, test.single_value));
StringRef output{
reinterpret_cast<char*>(array::begin(out_stream.data())),
static_cast<unsigned>(out_stream.size())
};
TOGO_LOGF(
"rewritten (%3u): <%.*s>\n",
output.size, output.size, output.data
);
TOGO_ASSERT(test.success, "read succeeded when it should have failed");
TOGO_ASSERT(
string::compare_equal(
test.single_value && test.expected_output.empty()
? StringRef{"null"}
: test.expected_output,
output
),
"output does not match"
);
} else {
TOGO_LOGF(
"failed to read%s: [%2u,%2u]: %s\n",
test.success ? " (UNEXPECTED)" : "",
pinfo.line,
pinfo.column,
pinfo.message
);
TOGO_ASSERT(!test.success, "read failed when it should have succeeded");
}
TOGO_LOG("\n");
}
bool rewrite_file(MemoryStream& out_stream, StringRef path) {
Object root;
if (!object::read_text_file(root, path)) {
TOGO_LOG("\\\\ failed to read\n");
return false;
}
if (!object::write_text(root, out_stream)) {
TOGO_LOG("\\\\ failed to rewrite\n");
return false;
}
io::seek_to(out_stream, 0);
if (!object::read_text(root, out_stream)) {
TOGO_LOG("\\\\ failed to reread\n");
return false;
}
return true;
}
signed main(signed argc, char* argv[]) {
memory_init();
if (argc > 1) {
bool print = true;
signed i = 1;
if (string::compare_equal({argv[i], cstr_tag{}}, "--noprint")) {
print = false;
++i;
}
MemoryStream out_stream{memory::default_allocator(), 4096 * 16};
for (; i < argc; ++i) {
StringRef path{argv[i], cstr_tag{}};
TOGO_LOGF("\n\\\\ file: %.*s\n", path.size, path.data);
if (rewrite_file(out_stream, path) && print) {
TOGO_LOGF("%.*s",
static_cast<unsigned>(out_stream.size()),
reinterpret_cast<char*>(array::begin(out_stream.data()))
);
}
out_stream.clear();
}
} else {
for (auto& test : tests) {
check(test);
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkProgressAccumulator.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkProgressAccumulator.h"
namespace itk {
ProgressAccumulator
::ProgressAccumulator()
{
m_MiniPipelineFilter = 0;
// Initialize the progress values
this->ResetProgress();
// Create a member command
m_CallbackCommand = CommandType::New();
m_CallbackCommand->SetCallbackFunction( this, & Self::ReportProgress );
}
ProgressAccumulator
::~ProgressAccumulator()
{
UnregisterAllFilters();
}
void
ProgressAccumulator
::RegisterInternalFilter(GenericFilterType *filter,float weight)
{
// Observe the filter
unsigned long tag =
filter->AddObserver(ProgressEvent(), m_CallbackCommand);
// Create a record for the filter
struct FilterRecord record;
record.Filter = filter;
record.Weight = weight;
record.ObserverTag = tag;
record.Progress = 0.0f;
// Add the record to the list
m_FilterRecord.push_back(record);
}
void
ProgressAccumulator
::UnregisterAllFilters()
{
// The filters should no longer be observing us
FilterRecordVector::iterator it;
for(it = m_FilterRecord.begin();it!=m_FilterRecord.end();++it)
{
it->Filter->RemoveObserver(it->ObserverTag);
}
// Clear the filter array
m_FilterRecord.clear();
// Reset the progress meter
ResetProgress();
}
void
ProgressAccumulator
::ResetProgress()
{
// Reset the accumulated progress
m_AccumulatedProgress = 0.0f;
// Reset each of the individial progress meters
FilterRecordVector::iterator it;
for(it = m_FilterRecord.begin();it!=m_FilterRecord.end();++it)
{
it->Progress = 0.0f;
}
}
void
ProgressAccumulator
::ReportProgress(Object *object, const EventObject &event)
{
const ProcessObject * internalFilter =
dynamic_cast<const ProcessObject *>( object );
ProgressEvent p;
if( typeid( event ) == typeid( p ) )
{
// Add up the progress from different filters
m_AccumulatedProgress = 0.0f;
FilterRecordVector::iterator it;
for(it = m_FilterRecord.begin();it!=m_FilterRecord.end();++it)
{
// Record the progress if it's from one of the registered filters
if(it->Filter == internalFilter)
{
it->Progress = internalFilter->GetProgress();
}
m_AccumulatedProgress += it->Progress * it->Weight;
}
// Update the progress of the client mini-pipeline filter
m_MiniPipelineFilter->UpdateProgress(m_AccumulatedProgress);
}
}
void ProgressAccumulator
::PrintSelf(std::ostream &os, Indent indent) const
{
Superclass::PrintSelf(os,indent);
if (m_MiniPipelineFilter)
{
os << indent << m_MiniPipelineFilter << std::endl;
}
os << indent << m_AccumulatedProgress << std::endl;
}
} // End namespace itk
<commit_msg>ERR: was not accumulating progress of filters that did not need to be run.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkProgressAccumulator.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkProgressAccumulator.h"
namespace itk {
ProgressAccumulator
::ProgressAccumulator()
{
m_MiniPipelineFilter = 0;
// Initialize the progress values
this->ResetProgress();
// Create a member command
m_CallbackCommand = CommandType::New();
m_CallbackCommand->SetCallbackFunction( this, & Self::ReportProgress );
}
ProgressAccumulator
::~ProgressAccumulator()
{
UnregisterAllFilters();
}
void
ProgressAccumulator
::RegisterInternalFilter(GenericFilterType *filter,float weight)
{
// Observe the filter
unsigned long tag =
filter->AddObserver(ProgressEvent(), m_CallbackCommand);
// Create a record for the filter
struct FilterRecord record;
record.Filter = filter;
record.Weight = weight;
record.ObserverTag = tag;
record.Progress = 0.0f;
// Add the record to the list
m_FilterRecord.push_back(record);
}
void
ProgressAccumulator
::UnregisterAllFilters()
{
// The filters should no longer be observing us
FilterRecordVector::iterator it;
for(it = m_FilterRecord.begin();it!=m_FilterRecord.end();++it)
{
it->Filter->RemoveObserver(it->ObserverTag);
}
// Clear the filter array
m_FilterRecord.clear();
// Reset the progress meter
ResetProgress();
}
void
ProgressAccumulator
::ResetProgress()
{
// Reset the accumulated progress
m_AccumulatedProgress = 0.0f;
// Reset each of the individial progress meters
FilterRecordVector::iterator it;
for(it = m_FilterRecord.begin();it!=m_FilterRecord.end();++it)
{
it->Progress = 0.0f;
}
}
void
ProgressAccumulator
::ReportProgress(Object *, const EventObject &event)
{
ProgressEvent p;
if( typeid( event ) == typeid( p ) )
{
// Add up the progress from different filters
m_AccumulatedProgress = 0.0f;
FilterRecordVector::iterator it;
for(it = m_FilterRecord.begin();it!=m_FilterRecord.end();++it)
{
m_AccumulatedProgress += it->Filter->GetProgress() * it->Weight;
}
// Update the progress of the client mini-pipeline filter
m_MiniPipelineFilter->UpdateProgress(m_AccumulatedProgress);
}
}
void ProgressAccumulator
::PrintSelf(std::ostream &os, Indent indent) const
{
Superclass::PrintSelf(os,indent);
if (m_MiniPipelineFilter)
{
os << indent << m_MiniPipelineFilter << std::endl;
}
os << indent << m_AccumulatedProgress << std::endl;
}
} // End namespace itk
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xtextedt.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2006-09-17 14:49:23 $
*
* 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_svtools.hxx"
#include <xtextedt.hxx>
#include <vcl/svapp.hxx> // International
#include <unotools/textsearch.hxx>
#ifndef _COM_SUN_STAR_UTIL_SEARCHOPTIONS_HPP_
#include <com/sun/star/util/SearchOptions.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HPP_
#include <com/sun/star/util/SearchFlags.hpp>
#endif
using namespace ::com::sun::star;
// -------------------------------------------------------------------------
// class ExtTextEngine
// -------------------------------------------------------------------------
ExtTextEngine::ExtTextEngine() : maGroupChars( String::CreateFromAscii( "(){}[]", 6 ) )
{
}
ExtTextEngine::~ExtTextEngine()
{
}
TextSelection ExtTextEngine::MatchGroup( const TextPaM& rCursor ) const
{
TextSelection aSel( rCursor );
USHORT nPos = rCursor.GetIndex();
ULONG nPara = rCursor.GetPara();
ULONG nParas = GetParagraphCount();
if ( ( nPara < nParas ) && ( nPos < GetTextLen( nPara ) ) )
{
USHORT nMatchChar = maGroupChars.Search( GetText( rCursor.GetPara() ).GetChar( nPos ) );
if ( nMatchChar != STRING_NOTFOUND )
{
if ( ( nMatchChar % 2 ) == 0 )
{
// Vorwaerts suchen...
sal_Unicode nSC = maGroupChars.GetChar( nMatchChar );
sal_Unicode nEC = maGroupChars.GetChar( nMatchChar+1 );
USHORT nCur = nPos+1;
USHORT nLevel = 1;
while ( nLevel && ( nPara < nParas ) )
{
XubString aStr = GetText( nPara );
while ( nCur < aStr.Len() )
{
if ( aStr.GetChar( nCur ) == nSC )
nLevel++;
else if ( aStr.GetChar( nCur ) == nEC )
{
nLevel--;
if ( !nLevel )
break; // while nCur...
}
nCur++;
}
if ( nLevel )
{
nPara++;
nCur = 0;
}
}
if ( nLevel == 0 ) // gefunden
{
aSel.GetStart() = rCursor;
aSel.GetEnd() = TextPaM( nPara, nCur+1 );
}
}
else
{
// Rueckwaerts suchen...
xub_Unicode nEC = maGroupChars.GetChar( nMatchChar );
xub_Unicode nSC = maGroupChars.GetChar( nMatchChar-1 );
USHORT nCur = rCursor.GetIndex()-1;
USHORT nLevel = 1;
while ( nLevel )
{
if ( GetTextLen( nPara ) )
{
XubString aStr = GetText( nPara );
while ( nCur )
{
if ( aStr.GetChar( nCur ) == nSC )
{
nLevel--;
if ( !nLevel )
break; // while nCur...
}
else if ( aStr.GetChar( nCur ) == nEC )
nLevel++;
nCur--;
}
}
if ( nLevel )
{
if ( nPara )
{
nPara--;
nCur = GetTextLen( nPara )-1; // egal ob negativ, weil if Len()
}
else
break;
}
}
if ( nLevel == 0 ) // gefunden
{
aSel.GetStart() = rCursor;
aSel.GetStart().GetIndex()++; // hinter das Zeichen
aSel.GetEnd() = TextPaM( nPara, nCur );
}
}
}
}
return aSel;
}
BOOL ExtTextEngine::Search( TextSelection& rSel, const util::SearchOptions& rSearchOptions, BOOL bForward )
{
TextSelection aSel( rSel );
aSel.Justify();
BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) );
TextPaM aStartPaM( aSel.GetEnd() );
if ( aSel.HasRange() && ( ( bSearchInSelection && bForward ) || ( !bSearchInSelection && !bForward ) ) )
{
aStartPaM = aSel.GetStart();
}
BOOL bFound = FALSE;
ULONG nStartNode, nEndNode;
if ( bSearchInSelection )
nEndNode = bForward ? aSel.GetEnd().GetPara() : aSel.GetStart().GetPara();
else
nEndNode = bForward ? (GetParagraphCount()-1) : 0;
nStartNode = aStartPaM.GetPara();
util::SearchOptions aOptions( rSearchOptions );
aOptions.Locale = Application::GetSettings().GetLocale();
utl::TextSearch aSearcher( rSearchOptions );
// ueber die Absaetze iterieren...
for ( ULONG nNode = nStartNode;
bForward ? ( nNode <= nEndNode) : ( nNode >= nEndNode );
bForward ? nNode++ : nNode-- )
{
String aText = GetText( nNode );
USHORT nStartPos = 0;
USHORT nEndPos = aText.Len();
if ( nNode == nStartNode )
{
if ( bForward )
nStartPos = aStartPaM.GetIndex();
else
nEndPos = aStartPaM.GetIndex();
}
if ( ( nNode == nEndNode ) && bSearchInSelection )
{
if ( bForward )
nEndPos = aSel.GetEnd().GetIndex();
else
nStartPos = aSel.GetStart().GetIndex();
}
if ( bForward )
bFound = aSearcher.SearchFrwrd( aText, &nStartPos, &nEndPos );
else
bFound = aSearcher.SearchBkwrd( aText, &nEndPos, &nStartPos );
if ( bFound )
{
rSel.GetStart().GetPara() = nNode;
rSel.GetStart().GetIndex() = nStartPos;
rSel.GetEnd().GetPara() = nNode;
rSel.GetEnd().GetIndex() = nEndPos;
// Ueber den Absatz selektieren?
// Select over the paragraph?
// FIXME This should be max long...
if( nEndPos == sal::static_int_cast<USHORT>(-1) ) // USHORT for 0 and -1 !
{
if ( (rSel.GetEnd().GetPara()+1) < GetParagraphCount() )
{
rSel.GetEnd().GetPara()++;
rSel.GetEnd().GetIndex() = 0;
}
else
{
rSel.GetEnd().GetIndex() = nStartPos;
bFound = FALSE;
}
}
break;
}
if ( !bForward && !nNode ) // Bei rueckwaertsuche, wenn nEndNode = 0:
break;
}
return bFound;
}
// -------------------------------------------------------------------------
// class ExtTextView
// -------------------------------------------------------------------------
ExtTextView::ExtTextView( ExtTextEngine* pEng, Window* pWindow )
: TextView( pEng, pWindow )
{
}
ExtTextView::~ExtTextView()
{
}
BOOL ExtTextView::MatchGroup()
{
TextSelection aTmpSel( GetSelection() );
aTmpSel.Justify();
if ( ( aTmpSel.GetStart().GetPara() != aTmpSel.GetEnd().GetPara() ) ||
( ( aTmpSel.GetEnd().GetIndex() - aTmpSel.GetStart().GetIndex() ) > 1 ) )
{
return FALSE;
}
TextSelection aMatchSel = ((ExtTextEngine*)GetTextEngine())->MatchGroup( aTmpSel.GetStart() );
if ( aMatchSel.HasRange() )
SetSelection( aMatchSel );
return aMatchSel.HasRange() ? TRUE : FALSE;
}
BOOL ExtTextView::Search( const util::SearchOptions& rSearchOptions, BOOL bForward )
{
BOOL bFound = FALSE;
TextSelection aSel( GetSelection() );
if ( ((ExtTextEngine*)GetTextEngine())->Search( aSel, rSearchOptions, bForward ) )
{
bFound = TRUE;
// Erstmal den Anfang des Wortes als Selektion einstellen,
// damit das ganze Wort in den sichtbaren Bereich kommt.
SetSelection( aSel.GetStart() );
ShowCursor( TRUE, FALSE );
}
else
{
aSel = GetSelection().GetEnd();
}
SetSelection( aSel );
ShowCursor();
return bFound;
}
USHORT ExtTextView::Replace( const util::SearchOptions& rSearchOptions, BOOL bAll, BOOL bForward )
{
USHORT nFound = 0;
if ( !bAll )
{
if ( GetSelection().HasRange() )
{
InsertText( rSearchOptions.replaceString );
nFound = 1;
Search( rSearchOptions, bForward ); // gleich zum naechsten
}
else
{
if( Search( rSearchOptions, bForward ) )
nFound = 1;
}
}
else
{
// Der Writer ersetzt alle, vom Anfang bis Ende...
ExtTextEngine* pTextEngine = (ExtTextEngine*)GetTextEngine();
// HideSelection();
TextSelection aSel;
BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) );
if ( bSearchInSelection )
{
aSel = GetSelection();
aSel.Justify();
}
TextSelection aSearchSel( aSel );
BOOL bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE );
if ( bFound )
pTextEngine->UndoActionStart( XTEXTUNDO_REPLACEALL );
while ( bFound )
{
nFound++;
TextPaM aNewStart = pTextEngine->ImpInsertText( aSel, rSearchOptions.replaceString );
aSel = aSearchSel;
aSel.GetStart() = aNewStart;
bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE );
}
if ( nFound )
{
SetSelection( aSel.GetStart() );
pTextEngine->FormatAndUpdate( this );
pTextEngine->UndoActionEnd( XTEXTUNDO_REPLACEALL );
}
}
return nFound;
}
BOOL ExtTextView::ImpIndentBlock( BOOL bRight )
{
BOOL bDone = FALSE;
TextSelection aSel = GetSelection();
aSel.Justify();
HideSelection();
GetTextEngine()->UndoActionStart( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK );
ULONG nStartPara = aSel.GetStart().GetPara();
ULONG nEndPara = aSel.GetEnd().GetPara();
if ( aSel.HasRange() && !aSel.GetEnd().GetIndex() )
{
nEndPara--; // den dann nicht einruecken...
}
for ( ULONG nPara = nStartPara; nPara <= nEndPara; nPara++ )
{
if ( bRight )
{
// Tabs hinzufuegen
GetTextEngine()->ImpInsertText( TextPaM( nPara, 0 ), '\t' );
bDone = TRUE;
}
else
{
// Tabs/Blanks entfernen
String aText = GetTextEngine()->GetText( nPara );
if ( aText.Len() && (
( aText.GetChar( 0 ) == '\t' ) ||
( aText.GetChar( 0 ) == ' ' ) ) )
{
GetTextEngine()->ImpDeleteText( TextSelection( TextPaM( nPara, 0 ), TextPaM( nPara, 1 ) ) );
bDone = TRUE;
}
}
}
GetTextEngine()->UndoActionEnd( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK );
BOOL bRange = aSel.HasRange();
if ( bRight )
{
aSel.GetStart().GetIndex()++;
if ( bRange && ( aSel.GetEnd().GetPara() == nEndPara ) )
aSel.GetEnd().GetIndex()++;
}
else
{
if ( aSel.GetStart().GetIndex() )
aSel.GetStart().GetIndex()--;
if ( bRange && aSel.GetEnd().GetIndex() )
aSel.GetEnd().GetIndex()--;
}
ImpSetSelection( aSel );
GetTextEngine()->FormatAndUpdate( this );
return bDone;
}
BOOL ExtTextView::IndentBlock()
{
return ImpIndentBlock( TRUE );
}
BOOL ExtTextView::UnindentBlock()
{
return ImpIndentBlock( FALSE );
}
<commit_msg>INTEGRATION: CWS sb59 (1.11.64); FILE MERGED 2006/07/28 15:24:16 sb 1.11.64.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xtextedt.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: obo $ $Date: 2006-10-12 15:16:42 $
*
* 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_svtools.hxx"
#include <xtextedt.hxx>
#include <vcl/svapp.hxx> // International
#include <unotools/textsearch.hxx>
#ifndef _COM_SUN_STAR_UTIL_SEARCHOPTIONS_HPP_
#include <com/sun/star/util/SearchOptions.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HPP_
#include <com/sun/star/util/SearchFlags.hpp>
#endif
using namespace ::com::sun::star;
// -------------------------------------------------------------------------
// class ExtTextEngine
// -------------------------------------------------------------------------
ExtTextEngine::ExtTextEngine() : maGroupChars( String::CreateFromAscii( "(){}[]", 6 ) )
{
}
ExtTextEngine::~ExtTextEngine()
{
}
TextSelection ExtTextEngine::MatchGroup( const TextPaM& rCursor ) const
{
TextSelection aSel( rCursor );
USHORT nPos = rCursor.GetIndex();
ULONG nPara = rCursor.GetPara();
ULONG nParas = GetParagraphCount();
if ( ( nPara < nParas ) && ( nPos < GetTextLen( nPara ) ) )
{
USHORT nMatchChar = maGroupChars.Search( GetText( rCursor.GetPara() ).GetChar( nPos ) );
if ( nMatchChar != STRING_NOTFOUND )
{
if ( ( nMatchChar % 2 ) == 0 )
{
// Vorwaerts suchen...
sal_Unicode nSC = maGroupChars.GetChar( nMatchChar );
sal_Unicode nEC = maGroupChars.GetChar( nMatchChar+1 );
USHORT nCur = nPos+1;
USHORT nLevel = 1;
while ( nLevel && ( nPara < nParas ) )
{
XubString aStr = GetText( nPara );
while ( nCur < aStr.Len() )
{
if ( aStr.GetChar( nCur ) == nSC )
nLevel++;
else if ( aStr.GetChar( nCur ) == nEC )
{
nLevel--;
if ( !nLevel )
break; // while nCur...
}
nCur++;
}
if ( nLevel )
{
nPara++;
nCur = 0;
}
}
if ( nLevel == 0 ) // gefunden
{
aSel.GetStart() = rCursor;
aSel.GetEnd() = TextPaM( nPara, nCur+1 );
}
}
else
{
// Rueckwaerts suchen...
xub_Unicode nEC = maGroupChars.GetChar( nMatchChar );
xub_Unicode nSC = maGroupChars.GetChar( nMatchChar-1 );
USHORT nCur = rCursor.GetIndex()-1;
USHORT nLevel = 1;
while ( nLevel )
{
if ( GetTextLen( nPara ) )
{
XubString aStr = GetText( nPara );
while ( nCur )
{
if ( aStr.GetChar( nCur ) == nSC )
{
nLevel--;
if ( !nLevel )
break; // while nCur...
}
else if ( aStr.GetChar( nCur ) == nEC )
nLevel++;
nCur--;
}
}
if ( nLevel )
{
if ( nPara )
{
nPara--;
nCur = GetTextLen( nPara )-1; // egal ob negativ, weil if Len()
}
else
break;
}
}
if ( nLevel == 0 ) // gefunden
{
aSel.GetStart() = rCursor;
aSel.GetStart().GetIndex()++; // hinter das Zeichen
aSel.GetEnd() = TextPaM( nPara, nCur );
}
}
}
}
return aSel;
}
BOOL ExtTextEngine::Search( TextSelection& rSel, const util::SearchOptions& rSearchOptions, BOOL bForward )
{
TextSelection aSel( rSel );
aSel.Justify();
BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) );
TextPaM aStartPaM( aSel.GetEnd() );
if ( aSel.HasRange() && ( ( bSearchInSelection && bForward ) || ( !bSearchInSelection && !bForward ) ) )
{
aStartPaM = aSel.GetStart();
}
bool bFound = false;
ULONG nStartNode, nEndNode;
if ( bSearchInSelection )
nEndNode = bForward ? aSel.GetEnd().GetPara() : aSel.GetStart().GetPara();
else
nEndNode = bForward ? (GetParagraphCount()-1) : 0;
nStartNode = aStartPaM.GetPara();
util::SearchOptions aOptions( rSearchOptions );
aOptions.Locale = Application::GetSettings().GetLocale();
utl::TextSearch aSearcher( rSearchOptions );
// ueber die Absaetze iterieren...
for ( ULONG nNode = nStartNode;
bForward ? ( nNode <= nEndNode) : ( nNode >= nEndNode );
bForward ? nNode++ : nNode-- )
{
String aText = GetText( nNode );
USHORT nStartPos = 0;
USHORT nEndPos = aText.Len();
if ( nNode == nStartNode )
{
if ( bForward )
nStartPos = aStartPaM.GetIndex();
else
nEndPos = aStartPaM.GetIndex();
}
if ( ( nNode == nEndNode ) && bSearchInSelection )
{
if ( bForward )
nEndPos = aSel.GetEnd().GetIndex();
else
nStartPos = aSel.GetStart().GetIndex();
}
if ( bForward )
bFound = aSearcher.SearchFrwrd( aText, &nStartPos, &nEndPos );
else
bFound = aSearcher.SearchBkwrd( aText, &nEndPos, &nStartPos );
if ( bFound )
{
rSel.GetStart().GetPara() = nNode;
rSel.GetStart().GetIndex() = nStartPos;
rSel.GetEnd().GetPara() = nNode;
rSel.GetEnd().GetIndex() = nEndPos;
// Ueber den Absatz selektieren?
// Select over the paragraph?
// FIXME This should be max long...
if( nEndPos == sal::static_int_cast<USHORT>(-1) ) // USHORT for 0 and -1 !
{
if ( (rSel.GetEnd().GetPara()+1) < GetParagraphCount() )
{
rSel.GetEnd().GetPara()++;
rSel.GetEnd().GetIndex() = 0;
}
else
{
rSel.GetEnd().GetIndex() = nStartPos;
bFound = false;
}
}
break;
}
if ( !bForward && !nNode ) // Bei rueckwaertsuche, wenn nEndNode = 0:
break;
}
return bFound;
}
// -------------------------------------------------------------------------
// class ExtTextView
// -------------------------------------------------------------------------
ExtTextView::ExtTextView( ExtTextEngine* pEng, Window* pWindow )
: TextView( pEng, pWindow )
{
}
ExtTextView::~ExtTextView()
{
}
BOOL ExtTextView::MatchGroup()
{
TextSelection aTmpSel( GetSelection() );
aTmpSel.Justify();
if ( ( aTmpSel.GetStart().GetPara() != aTmpSel.GetEnd().GetPara() ) ||
( ( aTmpSel.GetEnd().GetIndex() - aTmpSel.GetStart().GetIndex() ) > 1 ) )
{
return FALSE;
}
TextSelection aMatchSel = ((ExtTextEngine*)GetTextEngine())->MatchGroup( aTmpSel.GetStart() );
if ( aMatchSel.HasRange() )
SetSelection( aMatchSel );
return aMatchSel.HasRange() ? TRUE : FALSE;
}
BOOL ExtTextView::Search( const util::SearchOptions& rSearchOptions, BOOL bForward )
{
BOOL bFound = FALSE;
TextSelection aSel( GetSelection() );
if ( ((ExtTextEngine*)GetTextEngine())->Search( aSel, rSearchOptions, bForward ) )
{
bFound = TRUE;
// Erstmal den Anfang des Wortes als Selektion einstellen,
// damit das ganze Wort in den sichtbaren Bereich kommt.
SetSelection( aSel.GetStart() );
ShowCursor( TRUE, FALSE );
}
else
{
aSel = GetSelection().GetEnd();
}
SetSelection( aSel );
ShowCursor();
return bFound;
}
USHORT ExtTextView::Replace( const util::SearchOptions& rSearchOptions, BOOL bAll, BOOL bForward )
{
USHORT nFound = 0;
if ( !bAll )
{
if ( GetSelection().HasRange() )
{
InsertText( rSearchOptions.replaceString );
nFound = 1;
Search( rSearchOptions, bForward ); // gleich zum naechsten
}
else
{
if( Search( rSearchOptions, bForward ) )
nFound = 1;
}
}
else
{
// Der Writer ersetzt alle, vom Anfang bis Ende...
ExtTextEngine* pTextEngine = (ExtTextEngine*)GetTextEngine();
// HideSelection();
TextSelection aSel;
BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) );
if ( bSearchInSelection )
{
aSel = GetSelection();
aSel.Justify();
}
TextSelection aSearchSel( aSel );
BOOL bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE );
if ( bFound )
pTextEngine->UndoActionStart( XTEXTUNDO_REPLACEALL );
while ( bFound )
{
nFound++;
TextPaM aNewStart = pTextEngine->ImpInsertText( aSel, rSearchOptions.replaceString );
aSel = aSearchSel;
aSel.GetStart() = aNewStart;
bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE );
}
if ( nFound )
{
SetSelection( aSel.GetStart() );
pTextEngine->FormatAndUpdate( this );
pTextEngine->UndoActionEnd( XTEXTUNDO_REPLACEALL );
}
}
return nFound;
}
BOOL ExtTextView::ImpIndentBlock( BOOL bRight )
{
BOOL bDone = FALSE;
TextSelection aSel = GetSelection();
aSel.Justify();
HideSelection();
GetTextEngine()->UndoActionStart( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK );
ULONG nStartPara = aSel.GetStart().GetPara();
ULONG nEndPara = aSel.GetEnd().GetPara();
if ( aSel.HasRange() && !aSel.GetEnd().GetIndex() )
{
nEndPara--; // den dann nicht einruecken...
}
for ( ULONG nPara = nStartPara; nPara <= nEndPara; nPara++ )
{
if ( bRight )
{
// Tabs hinzufuegen
GetTextEngine()->ImpInsertText( TextPaM( nPara, 0 ), '\t' );
bDone = TRUE;
}
else
{
// Tabs/Blanks entfernen
String aText = GetTextEngine()->GetText( nPara );
if ( aText.Len() && (
( aText.GetChar( 0 ) == '\t' ) ||
( aText.GetChar( 0 ) == ' ' ) ) )
{
GetTextEngine()->ImpDeleteText( TextSelection( TextPaM( nPara, 0 ), TextPaM( nPara, 1 ) ) );
bDone = TRUE;
}
}
}
GetTextEngine()->UndoActionEnd( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK );
BOOL bRange = aSel.HasRange();
if ( bRight )
{
aSel.GetStart().GetIndex()++;
if ( bRange && ( aSel.GetEnd().GetPara() == nEndPara ) )
aSel.GetEnd().GetIndex()++;
}
else
{
if ( aSel.GetStart().GetIndex() )
aSel.GetStart().GetIndex()--;
if ( bRange && aSel.GetEnd().GetIndex() )
aSel.GetEnd().GetIndex()--;
}
ImpSetSelection( aSel );
GetTextEngine()->FormatAndUpdate( this );
return bDone;
}
BOOL ExtTextView::IndentBlock()
{
return ImpIndentBlock( TRUE );
}
BOOL ExtTextView::UnindentBlock()
{
return ImpIndentBlock( FALSE );
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: borderconn.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-06-27 16:50:10 $
*
* 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_svx.hxx"
#ifndef SVX_BORDERCONN_HXX
#include "borderconn.hxx"
#endif
#ifndef SVX_FRMSEL_HXX
#include <svx/frmsel.hxx>
#endif
#ifndef _SVX_BOLNITEM_HXX
#include "bolnitem.hxx"
#endif
#ifndef _SVX_BOXITEM_HXX
#include <svx/boxitem.hxx>
#endif
#ifndef _SVX_ALGITEM_HXX
#include <svx/algitem.hxx>
#endif
#ifndef _SVX_SHADITEM_HXX
#include <svx/shaditem.hxx>
#endif
namespace svx {
/* ============================================================================
SvxLineItem connection
----------------------
Connects an SvxLineItem (that contains the style of one line of a cell border)
with one frame border from a svx::FrameSelector control. If this connection is
used, no additional code is needed in the Reset() and FillItemSet() functions
of the tab page.
============================================================================ */
// 1st: item wrappers ---------------------------------------------------------
class LineItemWrapper : public sfx::SingleItemWrapper< SvxLineItem, const SvxBorderLine* >
{
public:
inline explicit LineItemWrapper( USHORT nSlot ) : SingleItemWrapperType( nSlot ) {}
virtual const SvxBorderLine* GetItemValue( const SvxLineItem& rItem ) const
{ return rItem.GetLine(); }
virtual void SetItemValue( SvxLineItem& rItem, const SvxBorderLine* pLine ) const
{ rItem.SetLine( pLine ); }
};
// 2nd: control wrappers ------------------------------------------------------
class FrameSelectorWrapper : public sfx::SingleControlWrapper< FrameSelector, const SvxBorderLine* >
{
public:
inline explicit FrameSelectorWrapper( FrameSelector& rFrameSel, FrameBorderType eBorder ) :
SingleControlWrapperType( rFrameSel ), meBorder( eBorder ) {}
virtual bool IsControlDontKnow() const;
virtual void SetControlDontKnow( bool bSet );
virtual const SvxBorderLine* GetControlValue() const;
virtual void SetControlValue( const SvxBorderLine* pLine );
private:
FrameBorderType meBorder; /// The line this wrapper works with.
};
bool FrameSelectorWrapper::IsControlDontKnow() const
{
return GetControl().GetFrameBorderState( meBorder ) == FRAMESTATE_DONTCARE;
}
void FrameSelectorWrapper::SetControlDontKnow( bool bSet )
{
if( bSet )
GetControl().SetBorderDontCare( meBorder );
}
const SvxBorderLine* FrameSelectorWrapper::GetControlValue() const
{
return GetControl().GetFrameBorderStyle( meBorder );
}
void FrameSelectorWrapper::SetControlValue( const SvxBorderLine* pLine )
{
GetControl().ShowBorder( meBorder, pLine );
}
// 3rd: connection ------------------------------------------------------------
typedef sfx::ItemControlConnection< LineItemWrapper, FrameSelectorWrapper > FrameLineConnection;
/* ============================================================================
SvxMarginItem connection
------------------------
Connects an SvxMarginItem (that contains the inner margin of all cell borders)
with the numerical edit controls of the SvxBorderTabPage. If this connection is
used, no additional code is needed in the Reset() and FillItemSet() functions
of the tab page.
============================================================================ */
// 1st: item wrappers ---------------------------------------------------------
typedef sfx::IdentItemWrapper< SvxMarginItem > MarginItemWrapper;
// 2nd: control wrappers ------------------------------------------------------
class MarginControlsWrapper : public sfx::MultiControlWrapper< SvxMarginItem >
{
public:
explicit MarginControlsWrapper(
MetricField& rMfLeft, MetricField& rMfRight,
MetricField& rMfTop, MetricField& rMfBottom );
virtual SvxMarginItem GetControlValue() const;
virtual void SetControlValue( SvxMarginItem aItem );
private:
sfx::Int16MetricFieldWrapper maLeftWrp;
sfx::Int16MetricFieldWrapper maRightWrp;
sfx::Int16MetricFieldWrapper maTopWrp;
sfx::Int16MetricFieldWrapper maBottomWrp;
};
MarginControlsWrapper::MarginControlsWrapper(
MetricField& rMfLeft, MetricField& rMfRight, MetricField& rMfTop, MetricField& rMfBottom ) :
maLeftWrp( rMfLeft, FUNIT_TWIP ),
maRightWrp( rMfRight, FUNIT_TWIP ),
maTopWrp( rMfTop, FUNIT_TWIP ),
maBottomWrp( rMfBottom, FUNIT_TWIP )
{
RegisterControlWrapper( maLeftWrp );
RegisterControlWrapper( maRightWrp );
RegisterControlWrapper( maTopWrp );
RegisterControlWrapper( maBottomWrp );
}
SvxMarginItem MarginControlsWrapper::GetControlValue() const
{
SvxMarginItem aItem( GetDefaultValue() );
if( !maLeftWrp.IsControlDontKnow() )
aItem.SetLeftMargin( maLeftWrp.GetControlValue() );
if( !maRightWrp.IsControlDontKnow() )
aItem.SetRightMargin( maRightWrp.GetControlValue() );
if( !maTopWrp.IsControlDontKnow() )
aItem.SetTopMargin( maTopWrp.GetControlValue() );
if( !maBottomWrp.IsControlDontKnow() )
aItem.SetBottomMargin( maBottomWrp.GetControlValue() );
return aItem;
}
void MarginControlsWrapper::SetControlValue( SvxMarginItem aItem )
{
maLeftWrp.SetControlValue( aItem.GetLeftMargin() );
maRightWrp.SetControlValue( aItem.GetRightMargin() );
maTopWrp.SetControlValue( aItem.GetTopMargin() );
maBottomWrp.SetControlValue( aItem.GetBottomMargin() );
}
// 3rd: connection ------------------------------------------------------------
class MarginConnection : public sfx::ItemControlConnection< MarginItemWrapper, MarginControlsWrapper >
{
public:
explicit MarginConnection( const SfxItemSet& rItemSet,
MetricField& rMfLeft, MetricField& rMfRight,
MetricField& rMfTop, MetricField& rMfBottom,
sfx::ItemConnFlags nFlags = sfx::ITEMCONN_DEFAULT );
};
MarginConnection::MarginConnection( const SfxItemSet& rItemSet,
MetricField& rMfLeft, MetricField& rMfRight, MetricField& rMfTop, MetricField& rMfBottom,
sfx::ItemConnFlags nFlags ) :
ItemControlConnectionType( SID_ATTR_ALIGN_MARGIN, new MarginControlsWrapper( rMfLeft, rMfRight, rMfTop, rMfBottom ), nFlags )
{
mxCtrlWrp->SetDefaultValue( maItemWrp.GetDefaultItem( rItemSet ) );
}
/* ============================================================================
SvxShadowItem connection
------------------------
Connects an SvxShadowItem (that contains shadow position, size, and color) with
the controls of the SvxBorderTabPage. If this connection is used, no additional
code is needed in the Reset() and FillItemSet() functions of the tab page.
============================================================================ */
// 1st: item wrappers ---------------------------------------------------------
typedef sfx::IdentItemWrapper< SvxShadowItem > ShadowItemWrapper;
// 2nd: control wrappers ------------------------------------------------------
typedef sfx::ValueSetWrapper< SvxShadowLocation > ShadowPosWrapper;
static const ShadowPosWrapper::MapEntryType s_pShadowPosMap[] =
{
{ 1, SVX_SHADOW_NONE },
{ 2, SVX_SHADOW_BOTTOMRIGHT },
{ 3, SVX_SHADOW_TOPRIGHT },
{ 4, SVX_SHADOW_BOTTOMLEFT },
{ 5, SVX_SHADOW_TOPLEFT },
{ VALUESET_ITEM_NOTFOUND, SVX_SHADOW_NONE }
};
class ShadowControlsWrapper : public sfx::MultiControlWrapper< SvxShadowItem >
{
public:
explicit ShadowControlsWrapper( ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor );
virtual SvxShadowItem GetControlValue() const;
virtual void SetControlValue( SvxShadowItem aItem );
private:
ShadowPosWrapper maPosWrp;
sfx::UShortMetricFieldWrapper maSizeWrp;
sfx::ColorListBoxWrapper maColorWrp;
};
ShadowControlsWrapper::ShadowControlsWrapper(
ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor ) :
maPosWrp( rVsPos, s_pShadowPosMap ),
maSizeWrp( rMfSize, FUNIT_TWIP ),
maColorWrp( rLbColor )
{
RegisterControlWrapper( maPosWrp );
RegisterControlWrapper( maSizeWrp );
RegisterControlWrapper( maColorWrp );
}
SvxShadowItem ShadowControlsWrapper::GetControlValue() const
{
SvxShadowItem aItem( GetDefaultValue() );
if( !maPosWrp.IsControlDontKnow() )
aItem.SetLocation( maPosWrp.GetControlValue() );
if( !maSizeWrp.IsControlDontKnow() )
aItem.SetWidth( maSizeWrp.GetControlValue() );
if( !maColorWrp.IsControlDontKnow() )
aItem.SetColor( maColorWrp.GetControlValue() );
return aItem;
}
void ShadowControlsWrapper::SetControlValue( SvxShadowItem aItem )
{
maPosWrp.SetControlValue( aItem.GetLocation() );
maSizeWrp.SetControlValue( aItem.GetWidth() );
maColorWrp.SetControlValue( aItem.GetColor() );
}
// 3rd: connection ------------------------------------------------------------
class ShadowConnection : public sfx::ItemControlConnection< ShadowItemWrapper, ShadowControlsWrapper >
{
public:
explicit ShadowConnection( const SfxItemSet& rItemSet,
ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor,
sfx::ItemConnFlags nFlags = sfx::ITEMCONN_DEFAULT );
};
ShadowConnection::ShadowConnection( const SfxItemSet& rItemSet,
ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor, sfx::ItemConnFlags nFlags ) :
ItemControlConnectionType( SID_ATTR_BORDER_SHADOW, new ShadowControlsWrapper( rVsPos, rMfSize, rLbColor ), nFlags )
{
mxCtrlWrp->SetDefaultValue( maItemWrp.GetDefaultItem( rItemSet ) );
}
// ============================================================================
// ============================================================================
sfx::ItemConnectionBase* CreateFrameLineConnection( USHORT nSlot,
FrameSelector& rFrameSel, FrameBorderType eBorder, sfx::ItemConnFlags nFlags )
{
return new FrameLineConnection( nSlot, new FrameSelectorWrapper( rFrameSel, eBorder ), nFlags );
}
sfx::ItemConnectionBase* CreateFrameBoxConnection( USHORT /*nBoxSlot*/, USHORT /*nBoxInfoSlot*/,
FrameSelector& /*rFrameSel*/, FrameBorderType /*eBorder*/, sfx::ItemConnFlags /*nFlags*/ )
{
DBG_ERRORFILE( "svx::CreateFrameBoxConnection - not implemented" );
return 0;
}
sfx::ItemConnectionBase* CreateMarginConnection( const SfxItemSet& rItemSet,
MetricField& rMfLeft, MetricField& rMfRight,
MetricField& rMfTop, MetricField& rMfBottom,
sfx::ItemConnFlags nFlags )
{
return new MarginConnection( rItemSet, rMfLeft, rMfRight, rMfTop, rMfBottom, nFlags );
}
sfx::ItemConnectionBase* CreateShadowConnection( const SfxItemSet& rItemSet,
ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor,
sfx::ItemConnFlags nFlags )
{
return new ShadowConnection( rItemSet, rVsPos, rMfSize, rLbColor, nFlags );
}
// ============================================================================
} // namespace svx
<commit_msg>INTEGRATION: CWS changefileheader (1.7.368); FILE MERGED 2008/04/01 12:48:05 thb 1.7.368.2: #i85898# Stripping all external header guards 2008/03/31 14:19:19 rt 1.7.368.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: borderconn.cxx,v $
* $Revision: 1.8 $
*
* 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_svx.hxx"
#include "borderconn.hxx"
#include <svx/frmsel.hxx>
#include "bolnitem.hxx"
#include <svx/boxitem.hxx>
#include <svx/algitem.hxx>
#include <svx/shaditem.hxx>
namespace svx {
/* ============================================================================
SvxLineItem connection
----------------------
Connects an SvxLineItem (that contains the style of one line of a cell border)
with one frame border from a svx::FrameSelector control. If this connection is
used, no additional code is needed in the Reset() and FillItemSet() functions
of the tab page.
============================================================================ */
// 1st: item wrappers ---------------------------------------------------------
class LineItemWrapper : public sfx::SingleItemWrapper< SvxLineItem, const SvxBorderLine* >
{
public:
inline explicit LineItemWrapper( USHORT nSlot ) : SingleItemWrapperType( nSlot ) {}
virtual const SvxBorderLine* GetItemValue( const SvxLineItem& rItem ) const
{ return rItem.GetLine(); }
virtual void SetItemValue( SvxLineItem& rItem, const SvxBorderLine* pLine ) const
{ rItem.SetLine( pLine ); }
};
// 2nd: control wrappers ------------------------------------------------------
class FrameSelectorWrapper : public sfx::SingleControlWrapper< FrameSelector, const SvxBorderLine* >
{
public:
inline explicit FrameSelectorWrapper( FrameSelector& rFrameSel, FrameBorderType eBorder ) :
SingleControlWrapperType( rFrameSel ), meBorder( eBorder ) {}
virtual bool IsControlDontKnow() const;
virtual void SetControlDontKnow( bool bSet );
virtual const SvxBorderLine* GetControlValue() const;
virtual void SetControlValue( const SvxBorderLine* pLine );
private:
FrameBorderType meBorder; /// The line this wrapper works with.
};
bool FrameSelectorWrapper::IsControlDontKnow() const
{
return GetControl().GetFrameBorderState( meBorder ) == FRAMESTATE_DONTCARE;
}
void FrameSelectorWrapper::SetControlDontKnow( bool bSet )
{
if( bSet )
GetControl().SetBorderDontCare( meBorder );
}
const SvxBorderLine* FrameSelectorWrapper::GetControlValue() const
{
return GetControl().GetFrameBorderStyle( meBorder );
}
void FrameSelectorWrapper::SetControlValue( const SvxBorderLine* pLine )
{
GetControl().ShowBorder( meBorder, pLine );
}
// 3rd: connection ------------------------------------------------------------
typedef sfx::ItemControlConnection< LineItemWrapper, FrameSelectorWrapper > FrameLineConnection;
/* ============================================================================
SvxMarginItem connection
------------------------
Connects an SvxMarginItem (that contains the inner margin of all cell borders)
with the numerical edit controls of the SvxBorderTabPage. If this connection is
used, no additional code is needed in the Reset() and FillItemSet() functions
of the tab page.
============================================================================ */
// 1st: item wrappers ---------------------------------------------------------
typedef sfx::IdentItemWrapper< SvxMarginItem > MarginItemWrapper;
// 2nd: control wrappers ------------------------------------------------------
class MarginControlsWrapper : public sfx::MultiControlWrapper< SvxMarginItem >
{
public:
explicit MarginControlsWrapper(
MetricField& rMfLeft, MetricField& rMfRight,
MetricField& rMfTop, MetricField& rMfBottom );
virtual SvxMarginItem GetControlValue() const;
virtual void SetControlValue( SvxMarginItem aItem );
private:
sfx::Int16MetricFieldWrapper maLeftWrp;
sfx::Int16MetricFieldWrapper maRightWrp;
sfx::Int16MetricFieldWrapper maTopWrp;
sfx::Int16MetricFieldWrapper maBottomWrp;
};
MarginControlsWrapper::MarginControlsWrapper(
MetricField& rMfLeft, MetricField& rMfRight, MetricField& rMfTop, MetricField& rMfBottom ) :
maLeftWrp( rMfLeft, FUNIT_TWIP ),
maRightWrp( rMfRight, FUNIT_TWIP ),
maTopWrp( rMfTop, FUNIT_TWIP ),
maBottomWrp( rMfBottom, FUNIT_TWIP )
{
RegisterControlWrapper( maLeftWrp );
RegisterControlWrapper( maRightWrp );
RegisterControlWrapper( maTopWrp );
RegisterControlWrapper( maBottomWrp );
}
SvxMarginItem MarginControlsWrapper::GetControlValue() const
{
SvxMarginItem aItem( GetDefaultValue() );
if( !maLeftWrp.IsControlDontKnow() )
aItem.SetLeftMargin( maLeftWrp.GetControlValue() );
if( !maRightWrp.IsControlDontKnow() )
aItem.SetRightMargin( maRightWrp.GetControlValue() );
if( !maTopWrp.IsControlDontKnow() )
aItem.SetTopMargin( maTopWrp.GetControlValue() );
if( !maBottomWrp.IsControlDontKnow() )
aItem.SetBottomMargin( maBottomWrp.GetControlValue() );
return aItem;
}
void MarginControlsWrapper::SetControlValue( SvxMarginItem aItem )
{
maLeftWrp.SetControlValue( aItem.GetLeftMargin() );
maRightWrp.SetControlValue( aItem.GetRightMargin() );
maTopWrp.SetControlValue( aItem.GetTopMargin() );
maBottomWrp.SetControlValue( aItem.GetBottomMargin() );
}
// 3rd: connection ------------------------------------------------------------
class MarginConnection : public sfx::ItemControlConnection< MarginItemWrapper, MarginControlsWrapper >
{
public:
explicit MarginConnection( const SfxItemSet& rItemSet,
MetricField& rMfLeft, MetricField& rMfRight,
MetricField& rMfTop, MetricField& rMfBottom,
sfx::ItemConnFlags nFlags = sfx::ITEMCONN_DEFAULT );
};
MarginConnection::MarginConnection( const SfxItemSet& rItemSet,
MetricField& rMfLeft, MetricField& rMfRight, MetricField& rMfTop, MetricField& rMfBottom,
sfx::ItemConnFlags nFlags ) :
ItemControlConnectionType( SID_ATTR_ALIGN_MARGIN, new MarginControlsWrapper( rMfLeft, rMfRight, rMfTop, rMfBottom ), nFlags )
{
mxCtrlWrp->SetDefaultValue( maItemWrp.GetDefaultItem( rItemSet ) );
}
/* ============================================================================
SvxShadowItem connection
------------------------
Connects an SvxShadowItem (that contains shadow position, size, and color) with
the controls of the SvxBorderTabPage. If this connection is used, no additional
code is needed in the Reset() and FillItemSet() functions of the tab page.
============================================================================ */
// 1st: item wrappers ---------------------------------------------------------
typedef sfx::IdentItemWrapper< SvxShadowItem > ShadowItemWrapper;
// 2nd: control wrappers ------------------------------------------------------
typedef sfx::ValueSetWrapper< SvxShadowLocation > ShadowPosWrapper;
static const ShadowPosWrapper::MapEntryType s_pShadowPosMap[] =
{
{ 1, SVX_SHADOW_NONE },
{ 2, SVX_SHADOW_BOTTOMRIGHT },
{ 3, SVX_SHADOW_TOPRIGHT },
{ 4, SVX_SHADOW_BOTTOMLEFT },
{ 5, SVX_SHADOW_TOPLEFT },
{ VALUESET_ITEM_NOTFOUND, SVX_SHADOW_NONE }
};
class ShadowControlsWrapper : public sfx::MultiControlWrapper< SvxShadowItem >
{
public:
explicit ShadowControlsWrapper( ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor );
virtual SvxShadowItem GetControlValue() const;
virtual void SetControlValue( SvxShadowItem aItem );
private:
ShadowPosWrapper maPosWrp;
sfx::UShortMetricFieldWrapper maSizeWrp;
sfx::ColorListBoxWrapper maColorWrp;
};
ShadowControlsWrapper::ShadowControlsWrapper(
ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor ) :
maPosWrp( rVsPos, s_pShadowPosMap ),
maSizeWrp( rMfSize, FUNIT_TWIP ),
maColorWrp( rLbColor )
{
RegisterControlWrapper( maPosWrp );
RegisterControlWrapper( maSizeWrp );
RegisterControlWrapper( maColorWrp );
}
SvxShadowItem ShadowControlsWrapper::GetControlValue() const
{
SvxShadowItem aItem( GetDefaultValue() );
if( !maPosWrp.IsControlDontKnow() )
aItem.SetLocation( maPosWrp.GetControlValue() );
if( !maSizeWrp.IsControlDontKnow() )
aItem.SetWidth( maSizeWrp.GetControlValue() );
if( !maColorWrp.IsControlDontKnow() )
aItem.SetColor( maColorWrp.GetControlValue() );
return aItem;
}
void ShadowControlsWrapper::SetControlValue( SvxShadowItem aItem )
{
maPosWrp.SetControlValue( aItem.GetLocation() );
maSizeWrp.SetControlValue( aItem.GetWidth() );
maColorWrp.SetControlValue( aItem.GetColor() );
}
// 3rd: connection ------------------------------------------------------------
class ShadowConnection : public sfx::ItemControlConnection< ShadowItemWrapper, ShadowControlsWrapper >
{
public:
explicit ShadowConnection( const SfxItemSet& rItemSet,
ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor,
sfx::ItemConnFlags nFlags = sfx::ITEMCONN_DEFAULT );
};
ShadowConnection::ShadowConnection( const SfxItemSet& rItemSet,
ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor, sfx::ItemConnFlags nFlags ) :
ItemControlConnectionType( SID_ATTR_BORDER_SHADOW, new ShadowControlsWrapper( rVsPos, rMfSize, rLbColor ), nFlags )
{
mxCtrlWrp->SetDefaultValue( maItemWrp.GetDefaultItem( rItemSet ) );
}
// ============================================================================
// ============================================================================
sfx::ItemConnectionBase* CreateFrameLineConnection( USHORT nSlot,
FrameSelector& rFrameSel, FrameBorderType eBorder, sfx::ItemConnFlags nFlags )
{
return new FrameLineConnection( nSlot, new FrameSelectorWrapper( rFrameSel, eBorder ), nFlags );
}
sfx::ItemConnectionBase* CreateFrameBoxConnection( USHORT /*nBoxSlot*/, USHORT /*nBoxInfoSlot*/,
FrameSelector& /*rFrameSel*/, FrameBorderType /*eBorder*/, sfx::ItemConnFlags /*nFlags*/ )
{
DBG_ERRORFILE( "svx::CreateFrameBoxConnection - not implemented" );
return 0;
}
sfx::ItemConnectionBase* CreateMarginConnection( const SfxItemSet& rItemSet,
MetricField& rMfLeft, MetricField& rMfRight,
MetricField& rMfTop, MetricField& rMfBottom,
sfx::ItemConnFlags nFlags )
{
return new MarginConnection( rItemSet, rMfLeft, rMfRight, rMfTop, rMfBottom, nFlags );
}
sfx::ItemConnectionBase* CreateShadowConnection( const SfxItemSet& rItemSet,
ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor,
sfx::ItemConnFlags nFlags )
{
return new ShadowConnection( rItemSet, rVsPos, rMfSize, rLbColor, nFlags );
}
// ============================================================================
} // namespace svx
<|endoftext|> |
<commit_before>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
/****************************************************************************
NTAIO.cc
****************************************************************************/
#if !defined (_WIN_9xMe)
#include "P_AIO.h"
extern Continuation *aio_err_callbck;
// AIO Stats
extern uint64 aio_num_read;
extern uint64 aio_bytes_read;
extern uint64 aio_num_write;
extern uint64 aio_bytes_written;
NTIOCompletionPort aio_completion_port(1);
static inline void
init_op_sequence(AIOCallback * op, int opcode)
{
// zero aio_result's and init opcodes
AIOCallback *cur_op;
for (cur_op = op; cur_op; cur_op = cur_op->then) {
cur_op->aio_result = 0;
cur_op->aiocb.aio_lio_opcode = opcode;
// set the last op to point to the first op
if (cur_op->then == NULL)
((AIOCallbackInternal *) cur_op)->first = op;
}
}
static inline void
cache_op(AIOCallback * op)
{
DWORD bytes_trans;
// make op continuation share op->action's mutex
op->mutex = op->action.mutex;
// construct a continuation to handle the io completion
NTCompletionEvent *ce = NTCompletionEvent_alloc(op);
OVERLAPPED *overlapped = ce->get_overlapped();
overlapped->Offset = (unsigned long) (op->aiocb.aio_offset & 0xFFFFFFFF);
overlapped->OffsetHigh = (unsigned long)
(op->aiocb.aio_offset >> 32) & 0xFFFFFFFF;
// do the io
BOOL ret;
switch (op->aiocb.aio_lio_opcode) {
case LIO_READ:
ret = ReadFile((HANDLE) op->aiocb.aio_fildes,
op->aiocb.aio_buf, (unsigned long) op->aiocb.aio_nbytes, &bytes_trans, overlapped);
break;
case LIO_WRITE:
ret = WriteFile((HANDLE) op->aiocb.aio_fildes,
op->aiocb.aio_buf, (unsigned long) op->aiocb.aio_nbytes, &bytes_trans, overlapped);
break;
default:
ink_debug_assert(!"unknown aio_lio_opcode");
}
DWORD lerror = GetLastError();
if (ret == FALSE && lerror != ERROR_IO_PENDING) {
op->aio_result = -((int) lerror);
eventProcessor.schedule_imm(op);
}
}
int
ink_aio_read(AIOCallback * op)
{
init_op_sequence(op, LIO_READ);
cache_op(op);
return 1;
}
int
ink_aio_write(AIOCallback * op)
{
init_op_sequence(op, LIO_WRITE);
cache_op(op);
return 1;
}
struct AIOMissEvent:Continuation
{
AIOCallback *cb;
int mainEvent(int event, Event * e)
{
if (!cb->action.cancelled)
cb->action.continuation->handleEvent(AIO_EVENT_DONE, cb);
delete this;
return EVENT_DONE;
}
AIOMissEvent(ProxyMutex * amutex, AIOCallback * acb)
: Continuation(amutex), cb(acb)
{
SET_HANDLER(&AIOMissEvent::mainEvent);
}
};
int
AIOCallbackInternal::io_complete(int event, void *data)
{
int lerror;
NTCompletionEvent *ce = (NTCompletionEvent *) data;
// if aio_result is set, the original Read/Write call failed
if (!aio_result) {
lerror = ce->lerror;
aio_result = lerror ? -lerror : ce->_bytes_transferred;
}
// handle io errors
if ((lerror != 0) && aio_err_callbck) {
// schedule aio_err_callbck to be called-back
// FIXME: optimization, please... ^_^
AIOCallback *op = NEW(new AIOCallbackInternal());
op->aiocb.aio_fildes = aiocb.aio_fildes;
op->action = aio_err_callbck;
eventProcessor.schedule_imm(NEW(new AIOMissEvent(op->action.mutex, op)));
} else {
ink_debug_assert(ce->_bytes_transferred == aiocb.aio_nbytes);
}
if (then) {
// more op's in this sequence
cache_op(then);
} else {
// we're done! callback action
if (!first->action.cancelled) {
first->action.continuation->handleEvent(AIO_EVENT_DONE, first);
}
}
return 0;
}
#endif //_WIN_9xMe
<commit_msg>remove Windows ME conditional... don't think that is ever coming back :)<commit_after>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
/****************************************************************************
NTAIO.cc
****************************************************************************/
#include "P_AIO.h"
extern Continuation *aio_err_callbck;
// AIO Stats
extern uint64 aio_num_read;
extern uint64 aio_bytes_read;
extern uint64 aio_num_write;
extern uint64 aio_bytes_written;
NTIOCompletionPort aio_completion_port(1);
static inline void
init_op_sequence(AIOCallback * op, int opcode)
{
// zero aio_result's and init opcodes
AIOCallback *cur_op;
for (cur_op = op; cur_op; cur_op = cur_op->then) {
cur_op->aio_result = 0;
cur_op->aiocb.aio_lio_opcode = opcode;
// set the last op to point to the first op
if (cur_op->then == NULL)
((AIOCallbackInternal *) cur_op)->first = op;
}
}
static inline void
cache_op(AIOCallback * op)
{
DWORD bytes_trans;
// make op continuation share op->action's mutex
op->mutex = op->action.mutex;
// construct a continuation to handle the io completion
NTCompletionEvent *ce = NTCompletionEvent_alloc(op);
OVERLAPPED *overlapped = ce->get_overlapped();
overlapped->Offset = (unsigned long) (op->aiocb.aio_offset & 0xFFFFFFFF);
overlapped->OffsetHigh = (unsigned long)
(op->aiocb.aio_offset >> 32) & 0xFFFFFFFF;
// do the io
BOOL ret;
switch (op->aiocb.aio_lio_opcode) {
case LIO_READ:
ret = ReadFile((HANDLE) op->aiocb.aio_fildes,
op->aiocb.aio_buf, (unsigned long) op->aiocb.aio_nbytes, &bytes_trans, overlapped);
break;
case LIO_WRITE:
ret = WriteFile((HANDLE) op->aiocb.aio_fildes,
op->aiocb.aio_buf, (unsigned long) op->aiocb.aio_nbytes, &bytes_trans, overlapped);
break;
default:
ink_debug_assert(!"unknown aio_lio_opcode");
}
DWORD lerror = GetLastError();
if (ret == FALSE && lerror != ERROR_IO_PENDING) {
op->aio_result = -((int) lerror);
eventProcessor.schedule_imm(op);
}
}
int
ink_aio_read(AIOCallback * op)
{
init_op_sequence(op, LIO_READ);
cache_op(op);
return 1;
}
int
ink_aio_write(AIOCallback * op)
{
init_op_sequence(op, LIO_WRITE);
cache_op(op);
return 1;
}
struct AIOMissEvent:Continuation
{
AIOCallback *cb;
int mainEvent(int event, Event * e)
{
if (!cb->action.cancelled)
cb->action.continuation->handleEvent(AIO_EVENT_DONE, cb);
delete this;
return EVENT_DONE;
}
AIOMissEvent(ProxyMutex * amutex, AIOCallback * acb)
: Continuation(amutex), cb(acb)
{
SET_HANDLER(&AIOMissEvent::mainEvent);
}
};
int
AIOCallbackInternal::io_complete(int event, void *data)
{
int lerror;
NTCompletionEvent *ce = (NTCompletionEvent *) data;
// if aio_result is set, the original Read/Write call failed
if (!aio_result) {
lerror = ce->lerror;
aio_result = lerror ? -lerror : ce->_bytes_transferred;
}
// handle io errors
if ((lerror != 0) && aio_err_callbck) {
// schedule aio_err_callbck to be called-back
// FIXME: optimization, please... ^_^
AIOCallback *op = NEW(new AIOCallbackInternal());
op->aiocb.aio_fildes = aiocb.aio_fildes;
op->action = aio_err_callbck;
eventProcessor.schedule_imm(NEW(new AIOMissEvent(op->action.mutex, op)));
} else {
ink_debug_assert(ce->_bytes_transferred == aiocb.aio_nbytes);
}
if (then) {
// more op's in this sequence
cache_op(then);
} else {
// we're done! callback action
if (!first->action.cancelled) {
first->action.continuation->handleEvent(AIO_EVENT_DONE, first);
}
}
return 0;
}
<|endoftext|> |
<commit_before>#define _USE_MATH_DEFINES // for math constants in C++
#include <opencv2\calib3d\calib3d.hpp>
#include "DepthToPointTranslator1.h"
DepthToPointTranslator1::DepthToPointTranslator1(void)
{
}
DepthToPointTranslator1::~DepthToPointTranslator1(void)
{
}
oclMat DepthToPointTranslator1::translateDepthToPoints(const oclMat& depth,
const LightFieldPicture& lightfield) const
{
Mat depthMap, cameraMatrix, points;
depth.download(depthMap);
// 1) generate camera matrix
// rotation and translation are 0 => the camera matrix P is reduced to the
// calibration matrix K
const float width = depth.size().width;
const float height = depth.size().height;
const float cx = width / 2.; // (cx, cy) is the optical center)
const float cy = height / 2.;
const float fx = lightfield.getRawFocalLength(); // fx = f
const float fy = height / width * fx; // fy = aspectRatio * f
float K[4][4] = {
{ fx, 0, cx, 0 },
{ 0, fy, cy, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 1 }};
cameraMatrix = Mat(4, 4, CV_32FC1, K);
// 2) reproject image points with depth to 3d space
reprojectImageTo3D(depthMap, points, cameraMatrix.inv());
// 3) scale to compensate the shape of the microlens array
const float sx = 1. / lightfield.loader.scaleFactor[0];
const float sy = 1. / lightfield.loader.scaleFactor[1] * cos(M_PI / 3.);
const Scalar scale = Scalar(sx, sy, 1);
points = points.mul(scale);
return oclMat(points);
}<commit_msg>Replaced generation of calibration matrix. Matrix from LightFieldPicture used instead.<commit_after>#define _USE_MATH_DEFINES // for math constants in C++
#include <opencv2\calib3d\calib3d.hpp>
#include "CDCDepthEstimator.h"
#include "DepthToPointTranslator1.h"
DepthToPointTranslator1::DepthToPointTranslator1(void)
{
}
DepthToPointTranslator1::~DepthToPointTranslator1(void)
{
}
oclMat DepthToPointTranslator1::translateDepthToPoints(const oclMat& depth,
const LightFieldPicture& lightfield) const
{
Mat depthMap, cameraMatrix, roi, points;
depth.download(depthMap);
// 1) generate camera matrix
// rotation and translation are 0 => the camera matrix P is reduced to the
// calibration matrix K
cameraMatrix = Mat(4, 4, CV_32FC1, Scalar(0));
roi = cameraMatrix(Rect(0, 0, 3, 3));
lightfield.getCalibrationMatrix().copyTo(roi);
/*
const float width = depth.size().width;
const float height = depth.size().height;
const float cx = 0; // (cx, cy) is the optical center
const float cy = 0;
const float f = lightfield.loader.focalLength / lightfield.loader.pixelPitch;
const float aspectRatio = height / width;
const float fx = f;
const float fy = aspectRatio * f;
float K[4][4] = {
{ fx, 0, cx, 0 },
{ 0, fy, cy, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 1 }};
cameraMatrix = Mat(4, 4, CV_32FC1, K);
*/
// 2) reproject image points with depth to 3d space
reprojectImageTo3D(depthMap, points, cameraMatrix.inv());
// 3) scale to proper size
const float sx = 1.; // width / 2. * lightfield.loader.pixelPitch;
const float sy = -1.; // height / 2. * lightfield.loader.pixelPitch * cos(M_PI / 3.;)
const float sz = 1.; // / (float) CDCDepthEstimator::ALPHA_MAX;
const Scalar scale = Scalar(sx, sy, sz);
points = points.mul(scale);
return oclMat(points);
}<|endoftext|> |
<commit_before>/*
Conrad 'Condzi' Kubacki 2017
https://github.com/condzi
*/
#pragma once
#include <algorithm>
#include <cmath>
#include <cinttypes>
// std::move
#include <utility>
// For fancy AsString method.
#include <string>
// Conversion to SFML type vector.
#include <SFML/System/Vector2.hpp>
namespace con
{
template <typename T>
struct Vec2;
template <typename T>
struct Vec2
{
T x, y;
static const Vec2<T> Zero;
static const Vec2<T> One;
static const Vec2<T> Left;
static const Vec2<T> Right;
static const Vec2<T> Up;
static const Vec2<T> Down;
Vec2() :
x( 0 ), y( 0 )
{}
Vec2( T xx, T yy ) :
x( std::move( xx ) ),
y( std::move( yy ) )
{}
template <typename Y>
Vec2( Y xx, Y yy ) :
x( std::move( static_cast<T>( xx ) ) ),
y( std::move( static_cast<T>( yy ) ) )
{}
template <typename Y>
Vec2( Vec2<Y> second ) :
x( std::move( static_cast<T>( second.x ) ) ),
y( std::move( static_cast<T>( second.y ) ) )
{}
// Making Vec2 polymorphic makes it bigger by 4 bytes. (polymorphic size: 12 bytes, non polymorphic - 8)
#if !defined NO_POLYMORPHIC_VEC2
virtual ~Vec2() {}
#endif
void Set( T xx, T yy )
{
this->x = std::move( xx );
this->y = std::move( yy );
}
void Set( const Vec2<T>& second )
{
*this = second;
}
sf::Vector2<T> AsSFMLVec() const;
std::string AsString() const;
Vec2<T> GetAbs() const;
T GetMin() const;
T GetMax() const;
T Length() const;
T LengthSquared() const;
template <typename Y>
T DotProduct( const Vec2<Y>& second ) const;
template <typename Y>
T CrossProduct( const Vec2<Y>& second ) const;
static T DistanceSquared( const Vec2<T>& first, const Vec2<T>& second );
static T Distance( const Vec2<T>& first, const Vec2<T>& second );
Vec2<T> operator-() const;
template <typename Y>
Vec2<T> operator+( const Vec2<Y>& second ) const;
template <typename Y>
Vec2<T> operator-( const Vec2<Y>& second ) const;
template <typename Y>
Vec2<T> operator*( const Vec2<Y>& second ) const;
template <typename Y>
Vec2<T> operator/( const Vec2<Y>& second ) const;
template <typename Y>
Vec2<T> operator+( const Y value ) const;
template <typename Y>
Vec2<T> operator-( const Y value ) const;
template <typename Y>
Vec2<T> operator*( const Y value ) const;
template <typename Y>
Vec2<T> operator/( const Y value ) const;
template <typename Y>
Vec2<T> operator+=( const Vec2<Y>& second );
template <typename Y>
Vec2<T> operator-=( const Vec2<Y>& second );
template <typename Y>
Vec2<T> operator*=( const Vec2<Y>& second );
template <typename Y>
Vec2<T> operator/=( const Vec2<Y>& second );
template <typename Y>
Vec2<T> operator+=( const Y value );
template <typename Y>
Vec2<T> operator-=( const Y value );
template <typename Y>
Vec2<T> operator*=( const Y value );
template <typename Y>
Vec2<T> operator/=( const Y value );
template <typename Y>
bool operator==( const Vec2<Y>& second ) const;
template <typename Y>
bool operator!=( const Vec2<Y>& second ) const;
template <typename Y>
bool operator<( const Vec2<Y>& second ) const;
template <typename Y>
bool operator>( const Vec2<Y>& second ) const;
template <typename Y>
bool operator<=( const Vec2<Y>& second ) const;
template <typename Y>
bool operator>=( const Vec2<Y>& second ) const;
};
template <typename T>
const Vec2<T> Vec2<T>::Zero = Vec2<T>();
template <typename T>
const Vec2<T> Vec2<T>::One = Vec2<T>( 1, 1 );
template <typename T>
const Vec2<T> Vec2<T>::Left = Vec2<T>( -1, 0 );
template <typename T>
const Vec2<T> Vec2<T>::Right = Vec2<T>( 1, 0 );
template <typename T>
const Vec2<T> Vec2<T>::Up = Vec2<T>( 0, 1 );
template <typename T>
const Vec2<T> Vec2<T>::Down = Vec2<T>( 0, -1 );
template <typename T>
Vec2<T> operator+( const T left, const Vec2<T>& right );
template <typename T>
Vec2<T> operator-( const T left, const Vec2<T>& right );
template <typename T>
Vec2<T> operator*( const T left, const Vec2<T>& right );
template <typename T>
Vec2<T> operator/( const T left, const Vec2<T>& right );
#include <Core/Vec2.inl>
typedef Vec2<float> Vec2f;
typedef Vec2<int32_t> Vec2i;
typedef Vec2<uint32_t> Vec2u;
}<commit_msg>add Vec2 constructor from sf::Vector2<commit_after>/*
Conrad 'Condzi' Kubacki 2017
https://github.com/condzi
*/
#pragma once
#include <algorithm>
#include <cmath>
#include <cinttypes>
// std::move
#include <utility>
// For fancy AsString method.
#include <string>
// Conversion to SFML type vector.
#include <SFML/System/Vector2.hpp>
namespace con
{
template <typename T>
struct Vec2;
template <typename T>
struct Vec2
{
T x, y;
static const Vec2<T> Zero;
static const Vec2<T> One;
static const Vec2<T> Left;
static const Vec2<T> Right;
static const Vec2<T> Up;
static const Vec2<T> Down;
Vec2() :
x( 0 ), y( 0 )
{}
Vec2( T xx, T yy ) :
x( std::move( xx ) ),
y( std::move( yy ) )
{}
template <typename Y>
Vec2( Y xx, Y yy ) :
x( std::move( static_cast<T>( xx ) ) ),
y( std::move( static_cast<T>( yy ) ) )
{}
template <typename Y>
Vec2( const Vec2<Y> second ) :
x( std::move( static_cast<T>( second.x ) ) ),
y( std::move( static_cast<T>( second.y ) ) )
{}
Vec2( const sf::Vector2<T> second ) :
x( std::move( static_cast<T>( second.x ) ) ),
y( std::move( static_cast<T>( second.y ) ) )
{}
// Making Vec2 polymorphic makes it bigger by 4 bytes. (polymorphic size: 12 bytes, non polymorphic - 8)
#if !defined NO_POLYMORPHIC_VEC2
virtual ~Vec2() {}
#endif
void Set( T xx, T yy )
{
this->x = std::move( xx );
this->y = std::move( yy );
}
void Set( const Vec2<T>& second )
{
*this = second;
}
void Set( const sf::Vector2<T>& second )
{
this->Set( second.x, second.y );
}
sf::Vector2<T> AsSFMLVec() const;
std::string AsString() const;
Vec2<T> GetAbs() const;
T GetMin() const;
T GetMax() const;
T Length() const;
T LengthSquared() const;
template <typename Y>
T DotProduct( const Vec2<Y>& second ) const;
template <typename Y>
T CrossProduct( const Vec2<Y>& second ) const;
static T DistanceSquared( const Vec2<T>& first, const Vec2<T>& second );
static T Distance( const Vec2<T>& first, const Vec2<T>& second );
Vec2<T> operator-() const;
template <typename Y>
Vec2<T> operator+( const Vec2<Y>& second ) const;
template <typename Y>
Vec2<T> operator-( const Vec2<Y>& second ) const;
template <typename Y>
Vec2<T> operator*( const Vec2<Y>& second ) const;
template <typename Y>
Vec2<T> operator/( const Vec2<Y>& second ) const;
template <typename Y>
Vec2<T> operator+( const Y value ) const;
template <typename Y>
Vec2<T> operator-( const Y value ) const;
template <typename Y>
Vec2<T> operator*( const Y value ) const;
template <typename Y>
Vec2<T> operator/( const Y value ) const;
template <typename Y>
Vec2<T> operator+=( const Vec2<Y>& second );
template <typename Y>
Vec2<T> operator-=( const Vec2<Y>& second );
template <typename Y>
Vec2<T> operator*=( const Vec2<Y>& second );
template <typename Y>
Vec2<T> operator/=( const Vec2<Y>& second );
template <typename Y>
Vec2<T> operator+=( const Y value );
template <typename Y>
Vec2<T> operator-=( const Y value );
template <typename Y>
Vec2<T> operator*=( const Y value );
template <typename Y>
Vec2<T> operator/=( const Y value );
template <typename Y>
bool operator==( const Vec2<Y>& second ) const;
template <typename Y>
bool operator!=( const Vec2<Y>& second ) const;
template <typename Y>
bool operator<( const Vec2<Y>& second ) const;
template <typename Y>
bool operator>( const Vec2<Y>& second ) const;
template <typename Y>
bool operator<=( const Vec2<Y>& second ) const;
template <typename Y>
bool operator>=( const Vec2<Y>& second ) const;
};
template <typename T>
const Vec2<T> Vec2<T>::Zero = Vec2<T>();
template <typename T>
const Vec2<T> Vec2<T>::One = Vec2<T>( 1, 1 );
template <typename T>
const Vec2<T> Vec2<T>::Left = Vec2<T>( -1, 0 );
template <typename T>
const Vec2<T> Vec2<T>::Right = Vec2<T>( 1, 0 );
template <typename T>
const Vec2<T> Vec2<T>::Up = Vec2<T>( 0, 1 );
template <typename T>
const Vec2<T> Vec2<T>::Down = Vec2<T>( 0, -1 );
template <typename T>
Vec2<T> operator+( const T left, const Vec2<T>& right );
template <typename T>
Vec2<T> operator-( const T left, const Vec2<T>& right );
template <typename T>
Vec2<T> operator*( const T left, const Vec2<T>& right );
template <typename T>
Vec2<T> operator/( const T left, const Vec2<T>& right );
#include <Core/Vec2.inl>
typedef Vec2<float> Vec2f;
typedef Vec2<int32_t> Vec2i;
typedef Vec2<uint32_t> Vec2u;
}<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <stdexcept>
#include "grammar.hpp"
void gen_seq(Grammar &g, unsigned k, const std::string& str);
int main(int argc, char **argv) {
int n;
if (argc < 3 || (n = std::stoi(argv[1])) < 0) {
std::cerr << "Usage: " << argv[0]
<< " number_of_iterations [rules]\n"
<< " rule = probability char string\n";
return 1;
}
Grammar g(argv[2]);
argc -= 3;
argv += 3;
double prob;
while (argc) {
try {
prob = std::stod(argv[0]);
} catch (const std::invalid_argument &e) {
std::cerr << "grammargen error: "
<< argv[0] << " is not a positive number\n";
return 1;
}
if (prob <= 0) {
std::cerr << "grammargen error: "
<< argv[0] << " is not a positive number\n";
return 1;
}
g.addRule(argv[1][0], argv[2], prob);
argc -= 3;
argv += 3;
}
gen_seq(g, n, g.axiom);
std::cout << std::endl;
return 0;
}
void gen_seq(Grammar &g, unsigned k, const std::string& str)
{
if (k) {
for(const auto& ch : str) {
if(g.hasRule(ch)) {
gen_seq(g, k-1, g(ch));
} else {
std::cout << ch;
}
}
} else {
std::cout << str;
}
}
<commit_msg>update<commit_after>#include <iostream>
#include <string>
#include <stdexcept>
#include "grammar.hpp"
void gen_seq(Grammar &g, unsigned k, const std::string& str);
int main(int argc, char **argv) {
int n;
if (argc < 3 || argc % 3 != 0 || (n = std::stoi(argv[1])) < 0) {
std::cerr << "Usage: " << argv[0]
<< " number_of_iterations [rules]\n"
<< " rule = probability char string\n";
return 1;
}
Grammar g(argv[2]);
argc -= 3;
argv += 3;
double prob;
while (argc) {
try {
prob = std::stod(argv[0]);
} catch (const std::invalid_argument &e) {
std::cerr << "grammargen error: "
<< argv[0] << " is not a positive number\n";
return 1;
}
if (prob <= 0) {
std::cerr << "grammargen error: "
<< argv[0] << " is not a positive number\n";
return 1;
}
g.addRule(argv[1][0], argv[2], prob);
argc -= 3;
argv += 3;
}
gen_seq(g, n, g.axiom);
std::cout << std::endl;
return 0;
}
void gen_seq(Grammar &g, unsigned k, const std::string& str)
{
if (k) {
for(const auto& ch : str) {
if(g.hasRule(ch)) {
gen_seq(g, k-1, g(ch));
} else {
std::cout << ch;
}
}
} else {
std::cout << str;
}
}
<|endoftext|> |
<commit_before>#include "ModI2CHost.h"
CModI2CHost::CModI2CHost(void)
{
// nothing
}
void CModI2CHost::Begin(void)
{
CModTemplate::Begin();
ModGUID = 8; // GUID of this sspecific mod
if (Global.HasUSB) // i2c host only activates if this device is plugged into the PC
{
Wire.begin();
}
}
void CModI2CHost::LoadData(void)
{
CModTemplate::LoadData();
if (Global.HasUSB)
{
}
}
void CModI2CHost::Loop(void)
{
CModTemplate::Loop();
if (Global.HasUSB)
{
// syncs templayer value with guest
if (Global.TempLayer != I2CTempLayer)
{
SetTempLayer();
I2CTempLayer = Global.TempLayer;
}
if (Global.LEDBrightness != I2CLEDBrightness)
{
SetSubLEDBrightness();
I2CLEDBrightness = Global.LEDBrightness;
}
if (Global.RefreshDelay != I2CRefresh)
{
SetSubRefreshRate();
I2CRefresh = Global.RefreshDelay;
}
// gets keystrokes from guest
Wire.requestFrom(8, 32);
bool hasInput = true;
byte keyData[8];
byte keyType[8];
byte keyMode[8];
byte keyX[8];
byte keyY[8];
byte keyIndex = 0;
while (hasInput)
{
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
byte tempByte = Wire.read();
keyX[keyIndex] = tempByte & 0x0f; // bitwise structure is YYYYXXXX
keyY[keyIndex] = tempByte >> 4;
}
else
{
hasInput = false;
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyData[keyIndex] = Wire.read();
}
else
{
hasInput = false;
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyType[keyIndex] = Wire.read();
}
else
{
hasInput = false;
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyMode[keyIndex] = Wire.read();
keyIndex++;
}
else
{
hasInput = false;
}
}
for (byte i = 0; i < keyIndex; i++)
{
if (keyMode[i] == 1) // release key
{
Animus.ReleaseKey(keyData[i], keyType[i]);
}
else if (keyMode[i] == 5) // press key
{
Animus.PrePress(keyData[i], keyType[i]);
if (Global.TempLayer != I2CTempLayer)
{
SetTempLayer();
I2CTempLayer = Global.TempLayer;
Wire.beginTransmission(8);
Wire.write(6);
Wire.write(keyX[i]);
Wire.write(keyY[i]);
Wire.endTransmission();
Wire.requestFrom(8, 2);
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyData[i] = Wire.read();
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyType[i] = Wire.read();
}
}
Animus.PressKey(keyData[i], keyType[i]);
}
}
}
if (Animus.Async1MSDelay())
{
if (Global.HasUSB)
{
}
}
}
void CModI2CHost::PressCoords(byte x, byte y)
{
CModTemplate::PressCoords(x, y);
if (Global.HasUSB)
{
}
}
void CModI2CHost::PrePress(byte val, byte type)
{
CModTemplate::PrePress(val, type);
if (Global.HasUSB)
{
}
}
void CModI2CHost::PressKey(byte val, byte type)
{
CModTemplate::PressKey(val, type);
if (Global.HasUSB)
{
}
}
void CModI2CHost::ReleaseKey(byte val, byte type)
{
CModTemplate::ReleaseKey(val, type);
if (Global.HasUSB)
{
}
}
void CModI2CHost::SerialComms(byte mode) // holy shit this is complicated
{
CModTemplate::SerialComms(mode);
// serial communication
if (Global.HasUSB)
{
if (Comms.mode == 6) // write to guest eeprom starting at addr = 0 or 900, ending at first short read from serial
{
PersMem.SetEEPROM(0, 5);
if (Serial.available()) //TODO I might want to work in a timeout or fail check for this
{
if (SerialLoaderByteStatus == 0) // if this is the first time mode 6 has made contact
{
EEPROMPacket[0] = (byte)Serial.read();
SerialLoaderByteStatus = 1;
}
else if (SerialLoaderByteStatus == 1) // if this is the second time mode 6 has made contact
{
EEPROMPacket[1] = (byte)Serial.read();
SerialLoaderByteStatus = 2;
}
else if (SerialLoaderByteStatus == 2) // if status is 2, get packet size
{
EEPROMPacketSize = (byte)Serial.read();
SerialLoaderByteStatus = 3;
}
else if (SerialLoaderByteStatus == 3) // if mode 6 has obtained the start address and package length
{
if (EEPROMPacketSize > 0)
{
EEPROMPacket[EEPROMPacketIndex] = (byte)Serial.read();
EEPROMPacketIndex++;
EEPROMPacketSize--;
}
if (EEPROMPacketSize <= 0)
{
SetSubEEPROM();
EEPROMPacketIndex = 2;
SerialLoaderByteStatus = 0;
Comms.mode = 0;
}
}
}
}
else if (Comms.mode == 7) // request read sub EEPROM
{
short addr = 0;
while(addr < 1024)
{
GetSubEEPROM(addr);
Wire.requestFrom(8, 32);
while(Wire.available())
{
Serial.println(Wire.read());
}
addr = addr + 32;
}
Comms.mode = 0;
}
}
}
void CModI2CHost::SetTempLayer()
{
Wire.beginTransmission(8);
Wire.write(1);
Wire.write(Global.TempLayer);
Wire.endTransmission();
}
void CModI2CHost::SetSubEEPROM(void)
{
Wire.beginTransmission(8);
Wire.write(2);
Wire.write(EEPROMPacket, EEPROMPacketIndex);
Wire.endTransmission();
}
void CModI2CHost::GetSubEEPROM(short startAddr)
{
Wire.beginTransmission(8);
Wire.write(3);
byte byteA = startAddr >> 8; // this gets the bytes 1111111100000000
byte byteB = startAddr & 0xff; // this gets the bytes 0000000011111111
Wire.write(byteA);
Wire.write(byteB);
Wire.endTransmission();
}
void CModI2CHost::SetSubLEDBrightness(void)
{
Wire.beginTransmission(8);
Wire.write(4);
Wire.write(Global.LEDBrightness);
Wire.endTransmission();
}
void CModI2CHost::SetSubRefreshRate(void)
{
Wire.beginTransmission(8);
Wire.write(5);
Wire.write(Global.RefreshDelay);
Wire.endTransmission();
}
CModI2CHost ModI2CHost;
<commit_msg>add: i2c master comments<commit_after>#include "ModI2CHost.h"
CModI2CHost::CModI2CHost(void)
{
// nothing
}
void CModI2CHost::Begin(void)
{
CModTemplate::Begin();
ModGUID = 8; // GUID of this sspecific mod
if (Global.HasUSB) // i2c host only activates if this device is plugged into the PC
{
Wire.begin();
}
}
void CModI2CHost::LoadData(void)
{
CModTemplate::LoadData();
if (Global.HasUSB)
{
}
}
void CModI2CHost::Loop(void)
{
CModTemplate::Loop();
if (Global.HasUSB)
{
// syncs templayer value with guest
if (Global.TempLayer != I2CTempLayer)
{
SetTempLayer();
I2CTempLayer = Global.TempLayer;
}
if (Global.LEDBrightness != I2CLEDBrightness)
{
SetSubLEDBrightness();
I2CLEDBrightness = Global.LEDBrightness;
}
if (Global.RefreshDelay != I2CRefresh)
{
SetSubRefreshRate();
I2CRefresh = Global.RefreshDelay;
}
// gets keystrokes from guest
Wire.requestFrom(8, 32);
bool hasInput = true;
byte keyData[8];
byte keyType[8];
byte keyMode[8];
byte keyX[8];
byte keyY[8];
byte keyIndex = 0;
while (hasInput)
{
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
// gets XY coords for pressed key
byte tempByte = Wire.read();
keyX[keyIndex] = tempByte & 0x0f; // bitwise structure is YYYYXXXX
keyY[keyIndex] = tempByte >> 4;
}
else
{
hasInput = false;
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyData[keyIndex] = Wire.read();
}
else
{
hasInput = false;
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyType[keyIndex] = Wire.read();
}
else
{
hasInput = false;
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyMode[keyIndex] = Wire.read();
keyIndex++;
}
else
{
hasInput = false;
}
}
for (byte i = 0; i < keyIndex; i++)
{
if (keyMode[i] == 1) // release key
{
Animus.ReleaseKey(keyData[i], keyType[i]);
}
else if (keyMode[i] == 5) // press key
{
Animus.PrePress(keyData[i], keyType[i]);
if (Global.TempLayer != I2CTempLayer)
{
SetTempLayer();
I2CTempLayer = Global.TempLayer;
Wire.beginTransmission(8);
Wire.write(6);
Wire.write(keyX[i]);
Wire.write(keyY[i]);
Wire.endTransmission();
Wire.requestFrom(8, 2);
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyData[i] = Wire.read();
}
if (Wire.available()) // need to put ifs in here so trailing bytes are left out
{
keyType[i] = Wire.read();
}
}
Animus.PressKey(keyData[i], keyType[i]);
}
}
}
if (Animus.Async1MSDelay())
{
if (Global.HasUSB)
{
}
}
}
void CModI2CHost::PressCoords(byte x, byte y)
{
CModTemplate::PressCoords(x, y);
if (Global.HasUSB)
{
}
}
void CModI2CHost::PrePress(byte val, byte type)
{
CModTemplate::PrePress(val, type);
if (Global.HasUSB)
{
}
}
void CModI2CHost::PressKey(byte val, byte type)
{
CModTemplate::PressKey(val, type);
if (Global.HasUSB)
{
}
}
void CModI2CHost::ReleaseKey(byte val, byte type)
{
CModTemplate::ReleaseKey(val, type);
if (Global.HasUSB)
{
}
}
void CModI2CHost::SerialComms(byte mode) // holy shit this is complicated
{
CModTemplate::SerialComms(mode);
// serial communication
if (Global.HasUSB)
{
if (Comms.mode == 6) // write to guest eeprom starting at addr = 0 or 900, ending at first short read from serial
{
PersMem.SetEEPROM(0, 5);
if (Serial.available()) //TODO I might want to work in a timeout or fail check for this
{
if (SerialLoaderByteStatus == 0) // if this is the first time mode 6 has made contact
{
EEPROMPacket[0] = (byte)Serial.read();
SerialLoaderByteStatus = 1;
}
else if (SerialLoaderByteStatus == 1) // if this is the second time mode 6 has made contact
{
EEPROMPacket[1] = (byte)Serial.read();
SerialLoaderByteStatus = 2;
}
else if (SerialLoaderByteStatus == 2) // if status is 2, get packet size
{
EEPROMPacketSize = (byte)Serial.read();
SerialLoaderByteStatus = 3;
}
else if (SerialLoaderByteStatus == 3) // if mode 6 has obtained the start address and package length
{
if (EEPROMPacketSize > 0)
{
EEPROMPacket[EEPROMPacketIndex] = (byte)Serial.read();
EEPROMPacketIndex++;
EEPROMPacketSize--;
}
if (EEPROMPacketSize <= 0)
{
SetSubEEPROM();
EEPROMPacketIndex = 2;
SerialLoaderByteStatus = 0;
Comms.mode = 0;
}
}
}
}
else if (Comms.mode == 7) // request read sub EEPROM
{
short addr = 0;
while(addr < 1024)
{
GetSubEEPROM(addr);
Wire.requestFrom(8, 32);
while(Wire.available())
{
Serial.println(Wire.read());
}
addr = addr + 32;
}
Comms.mode = 0;
}
}
}
void CModI2CHost::SetTempLayer()
{
Wire.beginTransmission(8);
Wire.write(1);
Wire.write(Global.TempLayer);
Wire.endTransmission();
}
void CModI2CHost::SetSubEEPROM(void)
{
Wire.beginTransmission(8);
Wire.write(2);
Wire.write(EEPROMPacket, EEPROMPacketIndex);
Wire.endTransmission();
}
void CModI2CHost::GetSubEEPROM(short startAddr)
{
Wire.beginTransmission(8);
Wire.write(3);
byte byteA = startAddr >> 8; // this gets the bytes 1111111100000000
byte byteB = startAddr & 0xff; // this gets the bytes 0000000011111111
Wire.write(byteA);
Wire.write(byteB);
Wire.endTransmission();
}
void CModI2CHost::SetSubLEDBrightness(void)
{
Wire.beginTransmission(8);
Wire.write(4);
Wire.write(Global.LEDBrightness);
Wire.endTransmission();
}
void CModI2CHost::SetSubRefreshRate(void)
{
Wire.beginTransmission(8);
Wire.write(5);
Wire.write(Global.RefreshDelay);
Wire.endTransmission();
}
CModI2CHost ModI2CHost;
<|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/autofill/autofill_metrics.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
AutofillMetrics::AutofillMetrics() {
}
AutofillMetrics::~AutofillMetrics() {
}
void AutofillMetrics::Log(CreditCardInfoBarMetric metric) const {
DCHECK(metric < NUM_CREDIT_CARD_INFO_BAR_METRICS);
UMA_HISTOGRAM_ENUMERATION("Autofill.CreditCardInfoBar", metric,
NUM_CREDIT_CARD_INFO_BAR_METRICS);
}
void AutofillMetrics::Log(HeuristicTypeQualityMetric metric) const {
DCHECK(metric < NUM_HEURISTIC_TYPE_QUALITY_METRICS);
UMA_HISTOGRAM_ENUMERATION("Autofill.Quality.HeuristicType", metric,
NUM_HEURISTIC_TYPE_QUALITY_METRICS);
}
void AutofillMetrics::Log(PredictedTypeQualityMetric metric,
const std::string& experiment_id) const {
DCHECK(metric < NUM_PREDICTED_TYPE_QUALITY_METRICS);
std::string histogram_name = "Autofill.Quality.PredictedType";
if (!experiment_id.empty())
histogram_name += "_" + experiment_id;
UMA_HISTOGRAM_ENUMERATION(histogram_name, metric,
NUM_PREDICTED_TYPE_QUALITY_METRICS);
}
void AutofillMetrics::Log(QualityMetric metric,
const std::string& experiment_id) const {
DCHECK(metric < NUM_QUALITY_METRICS);
std::string histogram_name = "Autofill.Quality";
if (!experiment_id.empty())
histogram_name += "_" + experiment_id;
UMA_HISTOGRAM_ENUMERATION(histogram_name, metric, NUM_QUALITY_METRICS);
}
void AutofillMetrics::Log(ServerQueryMetric metric) const {
DCHECK(metric < NUM_SERVER_QUERY_METRICS);
UMA_HISTOGRAM_ENUMERATION("Autofill.ServerQueryResponse", metric,
NUM_SERVER_QUERY_METRICS);
}
void AutofillMetrics::Log(ServerTypeQualityMetric metric,
const std::string& experiment_id) const {
DCHECK(metric < NUM_SERVER_TYPE_QUALITY_METRICS);
std::string histogram_name = "Autofill.Quality.ServerType";
if (!experiment_id.empty())
histogram_name += "_" + experiment_id;
UMA_HISTOGRAM_ENUMERATION(histogram_name, metric,
NUM_SERVER_TYPE_QUALITY_METRICS);
}
void AutofillMetrics::LogStoredProfileCount(size_t num_profiles) const {
UMA_HISTOGRAM_COUNTS("Autofill.StoredProfileCount", num_profiles);
}
void AutofillMetrics::LogAddressSuggestionsCount(size_t num_suggestions) const {
UMA_HISTOGRAM_COUNTS("Autofill.AddressSuggestionsCount", num_suggestions);
}
<commit_msg>Unroll Autofill metrics macros, since the metric names can vary over time.<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/autofill/autofill_metrics.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
namespace {
void LogUMAHistogramEnumeration(const std::string& name,
int sample,
int boundary_value) {
// We can't use the UMA_HISTOGRAM_ENUMERATION macro here because the histogram
// name can vary over the duration of the program.
// Note that this leaks memory; that is expected behavior.
base::Histogram* counter =
base::LinearHistogram::FactoryGet(
name,
1,
boundary_value,
boundary_value + 1,
base::Histogram::kUmaTargetedHistogramFlag);
counter->Add(sample);
}
} // namespace
AutofillMetrics::AutofillMetrics() {
}
AutofillMetrics::~AutofillMetrics() {
}
void AutofillMetrics::Log(CreditCardInfoBarMetric metric) const {
DCHECK(metric < NUM_CREDIT_CARD_INFO_BAR_METRICS);
UMA_HISTOGRAM_ENUMERATION("Autofill.CreditCardInfoBar", metric,
NUM_CREDIT_CARD_INFO_BAR_METRICS);
}
void AutofillMetrics::Log(HeuristicTypeQualityMetric metric) const {
DCHECK(metric < NUM_HEURISTIC_TYPE_QUALITY_METRICS);
UMA_HISTOGRAM_ENUMERATION("Autofill.Quality.HeuristicType", metric,
NUM_HEURISTIC_TYPE_QUALITY_METRICS);
}
void AutofillMetrics::Log(PredictedTypeQualityMetric metric,
const std::string& experiment_id) const {
DCHECK(metric < NUM_PREDICTED_TYPE_QUALITY_METRICS);
std::string histogram_name = "Autofill.Quality.PredictedType";
if (!experiment_id.empty())
histogram_name += "_" + experiment_id;
LogUMAHistogramEnumeration(histogram_name, metric,
NUM_PREDICTED_TYPE_QUALITY_METRICS);
}
void AutofillMetrics::Log(QualityMetric metric,
const std::string& experiment_id) const {
DCHECK(metric < NUM_QUALITY_METRICS);
std::string histogram_name = "Autofill.Quality";
if (!experiment_id.empty())
histogram_name += "_" + experiment_id;
LogUMAHistogramEnumeration(histogram_name, metric, NUM_QUALITY_METRICS);
}
void AutofillMetrics::Log(ServerQueryMetric metric) const {
DCHECK(metric < NUM_SERVER_QUERY_METRICS);
UMA_HISTOGRAM_ENUMERATION("Autofill.ServerQueryResponse", metric,
NUM_SERVER_QUERY_METRICS);
}
void AutofillMetrics::Log(ServerTypeQualityMetric metric,
const std::string& experiment_id) const {
DCHECK(metric < NUM_SERVER_TYPE_QUALITY_METRICS);
std::string histogram_name = "Autofill.Quality.ServerType";
if (!experiment_id.empty())
histogram_name += "_" + experiment_id;
LogUMAHistogramEnumeration(histogram_name, metric,
NUM_SERVER_TYPE_QUALITY_METRICS);
}
void AutofillMetrics::LogStoredProfileCount(size_t num_profiles) const {
UMA_HISTOGRAM_COUNTS("Autofill.StoredProfileCount", num_profiles);
}
void AutofillMetrics::LogAddressSuggestionsCount(size_t num_suggestions) const {
UMA_HISTOGRAM_COUNTS("Autofill.AddressSuggestionsCount", num_suggestions);
}
<|endoftext|> |
<commit_before>#include "xchainer/python/array.h"
#include <algorithm>
#include <cstdint>
#include <string>
#include <vector>
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include <nonstd/optional.hpp>
#include "xchainer/array.h"
#include "xchainer/array_index.h"
#include "xchainer/backward.h"
#include "xchainer/constant.h"
#include "xchainer/context.h"
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/indexable_array.h"
#include "xchainer/indexer.h"
#include "xchainer/native/native_backend.h"
#include "xchainer/routines/creation.h"
#include "xchainer/routines/manipulation.h"
#include "xchainer/slice.h"
#include "xchainer/python/array_index.h"
#include "xchainer/python/common.h"
#include "xchainer/python/device.h"
#include "xchainer/python/shape.h"
#include "xchainer/python/strides.h"
namespace xchainer {
namespace python {
namespace internal {
namespace py = pybind11;
namespace {
Dtype NumpyDtypeToDtype(const py::dtype& npdtype) {
switch (npdtype.kind()) {
case 'b':
return Dtype::kBool;
case 'i':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kInt8;
case 2:
return Dtype::kInt16;
case 4:
return Dtype::kInt32;
case 8:
return Dtype::kInt64;
default:
break;
}
break;
case 'u':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kUInt8;
default:
break;
}
break;
case 'f':
switch (npdtype.itemsize()) {
case 4:
return Dtype::kFloat32;
case 8:
return Dtype::kFloat64;
default:
break;
}
break;
default:
break;
}
throw DtypeError("unsupported NumPy dtype");
}
ArrayBodyPtr MakeArray(const py::tuple& shape_tup, Dtype dtype, const py::list& list, const nonstd::optional<std::string>& device_id) {
Shape shape = ToShape(shape_tup);
auto total_size = shape.GetTotalSize();
auto bytes = GetElementSize(dtype) * total_size;
if (static_cast<size_t>(total_size) != list.size()) {
throw DimensionError("Invalid data length");
}
// Allocate a buffer and copy data
std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
VisitDtype(dtype, [&](auto pt) {
using T = typename decltype(pt)::type;
std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
});
return Array::FromBuffer(shape, dtype, ptr, GetDevice(device_id)).move_body();
}
ArrayBodyPtr MakeArray(py::array array, const nonstd::optional<std::string>& device_id) {
Dtype dtype = NumpyDtypeToDtype(array.dtype());
const py::buffer_info& info = array.request();
Shape shape{info.shape};
Strides strides{info.strides};
// data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released
void* underlying_data = array.mutable_data();
std::shared_ptr<void> data{std::make_shared<py::array>(std::move(array)), underlying_data};
return xchainer::internal::FromBuffer(shape, dtype, data, strides, GetDevice(device_id)).move_body();
}
py::buffer_info MakeNumpyArrayFromArray(ArrayBody& self) {
// Used as a temporary accessor
Array array{ArrayBodyPtr(&self, [](ArrayBody* ptr) {
(void)ptr; // unused
})};
return py::buffer_info(
array.data().get(),
array.element_bytes(),
std::string(1, GetCharCode(array.dtype())),
array.ndim(),
array.shape(),
array.strides());
}
} // namespace
void InitXchainerArray(pybind11::module& m) {
py::class_<ArrayBody, ArrayBodyPtr> c{m, "Array", py::buffer_protocol()};
c.def(py::init(py::overload_cast<const py::tuple&, Dtype, const py::list&, const nonstd::optional<std::string>&>(&MakeArray)),
py::arg("shape"),
py::arg("dtype"),
py::arg("data"),
py::arg("device") = nullptr);
c.def(py::init(py::overload_cast<py::array, const nonstd::optional<std::string>&>(&MakeArray)),
py::arg("data"),
py::arg("device") = nullptr);
// TODO(niboshi): We cannot support buffer protocol for general device. Remove the binding and provide alternative interface
// to convert to NumPy array.
c.def_buffer(&MakeNumpyArrayFromArray);
c.def("__bool__", [](const ArrayBodyPtr& self) -> bool { return static_cast<bool>(AsScalar(Array{self})); });
c.def("__int__", [](const ArrayBodyPtr& self) -> int64_t { return static_cast<int64_t>(AsScalar(Array{self})); });
c.def("__float__", [](const ArrayBodyPtr& self) -> double { return static_cast<double>(AsScalar(Array{self})); });
c.def("view", [](const ArrayBodyPtr& self) {
// Duplicate the array body
return std::make_shared<ArrayBody>(*self);
});
c.def("__repr__", [](const ArrayBodyPtr& self) { return Array{self}.ToString(); });
c.def("to_device", [](const ArrayBodyPtr& self, Device& device) { return Array{self}.ToDevice(device).move_body(); });
c.def("to_device", [](const ArrayBodyPtr& self, const std::string& device_name) {
Device& device = GetDefaultContext().GetDevice({device_name});
return Array{self}.ToDevice(device).move_body();
});
c.def("to_device", [](const ArrayBodyPtr& self, const std::string& backend_name, int index) {
Device& device = GetDefaultContext().GetDevice({backend_name, index});
return Array{self}.ToDevice(device).move_body();
});
c.def("as_constant",
[](const ArrayBodyPtr& self, bool copy) { return Array{self}.AsConstant(copy ? CopyKind::kCopy : CopyKind::kView).move_body(); },
py::arg("copy") = false);
c.def("as_constant",
[](const ArrayBodyPtr& self, const std::vector<GraphId>& graph_ids, bool copy) {
return Array{self}.AsConstant(graph_ids, copy ? CopyKind::kCopy : CopyKind::kView).move_body();
},
py::arg().noconvert(),
py::arg("copy") = false);
c.def("copy", [](const ArrayBodyPtr& self) { return Array{self}.Copy().move_body(); });
c.def("__getitem__", [](const ArrayBodyPtr& self, py::handle handle) {
return Array{self}.At(python::internal::MakeArrayIndices(handle)).move_body();
});
c.def("transpose", [](const ArrayBodyPtr& self) { return Array{self}.Transpose().move_body(); });
c.def("reshape", [](const ArrayBodyPtr& self, py::tuple shape) { return Array{self}.Reshape(ToShape(shape)).move_body(); });
c.def("reshape", [](const ArrayBodyPtr& self, const std::vector<int64_t>& shape) {
return Array{self}.Reshape({shape.begin(), shape.end()}).move_body();
});
c.def("reshape", [](const ArrayBodyPtr& self, py::args args) {
auto shape = py::cast<std::vector<int64_t>>(args);
return Array{self}.Reshape({shape.begin(), shape.end()}).move_body();
});
c.def("__eq__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} == Array{rhs}).move_body(); });
c.def("__iadd__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} += Array{rhs}).move_body(); });
c.def("__imul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} *= Array{rhs}).move_body(); });
c.def("__add__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} + Array{rhs}).move_body(); });
c.def("__mul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} * Array{rhs}).move_body(); });
c.def("__mul__", [](const ArrayBodyPtr& self, Scalar rhs) { return (Array{self} * rhs).move_body(); });
c.def("__rmul__", [](const ArrayBodyPtr& self, Scalar lhs) { return (lhs * Array{self}).move_body(); });
c.def("sum",
[](const ArrayBodyPtr& self, int8_t axis, bool keepdims) {
return Array{self}.Sum(std::vector<int8_t>{axis}, keepdims).move_body();
},
py::arg("axis"),
py::arg("keepdims") = false);
c.def("sum",
[](const ArrayBodyPtr& self, nonstd::optional<std::vector<int8_t>> axis, bool keepdims) {
return Array{self}.Sum(axis, keepdims).move_body();
},
py::arg("axis") = nullptr,
py::arg("keepdims") = false);
c.def("require_grad",
[](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.RequireGrad(graph_id).move_body(); },
py::arg("graph_id") = kDefaultGraphId);
c.def("is_grad_required",
[](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.IsGradRequired(graph_id); },
py::arg("graph_id") = kDefaultGraphId);
c.def("get_grad",
[](const ArrayBodyPtr& self, const GraphId& graph_id) -> ConstArrayBodyPtr {
const nonstd::optional<Array>& grad = Array{self}.GetGrad(graph_id);
if (!grad.has_value()) {
return nullptr;
}
return grad->body();
},
py::arg("graph_id") = kDefaultGraphId);
c.def("set_grad",
[](const ArrayBodyPtr& self, const ArrayBodyPtr& grad, const GraphId& graph_id) {
auto array = Array{self};
if (grad) {
array.SetGrad(Array{grad}, graph_id);
} else {
array.ClearGrad(graph_id);
}
},
py::arg("grad"),
py::arg("graph_id") = kDefaultGraphId);
c.def("backward",
[](const ArrayBodyPtr& self, const GraphId& graph_id, bool enable_double_backprop) {
Array array{self};
auto double_backprop = enable_double_backprop ? DoubleBackpropOption::kEnable : DoubleBackpropOption::kDisable;
Backward(array, graph_id, double_backprop);
},
py::arg("graph_id") = kDefaultGraphId,
py::arg("enable_double_backprop") = false);
c.def_property(
"grad",
[](const ArrayBodyPtr& self) -> ConstArrayBodyPtr {
const nonstd::optional<Array>& grad = Array{self}.GetGrad(kDefaultGraphId);
if (!grad.has_value()) {
return nullptr;
}
return grad->body();
},
[](const ArrayBodyPtr& self, const ArrayBodyPtr& grad) {
auto array = Array{self};
if (grad) {
array.SetGrad(Array{grad}, kDefaultGraphId);
} else {
array.ClearGrad(kDefaultGraphId);
}
});
c.def("cleargrad",
[](const ArrayBodyPtr& self, const GraphId& graph_id) { Array{self}.ClearGrad(graph_id); },
py::arg("graph_id") = kDefaultGraphId);
c.def_property_readonly(
"device", [](const ArrayBodyPtr& self) -> Device& { return Array{self}.device(); }, py::return_value_policy::reference);
c.def_property_readonly("dtype", [](const ArrayBodyPtr& self) { return Array{self}.dtype(); });
c.def_property_readonly("element_bytes", [](const ArrayBodyPtr& self) { return Array{self}.element_bytes(); });
c.def_property_readonly("is_contiguous", [](const ArrayBodyPtr& self) { return Array{self}.IsContiguous(); });
c.def_property_readonly("ndim", [](const ArrayBodyPtr& self) { return Array{self}.ndim(); });
c.def_property_readonly("offset", [](const ArrayBodyPtr& self) { return Array{self}.offset(); });
c.def_property_readonly("shape", [](const ArrayBodyPtr& self) { return ToTuple(Array{self}.shape()); });
c.def_property_readonly("strides", [](const ArrayBodyPtr& self) { return ToTuple(Array{self}.strides()); });
c.def_property_readonly("total_bytes", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalBytes(); });
c.def_property_readonly("total_size", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalSize(); });
c.def_property_readonly("T", [](const ArrayBodyPtr& self) { return Array{self}.Transpose().move_body(); });
c.def_property_readonly(
"_debug_data_memory_address", // These methods starting with `_debug_` are stubs for testing
[](const ArrayBodyPtr& self) -> intptr_t {
const void* ptr = Array{self}.data().get();
return reinterpret_cast<intptr_t>(ptr); // NOLINT: reinterpret_cast
});
c.def_property_readonly("_debug_flat_data", [](const ArrayBodyPtr& self) {
py::list list;
const Array orig_array{self};
Context& context = orig_array.device().backend().context();
Backend& native_backend = context.GetBackend(native::NativeBackend::kDefaultName);
Device& native_device = native_backend.GetDevice(0);
Array array = Array{self}.ToDevice(native_device);
native_device.Synchronize();
// Copy data into the list
VisitDtype(array.dtype(), [&array, &list](auto pt) {
using T = typename decltype(pt)::type;
IndexableArray<const T> iarray{array};
Indexer<> indexer{array.shape()};
for (int64_t i = 0; i < indexer.total_size(); ++i) {
indexer.Set(i);
list.append(iarray[indexer]);
}
});
return list;
});
}
} // namespace internal
} // namespace python
} // namespace xchainer
<commit_msg>Use Array::ToNativeDevice in _debug_flat_data binding<commit_after>#include "xchainer/python/array.h"
#include <algorithm>
#include <cstdint>
#include <string>
#include <vector>
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include <nonstd/optional.hpp>
#include "xchainer/array.h"
#include "xchainer/array_index.h"
#include "xchainer/backward.h"
#include "xchainer/constant.h"
#include "xchainer/context.h"
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/indexable_array.h"
#include "xchainer/indexer.h"
#include "xchainer/native/native_backend.h"
#include "xchainer/routines/creation.h"
#include "xchainer/routines/manipulation.h"
#include "xchainer/slice.h"
#include "xchainer/python/array_index.h"
#include "xchainer/python/common.h"
#include "xchainer/python/device.h"
#include "xchainer/python/shape.h"
#include "xchainer/python/strides.h"
namespace xchainer {
namespace python {
namespace internal {
namespace py = pybind11;
namespace {
Dtype NumpyDtypeToDtype(const py::dtype& npdtype) {
switch (npdtype.kind()) {
case 'b':
return Dtype::kBool;
case 'i':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kInt8;
case 2:
return Dtype::kInt16;
case 4:
return Dtype::kInt32;
case 8:
return Dtype::kInt64;
default:
break;
}
break;
case 'u':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kUInt8;
default:
break;
}
break;
case 'f':
switch (npdtype.itemsize()) {
case 4:
return Dtype::kFloat32;
case 8:
return Dtype::kFloat64;
default:
break;
}
break;
default:
break;
}
throw DtypeError("unsupported NumPy dtype");
}
ArrayBodyPtr MakeArray(const py::tuple& shape_tup, Dtype dtype, const py::list& list, const nonstd::optional<std::string>& device_id) {
Shape shape = ToShape(shape_tup);
auto total_size = shape.GetTotalSize();
auto bytes = GetElementSize(dtype) * total_size;
if (static_cast<size_t>(total_size) != list.size()) {
throw DimensionError("Invalid data length");
}
// Allocate a buffer and copy data
std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
VisitDtype(dtype, [&](auto pt) {
using T = typename decltype(pt)::type;
std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
});
return Array::FromBuffer(shape, dtype, ptr, GetDevice(device_id)).move_body();
}
ArrayBodyPtr MakeArray(py::array array, const nonstd::optional<std::string>& device_id) {
Dtype dtype = NumpyDtypeToDtype(array.dtype());
const py::buffer_info& info = array.request();
Shape shape{info.shape};
Strides strides{info.strides};
// data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released
void* underlying_data = array.mutable_data();
std::shared_ptr<void> data{std::make_shared<py::array>(std::move(array)), underlying_data};
return xchainer::internal::FromBuffer(shape, dtype, data, strides, GetDevice(device_id)).move_body();
}
py::buffer_info MakeNumpyArrayFromArray(ArrayBody& self) {
// Used as a temporary accessor
Array array{ArrayBodyPtr(&self, [](ArrayBody* ptr) {
(void)ptr; // unused
})};
return py::buffer_info(
array.data().get(),
array.element_bytes(),
std::string(1, GetCharCode(array.dtype())),
array.ndim(),
array.shape(),
array.strides());
}
} // namespace
void InitXchainerArray(pybind11::module& m) {
py::class_<ArrayBody, ArrayBodyPtr> c{m, "Array", py::buffer_protocol()};
c.def(py::init(py::overload_cast<const py::tuple&, Dtype, const py::list&, const nonstd::optional<std::string>&>(&MakeArray)),
py::arg("shape"),
py::arg("dtype"),
py::arg("data"),
py::arg("device") = nullptr);
c.def(py::init(py::overload_cast<py::array, const nonstd::optional<std::string>&>(&MakeArray)),
py::arg("data"),
py::arg("device") = nullptr);
// TODO(niboshi): We cannot support buffer protocol for general device. Remove the binding and provide alternative interface
// to convert to NumPy array.
c.def_buffer(&MakeNumpyArrayFromArray);
c.def("__bool__", [](const ArrayBodyPtr& self) -> bool { return static_cast<bool>(AsScalar(Array{self})); });
c.def("__int__", [](const ArrayBodyPtr& self) -> int64_t { return static_cast<int64_t>(AsScalar(Array{self})); });
c.def("__float__", [](const ArrayBodyPtr& self) -> double { return static_cast<double>(AsScalar(Array{self})); });
c.def("view", [](const ArrayBodyPtr& self) {
// Duplicate the array body
return std::make_shared<ArrayBody>(*self);
});
c.def("__repr__", [](const ArrayBodyPtr& self) { return Array{self}.ToString(); });
c.def("to_device", [](const ArrayBodyPtr& self, Device& device) { return Array{self}.ToDevice(device).move_body(); });
c.def("to_device", [](const ArrayBodyPtr& self, const std::string& device_name) {
Device& device = GetDefaultContext().GetDevice({device_name});
return Array{self}.ToDevice(device).move_body();
});
c.def("to_device", [](const ArrayBodyPtr& self, const std::string& backend_name, int index) {
Device& device = GetDefaultContext().GetDevice({backend_name, index});
return Array{self}.ToDevice(device).move_body();
});
c.def("as_constant",
[](const ArrayBodyPtr& self, bool copy) { return Array{self}.AsConstant(copy ? CopyKind::kCopy : CopyKind::kView).move_body(); },
py::arg("copy") = false);
c.def("as_constant",
[](const ArrayBodyPtr& self, const std::vector<GraphId>& graph_ids, bool copy) {
return Array{self}.AsConstant(graph_ids, copy ? CopyKind::kCopy : CopyKind::kView).move_body();
},
py::arg().noconvert(),
py::arg("copy") = false);
c.def("copy", [](const ArrayBodyPtr& self) { return Array{self}.Copy().move_body(); });
c.def("__getitem__", [](const ArrayBodyPtr& self, py::handle handle) {
return Array{self}.At(python::internal::MakeArrayIndices(handle)).move_body();
});
c.def("transpose", [](const ArrayBodyPtr& self) { return Array{self}.Transpose().move_body(); });
c.def("reshape", [](const ArrayBodyPtr& self, py::tuple shape) { return Array{self}.Reshape(ToShape(shape)).move_body(); });
c.def("reshape", [](const ArrayBodyPtr& self, const std::vector<int64_t>& shape) {
return Array{self}.Reshape({shape.begin(), shape.end()}).move_body();
});
c.def("reshape", [](const ArrayBodyPtr& self, py::args args) {
auto shape = py::cast<std::vector<int64_t>>(args);
return Array{self}.Reshape({shape.begin(), shape.end()}).move_body();
});
c.def("__eq__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} == Array{rhs}).move_body(); });
c.def("__iadd__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} += Array{rhs}).move_body(); });
c.def("__imul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} *= Array{rhs}).move_body(); });
c.def("__add__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} + Array{rhs}).move_body(); });
c.def("__mul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} * Array{rhs}).move_body(); });
c.def("__mul__", [](const ArrayBodyPtr& self, Scalar rhs) { return (Array{self} * rhs).move_body(); });
c.def("__rmul__", [](const ArrayBodyPtr& self, Scalar lhs) { return (lhs * Array{self}).move_body(); });
c.def("sum",
[](const ArrayBodyPtr& self, int8_t axis, bool keepdims) {
return Array{self}.Sum(std::vector<int8_t>{axis}, keepdims).move_body();
},
py::arg("axis"),
py::arg("keepdims") = false);
c.def("sum",
[](const ArrayBodyPtr& self, nonstd::optional<std::vector<int8_t>> axis, bool keepdims) {
return Array{self}.Sum(axis, keepdims).move_body();
},
py::arg("axis") = nullptr,
py::arg("keepdims") = false);
c.def("require_grad",
[](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.RequireGrad(graph_id).move_body(); },
py::arg("graph_id") = kDefaultGraphId);
c.def("is_grad_required",
[](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.IsGradRequired(graph_id); },
py::arg("graph_id") = kDefaultGraphId);
c.def("get_grad",
[](const ArrayBodyPtr& self, const GraphId& graph_id) -> ConstArrayBodyPtr {
const nonstd::optional<Array>& grad = Array{self}.GetGrad(graph_id);
if (!grad.has_value()) {
return nullptr;
}
return grad->body();
},
py::arg("graph_id") = kDefaultGraphId);
c.def("set_grad",
[](const ArrayBodyPtr& self, const ArrayBodyPtr& grad, const GraphId& graph_id) {
auto array = Array{self};
if (grad) {
array.SetGrad(Array{grad}, graph_id);
} else {
array.ClearGrad(graph_id);
}
},
py::arg("grad"),
py::arg("graph_id") = kDefaultGraphId);
c.def("backward",
[](const ArrayBodyPtr& self, const GraphId& graph_id, bool enable_double_backprop) {
Array array{self};
auto double_backprop = enable_double_backprop ? DoubleBackpropOption::kEnable : DoubleBackpropOption::kDisable;
Backward(array, graph_id, double_backprop);
},
py::arg("graph_id") = kDefaultGraphId,
py::arg("enable_double_backprop") = false);
c.def_property(
"grad",
[](const ArrayBodyPtr& self) -> ConstArrayBodyPtr {
const nonstd::optional<Array>& grad = Array{self}.GetGrad(kDefaultGraphId);
if (!grad.has_value()) {
return nullptr;
}
return grad->body();
},
[](const ArrayBodyPtr& self, const ArrayBodyPtr& grad) {
auto array = Array{self};
if (grad) {
array.SetGrad(Array{grad}, kDefaultGraphId);
} else {
array.ClearGrad(kDefaultGraphId);
}
});
c.def("cleargrad",
[](const ArrayBodyPtr& self, const GraphId& graph_id) { Array{self}.ClearGrad(graph_id); },
py::arg("graph_id") = kDefaultGraphId);
c.def_property_readonly(
"device", [](const ArrayBodyPtr& self) -> Device& { return Array{self}.device(); }, py::return_value_policy::reference);
c.def_property_readonly("dtype", [](const ArrayBodyPtr& self) { return Array{self}.dtype(); });
c.def_property_readonly("element_bytes", [](const ArrayBodyPtr& self) { return Array{self}.element_bytes(); });
c.def_property_readonly("is_contiguous", [](const ArrayBodyPtr& self) { return Array{self}.IsContiguous(); });
c.def_property_readonly("ndim", [](const ArrayBodyPtr& self) { return Array{self}.ndim(); });
c.def_property_readonly("offset", [](const ArrayBodyPtr& self) { return Array{self}.offset(); });
c.def_property_readonly("shape", [](const ArrayBodyPtr& self) { return ToTuple(Array{self}.shape()); });
c.def_property_readonly("strides", [](const ArrayBodyPtr& self) { return ToTuple(Array{self}.strides()); });
c.def_property_readonly("total_bytes", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalBytes(); });
c.def_property_readonly("total_size", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalSize(); });
c.def_property_readonly("T", [](const ArrayBodyPtr& self) { return Array{self}.Transpose().move_body(); });
c.def_property_readonly(
"_debug_data_memory_address", // These methods starting with `_debug_` are stubs for testing
[](const ArrayBodyPtr& self) -> intptr_t {
const void* ptr = Array{self}.data().get();
return reinterpret_cast<intptr_t>(ptr); // NOLINT: reinterpret_cast
});
c.def_property_readonly("_debug_flat_data", [](const ArrayBodyPtr& self) {
py::list list;
Array array = Array{self}.ToNativeDevice();
// Copy data into the list
VisitDtype(array.dtype(), [&array, &list](auto pt) {
using T = typename decltype(pt)::type;
IndexableArray<const T> iarray{array};
Indexer<> indexer{array.shape()};
for (int64_t i = 0; i < indexer.total_size(); ++i) {
indexer.Set(i);
list.append(iarray[indexer]);
}
});
return list;
});
}
} // namespace internal
} // namespace python
} // namespace xchainer
<|endoftext|> |
<commit_before>/* FILE INFORMATION
File: register.cpp
Authors: Matthew Cole <mcole8@binghamton.edu>
Brian Gracin <bgracin1@binghamton.edu>
Description: Contains the Registers class, which simulates operation of a register file.
*/
#include "register.h"
Registers::Registers(){
this->initialize();
}
//Initialize the RF with all registers/flags set to zero
//and all validities set to true
void Registers::initialize(){
std::string reg_name;
//Set general purpose register values and valids
for (int r=0; r<NUM_REGS; r++){
reg_name = "R" + std::to_string(r);
this.reg_file[reg_name] = std::make_tuple(0, true)
}
//Set flag and special register values and valids
this.reg_file["X"] = std::make_tuple(0, true);
this.reg_file["Z"] = std::make_tuple(0, true);
}
//Display the contents of the registers/flags
void Registers::display(){
std::string myname = "";
int myvalue = 0;
bool myvalid = true;
std::cout << "Register File and Flags:" << endl;
for (auto it = this.reg_file.begin(); it != this.reg_file.end(); ++it) {
myname = it->first;
std::tie(myvalue, myvalid) = it->second;
std::cout << myname << ": " << myvalue << "," << myvalid << std::endl;
}
}
//Set reg_file[register] = (value,valid)
//Throws std::invalid_argument exception if register doesn't exist
void write(std::string register, int value, bool valid){
auto it = this.reg_file.find(register);
if (it != this.reg_file.end()){
this.reg_file[register] = std::make_tuple(value, valid);
} else {
std::string what_arg = register + " is not a valid register";
throw std::invalid_argument(what_arg);
}
}
//Get reg_file[register] value
//Throws std::invalid_argument exception if register doesn't exist
int read(std::string register){
int myvalue;
auto it = this.reg_file.find(register);
if (it != this.reg_file.end()) {
myvalue = std::get<0>(it->second);
} else {
std::string what_arg = register + " is not a valid register";
throw std::invalid_argument(what_arg);
}
return myvalue;
}
//Check reg_file[register] validity
//Throws std::invalid_argument exception if register doesn't exist
bool isValid(std::string register){
bool myvalid;
auto it = this.reg_file.find(register);
if (it != this.reg_file.end()) {
myvalid = std::get<1>(it->second);
} else {
std::string what_arg = register + " is not a valid register";
throw std::invalid_argument(what_arg);
}
return myvalid;
}
<commit_msg>Troubleshooting registers.*<commit_after>/* FILE INFORMATION
File: register.cpp
Authors: Matthew Cole <mcole8@binghamton.edu>
Brian Gracin <bgracin1@binghamton.edu>
Description: Contains the Registers class, which simulates operation of a register file.
*/
#include "register.h"
Registers::Registers(){
this->initialize();
}
//Initialize the RF with all registers/flags set to zero
//and all validities set to true
void Registers::initialize(){
std::string reg_name;
//Set general purpose register values and valids
for (int r=0; r<NUM_REGS; r++){
reg_name = "R" + std::to_string(r);
this.reg_file[reg_name] = std::make_tuple(0, true)
}
//Set flag and special register values and valids
this.reg_file["X"] = std::make_tuple(0, true);
this.reg_file["Z"] = std::make_tuple(0, true);
}
//Display the contents of the registers/flags
void Registers::display(){
std::string myname = "";
int myvalue = 0;
bool myvalid = true;
std::cout << "Register File and Flags:" << endl;
for (auto it = this.reg_file.begin(); it != this.reg_file.end(); ++it) {
myname = it->first;
std::tie(myvalue, myvalid) = it->second;
std::cout << myname << ": " << myvalue << "," << myvalid << std::endl;
}
}
//Set reg_file[register] = (value,valid)
//Throws std::invalid_argument exception if register doesn't exist
void Registers::write(std::string register, int value, bool valid){
auto it = this.reg_file.find(register);
if (it != this.reg_file.end()){
this.reg_file[register] = std::make_tuple(value, valid);
} else {
std::string what_arg = register + " is not a valid register";
throw std::invalid_argument(what_arg);
}
}
//Get reg_file[register] value
//Throws std::invalid_argument exception if register doesn't exist
int Registers::read(std::string register){
int myvalue;
auto it = this.reg_file.find(register);
if (it != this.reg_file.end()) {
myvalue = std::get<0>(it->second);
} else {
std::string what_arg = register + " is not a valid register";
throw std::invalid_argument(what_arg);
}
return myvalue;
}
//Check reg_file[register] validity
//Throws std::invalid_argument exception if register doesn't exist
bool Registers::isValid(std::string register){
bool myvalid;
auto it = this.reg_file.find(register);
if (it != this.reg_file.end()) {
myvalid = std::get<1>(it->second);
} else {
std::string what_arg = register + " is not a valid register";
throw std::invalid_argument(what_arg);
}
return myvalid;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkMeshVtkMapper3D.h"
#include "mitkDataTreeNode.h"
#include "mitkProperties.h"
//#include "mitkStringProperty.h"
//#include "mitkColorProperty.h"
#include "mitkOpenGLRenderer.h"
#ifndef VCL_VC60
#include "mitkMeshUtil.h"
#endif
#include <vtkActor.h>
#include <vtkFollower.h>
#include <vtkAssembly.h>
#include <vtkProp3DCollection.h>
#include <vtkRenderer.h>
#include <vtkPropAssembly.h>
#include <vtkProperty.h>
#include <vtkPolyDataMapper.h>
#include <stdlib.h>
const mitk::Mesh* mitk::MeshVtkMapper3D::GetInput()
{
return static_cast<const mitk::Mesh * > ( GetData() );
}
vtkProp* mitk::MeshVtkMapper3D::GetProp()
{
return m_PropAssemply;
}
mitk::MeshVtkMapper3D::MeshVtkMapper3D() : m_PropAssemply(NULL)
{
m_Spheres = vtkAppendPolyData::New();
m_Contour = vtkPolyData::New();
m_SpheresActor = vtkActor::New();
m_SpheresMapper = vtkPolyDataMapper::New();
m_SpheresActor->SetMapper(m_SpheresMapper);
m_ContourActor = vtkActor::New();
m_ContourMapper = vtkPolyDataMapper::New();
m_ContourActor->SetMapper(m_ContourMapper);
m_ContourActor->GetProperty()->SetAmbient(1.0);
m_PropAssemply = vtkPropAssembly::New();
// a vtkPropAssembly is not a sub-class of vtkProp3D, so
// we cannot use m_Prop3D.
m_Prop3D = NULL;
}
mitk::MeshVtkMapper3D::~MeshVtkMapper3D()
{
m_ContourActor->Delete();
m_SpheresActor->Delete();
m_ContourMapper->Delete();
m_SpheresMapper->Delete();
m_PropAssemply->Delete();
m_Spheres->Delete();
m_Contour->Delete();
}
void mitk::MeshVtkMapper3D::GenerateData(mitk::BaseRenderer* renderer)
{
if(IsVisible(renderer)==false)
{
m_PropAssemply->VisibilityOff();
return;
}
m_PropAssemply->VisibilityOn();
m_PropAssemply->GetParts()->RemoveAllItems();
m_Spheres->RemoveAllInputs();
m_Contour->Initialize();
mitk::Mesh::Pointer input = const_cast<mitk::Mesh*>(this->GetInput());
mitk::Mesh::DataType::Pointer mesh;
mesh = input->GetMesh();
mitk::Mesh::PointsContainer::Iterator i;
int j;
#if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) ))
double rgba[4]={1.0f,1.0f,1.0f,1.0f};
#else
float rgba[4]={1.0f,1.0f,1.0f,1.0f};
#endif
// check for color prop and use it for rendering if it exists
GetColor((float*)rgba, renderer);
if(mesh->GetNumberOfPoints()>0)
{
// build m_Spheres->GetOutput() vtkPolyData
int pointSize = 2;
mitk::IntProperty::Pointer pointSizeProp = dynamic_cast<mitk::IntProperty *>(this->GetDataTreeNode()->GetProperty("pointsize").GetPointer());
if (pointSizeProp.IsNotNull())
pointSize = pointSizeProp->GetValue();
for (j=0, i=mesh->GetPoints()->Begin(); i!=mesh->GetPoints()->End() ; i++,j++)
{
vtkSphereSource *sphere = vtkSphereSource::New();
sphere->SetRadius(pointSize);
sphere->SetCenter(i.Value()[0],i.Value()[1],i.Value()[2]);
m_Spheres->AddInput(sphere->GetOutput());
}
// setup mapper, actor and add to assembly
m_SpheresMapper->SetInput(m_Spheres->GetOutput());
m_SpheresActor->GetProperty()->SetColor(rgba);
m_PropAssemply->AddPart(m_SpheresActor);
}
if(mesh->GetNumberOfCells()>0)
{
// build m_Contour vtkPolyData
#ifdef VCL_VC60
itkExceptionMacro(<<"MeshVtkMapper3D currently not working for MS Visual C++ 6.0, because MeshUtils are currently not supported.");
#else
m_Contour = MeshUtil<mitk::Mesh::MeshType>::MeshToPolyData(mesh.GetPointer(), false, false, 0, NULL, m_Contour);
#endif
if(m_Contour->GetNumberOfCells()>0)
{
// setup mapper, actor and add to assembly
m_ContourMapper->SetInput(m_Contour);
bool wireframe=true;
GetDataTreeNode()->GetVisibility(wireframe, renderer, "wireframe");
if(wireframe)
m_ContourActor->GetProperty()->SetRepresentationToWireframe();
else
m_ContourActor->GetProperty()->SetRepresentationToSurface();
m_ContourActor->GetProperty()->SetColor(rgba);
m_PropAssemply->AddPart(m_ContourActor);
}
}
}
<commit_msg>STY: vtkFloatingPointType instead of version check<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkMeshVtkMapper3D.h"
#include "mitkDataTreeNode.h"
#include "mitkProperties.h"
//#include "mitkStringProperty.h"
//#include "mitkColorProperty.h"
#include "mitkOpenGLRenderer.h"
#ifndef VCL_VC60
#include "mitkMeshUtil.h"
#endif
#include <vtkActor.h>
#include <vtkFollower.h>
#include <vtkAssembly.h>
#include <vtkProp3DCollection.h>
#include <vtkRenderer.h>
#include <vtkPropAssembly.h>
#include <vtkProperty.h>
#include <vtkPolyDataMapper.h>
#include <stdlib.h>
const mitk::Mesh* mitk::MeshVtkMapper3D::GetInput()
{
return static_cast<const mitk::Mesh * > ( GetData() );
}
vtkProp* mitk::MeshVtkMapper3D::GetProp()
{
return m_PropAssemply;
}
mitk::MeshVtkMapper3D::MeshVtkMapper3D() : m_PropAssemply(NULL)
{
m_Spheres = vtkAppendPolyData::New();
m_Contour = vtkPolyData::New();
m_SpheresActor = vtkActor::New();
m_SpheresMapper = vtkPolyDataMapper::New();
m_SpheresActor->SetMapper(m_SpheresMapper);
m_ContourActor = vtkActor::New();
m_ContourMapper = vtkPolyDataMapper::New();
m_ContourActor->SetMapper(m_ContourMapper);
m_ContourActor->GetProperty()->SetAmbient(1.0);
m_PropAssemply = vtkPropAssembly::New();
// a vtkPropAssembly is not a sub-class of vtkProp3D, so
// we cannot use m_Prop3D.
m_Prop3D = NULL;
}
mitk::MeshVtkMapper3D::~MeshVtkMapper3D()
{
m_ContourActor->Delete();
m_SpheresActor->Delete();
m_ContourMapper->Delete();
m_SpheresMapper->Delete();
m_PropAssemply->Delete();
m_Spheres->Delete();
m_Contour->Delete();
}
void mitk::MeshVtkMapper3D::GenerateData(mitk::BaseRenderer* renderer)
{
if(IsVisible(renderer)==false)
{
m_PropAssemply->VisibilityOff();
return;
}
m_PropAssemply->VisibilityOn();
m_PropAssemply->GetParts()->RemoveAllItems();
m_Spheres->RemoveAllInputs();
m_Contour->Initialize();
mitk::Mesh::Pointer input = const_cast<mitk::Mesh*>(this->GetInput());
mitk::Mesh::DataType::Pointer mesh;
mesh = input->GetMesh();
mitk::Mesh::PointsContainer::Iterator i;
int j;
vtkFloatingPointType rgba[4]={1.0f,1.0f,1.0f,1.0f};
// check for color prop and use it for rendering if it exists
GetColor((float*)rgba, renderer);
if(mesh->GetNumberOfPoints()>0)
{
// build m_Spheres->GetOutput() vtkPolyData
int pointSize = 2;
mitk::IntProperty::Pointer pointSizeProp = dynamic_cast<mitk::IntProperty *>(this->GetDataTreeNode()->GetProperty("pointsize").GetPointer());
if (pointSizeProp.IsNotNull())
pointSize = pointSizeProp->GetValue();
for (j=0, i=mesh->GetPoints()->Begin(); i!=mesh->GetPoints()->End() ; i++,j++)
{
vtkSphereSource *sphere = vtkSphereSource::New();
sphere->SetRadius(pointSize);
sphere->SetCenter(i.Value()[0],i.Value()[1],i.Value()[2]);
m_Spheres->AddInput(sphere->GetOutput());
}
// setup mapper, actor and add to assembly
m_SpheresMapper->SetInput(m_Spheres->GetOutput());
m_SpheresActor->GetProperty()->SetColor(rgba);
m_PropAssemply->AddPart(m_SpheresActor);
}
if(mesh->GetNumberOfCells()>0)
{
// build m_Contour vtkPolyData
#ifdef VCL_VC60
itkExceptionMacro(<<"MeshVtkMapper3D currently not working for MS Visual C++ 6.0, because MeshUtils are currently not supported.");
#else
m_Contour = MeshUtil<mitk::Mesh::MeshType>::MeshToPolyData(mesh.GetPointer(), false, false, 0, NULL, m_Contour);
#endif
if(m_Contour->GetNumberOfCells()>0)
{
// setup mapper, actor and add to assembly
m_ContourMapper->SetInput(m_Contour);
bool wireframe=true;
GetDataTreeNode()->GetVisibility(wireframe, renderer, "wireframe");
if(wireframe)
m_ContourActor->GetProperty()->SetRepresentationToWireframe();
else
m_ContourActor->GetProperty()->SetRepresentationToSurface();
m_ContourActor->GetProperty()->SetColor(rgba);
m_PropAssemply->AddPart(m_ContourActor);
}
}
}
<|endoftext|> |
<commit_before>// Copyright 2016 <Morgan Rockett>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "Eigen/Dense"
#include "gtest/gtest.h"
#include "include/cpu_operations.h"
#include "include/matrix.h"
TEST(Mutilply, ScalarMatrixMult) {
int scalar;
scalar = 3;
Eigen::MatrixXi a(3, 3);
a << 0, 1, 2,
3, 2, 1,
1, 3, 0;
Eigen::MatrixXi correct_ans(3, 3);
correct_ans << 0, 3, 6,
9, 6, 3,
3, 9, 0;
Nice::Matrix<int> calc_ans = Nice::CpuOperations<int>::Multiply(a, scalar);
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
EXPECT_EQ(correct_ans(i, j), calc_ans(i, j));
}
TEST(Mutilply, MatrixMatrixMult) {
Eigen::MatrixXi a(3, 3);
a << 0, 1, 2,
3, 2, 1,
1, 3, 0;
Eigen::MatrixXi b(3, 3);
b << 1, 0, 2,
2, 1, 0,
0, 2, 1;
Eigen::MatrixXi correct_ans(3, 3);
correct_ans << 2, 5, 2,
7, 4, 7,
7, 3, 2;
Nice::Matrix<int> calc_ans = Nice::CpuOperations<int>::Multiply(a, b);
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
EXPECT_EQ(correct_ans(i, j), calc_ans(i, j));
}
<commit_msg>Updating Multiply<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2016 Northeastern University
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "Eigen/Dense"
#include "gtest/gtest.h"
#include "include/cpu_operations.h"
#include "include/matrix.h"
TEST(Mutilply, ScalarMatrixMult) {
int scalar;
scalar = 3;
Eigen::MatrixXi a(3, 3);
a << 0, 1, 2,
3, 2, 1,
1, 3, 0;
Eigen::MatrixXi correct_ans(3, 3);
correct_ans << 0, 3, 6,
9, 6, 3,
3, 9, 0;
Nice::Matrix<int> calc_ans = Nice::CpuOperations<int>::Multiply(a, scalar);
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
EXPECT_EQ(correct_ans(i, j), calc_ans(i, j));
}
TEST(Mutilply, MatrixMatrixMult) {
Eigen::MatrixXi a(3, 3);
a << 0, 1, 2,
3, 2, 1,
1, 3, 0;
Eigen::MatrixXi b(3, 3);
b << 1, 0, 2,
2, 1, 0,
0, 2, 1;
Eigen::MatrixXi correct_ans(3, 3);
correct_ans << 2, 5, 2,
7, 4, 7,
7, 3, 2;
Nice::Matrix<int> calc_ans = Nice::CpuOperations<int>::Multiply(a, b);
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
EXPECT_EQ(correct_ans(i, j), calc_ans(i, j));
}
<|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 file.
#include "chrome/browser/debugger/devtools_manager.h"
#include "base/message_loop.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/site_instance.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "googleurl/src/gurl.h"
DevToolsManager::DevToolsManager()
: inspected_rvh_for_reopen_(NULL) {
}
DevToolsManager::~DevToolsManager() {
DCHECK(inspected_rvh_to_client_host_.empty());
DCHECK(client_host_to_inspected_rvh_.empty());
}
DevToolsClientHost* DevToolsManager::GetDevToolsClientHostFor(
RenderViewHost* inspected_rvh) {
InspectedRvhToClientHostMap::iterator it =
inspected_rvh_to_client_host_.find(inspected_rvh);
if (it != inspected_rvh_to_client_host_.end()) {
return it->second;
}
return NULL;
}
void DevToolsManager::RegisterDevToolsClientHostFor(
RenderViewHost* inspected_rvh,
DevToolsClientHost* client_host) {
DCHECK(!GetDevToolsClientHostFor(inspected_rvh));
inspected_rvh_to_client_host_[inspected_rvh] = client_host;
client_host_to_inspected_rvh_[client_host] = inspected_rvh;
client_host->set_close_listener(this);
SendAttachToAgent(inspected_rvh);
}
void DevToolsManager::ForwardToDevToolsAgent(
RenderViewHost* client_rvh,
const IPC::Message& message) {
for (InspectedRvhToClientHostMap::iterator it =
inspected_rvh_to_client_host_.begin();
it != inspected_rvh_to_client_host_.end();
++it) {
DevToolsWindow* win = it->second->AsDevToolsWindow();
if (!win) {
continue;
}
if (client_rvh == win->GetRenderViewHost()) {
ForwardToDevToolsAgent(win, message);
return;
}
}
}
void DevToolsManager::ForwardToDevToolsAgent(DevToolsClientHost* from,
const IPC::Message& message) {
RenderViewHost* inspected_rvh = GetInspectedRenderViewHost(from);
if (!inspected_rvh) {
// TODO(yurys): notify client that the agent is no longer available
NOTREACHED();
return;
}
IPC::Message* m = new IPC::Message(message);
m->set_routing_id(inspected_rvh->routing_id());
inspected_rvh->Send(m);
}
void DevToolsManager::ForwardToDevToolsClient(RenderViewHost* inspected_rvh,
const IPC::Message& message) {
DevToolsClientHost* client_host = GetDevToolsClientHostFor(inspected_rvh);
if (!client_host) {
// Client window was closed while there were messages
// being sent to it.
return;
}
client_host->SendMessageToClient(message);
}
void DevToolsManager::OpenDevToolsWindow(RenderViewHost* inspected_rvh) {
DevToolsClientHost* host = GetDevToolsClientHostFor(inspected_rvh);
if (!host) {
host = new DevToolsWindow(
inspected_rvh->site_instance()->browsing_instance()->profile());
RegisterDevToolsClientHostFor(inspected_rvh, host);
}
DevToolsWindow* window = host->AsDevToolsWindow();
if (window)
window->Show();
}
void DevToolsManager::InspectElement(RenderViewHost* inspected_rvh,
int x,
int y) {
OpenDevToolsWindow(inspected_rvh);
IPC::Message* m = new DevToolsAgentMsg_InspectElement(x, y);
m->set_routing_id(inspected_rvh->routing_id());
inspected_rvh->Send(m);
}
void DevToolsManager::ClientHostClosing(DevToolsClientHost* host) {
RenderViewHost* inspected_rvh = GetInspectedRenderViewHost(host);
if (!inspected_rvh) {
return;
}
SendDetachToAgent(inspected_rvh);
inspected_rvh_to_client_host_.erase(inspected_rvh);
client_host_to_inspected_rvh_.erase(host);
}
RenderViewHost* DevToolsManager::GetInspectedRenderViewHost(
DevToolsClientHost* client_host) {
ClientHostToInspectedRvhMap::iterator it =
client_host_to_inspected_rvh_.find(client_host);
if (it != client_host_to_inspected_rvh_.end()) {
return it->second;
}
return NULL;
}
void DevToolsManager::UnregisterDevToolsClientHostFor(
RenderViewHost* inspected_rvh) {
DevToolsClientHost* host = GetDevToolsClientHostFor(inspected_rvh);
if (!host) {
return;
}
host->InspectedTabClosing();
inspected_rvh_to_client_host_.erase(inspected_rvh);
client_host_to_inspected_rvh_.erase(host);
if (inspected_rvh_for_reopen_ == inspected_rvh) {
inspected_rvh_for_reopen_ = NULL;
}
}
void DevToolsManager::OnNavigatingToPendingEntry(RenderViewHost* rvh,
RenderViewHost* dest_rvh,
const GURL& gurl) {
DevToolsClientHost* client_host =
GetDevToolsClientHostFor(rvh);
if (client_host) {
// Navigating to URL in the inspected window.
inspected_rvh_to_client_host_.erase(rvh);
inspected_rvh_to_client_host_[dest_rvh] = client_host;
client_host_to_inspected_rvh_[client_host] = dest_rvh;
SendAttachToAgent(dest_rvh);
return;
}
// Iterate over client hosts and if there is one that has render view host
// changing, reopen entire client window (this must be caused by the user
// manually refreshing its content).
for (ClientHostToInspectedRvhMap::iterator it =
client_host_to_inspected_rvh_.begin();
it != client_host_to_inspected_rvh_.end(); ++it) {
DevToolsWindow* window = it->first->AsDevToolsWindow();
if (window && window->GetRenderViewHost() == rvh) {
RenderViewHost* inspected_rvn = it->second;
UnregisterDevToolsClientHostFor(inspected_rvn);
SendDetachToAgent(inspected_rvn);
inspected_rvh_for_reopen_ = inspected_rvn;
MessageLoop::current()->PostTask(FROM_HERE,
NewRunnableMethod(this,
&DevToolsManager::ForceReopenWindow));
return;
}
}
}
void DevToolsManager::SendAttachToAgent(RenderViewHost* inspected_rvh) {
if (inspected_rvh) {
IPC::Message* m = new DevToolsAgentMsg_Attach();
m->set_routing_id(inspected_rvh->routing_id());
inspected_rvh->Send(m);
}
}
void DevToolsManager::SendDetachToAgent(RenderViewHost* inspected_rvh) {
if (inspected_rvh) {
IPC::Message* m = new DevToolsAgentMsg_Detach();
m->set_routing_id(inspected_rvh->routing_id());
inspected_rvh->Send(m);
}
}
void DevToolsManager::ForceReopenWindow() {
if (inspected_rvh_for_reopen_) {
OpenDevToolsWindow(inspected_rvh_for_reopen_);
inspected_rvh_for_reopen_ = NULL;
}
}
<commit_msg>DevTools: do not crash on rapid refresh while on a Dev Tools Client window.<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 file.
#include "chrome/browser/debugger/devtools_manager.h"
#include "base/message_loop.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/site_instance.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "googleurl/src/gurl.h"
DevToolsManager::DevToolsManager()
: inspected_rvh_for_reopen_(NULL) {
}
DevToolsManager::~DevToolsManager() {
DCHECK(inspected_rvh_to_client_host_.empty());
DCHECK(client_host_to_inspected_rvh_.empty());
}
DevToolsClientHost* DevToolsManager::GetDevToolsClientHostFor(
RenderViewHost* inspected_rvh) {
InspectedRvhToClientHostMap::iterator it =
inspected_rvh_to_client_host_.find(inspected_rvh);
if (it != inspected_rvh_to_client_host_.end()) {
return it->second;
}
return NULL;
}
void DevToolsManager::RegisterDevToolsClientHostFor(
RenderViewHost* inspected_rvh,
DevToolsClientHost* client_host) {
DCHECK(!GetDevToolsClientHostFor(inspected_rvh));
inspected_rvh_to_client_host_[inspected_rvh] = client_host;
client_host_to_inspected_rvh_[client_host] = inspected_rvh;
client_host->set_close_listener(this);
SendAttachToAgent(inspected_rvh);
}
void DevToolsManager::ForwardToDevToolsAgent(
RenderViewHost* client_rvh,
const IPC::Message& message) {
for (InspectedRvhToClientHostMap::iterator it =
inspected_rvh_to_client_host_.begin();
it != inspected_rvh_to_client_host_.end();
++it) {
DevToolsWindow* win = it->second->AsDevToolsWindow();
if (!win) {
continue;
}
if (client_rvh == win->GetRenderViewHost()) {
ForwardToDevToolsAgent(win, message);
return;
}
}
}
void DevToolsManager::ForwardToDevToolsAgent(DevToolsClientHost* from,
const IPC::Message& message) {
RenderViewHost* inspected_rvh = GetInspectedRenderViewHost(from);
if (!inspected_rvh) {
// TODO(yurys): notify client that the agent is no longer available
NOTREACHED();
return;
}
IPC::Message* m = new IPC::Message(message);
m->set_routing_id(inspected_rvh->routing_id());
inspected_rvh->Send(m);
}
void DevToolsManager::ForwardToDevToolsClient(RenderViewHost* inspected_rvh,
const IPC::Message& message) {
DevToolsClientHost* client_host = GetDevToolsClientHostFor(inspected_rvh);
if (!client_host) {
// Client window was closed while there were messages
// being sent to it.
return;
}
client_host->SendMessageToClient(message);
}
void DevToolsManager::OpenDevToolsWindow(RenderViewHost* inspected_rvh) {
DevToolsClientHost* host = GetDevToolsClientHostFor(inspected_rvh);
if (!host) {
host = new DevToolsWindow(
inspected_rvh->site_instance()->browsing_instance()->profile());
RegisterDevToolsClientHostFor(inspected_rvh, host);
}
DevToolsWindow* window = host->AsDevToolsWindow();
if (window)
window->Show();
}
void DevToolsManager::InspectElement(RenderViewHost* inspected_rvh,
int x,
int y) {
OpenDevToolsWindow(inspected_rvh);
IPC::Message* m = new DevToolsAgentMsg_InspectElement(x, y);
m->set_routing_id(inspected_rvh->routing_id());
inspected_rvh->Send(m);
}
void DevToolsManager::ClientHostClosing(DevToolsClientHost* host) {
RenderViewHost* inspected_rvh = GetInspectedRenderViewHost(host);
if (!inspected_rvh) {
return;
}
SendDetachToAgent(inspected_rvh);
inspected_rvh_to_client_host_.erase(inspected_rvh);
client_host_to_inspected_rvh_.erase(host);
}
RenderViewHost* DevToolsManager::GetInspectedRenderViewHost(
DevToolsClientHost* client_host) {
ClientHostToInspectedRvhMap::iterator it =
client_host_to_inspected_rvh_.find(client_host);
if (it != client_host_to_inspected_rvh_.end()) {
return it->second;
}
return NULL;
}
void DevToolsManager::UnregisterDevToolsClientHostFor(
RenderViewHost* inspected_rvh) {
DevToolsClientHost* host = GetDevToolsClientHostFor(inspected_rvh);
if (!host) {
return;
}
host->InspectedTabClosing();
inspected_rvh_to_client_host_.erase(inspected_rvh);
client_host_to_inspected_rvh_.erase(host);
if (inspected_rvh_for_reopen_ == inspected_rvh) {
inspected_rvh_for_reopen_ = NULL;
}
}
void DevToolsManager::OnNavigatingToPendingEntry(RenderViewHost* rvh,
RenderViewHost* dest_rvh,
const GURL& gurl) {
DevToolsClientHost* client_host =
GetDevToolsClientHostFor(rvh);
if (client_host) {
// Navigating to URL in the inspected window.
inspected_rvh_to_client_host_.erase(rvh);
inspected_rvh_to_client_host_[dest_rvh] = client_host;
client_host_to_inspected_rvh_[client_host] = dest_rvh;
SendAttachToAgent(dest_rvh);
return;
}
// Iterate over client hosts and if there is one that has render view host
// changing, reopen entire client window (this must be caused by the user
// manually refreshing its content).
for (ClientHostToInspectedRvhMap::iterator it =
client_host_to_inspected_rvh_.begin();
it != client_host_to_inspected_rvh_.end(); ++it) {
DevToolsWindow* window = it->first->AsDevToolsWindow();
if (window && window->GetRenderViewHost() == rvh) {
inspected_rvh_for_reopen_ = it->second;
MessageLoop::current()->PostTask(FROM_HERE,
NewRunnableMethod(this,
&DevToolsManager::ForceReopenWindow));
return;
}
}
}
void DevToolsManager::SendAttachToAgent(RenderViewHost* inspected_rvh) {
if (inspected_rvh) {
IPC::Message* m = new DevToolsAgentMsg_Attach();
m->set_routing_id(inspected_rvh->routing_id());
inspected_rvh->Send(m);
}
}
void DevToolsManager::SendDetachToAgent(RenderViewHost* inspected_rvh) {
if (inspected_rvh) {
IPC::Message* m = new DevToolsAgentMsg_Detach();
m->set_routing_id(inspected_rvh->routing_id());
inspected_rvh->Send(m);
}
}
void DevToolsManager::ForceReopenWindow() {
if (inspected_rvh_for_reopen_) {
RenderViewHost* inspected_rvn = inspected_rvh_for_reopen_;
SendDetachToAgent(inspected_rvn);
UnregisterDevToolsClientHostFor(inspected_rvn);
OpenDevToolsWindow(inspected_rvn);
}
}
<|endoftext|> |
<commit_before>#include <common/buffer.h>
#include <common/endian.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_cache.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_hash.h>
struct candidate_symbol {
bool set_;
unsigned offset_;
uint64_t symbol_;
};
XCodecEncoder::XCodecEncoder(XCodecCache *cache)
: log_("/xcodec/encoder"),
cache_(cache),
window_()
{ }
XCodecEncoder::~XCodecEncoder()
{ }
/*
* This takes a view of a data stream and turns it into a series of references
* to other data, declarations of data to be referenced, and data that needs
* escaped.
*/
void
XCodecEncoder::encode(Buffer *output, Buffer *input)
{
if (input->empty())
return;
if (input->length() < XCODEC_SEGMENT_LENGTH) {
encode_escape(output, input, input->length());
return;
}
XCodecHash xcodec_hash;
candidate_symbol candidate;
Buffer outq;
unsigned o = 0;
candidate.set_ = false;
/*
* While there is input.
*/
while (!input->empty()) {
/*
* If we cannot acquire a complete hash within this segment,
* stop looking.
*/
if (o + input->length() < XCODEC_SEGMENT_LENGTH) {
DEBUG(log_) << "Buffer couldn't yield a hash.";
outq.append(input);
input->clear();
break;
}
/*
* Take the first BufferSegment out of the input Buffer.
*/
BufferSegment *seg;
input->moveout(&seg);
/*
* And add it to a temporary Buffer where input is queued.
*/
outq.append(seg);
/*
* And for every byte in this BufferSegment.
*/
const uint8_t *p, *q = seg->end();
for (p = seg->data(); p < q; p++) {
/*
* If we cannot acquire a complete hash within this segment.
*/
if (o + (q - p) < XCODEC_SEGMENT_LENGTH) {
/*
* Hash all of the bytes from it and continue.
*/
o += q - p;
while (p < q)
xcodec_hash.add(*p++);
break;
}
/*
* If we don't have a complete hash.
*/
if (o < XCODEC_SEGMENT_LENGTH) {
for (;;) {
/*
* Add bytes to the hash.
*/
xcodec_hash.add(*p);
/*
* Until we have a complete hash.
*/
if (++o == XCODEC_SEGMENT_LENGTH)
break;
/*
* Go to the next byte.
*/
p++;
}
ASSERT(o == XCODEC_SEGMENT_LENGTH);
} else {
/*
* Roll it into the rolling hash.
*/
xcodec_hash.roll(*p);
o++;
}
ASSERT(o >= XCODEC_SEGMENT_LENGTH);
ASSERT(p != q);
/*
* And then mix the hash's internal state into a
* uint64_t that we can use to refer to that data
* and to look up possible past occurances of that
* data in the XCodecCache.
*/
unsigned start = o - XCODEC_SEGMENT_LENGTH;
uint64_t hash = xcodec_hash.mix();
/*
* If there is a pending candidate hash that wouldn't
* overlap with the data that the rolling hash presently
* covers, declare it now.
*/
if (candidate.set_ && candidate.offset_ + XCODEC_SEGMENT_LENGTH <= start) {
BufferSegment *nseg;
encode_declaration(output, &outq, candidate.offset_, candidate.symbol_, &nseg);
o -= candidate.offset_ + XCODEC_SEGMENT_LENGTH;
start = o - XCODEC_SEGMENT_LENGTH;
candidate.set_ = false;
/*
* If, on top of that, the just-declared hash is
* the same as the current hash, consider referencing
* it immediately.
*/
if (hash == candidate.symbol_) {
/*
* If it's a hash collision, though, nevermind.
* Skip trying to use this hash as a reference,
* too, and go on to the next one.
*/
if (!encode_reference(output, &outq, start, hash, nseg)) {
nseg->unref();
DEBUG(log_) << "Collision in adjacent-declare pass.";
continue;
}
nseg->unref();
/*
* But if there's no collection, then we can move
* on to looking for the *next* hash/data to declare
* or reference.
*/
o = 0;
xcodec_hash.reset();
DEBUG(log_) << "Hit in adjacent-declare pass.";
continue;
}
nseg->unref();
}
/*
* Now attempt to encode this hash as a reference if it
* has been defined before.
*/
BufferSegment *oseg = cache_->lookup(hash);
if (oseg != NULL) {
/*
* This segment already exists. If it's
* identical to this chunk of data, then that's
* positively fantastic.
*/
if (encode_reference(output, &outq, start, hash, oseg)) {
oseg->unref();
o = 0;
xcodec_hash.reset();
/*
* We have output any data before this hash
* in escaped form, so any candidate hash
* before it is invalid now.
*/
candidate.set_ = false;
continue;
}
/*
* This hash isn't usable because it collides
* with another, so keep looking for something
* viable.
*/
oseg->unref();
DEBUG(log_) << "Collision in first pass.";
continue;
}
/*
* Not defined before, it's a candidate for declaration if
* we don't already have one.
*/
if (candidate.set_) {
/*
* We already have a hash that occurs earlier,
* isn't a collision and includes data that's
* covered by this hash, so don't remember it
* and keep going.
*/
ASSERT(candidate.offset_ + XCODEC_SEGMENT_LENGTH > start);
continue;
}
/*
* The hash at this offset doesn't collide with any
* other and is the first viable hash we've seen so far
* in the stream, so remember it so that if we don't
* find something to reference we can declare this one
* for future use.
*/
candidate.offset_ = start;
candidate.symbol_ = hash;
candidate.set_ = true;
}
seg->unref();
}
/*
* Done processing input. If there's still data in the outq Buffer,
* then we need to declare any candidate hashes and escape any data
* after them.
*/
/*
* There's a hash we can declare, do it.
*/
if (candidate.set_) {
ASSERT(!outq.empty());
encode_declaration(output, &outq, candidate.offset_, candidate.symbol_, NULL);
candidate.set_ = false;
}
/*
* There's data after that hash or no candidate hash, so
* just escape it.
*/
if (!outq.empty()) {
encode_escape(output, &outq, outq.length());
}
ASSERT(!candidate.set_);
ASSERT(outq.empty());
ASSERT(input->empty());
}
void
XCodecEncoder::encode_declaration(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment **segp)
{
if (offset != 0) {
encode_escape(output, input, offset);
}
BufferSegment *nseg;
input->copyout(&nseg, XCODEC_SEGMENT_LENGTH);
cache_->enter(hash, nseg);
output->append(XCODEC_MAGIC);
output->append(XCODEC_OP_EXTRACT);
output->append(nseg);
window_.declare(hash, nseg);
if (segp == NULL)
nseg->unref();
/*
* Skip to the end.
*/
input->skip(XCODEC_SEGMENT_LENGTH);
if (segp != NULL)
*segp = nseg;
}
void
XCodecEncoder::encode_escape(Buffer *output, Buffer *input, unsigned length)
{
ASSERT(length != 0);
do {
unsigned offset;
if (!input->find(XCODEC_MAGIC, &offset, length)) {
output->append(input, length);
input->skip(length);
return;
}
if (offset != 0) {
output->append(input, offset);
length -= offset;
input->skip(offset);
}
output->append(XCODEC_MAGIC);
output->append(XCODEC_OP_ESCAPE);
length -= sizeof XCODEC_MAGIC;
input->skip(sizeof XCODEC_MAGIC);
} while (length != 0);
}
bool
XCodecEncoder::encode_reference(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment *oseg)
{
uint8_t data[XCODEC_SEGMENT_LENGTH];
input->copyout(data, offset, sizeof data);
if (!oseg->equal(data, sizeof data))
return (false);
if (offset != 0) {
encode_escape(output, input, offset);
}
/*
* Skip to the end.
*/
input->skip(XCODEC_SEGMENT_LENGTH);
/*
* And output a reference.
*/
uint8_t b;
if (window_.present(hash, &b)) {
output->append(XCODEC_MAGIC);
output->append(XCODEC_OP_BACKREF);
output->append(b);
} else {
output->append(XCODEC_MAGIC);
output->append(XCODEC_OP_REF);
uint64_t behash = BigEndian::encode(hash);
output->append(&behash);
window_.declare(hash, oseg);
}
return (true);
}
<commit_msg>Add a comment and reformat a nearby one.<commit_after>#include <common/buffer.h>
#include <common/endian.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_cache.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_hash.h>
struct candidate_symbol {
bool set_;
unsigned offset_;
uint64_t symbol_;
};
XCodecEncoder::XCodecEncoder(XCodecCache *cache)
: log_("/xcodec/encoder"),
cache_(cache),
window_()
{ }
XCodecEncoder::~XCodecEncoder()
{ }
/*
* This takes a view of a data stream and turns it into a series of references
* to other data, declarations of data to be referenced, and data that needs
* escaped.
*/
void
XCodecEncoder::encode(Buffer *output, Buffer *input)
{
if (input->empty())
return;
if (input->length() < XCODEC_SEGMENT_LENGTH) {
encode_escape(output, input, input->length());
return;
}
XCodecHash xcodec_hash;
candidate_symbol candidate;
Buffer outq;
unsigned o = 0;
candidate.set_ = false;
/*
* While there is input.
*/
while (!input->empty()) {
/*
* If we cannot acquire a complete hash within this segment,
* stop looking.
*/
if (o + input->length() < XCODEC_SEGMENT_LENGTH) {
DEBUG(log_) << "Buffer couldn't yield a hash.";
outq.append(input);
input->clear();
break;
}
/*
* Take the first BufferSegment out of the input Buffer.
*/
BufferSegment *seg;
input->moveout(&seg);
/*
* And add it to a temporary Buffer where input is queued.
*/
outq.append(seg);
/*
* And for every byte in this BufferSegment.
*/
const uint8_t *p, *q = seg->end();
for (p = seg->data(); p < q; p++) {
/*
* If we cannot acquire a complete hash within this segment.
*/
if (o + (q - p) < XCODEC_SEGMENT_LENGTH) {
/*
* Hash all of the bytes from it and continue.
*/
o += q - p;
while (p < q)
xcodec_hash.add(*p++);
break;
}
/*
* If we don't have a complete hash.
*/
if (o < XCODEC_SEGMENT_LENGTH) {
for (;;) {
/*
* Add bytes to the hash.
*/
xcodec_hash.add(*p);
/*
* Until we have a complete hash.
*/
if (++o == XCODEC_SEGMENT_LENGTH)
break;
/*
* Go to the next byte.
*/
p++;
}
ASSERT(o == XCODEC_SEGMENT_LENGTH);
} else {
/*
* Roll it into the rolling hash.
*/
xcodec_hash.roll(*p);
o++;
}
ASSERT(o >= XCODEC_SEGMENT_LENGTH);
ASSERT(p != q);
/*
* And then mix the hash's internal state into a
* uint64_t that we can use to refer to that data
* and to look up possible past occurances of that
* data in the XCodecCache.
*/
unsigned start = o - XCODEC_SEGMENT_LENGTH;
uint64_t hash = xcodec_hash.mix();
/*
* If there is a pending candidate hash that wouldn't
* overlap with the data that the rolling hash presently
* covers, declare it now.
*/
if (candidate.set_ && candidate.offset_ + XCODEC_SEGMENT_LENGTH <= start) {
BufferSegment *nseg;
encode_declaration(output, &outq, candidate.offset_, candidate.symbol_, &nseg);
o -= candidate.offset_ + XCODEC_SEGMENT_LENGTH;
start = o - XCODEC_SEGMENT_LENGTH;
candidate.set_ = false;
/*
* If, on top of that, the just-declared hash is
* the same as the current hash, consider referencing
* it immediately.
*/
if (hash == candidate.symbol_) {
/*
* If it's a hash collision, though, nevermind.
* Skip trying to use this hash as a reference,
* too, and go on to the next one.
*/
if (!encode_reference(output, &outq, start, hash, nseg)) {
nseg->unref();
DEBUG(log_) << "Collision in adjacent-declare pass.";
continue;
}
nseg->unref();
/*
* But if there's no collection, then we can move
* on to looking for the *next* hash/data to declare
* or reference.
*/
o = 0;
xcodec_hash.reset();
DEBUG(log_) << "Hit in adjacent-declare pass.";
continue;
}
nseg->unref();
}
/*
* Now attempt to encode this hash as a reference if it
* has been defined before.
*/
BufferSegment *oseg = cache_->lookup(hash);
if (oseg != NULL) {
/*
* This segment already exists. If it's
* identical to this chunk of data, then that's
* positively fantastic.
*/
if (encode_reference(output, &outq, start, hash, oseg)) {
oseg->unref();
o = 0;
xcodec_hash.reset();
/*
* We have output any data before this hash
* in escaped form, so any candidate hash
* before it is invalid now.
*/
candidate.set_ = false;
continue;
}
/*
* This hash isn't usable because it collides
* with another, so keep looking for something
* viable.
*
* XXX
* If this is the first hash (i.e.
* !candidate.set_) then we can adjust the
* start of the current window and escape the
* first byte right away. Does that help?
*/
oseg->unref();
DEBUG(log_) << "Collision in first pass.";
continue;
}
/*
* Not defined before, it's a candidate for declaration
* if we don't already have one.
*/
if (candidate.set_) {
/*
* We already have a hash that occurs earlier,
* isn't a collision and includes data that's
* covered by this hash, so don't remember it
* and keep going.
*/
ASSERT(candidate.offset_ + XCODEC_SEGMENT_LENGTH > start);
continue;
}
/*
* The hash at this offset doesn't collide with any
* other and is the first viable hash we've seen so far
* in the stream, so remember it so that if we don't
* find something to reference we can declare this one
* for future use.
*/
candidate.offset_ = start;
candidate.symbol_ = hash;
candidate.set_ = true;
}
seg->unref();
}
/*
* Done processing input. If there's still data in the outq Buffer,
* then we need to declare any candidate hashes and escape any data
* after them.
*/
/*
* There's a hash we can declare, do it.
*/
if (candidate.set_) {
ASSERT(!outq.empty());
encode_declaration(output, &outq, candidate.offset_, candidate.symbol_, NULL);
candidate.set_ = false;
}
/*
* There's data after that hash or no candidate hash, so
* just escape it.
*/
if (!outq.empty()) {
encode_escape(output, &outq, outq.length());
}
ASSERT(!candidate.set_);
ASSERT(outq.empty());
ASSERT(input->empty());
}
void
XCodecEncoder::encode_declaration(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment **segp)
{
if (offset != 0) {
encode_escape(output, input, offset);
}
BufferSegment *nseg;
input->copyout(&nseg, XCODEC_SEGMENT_LENGTH);
cache_->enter(hash, nseg);
output->append(XCODEC_MAGIC);
output->append(XCODEC_OP_EXTRACT);
output->append(nseg);
window_.declare(hash, nseg);
if (segp == NULL)
nseg->unref();
/*
* Skip to the end.
*/
input->skip(XCODEC_SEGMENT_LENGTH);
if (segp != NULL)
*segp = nseg;
}
void
XCodecEncoder::encode_escape(Buffer *output, Buffer *input, unsigned length)
{
ASSERT(length != 0);
do {
unsigned offset;
if (!input->find(XCODEC_MAGIC, &offset, length)) {
output->append(input, length);
input->skip(length);
return;
}
if (offset != 0) {
output->append(input, offset);
length -= offset;
input->skip(offset);
}
output->append(XCODEC_MAGIC);
output->append(XCODEC_OP_ESCAPE);
length -= sizeof XCODEC_MAGIC;
input->skip(sizeof XCODEC_MAGIC);
} while (length != 0);
}
bool
XCodecEncoder::encode_reference(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment *oseg)
{
uint8_t data[XCODEC_SEGMENT_LENGTH];
input->copyout(data, offset, sizeof data);
if (!oseg->equal(data, sizeof data))
return (false);
if (offset != 0) {
encode_escape(output, input, offset);
}
/*
* Skip to the end.
*/
input->skip(XCODEC_SEGMENT_LENGTH);
/*
* And output a reference.
*/
uint8_t b;
if (window_.present(hash, &b)) {
output->append(XCODEC_MAGIC);
output->append(XCODEC_OP_BACKREF);
output->append(b);
} else {
output->append(XCODEC_MAGIC);
output->append(XCODEC_OP_REF);
uint64_t behash = BigEndian::encode(hash);
output->append(&behash);
window_.declare(hash, oseg);
}
return (true);
}
<|endoftext|> |
<commit_before>// -*- coding: utf-8 -*-
/** \example mujinmovetool.cpp
Shows how to move tool to a specified position and orientation in two ways.
example1: mujinmovetool --controller_hostname=yourhost --robotname=yourrobot --goals=700 600 500 0 0 180
example2: mujinmovetool --controller_hostname=yourhost --robotname=yourrobot --goals=700 600 500 0 0 180 --goaltype=translationdirection5d --movelinear=true
*/
#include <mujincontrollerclient/binpickingtask.h>
#include <iostream>
#if defined(_WIN32) || defined(_WIN64)
#undef GetUserName // clashes with ControllerClient::GetUserName
#endif // defined(_WIN32) || defined(_WIN64)
using namespace mujinclient;
#include <boost/program_options.hpp>
namespace bpo = boost::program_options;
using namespace std;
static string s_robotname;
/// \brief parse command line options and store in a map
/// \param argc number of arguments
/// \param argv arguments
/// \param opts map where parsed options are stored
/// \return true if non-help options are parsed succesfully.
bool ParseOptions(int argc, char ** argv, bpo::variables_map& opts)
{
// parse command line arguments
bpo::options_description desc("Options");
desc.add_options()
("help,h", "produce help message")
("controller_hostname", bpo::value<string>()->required(), "hostname or ip of the mujin controller, e.g. controllerXX or 192.168.0.1")
("controller_port", bpo::value<unsigned int>()->default_value(80), "port of the mujin controller")
("slave_request_id", bpo::value<string>()->default_value(""), "request id of the mujin slave, e.g. controller20_slave0. If empty, uses ")
("controller_username_password", bpo::value<string>()->default_value("testuser:pass"), "username and password to the mujin controller, e.g. username:password")
("controller_command_timeout", bpo::value<double>()->default_value(10), "command timeout in seconds, e.g. 10")
("locale", bpo::value<string>()->default_value("en_US"), "locale to use for the mujin controller client")
("task_scenepk", bpo::value<string>()->default_value(""), "scene pk of the binpicking task on the mujin controller, e.g. officeboltpicking.mujin.dae.")
("robotname", bpo::value<string>()->default_value(""), "robot name.")
("taskparameters", bpo::value<string>()->default_value("{}"), "binpicking task parameters, e.g. {'robotname': 'robot', 'robots':{'robot': {'externalCollisionIO':{}, 'gripperControlInfo':{}, 'robotControllerUri': '', robotDeviceIOUri': '', 'toolname': 'tool'}}}")
("zmq_port", bpo::value<unsigned int>()->default_value(11000), "port of the binpicking task on the mujin controller")
("heartbeat_port", bpo::value<unsigned int>()->default_value(11001), "port of the binpicking task's heartbeat signal on the mujin controller")
("toolname", bpo::value<string>()->default_value(""), "tool name, e.g. flange")
("goaltype", bpo::value<string>()->default_value("transform6d"), "mode to move tool with. Either transform6d or translationdirection5d")
("goals", bpo::value<vector<double> >()->multitoken(), "goal to move tool to, \'X Y Z RX RY RZ\'. Units are in mm and deg.")
("speed", bpo::value<double>()->default_value(0.1), "speed to move at")
("movelinear", bpo::value<bool>()->default_value(false), "whether to move tool linearly")
;
try {
bpo::store(bpo::parse_command_line(argc, argv, desc, bpo::command_line_style::unix_style ^ bpo::command_line_style::allow_short), opts);
}
catch (const exception& ex) {
stringstream errss;
errss << "Caught exception " << ex.what();
cerr << errss.str() << endl;
return false;
}
bool badargs = false;
try {
bpo::notify(opts);
}
catch(const exception& ex) {
stringstream errss;
errss << "Caught exception " << ex.what();
cerr << errss.str() << endl;
badargs = true;
}
if (!badargs) {
badargs = opts.find("goals") == opts.end() || opts["goals"].as<vector<double> >().size() < 6;
}
if(opts.count("help") || badargs) {
cout << "Usage: " << argv[0] << " [OPTS]" << endl;
cout << endl;
cout << desc << endl;
return false;
}
return true;
}
/// \brief initialize BinPickingTask and establish communication with controller
/// \param opts options parsed from command line
/// \param pBinPickingTask bin picking task to be initialized
void InitializeTask(const bpo::variables_map& opts,
BinPickingTaskResourcePtr& pBinpickingTask)
{
const string controllerUsernamePass = opts["controller_username_password"].as<string>();
const double controllerCommandTimeout = opts["controller_command_timeout"].as<double>();
const string taskparameters = opts["taskparameters"].as<string>();
const string locale = opts["locale"].as<string>();
const unsigned int taskZmqPort = opts["zmq_port"].as<unsigned int>();
const string hostname = opts["controller_hostname"].as<string>();
const unsigned int controllerPort = opts["controller_port"].as<unsigned int>();
stringstream urlss;
urlss << "http://" << hostname << ":" << controllerPort;
const unsigned int heartbeatPort = opts["heartbeat_port"].as<unsigned int>();
string slaverequestid = opts["slave_request_id"].as<string>();
string taskScenePk = opts["task_scenepk"].as<string>();
const bool needtoobtainfromheatbeat = taskScenePk.empty() || slaverequestid.empty();
if (needtoobtainfromheatbeat) {
stringstream endpoint;
endpoint << "tcp:\/\/" << hostname << ":" << heartbeatPort;
cout << "connecting to heartbeat at " << endpoint.str() << endl;
string heartbeat;
const size_t num_try_heartbeat(5);
for (size_t it_try_heartbeat = 0; it_try_heartbeat < num_try_heartbeat; ++it_try_heartbeat) {
heartbeat = utils::GetHeartbeat(endpoint.str());
if (!heartbeat.empty()) {
break;
}
cout << "Failed to get heart beat " << it_try_heartbeat << "/" << num_try_heartbeat << "\n";
boost::this_thread::sleep(boost::posix_time::seconds(1));
}
if (heartbeat.empty()) {
throw MujinException(boost::str(boost::format("Failed to obtain heartbeat from %s. Is controller running?")%endpoint.str()));
}
if (taskScenePk.empty()) {
taskScenePk = utils::GetScenePkFromHeatbeat(heartbeat);
cout << "task_scenepk: " << taskScenePk << " is obtained from heatbeat\n";
}
if (slaverequestid.empty()) {
slaverequestid = utils::GetSlaveRequestIdFromHeatbeat(heartbeat);
cout << "slave_request_id: " << slaverequestid << " is obtained from heatbeat\n";
}
}
// cout << taskparameters << endl;
const string tasktype = "realtimeitlplanning";
// connect to mujin controller
ControllerClientPtr controllerclient = CreateControllerClient(controllerUsernamePass, urlss.str());
cout << "connected to mujin controller at " << urlss.str() << endl;
SceneResourcePtr scene(new SceneResource(controllerclient, taskScenePk));
// initialize binpicking task
pBinpickingTask = scene->GetOrCreateBinPickingTaskFromName_UTF8(tasktype+string("task1"), tasktype, TRO_EnableZMQ);
const string userinfo = "{\"username\": \"" + controllerclient->GetUserName() + "\", ""\"locale\": \"" + locale + "\"}";
cout << "initialzing binpickingtask with userinfo=" + userinfo << " taskparameters=" << taskparameters << endl;
s_robotname = opts["robotname"].as<string>();
if (s_robotname.empty()) {
vector<SceneResource::InstObjectPtr> instobjects;
scene->GetInstObjects(instobjects);
for (vector<SceneResource::InstObjectPtr>::const_iterator it = instobjects.begin();
it != instobjects.end(); ++it) {
if (!(**it).dofvalues.empty()) {
s_robotname = (**it).name;
cout << "robot name: " << s_robotname << " is obtained from scene\n";
break;
}
}
if (s_robotname.empty()) {
throw MujinException("Robot name was not given by command line option. Also, failed to obtain robot name from scene.\n");
}
}
boost::shared_ptr<zmq::context_t> zmqcontext(new zmq::context_t(1));
pBinpickingTask->Initialize(taskparameters, taskZmqPort, heartbeatPort, zmqcontext, false, 10, controllerCommandTimeout, userinfo, slaverequestid);
}
/// \brief convert state of bin picking task to string
/// \param state state to convert to string
/// \return state converted to string
string ConvertStateToString(const BinPickingTaskResource::ResultGetBinpickingState& state)
{
if (state.currentJointValues.empty() || state.currentToolValues.size() < 6) {
stringstream ss;
ss << "Failed to obtain robot state: joint values have "
<< state.currentJointValues.size() << " elements and tool values have "
<< state.currentToolValues.size() << " elements\n";
throw std::runtime_error(ss.str());
}
stringstream ss;
ss << state.timestamp << " (ms): joint:";
for (size_t i = 0; i < state.currentJointValues.size(); ++i) {
ss << state.jointNames[i] << "=" << state.currentJointValues[i] << " ";
}
ss << "X=" << state.currentToolValues[0] << " ";
ss << "Y=" << state.currentToolValues[1] << " ";
ss << "Z=" << state.currentToolValues[2] << " ";
ss << "RX=" << state.currentToolValues[3] << " ";
ss << "RY=" << state.currentToolValues[4] << " ";
ss << "RZ=" << state.currentToolValues[5];
return ss.str();
}
/// \brief run hand moving task
/// \param pTask task
/// \param goaltype whether to specify goal in 6 dimension(transform6d) or 5 dimension(translationdirection5d)
/// \param goals goal of the hand
/// \param speed speed to move at
/// \param robotname robot name
/// \param toolname tool name
/// \param whether to move in line or not
void Run(BinPickingTaskResourcePtr& pTask,
const string& goaltype,
const vector<double>& goals,
double speed,
const string& robotname,
const string& toolname,
bool movelinear)
{
// print state
BinPickingTaskResource::ResultGetBinpickingState result;
pTask->GetPublishedTaskState(result, robotname, "mm", 1.0);
cout << "Starting:\n" << ConvertStateToString(result) << endl;
// start moving
if (movelinear) {
pTask->MoveToolLinear(goaltype, goals, robotname, toolname, speed);
}
else {
pTask->MoveToHandPosition(goaltype, goals, robotname, toolname, speed);
}
// print state
pTask->GetPublishedTaskState(result, robotname, "mm", 1.0);
cout << "Finished:\n" << ConvertStateToString(result) << endl;
}
int main(int argc, char ** argv)
{
// parsing options
bpo::variables_map opts;
if (!ParseOptions(argc, argv, opts)) {
// parsing option failed
return 1;
}
const string robotname = opts["robotname"].as<string>();
const string toolname = opts["toolname"].as<string>();
const vector<double> goals = opts["goals"].as<vector<double> >();
const string goaltype = opts["goaltype"].as<string>();
const double speed = opts["speed"].as<double>();
const bool movelinearly = opts["movelinear"].as<bool>();
// initializing
BinPickingTaskResourcePtr pBinpickingTask;
InitializeTask(opts, pBinpickingTask);
// do interesting part
Run(pBinpickingTask, goaltype, goals, speed, s_robotname, toolname, movelinearly);
return 0;
}
<commit_msg>bug fix ignored timeout<commit_after>// -*- coding: utf-8 -*-
/** \example mujinmovetool.cpp
Shows how to move tool to a specified position and orientation in two ways.
example1: mujinmovetool --controller_hostname=yourhost --robotname=yourrobot --goals=700 600 500 0 0 180
example2: mujinmovetool --controller_hostname=yourhost --robotname=yourrobot --goals=700 600 500 0 0 180 --goaltype=translationdirection5d --movelinear=true
*/
#include <mujincontrollerclient/binpickingtask.h>
#include <iostream>
#if defined(_WIN32) || defined(_WIN64)
#undef GetUserName // clashes with ControllerClient::GetUserName
#endif // defined(_WIN32) || defined(_WIN64)
using namespace mujinclient;
#include <boost/program_options.hpp>
namespace bpo = boost::program_options;
using namespace std;
static string s_robotname;
/// \brief parse command line options and store in a map
/// \param argc number of arguments
/// \param argv arguments
/// \param opts map where parsed options are stored
/// \return true if non-help options are parsed succesfully.
bool ParseOptions(int argc, char ** argv, bpo::variables_map& opts)
{
// parse command line arguments
bpo::options_description desc("Options");
desc.add_options()
("help,h", "produce help message")
("controller_hostname", bpo::value<string>()->required(), "hostname or ip of the mujin controller, e.g. controllerXX or 192.168.0.1")
("controller_port", bpo::value<unsigned int>()->default_value(80), "port of the mujin controller")
("slave_request_id", bpo::value<string>()->default_value(""), "request id of the mujin slave, e.g. controller20_slave0. If empty, uses ")
("controller_username_password", bpo::value<string>()->default_value("testuser:pass"), "username and password to the mujin controller, e.g. username:password")
("controller_command_timeout", bpo::value<double>()->default_value(10), "command timeout in seconds, e.g. 10")
("locale", bpo::value<string>()->default_value("en_US"), "locale to use for the mujin controller client")
("task_scenepk", bpo::value<string>()->default_value(""), "scene pk of the binpicking task on the mujin controller, e.g. officeboltpicking.mujin.dae.")
("robotname", bpo::value<string>()->default_value(""), "robot name.")
("taskparameters", bpo::value<string>()->default_value("{}"), "binpicking task parameters, e.g. {'robotname': 'robot', 'robots':{'robot': {'externalCollisionIO':{}, 'gripperControlInfo':{}, 'robotControllerUri': '', robotDeviceIOUri': '', 'toolname': 'tool'}}}")
("zmq_port", bpo::value<unsigned int>()->default_value(11000), "port of the binpicking task on the mujin controller")
("heartbeat_port", bpo::value<unsigned int>()->default_value(11001), "port of the binpicking task's heartbeat signal on the mujin controller")
("toolname", bpo::value<string>()->default_value(""), "tool name, e.g. flange")
("goaltype", bpo::value<string>()->default_value("transform6d"), "mode to move tool with. Either transform6d or translationdirection5d")
("goals", bpo::value<vector<double> >()->multitoken(), "goal to move tool to, \'X Y Z RX RY RZ\'. Units are in mm and deg.")
("speed", bpo::value<double>()->default_value(0.1), "speed to move at")
("movelinear", bpo::value<bool>()->default_value(false), "whether to move tool linearly")
;
try {
bpo::store(bpo::parse_command_line(argc, argv, desc, bpo::command_line_style::unix_style ^ bpo::command_line_style::allow_short), opts);
}
catch (const exception& ex) {
stringstream errss;
errss << "Caught exception " << ex.what();
cerr << errss.str() << endl;
return false;
}
bool badargs = false;
try {
bpo::notify(opts);
}
catch(const exception& ex) {
stringstream errss;
errss << "Caught exception " << ex.what();
cerr << errss.str() << endl;
badargs = true;
}
if (!badargs) {
badargs = opts.find("goals") == opts.end() || opts["goals"].as<vector<double> >().size() < 6;
}
if(opts.count("help") || badargs) {
cout << "Usage: " << argv[0] << " [OPTS]" << endl;
cout << endl;
cout << desc << endl;
return false;
}
return true;
}
/// \brief initialize BinPickingTask and establish communication with controller
/// \param opts options parsed from command line
/// \param pBinPickingTask bin picking task to be initialized
void InitializeTask(const bpo::variables_map& opts,
BinPickingTaskResourcePtr& pBinpickingTask)
{
const string controllerUsernamePass = opts["controller_username_password"].as<string>();
const double controllerCommandTimeout = opts["controller_command_timeout"].as<double>();
const string taskparameters = opts["taskparameters"].as<string>();
const string locale = opts["locale"].as<string>();
const unsigned int taskZmqPort = opts["zmq_port"].as<unsigned int>();
const string hostname = opts["controller_hostname"].as<string>();
const unsigned int controllerPort = opts["controller_port"].as<unsigned int>();
stringstream urlss;
urlss << "http://" << hostname << ":" << controllerPort;
const unsigned int heartbeatPort = opts["heartbeat_port"].as<unsigned int>();
string slaverequestid = opts["slave_request_id"].as<string>();
string taskScenePk = opts["task_scenepk"].as<string>();
const bool needtoobtainfromheatbeat = taskScenePk.empty() || slaverequestid.empty();
if (needtoobtainfromheatbeat) {
stringstream endpoint;
endpoint << "tcp:\/\/" << hostname << ":" << heartbeatPort;
cout << "connecting to heartbeat at " << endpoint.str() << endl;
string heartbeat;
const size_t num_try_heartbeat(5);
for (size_t it_try_heartbeat = 0; it_try_heartbeat < num_try_heartbeat; ++it_try_heartbeat) {
heartbeat = utils::GetHeartbeat(endpoint.str());
if (!heartbeat.empty()) {
break;
}
cout << "Failed to get heart beat " << it_try_heartbeat << "/" << num_try_heartbeat << "\n";
boost::this_thread::sleep(boost::posix_time::seconds(1));
}
if (heartbeat.empty()) {
throw MujinException(boost::str(boost::format("Failed to obtain heartbeat from %s. Is controller running?")%endpoint.str()));
}
if (taskScenePk.empty()) {
taskScenePk = utils::GetScenePkFromHeatbeat(heartbeat);
cout << "task_scenepk: " << taskScenePk << " is obtained from heatbeat\n";
}
if (slaverequestid.empty()) {
slaverequestid = utils::GetSlaveRequestIdFromHeatbeat(heartbeat);
cout << "slave_request_id: " << slaverequestid << " is obtained from heatbeat\n";
}
}
// cout << taskparameters << endl;
const string tasktype = "realtimeitlplanning";
// connect to mujin controller
ControllerClientPtr controllerclient = CreateControllerClient(controllerUsernamePass, urlss.str());
cout << "connected to mujin controller at " << urlss.str() << endl;
SceneResourcePtr scene(new SceneResource(controllerclient, taskScenePk));
// initialize binpicking task
pBinpickingTask = scene->GetOrCreateBinPickingTaskFromName_UTF8(tasktype+string("task1"), tasktype, TRO_EnableZMQ);
const string userinfo = "{\"username\": \"" + controllerclient->GetUserName() + "\", ""\"locale\": \"" + locale + "\"}";
cout << "initialzing binpickingtask with userinfo=" + userinfo << " taskparameters=" << taskparameters << endl;
s_robotname = opts["robotname"].as<string>();
if (s_robotname.empty()) {
vector<SceneResource::InstObjectPtr> instobjects;
scene->GetInstObjects(instobjects);
for (vector<SceneResource::InstObjectPtr>::const_iterator it = instobjects.begin();
it != instobjects.end(); ++it) {
if (!(**it).dofvalues.empty()) {
s_robotname = (**it).name;
cout << "robot name: " << s_robotname << " is obtained from scene\n";
break;
}
}
if (s_robotname.empty()) {
throw MujinException("Robot name was not given by command line option. Also, failed to obtain robot name from scene.\n");
}
}
boost::shared_ptr<zmq::context_t> zmqcontext(new zmq::context_t(1));
pBinpickingTask->Initialize(taskparameters, taskZmqPort, heartbeatPort, zmqcontext, false, controllerCommandTimeout, controllerCommandTimeout, userinfo, slaverequestid);
}
/// \brief convert state of bin picking task to string
/// \param state state to convert to string
/// \return state converted to string
string ConvertStateToString(const BinPickingTaskResource::ResultGetBinpickingState& state)
{
if (state.currentJointValues.empty() || state.currentToolValues.size() < 6) {
stringstream ss;
ss << "Failed to obtain robot state: joint values have "
<< state.currentJointValues.size() << " elements and tool values have "
<< state.currentToolValues.size() << " elements\n";
throw std::runtime_error(ss.str());
}
stringstream ss;
ss << state.timestamp << " (ms): joint:";
for (size_t i = 0; i < state.currentJointValues.size(); ++i) {
ss << state.jointNames[i] << "=" << state.currentJointValues[i] << " ";
}
ss << "X=" << state.currentToolValues[0] << " ";
ss << "Y=" << state.currentToolValues[1] << " ";
ss << "Z=" << state.currentToolValues[2] << " ";
ss << "RX=" << state.currentToolValues[3] << " ";
ss << "RY=" << state.currentToolValues[4] << " ";
ss << "RZ=" << state.currentToolValues[5];
return ss.str();
}
/// \brief run hand moving task
/// \param pTask task
/// \param goaltype whether to specify goal in 6 dimension(transform6d) or 5 dimension(translationdirection5d)
/// \param goals goal of the hand
/// \param speed speed to move at
/// \param robotname robot name
/// \param toolname tool name
/// \param whether to move in line or not
void Run(BinPickingTaskResourcePtr& pTask,
const string& goaltype,
const vector<double>& goals,
double speed,
const string& robotname,
const string& toolname,
bool movelinear,
double timeout)
{
// print state
BinPickingTaskResource::ResultGetBinpickingState result;
pTask->GetPublishedTaskState(result, robotname, "mm", 1.0);
cout << "Starting:\n" << ConvertStateToString(result) << endl;
// start moving
if (movelinear) {
pTask->MoveToolLinear(goaltype, goals, robotname, toolname, speed, timeout);
}
else {
pTask->MoveToHandPosition(goaltype, goals, robotname, toolname, speed, timeout);
}
// print state
pTask->GetPublishedTaskState(result, robotname, "mm", 1.0);
cout << "Finished:\n" << ConvertStateToString(result) << endl;
}
int main(int argc, char ** argv)
{
// parsing options
bpo::variables_map opts;
if (!ParseOptions(argc, argv, opts)) {
// parsing option failed
return 1;
}
const string robotname = opts["robotname"].as<string>();
const string toolname = opts["toolname"].as<string>();
const vector<double> goals = opts["goals"].as<vector<double> >();
const string goaltype = opts["goaltype"].as<string>();
const double speed = opts["speed"].as<double>();
const bool movelinearly = opts["movelinear"].as<bool>();
const double timeout = opts["controller_command_timeout"].as<double>();
// initializing
BinPickingTaskResourcePtr pBinpickingTask;
InitializeTask(opts, pBinpickingTask);
// do interesting part
Run(pBinpickingTask, goaltype, goals, speed, s_robotname, toolname, movelinearly, timeout);
return 0;
}
<|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 file.
#include "chrome/browser/gtk/location_bar_view_gtk.h"
#include <string>
#include "app/resource_bundle.h"
#include "base/basictypes.h"
#include "base/gfx/gtk_util.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/alternate_nav_url_fetcher.h"
#include "chrome/browser/autocomplete/autocomplete_edit_view_gtk.h"
#include "chrome/browser/command_updater.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/page_transition_types.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "webkit/glue/window_open_disposition.h"
namespace {
// We are positioned with a little bit of extra space that we don't use now.
const int kTopMargin = 1;
const int kBottomMargin = 1;
// We don't want to edit control's text to be right against the edge.
const int kEditLeftRightPadding = 4;
// We draw a border on the top and bottom (but not on left or right).
const int kBorderThickness = 1;
// Padding around the security icon.
const int kSecurityIconPaddingLeft = 4;
const int kSecurityIconPaddingRight = 2;
// TODO(deanm): Eventually this should be painted with the background png
// image, but for now we get pretty close by just drawing a solid border.
const GdkColor kBorderColor = GDK_COLOR_RGB(0xbe, 0xc8, 0xd4);
} // namespace
// static
const GdkColor LocationBarViewGtk::kBackgroundColorByLevel[3] = {
GDK_COLOR_RGB(255, 245, 195), // SecurityLevel SECURE: Yellow.
GDK_COLOR_RGB(255, 255, 255), // SecurityLevel NORMAL: White.
GDK_COLOR_RGB(255, 255, 255), // SecurityLevel INSECURE: White.
};
LocationBarViewGtk::LocationBarViewGtk(CommandUpdater* command_updater,
ToolbarModel* toolbar_model, AutocompletePopupPositioner* popup_positioner)
: security_icon_(NULL),
profile_(NULL),
command_updater_(command_updater),
toolbar_model_(toolbar_model),
popup_positioner_(popup_positioner),
disposition_(CURRENT_TAB),
transition_(PageTransition::TYPED) {
}
LocationBarViewGtk::~LocationBarViewGtk() {
// All of our widgets should have be children of / owned by the alignment.
alignment_.Destroy();
}
void LocationBarViewGtk::Init() {
location_entry_.reset(new AutocompleteEditViewGtk(this,
toolbar_model_,
profile_,
command_updater_,
popup_positioner_));
location_entry_->Init();
alignment_.Own(gtk_alignment_new(0.0, 0.0, 1.0, 1.0));
UpdateAlignmentPadding();
// We will paint for the alignment, to paint the background and border.
gtk_widget_set_app_paintable(alignment_.get(), TRUE);
// Have GTK double buffer around the expose signal.
gtk_widget_set_double_buffered(alignment_.get(), TRUE);
g_signal_connect(alignment_.get(), "expose-event",
G_CALLBACK(&HandleExposeThunk), this);
gtk_container_add(GTK_CONTAINER(alignment_.get()),
location_entry_->widget());
}
void LocationBarViewGtk::SetProfile(Profile* profile) {
profile_ = profile;
}
void LocationBarViewGtk::Update(const TabContents* contents) {
SetSecurityIcon(toolbar_model_->GetIcon());
location_entry_->Update(contents);
// The security level (background color) could have changed, etc.
gtk_widget_queue_draw(alignment_.get());
}
void LocationBarViewGtk::OnAutocompleteAccept(const GURL& url,
WindowOpenDisposition disposition,
PageTransition::Type transition,
const GURL& alternate_nav_url) {
if (!url.is_valid())
return;
location_input_ = UTF8ToWide(url.spec());
disposition_ = disposition;
transition_ = transition;
if (!command_updater_)
return;
if (!alternate_nav_url.is_valid()) {
command_updater_->ExecuteCommand(IDC_OPEN_CURRENT_URL);
return;
}
scoped_ptr<AlternateNavURLFetcher> fetcher(
new AlternateNavURLFetcher(alternate_nav_url));
// The AlternateNavURLFetcher will listen for the pending navigation
// notification that will be issued as a result of the "open URL." It
// will automatically install itself into that navigation controller.
command_updater_->ExecuteCommand(IDC_OPEN_CURRENT_URL);
if (fetcher->state() == AlternateNavURLFetcher::NOT_STARTED) {
// I'm not sure this should be reachable, but I'm not also sure enough
// that it shouldn't to stick in a NOTREACHED(). In any case, this is
// harmless; we can simply let the fetcher get deleted here and it will
// clean itself up properly.
} else {
fetcher.release(); // The navigation controller will delete the fetcher.
}
}
void LocationBarViewGtk::OnChanged() {
// TODO(deanm): Here is where we would do layout when we have things like
// the keyword display, ssl icons, etc.
}
void LocationBarViewGtk::OnInputInProgress(bool in_progress) {
NOTIMPLEMENTED();
}
SkBitmap LocationBarViewGtk::GetFavIcon() const {
NOTIMPLEMENTED();
return SkBitmap();
}
std::wstring LocationBarViewGtk::GetTitle() const {
NOTIMPLEMENTED();
return std::wstring();
}
void LocationBarViewGtk::ShowFirstRunBubble() {
NOTIMPLEMENTED();
}
std::wstring LocationBarViewGtk::GetInputString() const {
return location_input_;
}
WindowOpenDisposition LocationBarViewGtk::GetWindowOpenDisposition() const {
return disposition_;
}
PageTransition::Type LocationBarViewGtk::GetPageTransition() const {
return transition_;
}
void LocationBarViewGtk::AcceptInput() {
AcceptInputWithDisposition(CURRENT_TAB);
}
void LocationBarViewGtk::AcceptInputWithDisposition(
WindowOpenDisposition disposition) {
location_entry_->model()->AcceptInput(disposition, false);
}
void LocationBarViewGtk::FocusLocation() {
location_entry_->SetFocus();
location_entry_->SelectAll(true);
}
void LocationBarViewGtk::FocusSearch() {
location_entry_->SetUserText(L"?");
location_entry_->SetFocus();
}
void LocationBarViewGtk::UpdatePageActions() {
NOTIMPLEMENTED();
}
void LocationBarViewGtk::SaveStateToContents(TabContents* contents) {
NOTIMPLEMENTED();
}
void LocationBarViewGtk::Revert() {
location_entry_->RevertAll();
}
gboolean LocationBarViewGtk::HandleExpose(GtkWidget* widget,
GdkEventExpose* event) {
GdkDrawable* drawable = GDK_DRAWABLE(event->window);
GdkGC* gc = gdk_gc_new(drawable);
GdkRectangle* alloc_rect = &alignment_.get()->allocation;
// The area outside of our margin, which includes the border.
GdkRectangle inner_rect = {
alloc_rect->x,
alloc_rect->y + kTopMargin,
alloc_rect->width,
alloc_rect->height - kTopMargin - kBottomMargin};
// Some of our calculations are a bit sloppy. Since we draw on our parent
// window, set a clip to make sure that we don't draw outside.
gdk_gc_set_clip_rectangle(gc, &inner_rect);
// Draw our 1px border. TODO(deanm): Maybe this would be cleaner as an
// overdrawn stroked rect with a clip to the allocation?
gdk_gc_set_rgb_fg_color(gc, &kBorderColor);
gdk_draw_rectangle(drawable, gc, TRUE,
inner_rect.x,
inner_rect.y,
inner_rect.width,
kBorderThickness);
gdk_draw_rectangle(drawable, gc, TRUE,
inner_rect.x,
inner_rect.y + inner_rect.height - kBorderThickness,
inner_rect.width,
kBorderThickness);
// Draw the background within the border.
gdk_gc_set_rgb_fg_color(gc,
&kBackgroundColorByLevel[toolbar_model_->GetSchemeSecurityLevel()]);
gdk_draw_rectangle(drawable, gc, TRUE,
inner_rect.x,
inner_rect.y + kBorderThickness,
inner_rect.width,
inner_rect.height - (kBorderThickness * 2));
// If we have an SSL icon, draw it vertically centered on the right side.
if (security_icon_) {
int icon_width = gdk_pixbuf_get_width(security_icon_);
int icon_height = gdk_pixbuf_get_height(security_icon_);
int icon_x = inner_rect.x + inner_rect.width -
kBorderThickness - icon_width - kSecurityIconPaddingRight;
int icon_y = inner_rect.y +
((inner_rect.height - icon_height) / 2);
gdk_draw_pixbuf(drawable, gc, security_icon_,
0, 0, icon_x, icon_y, -1, -1,
GDK_RGB_DITHER_NONE, 0, 0);
}
g_object_unref(gc);
return FALSE; // Continue propagating the expose.
}
void LocationBarViewGtk::UpdateAlignmentPadding() {
// When we have an icon, increase our right padding to make space for it.
int right_padding = security_icon_ ? gdk_pixbuf_get_width(security_icon_) +
kSecurityIconPaddingLeft + kSecurityIconPaddingRight :
kEditLeftRightPadding;
gtk_alignment_set_padding(GTK_ALIGNMENT(alignment_.get()),
kTopMargin + kBorderThickness,
kBottomMargin + kBorderThickness,
kEditLeftRightPadding, right_padding);
}
void LocationBarViewGtk::SetSecurityIcon(ToolbarModel::Icon icon) {
static ResourceBundle& rb = ResourceBundle::GetSharedInstance();
static GdkPixbuf* kLockIcon = rb.GetPixbufNamed(IDR_LOCK);
static GdkPixbuf* kWarningIcon = rb.GetPixbufNamed(IDR_WARNING);
switch (icon) {
case ToolbarModel::LOCK_ICON:
security_icon_ = kLockIcon;
break;
case ToolbarModel::WARNING_ICON:
security_icon_ = kWarningIcon;
break;
case ToolbarModel::NO_ICON:
security_icon_ = NULL;
break;
default:
NOTREACHED();
security_icon_ = NULL;
break;
}
// Make sure there is room for the icon.
UpdateAlignmentPadding();
}
<commit_msg>linux: not supporting page actions is a bug.<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 file.
#include "chrome/browser/gtk/location_bar_view_gtk.h"
#include <string>
#include "app/resource_bundle.h"
#include "base/basictypes.h"
#include "base/gfx/gtk_util.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/alternate_nav_url_fetcher.h"
#include "chrome/browser/autocomplete/autocomplete_edit_view_gtk.h"
#include "chrome/browser/command_updater.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/page_transition_types.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "webkit/glue/window_open_disposition.h"
namespace {
// We are positioned with a little bit of extra space that we don't use now.
const int kTopMargin = 1;
const int kBottomMargin = 1;
// We don't want to edit control's text to be right against the edge.
const int kEditLeftRightPadding = 4;
// We draw a border on the top and bottom (but not on left or right).
const int kBorderThickness = 1;
// Padding around the security icon.
const int kSecurityIconPaddingLeft = 4;
const int kSecurityIconPaddingRight = 2;
// TODO(deanm): Eventually this should be painted with the background png
// image, but for now we get pretty close by just drawing a solid border.
const GdkColor kBorderColor = GDK_COLOR_RGB(0xbe, 0xc8, 0xd4);
} // namespace
// static
const GdkColor LocationBarViewGtk::kBackgroundColorByLevel[3] = {
GDK_COLOR_RGB(255, 245, 195), // SecurityLevel SECURE: Yellow.
GDK_COLOR_RGB(255, 255, 255), // SecurityLevel NORMAL: White.
GDK_COLOR_RGB(255, 255, 255), // SecurityLevel INSECURE: White.
};
LocationBarViewGtk::LocationBarViewGtk(CommandUpdater* command_updater,
ToolbarModel* toolbar_model, AutocompletePopupPositioner* popup_positioner)
: security_icon_(NULL),
profile_(NULL),
command_updater_(command_updater),
toolbar_model_(toolbar_model),
popup_positioner_(popup_positioner),
disposition_(CURRENT_TAB),
transition_(PageTransition::TYPED) {
}
LocationBarViewGtk::~LocationBarViewGtk() {
// All of our widgets should have be children of / owned by the alignment.
alignment_.Destroy();
}
void LocationBarViewGtk::Init() {
location_entry_.reset(new AutocompleteEditViewGtk(this,
toolbar_model_,
profile_,
command_updater_,
popup_positioner_));
location_entry_->Init();
alignment_.Own(gtk_alignment_new(0.0, 0.0, 1.0, 1.0));
UpdateAlignmentPadding();
// We will paint for the alignment, to paint the background and border.
gtk_widget_set_app_paintable(alignment_.get(), TRUE);
// Have GTK double buffer around the expose signal.
gtk_widget_set_double_buffered(alignment_.get(), TRUE);
g_signal_connect(alignment_.get(), "expose-event",
G_CALLBACK(&HandleExposeThunk), this);
gtk_container_add(GTK_CONTAINER(alignment_.get()),
location_entry_->widget());
}
void LocationBarViewGtk::SetProfile(Profile* profile) {
profile_ = profile;
}
void LocationBarViewGtk::Update(const TabContents* contents) {
SetSecurityIcon(toolbar_model_->GetIcon());
location_entry_->Update(contents);
// The security level (background color) could have changed, etc.
gtk_widget_queue_draw(alignment_.get());
}
void LocationBarViewGtk::OnAutocompleteAccept(const GURL& url,
WindowOpenDisposition disposition,
PageTransition::Type transition,
const GURL& alternate_nav_url) {
if (!url.is_valid())
return;
location_input_ = UTF8ToWide(url.spec());
disposition_ = disposition;
transition_ = transition;
if (!command_updater_)
return;
if (!alternate_nav_url.is_valid()) {
command_updater_->ExecuteCommand(IDC_OPEN_CURRENT_URL);
return;
}
scoped_ptr<AlternateNavURLFetcher> fetcher(
new AlternateNavURLFetcher(alternate_nav_url));
// The AlternateNavURLFetcher will listen for the pending navigation
// notification that will be issued as a result of the "open URL." It
// will automatically install itself into that navigation controller.
command_updater_->ExecuteCommand(IDC_OPEN_CURRENT_URL);
if (fetcher->state() == AlternateNavURLFetcher::NOT_STARTED) {
// I'm not sure this should be reachable, but I'm not also sure enough
// that it shouldn't to stick in a NOTREACHED(). In any case, this is
// harmless; we can simply let the fetcher get deleted here and it will
// clean itself up properly.
} else {
fetcher.release(); // The navigation controller will delete the fetcher.
}
}
void LocationBarViewGtk::OnChanged() {
// TODO(deanm): Here is where we would do layout when we have things like
// the keyword display, ssl icons, etc.
}
void LocationBarViewGtk::OnInputInProgress(bool in_progress) {
NOTIMPLEMENTED();
}
SkBitmap LocationBarViewGtk::GetFavIcon() const {
NOTIMPLEMENTED();
return SkBitmap();
}
std::wstring LocationBarViewGtk::GetTitle() const {
NOTIMPLEMENTED();
return std::wstring();
}
void LocationBarViewGtk::ShowFirstRunBubble() {
NOTIMPLEMENTED();
}
std::wstring LocationBarViewGtk::GetInputString() const {
return location_input_;
}
WindowOpenDisposition LocationBarViewGtk::GetWindowOpenDisposition() const {
return disposition_;
}
PageTransition::Type LocationBarViewGtk::GetPageTransition() const {
return transition_;
}
void LocationBarViewGtk::AcceptInput() {
AcceptInputWithDisposition(CURRENT_TAB);
}
void LocationBarViewGtk::AcceptInputWithDisposition(
WindowOpenDisposition disposition) {
location_entry_->model()->AcceptInput(disposition, false);
}
void LocationBarViewGtk::FocusLocation() {
location_entry_->SetFocus();
location_entry_->SelectAll(true);
}
void LocationBarViewGtk::FocusSearch() {
location_entry_->SetUserText(L"?");
location_entry_->SetFocus();
}
void LocationBarViewGtk::UpdatePageActions() {
// http://code.google.com/p/chromium/issues/detail?id=11973
}
void LocationBarViewGtk::SaveStateToContents(TabContents* contents) {
NOTIMPLEMENTED();
}
void LocationBarViewGtk::Revert() {
location_entry_->RevertAll();
}
gboolean LocationBarViewGtk::HandleExpose(GtkWidget* widget,
GdkEventExpose* event) {
GdkDrawable* drawable = GDK_DRAWABLE(event->window);
GdkGC* gc = gdk_gc_new(drawable);
GdkRectangle* alloc_rect = &alignment_.get()->allocation;
// The area outside of our margin, which includes the border.
GdkRectangle inner_rect = {
alloc_rect->x,
alloc_rect->y + kTopMargin,
alloc_rect->width,
alloc_rect->height - kTopMargin - kBottomMargin};
// Some of our calculations are a bit sloppy. Since we draw on our parent
// window, set a clip to make sure that we don't draw outside.
gdk_gc_set_clip_rectangle(gc, &inner_rect);
// Draw our 1px border. TODO(deanm): Maybe this would be cleaner as an
// overdrawn stroked rect with a clip to the allocation?
gdk_gc_set_rgb_fg_color(gc, &kBorderColor);
gdk_draw_rectangle(drawable, gc, TRUE,
inner_rect.x,
inner_rect.y,
inner_rect.width,
kBorderThickness);
gdk_draw_rectangle(drawable, gc, TRUE,
inner_rect.x,
inner_rect.y + inner_rect.height - kBorderThickness,
inner_rect.width,
kBorderThickness);
// Draw the background within the border.
gdk_gc_set_rgb_fg_color(gc,
&kBackgroundColorByLevel[toolbar_model_->GetSchemeSecurityLevel()]);
gdk_draw_rectangle(drawable, gc, TRUE,
inner_rect.x,
inner_rect.y + kBorderThickness,
inner_rect.width,
inner_rect.height - (kBorderThickness * 2));
// If we have an SSL icon, draw it vertically centered on the right side.
if (security_icon_) {
int icon_width = gdk_pixbuf_get_width(security_icon_);
int icon_height = gdk_pixbuf_get_height(security_icon_);
int icon_x = inner_rect.x + inner_rect.width -
kBorderThickness - icon_width - kSecurityIconPaddingRight;
int icon_y = inner_rect.y +
((inner_rect.height - icon_height) / 2);
gdk_draw_pixbuf(drawable, gc, security_icon_,
0, 0, icon_x, icon_y, -1, -1,
GDK_RGB_DITHER_NONE, 0, 0);
}
g_object_unref(gc);
return FALSE; // Continue propagating the expose.
}
void LocationBarViewGtk::UpdateAlignmentPadding() {
// When we have an icon, increase our right padding to make space for it.
int right_padding = security_icon_ ? gdk_pixbuf_get_width(security_icon_) +
kSecurityIconPaddingLeft + kSecurityIconPaddingRight :
kEditLeftRightPadding;
gtk_alignment_set_padding(GTK_ALIGNMENT(alignment_.get()),
kTopMargin + kBorderThickness,
kBottomMargin + kBorderThickness,
kEditLeftRightPadding, right_padding);
}
void LocationBarViewGtk::SetSecurityIcon(ToolbarModel::Icon icon) {
static ResourceBundle& rb = ResourceBundle::GetSharedInstance();
static GdkPixbuf* kLockIcon = rb.GetPixbufNamed(IDR_LOCK);
static GdkPixbuf* kWarningIcon = rb.GetPixbufNamed(IDR_WARNING);
switch (icon) {
case ToolbarModel::LOCK_ICON:
security_icon_ = kLockIcon;
break;
case ToolbarModel::WARNING_ICON:
security_icon_ = kWarningIcon;
break;
case ToolbarModel::NO_ICON:
security_icon_ = NULL;
break;
default:
NOTREACHED();
security_icon_ = NULL;
break;
}
// Make sure there is room for the icon.
UpdateAlignmentPadding();
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
#include <osl/thread.h>
#include <sfx2/linkmgr.hxx>
#include <doc.hxx>
#include <editsh.hxx>
#include <ndtxt.hxx>
#include <fmtfld.hxx>
#include <txtfld.hxx>
#include <ddefld.hxx>
#include <swtable.hxx>
#include <swbaslnk.hxx>
#include <swddetbl.hxx>
#include <unofldmid.h>
#include <hints.hxx>
using namespace ::com::sun::star;
#define DDE_TXT_ENCODING osl_getThreadTextEncoding()
class SwIntrnlRefLink : public SwBaseLink
{
SwDDEFieldType& rFldType;
public:
SwIntrnlRefLink( SwDDEFieldType& rType, sal_uInt16 nUpdateType, sal_uInt16 nFmt )
: SwBaseLink( nUpdateType, nFmt ),
rFldType( rType )
{}
virtual void Closed() SAL_OVERRIDE;
virtual ::sfx2::SvBaseLink::UpdateResult DataChanged(
const OUString& rMimeType, const ::com::sun::star::uno::Any & rValue ) SAL_OVERRIDE;
virtual const SwNode* GetAnchor() const SAL_OVERRIDE;
virtual bool IsInRange( sal_uLong nSttNd, sal_uLong nEndNd, sal_Int32 nStt = 0,
sal_Int32 nEnd = -1 ) const SAL_OVERRIDE;
};
::sfx2::SvBaseLink::UpdateResult SwIntrnlRefLink::DataChanged( const OUString& rMimeType,
const uno::Any & rValue )
{
switch( SotExchange::GetFormatIdFromMimeType( rMimeType ) )
{
case FORMAT_STRING:
if( !IsNoDataFlag() )
{
uno::Sequence< sal_Int8 > aSeq;
rValue >>= aSeq;
OUString sStr( (sal_Char*)aSeq.getConstArray(), aSeq.getLength(), DDE_TXT_ENCODING );
// remove not needed CR-LF at the end
sal_Int32 n = sStr.getLength();
while( n && 0 == sStr[ n-1 ] )
--n;
if( n && 0x0a == sStr[ n-1 ] )
--n;
if( n && 0x0d == sStr[ n-1 ] )
--n;
bool bDel = n != sStr.getLength();
if( bDel )
sStr = sStr.copy( 0, n );
rFldType.SetExpansion( sStr );
// set Expansion first! (otherwise this flag will be deleted)
rFldType.SetCRLFDelFlag( bDel );
}
break;
// other formats
default:
return SUCCESS;
}
OSL_ENSURE( rFldType.GetDoc(), "no pDoc" );
// no dependencies left?
if( rFldType.GetDepends() && !rFldType.IsModifyLocked() && !ChkNoDataFlag() )
{
SwViewShell* pSh;
SwEditShell* pESh = rFldType.GetDoc()->GetEditShell( &pSh );
// Search for fields. If no valid found, disconnect.
SwMsgPoolItem aUpdateDDE( RES_UPDATEDDETBL );
int bCallModify = sal_False;
rFldType.LockModify();
SwClientIter aIter( rFldType ); // TODO
SwClient * pLast = aIter.GoStart();
if( pLast ) // Could we jump to beginning?
do {
// a DDE table or a DDE field attribute in the text
if( !pLast->IsA( TYPE( SwFmtFld ) ) ||
((SwFmtFld*)pLast)->GetTxtFld() )
{
if( !bCallModify )
{
if( pESh )
pESh->StartAllAction();
else if( pSh )
pSh->StartAction();
}
pLast->ModifyNotification( 0, &aUpdateDDE );
bCallModify = sal_True;
}
} while( 0 != ( pLast = ++aIter ));
rFldType.UnlockModify();
if( bCallModify )
{
if( pESh )
pESh->EndAllAction();
else if( pSh )
pSh->EndAction();
if( pSh )
pSh->GetDoc()->SetModified();
}
}
return SUCCESS;
}
void SwIntrnlRefLink::Closed()
{
if( rFldType.GetDoc() && !rFldType.GetDoc()->IsInDtor() )
{
// advise goes, convert all fields into text?
SwViewShell* pSh;
SwEditShell* pESh = rFldType.GetDoc()->GetEditShell( &pSh );
if( pESh )
{
pESh->StartAllAction();
pESh->FieldToText( &rFldType );
pESh->EndAllAction();
}
else
{
pSh->StartAction();
// am Doc aufrufen ??
pSh->EndAction();
}
}
SvBaseLink::Closed();
}
const SwNode* SwIntrnlRefLink::GetAnchor() const
{
// here, any anchor of the normal NodesArray should be sufficient
const SwNode* pNd = 0;
SwClientIter aIter( rFldType ); // TODO
SwClient * pLast = aIter.GoStart();
if( pLast ) // Could we jump to beginning?
do {
// a DDE table or a DDE field attribute in the text
if( !pLast->IsA( TYPE( SwFmtFld ) ))
{
SwDepend* pDep = (SwDepend*)pLast;
SwDDETable* pDDETbl = (SwDDETable*)pDep->GetToTell();
pNd = pDDETbl->GetTabSortBoxes()[0]->GetSttNd();
}
else if( ((SwFmtFld*)pLast)->GetTxtFld() )
pNd = ((SwFmtFld*)pLast)->GetTxtFld()->GetpTxtNode();
if( pNd && &rFldType.GetDoc()->GetNodes() == &pNd->GetNodes() )
break;
pNd = 0;
} while( 0 != ( pLast = ++aIter ));
return pNd;
}
bool SwIntrnlRefLink::IsInRange( sal_uLong nSttNd, sal_uLong nEndNd,
sal_Int32 nStt, sal_Int32 nEnd ) const
{
// here, any anchor of the normal NodesArray should be sufficient
SwNodes* pNds = &rFldType.GetDoc()->GetNodes();
SwClientIter aIter( rFldType ); // TODO
SwClient * pLast = aIter.GoStart();
if( pLast ) // Could we jump to beginning?
do {
// a DDE table or a DDE field attribute in the text
if( !pLast->IsA( TYPE( SwFmtFld ) ))
{
SwDepend* pDep = (SwDepend*)pLast;
SwDDETable* pDDETbl = (SwDDETable*)pDep->GetToTell();
const SwTableNode* pTblNd = pDDETbl->GetTabSortBoxes()[0]->
GetSttNd()->FindTableNode();
if( pTblNd->GetNodes().IsDocNodes() &&
nSttNd < pTblNd->EndOfSectionIndex() &&
nEndNd > pTblNd->GetIndex() )
return true;
}
else if( ((SwFmtFld*)pLast)->GetTxtFld() )
{
const SwTxtFld* pTFld = ((SwFmtFld*)pLast)->GetTxtFld();
const SwTxtNode* pNd = pTFld->GetpTxtNode();
if( pNd && pNds == &pNd->GetNodes() )
{
sal_uLong nNdPos = pNd->GetIndex();
if( nSttNd <= nNdPos && nNdPos <= nEndNd &&
( nNdPos != nSttNd || *pTFld->GetStart() >= nStt ) &&
( nNdPos != nEndNd || *pTFld->GetStart() < nEnd ))
return true;
}
}
} while( 0 != ( pLast = ++aIter ));
return false;
}
SwDDEFieldType::SwDDEFieldType(const OUString& rName,
const OUString& rCmd, sal_uInt16 nUpdateType )
: SwFieldType( RES_DDEFLD ),
aName( rName ), pDoc( 0 ), nRefCnt( 0 )
{
bCRLFFlag = bDeleted = false;
refLink = new SwIntrnlRefLink( *this, nUpdateType, FORMAT_STRING );
SetCmd( rCmd );
}
SwDDEFieldType::~SwDDEFieldType()
{
if( pDoc && !pDoc->IsInDtor() )
pDoc->GetLinkManager().Remove( refLink );
refLink->Disconnect();
}
SwFieldType* SwDDEFieldType::Copy() const
{
SwDDEFieldType* pType = new SwDDEFieldType( aName, GetCmd(), GetType() );
pType->aExpansion = aExpansion;
pType->bCRLFFlag = bCRLFFlag;
pType->bDeleted = bDeleted;
pType->SetDoc( pDoc );
return pType;
}
OUString SwDDEFieldType::GetName() const
{
return aName;
}
void SwDDEFieldType::SetCmd( const OUString& _aStr )
{
OUString aStr = _aStr;
sal_Int32 nIndex = 0;
do
{
aStr = aStr.replaceFirst(" ", " ", &nIndex);
} while (nIndex>=0);
refLink->SetLinkSourceName( aStr );
}
OUString SwDDEFieldType::GetCmd() const
{
return refLink->GetLinkSourceName();
}
void SwDDEFieldType::SetDoc( SwDoc* pNewDoc )
{
if( pNewDoc == pDoc )
return;
if( pDoc && refLink.Is() )
{
OSL_ENSURE( !nRefCnt, "How do we get the references?" );
pDoc->GetLinkManager().Remove( refLink );
}
pDoc = pNewDoc;
if( pDoc && nRefCnt )
{
refLink->SetVisible( pDoc->IsVisibleLinks() );
pDoc->GetLinkManager().InsertDDELink( refLink );
}
}
void SwDDEFieldType::_RefCntChgd()
{
if( nRefCnt )
{
refLink->SetVisible( pDoc->IsVisibleLinks() );
pDoc->GetLinkManager().InsertDDELink( refLink );
if( pDoc->GetCurrentViewShell() )
UpdateNow();
}
else
{
Disconnect();
pDoc->GetLinkManager().Remove( refLink );
}
}
bool SwDDEFieldType::QueryValue( uno::Any& rVal, sal_uInt16 nWhichId ) const
{
sal_Int32 nPart = -1;
switch( nWhichId )
{
case FIELD_PROP_PAR2: nPart = 2; break;
case FIELD_PROP_PAR4: nPart = 1; break;
case FIELD_PROP_SUBTYPE: nPart = 0; break;
case FIELD_PROP_BOOL1:
{
sal_Bool bSet = GetType() == sfx2::LINKUPDATE_ALWAYS ? sal_True : sal_False;
rVal.setValue(&bSet, ::getBooleanCppuType());
}
break;
case FIELD_PROP_PAR5:
rVal <<= aExpansion;
break;
default:
OSL_FAIL("illegal property");
}
if ( nPart>=0 )
rVal <<= GetCmd().getToken(nPart, sfx2::cTokenSeparator);
return true;
}
bool SwDDEFieldType::PutValue( const uno::Any& rVal, sal_uInt16 nWhichId )
{
sal_Int32 nPart = -1;
switch( nWhichId )
{
case FIELD_PROP_PAR2: nPart = 2; break;
case FIELD_PROP_PAR4: nPart = 1; break;
case FIELD_PROP_SUBTYPE: nPart = 0; break;
case FIELD_PROP_BOOL1:
SetType( static_cast<sal_uInt16>(*(sal_Bool*)rVal.getValue() ?
sfx2::LINKUPDATE_ALWAYS :
sfx2::LINKUPDATE_ONCALL ) );
break;
case FIELD_PROP_PAR5:
rVal >>= aExpansion;
break;
default:
OSL_FAIL("illegal property");
}
if( nPart>=0 )
{
const OUString sOldCmd( GetCmd() );
OUString sNewCmd;
sal_Int32 nIndex = 0;
for (sal_Int32 i=0; i<3; ++i)
{
OUString sToken = sOldCmd.getToken(0, sfx2::cTokenSeparator, nIndex);
if (i==nPart)
{
rVal >>= sToken;
}
sNewCmd += sToken + OUString(sfx2::cTokenSeparator);
}
SetCmd( sNewCmd );
}
return true;
}
SwDDEField::SwDDEField( SwDDEFieldType* pInitType )
: SwField(pInitType)
{
}
SwDDEField::~SwDDEField()
{
if( GetTyp()->IsLastDepend() )
((SwDDEFieldType*)GetTyp())->Disconnect();
}
OUString SwDDEField::Expand() const
{
OUString aStr = ((SwDDEFieldType*)GetTyp())->GetExpansion();
aStr = aStr.replaceAll("\r", OUString());
aStr = aStr.replaceAll("\t", " ");
aStr = aStr.replaceAll("\n", "|");
if (aStr.endsWith("|"))
{
return aStr.copy(0, aStr.getLength()-1);
}
return aStr;
}
SwField* SwDDEField::Copy() const
{
return new SwDDEField((SwDDEFieldType*)GetTyp());
}
/// get field type name
OUString SwDDEField::GetPar1() const
{
return ((const SwDDEFieldType*)GetTyp())->GetName();
}
/// get field type command
OUString SwDDEField::GetPar2() const
{
return ((const SwDDEFieldType*)GetTyp())->GetCmd();
}
/// set field type command
void SwDDEField::SetPar2(const OUString& rStr)
{
((SwDDEFieldType*)GetTyp())->SetCmd(rStr);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fdo#78332: sw: fix separators in SwDDEFieldType::PutValue()<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
#include <osl/thread.h>
#include <sfx2/linkmgr.hxx>
#include <doc.hxx>
#include <editsh.hxx>
#include <ndtxt.hxx>
#include <fmtfld.hxx>
#include <txtfld.hxx>
#include <ddefld.hxx>
#include <swtable.hxx>
#include <swbaslnk.hxx>
#include <swddetbl.hxx>
#include <unofldmid.h>
#include <hints.hxx>
using namespace ::com::sun::star;
#define DDE_TXT_ENCODING osl_getThreadTextEncoding()
class SwIntrnlRefLink : public SwBaseLink
{
SwDDEFieldType& rFldType;
public:
SwIntrnlRefLink( SwDDEFieldType& rType, sal_uInt16 nUpdateType, sal_uInt16 nFmt )
: SwBaseLink( nUpdateType, nFmt ),
rFldType( rType )
{}
virtual void Closed() SAL_OVERRIDE;
virtual ::sfx2::SvBaseLink::UpdateResult DataChanged(
const OUString& rMimeType, const ::com::sun::star::uno::Any & rValue ) SAL_OVERRIDE;
virtual const SwNode* GetAnchor() const SAL_OVERRIDE;
virtual bool IsInRange( sal_uLong nSttNd, sal_uLong nEndNd, sal_Int32 nStt = 0,
sal_Int32 nEnd = -1 ) const SAL_OVERRIDE;
};
::sfx2::SvBaseLink::UpdateResult SwIntrnlRefLink::DataChanged( const OUString& rMimeType,
const uno::Any & rValue )
{
switch( SotExchange::GetFormatIdFromMimeType( rMimeType ) )
{
case FORMAT_STRING:
if( !IsNoDataFlag() )
{
uno::Sequence< sal_Int8 > aSeq;
rValue >>= aSeq;
OUString sStr( (sal_Char*)aSeq.getConstArray(), aSeq.getLength(), DDE_TXT_ENCODING );
// remove not needed CR-LF at the end
sal_Int32 n = sStr.getLength();
while( n && 0 == sStr[ n-1 ] )
--n;
if( n && 0x0a == sStr[ n-1 ] )
--n;
if( n && 0x0d == sStr[ n-1 ] )
--n;
bool bDel = n != sStr.getLength();
if( bDel )
sStr = sStr.copy( 0, n );
rFldType.SetExpansion( sStr );
// set Expansion first! (otherwise this flag will be deleted)
rFldType.SetCRLFDelFlag( bDel );
}
break;
// other formats
default:
return SUCCESS;
}
OSL_ENSURE( rFldType.GetDoc(), "no pDoc" );
// no dependencies left?
if( rFldType.GetDepends() && !rFldType.IsModifyLocked() && !ChkNoDataFlag() )
{
SwViewShell* pSh;
SwEditShell* pESh = rFldType.GetDoc()->GetEditShell( &pSh );
// Search for fields. If no valid found, disconnect.
SwMsgPoolItem aUpdateDDE( RES_UPDATEDDETBL );
int bCallModify = sal_False;
rFldType.LockModify();
SwClientIter aIter( rFldType ); // TODO
SwClient * pLast = aIter.GoStart();
if( pLast ) // Could we jump to beginning?
do {
// a DDE table or a DDE field attribute in the text
if( !pLast->IsA( TYPE( SwFmtFld ) ) ||
((SwFmtFld*)pLast)->GetTxtFld() )
{
if( !bCallModify )
{
if( pESh )
pESh->StartAllAction();
else if( pSh )
pSh->StartAction();
}
pLast->ModifyNotification( 0, &aUpdateDDE );
bCallModify = sal_True;
}
} while( 0 != ( pLast = ++aIter ));
rFldType.UnlockModify();
if( bCallModify )
{
if( pESh )
pESh->EndAllAction();
else if( pSh )
pSh->EndAction();
if( pSh )
pSh->GetDoc()->SetModified();
}
}
return SUCCESS;
}
void SwIntrnlRefLink::Closed()
{
if( rFldType.GetDoc() && !rFldType.GetDoc()->IsInDtor() )
{
// advise goes, convert all fields into text?
SwViewShell* pSh;
SwEditShell* pESh = rFldType.GetDoc()->GetEditShell( &pSh );
if( pESh )
{
pESh->StartAllAction();
pESh->FieldToText( &rFldType );
pESh->EndAllAction();
}
else
{
pSh->StartAction();
// am Doc aufrufen ??
pSh->EndAction();
}
}
SvBaseLink::Closed();
}
const SwNode* SwIntrnlRefLink::GetAnchor() const
{
// here, any anchor of the normal NodesArray should be sufficient
const SwNode* pNd = 0;
SwClientIter aIter( rFldType ); // TODO
SwClient * pLast = aIter.GoStart();
if( pLast ) // Could we jump to beginning?
do {
// a DDE table or a DDE field attribute in the text
if( !pLast->IsA( TYPE( SwFmtFld ) ))
{
SwDepend* pDep = (SwDepend*)pLast;
SwDDETable* pDDETbl = (SwDDETable*)pDep->GetToTell();
pNd = pDDETbl->GetTabSortBoxes()[0]->GetSttNd();
}
else if( ((SwFmtFld*)pLast)->GetTxtFld() )
pNd = ((SwFmtFld*)pLast)->GetTxtFld()->GetpTxtNode();
if( pNd && &rFldType.GetDoc()->GetNodes() == &pNd->GetNodes() )
break;
pNd = 0;
} while( 0 != ( pLast = ++aIter ));
return pNd;
}
bool SwIntrnlRefLink::IsInRange( sal_uLong nSttNd, sal_uLong nEndNd,
sal_Int32 nStt, sal_Int32 nEnd ) const
{
// here, any anchor of the normal NodesArray should be sufficient
SwNodes* pNds = &rFldType.GetDoc()->GetNodes();
SwClientIter aIter( rFldType ); // TODO
SwClient * pLast = aIter.GoStart();
if( pLast ) // Could we jump to beginning?
do {
// a DDE table or a DDE field attribute in the text
if( !pLast->IsA( TYPE( SwFmtFld ) ))
{
SwDepend* pDep = (SwDepend*)pLast;
SwDDETable* pDDETbl = (SwDDETable*)pDep->GetToTell();
const SwTableNode* pTblNd = pDDETbl->GetTabSortBoxes()[0]->
GetSttNd()->FindTableNode();
if( pTblNd->GetNodes().IsDocNodes() &&
nSttNd < pTblNd->EndOfSectionIndex() &&
nEndNd > pTblNd->GetIndex() )
return true;
}
else if( ((SwFmtFld*)pLast)->GetTxtFld() )
{
const SwTxtFld* pTFld = ((SwFmtFld*)pLast)->GetTxtFld();
const SwTxtNode* pNd = pTFld->GetpTxtNode();
if( pNd && pNds == &pNd->GetNodes() )
{
sal_uLong nNdPos = pNd->GetIndex();
if( nSttNd <= nNdPos && nNdPos <= nEndNd &&
( nNdPos != nSttNd || *pTFld->GetStart() >= nStt ) &&
( nNdPos != nEndNd || *pTFld->GetStart() < nEnd ))
return true;
}
}
} while( 0 != ( pLast = ++aIter ));
return false;
}
SwDDEFieldType::SwDDEFieldType(const OUString& rName,
const OUString& rCmd, sal_uInt16 nUpdateType )
: SwFieldType( RES_DDEFLD ),
aName( rName ), pDoc( 0 ), nRefCnt( 0 )
{
bCRLFFlag = bDeleted = false;
refLink = new SwIntrnlRefLink( *this, nUpdateType, FORMAT_STRING );
SetCmd( rCmd );
}
SwDDEFieldType::~SwDDEFieldType()
{
if( pDoc && !pDoc->IsInDtor() )
pDoc->GetLinkManager().Remove( refLink );
refLink->Disconnect();
}
SwFieldType* SwDDEFieldType::Copy() const
{
SwDDEFieldType* pType = new SwDDEFieldType( aName, GetCmd(), GetType() );
pType->aExpansion = aExpansion;
pType->bCRLFFlag = bCRLFFlag;
pType->bDeleted = bDeleted;
pType->SetDoc( pDoc );
return pType;
}
OUString SwDDEFieldType::GetName() const
{
return aName;
}
void SwDDEFieldType::SetCmd( const OUString& _aStr )
{
OUString aStr = _aStr;
sal_Int32 nIndex = 0;
do
{
aStr = aStr.replaceFirst(" ", " ", &nIndex);
} while (nIndex>=0);
refLink->SetLinkSourceName( aStr );
}
OUString SwDDEFieldType::GetCmd() const
{
return refLink->GetLinkSourceName();
}
void SwDDEFieldType::SetDoc( SwDoc* pNewDoc )
{
if( pNewDoc == pDoc )
return;
if( pDoc && refLink.Is() )
{
OSL_ENSURE( !nRefCnt, "How do we get the references?" );
pDoc->GetLinkManager().Remove( refLink );
}
pDoc = pNewDoc;
if( pDoc && nRefCnt )
{
refLink->SetVisible( pDoc->IsVisibleLinks() );
pDoc->GetLinkManager().InsertDDELink( refLink );
}
}
void SwDDEFieldType::_RefCntChgd()
{
if( nRefCnt )
{
refLink->SetVisible( pDoc->IsVisibleLinks() );
pDoc->GetLinkManager().InsertDDELink( refLink );
if( pDoc->GetCurrentViewShell() )
UpdateNow();
}
else
{
Disconnect();
pDoc->GetLinkManager().Remove( refLink );
}
}
bool SwDDEFieldType::QueryValue( uno::Any& rVal, sal_uInt16 nWhichId ) const
{
sal_Int32 nPart = -1;
switch( nWhichId )
{
case FIELD_PROP_PAR2: nPart = 2; break;
case FIELD_PROP_PAR4: nPart = 1; break;
case FIELD_PROP_SUBTYPE: nPart = 0; break;
case FIELD_PROP_BOOL1:
{
sal_Bool bSet = GetType() == sfx2::LINKUPDATE_ALWAYS ? sal_True : sal_False;
rVal.setValue(&bSet, ::getBooleanCppuType());
}
break;
case FIELD_PROP_PAR5:
rVal <<= aExpansion;
break;
default:
OSL_FAIL("illegal property");
}
if ( nPart>=0 )
rVal <<= GetCmd().getToken(nPart, sfx2::cTokenSeparator);
return true;
}
bool SwDDEFieldType::PutValue( const uno::Any& rVal, sal_uInt16 nWhichId )
{
sal_Int32 nPart = -1;
switch( nWhichId )
{
case FIELD_PROP_PAR2: nPart = 2; break;
case FIELD_PROP_PAR4: nPart = 1; break;
case FIELD_PROP_SUBTYPE: nPart = 0; break;
case FIELD_PROP_BOOL1:
SetType( static_cast<sal_uInt16>(*(sal_Bool*)rVal.getValue() ?
sfx2::LINKUPDATE_ALWAYS :
sfx2::LINKUPDATE_ONCALL ) );
break;
case FIELD_PROP_PAR5:
rVal >>= aExpansion;
break;
default:
OSL_FAIL("illegal property");
}
if( nPart>=0 )
{
const OUString sOldCmd( GetCmd() );
OUString sNewCmd;
sal_Int32 nIndex = 0;
for (sal_Int32 i=0; i<3; ++i)
{
OUString sToken = sOldCmd.getToken(0, sfx2::cTokenSeparator, nIndex);
if (i==nPart)
{
rVal >>= sToken;
}
sNewCmd += (i < 2)
? sToken + OUString(sfx2::cTokenSeparator) : sToken;
}
SetCmd( sNewCmd );
}
return true;
}
SwDDEField::SwDDEField( SwDDEFieldType* pInitType )
: SwField(pInitType)
{
}
SwDDEField::~SwDDEField()
{
if( GetTyp()->IsLastDepend() )
((SwDDEFieldType*)GetTyp())->Disconnect();
}
OUString SwDDEField::Expand() const
{
OUString aStr = ((SwDDEFieldType*)GetTyp())->GetExpansion();
aStr = aStr.replaceAll("\r", OUString());
aStr = aStr.replaceAll("\t", " ");
aStr = aStr.replaceAll("\n", "|");
if (aStr.endsWith("|"))
{
return aStr.copy(0, aStr.getLength()-1);
}
return aStr;
}
SwField* SwDDEField::Copy() const
{
return new SwDDEField((SwDDEFieldType*)GetTyp());
}
/// get field type name
OUString SwDDEField::GetPar1() const
{
return ((const SwDDEFieldType*)GetTyp())->GetName();
}
/// get field type command
OUString SwDDEField::GetPar2() const
{
return ((const SwDDEFieldType*)GetTyp())->GetCmd();
}
/// set field type command
void SwDDEField::SetPar2(const OUString& rStr)
{
((SwDDEFieldType*)GetTyp())->SetCmd(rStr);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before><commit_msg>coverity#1266486 Untrusted loop bound<commit_after><|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/webdata/web_intents_table.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"
#include "sql/statement.h"
namespace {
bool ExtractIntents(sql::Statement* s,
std::vector<WebIntentServiceData>* services) {
DCHECK(s);
while (s->Step()) {
WebIntentServiceData service;
string16 tmp = s->ColumnString16(0);
service.service_url = GURL(tmp);
service.action = s->ColumnString16(1);
service.type = s->ColumnString16(2);
service.title = s->ColumnString16(3);
tmp = s->ColumnString16(4);
// Default to window disposition.
service.disposition = WebIntentServiceData::DISPOSITION_WINDOW;
if (tmp == ASCIIToUTF16("inline"))
service.disposition = WebIntentServiceData::DISPOSITION_INLINE;
services->push_back(service);
}
return true;
}
}
WebIntentsTable::WebIntentsTable(sql::Connection* db,
sql::MetaTable* meta_table)
: WebDatabaseTable(db, meta_table) {
}
WebIntentsTable::~WebIntentsTable() {
}
bool WebIntentsTable::Init() {
if (db_->DoesTableExist("web_intents"))
return true;
if (!db_->Execute("CREATE TABLE web_intents ("
"service_url LONGVARCHAR,"
"action VARCHAR,"
"type VARCHAR,"
"title VARCHAR,"
"disposition VARCHAR,"
"UNIQUE (service_url, action, type))")) {
NOTREACHED();
return false;
}
if (!db_->Execute("CREATE INDEX web_intents_index "
"ON web_intents (action)")) {
NOTREACHED();
return false;
}
return true;
}
// TODO(jhawkins): Figure out Sync story.
bool WebIntentsTable::IsSyncable() {
return false;
}
bool WebIntentsTable::GetWebIntents(
const string16& action,
std::vector<WebIntentServiceData>* intents) {
DCHECK(intents);
sql::Statement s(db_->GetUniqueStatement(
"SELECT service_url, action, type, title, disposition FROM web_intents "
"WHERE action=?"));
if (!s) {
NOTREACHED() << "Statement prepare failed";
return false;
}
s.BindString16(0, action);
return ExtractIntents(&s, intents);
}
bool WebIntentsTable::GetAllWebIntents(
std::vector<WebIntentServiceData>* intents) {
DCHECK(intents);
sql::Statement s(db_->GetUniqueStatement(
"SELECT service_url, action, type, title, disposition FROM web_intents"));
if (!s) {
NOTREACHED() << "Statement prepare failed";
return false;
}
return ExtractIntents(&s, intents);
}
bool WebIntentsTable::SetWebIntent(const WebIntentServiceData& intent) {
sql::Statement s(db_->GetUniqueStatement(
"INSERT OR REPLACE INTO web_intents "
"(service_url, type, action, title, disposition) "
"VALUES (?, ?, ?, ?, ?)"));
if (!s) {
NOTREACHED() << "Statement prepare failed";
return false;
}
// Default to window disposition.
string16 disposition = ASCIIToUTF16("window");
if (intent.disposition == WebIntentServiceData::DISPOSITION_INLINE)
disposition = ASCIIToUTF16("inline");
s.BindString(0, intent.service_url.spec());
s.BindString16(1, intent.type);
s.BindString16(2, intent.action);
s.BindString16(3, intent.title);
s.BindString16(4, disposition);
return s.Run();
}
// TODO(jhawkins): Investigate the need to remove rows matching only
// |intent.service_url|. It's unlikely the user will be given the ability to
// remove at the granularity of actions or types.
bool WebIntentsTable::RemoveWebIntent(const WebIntentServiceData& intent) {
sql::Statement s(db_->GetUniqueStatement(
"DELETE FROM web_intents "
"WHERE service_url = ? AND action = ? AND type = ?"));
if (!s) {
NOTREACHED() << "Statement prepare failed";
return false;
}
s.BindString(0, intent.service_url.spec());
s.BindString16(1, intent.action);
s.BindString16(2, intent.type);
return s.Run();
}
<commit_msg>Web Intents: Remove handling of NOTREACHEDs.<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/webdata/web_intents_table.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"
#include "sql/statement.h"
namespace {
bool ExtractIntents(sql::Statement* s,
std::vector<WebIntentServiceData>* services) {
DCHECK(s);
while (s->Step()) {
WebIntentServiceData service;
string16 tmp = s->ColumnString16(0);
service.service_url = GURL(tmp);
service.action = s->ColumnString16(1);
service.type = s->ColumnString16(2);
service.title = s->ColumnString16(3);
tmp = s->ColumnString16(4);
// Default to window disposition.
service.disposition = WebIntentServiceData::DISPOSITION_WINDOW;
if (tmp == ASCIIToUTF16("inline"))
service.disposition = WebIntentServiceData::DISPOSITION_INLINE;
services->push_back(service);
}
return true;
}
}
WebIntentsTable::WebIntentsTable(sql::Connection* db,
sql::MetaTable* meta_table)
: WebDatabaseTable(db, meta_table) {
}
WebIntentsTable::~WebIntentsTable() {
}
bool WebIntentsTable::Init() {
if (db_->DoesTableExist("web_intents"))
return true;
if (!db_->Execute("CREATE TABLE web_intents ("
"service_url LONGVARCHAR,"
"action VARCHAR,"
"type VARCHAR,"
"title VARCHAR,"
"disposition VARCHAR,"
"UNIQUE (service_url, action, type))")) {
NOTREACHED();
}
if (!db_->Execute("CREATE INDEX web_intents_index ON web_intents (action)"))
NOTREACHED();
return true;
}
// TODO(jhawkins): Figure out Sync story.
bool WebIntentsTable::IsSyncable() {
return false;
}
bool WebIntentsTable::GetWebIntents(
const string16& action,
std::vector<WebIntentServiceData>* intents) {
DCHECK(intents);
sql::Statement s(db_->GetUniqueStatement(
"SELECT service_url, action, type, title, disposition FROM web_intents "
"WHERE action=?"));
if (!s)
NOTREACHED() << "Statement prepare failed";
s.BindString16(0, action);
return ExtractIntents(&s, intents);
}
bool WebIntentsTable::GetAllWebIntents(
std::vector<WebIntentServiceData>* intents) {
DCHECK(intents);
sql::Statement s(db_->GetUniqueStatement(
"SELECT service_url, action, type, title, disposition FROM web_intents"));
if (!s)
NOTREACHED() << "Statement prepare failed";
return ExtractIntents(&s, intents);
}
bool WebIntentsTable::SetWebIntent(const WebIntentServiceData& intent) {
sql::Statement s(db_->GetUniqueStatement(
"INSERT OR REPLACE INTO web_intents "
"(service_url, type, action, title, disposition) "
"VALUES (?, ?, ?, ?, ?)"));
if (!s)
NOTREACHED() << "Statement prepare failed";
// Default to window disposition.
string16 disposition = ASCIIToUTF16("window");
if (intent.disposition == WebIntentServiceData::DISPOSITION_INLINE)
disposition = ASCIIToUTF16("inline");
s.BindString(0, intent.service_url.spec());
s.BindString16(1, intent.type);
s.BindString16(2, intent.action);
s.BindString16(3, intent.title);
s.BindString16(4, disposition);
return s.Run();
}
// TODO(jhawkins): Investigate the need to remove rows matching only
// |intent.service_url|. It's unlikely the user will be given the ability to
// remove at the granularity of actions or types.
bool WebIntentsTable::RemoveWebIntent(const WebIntentServiceData& intent) {
sql::Statement s(db_->GetUniqueStatement(
"DELETE FROM web_intents "
"WHERE service_url = ? AND action = ? AND type = ?"));
if (!s)
NOTREACHED() << "Statement prepare failed";
s.BindString(0, intent.service_url.spec());
s.BindString16(1, intent.action);
s.BindString16(2, intent.type);
return s.Run();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docstdlg.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2006-09-16 22:49:09 $
*
* 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_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#include <stdio.h>
#include <ctype.h>
#ifndef _SWWAIT_HXX
#include <swwait.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _SWMODULE_HXX
#include <swmodule.hxx>
#endif
#ifndef _GLOBALS_HRC
#include <globals.hrc>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _PVIEW_HXX
#include <pview.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCSTDLG_HXX
#include <docstdlg.hxx>
#endif
#ifndef _MODCFG_HXX
#include <modcfg.hxx>
#endif
// fuer Statistikfelder
#ifndef _FLDMGR_HXX
#include <fldmgr.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _DOCSTDLG_HRC
#include <docstdlg.hrc>
#endif
/*--------------------------------------------------------------------
Beschreibung: Create
--------------------------------------------------------------------*/
SfxTabPage * SwDocStatPage::Create(Window *pParent, const SfxItemSet &rSet)
{
return new SwDocStatPage(pParent, rSet);
}
/*--------------------------------------------------------------------
Beschreibung: Ctor
--------------------------------------------------------------------*/
SwDocStatPage::SwDocStatPage(Window *pParent, const SfxItemSet &rSet) :
SfxTabPage (pParent, SW_RES(TP_DOC_STAT), rSet),
aTableLbl (this, SW_RES( FT_TABLE )),
aGrfLbl (this, SW_RES( FT_GRF )),
aOLELbl (this, SW_RES( FT_OLE )),
aPageLbl (this, SW_RES( FT_PAGE )),
aParaLbl (this, SW_RES( FT_PARA )),
aWordLbl (this, SW_RES( FT_WORD )),
aCharLbl (this, SW_RES( FT_CHAR )),
aTableNo (this, SW_RES( FT_TABLE_COUNT)),
aGrfNo (this, SW_RES( FT_GRF_COUNT )),
aOLENo (this, SW_RES( FT_OLE_COUNT )),
aPageNo (this, SW_RES( FT_PAGE_COUNT )),
aParaNo (this, SW_RES( FT_PARA_COUNT )),
aWordNo (this, SW_RES( FT_WORD_COUNT )),
aCharNo (this, SW_RES( FT_CHAR_COUNT )),
aLineLbl (this, SW_RES( FT_LINE )),
aLineNo (this, SW_RES( FT_LINE_COUNT )),
aUpdatePB (this, SW_RES( PB_PDATE ))
{
Update();
FreeResource();
aUpdatePB.SetClickHdl(LINK(this, SwDocStatPage, UpdateHdl));
//#111684# is the current view a page preview no SwFEShell can be found -> hide the update button
SwDocShell* pDocShell = (SwDocShell*) SfxObjectShell::Current();
SwFEShell* pFEShell = pDocShell->GetFEShell();
if(!pFEShell)
{
aUpdatePB.Show(FALSE);
aLineLbl.Show(FALSE);
aLineNo .Show(FALSE);
}
}
SwDocStatPage::~SwDocStatPage()
{
}
/*--------------------------------------------------------------------
Beschreibung: ItemSet fuellen bei Aenderung
--------------------------------------------------------------------*/
BOOL SwDocStatPage::FillItemSet(SfxItemSet &rSet)
{
return FALSE;
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwDocStatPage::Reset(const SfxItemSet &rSet)
{
}
/*------------------------------------------------------------------------
Beschreibung: Aktualisieren / Setzen der Daten
------------------------------------------------------------------------*/
void SwDocStatPage::SetData(const SwDocStat &rStat)
{
aTableNo.SetText(String::CreateFromInt32( rStat.nTbl ));
aGrfNo.SetText(String::CreateFromInt32( rStat.nGrf ));
aOLENo.SetText(String::CreateFromInt32( rStat.nOLE ));
aPageNo.SetText(String::CreateFromInt32( rStat.nPage ));
aParaNo.SetText(String::CreateFromInt32( rStat.nPara ));
aWordNo.SetText(String::CreateFromInt32( rStat.nWord ));
aCharNo.SetText(String::CreateFromInt32( rStat.nChar ));
}
/*------------------------------------------------------------------------
Beschreibung: Aktualisieren der Statistik
------------------------------------------------------------------------*/
void SwDocStatPage::Update()
{
SfxViewShell *pVSh = SfxViewShell::Current();
ViewShell *pSh = 0;
if ( pVSh->ISA(SwView) )
pSh = ((SwView*)pVSh)->GetWrtShellPtr();
else if ( pVSh->ISA(SwPagePreView) )
pSh = ((SwPagePreView*)pVSh)->GetViewShell();
ASSERT( pSh, "Shell not found" );
SwWait aWait( *pSh->GetDoc()->GetDocShell(), TRUE );
pSh->StartAction();
aDocStat = pSh->GetDoc()->GetDocStat();
pSh->GetDoc()->UpdateDocStat( aDocStat );
pSh->EndAction();
SetData(aDocStat);
}
/*-----------------19.06.97 16.37-------------------
Zeilennummer aktualisieren
--------------------------------------------------*/
IMPL_LINK( SwDocStatPage, UpdateHdl, PushButton*, pButton)
{
Update();
SwDocShell* pDocShell = (SwDocShell*) SfxObjectShell::Current();
SwFEShell* pFEShell = pDocShell->GetFEShell();
if(pFEShell)
aLineNo.SetText( String::CreateFromInt32( pFEShell->GetLineCount(FALSE)));
//pButton->Disable();
return 0;
}
<commit_msg>INTEGRATION: CWS swwarnings (1.12.222); FILE MERGED 2007/02/27 11:46:24 os 1.12.222.1: #i69287# warnings removed<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docstdlg.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2007-09-27 11:36:55 $
*
* 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_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#include <stdio.h>
#include <ctype.h>
#ifndef _SWWAIT_HXX
#include <swwait.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _SWMODULE_HXX
#include <swmodule.hxx>
#endif
#ifndef _GLOBALS_HRC
#include <globals.hrc>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _PVIEW_HXX
#include <pview.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCSTDLG_HXX
#include <docstdlg.hxx>
#endif
#ifndef _MODCFG_HXX
#include <modcfg.hxx>
#endif
// fuer Statistikfelder
#ifndef _FLDMGR_HXX
#include <fldmgr.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _DOCSTDLG_HRC
#include <docstdlg.hrc>
#endif
/*--------------------------------------------------------------------
Beschreibung: Create
--------------------------------------------------------------------*/
SfxTabPage * SwDocStatPage::Create(Window *pParent, const SfxItemSet &rSet)
{
return new SwDocStatPage(pParent, rSet);
}
/*--------------------------------------------------------------------
Beschreibung: Ctor
--------------------------------------------------------------------*/
SwDocStatPage::SwDocStatPage(Window *pParent, const SfxItemSet &rSet) :
SfxTabPage (pParent, SW_RES(TP_DOC_STAT), rSet),
aTableLbl (this, SW_RES( FT_TABLE )),
aGrfLbl (this, SW_RES( FT_GRF )),
aOLELbl (this, SW_RES( FT_OLE )),
aPageLbl (this, SW_RES( FT_PAGE )),
aParaLbl (this, SW_RES( FT_PARA )),
aWordLbl (this, SW_RES( FT_WORD )),
aCharLbl (this, SW_RES( FT_CHAR )),
aLineLbl (this, SW_RES( FT_LINE )),
aTableNo (this, SW_RES( FT_TABLE_COUNT)),
aGrfNo (this, SW_RES( FT_GRF_COUNT )),
aOLENo (this, SW_RES( FT_OLE_COUNT )),
aPageNo (this, SW_RES( FT_PAGE_COUNT )),
aParaNo (this, SW_RES( FT_PARA_COUNT )),
aWordNo (this, SW_RES( FT_WORD_COUNT )),
aCharNo (this, SW_RES( FT_CHAR_COUNT )),
aLineNo (this, SW_RES( FT_LINE_COUNT )),
aUpdatePB (this, SW_RES( PB_PDATE ))
{
Update();
FreeResource();
aUpdatePB.SetClickHdl(LINK(this, SwDocStatPage, UpdateHdl));
//#111684# is the current view a page preview no SwFEShell can be found -> hide the update button
SwDocShell* pDocShell = (SwDocShell*) SfxObjectShell::Current();
SwFEShell* pFEShell = pDocShell->GetFEShell();
if(!pFEShell)
{
aUpdatePB.Show(FALSE);
aLineLbl.Show(FALSE);
aLineNo .Show(FALSE);
}
}
SwDocStatPage::~SwDocStatPage()
{
}
/*--------------------------------------------------------------------
Beschreibung: ItemSet fuellen bei Aenderung
--------------------------------------------------------------------*/
BOOL SwDocStatPage::FillItemSet(SfxItemSet & /*rSet*/)
{
return FALSE;
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwDocStatPage::Reset(const SfxItemSet &/*rSet*/)
{
}
/*------------------------------------------------------------------------
Beschreibung: Aktualisieren / Setzen der Daten
------------------------------------------------------------------------*/
void SwDocStatPage::SetData(const SwDocStat &rStat)
{
aTableNo.SetText(String::CreateFromInt32( rStat.nTbl ));
aGrfNo.SetText(String::CreateFromInt32( rStat.nGrf ));
aOLENo.SetText(String::CreateFromInt32( rStat.nOLE ));
aPageNo.SetText(String::CreateFromInt32( rStat.nPage ));
aParaNo.SetText(String::CreateFromInt32( rStat.nPara ));
aWordNo.SetText(String::CreateFromInt32( rStat.nWord ));
aCharNo.SetText(String::CreateFromInt32( rStat.nChar ));
}
/*------------------------------------------------------------------------
Beschreibung: Aktualisieren der Statistik
------------------------------------------------------------------------*/
void SwDocStatPage::Update()
{
SfxViewShell *pVSh = SfxViewShell::Current();
ViewShell *pSh = 0;
if ( pVSh->ISA(SwView) )
pSh = ((SwView*)pVSh)->GetWrtShellPtr();
else if ( pVSh->ISA(SwPagePreView) )
pSh = ((SwPagePreView*)pVSh)->GetViewShell();
ASSERT( pSh, "Shell not found" );
SwWait aWait( *pSh->GetDoc()->GetDocShell(), TRUE );
pSh->StartAction();
aDocStat = pSh->GetDoc()->GetDocStat();
pSh->GetDoc()->UpdateDocStat( aDocStat );
pSh->EndAction();
SetData(aDocStat);
}
/*-----------------19.06.97 16.37-------------------
Zeilennummer aktualisieren
--------------------------------------------------*/
IMPL_LINK( SwDocStatPage, UpdateHdl, PushButton*, EMPTYARG)
{
Update();
SwDocShell* pDocShell = (SwDocShell*) SfxObjectShell::Current();
SwFEShell* pFEShell = pDocShell->GetFEShell();
if(pFEShell)
aLineNo.SetText( String::CreateFromInt32( pFEShell->GetLineCount(FALSE)));
//pButton->Disable();
return 0;
}
<|endoftext|> |
<commit_before>#include "v_avl.h"
#ifndef VOS_OK
#define VOS_OK (0)
#endif
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif /* __cpluscplus */
#endif /* __cpluscplus */
/*lint -save -e818*/
/* OSE-684 y00165807 */
unsigned int VOS_V_AVLInit(const char *pscKey)
{
(void)pscKey;
return VOS_OK;
}
unsigned int VOS_V_AVLFini()
{
return VOS_OK;
}
void AVL_Rotate_Right(AVL_NODE **ppstSubTree)
{
/* rotate ppstSubTree of AVL tree right */
AVL_NODE *pstLeftSon;
pstLeftSon = (*ppstSubTree)->pstLeft;
(*ppstSubTree)->pstLeft = pstLeftSon->pstRight;
if (NULL != (*ppstSubTree)->pstLeft)
{
(*ppstSubTree)->pstLeft->pstParent = (*ppstSubTree);
}
(*ppstSubTree)->sLHeight = pstLeftSon->sRHeight;
pstLeftSon->pstParent = (*ppstSubTree)->pstParent;
pstLeftSon->pstRight = *ppstSubTree;
pstLeftSon->pstRight->pstParent = pstLeftSon;
pstLeftSon->sRHeight = (1 + VOS_V2_AVL_MAX((*ppstSubTree)->sRHeight,
(*ppstSubTree)->sLHeight));
*ppstSubTree = pstLeftSon;
return;
} /* AVL_Rotate_Right */
<commit_msg>Update v_avl.cpp<commit_after>#include "v_avl.h"
#ifndef VOS_OK
#define VOS_OK (0)
#endif
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif /* __cpluscplus */
#endif /* __cpluscplus */
/*lint -save -e818*/
/* OSE-684 y00165807 */
unsigned int VOS_V_AVLInit(const char *pscKey)
{
(void)pscKey;
return VOS_OK;
}
unsigned int VOS_V_AVLFini()
{
return VOS_OK;
}
void AVL_Rotate_Right(AVL_NODE **ppstSubTree)
{
/* rotate ppstSubTree of AVL tree right */
AVL_NODE *pstLeftSon;
pstLeftSon = (*ppstSubTree)->pstLeft;
(*ppstSubTree)->pstLeft = pstLeftSon->pstRight;
if (NULL != (*ppstSubTree)->pstLeft)
{
(*ppstSubTree)->pstLeft->pstParent = (*ppstSubTree);
}
(*ppstSubTree)->sLHeight = pstLeftSon->sRHeight;
pstLeftSon->pstParent = (*ppstSubTree)->pstParent;
pstLeftSon->pstRight = *ppstSubTree;
pstLeftSon->pstRight->pstParent = pstLeftSon;
pstLeftSon->sRHeight = (1 + VOS_V2_AVL_MAX((*ppstSubTree)->sRHeight,
(*ppstSubTree)->sLHeight));
*ppstSubTree = pstLeftSon;
return;
} /* AVL_Rotate_Right */
void AVL_Rotate_Left(AVL_NODE **ppstSubTree)
{
/* rotate a ppstSubTree of the AVL tree left */
AVL_NODE *pstRightSon;
pstRightSon = (*ppstSubTree)->pstRight;
(*ppstSubTree)->pstRight = pstRightSon->pstLeft;
if (NULL != (*ppstSubTree)->pstRight)
{
(*ppstSubTree)->pstRight->pstParent = (*ppstSubTree);
}
(*ppstSubTree)->sRHeight = pstRightSon->sLHeight;
pstRightSon->pstParent = (*ppstSubTree)->pstParent;
pstRightSon->pstLeft = *ppstSubTree;
pstRightSon->pstLeft->pstParent = pstRightSon;
pstRightSon->sLHeight = (1 + VOS_V2_AVL_MAX((*ppstSubTree)->sRHeight,
(*ppstSubTree)->sLHeight));
*ppstSubTree = pstRightSon;
return;
} /* AVL_Rotate_Left */
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"
#include "llvm/Support/raw_ostream.h"
// Implements the CValuePrinter interface.
extern "C" void cling_PrintValue(void* /*clang::Expr**/ E,
void* /*clang::ASTContext**/ C,
const void* value) {
clang::Expr* Exp = (clang::Expr*)E;
clang::ASTContext* Context = (clang::ASTContext*)C;
cling::ValuePrinterInfo VPI(Exp, Context);
cling::printValue(llvm::outs(), value, value, VPI);
cling::flushOStream(llvm::outs());
}
static void StreamChar(llvm::raw_ostream& o, char v) {
o << '"' << v << "\"\n";
}
static void StreamCharPtr(llvm::raw_ostream& o, const char* const v) {
o << '"';
const char* p = v;
for (;*p && p - v < 128; ++p) {
o << *p;
}
if (*p) o << "\"...\n";
else o << "\"\n";
}
static void StreamRef(llvm::raw_ostream& o, const void* v) {
o <<"&" << v << "\n";
}
static void StreamPtr(llvm::raw_ostream& o, const void* v) {
o << *(uint64_t*)v << "\n";
}
static void StreamObj(llvm::raw_ostream& o, const void* v) {
// TODO: Print the object members.
o << "@" << v << "\n";
}
static void StreamValue(llvm::raw_ostream& o, const void* const p, clang::QualType Ty) {
if (Ty->isCharType())
StreamChar(o, *(char*)p);
else if (const clang::BuiltinType *BT
= llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) {
switch (BT->getKind()) {
case clang::BuiltinType::Bool:
if (*(bool*)p) o << "true\n";
else o << "false\n"; break;
case clang::BuiltinType::Int: o << *(int*)p << "\n"; break;
case clang::BuiltinType::Float: o << *(float*)p << "\n"; break;
case clang::BuiltinType::Double: o << *(double*)p << "\n"; break;
default:
StreamObj(o, p);
}
} else if (Ty->isReferenceType())
StreamRef(o, p);
else if (Ty->isPointerType()) {
clang::QualType PointeeTy = Ty->getPointeeType();
if (PointeeTy->isCharType())
StreamCharPtr(o, (const char*)p);
else
StreamPtr(o, p);
}
else
StreamObj(o, p);
}
namespace cling {
void printValueDefault(llvm::raw_ostream& o, const void* const p,
const ValuePrinterInfo& VPI) {
const clang::Expr* E = VPI.getExpr();
o << "(";
o << E->getType().getAsString();
if (E->isRValue()) // show the user that the var cannot be changed
o << " const";
o << ") ";
StreamValue(o, p, E->getType());
}
void flushOStream(llvm::raw_ostream& o) {
o.flush();
}
} // end namespace cling
<commit_msg>Use the right platform independent ptr type.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"
#include "llvm/Support/raw_ostream.h"
// Implements the CValuePrinter interface.
extern "C" void cling_PrintValue(void* /*clang::Expr**/ E,
void* /*clang::ASTContext**/ C,
const void* value) {
clang::Expr* Exp = (clang::Expr*)E;
clang::ASTContext* Context = (clang::ASTContext*)C;
cling::ValuePrinterInfo VPI(Exp, Context);
cling::printValue(llvm::outs(), value, value, VPI);
cling::flushOStream(llvm::outs());
}
static void StreamChar(llvm::raw_ostream& o, char v) {
o << '"' << v << "\"\n";
}
static void StreamCharPtr(llvm::raw_ostream& o, const char* const v) {
o << '"';
const char* p = v;
for (;*p && p - v < 128; ++p) {
o << *p;
}
if (*p) o << "\"...\n";
else o << "\"\n";
}
static void StreamRef(llvm::raw_ostream& o, const void* v) {
o <<"&" << v << "\n";
}
static void StreamPtr(llvm::raw_ostream& o, const void* v) {
o << *(intptr_t
*)v << "\n";
}
static void StreamObj(llvm::raw_ostream& o, const void* v) {
// TODO: Print the object members.
o << "@" << v << "\n";
}
static void StreamValue(llvm::raw_ostream& o, const void* const p, clang::QualType Ty) {
if (Ty->isCharType())
StreamChar(o, *(char*)p);
else if (const clang::BuiltinType *BT
= llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) {
switch (BT->getKind()) {
case clang::BuiltinType::Bool:
if (*(bool*)p) o << "true\n";
else o << "false\n"; break;
case clang::BuiltinType::Int: o << *(int*)p << "\n"; break;
case clang::BuiltinType::Float: o << *(float*)p << "\n"; break;
case clang::BuiltinType::Double: o << *(double*)p << "\n"; break;
default:
StreamObj(o, p);
}
} else if (Ty->isReferenceType())
StreamRef(o, p);
else if (Ty->isPointerType()) {
clang::QualType PointeeTy = Ty->getPointeeType();
if (PointeeTy->isCharType())
StreamCharPtr(o, (const char*)p);
else
StreamPtr(o, p);
}
else
StreamObj(o, p);
}
namespace cling {
void printValueDefault(llvm::raw_ostream& o, const void* const p,
const ValuePrinterInfo& VPI) {
const clang::Expr* E = VPI.getExpr();
o << "(";
o << E->getType().getAsString();
if (E->isRValue()) // show the user that the var cannot be changed
o << " const";
o << ") ";
StreamValue(o, p, E->getType());
}
void flushOStream(llvm::raw_ostream& o) {
o.flush();
}
} // end namespace cling
<|endoftext|> |
<commit_before>/*
* log.cpp - enable the log system
*
* Copyright (C) 2011-2014 Intel Corporation
* Author: Xin Tang <xin.t.tang@intel.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, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
/* log.cpp is to enable debug log with LIBYAMI_LOG_LEVEL and LIBYAMI_TRACE:
* LIBYAMI_LOG_LEVEL=log_level: the record will be printed if the log_level larger than (Error, 0), (Warning, 1), (Info, 2)(Debug & Debug_, 3).
* LIBYAMI_LOG=log_file: the libyami log saved into log_file;
*/
#include "log.h"
#include <ctype.h>
#include <stdarg.h>
#include <stdlib.h>
#include <time.h>
#include "common/lock.h"
int yamiLogFlag;
FILE* yamiLogFn;
int isInit = 0;
static YamiMediaCodec::Lock g_traceLock;
void yamiTraceInit()
{
YamiMediaCodec::AutoLock locker(g_traceLock);
if(!isInit){
char* libyamiLogLevel = getenv("LIBYAMI_LOG_LEVEL");
char* libyamLog = getenv("LIBYAMI_LOG");
FILE* tmp;
if (libyamiLogLevel){
yamiLogFlag = atoi(libyamiLogLevel);
if (libyamLog){
time_t now;
struct tm* curtime;
char filename[80];
time(&now);
curtime = localtime(&now);
sprintf(filename, "%s_%2d_%02d_%02d_%02d_%02d", libyamLog,
curtime->tm_year + 1900, curtime->tm_mon + 1, curtime->tm_mday,
curtime->tm_hour, curtime->tm_sec);
if (tmp = fopen(filename, "w")){
yamiLogFn = tmp;
yamiMessage(stdout, "Libyami_Trace is on, save log into %s.\n", filename);
} else {
yamiLogFn = stderr;
yamiMessage(stderr, "Open file %s failed.\n", filename);
}
}
else {
yamiLogFn = stderr;
yamiMessage(stderr, "Libyami_Trace is on stderr\n");
}
}
else
yamiLogFlag = 0;
isInit = 1;
}
}
<commit_msg>log: enable error log by default<commit_after>/*
* log.cpp - enable the log system
*
* Copyright (C) 2011-2014 Intel Corporation
* Author: Xin Tang <xin.t.tang@intel.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, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
/* log.cpp is to enable debug log with LIBYAMI_LOG_LEVEL and LIBYAMI_TRACE:
* LIBYAMI_LOG_LEVEL=log_level: the record will be printed if the log_level larger than (Error, 0), (Warning, 1), (Info, 2)(Debug & Debug_, 3).
* LIBYAMI_LOG=log_file: the libyami log saved into log_file;
*/
#include "log.h"
#include <ctype.h>
#include <stdarg.h>
#include <stdlib.h>
#include <time.h>
#include "common/lock.h"
int yamiLogFlag;
FILE* yamiLogFn;
int isInit = 0;
static YamiMediaCodec::Lock g_traceLock;
void yamiTraceInit()
{
YamiMediaCodec::AutoLock locker(g_traceLock);
if(!isInit){
char* libyamiLogLevel = getenv("LIBYAMI_LOG_LEVEL");
char* libyamLog = getenv("LIBYAMI_LOG");
FILE* tmp;
yamiLogFn = stderr;
if (libyamiLogLevel){
yamiLogFlag = atoi(libyamiLogLevel);
if (libyamLog){
time_t now;
struct tm* curtime;
char filename[80];
time(&now);
curtime = localtime(&now);
sprintf(filename, "%s_%2d_%02d_%02d_%02d_%02d", libyamLog,
curtime->tm_year + 1900, curtime->tm_mon + 1, curtime->tm_mday,
curtime->tm_hour, curtime->tm_sec);
if (tmp = fopen(filename, "w")){
yamiLogFn = tmp;
yamiMessage(stdout, "Libyami_Trace is on, save log into %s.\n", filename);
} else {
yamiMessage(stderr, "Open file %s failed.\n", filename);
}
}
}
else {
yamiLogFlag = YAMI_LOG_ERROR;
}
isInit = 1;
}
}
<|endoftext|> |
<commit_before>#include <QObject>
#include <QTest>
#include <QDebug>
#include "../Generator.hpp"
const QString c_typesSection = QStringLiteral("---types---");
const QString c_functionsSection = QStringLiteral("---functions---");
static QByteArray generateTextSpec(const QStringList &types, const QStringList &functions = {})
{
QByteArray result;
if (!types.isEmpty()) {
const QString textData = c_typesSection + QLatin1Char('\n') + types.join(QLatin1Char('\n')) + QLatin1Char('\n');
result += textData.toLocal8Bit();
}
if (!functions.isEmpty()) {
const QString textData = c_functionsSection + QLatin1Char('\n') + functions.join(QLatin1Char('\n')) + QLatin1Char('\n');
result += textData.toLocal8Bit();
}
return result;
}
const QStringList c_sourcesInputMediaDeps =
{
QStringLiteral("inputPhotoEmpty = InputPhoto;"),
QStringLiteral("inputFileEmpty = InputFile;"),
QStringLiteral("inputVideoEmpty = InputVideo;"),
QStringLiteral("inputAudioEmpty = InputAudio;"),
QStringLiteral("inputDocumentEmpty = InputDocument;"),
QStringLiteral("documentAttributeEmpty = DocumentAttribute;"),
};
const QStringList c_sourcesInputMedia =
{
QStringLiteral("inputMediaEmpty#9664f57f = InputMedia;"),
QStringLiteral("inputMediaUploadedPhoto#f7aff1c0 file:InputFile caption:string = InputMedia;"),
QStringLiteral("inputMediaPhoto#e9bfb4f3 id:InputPhoto caption:string = InputMedia;"),
QStringLiteral("inputMediaContact#a6e45987 phone_number:string first_name:string last_name:string = InputMedia;"),
QStringLiteral("inputMediaUploadedVideo#82713fdf file:InputFile duration:int w:int h:int mime_type:string caption:string = InputMedia;"),
QStringLiteral("inputMediaUploadedThumbVideo#7780ddf9 file:InputFile thumb:InputFile duration:int w:int h:int mime_type:string caption:string = InputMedia;"),
QStringLiteral("inputMediaVideo#936a4ebd id:InputVideo caption:string = InputMedia;"),
QStringLiteral("inputMediaUploadedAudio#4e498cab file:InputFile duration:int mime_type:string = InputMedia;"),
QStringLiteral("inputMediaAudio#89938781 id:InputAudio = InputMedia;"),
QStringLiteral("inputMediaUploadedDocument#1d89306d file:InputFile mime_type:string attributes:Vector<DocumentAttribute> caption:string = InputMedia;"),
QStringLiteral("inputMediaUploadedThumbDocument#ad613491 file:InputFile thumb:InputFile mime_type:string attributes:Vector<DocumentAttribute> caption:string = InputMedia;"),
QStringLiteral("inputMediaDocument#1a77f29c id:InputDocument caption:string = InputMedia;"),
};
const QStringList c_sourcesRichText =
{
QStringLiteral("textEmpty#dc3d824f = RichText;"),
QStringLiteral("textPlain#744694e0 text:string = RichText;"),
QStringLiteral("textBold#6724abc4 text:RichText = RichText;"),
QStringLiteral("textItalic#d912a59c text:RichText = RichText;"),
QStringLiteral("textUnderline#c12622c4 text:RichText = RichText;"),
QStringLiteral("textStrike#9bf8bb95 text:RichText = RichText;"),
QStringLiteral("textFixed#6c3f19b9 text:RichText = RichText;"),
QStringLiteral("textUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;"),
QStringLiteral("textEmail#de5a0dd6 text:RichText email:string = RichText;"),
QStringLiteral("textConcat#7e6260d7 texts:Vector<RichText> = RichText;"),
};
const QStringList c_sourcesPageBlock =
{
QStringLiteral("pageBlockUnsupported#13567e8a = PageBlock;"),
QStringLiteral("pageBlockTitle#70abc3fd text:RichText = PageBlock;"),
QStringLiteral("pageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;"),
QStringLiteral("pageBlockList#3a58c7f4 ordered:Bool items:Vector<RichText> = PageBlock;"),
QStringLiteral("pageBlockEmbedPost#292c7be9 url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector<PageBlock> caption:RichText = PageBlock;"),
QStringLiteral("pageBlockSlideshow#130c8963 items:Vector<PageBlock> caption:RichText = PageBlock;"),
QStringLiteral("pageBlockPhoto#e9c69982 photo_id:long caption:RichText = PageBlock;"),
};
class tst_Generator : public QObject
{
Q_OBJECT
public:
explicit tst_Generator(QObject *parent = nullptr);
TLType getSolvedType(const Generator &generator, const QString &typeName) const;
private slots:
void checkRemoveWord_data();
void checkRemoveWord();
void checkFormatName_data();
void checkFormatName();
void checkTypeWithMemberConflicts();
void recursiveTypeMembers();
void doubleRecursiveTypeMembers();
void predicateForCrc_data();
void predicateForCrc();
};
tst_Generator::tst_Generator(QObject *parent) :
QObject(parent)
{
}
TLType tst_Generator::getSolvedType(const Generator &generator, const QString &typeName) const
{
const QString tName = Generator::formatType(typeName);
for (const TLType solved : generator.solvedTypes()) {
if (solved.name == tName) {
return solved;
}
}
return TLType();
}
void tst_Generator::checkRemoveWord_data()
{
QTest::addColumn<QString>("input");
QTest::addColumn<QString>("output");
QTest::addColumn<QString>("word");
QTest::newRow("No word in the input")
<< "idInputVideo"
<< "idInputVideo"
<< "audio";
QTest::newRow("Word in the end (different case)")
<< "idInputVideo"
<< "idInput"
<< "video";
QTest::newRow("Word in the end (same case)")
<< "idInputVideo"
<< "idInput"
<< "Video";
QTest::newRow("Word in the middle (different case)")
<< "idInputVideo"
<< "idVideo"
<< "input";
QTest::newRow("Word in the middle (same case)")
<< "idInputVideo"
<< "idVideo"
<< "Input";
QTest::newRow("Word in the beginning (different case)")
<< "idInputVideo"
<< "inputVideo"
<< "Id";
QTest::newRow("Word in the beginning (same case)")
<< "idInputVideo"
<< "inputVideo"
<< "id";
}
void tst_Generator::checkRemoveWord()
{
QFETCH(QString, input);
QFETCH(QString, output);
QFETCH(QString, word);
QCOMPARE(Generator::removeWord(input, word), output);
}
void tst_Generator::checkFormatName_data()
{
QTest::addColumn<QString>("input");
QTest::addColumn<QString>("output");
QTest::addColumn<Generator::FormatOptions>("options");
QTest::newRow("UpperCaseFirstLetter")
<< "inputVideo"
<< "InputVideo"
<< Generator::FormatOptions(Generator::FormatOption::UpperCaseFirstLetter);
QTest::newRow("LowerCaseFirstLetter")
<< "InputVideo"
<< "inputVideo"
<< Generator::FormatOptions(Generator::FormatOption::LowerCaseFirstLetter);
QTest::newRow("SkipFirstWord")
<< "AuthCheckPassword"
<< "CheckPassword"
<< Generator::FormatOptions(Generator::FormatOption::SkipFirstWord);
QTest::newRow("RemoveSeparators")
<< "auth_checkPassword"
<< "authCheckPassword"
<< Generator::FormatOptions(Generator::FormatOption::RemoveSeparators);
QTest::newRow("SkipTl")
<< "TLInputPeer"
<< "InputPeer"
<< Generator::FormatOptions(Generator::FormatOption::SkipTl);
}
void tst_Generator::checkFormatName()
{
QFETCH(QString, input);
QFETCH(QString, output);
QFETCH(Generator::FormatOptions, options);
QCOMPARE(Generator::formatName(input, options), output);
}
void tst_Generator::checkTypeWithMemberConflicts()
{
const QStringList sources = c_sourcesInputMediaDeps + c_sourcesInputMedia;
const QString generatedTypeName = Generator::parseLine(c_sourcesInputMedia.first()).typeName;
const QByteArray textData = generateTextSpec(sources);
Generator generator;
QVERIFY(generator.loadFromText(textData));
QVERIFY(generator.resolveTypes());
QVERIFY(!generator.solvedTypes().isEmpty());
const TLType solvedType = getSolvedType(generator, generatedTypeName);
QVERIFY(!solvedType.name.isEmpty());
const QStringList structMembers = Generator::generateTLTypeMembers(solvedType);
static const QStringList checkList = {
QStringLiteral("TLInputFile thumb;"),
QStringLiteral("TLInputVideo inputVideoId;"),
QStringLiteral("TLInputAudio inputAudioId;"),
QStringLiteral("TLVector<TLDocumentAttribute> attributes;"),
};
for (const QString &mustHaveMember : checkList) {
if (!structMembers.contains(mustHaveMember)) {
qDebug().noquote() << "Generated members:";
for (const QString &member : structMembers) {
qDebug().noquote() << " " << member;
}
QString message = QStringLiteral("The member \"%1\" is missing in the generated struct of the type %2.").arg(mustHaveMember, generatedTypeName);
QFAIL(message.toUtf8().constData());
}
}
}
void tst_Generator::recursiveTypeMembers()
{
const QStringList sources = c_sourcesRichText;
const QString generatedTypeName = Generator::parseLine(c_sourcesRichText.first()).typeName;
const QByteArray textData = generateTextSpec(sources);
Generator generator;
QVERIFY(generator.loadFromText(textData));
QMap<QString, TLType> types = generator.types();
QCOMPARE(types.size(), 1);
QVERIFY(generator.resolveTypes());
QVERIFY(!generator.solvedTypes().isEmpty());
const TLType solvedType = getSolvedType(generator, generatedTypeName);
QVERIFY(!solvedType.name.isEmpty());
const QStringList structMembers = Generator::generateTLTypeMembers(solvedType);
static const QStringList checkList = {
QStringLiteral("QString email;"),
QStringLiteral("QString stringText;"),
QStringLiteral("TLRichTextPtr richText;"),
QStringLiteral("TLVector<TLRichText*> texts;"),
};
for (const QString &mustHaveMember : checkList) {
if (!structMembers.contains(mustHaveMember)) {
qDebug().noquote() << "Generated members:";
for (const QString &member : structMembers) {
qDebug().noquote() << " " << member;
}
QString message = QStringLiteral("The member \"%1\" is missing in the generated struct of the type %2.").arg(mustHaveMember, generatedTypeName);
QFAIL(message.toUtf8().constData());
}
}
}
void tst_Generator::doubleRecursiveTypeMembers()
{
const QStringList sources = c_sourcesRichText + c_sourcesPageBlock;
const QString generatedTypeName = Generator::parseLine(c_sourcesPageBlock.first()).typeName;
const QByteArray textData = generateTextSpec(sources);
Generator generator;
QVERIFY(generator.loadFromText(textData));
QMap<QString, TLType> types = generator.types();
QVERIFY(!types.isEmpty());
QVERIFY(generator.resolveTypes());
QVERIFY(!generator.solvedTypes().isEmpty());
const TLType solvedType = getSolvedType(generator, generatedTypeName);
QVERIFY(!solvedType.name.isEmpty());
const QStringList structMembers = Generator::generateTLTypeMembers(solvedType);
static const QStringList checkList = {
QStringLiteral("TLRichTextPtr text;"),
QStringLiteral("TLVector<TLRichText*> richTextItemsVector;"),
QStringLiteral("TLVector<TLPageBlock*> blocks;"),
QStringLiteral("TLVector<TLPageBlock*> pageBlockItemsVector;"),
QStringLiteral("TLRichTextPtr caption;"),
};
for (const QString &mustHaveMember : checkList) {
if (!structMembers.contains(mustHaveMember)) {
qDebug().noquote() << "Generated members:";
for (const QString &member : structMembers) {
qDebug().noquote() << " " << member;
}
QString message = QStringLiteral("The member \"%1\" is missing in the generated struct of the type %2.").arg(mustHaveMember, generatedTypeName);
QFAIL(message.toUtf8().constData());
}
}
}
void tst_Generator::predicateForCrc_data()
{
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QByteArray>("output");
QTest::addRow("Trivial") << QByteArrayLiteral("help.getConfig#c4f9186b = Config;")
<< QByteArrayLiteral("help.getConfig = Config");
QTest::addRow("Trivial") << QByteArrayLiteral("req_pq#60469778 nonce:int128 = ResPQ;")
<< QByteArrayLiteral("req_pq nonce:int128 = ResPQ");
QTest::addRow("With true flags") << QByteArrayLiteral("channels.createChannel#f4893d7f flags:#"
" broadcast:flags.0?true megagroup:flags.1?true"
" title:string about:string = Updates;")
<< QByteArrayLiteral("channels.createChannel flags:#"
" title:string about:string = Updates");
QTest::addRow("With flags") << QByteArrayLiteral("updates.getDifference#25939651 flags:#"
" pts:int pts_total_limit:flags.0?int date:int"
" qts:int = updates.Difference;")
<< QByteArrayLiteral("updates.getDifference flags:#"
" pts:int pts_total_limit:flags.0?int date:int"
" qts:int = updates.Difference");
QTest::addRow("With vector") << QByteArrayLiteral("messages.getAllChats#eba80ff0"
" except_ids:Vector<int> = messages.Chats;")
<< QByteArrayLiteral("messages.getAllChats"
" except_ids:Vector int = messages.Chats");
QTest::addRow("Vector") << QByteArrayLiteral("vector#1cb5c415 {t:Type} # [ t ] = Vector t;")
<< QByteArrayLiteral("vector t:Type # [ t ] = Vector t");
}
void tst_Generator::predicateForCrc()
{
QFETCH(QByteArray, input);
QFETCH(QByteArray, output);
QCOMPARE(Generator::getBarePredicate(input), output);
}
QTEST_APPLESS_MAIN(tst_Generator)
#include "tst_generator.moc"
<commit_msg>Tests/Generator: Add a test for TLType flags conflict<commit_after>#include <QObject>
#include <QTest>
#include <QDebug>
#include "../Generator.hpp"
const QString c_typesSection = QStringLiteral("---types---");
const QString c_functionsSection = QStringLiteral("---functions---");
static QByteArray generateTextSpec(const QStringList &types, const QStringList &functions = {})
{
QByteArray result;
if (!types.isEmpty()) {
const QString textData = c_typesSection + QLatin1Char('\n') + types.join(QLatin1Char('\n')) + QLatin1Char('\n');
result += textData.toLocal8Bit();
}
if (!functions.isEmpty()) {
const QString textData = c_functionsSection + QLatin1Char('\n') + functions.join(QLatin1Char('\n')) + QLatin1Char('\n');
result += textData.toLocal8Bit();
}
return result;
}
const QStringList c_sourcesInputMediaDeps =
{
QStringLiteral("inputPhotoEmpty = InputPhoto;"),
QStringLiteral("inputFileEmpty = InputFile;"),
QStringLiteral("inputVideoEmpty = InputVideo;"),
QStringLiteral("inputAudioEmpty = InputAudio;"),
QStringLiteral("inputDocumentEmpty = InputDocument;"),
QStringLiteral("documentAttributeEmpty = DocumentAttribute;"),
};
const QStringList c_sourcesInputMedia =
{
QStringLiteral("inputMediaEmpty#9664f57f = InputMedia;"),
QStringLiteral("inputMediaUploadedPhoto#2f37e231 flags:# file:InputFile caption:string stickers:flags.0?Vector<InputDocument> ttl_seconds:flags.1?int = InputMedia;"),
QStringLiteral("inputMediaPhotoExternal#922aec1 flags:# url:string caption:string ttl_seconds:flags.0?int = InputMedia;"),
QStringLiteral("inputMediaPhoto#e9bfb4f3 id:InputPhoto caption:string = InputMedia;"),
QStringLiteral("inputMediaContact#a6e45987 phone_number:string first_name:string last_name:string = InputMedia;"),
QStringLiteral("inputMediaUploadedVideo#82713fdf file:InputFile duration:int w:int h:int mime_type:string caption:string = InputMedia;"),
QStringLiteral("inputMediaUploadedThumbVideo#7780ddf9 file:InputFile thumb:InputFile duration:int w:int h:int mime_type:string caption:string = InputMedia;"),
QStringLiteral("inputMediaVideo#936a4ebd id:InputVideo caption:string = InputMedia;"),
QStringLiteral("inputMediaUploadedAudio#4e498cab file:InputFile duration:int mime_type:string = InputMedia;"),
QStringLiteral("inputMediaAudio#89938781 id:InputAudio = InputMedia;"),
QStringLiteral("inputMediaUploadedDocument#1d89306d file:InputFile mime_type:string attributes:Vector<DocumentAttribute> caption:string = InputMedia;"),
QStringLiteral("inputMediaUploadedThumbDocument#ad613491 file:InputFile thumb:InputFile mime_type:string attributes:Vector<DocumentAttribute> caption:string = InputMedia;"),
QStringLiteral("inputMediaDocument#1a77f29c id:InputDocument caption:string = InputMedia;"),
};
const QStringList c_inputMediaFlags =
{
QStringLiteral("TtlSeconds0 = 1 << 0,"),
QStringLiteral("Stickers = 1 << 0,"),
QStringLiteral("TtlSeconds1 = 1 << 1,"),
};
const QStringList c_sourcesRichText =
{
QStringLiteral("textEmpty#dc3d824f = RichText;"),
QStringLiteral("textPlain#744694e0 text:string = RichText;"),
QStringLiteral("textBold#6724abc4 text:RichText = RichText;"),
QStringLiteral("textItalic#d912a59c text:RichText = RichText;"),
QStringLiteral("textUnderline#c12622c4 text:RichText = RichText;"),
QStringLiteral("textStrike#9bf8bb95 text:RichText = RichText;"),
QStringLiteral("textFixed#6c3f19b9 text:RichText = RichText;"),
QStringLiteral("textUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;"),
QStringLiteral("textEmail#de5a0dd6 text:RichText email:string = RichText;"),
QStringLiteral("textConcat#7e6260d7 texts:Vector<RichText> = RichText;"),
};
const QStringList c_sourcesPageBlock =
{
QStringLiteral("pageBlockUnsupported#13567e8a = PageBlock;"),
QStringLiteral("pageBlockTitle#70abc3fd text:RichText = PageBlock;"),
QStringLiteral("pageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;"),
QStringLiteral("pageBlockList#3a58c7f4 ordered:Bool items:Vector<RichText> = PageBlock;"),
QStringLiteral("pageBlockEmbedPost#292c7be9 url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector<PageBlock> caption:RichText = PageBlock;"),
QStringLiteral("pageBlockSlideshow#130c8963 items:Vector<PageBlock> caption:RichText = PageBlock;"),
QStringLiteral("pageBlockPhoto#e9c69982 photo_id:long caption:RichText = PageBlock;"),
};
class tst_Generator : public QObject
{
Q_OBJECT
public:
explicit tst_Generator(QObject *parent = nullptr);
TLType getSolvedType(const Generator &generator, const QString &typeName) const;
private slots:
void checkRemoveWord_data();
void checkRemoveWord();
void checkFormatName_data();
void checkFormatName();
void checkTypeWithMemberConflicts();
void typeWithMemberFlagsConflict();
void recursiveTypeMembers();
void doubleRecursiveTypeMembers();
void predicateForCrc_data();
void predicateForCrc();
};
tst_Generator::tst_Generator(QObject *parent) :
QObject(parent)
{
}
TLType tst_Generator::getSolvedType(const Generator &generator, const QString &typeName) const
{
const QString tName = Generator::formatType(typeName);
for (const TLType solved : generator.solvedTypes()) {
if (solved.name == tName) {
return solved;
}
}
return TLType();
}
void tst_Generator::checkRemoveWord_data()
{
QTest::addColumn<QString>("input");
QTest::addColumn<QString>("output");
QTest::addColumn<QString>("word");
QTest::newRow("No word in the input")
<< "idInputVideo"
<< "idInputVideo"
<< "audio";
QTest::newRow("Word in the end (different case)")
<< "idInputVideo"
<< "idInput"
<< "video";
QTest::newRow("Word in the end (same case)")
<< "idInputVideo"
<< "idInput"
<< "Video";
QTest::newRow("Word in the middle (different case)")
<< "idInputVideo"
<< "idVideo"
<< "input";
QTest::newRow("Word in the middle (same case)")
<< "idInputVideo"
<< "idVideo"
<< "Input";
QTest::newRow("Word in the beginning (different case)")
<< "idInputVideo"
<< "inputVideo"
<< "Id";
QTest::newRow("Word in the beginning (same case)")
<< "idInputVideo"
<< "inputVideo"
<< "id";
}
void tst_Generator::checkRemoveWord()
{
QFETCH(QString, input);
QFETCH(QString, output);
QFETCH(QString, word);
QCOMPARE(Generator::removeWord(input, word), output);
}
void tst_Generator::checkFormatName_data()
{
QTest::addColumn<QString>("input");
QTest::addColumn<QString>("output");
QTest::addColumn<Generator::FormatOptions>("options");
QTest::newRow("UpperCaseFirstLetter")
<< "inputVideo"
<< "InputVideo"
<< Generator::FormatOptions(Generator::FormatOption::UpperCaseFirstLetter);
QTest::newRow("LowerCaseFirstLetter")
<< "InputVideo"
<< "inputVideo"
<< Generator::FormatOptions(Generator::FormatOption::LowerCaseFirstLetter);
QTest::newRow("SkipFirstWord")
<< "AuthCheckPassword"
<< "CheckPassword"
<< Generator::FormatOptions(Generator::FormatOption::SkipFirstWord);
QTest::newRow("RemoveSeparators")
<< "auth_checkPassword"
<< "authCheckPassword"
<< Generator::FormatOptions(Generator::FormatOption::RemoveSeparators);
QTest::newRow("SkipTl")
<< "TLInputPeer"
<< "InputPeer"
<< Generator::FormatOptions(Generator::FormatOption::SkipTl);
}
void tst_Generator::checkFormatName()
{
QFETCH(QString, input);
QFETCH(QString, output);
QFETCH(Generator::FormatOptions, options);
QCOMPARE(Generator::formatName(input, options), output);
}
void tst_Generator::checkTypeWithMemberConflicts()
{
const QStringList sources = c_sourcesInputMediaDeps + c_sourcesInputMedia;
const QString generatedTypeName = Generator::parseLine(c_sourcesInputMedia.first()).typeName;
const QByteArray textData = generateTextSpec(sources);
Generator generator;
QVERIFY(generator.loadFromText(textData));
QVERIFY(generator.resolveTypes());
QVERIFY(!generator.solvedTypes().isEmpty());
const TLType solvedType = getSolvedType(generator, generatedTypeName);
QVERIFY(!solvedType.name.isEmpty());
const QStringList structMembers = Generator::generateTLTypeMembers(solvedType);
static const QStringList checkList = {
QStringLiteral("TLInputFile thumb;"),
QStringLiteral("TLInputVideo inputVideoId;"),
QStringLiteral("TLInputAudio inputAudioId;"),
QStringLiteral("TLVector<TLDocumentAttribute> attributes;"),
};
for (const QString &mustHaveMember : checkList) {
if (!structMembers.contains(mustHaveMember)) {
qDebug().noquote() << "Generated members:";
for (const QString &member : structMembers) {
qDebug().noquote() << " " << member;
}
QString message = QStringLiteral("The member \"%1\" is missing in the generated struct of the type %2.").arg(mustHaveMember, generatedTypeName);
QFAIL(message.toUtf8().constData());
}
}
}
void tst_Generator::typeWithMemberFlagsConflict()
{
const QStringList sources = c_sourcesInputMediaDeps + c_sourcesInputMedia;
const QString generatedTypeName = Generator::parseLine(c_sourcesInputMedia.first()).typeName;
const QByteArray textData = generateTextSpec(sources);
Generator generator;
QVERIFY(generator.loadFromText(textData));
QVERIFY(generator.resolveTypes());
QVERIFY(!generator.solvedTypes().isEmpty());
const TLType solvedType = getSolvedType(generator, generatedTypeName);
QVERIFY(!solvedType.name.isEmpty());
const QStringList flags = Generator::generateTLTypeMemberFlags(solvedType);
QCOMPARE(flags, c_inputMediaFlags);
}
void tst_Generator::recursiveTypeMembers()
{
const QStringList sources = c_sourcesRichText;
const QString generatedTypeName = Generator::parseLine(c_sourcesRichText.first()).typeName;
const QByteArray textData = generateTextSpec(sources);
Generator generator;
QVERIFY(generator.loadFromText(textData));
QMap<QString, TLType> types = generator.types();
QCOMPARE(types.size(), 1);
QVERIFY(generator.resolveTypes());
QVERIFY(!generator.solvedTypes().isEmpty());
const TLType solvedType = getSolvedType(generator, generatedTypeName);
QVERIFY(!solvedType.name.isEmpty());
const QStringList structMembers = Generator::generateTLTypeMembers(solvedType);
static const QStringList checkList = {
QStringLiteral("QString email;"),
QStringLiteral("QString stringText;"),
QStringLiteral("TLRichTextPtr richText;"),
QStringLiteral("TLVector<TLRichText*> texts;"),
};
for (const QString &mustHaveMember : checkList) {
if (!structMembers.contains(mustHaveMember)) {
qDebug().noquote() << "Generated members:";
for (const QString &member : structMembers) {
qDebug().noquote() << " " << member;
}
QString message = QStringLiteral("The member \"%1\" is missing in the generated struct of the type %2.").arg(mustHaveMember, generatedTypeName);
QFAIL(message.toUtf8().constData());
}
}
}
void tst_Generator::doubleRecursiveTypeMembers()
{
const QStringList sources = c_sourcesRichText + c_sourcesPageBlock;
const QString generatedTypeName = Generator::parseLine(c_sourcesPageBlock.first()).typeName;
const QByteArray textData = generateTextSpec(sources);
Generator generator;
QVERIFY(generator.loadFromText(textData));
QMap<QString, TLType> types = generator.types();
QVERIFY(!types.isEmpty());
QVERIFY(generator.resolveTypes());
QVERIFY(!generator.solvedTypes().isEmpty());
const TLType solvedType = getSolvedType(generator, generatedTypeName);
QVERIFY(!solvedType.name.isEmpty());
const QStringList structMembers = Generator::generateTLTypeMembers(solvedType);
static const QStringList checkList = {
QStringLiteral("TLRichTextPtr text;"),
QStringLiteral("TLVector<TLRichText*> richTextItemsVector;"),
QStringLiteral("TLVector<TLPageBlock*> blocks;"),
QStringLiteral("TLVector<TLPageBlock*> pageBlockItemsVector;"),
QStringLiteral("TLRichTextPtr caption;"),
};
for (const QString &mustHaveMember : checkList) {
if (!structMembers.contains(mustHaveMember)) {
qDebug().noquote() << "Generated members:";
for (const QString &member : structMembers) {
qDebug().noquote() << " " << member;
}
QString message = QStringLiteral("The member \"%1\" is missing in the generated struct of the type %2.").arg(mustHaveMember, generatedTypeName);
QFAIL(message.toUtf8().constData());
}
}
}
void tst_Generator::predicateForCrc_data()
{
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QByteArray>("output");
QTest::addRow("Trivial") << QByteArrayLiteral("help.getConfig#c4f9186b = Config;")
<< QByteArrayLiteral("help.getConfig = Config");
QTest::addRow("Trivial") << QByteArrayLiteral("req_pq#60469778 nonce:int128 = ResPQ;")
<< QByteArrayLiteral("req_pq nonce:int128 = ResPQ");
QTest::addRow("With true flags") << QByteArrayLiteral("channels.createChannel#f4893d7f flags:#"
" broadcast:flags.0?true megagroup:flags.1?true"
" title:string about:string = Updates;")
<< QByteArrayLiteral("channels.createChannel flags:#"
" title:string about:string = Updates");
QTest::addRow("With flags") << QByteArrayLiteral("updates.getDifference#25939651 flags:#"
" pts:int pts_total_limit:flags.0?int date:int"
" qts:int = updates.Difference;")
<< QByteArrayLiteral("updates.getDifference flags:#"
" pts:int pts_total_limit:flags.0?int date:int"
" qts:int = updates.Difference");
QTest::addRow("With vector") << QByteArrayLiteral("messages.getAllChats#eba80ff0"
" except_ids:Vector<int> = messages.Chats;")
<< QByteArrayLiteral("messages.getAllChats"
" except_ids:Vector int = messages.Chats");
QTest::addRow("Vector") << QByteArrayLiteral("vector#1cb5c415 {t:Type} # [ t ] = Vector t;")
<< QByteArrayLiteral("vector t:Type # [ t ] = Vector t");
}
void tst_Generator::predicateForCrc()
{
QFETCH(QByteArray, input);
QFETCH(QByteArray, output);
QCOMPARE(Generator::getBarePredicate(input), output);
}
QTEST_APPLESS_MAIN(tst_Generator)
#include "tst_generator.moc"
<|endoftext|> |
<commit_before><commit_msg>gpu: Removed unused class declaration.<commit_after><|endoftext|> |
<commit_before>/* This file is part of the KDE libraries
Copyright (C) 2007 Laurent Montel <montel@kde.org>
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 <kmeditor.h>
#include <KApplication>
#include <kcmdlineargs.h>
#include <QAction>
#include <QMenu>
#include <QMenuBar>
#include <testkmeditorwin.h>
#include "testkmeditorwin.moc"
testKMeditorWindow::testKMeditorWindow()
{
setCaption("test kmeditor window");
editor = new KMeditor;
editor->setAcceptRichText(false);
setCentralWidget(editor);
QMenu *editMenu = menuBar()->addMenu(tr("Edit"));
QAction *act = new QAction(tr("bold"), this);
act->setChecked(true);
connect(act, SIGNAL(toggled(bool)), editor, SLOT(slotTextBold(bool)));
editMenu->addAction(act);
act = new QAction(tr("italic"), this);
act->setChecked(true);
connect(act, SIGNAL(toggled(bool)), editor, SLOT(slotTextItalic(bool)));
editMenu->addAction(act);
act = new QAction(tr("underline"), this);
act->setChecked(true);
connect(act, SIGNAL(toggled(bool)), editor, SLOT(slotTextUnder(bool)));
editMenu->addAction(act);
act = new QAction(tr("text color"), this);
connect(act, SIGNAL(triggered()), editor, SLOT(slotTextColor()));
editMenu->addAction(act);
act = new QAction(tr("Align left"), this);
connect(act, SIGNAL(triggered()), editor, SLOT(slotAlignLeft()));
editMenu->addAction(act);
act = new QAction(tr("Align right"), this);
connect(act, SIGNAL(triggered()), editor, SLOT(slotAlignRight()));
editMenu->addAction(act);
act = new QAction(tr("Align center"), this);
connect(act, SIGNAL(triggered()), editor, SLOT(slotAlignCenter()));
editMenu->addAction(act);
}
testKMeditorWindow::~testKMeditorWindow()
{
}
int main( int argc, char **argv )
{
KCmdLineArgs::init( argc, argv, "testkmeditorwin", "KMeditorTestWin", "kmeditor test win app", "1.0" );
KApplication app;
testKMeditorWindow *edit = new testKMeditorWindow();
edit->show();
return app.exec();
}
<commit_msg>setCheckable<commit_after>/* This file is part of the KDE libraries
Copyright (C) 2007 Laurent Montel <montel@kde.org>
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 <kmeditor.h>
#include <KApplication>
#include <kcmdlineargs.h>
#include <QAction>
#include <QMenu>
#include <QMenuBar>
#include <testkmeditorwin.h>
#include "testkmeditorwin.moc"
testKMeditorWindow::testKMeditorWindow()
{
setCaption("test kmeditor window");
editor = new KMeditor;
editor->setAcceptRichText(false);
setCentralWidget(editor);
QMenu *editMenu = menuBar()->addMenu(tr("Edit"));
QAction *act = new QAction(tr("bold"), this);
act->setCheckable(true);
connect(act, SIGNAL(triggered(bool)), editor, SLOT(slotTextBold(bool)));
editMenu->addAction(act);
act = new QAction(tr("italic"), this);
act->setCheckable(true);
connect(act, SIGNAL(triggered (bool)), editor, SLOT(slotTextItalic(bool)));
editMenu->addAction(act);
act = new QAction(tr("underline"), this);
act->setCheckable(true);
connect(act, SIGNAL(triggered (bool)), editor, SLOT(slotTextUnder(bool)));
editMenu->addAction(act);
act = new QAction(tr("text color"), this);
connect(act, SIGNAL(triggered()), editor, SLOT(slotTextColor()));
editMenu->addAction(act);
act = new QAction(tr("Align left"), this);
connect(act, SIGNAL(triggered()), editor, SLOT(slotAlignLeft()));
editMenu->addAction(act);
act = new QAction(tr("Align right"), this);
connect(act, SIGNAL(triggered()), editor, SLOT(slotAlignRight()));
editMenu->addAction(act);
act = new QAction(tr("Align center"), this);
connect(act, SIGNAL(triggered()), editor, SLOT(slotAlignCenter()));
editMenu->addAction(act);
}
testKMeditorWindow::~testKMeditorWindow()
{
}
int main( int argc, char **argv )
{
KCmdLineArgs::init( argc, argv, "testkmeditorwin", "KMeditorTestWin", "kmeditor test win app", "1.0" );
KApplication app;
testKMeditorWindow *edit = new testKMeditorWindow();
edit->show();
return app.exec();
}
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Nathan Osman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <QJsonArray>
#include <QJsonDocument>
#include <QMetaObject>
#include <QMetaProperty>
#include <nitroshare/jsonutil.h>
QJsonObject JsonUtil::objectToJson(QObject *object)
{
QJsonObject jsonObject;
for (int i = 1; i < object->metaObject()->propertyCount(); ++i) {
auto property = object->metaObject()->property(i);
auto name = property.name();
auto value = object->property(name);
if (property.type() == QVariant::LongLong) {
value = QString::number(value.toLongLong());
}
jsonObject.insert(name, QJsonValue::fromVariant(value));
}
return jsonObject;
}
QByteArray JsonUtil::jsonValueToByteArray(const QJsonValue &value)
{
// Begin by creating an array with a single item
QByteArray json = QJsonDocument(QJsonArray{value}).toJson().trimmed();
// Strip the initial '[' and ']'
return json.mid(1, json.length() - 2).trimmed();
}
<commit_msg>Ensure indentation is consistent.<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Nathan Osman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <QJsonArray>
#include <QJsonDocument>
#include <QMetaObject>
#include <QMetaProperty>
#include <nitroshare/jsonutil.h>
QJsonObject JsonUtil::objectToJson(QObject *object)
{
QJsonObject jsonObject;
for (int i = 1; i < object->metaObject()->propertyCount(); ++i) {
auto property = object->metaObject()->property(i);
auto name = property.name();
auto value = object->property(name);
if (property.type() == QVariant::LongLong) {
value = QString::number(value.toLongLong());
}
jsonObject.insert(name, QJsonValue::fromVariant(value));
}
return jsonObject;
}
QByteArray JsonUtil::jsonValueToByteArray(const QJsonValue &value)
{
switch (value.type()) {
case QJsonValue::Array:
return QJsonDocument(value.toArray()).toJson();
case QJsonValue::Object:
return QJsonDocument(value.toObject()).toJson();
default:
{
QByteArray json = QJsonDocument(QJsonArray{value}).toJson().trimmed();
return json.mid(1, json.length() - 2).trimmed() + "\n";
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013 midnightBITS
*
* 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.
*/
#ifndef __POST_MORTEM_HPP__
#define __POST_MORTEM_HPP__
#include <thread>
#include <net/filesystem.hpp>
#ifdef WIN32
# include <windows.h>
# pragma warning(push)
// warning C4091: 'typedef ': ignored on left of 'tagSTRUCT' when no variable is declared
# pragma warning(disable: 4091)
# include <DbgHelp.h>
# pragma warning(pop)
# pragma comment(lib, "dbghelp.lib")
#endif
namespace pm
{
#ifdef WIN32
class Win32PostMortemSupport {
static fs::path tempDir() {
auto size = GetTempPath(0, nullptr);
if (!size)
return fs::current_path();
++size;
std::unique_ptr<WCHAR[]> path{ new WCHAR[size] };
if (!GetTempPath(size, path.get()))
return fs::current_path();
return path.get();
}
static std::wstring buildPath() {
auto temp = tempDir();
temp /= "MiniDump.dmp";
temp.make_preferred();
return temp.wstring();
}
static LPCWSTR dumpPath() {
static std::wstring path = buildPath();
return path.c_str();
}
static void Write(_EXCEPTION_POINTERS* ep) {
auto mdt = static_cast<MINIDUMP_TYPE>(
MiniDumpWithDataSegs |
MiniDumpWithFullMemory |
MiniDumpWithFullMemoryInfo |
MiniDumpWithHandleData |
MiniDumpWithThreadInfo |
MiniDumpWithProcessThreadData |
MiniDumpWithUnloadedModules
);
auto file = CreateFileW(dumpPath(), GENERIC_READ | GENERIC_WRITE,
0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file && file != INVALID_HANDLE_VALUE) {
MINIDUMP_EXCEPTION_INFORMATION mei{ GetCurrentThreadId(), ep, TRUE };
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), file, mdt, ep ? &mei : nullptr, nullptr, nullptr);
CloseHandle(file);
}
TerminateProcess(GetCurrentProcess(), 1);
}
public:
template <class Fn, class... Args>
static void Run(Fn&& fn, Args&&... args) {
(void)dumpPath(); // build file path now for any OOM later...
_EXCEPTION_POINTERS* exception = nullptr;
__try {
fn(std::forward<Args>(args)...);
}
__except (exception = GetExceptionInformation(), EXCEPTION_EXECUTE_HANDLER) {
Write(exception);
}
}
};
template <class Fn, class... Args>
inline void PostMortemSupport(Fn&& fn, Args&&... args) {
Win32PostMortemSupport::Run(std::forward<Fn>(fn), std::forward<Args>(args)...);
}
#else // !WIN32
template <class Fn, class... Args>
inline void PostMortemSupport(Fn&& fn, Args&&... args) {
fn(std::forward<Args>(args)...);
}
#endif // WIN32
template <class Fn, class... Args>
inline std::thread thread(Fn&& fn, Args&&... args)
{
return std::thread{ PostMortemSupport<Fn, Args...>, std::forward<Fn>(fn), std::forward<Args>(args)... };
}
};
#endif // __POST_MORTEM_HPP__
<commit_msg>[JIRDESK-85] Postmortem dump information<commit_after>/*
* Copyright (C) 2013 midnightBITS
*
* 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.
*/
#ifndef __POST_MORTEM_HPP__
#define __POST_MORTEM_HPP__
#include <thread>
#include <net/filesystem.hpp>
#ifdef WIN32
# include <windows.h>
# pragma warning(push)
// warning C4091: 'typedef ': ignored on left of 'tagSTRUCT' when no variable is declared
# pragma warning(disable: 4091)
# include <DbgHelp.h>
# pragma warning(pop)
# pragma comment(lib, "dbghelp.lib")
#endif
namespace pm
{
#ifdef WIN32
class Win32PostMortemSupport {
static fs::path tempDir() {
auto size = GetTempPath(0, nullptr);
if (!size)
return fs::current_path();
++size;
std::unique_ptr<WCHAR[]> path{ new WCHAR[size] };
if (!GetTempPath(size, path.get()))
return fs::current_path();
return path.get();
}
static std::wstring buildPath() {
auto temp = tempDir();
temp /= "MiniDump.dmp";
temp.make_preferred();
return temp.wstring();
}
static LPCWSTR dumpPath() {
static std::wstring path = buildPath();
return path.c_str();
}
static void Write(_EXCEPTION_POINTERS* ep) {
auto mdt = static_cast<MINIDUMP_TYPE>(
MiniDumpWithDataSegs |
MiniDumpWithFullMemory |
MiniDumpWithFullMemoryInfo |
MiniDumpWithHandleData |
MiniDumpWithThreadInfo |
MiniDumpWithProcessThreadData |
MiniDumpWithUnloadedModules
);
auto file = CreateFileW(dumpPath(), GENERIC_READ | GENERIC_WRITE,
0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file && file != INVALID_HANDLE_VALUE) {
wchar_t buffer[2048];
MINIDUMP_EXCEPTION_INFORMATION mei{ GetCurrentThreadId(), ep, TRUE };
if (!MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), file, mdt, ep ? &mei : nullptr, nullptr, nullptr)) {
auto err = GetLastError();
CloseHandle(file);
DeleteFileW(dumpPath());
if (!err) {
swprintf_s(buffer, L"An error occured, but memory was not dumped due to unknown reason.");
} else {
swprintf_s(buffer, L"An error occured, but memory was not dumped due to error %08x.", err);
}
} else {
CloseHandle(file);
if (ep) {
swprintf_s(buffer, L"An error %08x occured at %p (thread %u), memory dumped to:\n\n%s",
ep->ExceptionRecord->ExceptionCode,
ep->ExceptionRecord->ExceptionAddress,
GetCurrentThreadId(),
dumpPath());
} else {
swprintf_s(buffer, L"An unkown error occured, memory dumped to:\n\n%s", dumpPath());
}
}
MessageBoxW(nullptr, buffer, L"This program perfomed illegal operation", MB_ICONINFORMATION);
}
TerminateProcess(GetCurrentProcess(), 1);
}
public:
template <class Fn, class... Args>
static void Run(Fn&& fn, Args&&... args) {
(void)dumpPath(); // build file path now for any OOM later...
_EXCEPTION_POINTERS* exception = nullptr;
__try {
fn(std::forward<Args>(args)...);
}
__except (exception = GetExceptionInformation(), EXCEPTION_EXECUTE_HANDLER) {
Write(exception);
}
}
};
template <class Fn, class... Args>
inline void PostMortemSupport(Fn&& fn, Args&&... args) {
Win32PostMortemSupport::Run(std::forward<Fn>(fn), std::forward<Args>(args)...);
}
#else // !WIN32
template <class Fn, class... Args>
inline void PostMortemSupport(Fn&& fn, Args&&... args) {
fn(std::forward<Args>(args)...);
}
#endif // WIN32
template <class Fn, class... Args>
inline std::thread thread(Fn&& fn, Args&&... args)
{
return std::thread{ PostMortemSupport<Fn, Args...>, std::forward<Fn>(fn), std::forward<Args>(args)... };
}
};
#endif // __POST_MORTEM_HPP__
<|endoftext|> |
<commit_before>#include "KernelJsonImporter.h"
#include <glkernel/Kernel.h>
#include <cppassist/logging/logging.h>
void forEachCell(cppexpose::VariantArray * depthArray, std::function<void(const cppexpose::Variant&)> lambda)
{
if (!depthArray)
{
cppassist::error() << "Malformed kernel input.";
}
for (const auto& heightVariant : *depthArray)
{
auto heightArray = heightVariant.asArray();
if (!heightArray)
{
cppassist::error() << "Malformed kernel input.";
}
for (const auto& widthVariant : *heightArray)
{
auto widthArray = widthVariant.asArray();
if (!widthArray)
{
cppassist::error() << "Malformed kernel input.";
}
for (const auto& elementVariant : *widthArray)
{
lambda(elementVariant);
}
}
}
}
// TODO: this is duplicated in the generated code, remove this duplication
float variantToFloat(const cppexpose::Variant & v)
{
return v.value<float>();
}
glm::vec2 variantToVec2(const cppexpose::Variant & v)
{
const auto arr = v.asArray();
const auto x = variantToFloat(arr->at(0));
const auto y = variantToFloat(arr->at(1));
return glm::vec2(x,y);
}
glm::vec3 variantToVec3(const cppexpose::Variant & v)
{
const auto arr = v.asArray();
const auto x = variantToFloat(arr->at(0));
const auto y = variantToFloat(arr->at(1));
const auto z = variantToFloat(arr->at(2));
return glm::vec3(x,y,z);
}
glm::vec4 variantToVec4(const cppexpose::Variant & v)
{
const auto arr = v.asArray();
const auto x = variantToFloat(arr->at(0));
const auto y = variantToFloat(arr->at(1));
const auto z = variantToFloat(arr->at(2));
const auto w = variantToFloat(arr->at(3));
return glm::vec4(x,y,z,w);
}
KernelJsonImporter::KernelJsonImporter(const std::string& inputFileName)
{
cppexpose::Variant root;
if (!cppexpose::JSON::load(root, inputFileName))
{
cppassist::error() << "Input JSON file could not be loaded.";
}
auto rootMap = root.asMap();
if (!rootMap)
{
cppassist::error() << "Input JSON is malformed.";
}
auto depthArray = rootMap->at("kernel").asArray();
auto sizeMap = rootMap->at("size").asMap();
int depth = sizeMap->at("depth").value<int>();
int height = sizeMap->at("height").value<int>();
int width = sizeMap->at("width").value<int>();
size_t numCells = 0;
int numComponents = -1;
forEachCell(depthArray, [&numCells, &numComponents](const cppexpose::Variant& elementVariant) {
if (elementVariant.isFloatingPoint())
{
if (numComponents != -1 && numComponents != 1) {
cppassist::error() << "All cells must have the same cell type (float, vec2, vec3 or vec4).";
}
numComponents = 1;
}
else
{
if (!elementVariant.isArray()) {
cppassist::error() << "Cell is not floating point or array.";
}
if (numComponents != -1 && elementVariant.asArray()->size() != numComponents) {
cppassist::error() << "All cells must have the same cell type (float, vec2, vec3 or vec4).";
}
numComponents = elementVariant.asArray()->size();
}
numCells++;
});
int i = 0;
if (numComponents == 1)
{
glkernel::kernel1 kernel(width, height, depth);
forEachCell(depthArray, [&i, &kernel](const cppexpose::Variant& elementVariant) {
kernel[i] = variantToFloat(elementVariant);
i++;
});
m_kernelVariant = cppexpose::Variant::fromValue(kernel);
}
else if (numComponents == 2)
{
glkernel::kernel2 kernel(width, height, depth);
forEachCell(depthArray, [&i, &kernel](const cppexpose::Variant& elementVariant) {
kernel[i] = variantToVec2(elementVariant);
i++;
});
m_kernelVariant = cppexpose::Variant::fromValue(kernel);
}
else if (numComponents == 3)
{
glkernel::kernel3 kernel(width, height, depth);
forEachCell(depthArray, [&i, &kernel](const cppexpose::Variant& elementVariant) {
kernel[i] = variantToVec3(elementVariant);
i++;
});
m_kernelVariant = cppexpose::Variant::fromValue(kernel);
}
else if (numComponents == 4)
{
glkernel::kernel4 kernel(width, height, depth);
forEachCell(depthArray, [&i, &kernel](const cppexpose::Variant& elementVariant) {
kernel[i] = variantToVec4(elementVariant);
i++;
});
m_kernelVariant = cppexpose::Variant::fromValue(kernel);
}
else
{
cppassist::error() << "Invalid number of components.";
}
}
cppexpose::Variant KernelJsonImporter::getKernel()
{
return m_kernelVariant;
}
<commit_msg>Replace error checks woth custom assert<commit_after>#include "KernelJsonImporter.h"
#include <glkernel/Kernel.h>
#include <cppassist/logging/logging.h>
void assert_msg(bool condition, const std::string& msg)
{
if (!condition)
{
throw std::logic_error(msg);
}
}
void forEachCell(cppexpose::VariantArray * depthArray, std::function<void(const cppexpose::Variant&)> lambda)
{
assert_msg(depthArray, "Malformed kernel input.");
for (const auto& heightVariant : *depthArray)
{
auto heightArray = heightVariant.asArray();
assert_msg(heightArray, "Malformed kernel input.");
for (const auto& widthVariant : *heightArray)
{
auto widthArray = widthVariant.asArray();
assert_msg(widthArray, "Malformed kernel input.");
for (const auto& elementVariant : *widthArray)
{
lambda(elementVariant);
}
}
}
}
// TODO: this is duplicated in the generated code, remove this duplication
float variantToFloat(const cppexpose::Variant & v)
{
return v.value<float>();
}
glm::vec2 variantToVec2(const cppexpose::Variant & v)
{
const auto arr = v.asArray();
const auto x = variantToFloat(arr->at(0));
const auto y = variantToFloat(arr->at(1));
return glm::vec2(x,y);
}
glm::vec3 variantToVec3(const cppexpose::Variant & v)
{
const auto arr = v.asArray();
const auto x = variantToFloat(arr->at(0));
const auto y = variantToFloat(arr->at(1));
const auto z = variantToFloat(arr->at(2));
return glm::vec3(x,y,z);
}
glm::vec4 variantToVec4(const cppexpose::Variant & v)
{
const auto arr = v.asArray();
const auto x = variantToFloat(arr->at(0));
const auto y = variantToFloat(arr->at(1));
const auto z = variantToFloat(arr->at(2));
const auto w = variantToFloat(arr->at(3));
return glm::vec4(x,y,z,w);
}
KernelJsonImporter::KernelJsonImporter(const std::string& inputFileName)
{
cppexpose::Variant root;
bool success = cppexpose::JSON::load(root, inputFileName);
assert_msg(success, "JSON could not be loaded.");
auto rootMap = root.asMap();
assert_msg(rootMap, "Input JSON is malformed.");
auto depthArray = rootMap->at("kernel").asArray();
auto sizeMap = rootMap->at("size").asMap();
int depth = sizeMap->at("depth").value<int>();
int height = sizeMap->at("height").value<int>();
int width = sizeMap->at("width").value<int>();
int numComponents = -1;
// assert that all cells have the same cell type
forEachCell(depthArray, [&numComponents](const cppexpose::Variant& elementVariant) {
if (elementVariant.isFloatingPoint())
{
assert_msg(numComponents == -1 || numComponents == 1,
"All cells must have the same cell type (float, vec2, vec3 or vec4).");
numComponents = 1;
}
else
{
assert_msg(elementVariant.isArray(), "Cell is not floating point or array.");
assert_msg(numComponents == -1 || elementVariant.asArray()->size() == numComponents,
"All cells must have the same cell type (float, vec2, vec3 or vec4).");
numComponents = elementVariant.asArray()->size();
}
});
int i = 0;
if (numComponents == 1)
{
glkernel::kernel1 kernel(width, height, depth);
forEachCell(depthArray, [&i, &kernel](const cppexpose::Variant& elementVariant) {
kernel[i] = variantToFloat(elementVariant);
i++;
});
m_kernelVariant = cppexpose::Variant::fromValue(kernel);
}
else if (numComponents == 2)
{
glkernel::kernel2 kernel(width, height, depth);
forEachCell(depthArray, [&i, &kernel](const cppexpose::Variant& elementVariant) {
kernel[i] = variantToVec2(elementVariant);
i++;
});
m_kernelVariant = cppexpose::Variant::fromValue(kernel);
}
else if (numComponents == 3)
{
glkernel::kernel3 kernel(width, height, depth);
forEachCell(depthArray, [&i, &kernel](const cppexpose::Variant& elementVariant) {
kernel[i] = variantToVec3(elementVariant);
i++;
});
m_kernelVariant = cppexpose::Variant::fromValue(kernel);
}
else if (numComponents == 4)
{
glkernel::kernel4 kernel(width, height, depth);
forEachCell(depthArray, [&i, &kernel](const cppexpose::Variant& elementVariant) {
kernel[i] = variantToVec4(elementVariant);
i++;
});
m_kernelVariant = cppexpose::Variant::fromValue(kernel);
}
else
{
cppassist::error() << "Invalid number of components.";
}
}
cppexpose::Variant KernelJsonImporter::getKernel()
{
return m_kernelVariant;
}
<|endoftext|> |
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
#include <stdio.h>
#include "UniquePtr.h"
#include "class_linker.h"
#include "dex_verifier.h"
#include "object.h"
#include "jni.h"
namespace art {
#define REG(method, reg_bitmap, reg) \
( ((reg) < (method)->NumRegisters()) && \
(( *((reg_bitmap) + (reg)/8) >> ((reg) % 8) ) & 0x01) )
#define CHECK_REGS(...) do { \
int t[] = {__VA_ARGS__}; \
int t_size = sizeof(t) / sizeof(*t); \
for (int i = 0; i < t_size; ++i) \
CHECK(REG(m, reg_bitmap, t[i])) << "Error: Reg " << i << " is not in RegisterMap"; \
} while(false)
static int gJava_StackWalk_refmap_calls = 0;
struct ReferenceMapVisitor : public Thread::StackVisitor {
ReferenceMapVisitor() {
}
void VisitFrame(const Frame& frame, uintptr_t pc) {
Method* m = frame.GetMethod();
CHECK(m != NULL);
LOG(INFO) << "At " << PrettyMethod(m, false);
if (m->IsCalleeSaveMethod() || m->IsNative()) {
LOG(WARNING) << "no PC for " << PrettyMethod(m);
CHECK_EQ(pc, 0u);
return;
}
verifier::PcToReferenceMap map(m);
const uint8_t* reg_bitmap = map.FindBitMap(m->ToDexPC(pc));
String* m_name = m->GetName();
// Given the method name and the number of times the method has been called,
// we know the Dex registers with live reference values. Assert that what we
// find is what is expected.
if (m_name->Equals("f") == 0) {
if (gJava_StackWalk_refmap_calls == 1) {
CHECK_EQ(1U, m->ToDexPC(pc));
CHECK_REGS(1);
} else {
CHECK_EQ(gJava_StackWalk_refmap_calls, 2);
CHECK_EQ(5U, m->ToDexPC(pc));
CHECK_REGS(1);
}
} else if (m_name->Equals("g") == 0) {
if (gJava_StackWalk_refmap_calls == 1) {
CHECK_EQ(0xcU, m->ToDexPC(pc));
CHECK_REGS(0, 2); // Note that v1 is not in the minimal root set
} else {
CHECK_EQ(gJava_StackWalk_refmap_calls, 2);
CHECK_EQ(0xcU, m->ToDexPC(pc));
CHECK_REGS(0, 2);
}
} else if (m_name->Equals("shlemiel") == 0) {
if (gJava_StackWalk_refmap_calls == 1) {
CHECK_EQ(0x380U, m->ToDexPC(pc));
CHECK_REGS(2, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 21, 25);
} else {
CHECK_EQ(gJava_StackWalk_refmap_calls, 2);
CHECK_EQ(0x380U, m->ToDexPC(pc));
CHECK_REGS(2, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 21, 25);
}
}
LOG(INFO) << reg_bitmap;
}
};
extern "C"
JNIEXPORT jint JNICALL Java_StackWalk_refmap(JNIEnv* env, jobject thisObj, jint count) {
CHECK_EQ(count, 0);
gJava_StackWalk_refmap_calls++;
// Visitor
ReferenceMapVisitor mapper;
Thread::Current()->WalkStack(&mapper);
return count + 1;
}
extern "C"
JNIEXPORT jint JNICALL Java_StackWalk2_refmap2(JNIEnv* env, jobject thisObj, jint count) {
gJava_StackWalk_refmap_calls++;
// Visitor
ReferenceMapVisitor mapper;
Thread::Current()->WalkStack(&mapper);
return count + 1;
}
}
<commit_msg>Fix the StackWalk unit test. SegFault was caused by wrong comparisons.<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
#include <stdio.h>
#include "UniquePtr.h"
#include "class_linker.h"
#include "dex_verifier.h"
#include "object.h"
#include "jni.h"
namespace art {
#define REG(method, reg_bitmap, reg) \
( ((reg) < (method)->NumRegisters()) && \
(( *((reg_bitmap) + (reg)/8) >> ((reg) % 8) ) & 0x01) )
#define CHECK_REGS(...) do { \
int t[] = {__VA_ARGS__}; \
int t_size = sizeof(t) / sizeof(*t); \
for (int i = 0; i < t_size; ++i) \
CHECK(REG(m, reg_bitmap, t[i])) << "Error: Reg " << i << " is not in RegisterMap"; \
} while(false)
static int gJava_StackWalk_refmap_calls = 0;
struct ReferenceMapVisitor : public Thread::StackVisitor {
ReferenceMapVisitor() {
}
void VisitFrame(const Frame& frame, uintptr_t pc) {
Method* m = frame.GetMethod();
CHECK(m != NULL);
LOG(INFO) << "At " << PrettyMethod(m, false);
if (m->IsCalleeSaveMethod() || m->IsNative()) {
LOG(WARNING) << "no PC for " << PrettyMethod(m);
CHECK_EQ(pc, 0u);
return;
}
verifier::PcToReferenceMap map(m);
const uint8_t* reg_bitmap = map.FindBitMap(m->ToDexPC(pc));
String* m_name = m->GetName();
// Given the method name and the number of times the method has been called,
// we know the Dex registers with live reference values. Assert that what we
// find is what is expected.
if (m_name->Equals("f")) {
if (gJava_StackWalk_refmap_calls == 1) {
CHECK_EQ(1U, m->ToDexPC(pc));
CHECK_REGS(1);
} else {
CHECK_EQ(gJava_StackWalk_refmap_calls, 2);
CHECK_EQ(5U, m->ToDexPC(pc));
CHECK_REGS(1);
}
} else if (m_name->Equals("g")) {
if (gJava_StackWalk_refmap_calls == 1) {
CHECK_EQ(0xcU, m->ToDexPC(pc));
CHECK_REGS(0, 2); // Note that v1 is not in the minimal root set
} else {
CHECK_EQ(gJava_StackWalk_refmap_calls, 2);
CHECK_EQ(0xcU, m->ToDexPC(pc));
CHECK_REGS(0, 2);
}
} else if (m_name->Equals("shlemiel")) {
if (gJava_StackWalk_refmap_calls == 1) {
CHECK_EQ(0x380U, m->ToDexPC(pc));
CHECK_REGS(2, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 21, 25);
} else {
CHECK_EQ(gJava_StackWalk_refmap_calls, 2);
CHECK_EQ(0x380U, m->ToDexPC(pc));
CHECK_REGS(2, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 21, 25);
}
}
LOG(INFO) << reg_bitmap;
}
};
extern "C"
JNIEXPORT jint JNICALL Java_StackWalk_refmap(JNIEnv* env, jobject thisObj, jint count) {
CHECK_EQ(count, 0);
gJava_StackWalk_refmap_calls++;
// Visitor
ReferenceMapVisitor mapper;
Thread::Current()->WalkStack(&mapper);
return count + 1;
}
extern "C"
JNIEXPORT jint JNICALL Java_StackWalk2_refmap2(JNIEnv* env, jobject thisObj, jint count) {
gJava_StackWalk_refmap_calls++;
// Visitor
ReferenceMapVisitor mapper;
Thread::Current()->WalkStack(&mapper);
return count + 1;
}
}
<|endoftext|> |
<commit_before>// This file is part of hdf5_handler: an HDF5 file handler for the OPeNDAP
// data server.
// Copyright (c) 2011-2016 The HDF Group, Inc. and OPeNDAP, Inc.
//
// This 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 software 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// You can contact The HDF Group, Inc. at 1800 South Oak Street,
// Suite 203, Champaign, IL 61820
////////////////////////////////////////////////////////////////////////////////
/// \file h5cfdaputil.cc
/// \brief Helper functions for generating DAS attributes and a function to check BES Key.
///
///
/// \author Muqun Yang <myang6@hdfgroup.org>
///
/// Copyright (C) 2011-2016 The HDF Group
///
/// All rights reserved.
////////////////////////////////////////////////////////////////////////////////
#include "h5cfdaputil.h"
#include <math.h>
using namespace std;
using namespace libdap;
string HDF5CFDAPUtil::escattr(string s)
{
const string printable = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()_-+={[}]|\\:;<,>.?/'\"\n\t\r";
const string ESC = "\\";
const string DOUBLE_ESC = ESC + ESC;
const string QUOTE = "\"";
const string ESCQUOTE = ESC + QUOTE;
// escape \ with a second backslash
size_t ind = 0;
while ((ind = s.find(ESC, ind)) != string::npos) {
s.replace(ind, 1, DOUBLE_ESC);
ind += DOUBLE_ESC.length();
}
// escape non-printing characters with octal escape
ind = 0;
while ((ind = s.find_first_not_of(printable, ind)) != string::npos)
s.replace(ind, 1, ESC + octstring(s[ind]));
// escape " with backslash
ind = 0;
while ((ind = s.find(QUOTE, ind)) != string::npos) {
s.replace(ind, 1, ESCQUOTE);
ind += ESCQUOTE.length();
}
return s;
}
// present the string in octal base.
string
HDF5CFDAPUtil::octstring(unsigned char val)
{
ostringstream buf;
buf << oct << setw(3) << setfill('0')
<< static_cast<unsigned int>(val);
return buf.str();
}
void HDF5CFDAPUtil::replace_double_quote(string & str) {
const string offend_char = "\"";
const string replace_str = ""e";
size_t found_quote = 0;
size_t start_pos = 0;
while (found_quote != string::npos) {
found_quote = str.find(offend_char,start_pos);
if (found_quote!= string::npos){
str.replace(found_quote,offend_char.size(),replace_str);
start_pos = found_quote+1;
}
}
}
string HDF5CFDAPUtil::print_type(H5DataType type) {
// The list is based on libdap/AttrTable.h.
// We added DAP4 INT64 and UINT64 support.
string DAPUNSUPPORTED ="Unsupported";
string DAPBYTE ="Byte";
string DAPINT16 ="Int16";
string DAPUINT16 ="Uint16";
string DAPINT32 ="Int32";
string DAPUINT32 ="Uint32";
string DAPFLOAT32 ="Float32";
string DAPFLOAT64 ="Float64";
string DAP4INT64 ="Int64";
string DAP4UINT64 ="UInt64";
string DAPSTRING = "String";
switch (type) {
case H5UCHAR:
return DAPBYTE;
case H5CHAR:
return DAPINT16;
case H5INT16:
return DAPINT16;
case H5UINT16:
return DAPUINT16;
case H5INT32:
return DAPINT32;
case H5UINT32:
return DAPUINT32;
case H5FLOAT32:
return DAPFLOAT32;
case H5FLOAT64:
return DAPFLOAT64;
case H5FSTRING:
case H5VSTRING:
return DAPSTRING;
case H5INT64:
return DAP4INT64;
case H5UINT64:
return DAP4UINT64;
case H5REFERENCE:
case H5COMPOUND:
case H5ARRAY:
return DAPUNSUPPORTED;
default:
return DAPUNSUPPORTED;
}
}
H5DataType
HDF5CFDAPUtil::get_mem_dtype(H5DataType dtype,size_t mem_dtype_size ) {
// Currently in addition to "char" to "int16", all other memory datatype will be the same as the datatype.
// So we have a short cut for this function
return ((H5INT16 == dtype) && (1 == mem_dtype_size))?H5CHAR:dtype;
}
string
HDF5CFDAPUtil:: print_attr(H5DataType type, int loc, void *vals)
{
ostringstream rep;
union {
unsigned char* ucp;
char *cp;
short *sp;
unsigned short *usp;
int *ip;
unsigned int *uip;
long long *llp;
unsigned long long *ullp;
float *fp;
double *dp;
} gp;
switch (type) {
case H5UCHAR:
{
unsigned char uc;
gp.ucp = (unsigned char *) vals;
uc = *(gp.ucp+loc);
rep << (int)uc;
return rep.str();
}
case H5CHAR:
{
gp.cp = (char *) vals;
char c;
c = *(gp.cp+loc);
// Since the character may be a special character and DAP may not be able to represent so supposedly we should escape the character
// by calling the escattr function. However, HDF5 native char maps to DAP Int16. So the mapping assumes that users will never
// use HDF5 native char or HDF5 unsigned native char to represent characters. Instead HDF5 string should be used to represent characters.
// So don't do any escaping of H5CHAR for now. KY 2016-10-14
rep <<(int)c;
return rep.str();
}
case H5INT16:
{
gp.sp = (short *) vals;
rep<< *(gp.sp+loc);
return rep.str();
}
case H5UINT16:
{
gp.usp = (unsigned short *) vals;
rep << *(gp.usp+loc);
return rep.str();
}
case H5INT32:
{
gp.ip = (int *) vals;
rep << *(gp.ip+loc);
return rep.str();
}
case H5UINT32:
{
gp.uip = (unsigned int *) vals;
rep << *(gp.uip+loc);
return rep.str();
}
case H5INT64: // For DAP4 CF support only
{
gp.llp = (long long *) vals;
rep << *(gp.llp+loc);
return rep.str();
}
case H5UINT64: // For DAP4 CF support only
{
gp.ullp = (unsigned long long *) vals;
rep << *(gp.ullp+loc);
return rep.str();
}
case H5FLOAT32:
{
float attr_val = *(float*)vals;
bool is_a_fin = isfinite(attr_val);
gp.fp = (float *) vals;
rep << showpoint;
rep << setprecision(10);
rep << *(gp.fp+loc);
string tmp_rep_str = rep.str();
if (tmp_rep_str.find('.') == string::npos
&& tmp_rep_str.find('e') == string::npos
&& tmp_rep_str.find('E') == string::npos
&& (true == is_a_fin)){
rep<<".";
}
return rep.str();
}
case H5FLOAT64:
{
double attr_val = *(double*)vals;
bool is_a_fin = isfinite(attr_val);
gp.dp = (double *) vals;
rep << std::showpoint;
rep << std::setprecision(17);
rep << *(gp.dp+loc);
string tmp_rep_str = rep.str();
if (tmp_rep_str.find('.') == string::npos
&& tmp_rep_str.find('e') == string::npos
&& tmp_rep_str.find('E') == string::npos
&& (true == is_a_fin)) {
rep << ".";
}
return rep.str();
}
default:
return string("UNKNOWN");
}
}
// This helper function is used for 64-bit integer DAP4 support.
// We need to support the attributes of all types for 64-bit integer variables.
D4AttributeType HDF5CFDAPUtil::daptype_strrep_to_dap4_attrtype(std::string s){
if (s == "Byte")
return attr_byte_c;
else if (s == "Int8")
return attr_int8_c;
else if (s == "UInt8") // This may never be used.
return attr_uint8_c;
else if (s == "Int16")
return attr_int16_c;
else if (s == "UInt16")
return attr_uint16_c;
else if (s == "Int32")
return attr_int32_c;
else if (s == "UInt32")
return attr_uint32_c;
else if (s == "Int64")
return attr_int64_c;
else if (s == "UInt64")
return attr_uint64_c;
else if (s == "Float32")
return attr_float32_c;
else if (s == "Float64")
return attr_float64_c;
else if (s == "String")
return attr_str_c;
else if (s == "Url")
return attr_url_c;
else
return attr_null_c;
}
<commit_msg>Minor changes to escattr - no more escaping \ and ".<commit_after>// This file is part of hdf5_handler: an HDF5 file handler for the OPeNDAP
// data server.
// Copyright (c) 2011-2016 The HDF Group, Inc. and OPeNDAP, Inc.
//
// This 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 software 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// You can contact The HDF Group, Inc. at 1800 South Oak Street,
// Suite 203, Champaign, IL 61820
////////////////////////////////////////////////////////////////////////////////
/// \file h5cfdaputil.cc
/// \brief Helper functions for generating DAS attributes and a function to check BES Key.
///
///
/// \author Muqun Yang <myang6@hdfgroup.org>
///
/// Copyright (C) 2011-2016 The HDF Group
///
/// All rights reserved.
////////////////////////////////////////////////////////////////////////////////
#include "h5cfdaputil.h"
#include <math.h>
using namespace std;
using namespace libdap;
// Part of a large fix for attributes. Escaping the values of the attributes
// may have been a bad idea. It breaks using JSON, for example. If this is a
// bad idea - to turn of escaping - then we'll have to figure out how to store
// 'serialized JSON' in attributes because it's being used in netcdf/hdf files.
// If we stick with this, there's clearly a more performant solution - eliminate
// the calls to this code.
// jhrg 6/25/21
#define ESCAPE_STRING_ATTRIBUTES 0
string HDF5CFDAPUtil::escattr(string s)
{
const string printable = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()_-+={[}]|\\:;<,>.?/'\"\n\t\r";
const string ESC = "\\";
#if ESCAPE_STRING_ATTRIBUTES
const string DOUBLE_ESC = ESC + ESC;
const string QUOTE = "\"";
const string ESCQUOTE = ESC + QUOTE;
// escape \ with a second backslash
size_t ind = 0;
while ((ind = s.find(ESC, ind)) != string::npos) {
s.replace(ind, 1, DOUBLE_ESC);
ind += DOUBLE_ESC.length();
}
// escape " with backslash
ind = 0;
while ((ind = s.find(QUOTE, ind)) != string::npos) {
s.replace(ind, 1, ESCQUOTE);
ind += ESCQUOTE.length();
}
#endif
// escape non-printing characters with octal escape
size_t ind = 0;
while ((ind = s.find_first_not_of(printable, ind)) != string::npos)
s.replace(ind, 1, ESC + octstring(s[ind]));
return s;
}
// present the string in octal base.
string
HDF5CFDAPUtil::octstring(unsigned char val)
{
ostringstream buf;
buf << oct << setw(3) << setfill('0')
<< static_cast<unsigned int>(val);
return buf.str();
}
void HDF5CFDAPUtil::replace_double_quote(string & str) {
const string offend_char = "\"";
const string replace_str = ""e";
size_t found_quote = 0;
size_t start_pos = 0;
while (found_quote != string::npos) {
found_quote = str.find(offend_char,start_pos);
if (found_quote!= string::npos){
str.replace(found_quote,offend_char.size(),replace_str);
start_pos = found_quote+1;
}
}
}
string HDF5CFDAPUtil::print_type(H5DataType type) {
// The list is based on libdap/AttrTable.h.
// We added DAP4 INT64 and UINT64 support.
string DAPUNSUPPORTED ="Unsupported";
string DAPBYTE ="Byte";
string DAPINT16 ="Int16";
string DAPUINT16 ="Uint16";
string DAPINT32 ="Int32";
string DAPUINT32 ="Uint32";
string DAPFLOAT32 ="Float32";
string DAPFLOAT64 ="Float64";
string DAP4INT64 ="Int64";
string DAP4UINT64 ="UInt64";
string DAPSTRING = "String";
switch (type) {
case H5UCHAR:
return DAPBYTE;
case H5CHAR:
return DAPINT16;
case H5INT16:
return DAPINT16;
case H5UINT16:
return DAPUINT16;
case H5INT32:
return DAPINT32;
case H5UINT32:
return DAPUINT32;
case H5FLOAT32:
return DAPFLOAT32;
case H5FLOAT64:
return DAPFLOAT64;
case H5FSTRING:
case H5VSTRING:
return DAPSTRING;
case H5INT64:
return DAP4INT64;
case H5UINT64:
return DAP4UINT64;
case H5REFERENCE:
case H5COMPOUND:
case H5ARRAY:
return DAPUNSUPPORTED;
default:
return DAPUNSUPPORTED;
}
}
H5DataType
HDF5CFDAPUtil::get_mem_dtype(H5DataType dtype,size_t mem_dtype_size ) {
// Currently in addition to "char" to "int16", all other memory datatype will be the same as the datatype.
// So we have a short cut for this function
return ((H5INT16 == dtype) && (1 == mem_dtype_size))?H5CHAR:dtype;
}
string
HDF5CFDAPUtil:: print_attr(H5DataType type, int loc, void *vals)
{
ostringstream rep;
union {
unsigned char* ucp;
char *cp;
short *sp;
unsigned short *usp;
int *ip;
unsigned int *uip;
long long *llp;
unsigned long long *ullp;
float *fp;
double *dp;
} gp;
switch (type) {
case H5UCHAR:
{
unsigned char uc;
gp.ucp = (unsigned char *) vals;
uc = *(gp.ucp+loc);
rep << (int)uc;
return rep.str();
}
case H5CHAR:
{
gp.cp = (char *) vals;
char c;
c = *(gp.cp+loc);
// Since the character may be a special character and DAP may not be able to represent so supposedly we should escape the character
// by calling the escattr function. However, HDF5 native char maps to DAP Int16. So the mapping assumes that users will never
// use HDF5 native char or HDF5 unsigned native char to represent characters. Instead HDF5 string should be used to represent characters.
// So don't do any escaping of H5CHAR for now. KY 2016-10-14
rep <<(int)c;
return rep.str();
}
case H5INT16:
{
gp.sp = (short *) vals;
rep<< *(gp.sp+loc);
return rep.str();
}
case H5UINT16:
{
gp.usp = (unsigned short *) vals;
rep << *(gp.usp+loc);
return rep.str();
}
case H5INT32:
{
gp.ip = (int *) vals;
rep << *(gp.ip+loc);
return rep.str();
}
case H5UINT32:
{
gp.uip = (unsigned int *) vals;
rep << *(gp.uip+loc);
return rep.str();
}
case H5INT64: // For DAP4 CF support only
{
gp.llp = (long long *) vals;
rep << *(gp.llp+loc);
return rep.str();
}
case H5UINT64: // For DAP4 CF support only
{
gp.ullp = (unsigned long long *) vals;
rep << *(gp.ullp+loc);
return rep.str();
}
case H5FLOAT32:
{
float attr_val = *(float*)vals;
bool is_a_fin = isfinite(attr_val);
gp.fp = (float *) vals;
rep << showpoint;
rep << setprecision(10);
rep << *(gp.fp+loc);
string tmp_rep_str = rep.str();
if (tmp_rep_str.find('.') == string::npos
&& tmp_rep_str.find('e') == string::npos
&& tmp_rep_str.find('E') == string::npos
&& (true == is_a_fin)){
rep<<".";
}
return rep.str();
}
case H5FLOAT64:
{
double attr_val = *(double*)vals;
bool is_a_fin = isfinite(attr_val);
gp.dp = (double *) vals;
rep << std::showpoint;
rep << std::setprecision(17);
rep << *(gp.dp+loc);
string tmp_rep_str = rep.str();
if (tmp_rep_str.find('.') == string::npos
&& tmp_rep_str.find('e') == string::npos
&& tmp_rep_str.find('E') == string::npos
&& (true == is_a_fin)) {
rep << ".";
}
return rep.str();
}
default:
return string("UNKNOWN");
}
}
// This helper function is used for 64-bit integer DAP4 support.
// We need to support the attributes of all types for 64-bit integer variables.
D4AttributeType HDF5CFDAPUtil::daptype_strrep_to_dap4_attrtype(std::string s){
if (s == "Byte")
return attr_byte_c;
else if (s == "Int8")
return attr_int8_c;
else if (s == "UInt8") // This may never be used.
return attr_uint8_c;
else if (s == "Int16")
return attr_int16_c;
else if (s == "UInt16")
return attr_uint16_c;
else if (s == "Int32")
return attr_int32_c;
else if (s == "UInt32")
return attr_uint32_c;
else if (s == "Int64")
return attr_int64_c;
else if (s == "UInt64")
return attr_uint64_c;
else if (s == "Float32")
return attr_float32_c;
else if (s == "Float64")
return attr_float64_c;
else if (s == "String")
return attr_str_c;
else if (s == "Url")
return attr_url_c;
else
return attr_null_c;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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 "net/third_party/quiche/src/quic/test_tools/simulator/quic_endpoint.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
#include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h"
#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
#include "net/third_party/quiche/src/quic/test_tools/simulator/simulator.h"
#include "net/third_party/quiche/src/quic/test_tools/simulator/switch.h"
using ::testing::_;
using ::testing::NiceMock;
using ::testing::Return;
namespace quic {
namespace simulator {
const QuicBandwidth kDefaultBandwidth =
QuicBandwidth::FromKBitsPerSecond(10 * 1000);
const QuicTime::Delta kDefaultPropagationDelay =
QuicTime::Delta::FromMilliseconds(20);
const QuicByteCount kDefaultBdp = kDefaultBandwidth * kDefaultPropagationDelay;
// A simple test harness where all hosts are connected to a switch with
// identical links.
class QuicEndpointTest : public QuicTest {
public:
QuicEndpointTest()
: simulator_(), switch_(&simulator_, "Switch", 8, kDefaultBdp * 2) {}
protected:
Simulator simulator_;
Switch switch_;
std::unique_ptr<SymmetricLink> Link(Endpoint* a, Endpoint* b) {
return QuicMakeUnique<SymmetricLink>(a, b, kDefaultBandwidth,
kDefaultPropagationDelay);
}
std::unique_ptr<SymmetricLink> CustomLink(Endpoint* a,
Endpoint* b,
uint64_t extra_rtt_ms) {
return QuicMakeUnique<SymmetricLink>(
a, b, kDefaultBandwidth,
kDefaultPropagationDelay +
QuicTime::Delta::FromMilliseconds(extra_rtt_ms));
}
};
// Test transmission from one host to another.
TEST_F(QuicEndpointTest, OneWayTransmission) {
QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B",
Perspective::IS_CLIENT, test::TestConnectionId(42));
QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A",
Perspective::IS_SERVER, test::TestConnectionId(42));
auto link_a = Link(&endpoint_a, switch_.port(1));
auto link_b = Link(&endpoint_b, switch_.port(2));
// First transmit a small, packet-size chunk of data.
endpoint_a.AddBytesToTransfer(600);
QuicTime end_time =
simulator_.GetClock()->Now() + QuicTime::Delta::FromMilliseconds(1000);
simulator_.RunUntil(
[this, end_time]() { return simulator_.GetClock()->Now() >= end_time; });
EXPECT_EQ(600u, endpoint_a.bytes_transferred());
ASSERT_EQ(600u, endpoint_b.bytes_received());
EXPECT_FALSE(endpoint_a.wrong_data_received());
EXPECT_FALSE(endpoint_b.wrong_data_received());
// After a small chunk succeeds, try to transfer 2 MiB.
endpoint_a.AddBytesToTransfer(2 * 1024 * 1024);
end_time = simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(5);
simulator_.RunUntil(
[this, end_time]() { return simulator_.GetClock()->Now() >= end_time; });
const QuicByteCount total_bytes_transferred = 600 + 2 * 1024 * 1024;
EXPECT_EQ(total_bytes_transferred, endpoint_a.bytes_transferred());
EXPECT_EQ(total_bytes_transferred, endpoint_b.bytes_received());
EXPECT_EQ(0u, endpoint_a.write_blocked_count());
EXPECT_FALSE(endpoint_a.wrong_data_received());
EXPECT_FALSE(endpoint_b.wrong_data_received());
}
// Test the situation in which the writer becomes write-blocked.
TEST_F(QuicEndpointTest, WriteBlocked) {
QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B",
Perspective::IS_CLIENT, test::TestConnectionId(42));
QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A",
Perspective::IS_SERVER, test::TestConnectionId(42));
auto link_a = Link(&endpoint_a, switch_.port(1));
auto link_b = Link(&endpoint_b, switch_.port(2));
// Will be owned by the sent packet manager.
auto* sender = new NiceMock<test::MockSendAlgorithm>();
EXPECT_CALL(*sender, CanSend(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*sender, PacingRate(_))
.WillRepeatedly(Return(10 * kDefaultBandwidth));
EXPECT_CALL(*sender, BandwidthEstimate())
.WillRepeatedly(Return(10 * kDefaultBandwidth));
EXPECT_CALL(*sender, GetCongestionWindow())
.WillRepeatedly(
Return(kMaxOutgoingPacketSize * kDefaultMaxCongestionWindowPackets));
test::QuicConnectionPeer::SetSendAlgorithm(endpoint_a.connection(), sender);
// First transmit a small, packet-size chunk of data.
QuicByteCount bytes_to_transfer = 3 * 1024 * 1024;
endpoint_a.AddBytesToTransfer(bytes_to_transfer);
QuicTime end_time =
simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(30);
simulator_.RunUntil([this, &endpoint_b, bytes_to_transfer, end_time]() {
return endpoint_b.bytes_received() == bytes_to_transfer ||
simulator_.GetClock()->Now() >= end_time;
});
EXPECT_EQ(bytes_to_transfer, endpoint_a.bytes_transferred());
EXPECT_EQ(bytes_to_transfer, endpoint_b.bytes_received());
EXPECT_GT(endpoint_a.write_blocked_count(), 0u);
EXPECT_FALSE(endpoint_a.wrong_data_received());
EXPECT_FALSE(endpoint_b.wrong_data_received());
}
// Test transmission of 1 MiB of data between two hosts simultaneously in both
// directions.
TEST_F(QuicEndpointTest, TwoWayTransmission) {
QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B",
Perspective::IS_CLIENT, test::TestConnectionId(42));
QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A",
Perspective::IS_SERVER, test::TestConnectionId(42));
auto link_a = Link(&endpoint_a, switch_.port(1));
auto link_b = Link(&endpoint_b, switch_.port(2));
endpoint_a.RecordTrace();
endpoint_b.RecordTrace();
endpoint_a.AddBytesToTransfer(1024 * 1024);
endpoint_b.AddBytesToTransfer(1024 * 1024);
QuicTime end_time =
simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(5);
simulator_.RunUntil(
[this, end_time]() { return simulator_.GetClock()->Now() >= end_time; });
EXPECT_EQ(1024u * 1024u, endpoint_a.bytes_transferred());
EXPECT_EQ(1024u * 1024u, endpoint_b.bytes_transferred());
EXPECT_EQ(1024u * 1024u, endpoint_a.bytes_received());
EXPECT_EQ(1024u * 1024u, endpoint_b.bytes_received());
EXPECT_FALSE(endpoint_a.wrong_data_received());
EXPECT_FALSE(endpoint_b.wrong_data_received());
}
// Simulate three hosts trying to send data to a fourth one simultaneously.
TEST_F(QuicEndpointTest, Competition) {
// TODO(63765788): Turn back on this flag when the issue if fixed.
SetQuicReloadableFlag(quic_bbr_one_mss_conservation, false);
auto endpoint_a = QuicMakeUnique<QuicEndpoint>(
&simulator_, "Endpoint A", "Endpoint D (A)", Perspective::IS_CLIENT,
test::TestConnectionId(42));
auto endpoint_b = QuicMakeUnique<QuicEndpoint>(
&simulator_, "Endpoint B", "Endpoint D (B)", Perspective::IS_CLIENT,
test::TestConnectionId(43));
auto endpoint_c = QuicMakeUnique<QuicEndpoint>(
&simulator_, "Endpoint C", "Endpoint D (C)", Perspective::IS_CLIENT,
test::TestConnectionId(44));
auto endpoint_d_a = QuicMakeUnique<QuicEndpoint>(
&simulator_, "Endpoint D (A)", "Endpoint A", Perspective::IS_SERVER,
test::TestConnectionId(42));
auto endpoint_d_b = QuicMakeUnique<QuicEndpoint>(
&simulator_, "Endpoint D (B)", "Endpoint B", Perspective::IS_SERVER,
test::TestConnectionId(43));
auto endpoint_d_c = QuicMakeUnique<QuicEndpoint>(
&simulator_, "Endpoint D (C)", "Endpoint C", Perspective::IS_SERVER,
test::TestConnectionId(44));
QuicEndpointMultiplexer endpoint_d(
"Endpoint D",
{endpoint_d_a.get(), endpoint_d_b.get(), endpoint_d_c.get()});
// Create links with slightly different RTTs in order to avoid pathological
// side-effects of packets entering the queue at the exactly same time.
auto link_a = CustomLink(endpoint_a.get(), switch_.port(1), 0);
auto link_b = CustomLink(endpoint_b.get(), switch_.port(2), 1);
auto link_c = CustomLink(endpoint_c.get(), switch_.port(3), 2);
auto link_d = Link(&endpoint_d, switch_.port(4));
endpoint_a->AddBytesToTransfer(2 * 1024 * 1024);
endpoint_b->AddBytesToTransfer(2 * 1024 * 1024);
endpoint_c->AddBytesToTransfer(2 * 1024 * 1024);
QuicTime end_time =
simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(10);
simulator_.RunUntil(
[this, end_time]() { return simulator_.GetClock()->Now() >= end_time; });
for (QuicEndpoint* endpoint :
{endpoint_a.get(), endpoint_b.get(), endpoint_c.get()}) {
EXPECT_EQ(2u * 1024u * 1024u, endpoint->bytes_transferred());
EXPECT_GE(endpoint->connection()->GetStats().packets_lost, 0u);
}
for (QuicEndpoint* endpoint :
{endpoint_d_a.get(), endpoint_d_b.get(), endpoint_d_c.get()}) {
EXPECT_EQ(2u * 1024u * 1024u, endpoint->bytes_received());
EXPECT_FALSE(endpoint->wrong_data_received());
}
}
} // namespace simulator
} // namespace quic
<commit_msg>gfe-relnote: (n/a) Deflake quic_endpoint_test. Test only.<commit_after>// Copyright (c) 2012 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 "net/third_party/quiche/src/quic/test_tools/simulator/quic_endpoint.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
#include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h"
#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
#include "net/third_party/quiche/src/quic/test_tools/simulator/simulator.h"
#include "net/third_party/quiche/src/quic/test_tools/simulator/switch.h"
using ::testing::_;
using ::testing::NiceMock;
using ::testing::Return;
namespace quic {
namespace simulator {
const QuicBandwidth kDefaultBandwidth =
QuicBandwidth::FromKBitsPerSecond(10 * 1000);
const QuicTime::Delta kDefaultPropagationDelay =
QuicTime::Delta::FromMilliseconds(20);
const QuicByteCount kDefaultBdp = kDefaultBandwidth * kDefaultPropagationDelay;
// A simple test harness where all hosts are connected to a switch with
// identical links.
class QuicEndpointTest : public QuicTest {
public:
QuicEndpointTest()
: simulator_(), switch_(&simulator_, "Switch", 8, kDefaultBdp * 2) {}
protected:
Simulator simulator_;
Switch switch_;
std::unique_ptr<SymmetricLink> Link(Endpoint* a, Endpoint* b) {
return QuicMakeUnique<SymmetricLink>(a, b, kDefaultBandwidth,
kDefaultPropagationDelay);
}
std::unique_ptr<SymmetricLink> CustomLink(Endpoint* a,
Endpoint* b,
uint64_t extra_rtt_ms) {
return QuicMakeUnique<SymmetricLink>(
a, b, kDefaultBandwidth,
kDefaultPropagationDelay +
QuicTime::Delta::FromMilliseconds(extra_rtt_ms));
}
};
// Test transmission from one host to another.
TEST_F(QuicEndpointTest, OneWayTransmission) {
QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B",
Perspective::IS_CLIENT, test::TestConnectionId(42));
QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A",
Perspective::IS_SERVER, test::TestConnectionId(42));
auto link_a = Link(&endpoint_a, switch_.port(1));
auto link_b = Link(&endpoint_b, switch_.port(2));
// First transmit a small, packet-size chunk of data.
endpoint_a.AddBytesToTransfer(600);
QuicTime end_time =
simulator_.GetClock()->Now() + QuicTime::Delta::FromMilliseconds(1000);
simulator_.RunUntil(
[this, end_time]() { return simulator_.GetClock()->Now() >= end_time; });
EXPECT_EQ(600u, endpoint_a.bytes_transferred());
ASSERT_EQ(600u, endpoint_b.bytes_received());
EXPECT_FALSE(endpoint_a.wrong_data_received());
EXPECT_FALSE(endpoint_b.wrong_data_received());
// After a small chunk succeeds, try to transfer 2 MiB.
endpoint_a.AddBytesToTransfer(2 * 1024 * 1024);
end_time = simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(5);
simulator_.RunUntil(
[this, end_time]() { return simulator_.GetClock()->Now() >= end_time; });
const QuicByteCount total_bytes_transferred = 600 + 2 * 1024 * 1024;
EXPECT_EQ(total_bytes_transferred, endpoint_a.bytes_transferred());
EXPECT_EQ(total_bytes_transferred, endpoint_b.bytes_received());
EXPECT_EQ(0u, endpoint_a.write_blocked_count());
EXPECT_FALSE(endpoint_a.wrong_data_received());
EXPECT_FALSE(endpoint_b.wrong_data_received());
}
// Test the situation in which the writer becomes write-blocked.
TEST_F(QuicEndpointTest, WriteBlocked) {
QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B",
Perspective::IS_CLIENT, test::TestConnectionId(42));
QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A",
Perspective::IS_SERVER, test::TestConnectionId(42));
auto link_a = Link(&endpoint_a, switch_.port(1));
auto link_b = Link(&endpoint_b, switch_.port(2));
// Will be owned by the sent packet manager.
auto* sender = new NiceMock<test::MockSendAlgorithm>();
EXPECT_CALL(*sender, CanSend(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*sender, PacingRate(_))
.WillRepeatedly(Return(10 * kDefaultBandwidth));
EXPECT_CALL(*sender, BandwidthEstimate())
.WillRepeatedly(Return(10 * kDefaultBandwidth));
EXPECT_CALL(*sender, GetCongestionWindow())
.WillRepeatedly(
Return(kMaxOutgoingPacketSize * kDefaultMaxCongestionWindowPackets));
test::QuicConnectionPeer::SetSendAlgorithm(endpoint_a.connection(), sender);
// First transmit a small, packet-size chunk of data.
QuicByteCount bytes_to_transfer = 3 * 1024 * 1024;
endpoint_a.AddBytesToTransfer(bytes_to_transfer);
QuicTime end_time =
simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(30);
simulator_.RunUntil([this, &endpoint_b, bytes_to_transfer, end_time]() {
return endpoint_b.bytes_received() == bytes_to_transfer ||
simulator_.GetClock()->Now() >= end_time;
});
EXPECT_EQ(bytes_to_transfer, endpoint_a.bytes_transferred());
EXPECT_EQ(bytes_to_transfer, endpoint_b.bytes_received());
EXPECT_GT(endpoint_a.write_blocked_count(), 0u);
EXPECT_FALSE(endpoint_a.wrong_data_received());
EXPECT_FALSE(endpoint_b.wrong_data_received());
}
// Test transmission of 1 MiB of data between two hosts simultaneously in both
// directions.
TEST_F(QuicEndpointTest, TwoWayTransmission) {
QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B",
Perspective::IS_CLIENT, test::TestConnectionId(42));
QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A",
Perspective::IS_SERVER, test::TestConnectionId(42));
auto link_a = Link(&endpoint_a, switch_.port(1));
auto link_b = Link(&endpoint_b, switch_.port(2));
endpoint_a.RecordTrace();
endpoint_b.RecordTrace();
endpoint_a.AddBytesToTransfer(1024 * 1024);
endpoint_b.AddBytesToTransfer(1024 * 1024);
QuicTime end_time =
simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(5);
simulator_.RunUntil(
[this, end_time]() { return simulator_.GetClock()->Now() >= end_time; });
EXPECT_EQ(1024u * 1024u, endpoint_a.bytes_transferred());
EXPECT_EQ(1024u * 1024u, endpoint_b.bytes_transferred());
EXPECT_EQ(1024u * 1024u, endpoint_a.bytes_received());
EXPECT_EQ(1024u * 1024u, endpoint_b.bytes_received());
EXPECT_FALSE(endpoint_a.wrong_data_received());
EXPECT_FALSE(endpoint_b.wrong_data_received());
}
// Simulate three hosts trying to send data to a fourth one simultaneously.
TEST_F(QuicEndpointTest, Competition) {
// TODO(63765788): Turn back on this flag when the issue if fixed.
SetQuicReloadableFlag(quic_bbr_one_mss_conservation, false);
auto endpoint_a = QuicMakeUnique<QuicEndpoint>(
&simulator_, "Endpoint A", "Endpoint D (A)", Perspective::IS_CLIENT,
test::TestConnectionId(42));
auto endpoint_b = QuicMakeUnique<QuicEndpoint>(
&simulator_, "Endpoint B", "Endpoint D (B)", Perspective::IS_CLIENT,
test::TestConnectionId(43));
auto endpoint_c = QuicMakeUnique<QuicEndpoint>(
&simulator_, "Endpoint C", "Endpoint D (C)", Perspective::IS_CLIENT,
test::TestConnectionId(44));
auto endpoint_d_a = QuicMakeUnique<QuicEndpoint>(
&simulator_, "Endpoint D (A)", "Endpoint A", Perspective::IS_SERVER,
test::TestConnectionId(42));
auto endpoint_d_b = QuicMakeUnique<QuicEndpoint>(
&simulator_, "Endpoint D (B)", "Endpoint B", Perspective::IS_SERVER,
test::TestConnectionId(43));
auto endpoint_d_c = QuicMakeUnique<QuicEndpoint>(
&simulator_, "Endpoint D (C)", "Endpoint C", Perspective::IS_SERVER,
test::TestConnectionId(44));
QuicEndpointMultiplexer endpoint_d(
"Endpoint D",
{endpoint_d_a.get(), endpoint_d_b.get(), endpoint_d_c.get()});
// Create links with slightly different RTTs in order to avoid pathological
// side-effects of packets entering the queue at the exactly same time.
auto link_a = CustomLink(endpoint_a.get(), switch_.port(1), 0);
auto link_b = CustomLink(endpoint_b.get(), switch_.port(2), 1);
auto link_c = CustomLink(endpoint_c.get(), switch_.port(3), 2);
auto link_d = Link(&endpoint_d, switch_.port(4));
endpoint_a->AddBytesToTransfer(2 * 1024 * 1024);
endpoint_b->AddBytesToTransfer(2 * 1024 * 1024);
endpoint_c->AddBytesToTransfer(2 * 1024 * 1024);
QuicTime end_time =
simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(12);
simulator_.RunUntil(
[this, end_time]() { return simulator_.GetClock()->Now() >= end_time; });
for (QuicEndpoint* endpoint :
{endpoint_a.get(), endpoint_b.get(), endpoint_c.get()}) {
EXPECT_EQ(2u * 1024u * 1024u, endpoint->bytes_transferred());
EXPECT_GE(endpoint->connection()->GetStats().packets_lost, 0u);
}
for (QuicEndpoint* endpoint :
{endpoint_d_a.get(), endpoint_d_b.get(), endpoint_d_c.get()}) {
EXPECT_EQ(2u * 1024u * 1024u, endpoint->bytes_received());
EXPECT_FALSE(endpoint->wrong_data_received());
}
}
} // namespace simulator
} // namespace quic
<|endoftext|> |
<commit_before>#include <Halide.h>
#include <stdio.h>
using namespace Halide;
int main(int argc, char **argv) {
Func f, g, h, j;
Var x, y;
f(x, y) = x + y;
g(x, y) = cast<float>(f(x, y) + f(x+1, y));
h(x, y) = f(x, y) + g(x, y);
j(x, y) = h(x, y) * 2;
f.compute_root();
g.compute_root();
h.compute_root();
const char *result_file = "compile_to_lowered_stmt.stmt";
j.compile_to_lowered_stmt(result_file);
assert(access("compile_to_lowered_stmt.stmt", F_OK) == 0 && "Output file not created.");
printf("Success!\n");
return 0;
}
<commit_msg>Check for unistd in compile_to_lowered_stmt<commit_after>#include <Halide.h>
#include <stdio.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
using namespace Halide;
int main(int argc, char **argv) {
Func f, g, h, j;
Var x, y;
f(x, y) = x + y;
g(x, y) = cast<float>(f(x, y) + f(x+1, y));
h(x, y) = f(x, y) + g(x, y);
j(x, y) = h(x, y) * 2;
f.compute_root();
g.compute_root();
h.compute_root();
const char *result_file = "compile_to_lowered_stmt.stmt";
j.compile_to_lowered_stmt(result_file);
#ifndef _MSC_VER
assert(access("compile_to_lowered_stmt.stmt", F_OK) == 0 && "Output file not created.");
#endif
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before>/* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Robotiq, 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 Robotiq, 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.
*
* Copyright (c) 2014, Robotiq, Inc
*/
/**
* \file rq_sensor.cpp
* \date July 14, 2014
* \author Jonathan Savoie <jonathan.savoie@robotiq.com>
* \maintainer Nicolas Lauzier <nicolas@robotiq.com>
*/
#include <string.h>
#include <stdio.h>
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "robotiq_force_torque_sensor/rq_sensor_state.h"
#include "robotiq_force_torque_sensor/ft_sensor.h"
#include "robotiq_force_torque_sensor/sensor_accessor.h"
static void decode_message_and_do(INT_8 const * const buff, INT_8 * const ret);
static void wait_for_other_connection(void);
ros::Publisher sensor_pub_acc;
/**
* \brief Decode the message received and do the associated action
* \param buff message to decode
* \param ret buffer containing the return value from a GET command
*/
static void decode_message_and_do(INT_8 const * const buff, INT_8 * const ret)
{
INT_8 get_or_set[3];
INT_8 nom_var[4];
if(buff == NULL || strlen(buff) != 7)
{
return;
}
strncpy(get_or_set, &buff[0], 3);
strncpy(nom_var, &buff[4], strlen(buff) -3);
if(strstr(get_or_set, "GET"))
{
rq_state_get_command(nom_var, ret);
}
else if(strstr(get_or_set, "SET"))
{
if(strstr(nom_var, "ZRO"))
{
rq_state_do_zero_force_flag();
strcpy(ret,"Done");
}
}
}
bool receiverCallback(robotiq_force_torque_sensor::sensor_accessor::Request& req,
robotiq_force_torque_sensor::sensor_accessor::Response& res)
{
ROS_INFO("I heard: [%s]",req.command.c_str());
INT_8 buffer[512];
decode_message_and_do((char*)req.command.c_str(), buffer);
res.res = buffer;
ROS_INFO("I send: [%s]", res.res.c_str());
return true;
}
/**
* \fn static void wait_for_other_connection()
* \brief Each second, checks for a sensor that has been connected
*/
static void wait_for_other_connection(void)
{
INT_8 ret;
while(1)
{
usleep(1000000);//Attend 1 seconde.
ret = rq_sensor_state();
if(ret == 0)
{
break;
}
ros::spinOnce();
}
}
/**
* \fn void get_data(void)
* \brief Builds the message with the force/torque data
* \return ft_sensor updated with the latest data
*/
static robotiq_force_torque_sensor::ft_sensor get_data(void)
{
robotiq_force_torque_sensor::ft_sensor msgStream;
msgStream.Fx = rq_state_get_received_data(0);
msgStream.Fy = rq_state_get_received_data(1);
msgStream.Fz = rq_state_get_received_data(2);
msgStream.Mx = rq_state_get_received_data(3);
msgStream.My = rq_state_get_received_data(4);
msgStream.Mz = rq_state_get_received_data(5);
return msgStream;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "robotiq_force_torque_sensor");
INT_8 bufStream[512];
robotiq_force_torque_sensor::ft_sensor msgStream;
ros::NodeHandle n;
INT_8 ret;
//If we can't initialize, we return an error
ret = rq_sensor_state();
if(ret == -1)
{
wait_for_other_connection();
}
//Reads basic info on the sensor
ret = rq_sensor_state();
if(ret == -1)
{
wait_for_other_connection();
}
//Starts the stream
ret = rq_sensor_state();
if(ret == -1)
{
wait_for_other_connection();
}
ros::Publisher sensor_pub = n.advertise<robotiq_force_torque_sensor::ft_sensor>("robotiq_force_torque_sensor", 512);
ros::ServiceServer service = n.advertiseService("robotiq_force_torque_sensor_acc", receiverCallback);
//std_msgs::String msg;
while(1)
{
ret = rq_sensor_state();
if(ret == -1)
{
wait_for_other_connection();
}
if(rq_sensor_get_current_state() == RQ_STATE_RUN)
{
strcpy(bufStream,"");
msgStream = get_data();
if(rq_state_got_new_message())
{
sensor_pub.publish(msgStream);
}
}
ros::spinOnce();
}
return 0;
}
<commit_msg>added code to fix rq_sensor hang on ctrl-c<commit_after>/* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Robotiq, 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 Robotiq, 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.
*
* Copyright (c) 2014, Robotiq, Inc
*/
/**
* \file rq_sensor.cpp
* \date July 14, 2014
* \author Jonathan Savoie <jonathan.savoie@robotiq.com>
* \maintainer Nicolas Lauzier <nicolas@robotiq.com>
*/
#include <string.h>
#include <stdio.h>
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "robotiq_force_torque_sensor/rq_sensor_state.h"
#include "robotiq_force_torque_sensor/rq_sensor_com.h"
#include "robotiq_force_torque_sensor/ft_sensor.h"
#include "robotiq_force_torque_sensor/sensor_accessor.h"
static void decode_message_and_do(INT_8 const * const buff, INT_8 * const ret);
static void wait_for_other_connection(void);
ros::Publisher sensor_pub_acc;
/**
* \brief Decode the message received and do the associated action
* \param buff message to decode
* \param ret buffer containing the return value from a GET command
*/
static void decode_message_and_do(INT_8 const * const buff, INT_8 * const ret)
{
INT_8 get_or_set[3];
INT_8 nom_var[4];
if(buff == NULL || strlen(buff) != 7)
{
return;
}
strncpy(get_or_set, &buff[0], 3);
strncpy(nom_var, &buff[4], strlen(buff) -3);
if(strstr(get_or_set, "GET"))
{
rq_state_get_command(nom_var, ret);
}
else if(strstr(get_or_set, "SET"))
{
if(strstr(nom_var, "ZRO"))
{
rq_state_do_zero_force_flag();
strcpy(ret,"Done");
}
}
}
bool receiverCallback(robotiq_force_torque_sensor::sensor_accessor::Request& req,
robotiq_force_torque_sensor::sensor_accessor::Response& res)
{
ROS_INFO("I heard: [%s]",req.command.c_str());
INT_8 buffer[512];
decode_message_and_do((char*)req.command.c_str(), buffer);
res.res = buffer;
ROS_INFO("I send: [%s]", res.res.c_str());
return true;
}
/**
* \fn static void wait_for_other_connection()
* \brief Each second, checks for a sensor that has been connected
*/
static void wait_for_other_connection(void)
{
INT_8 ret;
while(1)
{
ROS_WARN("Waiting for Connection.");
usleep(1000000);//Attend 1 seconde.
ret = rq_sensor_state();
if(ret == 0)
{
break;
}
ros::spinOnce();
}
}
/**
* \fn void get_data(void)
* \brief Builds the message with the force/torque data
* \return ft_sensor updated with the latest data
*/
static robotiq_force_torque_sensor::ft_sensor get_data(void)
{
robotiq_force_torque_sensor::ft_sensor msgStream;
msgStream.Fx = rq_state_get_received_data(0);
msgStream.Fy = rq_state_get_received_data(1);
msgStream.Fz = rq_state_get_received_data(2);
msgStream.Mx = rq_state_get_received_data(3);
msgStream.My = rq_state_get_received_data(4);
msgStream.Mz = rq_state_get_received_data(5);
return msgStream;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "robotiq_force_torque_sensor");
INT_8 bufStream[512];
robotiq_force_torque_sensor::ft_sensor msgStream;
ros::NodeHandle n;
INT_8 ret;
//If we can't initialize, we return an error
ROS_WARN("Attempting to Initialize");
ret = rq_sensor_state();
if(ret == -1)
{
wait_for_other_connection();
}
//Reads basic info on the sensor
ROS_WARN("Reading Sensor State");
ret = rq_sensor_state();
if(ret == -1)
{
wait_for_other_connection();
}
//Starts the stream
ret = rq_sensor_state();
ROS_WARN("Starting Sensor Stream");
if(ret == -1)
{
wait_for_other_connection();
}
ros::Publisher sensor_pub = n.advertise<robotiq_force_torque_sensor::ft_sensor>("robotiq_force_torque_sensor", 512);
ros::ServiceServer service = n.advertiseService("robotiq_force_torque_sensor_acc", receiverCallback);
//std_msgs::String msg;
while(ros::ok())
{
ret = rq_sensor_state();
if(ret == -1)
{
ROS_WARN("Waiting for Connections");
wait_for_other_connection();
}
if(rq_sensor_get_current_state() == RQ_STATE_RUN)
{
strcpy(bufStream,"");
msgStream = get_data();
if(rq_state_got_new_message())
{
sensor_pub.publish(msgStream);
}
}
ros::spinOnce();
}
stop_connection();
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream.h>
#include <pwd.h>
#include "condor_common.h"
#include "_condor_fix_resource.h"
#include "condor_config.h"
#include "condor_q.h"
#include "proc_obj.h"
#include "condor_attributes.h"
#include "files.h"
extern "C" SetSyscalls(){}
extern "C" int float_to_rusage (float, struct rusage *);
void short_print (int, int, const char*, int, int, int, int, int, const char *);
static void short_header (void);
static void usage (char *);
static void displayJobShort (ClassAd *);
static void shorten (char *, int);
static int verbose = 0, summarize = 1;
static int malformed, unexpanded, running, idle;
extern "C" BUCKET* ConfigTab[];
extern int Termlog;
int main (int argc, char **argv)
{
CondorQ Q;
ClassAdList jobs;
ClassAd *job;
int i;
int cluster, proc;
char constraint[1024];
char *host = 0;
struct passwd* pwd;
char* config_location;
char* scheddAddr;
for (i = 1; i < argc; i++)
{
if (strcmp (argv[i], "-l") == 0)
{
verbose = 1;
summarize = 0;
}
else
if (strcmp (argv[i], "-D") == 0)
{
Termlog = 1;
set_debug_flags( argv[++i] );
}
else
if (strcmp (argv[i], "-h") == 0)
{
host = argv[++i];
}
else
if (strcmp (argv[i], "-C") == 0)
{
Q.add (argv[++i]);
summarize = 0;
}
else
if (sscanf (argv[i], "%d.%d", &cluster, &proc) == 2)
{
sprintf (constraint, "((%s == %d) && (%s == %d))",
ATTR_CLUSTER_ID, cluster,
ATTR_PROC_ID, proc);
Q.add (constraint);
summarize = 0;
}
else
if (sscanf (argv[i], "%d", &cluster) == 1)
{
sprintf (constraint, "(%s == %d)", ATTR_CLUSTER_ID, cluster);
Q.add (constraint);
summarize = 0;
}
else
{
usage (argv[0]);
exit (1);
}
}
/* Weiru */
if((pwd = getpwnam("condor")) == NULL)
{
printf( "condor not in passwd file" );
exit(1);
}
if(read_config(pwd->pw_dir, MASTER_CONFIG, NULL, ConfigTab, TABLESIZE,
EXPAND_LAZY) < 0)
{
config(argv[0], NULL);
}
else
{
config_location = param("CONFIG_FILE_LOCATION");
if(!config_location)
{
config_location = pwd->pw_dir;
}
if(config_from_server(config_location, argv[0], NULL) < 0)
{
config(argv[0], NULL);
}
}
// find ip port of schedd from collector
if(!host)
{
host = new char[256];
if(gethostname(host, 256) < 0)
{
printf("Can't find host\n");
exit(1);
}
}
if((scheddAddr = get_schedd_addr(host)) == NULL)
{
printf("Can't find schedd address on %s\n", host);
exit(1);
}
// fetch queue from schedd
if (Q.fetchQueueFromHost (jobs, scheddAddr) != Q_OK)
{
printf ("Error connecting to job queue\n");
exit (1);
}
// initialize counters
malformed = 0; idle = 0; running = 0; unexpanded = 0;
if (verbose)
{
jobs.fPrintAttrListList (stdout);
}
else
{
short_header ();
jobs.Open ();
while (job = jobs.Next())
{
displayJobShort (job);
}
jobs.Close ();
}
if (summarize)
{
printf ("\n%d jobs; %d unexpanded, %d idle, %d running, %d malformed\n",
unexpanded+idle+running+malformed, unexpanded, idle, running,
malformed);
}
return 0;
}
static void
displayJobShort (ClassAd *ad)
{
int cluster, proc, date, status, prio, image_size;
float usage;
char owner[64], cmd[2048], args[2048];
struct rusage ru;
if (!ad->EvalInteger (ATTR_CLUSTER_ID, NULL, cluster) ||
!ad->EvalInteger (ATTR_PROC_ID, NULL, proc) ||
!ad->EvalInteger ("Q_Date", NULL, date) ||
!ad->EvalFloat ("Remote_CPU", NULL, usage) ||
!ad->EvalInteger ("Status", NULL, status) ||
!ad->EvalInteger (ATTR_PRIO, NULL, prio) ||
!ad->EvalInteger ("Image_size", NULL, image_size) ||
!ad->EvalString (ATTR_OWNER, NULL, owner) ||
!ad->EvalString ("Cmd", NULL, cmd) )
{
printf (" --- ???? --- \n");
return;
}
float_to_rusage (usage, &ru);
shorten (owner, 14);
if (ad->EvalString ("Args", NULL, args)) strcat (cmd, args);
shorten (cmd, 18);
short_print (cluster, proc, owner, date, ru.ru_utime.tv_sec, status, prio,
image_size, cmd);
switch (status)
{
case UNEXPANDED: unexpanded++; break;
case IDLE: idle++; break;
case RUNNING: running++; break;
}
}
static void
short_header (void)
{
printf( " %-7s %-14s %11s %12s %-2s %-3s %-4s %-18s\n",
"ID",
"OWNER",
"SUBMITTED",
"CPU_USAGE",
"ST",
"PRI",
"SIZE",
"CMD"
);
}
static void
shorten (char *buff, int len)
{
if (strlen (buff) > len) buff[len] = '\0';
}
static void
usage (char *myName)
{
printf ("usage: %s [-h <host>] [-l] [<constraint> ...]\n", myName);
printf ("\twhere <host> is one of:\n");
printf ("\t\thostname\n\t\t<hostname:port>\n\t\t<xx.xx.xx.xx:port>\n");
printf ("\tand a <constraint> is one of:\n");
printf ("\t\tcluster\n\t\tcluster.proc\n\t\t-C <ClassAd expression>\n");
}
<commit_msg>don't need proc_obj.h<commit_after>#include <iostream.h>
#include <pwd.h>
#include "condor_common.h"
#include "_condor_fix_resource.h"
#include "condor_config.h"
#include "condor_q.h"
#include "condor_attributes.h"
#include "files.h"
extern "C" SetSyscalls(){}
extern "C" int float_to_rusage (float, struct rusage *);
void short_print (int, int, const char*, int, int, int, int, int, const char *);
static void short_header (void);
static void usage (char *);
static void displayJobShort (ClassAd *);
static void shorten (char *, int);
static int verbose = 0, summarize = 1;
static int malformed, unexpanded, running, idle;
extern "C" BUCKET* ConfigTab[];
extern int Termlog;
int main (int argc, char **argv)
{
CondorQ Q;
ClassAdList jobs;
ClassAd *job;
int i;
int cluster, proc;
char constraint[1024];
char *host = 0;
struct passwd* pwd;
char* config_location;
char* scheddAddr;
for (i = 1; i < argc; i++)
{
if (strcmp (argv[i], "-l") == 0)
{
verbose = 1;
summarize = 0;
}
else
if (strcmp (argv[i], "-D") == 0)
{
Termlog = 1;
set_debug_flags( argv[++i] );
}
else
if (strcmp (argv[i], "-h") == 0)
{
host = argv[++i];
}
else
if (strcmp (argv[i], "-C") == 0)
{
Q.add (argv[++i]);
summarize = 0;
}
else
if (sscanf (argv[i], "%d.%d", &cluster, &proc) == 2)
{
sprintf (constraint, "((%s == %d) && (%s == %d))",
ATTR_CLUSTER_ID, cluster,
ATTR_PROC_ID, proc);
Q.add (constraint);
summarize = 0;
}
else
if (sscanf (argv[i], "%d", &cluster) == 1)
{
sprintf (constraint, "(%s == %d)", ATTR_CLUSTER_ID, cluster);
Q.add (constraint);
summarize = 0;
}
else
{
usage (argv[0]);
exit (1);
}
}
/* Weiru */
if((pwd = getpwnam("condor")) == NULL)
{
printf( "condor not in passwd file" );
exit(1);
}
if(read_config(pwd->pw_dir, MASTER_CONFIG, NULL, ConfigTab, TABLESIZE,
EXPAND_LAZY) < 0)
{
config(argv[0], NULL);
}
else
{
config_location = param("CONFIG_FILE_LOCATION");
if(!config_location)
{
config_location = pwd->pw_dir;
}
if(config_from_server(config_location, argv[0], NULL) < 0)
{
config(argv[0], NULL);
}
}
// find ip port of schedd from collector
if(!host)
{
host = new char[256];
if(gethostname(host, 256) < 0)
{
printf("Can't find host\n");
exit(1);
}
}
if((scheddAddr = get_schedd_addr(host)) == NULL)
{
printf("Can't find schedd address on %s\n", host);
exit(1);
}
// fetch queue from schedd
if (Q.fetchQueueFromHost (jobs, scheddAddr) != Q_OK)
{
printf ("Error connecting to job queue\n");
exit (1);
}
// initialize counters
malformed = 0; idle = 0; running = 0; unexpanded = 0;
if (verbose)
{
jobs.fPrintAttrListList (stdout);
}
else
{
short_header ();
jobs.Open ();
while (job = jobs.Next())
{
displayJobShort (job);
}
jobs.Close ();
}
if (summarize)
{
printf ("\n%d jobs; %d unexpanded, %d idle, %d running, %d malformed\n",
unexpanded+idle+running+malformed, unexpanded, idle, running,
malformed);
}
return 0;
}
static void
displayJobShort (ClassAd *ad)
{
int cluster, proc, date, status, prio, image_size;
float usage;
char owner[64], cmd[2048], args[2048];
struct rusage ru;
if (!ad->EvalInteger (ATTR_CLUSTER_ID, NULL, cluster) ||
!ad->EvalInteger (ATTR_PROC_ID, NULL, proc) ||
!ad->EvalInteger ("Q_Date", NULL, date) ||
!ad->EvalFloat ("Remote_CPU", NULL, usage) ||
!ad->EvalInteger ("Status", NULL, status) ||
!ad->EvalInteger (ATTR_PRIO, NULL, prio) ||
!ad->EvalInteger ("Image_size", NULL, image_size) ||
!ad->EvalString (ATTR_OWNER, NULL, owner) ||
!ad->EvalString ("Cmd", NULL, cmd) )
{
printf (" --- ???? --- \n");
return;
}
float_to_rusage (usage, &ru);
shorten (owner, 14);
if (ad->EvalString ("Args", NULL, args)) strcat (cmd, args);
shorten (cmd, 18);
short_print (cluster, proc, owner, date, ru.ru_utime.tv_sec, status, prio,
image_size, cmd);
switch (status)
{
case UNEXPANDED: unexpanded++; break;
case IDLE: idle++; break;
case RUNNING: running++; break;
}
}
static void
short_header (void)
{
printf( " %-7s %-14s %11s %12s %-2s %-3s %-4s %-18s\n",
"ID",
"OWNER",
"SUBMITTED",
"CPU_USAGE",
"ST",
"PRI",
"SIZE",
"CMD"
);
}
static void
shorten (char *buff, int len)
{
if (strlen (buff) > len) buff[len] = '\0';
}
static void
usage (char *myName)
{
printf ("usage: %s [-h <host>] [-l] [<constraint> ...]\n", myName);
printf ("\twhere <host> is one of:\n");
printf ("\t\thostname\n\t\t<hostname:port>\n\t\t<xx.xx.xx.xx:port>\n");
printf ("\tand a <constraint> is one of:\n");
printf ("\t\tcluster\n\t\tcluster.proc\n\t\t-C <ClassAd expression>\n");
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File ErrorUtil.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: error related utilities
//
///////////////////////////////////////////////////////////////////////////////
#ifndef ERRORUTIL_HPP
#define ERRORUTIL_HPP
#include <iostream>
#include <stdexcept>
#include <boost/lexical_cast.hpp>
namespace ErrorUtil
{
enum ErrType
{
efatal,
ewarning
};
#ifdef ENABLE_NEKTAR_EXCEPTIONS
static void ExceptionError(ErrType type, const char *routine, int lineNumber, const char *msg)
{
std::string errorMessage = std::string(routine) + "[" +
boost::lexical_cast<std::string>(lineNumber) + "]:" +
std::string(msg);
std::cerr << errorMessage << std::endl;
throw std::runtime_error(errorMessage);
}
#endif
static void Error(ErrType type, const char *routine, int lineNumber, const char *msg)
{
switch(type)
{
case efatal:
std::cerr << routine << "[" << lineNumber << "]:" << msg << std::endl;
exit(1);
break;
case ewarning:
std::cerr << routine << ": " << msg << std::endl;
break;
default:
std::cerr << "Unknown warning type" << std::endl;
}
}
} // end of namespace
/// Assert Level 0 -- Fundamental assert which
/// is used whether in FULLDEBUG, DEBUG or OPT
/// compilation mode. This level assert is
/// considered code critical, even under
/// optimized compilation.
#define NEKERROR(type, msg) \
ErrorUtil::Error(type, __FILE__, __LINE__, msg);
#ifdef ENABLE_NEKTAR_EXCEPTIONS
#define ASSERTL0(condition,msg) \
if(!(condition)) \
{ \
fprintf(stderr,"Level 0 Assert Violation\n"); \
ErrorUtil::ExceptionError(ErrorUtil::efatal, __FILE__, __LINE__, msg); \
}
#else
#define ASSERTL0(condition,msg) \
if(!(condition)) \
{ \
fprintf(stderr,"Level 0 Assert Violation\n"); \
ErrorUtil::Error(ErrorUtil::efatal, __FILE__, __LINE__, msg); \
}
#endif
/// Assert Level 1 -- Debugging which is used whether in FULLDEBUG or
/// DEBUG compilation mode. This level assert is designed for aiding
/// in standard debug (-g) mode
#ifdef DEBUG
#ifdef ENABLE_NEKTAR_EXCEPTIONS
#define ASSERTL1(condition,msg) \
if(!(condition)) \
{ \
fprintf(stderr,"Level 1 Assert Violation\n"); \
ErrorUtil::ExceptionError(ErrorUtil::efatal, __FILE__, __LINE__, msg); \
}
#else
#define ASSERTL1(condition,msg) \
if(!(condition)) \
{ \
fprintf(stderr,"Level 1 Assert Violation\n"); \
ErrorUtil::Error(ErrorUtil::efatal, __FILE__, __LINE__, msg); \
}
#endif
#else
#define ASSERTL1(condition,msg)
#endif
/// Assert Level 2 -- Debugging which is used FULLDEBUG compilation
/// mode. This level assert is designed to provide addition safety
/// checks within the code (such as bounds checking, etc.).
#ifdef FULLDEBUG
#ifdef ENABLE_NEKTAR_EXCEPTIONS
#define ASSERTL2(condition,msg) \
if(!(condition)) \
{ \
fprintf(stderr,"Level 2 Assert Violation\n"); \
ErrorUtil::ExceptionError(ErrorUtil::efatal, __FILE__, __LINE__, msg); \
}
#else
#define ASSERTL2(condition,msg) \
if(!(condition)) \
{ \
fprintf(stderr,"Level 2 Assert Violation\n"); \
ErrorUtil::Error(ErrorUtil::efatal, __FILE__, __LINE__, msg); \
}
#endif
#else
#define ASSERTL2(condition,msg)
#endif
#endif //ERRORUTIL_HPP
/***
$Log: ErrorUtil.hpp,v $
Revision 1.1 2006/06/01 11:07:52 kirby
*** empty log message ***
Revision 1.4 2006/05/16 20:40:44 jfrazier
Renamed ERROR to NEKERROR to prevent conflict in Visual Studio.
Revision 1.3 2006/05/09 16:40:57 jfrazier
Added ERROR macro definition.
Revision 1.2 2006/05/07 18:51:05 bnelson
Format changes for coding standard.
Revision 1.1 2006/05/04 18:57:41 kirby
*** empty log message ***
Revision 1.7 2006/04/14 14:51:17 jfrazier
Fixed a problem which is most likely a preprocessor problem. The file and line
number were inconsistent between release and debug builds.
**/
<commit_msg>Errors throw a new exception type NekError.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File ErrorUtil.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: error related utilities
//
///////////////////////////////////////////////////////////////////////////////
#ifndef ERRORUTIL_HPP
#define ERRORUTIL_HPP
#include <iostream>
#include <stdexcept>
#include <boost/lexical_cast.hpp>
namespace ErrorUtil
{
enum ErrType
{
efatal,
ewarning
};
#ifdef ENABLE_NEKTAR_EXCEPTIONS
class NekError : public std::runtime_error
{
public:
NekError(const std::string& message) : std::runtime_error(message) {}
};
static void ExceptionError(ErrType type, const char *routine, int lineNumber, const char *msg)
{
std::string errorMessage = std::string(routine) + "[" +
boost::lexical_cast<std::string>(lineNumber) + "]:" +
std::string(msg);
std::cerr << errorMessage << std::endl;
throw NekError(errorMessage);
}
#endif
static void Error(ErrType type, const char *routine, int lineNumber, const char *msg)
{
switch(type)
{
case efatal:
std::cerr << routine << "[" << lineNumber << "]:" << msg << std::endl;
exit(1);
break;
case ewarning:
std::cerr << routine << ": " << msg << std::endl;
break;
default:
std::cerr << "Unknown warning type" << std::endl;
}
}
} // end of namespace
/// Assert Level 0 -- Fundamental assert which
/// is used whether in FULLDEBUG, DEBUG or OPT
/// compilation mode. This level assert is
/// considered code critical, even under
/// optimized compilation.
#define NEKERROR(type, msg) \
ErrorUtil::Error(type, __FILE__, __LINE__, msg);
#ifdef ENABLE_NEKTAR_EXCEPTIONS
#define ASSERTL0(condition,msg) \
if(!(condition)) \
{ \
fprintf(stderr,"Level 0 Assert Violation\n"); \
ErrorUtil::ExceptionError(ErrorUtil::efatal, __FILE__, __LINE__, msg); \
}
#else
#define ASSERTL0(condition,msg) \
if(!(condition)) \
{ \
fprintf(stderr,"Level 0 Assert Violation\n"); \
ErrorUtil::Error(ErrorUtil::efatal, __FILE__, __LINE__, msg); \
}
#endif
/// Assert Level 1 -- Debugging which is used whether in FULLDEBUG or
/// DEBUG compilation mode. This level assert is designed for aiding
/// in standard debug (-g) mode
#ifdef DEBUG
#ifdef ENABLE_NEKTAR_EXCEPTIONS
#define ASSERTL1(condition,msg) \
if(!(condition)) \
{ \
fprintf(stderr,"Level 1 Assert Violation\n"); \
ErrorUtil::ExceptionError(ErrorUtil::efatal, __FILE__, __LINE__, msg); \
}
#else
#define ASSERTL1(condition,msg) \
if(!(condition)) \
{ \
fprintf(stderr,"Level 1 Assert Violation\n"); \
ErrorUtil::Error(ErrorUtil::efatal, __FILE__, __LINE__, msg); \
}
#endif
#else
#define ASSERTL1(condition,msg)
#endif
/// Assert Level 2 -- Debugging which is used FULLDEBUG compilation
/// mode. This level assert is designed to provide addition safety
/// checks within the code (such as bounds checking, etc.).
#ifdef FULLDEBUG
#ifdef ENABLE_NEKTAR_EXCEPTIONS
#define ASSERTL2(condition,msg) \
if(!(condition)) \
{ \
fprintf(stderr,"Level 2 Assert Violation\n"); \
ErrorUtil::ExceptionError(ErrorUtil::efatal, __FILE__, __LINE__, msg); \
}
#else
#define ASSERTL2(condition,msg) \
if(!(condition)) \
{ \
fprintf(stderr,"Level 2 Assert Violation\n"); \
ErrorUtil::Error(ErrorUtil::efatal, __FILE__, __LINE__, msg); \
}
#endif
#else
#define ASSERTL2(condition,msg)
#endif
#endif //ERRORUTIL_HPP
/***
$Log: ErrorUtil.hpp,v $
Revision 1.2 2006/08/14 02:18:02 bnelson
Added the option to throw exceptions when an error is encountered.
Revision 1.1 2006/06/01 11:07:52 kirby
*** empty log message ***
Revision 1.4 2006/05/16 20:40:44 jfrazier
Renamed ERROR to NEKERROR to prevent conflict in Visual Studio.
Revision 1.3 2006/05/09 16:40:57 jfrazier
Added ERROR macro definition.
Revision 1.2 2006/05/07 18:51:05 bnelson
Format changes for coding standard.
Revision 1.1 2006/05/04 18:57:41 kirby
*** empty log message ***
Revision 1.7 2006/04/14 14:51:17 jfrazier
Fixed a problem which is most likely a preprocessor problem. The file and line
number were inconsistent between release and debug builds.
**/
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: dependencies.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-09-08 16:27:10 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "codemaker/dependencies.hxx"
#include "codemaker/typemanager.hxx"
#include "codemaker/unotype.hxx"
#include "osl/diagnose.h"
#include "registry/reader.hxx"
#include "rtl/string.hxx"
#include "rtl/textcvt.h"
#include "rtl/textenc.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include <vector>
using codemaker::Dependencies;
namespace {
struct Bad {};
}
Dependencies::Dependencies(
TypeManager const & manager, rtl::OString const & type):
m_voidDependency(false), m_booleanDependency(false),
m_byteDependency(false), m_shortDependency(false),
m_unsignedShortDependency(false), m_longDependency(false),
m_unsignedLongDependency(false), m_hyperDependency(false),
m_unsignedHyperDependency(false), m_floatDependency(false),
m_doubleDependency(false), m_charDependency(false),
m_stringDependency(false), m_typeDependency(false), m_anyDependency(false),
m_sequenceDependency(false)
{
typereg::Reader reader(manager.getTypeReader(type));
m_valid = reader.isValid();
if (m_valid) {
// Not everything is checked for consistency, just things that are cheap
// to test:
try {
RTTypeClass tc = reader.getTypeClass();
if (tc != RT_TYPE_SERVICE) {
for (sal_Int16 i = 0; i < reader.getSuperTypeCount(); ++i) {
insert(reader.getSuperTypeName(i), true);
}
}
if (tc != RT_TYPE_ENUM) {
{for (sal_Int16 i = 0; i < reader.getFieldCount(); ++i) {
if ((reader.getFieldFlags(i) & RT_ACCESS_PARAMETERIZED_TYPE)
== 0)
{
insert(reader.getFieldTypeName(i), false);
}
}}
}
for (sal_Int16 i = 0; i < reader.getMethodCount(); ++i) {
insert(reader.getMethodReturnTypeName(i), false);
for (sal_Int16 j = 0; j < reader.getMethodParameterCount(i);
++j)
{
if ((reader.getMethodParameterFlags(i, j) & RT_PARAM_REST)
!= 0)
{
m_sequenceDependency = true;
}
insert(reader.getMethodParameterTypeName(i, j), false);
}
for (sal_Int16 j = 0; j < reader.getMethodExceptionCount(i);
++j)
{
insert(reader.getMethodExceptionTypeName(i, j), false);
}
}
for (sal_Int16 i = 0; i < reader.getReferenceCount(); ++i) {
if (reader.getReferenceSort(i) != RT_REF_TYPE_PARAMETER) {
insert(reader.getReferenceTypeName(i), false);
}
}
} catch (Bad &) {
m_map.clear();
m_valid = false;
m_voidDependency = false;
m_booleanDependency = false;
m_byteDependency = false;
m_shortDependency = false;
m_unsignedShortDependency = false;
m_longDependency = false;
m_unsignedLongDependency = false;
m_hyperDependency = false;
m_unsignedHyperDependency = false;
m_floatDependency = false;
m_doubleDependency = false;
m_charDependency = false;
m_stringDependency = false;
m_typeDependency = false;
m_anyDependency = false;
m_sequenceDependency = false;
}
}
}
Dependencies::~Dependencies()
{}
void Dependencies::insert(rtl::OUString const & type, bool base) {
rtl::OString t;
if (!type.convertToString(
&t, RTL_TEXTENCODING_UTF8,
(RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR
| RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR)))
{
throw Bad();
}
insert(t, base);
}
void Dependencies::insert(rtl::OString const & type, bool base) {
sal_Int32 rank;
std::vector< rtl::OString > args;
rtl::OString t(UnoType::decompose(type, &rank, &args));
if (rank > 0) {
m_sequenceDependency = true;
}
switch (UnoType::getSort(t)) {
case UnoType::SORT_VOID:
if (rank != 0 || !args.empty()) {
throw Bad();
}
m_voidDependency = true;
break;
case UnoType::SORT_BOOLEAN:
if (!args.empty()) {
throw Bad();
}
m_booleanDependency = true;
break;
case UnoType::SORT_BYTE:
if (!args.empty()) {
throw Bad();
}
m_byteDependency = true;
break;
case UnoType::SORT_SHORT:
if (!args.empty()) {
throw Bad();
}
m_shortDependency = true;
break;
case UnoType::SORT_UNSIGNED_SHORT:
if (!args.empty()) {
throw Bad();
}
m_unsignedShortDependency = true;
break;
case UnoType::SORT_LONG:
if (!args.empty()) {
throw Bad();
}
m_longDependency = true;
break;
case UnoType::SORT_UNSIGNED_LONG:
if (!args.empty()) {
throw Bad();
}
m_unsignedLongDependency = true;
break;
case UnoType::SORT_HYPER:
if (!args.empty()) {
throw Bad();
}
m_hyperDependency = true;
break;
case UnoType::SORT_UNSIGNED_HYPER:
if (!args.empty()) {
throw Bad();
}
m_unsignedHyperDependency = true;
break;
case UnoType::SORT_FLOAT:
if (!args.empty()) {
throw Bad();
}
m_floatDependency = true;
break;
case UnoType::SORT_DOUBLE:
if (!args.empty()) {
throw Bad();
}
m_doubleDependency = true;
break;
case UnoType::SORT_CHAR:
if (!args.empty()) {
throw Bad();
}
m_charDependency = true;
break;
case UnoType::SORT_STRING:
if (!args.empty()) {
throw Bad();
}
m_stringDependency = true;
break;
case UnoType::SORT_TYPE:
if (!args.empty()) {
throw Bad();
}
m_typeDependency = true;
break;
case UnoType::SORT_ANY:
if (!args.empty()) {
throw Bad();
}
m_anyDependency = true;
break;
case UnoType::SORT_COMPLEX:
{
{for (std::vector< rtl::OString >::iterator i(args.begin());
i != args.end(); ++i)
{
insert(*i, false);
}}
Map::iterator i(m_map.find(t));
if (i == m_map.end()) {
m_map.insert(
Map::value_type(t, base ? KIND_BASE : KIND_NO_BASE));
} else if (base) {
i->second = KIND_BASE;
}
break;
}
default:
OSL_ASSERT(false);
break;
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.26); FILE MERGED 2005/09/05 17:27:57 rt 1.4.26.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dependencies.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 02:09:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "codemaker/dependencies.hxx"
#include "codemaker/typemanager.hxx"
#include "codemaker/unotype.hxx"
#include "osl/diagnose.h"
#include "registry/reader.hxx"
#include "rtl/string.hxx"
#include "rtl/textcvt.h"
#include "rtl/textenc.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include <vector>
using codemaker::Dependencies;
namespace {
struct Bad {};
}
Dependencies::Dependencies(
TypeManager const & manager, rtl::OString const & type):
m_voidDependency(false), m_booleanDependency(false),
m_byteDependency(false), m_shortDependency(false),
m_unsignedShortDependency(false), m_longDependency(false),
m_unsignedLongDependency(false), m_hyperDependency(false),
m_unsignedHyperDependency(false), m_floatDependency(false),
m_doubleDependency(false), m_charDependency(false),
m_stringDependency(false), m_typeDependency(false), m_anyDependency(false),
m_sequenceDependency(false)
{
typereg::Reader reader(manager.getTypeReader(type));
m_valid = reader.isValid();
if (m_valid) {
// Not everything is checked for consistency, just things that are cheap
// to test:
try {
RTTypeClass tc = reader.getTypeClass();
if (tc != RT_TYPE_SERVICE) {
for (sal_Int16 i = 0; i < reader.getSuperTypeCount(); ++i) {
insert(reader.getSuperTypeName(i), true);
}
}
if (tc != RT_TYPE_ENUM) {
{for (sal_Int16 i = 0; i < reader.getFieldCount(); ++i) {
if ((reader.getFieldFlags(i) & RT_ACCESS_PARAMETERIZED_TYPE)
== 0)
{
insert(reader.getFieldTypeName(i), false);
}
}}
}
for (sal_Int16 i = 0; i < reader.getMethodCount(); ++i) {
insert(reader.getMethodReturnTypeName(i), false);
for (sal_Int16 j = 0; j < reader.getMethodParameterCount(i);
++j)
{
if ((reader.getMethodParameterFlags(i, j) & RT_PARAM_REST)
!= 0)
{
m_sequenceDependency = true;
}
insert(reader.getMethodParameterTypeName(i, j), false);
}
for (sal_Int16 j = 0; j < reader.getMethodExceptionCount(i);
++j)
{
insert(reader.getMethodExceptionTypeName(i, j), false);
}
}
for (sal_Int16 i = 0; i < reader.getReferenceCount(); ++i) {
if (reader.getReferenceSort(i) != RT_REF_TYPE_PARAMETER) {
insert(reader.getReferenceTypeName(i), false);
}
}
} catch (Bad &) {
m_map.clear();
m_valid = false;
m_voidDependency = false;
m_booleanDependency = false;
m_byteDependency = false;
m_shortDependency = false;
m_unsignedShortDependency = false;
m_longDependency = false;
m_unsignedLongDependency = false;
m_hyperDependency = false;
m_unsignedHyperDependency = false;
m_floatDependency = false;
m_doubleDependency = false;
m_charDependency = false;
m_stringDependency = false;
m_typeDependency = false;
m_anyDependency = false;
m_sequenceDependency = false;
}
}
}
Dependencies::~Dependencies()
{}
void Dependencies::insert(rtl::OUString const & type, bool base) {
rtl::OString t;
if (!type.convertToString(
&t, RTL_TEXTENCODING_UTF8,
(RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR
| RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR)))
{
throw Bad();
}
insert(t, base);
}
void Dependencies::insert(rtl::OString const & type, bool base) {
sal_Int32 rank;
std::vector< rtl::OString > args;
rtl::OString t(UnoType::decompose(type, &rank, &args));
if (rank > 0) {
m_sequenceDependency = true;
}
switch (UnoType::getSort(t)) {
case UnoType::SORT_VOID:
if (rank != 0 || !args.empty()) {
throw Bad();
}
m_voidDependency = true;
break;
case UnoType::SORT_BOOLEAN:
if (!args.empty()) {
throw Bad();
}
m_booleanDependency = true;
break;
case UnoType::SORT_BYTE:
if (!args.empty()) {
throw Bad();
}
m_byteDependency = true;
break;
case UnoType::SORT_SHORT:
if (!args.empty()) {
throw Bad();
}
m_shortDependency = true;
break;
case UnoType::SORT_UNSIGNED_SHORT:
if (!args.empty()) {
throw Bad();
}
m_unsignedShortDependency = true;
break;
case UnoType::SORT_LONG:
if (!args.empty()) {
throw Bad();
}
m_longDependency = true;
break;
case UnoType::SORT_UNSIGNED_LONG:
if (!args.empty()) {
throw Bad();
}
m_unsignedLongDependency = true;
break;
case UnoType::SORT_HYPER:
if (!args.empty()) {
throw Bad();
}
m_hyperDependency = true;
break;
case UnoType::SORT_UNSIGNED_HYPER:
if (!args.empty()) {
throw Bad();
}
m_unsignedHyperDependency = true;
break;
case UnoType::SORT_FLOAT:
if (!args.empty()) {
throw Bad();
}
m_floatDependency = true;
break;
case UnoType::SORT_DOUBLE:
if (!args.empty()) {
throw Bad();
}
m_doubleDependency = true;
break;
case UnoType::SORT_CHAR:
if (!args.empty()) {
throw Bad();
}
m_charDependency = true;
break;
case UnoType::SORT_STRING:
if (!args.empty()) {
throw Bad();
}
m_stringDependency = true;
break;
case UnoType::SORT_TYPE:
if (!args.empty()) {
throw Bad();
}
m_typeDependency = true;
break;
case UnoType::SORT_ANY:
if (!args.empty()) {
throw Bad();
}
m_anyDependency = true;
break;
case UnoType::SORT_COMPLEX:
{
{for (std::vector< rtl::OString >::iterator i(args.begin());
i != args.end(); ++i)
{
insert(*i, false);
}}
Map::iterator i(m_map.find(t));
if (i == m_map.end()) {
m_map.insert(
Map::value_type(t, base ? KIND_BASE : KIND_NO_BASE));
} else if (base) {
i->second = KIND_BASE;
}
break;
}
default:
OSL_ASSERT(false);
break;
}
}
<|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/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "net/http/http_cache.h"
#include "net/url_request/url_request_context.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
#include "webkit/tools/test_shell/test_shell_test.h"
namespace {
const wchar_t kTestUrlSwitch[] = L"test-url";
// A test to help determine if any nodes have been leaked as a result of
// visiting a given URL. If enabled in WebCore, the number of leaked nodes
// can be printed upon termination. This is only enabled in debug builds, so
// it only makes sense to run this using a debug build.
//
// It will load a URL, visit about:blank, and then perform garbage collection.
// The number of remaining (potentially leaked) nodes will be printed on exit.
class NodeLeakTest : public TestShellTest {
public:
virtual void SetUp() {
CommandLine parsed_command_line;
std::wstring js_flags =
parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags);
CommandLine::AppendSwitch(&js_flags, L"expose-gc");
webkit_glue::SetJavaScriptFlags(js_flags);
// Expose GCController to JavaScript as well.
webkit_glue::SetShouldExposeGCController(true);
std::wstring cache_path =
parsed_command_line.GetSwitchValue(test_shell::kCacheDir);
if (cache_path.empty()) {
PathService::Get(base::DIR_EXE, &cache_path);
file_util::AppendToPath(&cache_path, L"cache");
}
if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
const std::wstring timeout_str = parsed_command_line.GetSwitchValue(
test_shell::kTestShellTimeOut);
int timeout_ms = static_cast<int>(StringToInt64(timeout_str.c_str()));
if (timeout_ms > 0)
TestShell::SetFileTestTimeout(timeout_ms);
}
// Optionally use playback mode (for instance if running automated tests).
net::HttpCache::Mode mode =
parsed_command_line.HasSwitch(test_shell::kPlaybackMode) ?
net::HttpCache::PLAYBACK : net::HttpCache::NORMAL;
SimpleResourceLoaderBridge::Init(
new TestShellRequestContext(cache_path, mode));
TestShellTest::SetUp();
}
virtual void TearDown() {
TestShellTest::TearDown();
SimpleResourceLoaderBridge::Shutdown();
}
void NavigateToURL(const std::wstring& test_url) {
test_shell_->LoadURL(test_url.c_str());
test_shell_->WaitTestFinished();
// Depends on TestShellTests::TearDown to load blank page and
// the TestShell destructor to call garbage collection.
}
};
} // namespace
TEST_F(NodeLeakTest, TestURL) {
CommandLine parsed_command_line;
if (parsed_command_line.HasSwitch(kTestUrlSwitch)) {
NavigateToURL(parsed_command_line.GetSwitchValue(kTestUrlSwitch).c_str());
}
}
<commit_msg>Missed a usage of TestShellRequestContext. This one is allowed to behave as before.<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/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "net/http/http_cache.h"
#include "net/url_request/url_request_context.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
#include "webkit/tools/test_shell/test_shell_test.h"
namespace {
const wchar_t kTestUrlSwitch[] = L"test-url";
// A test to help determine if any nodes have been leaked as a result of
// visiting a given URL. If enabled in WebCore, the number of leaked nodes
// can be printed upon termination. This is only enabled in debug builds, so
// it only makes sense to run this using a debug build.
//
// It will load a URL, visit about:blank, and then perform garbage collection.
// The number of remaining (potentially leaked) nodes will be printed on exit.
class NodeLeakTest : public TestShellTest {
public:
virtual void SetUp() {
CommandLine parsed_command_line;
std::wstring js_flags =
parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags);
CommandLine::AppendSwitch(&js_flags, L"expose-gc");
webkit_glue::SetJavaScriptFlags(js_flags);
// Expose GCController to JavaScript as well.
webkit_glue::SetShouldExposeGCController(true);
std::wstring cache_path =
parsed_command_line.GetSwitchValue(test_shell::kCacheDir);
if (cache_path.empty()) {
PathService::Get(base::DIR_EXE, &cache_path);
file_util::AppendToPath(&cache_path, L"cache");
}
if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
const std::wstring timeout_str = parsed_command_line.GetSwitchValue(
test_shell::kTestShellTimeOut);
int timeout_ms = static_cast<int>(StringToInt64(timeout_str.c_str()));
if (timeout_ms > 0)
TestShell::SetFileTestTimeout(timeout_ms);
}
// Optionally use playback mode (for instance if running automated tests).
net::HttpCache::Mode mode =
parsed_command_line.HasSwitch(test_shell::kPlaybackMode) ?
net::HttpCache::PLAYBACK : net::HttpCache::NORMAL;
SimpleResourceLoaderBridge::Init(
new TestShellRequestContext(cache_path, mode, false));
TestShellTest::SetUp();
}
virtual void TearDown() {
TestShellTest::TearDown();
SimpleResourceLoaderBridge::Shutdown();
}
void NavigateToURL(const std::wstring& test_url) {
test_shell_->LoadURL(test_url.c_str());
test_shell_->WaitTestFinished();
// Depends on TestShellTests::TearDown to load blank page and
// the TestShell destructor to call garbage collection.
}
};
} // namespace
TEST_F(NodeLeakTest, TestURL) {
CommandLine parsed_command_line;
if (parsed_command_line.HasSwitch(kTestUrlSwitch)) {
NavigateToURL(parsed_command_line.GetSwitchValue(kTestUrlSwitch).c_str());
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.