text stringlengths 54 60.6k |
|---|
<commit_before>#include <errno.h>
#include <stdlib.h>
#include <getopt.h>
#include <string>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include "logger.h"
#include "client.h"
#include <libwatcher/labelMessage.h>
using namespace std;
using namespace watcher;
using namespace watcher::event;
using namespace boost;
void usage(const char *progName)
{
fprintf(stderr, "Usage: %s [args] [optional args]\n", basename(progName));
fprintf(stderr, "Args:\n");
fprintf(stderr, " -l, --label=label The text to put in the label\n");
fprintf(stderr, " -s, --server=server The name/address of the watcherd server\n");
fprintf(stderr, " -h,-H,-?,-help Show this usage message\n");
fprintf(stderr, "\n");
fprintf(stderr, "Optional args:\n");
fprintf(stderr, " If address is specified, the label will attach to the node with that address. If cooridinates are\n");
fprintf(stderr, " specified, the label will float at those coordinates. The node address takes precedence. If neither\n");
fprintf(stderr, " option is specified, the label will attach to the local node in the watcher.\n");
fprintf(stderr, " -n, --node=address The node to attach the label to.\n");
fprintf(stderr, " -x, --latitude=coord The latitude to float the node at.\n");
fprintf(stderr, " -y, --longitude=coord The longitude to float the node at.\n");
fprintf(stderr, " -z, --altitiude=coord The altitude to float the node at.\n");
fprintf(stderr, "\n");
fprintf(stderr, " -p, --logProps log.properties file, which controls logging for this program\n");
fprintf(stderr, " -t, --fontSize=size The font size of the label\n");
fprintf(stderr, " -f, --foreground=color The foreground color of the label. Can be ROYGBIV or RGBA format, string or hex value.\n");
fprintf(stderr, " -b, --background=color The background color of the label. Can be ROYGBIV or RGBA format, string or hex value.\n");
fprintf(stderr, " -e, --expiration=seconds How long in secondt to diplay the label\n");
exit(1);
}
int main(int argc, char **argv)
{
TRACE_ENTER();
int c;
string label;
string server;
string logProps("log.properties");
unsigned int fontSize=10;
asio::ip::address address(boost::asio::ip::address::from_string("127.0.0.1")); // loclahost
Color fg=Color::black;
Color bg=Color::white;
uint32_t expiration=10000;
float lat=0.0, lng=0.0, alt=0.0;
while (true)
{
int option_index = 0;
static struct option long_options[] = {
{"label", required_argument, 0, 'l'},
{"server", required_argument, 0, 's'},
{"node", required_argument, 0, 'n'},
{"latitude", required_argument, 0, 'x'},
{"longitude", required_argument, 0, 'y'},
{"altitiude", required_argument, 0, 'z'},
{"logProps", required_argument, 0, 'p'},
{"fontSize", required_argument, 0, 't'},
{"foreground", required_argument, 0, 'f'},
{"background", required_argument, 0, 'b'},
{"expiration", required_argument, 0, 'e'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
c = getopt_long(argc, argv, "l:s:n:x:y:t:p:z:f:b;e:hH?", long_options, &option_index);
if (c == -1)
break;
switch(c)
{
case 'l': label=optarg; break;
case 's': server=optarg; break;
case 'p': logProps=optarg; break;
case 't': fontSize=lexical_cast<unsigned int>(optarg); break;
case 'f': { bool val=fg.fromString(optarg); if (!val) { printf("\nBad argument for fg color\n\n"); usage(argv[0]); } break; }
case 'g': { bool val=bg.fromString(optarg); if (!val) { printf("\nBad argument for bg color\n\n"); usage(argv[0]); } break; }
case 'e': expiration=lexical_cast<uint32_t>(optarg); break;
case 'n':
{
boost::system::error_code e;
address=asio::ip::address::from_string(optarg, e);
if (e)
{
fprintf(stderr, "\nI did not understand the \"node\" argument: %s. It should be a host address.\n\n", optarg);
usage(argv[0]);
TRACE_EXIT_RET(EXIT_FAILURE);
return EXIT_FAILURE;
}
}
break;
case 'x': lat=lexical_cast<float>(optarg); break; // GTL should try{}catch{} here for invalid values.
case 'y': lng=lexical_cast<float>(optarg); break; // GTL should try{}catch{} here for invalid values.
case 'z': alt=lexical_cast<float>(optarg); break; // GTL should try{}catch{} here for invalid values.
case 'h':
case 'H':
case '?':
default:
usage(argv[0]);
break;
}
}
if (server=="" || label=="")
{
usage(argv[0]);
exit(1);
}
//
// Now do some actual work.
//
LOAD_LOG_PROPS(logProps);
watcher::Client client(server);
LOG_INFO("Connecting to " << server << " and sending message.");
LabelMessagePtr lm = LabelMessagePtr(new LabelMessage);
lm->label=label;
lm->fontSize=fontSize;
lm->address=address;
lm->foreground=fg;
lm->background=bg;
lm->expiration=expiration;
lm->lat=lat;
lm->lng=lng;
lm->alt=alt;
if(!client.sendMessage(lm))
{
LOG_ERROR("Error sending label message: " << *lm);
TRACE_EXIT_RET(EXIT_FAILURE);
return EXIT_FAILURE;
}
client.wait();
TRACE_EXIT_RET(EXIT_SUCCESS);
return EXIT_SUCCESS;
}
<commit_msg>labelMessageTest: added -r --remove option. Will remove the label if it's there.<commit_after>#include <errno.h>
#include <stdlib.h>
#include <getopt.h>
#include <string>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include "logger.h"
#include "client.h"
#include <libwatcher/labelMessage.h>
using namespace std;
using namespace watcher;
using namespace watcher::event;
using namespace boost;
void usage(const char *progName)
{
fprintf(stderr, "Usage: %s [args] [optional args]\n", basename(progName));
fprintf(stderr, "Args:\n");
fprintf(stderr, " -l, --label=label The text to put in the label\n");
fprintf(stderr, " -s, --server=server The name/address of the watcherd server\n");
fprintf(stderr, " -h,-H,-?,-help Show this usage message\n");
fprintf(stderr, "\n");
fprintf(stderr, "Optional args:\n");
fprintf(stderr, " If address is specified, the label will attach to the node with that address. If cooridinates are\n");
fprintf(stderr, " specified, the label will float at those coordinates. The node address takes precedence. If neither\n");
fprintf(stderr, " option is specified, the label will attach to the local node in the watcher.\n");
fprintf(stderr, " -n, --node=address The node to attach the label to.\n");
fprintf(stderr, " -x, --latitude=coord The latitude to float the node at.\n");
fprintf(stderr, " -y, --longitude=coord The longitude to float the node at.\n");
fprintf(stderr, " -z, --altitiude=coord The altitude to float the node at.\n");
fprintf(stderr, "\n");
fprintf(stderr, " -p, --logProps log.properties file, which controls logging for this program\n");
fprintf(stderr, " -t, --fontSize=size The font size of the label\n");
fprintf(stderr, " -f, --foreground=color The foreground color of the label. Can be ROYGBIV or RGBA format, string or hex value.\n");
fprintf(stderr, " -b, --background=color The background color of the label. Can be ROYGBIV or RGBA format, string or hex value.\n");
fprintf(stderr, " -e, --expiration=seconds How long in secondt to diplay the label\n");
fprintf(stderr, " -r, --remove Remove the label if it is attached\n");
exit(1);
}
int main(int argc, char **argv)
{
TRACE_ENTER();
int c;
string label;
string server;
string logProps("labelMessageTest.log.properties");
unsigned int fontSize=10;
asio::ip::address address;
Color fg=Color::black;
Color bg=Color::white;
uint32_t expiration=10000;
float lat=0.0, lng=0.0, alt=0.0;
bool remove=false;
while (true)
{
int option_index = 0;
static struct option long_options[] = {
{"label", required_argument, 0, 'l'},
{"server", required_argument, 0, 's'},
{"node", required_argument, 0, 'n'},
{"latitude", required_argument, 0, 'x'},
{"longitude", required_argument, 0, 'y'},
{"altitiude", required_argument, 0, 'z'},
{"logProps", required_argument, 0, 'p'},
{"fontSize", required_argument, 0, 't'},
{"foreground", required_argument, 0, 'f'},
{"background", required_argument, 0, 'b'},
{"expiration", required_argument, 0, 'e'},
{"remove", no_argument, 0, 'r'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
c = getopt_long(argc, argv, "l:s:n:x:y:t:p:z:f:b:e:rhH?", long_options, &option_index);
if (c == -1)
break;
switch(c)
{
case 'l': label=optarg; break;
case 's': server=optarg; break;
case 'p': logProps=optarg; break;
case 't': fontSize=lexical_cast<unsigned int>(optarg); break;
case 'f': { bool val=fg.fromString(optarg); if (!val) { printf("\nBad argument for fg color\n\n"); usage(argv[0]); } break; }
case 'g': { bool val=bg.fromString(optarg); if (!val) { printf("\nBad argument for bg color\n\n"); usage(argv[0]); } break; }
case 'e': expiration=lexical_cast<uint32_t>(optarg); break;
case 'n':
{
boost::system::error_code e;
address=asio::ip::address::from_string(optarg, e);
if (e)
{
fprintf(stderr, "\nI did not understand the \"node\" argument: %s. It should be a host address.\n\n", optarg);
usage(argv[0]);
TRACE_EXIT_RET(EXIT_FAILURE);
return EXIT_FAILURE;
}
}
break;
case 'x': lat=lexical_cast<float>(optarg); break; // GTL should try{}catch{} here for invalid values.
case 'y': lng=lexical_cast<float>(optarg); break; // GTL should try{}catch{} here for invalid values.
case 'z': alt=lexical_cast<float>(optarg); break; // GTL should try{}catch{} here for invalid values.
case 'r': remove=true; break;
case 'h':
case 'H':
case '?':
default:
usage(argv[0]);
break;
}
}
if (server=="" || label=="")
{
usage(argv[0]);
exit(1);
}
//
// Now do some actual work.
//
LOAD_LOG_PROPS(logProps);
watcher::Client client(server);
LOG_INFO("Connecting to " << server << " and sending message.");
LabelMessagePtr lm = LabelMessagePtr(new LabelMessage);
lm->label=label;
lm->fontSize=fontSize;
lm->fromNodeID=address;
lm->foreground=fg;
lm->background=bg;
lm->expiration=expiration;
lm->lat=lat;
lm->lng=lng;
lm->alt=alt;
lm->addLabel=!remove;
if(!client.sendMessage(lm))
{
LOG_ERROR("Error sending label message: " << *lm);
TRACE_EXIT_RET(EXIT_FAILURE);
return EXIT_FAILURE;
}
client.wait();
TRACE_EXIT_RET(EXIT_SUCCESS);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2011 Martin Klapetek <mklapetek@kde.org>
Copyright (C) 2013 David Edmundson <davidedmundsonk@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.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
*/
#include "persondetailsview.h"
#include <QFormLayout>
#include <QLabel>
#include <QDebug>
#include <QList>
#include <KLocalizedString>
#include "abstractfieldwidgetfactory.h"
#include "plugins/emaildetailswidget.h"
namespace KPeople {
class PersonDetailsViewPrivate{
public:
PersonData *m_person;
QFormLayout *m_mainLayout;
QList<AbstractFieldWidgetFactory*> m_plugins;
};
}
using namespace KPeople;
class CoreFieldsPlugin : public AbstractFieldWidgetFactory
{
public:
CoreFieldsPlugin(KABC::Field *field);
virtual ~CoreFieldsPlugin();
virtual QString label() const;
virtual int sortWeight() const;
virtual QWidget* createDetailsWidget(const KABC::Addressee &person, QWidget *parent) const;
private:
KABC::Field* m_field;
};
CoreFieldsPlugin::CoreFieldsPlugin(KABC::Field* field):
m_field(field)
{
}
CoreFieldsPlugin::~CoreFieldsPlugin()
{
}
QString CoreFieldsPlugin::label() const
{
return m_field->label();
}
int CoreFieldsPlugin::sortWeight() const
{
return m_field->category()*10;
}
QWidget* CoreFieldsPlugin::createDetailsWidget(const KABC::Addressee &person, QWidget *parent) const
{
//don't handle emails here - KABC::Field just lists one which is rubbish. Instead use a custom plugin that lists everything
if (m_field->category() == KABC::Field::Email) {
return 0;
}
const QString &text = m_field->value(person);
if (text.isEmpty()) {
return 0;
}
return new QLabel(text, parent);
}
PersonDetailsView::PersonDetailsView(QWidget *parent)
: QWidget(parent),
d_ptr(new PersonDetailsViewPrivate())
{
Q_D(PersonDetailsView);
d->m_mainLayout = new QFormLayout(this);
d->m_person = 0;
//create plugins
Q_FOREACH(KABC::Field *field, KABC::Field::allFields()) {
d->m_plugins << new CoreFieldsPlugin(field);
}
d->m_plugins << new EmailFieldsPlugin();
//TODO Sort plugins
}
PersonDetailsView::~PersonDetailsView()
{
Q_D(PersonDetailsView);
// qDeleteAll<AbstractFieldWidgetFactory>(d->m_plugins);
delete d_ptr;
}
void PersonDetailsView::setPerson(PersonData *person)
{
Q_D(PersonDetailsView);
if (!d->m_person) {
disconnect(d->m_person, SIGNAL(dataChanged()), this, SLOT(reload()));
}
d->m_person = person;
connect(d->m_person, SIGNAL(dataChanged()), this, SLOT(reload()));
reload();
}
// void PersonDetailsView::setPersonsModel(PersonsModel *model)
// {
// Q_D(PersonDetailsView);
// Q_FOREACH (AbstractPersonDetailsWidget *detailsWidget, d->m_detailWidgets) {
// detailsWidget->setPersonsModel(model);
// }
// }
void PersonDetailsView::reload()
{
Q_D(PersonDetailsView);
//delete everything currently in the layout
QLayoutItem *child;
while ((child = layout()->takeAt(0)) != 0) {
delete child->widget();
delete child;
}
Q_FOREACH(AbstractFieldWidgetFactory *widgetFactor, d->m_plugins) {
const QString label = widgetFactor->label() + ':';
QWidget *widget = widgetFactor->createDetailsWidget(d->m_person->person(), this);
if (widget) {
QFont font = widget->font();
font.setBold(true);
widget->setFont(font);
d->m_mainLayout->addRow(label, widget);
}
}
}
<commit_msg>widgetFactor -> widgetFactory<commit_after>/*
Copyright (C) 2011 Martin Klapetek <mklapetek@kde.org>
Copyright (C) 2013 David Edmundson <davidedmundsonk@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.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
*/
#include "persondetailsview.h"
#include <QFormLayout>
#include <QLabel>
#include <QDebug>
#include <QList>
#include <KLocalizedString>
#include "abstractfieldwidgetfactory.h"
#include "plugins/emaildetailswidget.h"
namespace KPeople {
class PersonDetailsViewPrivate{
public:
PersonData *m_person;
QFormLayout *m_mainLayout;
QList<AbstractFieldWidgetFactory*> m_plugins;
};
}
using namespace KPeople;
class CoreFieldsPlugin : public AbstractFieldWidgetFactory
{
public:
CoreFieldsPlugin(KABC::Field *field);
virtual ~CoreFieldsPlugin();
virtual QString label() const;
virtual int sortWeight() const;
virtual QWidget* createDetailsWidget(const KABC::Addressee &person, QWidget *parent) const;
private:
KABC::Field* m_field;
};
CoreFieldsPlugin::CoreFieldsPlugin(KABC::Field* field):
m_field(field)
{
}
CoreFieldsPlugin::~CoreFieldsPlugin()
{
}
QString CoreFieldsPlugin::label() const
{
return m_field->label();
}
int CoreFieldsPlugin::sortWeight() const
{
return m_field->category()*10;
}
QWidget* CoreFieldsPlugin::createDetailsWidget(const KABC::Addressee &person, QWidget *parent) const
{
//don't handle emails here - KABC::Field just lists one which is rubbish. Instead use a custom plugin that lists everything
if (m_field->category() == KABC::Field::Email) {
return 0;
}
const QString &text = m_field->value(person);
if (text.isEmpty()) {
return 0;
}
return new QLabel(text, parent);
}
PersonDetailsView::PersonDetailsView(QWidget *parent)
: QWidget(parent),
d_ptr(new PersonDetailsViewPrivate())
{
Q_D(PersonDetailsView);
d->m_mainLayout = new QFormLayout(this);
d->m_person = 0;
//create plugins
Q_FOREACH(KABC::Field *field, KABC::Field::allFields()) {
d->m_plugins << new CoreFieldsPlugin(field);
}
d->m_plugins << new EmailFieldsPlugin();
//TODO Sort plugins
}
PersonDetailsView::~PersonDetailsView()
{
Q_D(PersonDetailsView);
// qDeleteAll<AbstractFieldWidgetFactory>(d->m_plugins);
delete d_ptr;
}
void PersonDetailsView::setPerson(PersonData *person)
{
Q_D(PersonDetailsView);
if (!d->m_person) {
disconnect(d->m_person, SIGNAL(dataChanged()), this, SLOT(reload()));
}
d->m_person = person;
connect(d->m_person, SIGNAL(dataChanged()), this, SLOT(reload()));
reload();
}
// void PersonDetailsView::setPersonsModel(PersonsModel *model)
// {
// Q_D(PersonDetailsView);
// Q_FOREACH (AbstractPersonDetailsWidget *detailsWidget, d->m_detailWidgets) {
// detailsWidget->setPersonsModel(model);
// }
// }
void PersonDetailsView::reload()
{
Q_D(PersonDetailsView);
//delete everything currently in the layout
QLayoutItem *child;
while ((child = layout()->takeAt(0)) != 0) {
delete child->widget();
delete child;
}
Q_FOREACH(AbstractFieldWidgetFactory *widgetFactory, d->m_plugins) {
const QString label = widgetFactory->label() + ':';
QWidget *widget = widgetFactory->createDetailsWidget(d->m_person->person(), this);
if (widget) {
QFont font = widget->font();
font.setBold(true);
widget->setFont(font);
d->m_mainLayout->addRow(label, widget);
}
}
}
<|endoftext|> |
<commit_before>// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include "command_queue.h"
#include "anh/logger.h"
#include "anh/service/service_manager.h"
#include "swganh/app/swganh_kernel.h"
#include "swganh/command/base_swg_command.h"
#include "swganh/command/command_interface.h"
#include "swganh/command/command_service_interface.h"
#include "swganh/object/creature/creature.h"
#include "swganh/object/tangible/tangible.h"
#include "swganh/object/object_controller.h"
#include "command_service.h"
using pub14_core::command::CommandQueue;
using pub14_core::command::CommandService;
using swganh::command::BaseSwgCommand;
using swganh::command::CommandCallback;
using swganh::command::CommandInterface;
using swganh::object::creature::Creature;
using swganh::object::tangible::Tangible;
CommandQueue::CommandQueue(
swganh::app::SwganhKernel* kernel)
: kernel_(kernel)
, timer_(kernel->GetIoService())
, processing_(false)
, default_command_(nullptr)
, active_(kernel->GetIoService())
{
command_service_ = kernel->GetServiceManager()->GetService<CommandService>("CommandService");
}
CommandQueue::~CommandQueue()
{
timer_.cancel();
}
void CommandQueue::EnqueueCommand(const std::shared_ptr<CommandInterface>& command)
{
auto swg_command = std::static_pointer_cast<BaseSwgCommand>(command);
bool is_valid;
uint32_t error;
uint32_t action;
std::tie(is_valid, error, action) = command_service_->ValidateForEnqueue(swg_command.get());
if (is_valid)
{
if (swg_command->IsQueuedCommand())
{
{
boost::lock_guard<boost::mutex> queue_lg(queue_mutex_);
queue_.push(swg_command);
}
Notify();
}
else
{
ProcessCommand(swg_command);
}
}
else
{
command_service_->SendCommandQueueRemove(swg_command->GetController(), swg_command->GetActionCounter(), swg_command->GetDefaultTime(), error, action);
}
}
void CommandQueue::SetDefaultCommand(const std::shared_ptr<swganh::command::CommandInterface>& command)
{
default_command_ = std::static_pointer_cast<BaseSwgCommand>(command);
Notify();
}
void CommandQueue::ClearDefaultCommand()
{
default_command_ = nullptr;
}
bool CommandQueue::HasDefaultCommand()
{
return default_command_ != nullptr;
}
void CommandQueue::ProcessCommand(const std::shared_ptr<swganh::command::BaseSwgCommand>& command)
{
try {
bool is_valid;
uint32_t error;
uint32_t action;
std::tie(is_valid, error, action) = command_service_->ValidateForProcessing(command.get());
if (is_valid)
{
if (command->Validate())
{
auto callback = command->Run();
if (callback)
{
HandleCallback(*callback);
}
}
else
{
action = 1; // indicates a general error
}
}
command_service_->SendCommandQueueRemove(command->GetController(), command->GetActionCounter(), command->GetDefaultTime(), error, action);
} catch(const std::exception& e) {
LOG(warning) << "Error Processing Command: " << command->GetCommandName() << "\n" << e.what();
}
}
void CommandQueue::Notify()
{
boost::unique_lock<boost::mutex> process_lg(process_mutex_);
if (!processing_)
{
processing_ = true;
process_lg.unlock();
if (auto command = GetNextCommand())
{
ProcessCommand(command);
timer_.expires_from_now(boost::posix_time::milliseconds(static_cast<uint64_t>(2000)));
timer_.async_wait([this] (const boost::system::error_code& ec)
{
if (!ec && this)
{
{
boost::lock_guard<boost::mutex> lg(process_mutex_);
processing_ = false;
}
this->Notify();
}
});
}
else
{
process_lg.lock();
processing_ = false;
}
}
}
void CommandQueue::HandleCallback(std::shared_ptr<CommandCallback> callback)
{
active_.AsyncDelayed(boost::posix_time::milliseconds(callback->GetDelayTimeInMs()),
[this, callback] ()
{
auto new_callback = (*callback)();
if (new_callback)
{
HandleCallback(*new_callback);
}
});
}
std::shared_ptr<swganh::command::BaseSwgCommand> CommandQueue::GetNextCommand()
{
std::shared_ptr<BaseSwgCommand> command = nullptr;
{
boost::lock_guard<boost::mutex> queue_lg(queue_mutex_);
if (!queue_.empty())
{
command = queue_.top();
queue_.pop();
}
else
{
command = default_command_;
}
}
return command;
}
<commit_msg>Now uses the proper time for command execution length<commit_after>// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include "command_queue.h"
#include "anh/logger.h"
#include "anh/service/service_manager.h"
#include "swganh/app/swganh_kernel.h"
#include "swganh/command/base_swg_command.h"
#include "swganh/command/command_interface.h"
#include "swganh/command/command_service_interface.h"
#include "swganh/object/creature/creature.h"
#include "swganh/object/tangible/tangible.h"
#include "swganh/object/object_controller.h"
#include "command_service.h"
using pub14_core::command::CommandQueue;
using pub14_core::command::CommandService;
using swganh::command::BaseSwgCommand;
using swganh::command::CommandCallback;
using swganh::command::CommandInterface;
using swganh::object::creature::Creature;
using swganh::object::tangible::Tangible;
CommandQueue::CommandQueue(
swganh::app::SwganhKernel* kernel)
: kernel_(kernel)
, timer_(kernel->GetIoService())
, processing_(false)
, default_command_(nullptr)
, active_(kernel->GetIoService())
{
command_service_ = kernel->GetServiceManager()->GetService<CommandService>("CommandService");
}
CommandQueue::~CommandQueue()
{
timer_.cancel();
}
void CommandQueue::EnqueueCommand(const std::shared_ptr<CommandInterface>& command)
{
auto swg_command = std::static_pointer_cast<BaseSwgCommand>(command);
bool is_valid;
uint32_t error;
uint32_t action;
std::tie(is_valid, error, action) = command_service_->ValidateForEnqueue(swg_command.get());
if (is_valid)
{
if (swg_command->IsQueuedCommand())
{
{
boost::lock_guard<boost::mutex> queue_lg(queue_mutex_);
queue_.push(swg_command);
}
Notify();
}
else
{
ProcessCommand(swg_command);
}
}
else
{
command_service_->SendCommandQueueRemove(swg_command->GetController(), swg_command->GetActionCounter(), swg_command->GetDefaultTime(), error, action);
}
}
void CommandQueue::SetDefaultCommand(const std::shared_ptr<swganh::command::CommandInterface>& command)
{
default_command_ = std::static_pointer_cast<BaseSwgCommand>(command);
Notify();
}
void CommandQueue::ClearDefaultCommand()
{
default_command_ = nullptr;
}
bool CommandQueue::HasDefaultCommand()
{
return default_command_ != nullptr;
}
void CommandQueue::ProcessCommand(const std::shared_ptr<swganh::command::BaseSwgCommand>& command)
{
try {
bool is_valid;
uint32_t error;
uint32_t action;
std::tie(is_valid, error, action) = command_service_->ValidateForProcessing(command.get());
if (is_valid)
{
if (command->Validate())
{
auto callback = command->Run();
if (callback)
{
HandleCallback(*callback);
}
}
else
{
action = 1; // indicates a general error
}
}
command_service_->SendCommandQueueRemove(command->GetController(), command->GetActionCounter(), command->GetDefaultTime(), error, action);
} catch(const std::exception& e) {
LOG(warning) << "Error Processing Command: " << command->GetCommandName() << "\n" << e.what();
}
}
void CommandQueue::Notify()
{
boost::unique_lock<boost::mutex> process_lg(process_mutex_);
if (!processing_)
{
processing_ = true;
process_lg.unlock();
if (auto command = GetNextCommand())
{
ProcessCommand(command);
timer_.expires_from_now(boost::posix_time::milliseconds(static_cast<uint64_t>(command->GetDefaultTime() * 1000)));
timer_.async_wait([this] (const boost::system::error_code& ec)
{
if (!ec && this)
{
{
boost::lock_guard<boost::mutex> lg(process_mutex_);
processing_ = false;
}
this->Notify();
}
});
}
else
{
process_lg.lock();
processing_ = false;
}
}
}
void CommandQueue::HandleCallback(std::shared_ptr<CommandCallback> callback)
{
active_.AsyncDelayed(boost::posix_time::milliseconds(callback->GetDelayTimeInMs()),
[this, callback] ()
{
auto new_callback = (*callback)();
if (new_callback)
{
HandleCallback(*new_callback);
}
});
}
std::shared_ptr<swganh::command::BaseSwgCommand> CommandQueue::GetNextCommand()
{
std::shared_ptr<BaseSwgCommand> command = nullptr;
{
boost::lock_guard<boost::mutex> queue_lg(queue_mutex_);
if (!queue_.empty())
{
command = queue_.top();
queue_.pop();
}
else
{
command = default_command_;
}
}
return command;
}
<|endoftext|> |
<commit_before>// This file is part of the "x0" project
// (c) 2009-2015 Christian Parpart <https://github.com/christianparpart>
//
// x0 is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License v3.0.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <xzero/http/hpack/Generator.h>
#include <xzero/http/hpack/StaticTable.h>
#include <xzero/http/hpack/DynamicTable.h>
#include <xzero/http/hpack/Huffman.h>
#include <xzero/http/HeaderFieldList.h>
#include <xzero/http/HeaderField.h>
#include <xzero/Buffer.h>
#include <xzero/logging.h>
extern std::string tob(uint8_t value);
namespace xzero {
namespace http {
namespace hpack {
#if !defined(NDEBUG)
#define TRACE(msg...) logTrace("http.hpack.Generator", msg)
#else
#define TRACE(msg...) do {} while (0)
#endif
//! 2^n, mask given bit, rest cleared
#define BIT(n) (1 << (n))
//! least significant bits (from 0) to n set, rest cleared
#define maskLSB(n) ((1 << (n)) - 1)
Generator::Generator(size_t maxSize)
: dynamicTable_(maxSize),
headerBlock_() {
headerBlock_.reserve(maxSize);
}
void Generator::setMaxSize(size_t maxSize) {
headerBlock_.reserve(maxSize);
dynamicTable_.setMaxSize(maxSize);
encodeInt(1, 5, maxSize);
}
void Generator::clear() {
headerBlock_.clear();
}
void Generator::reset() {
dynamicTable_.clear();
headerBlock_.clear();
// set header table size to 0 (for full eviction)
encodeInt(1, 5, (size_t) 0);
// now set it back to some meaningful value
encodeInt(1, 5, dynamicTable_.maxSize());
}
void Generator::generateHeaders(const HeaderFieldList& fields) {
for (const HeaderField& field: fields) {
generateHeader(field);
}
}
void Generator::generateHeader(const HeaderField& field) {
generateHeader(field.name(), field.value(), field.isSensitive());
}
void Generator::generateHeader(const std::string& name,
const std::string& value,
bool sensitive) {
// search in static table
bool nameValueMatch;
size_t index = StaticTable::find(name, value, &nameValueMatch);
if (index != StaticTable::npos) {
encodeHeaderIndexed(index + 1, nameValueMatch, name, value, sensitive);
return;
}
// search in dynamic table
index = dynamicTable_.find(name, value, &nameValueMatch);
if (index != DynamicTable::npos) {
encodeHeaderIndexed(index + StaticTable::length(),
nameValueMatch, name, value, sensitive);
return;
}
const size_t fieldSize = name.size() + value.size() +
DynamicTable::HeaderFieldOverheadSize;
if (sensitive) {
// (6.2.3) Literal Header Field Never Indexed (new name)
write8(1 << 4);
encodeString(name);
encodeString(value);
} else if (fieldSize < dynamicTable_.maxSize()) {
// (6.2.1) Literal Header Field with Incremental Indexing (new name)
dynamicTable_.add(name, value);
write8(1 << 6);
encodeString(name);
encodeString(value);
} else {
// (6.2.2) Literal Header Field without Indexing (new name)
write8(0);
encodeString(name);
encodeString(value);
}
}
void Generator::encodeHeaderIndexed(size_t index,
bool nameValueMatch,
const std::string& name,
const std::string& value,
bool sensitive) {
const size_t fieldSize = name.size() + value.size() +
DynamicTable::HeaderFieldOverheadSize;
if (nameValueMatch) {
// (6.1) indexed header field
encodeInt(1, 7, index);
} else if (!sensitive) {
// can be indexed
if (fieldSize < dynamicTable_.maxSize()) {
// (6.2.1) indexed name, literal value, indexable
dynamicTable_.add(name, value);
encodeInt(1, 6, index);
encodeString(value);
} else {
// (6.2.2) indexed name, literal value, non-indexable
encodeInt(0, 4, index);
encodeString(value);
}
} else {
// (6.2.3) indexed name, literal value, never index
encodeInt(1, 4, index);
encodeString(value);
}
}
void Generator::encodeInt(uint8_t suffix, uint8_t prefixBits, uint64_t value) {
headerBlock_.reserve(headerBlock_.size() + 8);
unsigned char* output = (unsigned char*) headerBlock_.end();
size_t n = encodeInt(suffix, prefixBits, value, output);
headerBlock_.resize(headerBlock_.size() + n);
}
void Generator::encodeString(const std::string& value, bool compressed) {
// (5.2) String Literal Representation
if (compressed && Huffman::encodeLength(value) < value.size()) {
std::string smaller = Huffman::encode(value);
encodeInt(1, 7, smaller.size());
headerBlock_.push_back(smaller);
} else {
// Huffman encoding disabled
encodeInt(0, 7, value.size());
headerBlock_.push_back(value);
}
}
size_t Generator::encodeInt(uint8_t suffix,
uint8_t prefixBits,
uint64_t value,
unsigned char* output) {
assert(prefixBits >= 1 && prefixBits <= 8);
const unsigned maxValue = maskLSB(prefixBits);
if (value < maxValue) {
*output = (suffix << prefixBits) | static_cast<uint8_t>(value);
return 1;
}
*output++ = maxValue;
value -= maxValue;
size_t n = 2;
while (value > maskLSB(7)) {
const unsigned char byte = BIT(7) | (value & maskLSB(7));
*output++ = byte;
value >>= 7;
n++;
}
*output = static_cast<unsigned char>(value);
return n;
}
} // namespace hpack
} // namespace http
} // namespace xzero
<commit_msg>[hpack] Generator: minor refactor<commit_after>// This file is part of the "x0" project
// (c) 2009-2015 Christian Parpart <https://github.com/christianparpart>
//
// x0 is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License v3.0.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <xzero/http/hpack/Generator.h>
#include <xzero/http/hpack/StaticTable.h>
#include <xzero/http/hpack/DynamicTable.h>
#include <xzero/http/hpack/Huffman.h>
#include <xzero/http/HeaderFieldList.h>
#include <xzero/http/HeaderField.h>
#include <xzero/Buffer.h>
#include <xzero/logging.h>
extern std::string tob(uint8_t value);
namespace xzero {
namespace http {
namespace hpack {
#if !defined(NDEBUG)
#define TRACE(msg...) logTrace("http.hpack.Generator", msg)
#else
#define TRACE(msg...) do {} while (0)
#endif
//! 2^n, mask given bit, rest cleared
#define BIT(n) (1 << (n))
//! least significant bits (from 0) to n set, rest cleared
#define maskLSB(n) ((1 << (n)) - 1)
Generator::Generator(size_t maxSize)
: dynamicTable_(maxSize),
headerBlock_() {
headerBlock_.reserve(maxSize);
}
void Generator::setMaxSize(size_t maxSize) {
headerBlock_.reserve(maxSize);
dynamicTable_.setMaxSize(maxSize);
encodeInt(1, 5, maxSize);
}
void Generator::clear() {
headerBlock_.clear();
}
void Generator::reset() {
dynamicTable_.clear();
headerBlock_.clear();
// set header table size to 0 (for full eviction)
encodeInt(1, 5, (size_t) 0);
// now set it back to some meaningful value
encodeInt(1, 5, dynamicTable_.maxSize());
}
void Generator::generateHeaders(const HeaderFieldList& fields) {
for (const HeaderField& field: fields) {
generateHeader(field);
}
}
void Generator::generateHeader(const HeaderField& field) {
generateHeader(field.name(), field.value(), field.isSensitive());
}
void Generator::generateHeader(const std::string& name,
const std::string& value,
bool sensitive) {
// search in static table
bool nameValueMatch;
size_t index = StaticTable::find(name, value, &nameValueMatch);
if (index != StaticTable::npos) {
encodeHeaderIndexed(index + 1, nameValueMatch, name, value, sensitive);
return;
}
// search in dynamic table
index = dynamicTable_.find(name, value, &nameValueMatch);
if (index != DynamicTable::npos) {
encodeHeaderIndexed(index + StaticTable::length(),
nameValueMatch, name, value, sensitive);
return;
}
const size_t fieldSize = name.size() + value.size() +
DynamicTable::HeaderFieldOverheadSize;
if (sensitive) {
// (6.2.3) Literal Header Field Never Indexed (new name)
write8(1 << 4);
encodeString(name);
encodeString(value);
} else if (fieldSize < dynamicTable_.maxSize()) {
// (6.2.1) Literal Header Field with Incremental Indexing (new name)
dynamicTable_.add(name, value);
write8(1 << 6);
encodeString(name);
encodeString(value);
} else {
// (6.2.2) Literal Header Field without Indexing (new name)
write8(0);
encodeString(name);
encodeString(value);
}
}
void Generator::encodeHeaderIndexed(size_t index,
bool nameValueMatch,
const std::string& name,
const std::string& value,
bool sensitive) {
const size_t fieldSize = name.size() + value.size() +
DynamicTable::HeaderFieldOverheadSize;
if (nameValueMatch) {
// (6.1) indexed header field
encodeInt(1, 7, index);
} else if (sensitive) {
// (6.2.3) indexed name, literal value, never index
encodeInt(1, 4, index);
encodeString(value);
} else if (fieldSize < dynamicTable_.maxSize()) {
// (6.2.1) indexed name, literal value, indexable
dynamicTable_.add(name, value);
encodeInt(1, 6, index);
encodeString(value);
} else {
// (6.2.2) indexed name, literal value, non-indexable
encodeInt(0, 4, index);
encodeString(value);
}
}
void Generator::encodeInt(uint8_t suffix, uint8_t prefixBits, uint64_t value) {
headerBlock_.reserve(headerBlock_.size() + 8);
unsigned char* output = (unsigned char*) headerBlock_.end();
size_t n = encodeInt(suffix, prefixBits, value, output);
headerBlock_.resize(headerBlock_.size() + n);
}
void Generator::encodeString(const std::string& value, bool compressed) {
// (5.2) String Literal Representation
if (compressed && Huffman::encodeLength(value) < value.size()) {
std::string smaller = Huffman::encode(value);
encodeInt(1, 7, smaller.size());
headerBlock_.push_back(smaller);
} else {
// Huffman encoding disabled
encodeInt(0, 7, value.size());
headerBlock_.push_back(value);
}
}
size_t Generator::encodeInt(uint8_t suffix,
uint8_t prefixBits,
uint64_t value,
unsigned char* output) {
assert(prefixBits >= 1 && prefixBits <= 8);
const unsigned maxValue = maskLSB(prefixBits);
if (value < maxValue) {
*output = (suffix << prefixBits) | static_cast<uint8_t>(value);
return 1;
}
*output++ = maxValue;
value -= maxValue;
size_t n = 2;
while (value > maskLSB(7)) {
const unsigned char byte = BIT(7) | (value & maskLSB(7));
*output++ = byte;
value >>= 7;
n++;
}
*output = static_cast<unsigned char>(value);
return n;
}
} // namespace hpack
} // namespace http
} // namespace xzero
<|endoftext|> |
<commit_before>#include "iobservable.h"
namespace gg
{
IObservable::~IObservable()
{
}
void IObservable::attach(IObserver & observer)
{
std::lock_guard<std::mutex> lock_guard(_observers_lock);
if (not attached(observer))
{
_observers.push_back(observer);
if (not attached(observer))
throw ObserverError("Could not attach observer");
}
}
void IObservable::detach(IObserver & observer)
{
std::lock_guard<std::mutex> lock_guard(_observers_lock);
_observers.erase(std::find_if(
_observers.begin(),
_observers.end(),
[&](const std::reference_wrapper<IObserver> &o)
{
return &(o.get()) == &observer;
}),
_observers.end());
if (attached(observer))
throw ObserverError("Could not detach observer");
}
void IObservable::notify(VideoFrame & frame) noexcept
{
std::lock_guard<std::mutex> lock_guard(_observers_lock);
for (IObserver & observer : _observers)
{
observer.update(frame);
}
}
bool IObservable::attached(const IObserver & observer) const noexcept
{
return std::find_if(
_observers.begin(),
_observers.end(),
[&](const std::reference_wrapper<IObserver> &o)
{
return &(o.get()) == &observer;
}) != _observers.end();
}
}
<commit_msg>Issue #86: added note to IObservable code about duplicate lambda<commit_after>#include "iobservable.h"
namespace gg
{
IObservable::~IObservable()
{
}
void IObservable::attach(IObserver & observer)
{
std::lock_guard<std::mutex> lock_guard(_observers_lock);
if (not attached(observer))
{
_observers.push_back(observer);
if (not attached(observer))
throw ObserverError("Could not attach observer");
}
}
void IObservable::detach(IObserver & observer)
{
std::lock_guard<std::mutex> lock_guard(_observers_lock);
_observers.erase(std::find_if(
_observers.begin(),
_observers.end(),
/* Note that this lambda is a duplicate of the one
* used in the attach function below.
*/
[&](const std::reference_wrapper<IObserver> &o)
{
return &(o.get()) == &observer;
}),
_observers.end());
if (attached(observer))
throw ObserverError("Could not detach observer");
}
void IObservable::notify(VideoFrame & frame) noexcept
{
std::lock_guard<std::mutex> lock_guard(_observers_lock);
for (IObserver & observer : _observers)
{
observer.update(frame);
}
}
bool IObservable::attached(const IObserver & observer) const noexcept
{
return std::find_if(
_observers.begin(),
_observers.end(),
/* Note that this lambda is a duplicate of the one
* used in the detach function above.
*/
[&](const std::reference_wrapper<IObserver> &o)
{
return &(o.get()) == &observer;
}) != _observers.end();
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: VTypeDef.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: oj $ $Date: 2000-10-30 07:21:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_SDBCX_TYPEDEF_HXX_
#define _CONNECTIVITY_SDBCX_TYPEDEF_HXX_
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
namespace connectivity
{
namespace sdbcx
{
typedef ::cppu::WeakComponentImplHelper3< ::com::sun::star::sdbcx::XColumnsSupplier,
::com::sun::star::container::XNamed,
::com::sun::star::lang::XServiceInfo> ODescriptor_BASE;
}
}
#endif // _CONNECTIVITY_SDBCX_TYPEDEF_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.362); FILE MERGED 2005/09/05 17:22:45 rt 1.2.362.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: VTypeDef.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 05:05:47 $
*
* 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 _CONNECTIVITY_SDBCX_TYPEDEF_HXX_
#define _CONNECTIVITY_SDBCX_TYPEDEF_HXX_
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
namespace connectivity
{
namespace sdbcx
{
typedef ::cppu::WeakComponentImplHelper3< ::com::sun::star::sdbcx::XColumnsSupplier,
::com::sun::star::container::XNamed,
::com::sun::star::lang::XServiceInfo> ODescriptor_BASE;
}
}
#endif // _CONNECTIVITY_SDBCX_TYPEDEF_HXX_
<|endoftext|> |
<commit_before>/*
* 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.
* Modified by Cloudius Systems.
* Copyright 2015 Cloudius Systems.
*/
#include "streaming/stream_result_future.hh"
#include "streaming/stream_manager.hh"
#include "log.hh"
namespace streaming {
extern logging::logger sslog;
void stream_result_future::init(UUID plan_id_, sstring description_, std::vector<stream_event_handler*> listeners_, shared_ptr<stream_coordinator> coordinator_) {
auto future = create_and_register(plan_id_, description_, coordinator_);
for (auto& listener : listeners_) {
future->add_event_listener(listener);
}
sslog.info("[Stream #{}] Executing streaming plan for {}", plan_id_, description_);
// Initialize and start all sessions
for (auto& session : coordinator_->get_all_stream_sessions()) {
session->init(future);
}
coordinator_->connect_all_stream_sessions();
}
void stream_result_future::init_receiving_side(int session_index, UUID plan_id,
sstring description, inet_address from, bool keep_ss_table_level) {
auto& sm = get_local_stream_manager();
auto f = sm.get_receiving_stream(plan_id);
if (f == nullptr) {
sslog.info("[Stream #{} ID#{}] Creating new streaming plan for {}", plan_id, session_index, description);
// The main reason we create a StreamResultFuture on the receiving side is for JMX exposure.
// TODO: stream_result_future needs a ref to stream_coordinator.
sm.register_receiving(make_shared<stream_result_future>(plan_id, description, keep_ss_table_level));
}
sslog.info("[Stream #{}, ID#{}] Received streaming plan for {}", plan_id, session_index, description);
}
void stream_result_future::handle_session_prepared(shared_ptr<stream_session> session) {
auto si = session->get_session_info();
sslog.info("[Stream #{} ID#{}] Prepare completed. Receiving {} files({} bytes), sending {} files({} bytes)",
session->plan_id(),
session->session_index(),
si.get_total_files_to_receive(),
si.get_total_size_to_receive(),
si.get_total_files_to_send(),
si.get_total_size_to_send());
auto event = session_prepared_event(plan_id, si);
_coordinator->add_session_info(std::move(si));
fire_stream_event(std::move(event));
}
void stream_result_future::handle_session_complete(shared_ptr<stream_session> session) {
sslog.info("[Stream #{}] Session with {} is complete", session->plan_id(), session->peer);
auto event = session_complete_event(session);
fire_stream_event(std::move(event));
auto si = session->get_session_info();
_coordinator->add_session_info(std::move(si));
maybe_complete();
}
template <typename Event>
void stream_result_future::fire_stream_event(Event event) {
// delegate to listener
for (auto listener : _event_listeners) {
listener->handle_stream_event(std::move(event));
}
}
void stream_result_future::maybe_complete() {
if (!_coordinator->has_active_sessions()) {
auto final_state = get_current_state();
if (final_state.has_failed_session()) {
sslog.warn("[Stream #{}] Stream failed", plan_id);
// FIXME: setException(new StreamException(finalState, "Stream failed"));
} else {
sslog.info("[Stream #{}] All sessions completed", plan_id);
// FIXME: set(finalState);
}
}
}
stream_state stream_result_future::get_current_state() {
return stream_state(plan_id, description, _coordinator->get_all_session_info());
}
void stream_result_future::handle_progress(progress_info progress) {
_coordinator->update_progress(progress);
fire_stream_event(progress_event(plan_id, std::move(progress)));
}
shared_ptr<stream_result_future> stream_result_future::create_and_register(UUID plan_id_, sstring description_, shared_ptr<stream_coordinator> coordinator_) {
auto future = make_shared<stream_result_future>(plan_id_, description_, coordinator_);
auto& sm = get_local_stream_manager();
sm.register_receiving(future);
return future;
}
} // namespace streaming
<commit_msg>streaming: Fix a logger printout<commit_after>/*
* 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.
* Modified by Cloudius Systems.
* Copyright 2015 Cloudius Systems.
*/
#include "streaming/stream_result_future.hh"
#include "streaming/stream_manager.hh"
#include "log.hh"
namespace streaming {
extern logging::logger sslog;
void stream_result_future::init(UUID plan_id_, sstring description_, std::vector<stream_event_handler*> listeners_, shared_ptr<stream_coordinator> coordinator_) {
auto future = create_and_register(plan_id_, description_, coordinator_);
for (auto& listener : listeners_) {
future->add_event_listener(listener);
}
sslog.info("[Stream #{}] Executing streaming plan for {}", plan_id_, description_);
// Initialize and start all sessions
for (auto& session : coordinator_->get_all_stream_sessions()) {
session->init(future);
}
coordinator_->connect_all_stream_sessions();
}
void stream_result_future::init_receiving_side(int session_index, UUID plan_id,
sstring description, inet_address from, bool keep_ss_table_level) {
auto& sm = get_local_stream_manager();
auto f = sm.get_receiving_stream(plan_id);
if (f == nullptr) {
sslog.info("[Stream #{} ID#{}] Creating new streaming plan for {}", plan_id, session_index, description);
// The main reason we create a StreamResultFuture on the receiving side is for JMX exposure.
// TODO: stream_result_future needs a ref to stream_coordinator.
sm.register_receiving(make_shared<stream_result_future>(plan_id, description, keep_ss_table_level));
}
sslog.info("[Stream #{} ID#{}] Received streaming plan for {}", plan_id, session_index, description);
}
void stream_result_future::handle_session_prepared(shared_ptr<stream_session> session) {
auto si = session->get_session_info();
sslog.info("[Stream #{} ID#{}] Prepare completed. Receiving {} files({} bytes), sending {} files({} bytes)",
session->plan_id(),
session->session_index(),
si.get_total_files_to_receive(),
si.get_total_size_to_receive(),
si.get_total_files_to_send(),
si.get_total_size_to_send());
auto event = session_prepared_event(plan_id, si);
_coordinator->add_session_info(std::move(si));
fire_stream_event(std::move(event));
}
void stream_result_future::handle_session_complete(shared_ptr<stream_session> session) {
sslog.info("[Stream #{}] Session with {} is complete", session->plan_id(), session->peer);
auto event = session_complete_event(session);
fire_stream_event(std::move(event));
auto si = session->get_session_info();
_coordinator->add_session_info(std::move(si));
maybe_complete();
}
template <typename Event>
void stream_result_future::fire_stream_event(Event event) {
// delegate to listener
for (auto listener : _event_listeners) {
listener->handle_stream_event(std::move(event));
}
}
void stream_result_future::maybe_complete() {
if (!_coordinator->has_active_sessions()) {
auto final_state = get_current_state();
if (final_state.has_failed_session()) {
sslog.warn("[Stream #{}] Stream failed", plan_id);
// FIXME: setException(new StreamException(finalState, "Stream failed"));
} else {
sslog.info("[Stream #{}] All sessions completed", plan_id);
// FIXME: set(finalState);
}
}
}
stream_state stream_result_future::get_current_state() {
return stream_state(plan_id, description, _coordinator->get_all_session_info());
}
void stream_result_future::handle_progress(progress_info progress) {
_coordinator->update_progress(progress);
fire_stream_event(progress_event(plan_id, std::move(progress)));
}
shared_ptr<stream_result_future> stream_result_future::create_and_register(UUID plan_id_, sstring description_, shared_ptr<stream_coordinator> coordinator_) {
auto future = make_shared<stream_result_future>(plan_id_, description_, coordinator_);
auto& sm = get_local_stream_manager();
sm.register_receiving(future);
return future;
}
} // namespace streaming
<|endoftext|> |
<commit_before>#include "qgeoroutingmanagerenginegooglemaps.h"
#include "qgeoroutereplygooglemaps.h"
#include <QtCore/QUrlQuery>
#include <QtCore/QDebug>
QGeoRoutingManagerEngineGooglemaps::QGeoRoutingManagerEngineGooglemaps(const QVariantMap ¶meters,
QGeoServiceProvider::Error *error,
QString *errorString)
: QGeoRoutingManagerEngine(parameters), m_networkManager(new QNetworkAccessManager(this))
{
if (parameters.contains(QStringLiteral("googlemaps.useragent")))
m_userAgent = parameters.value(QStringLiteral("googlemaps.useragent")).toString().toLatin1();
else
m_userAgent = "Qt Location based application";
m_urlPrefix = QStringLiteral("http://maps.googleapis.com/maps/api/directions/json");
m_apiKey = parameters.value(QStringLiteral("googlemaps.route.apikey")).toString();
*error = QGeoServiceProvider::NoError;
errorString->clear();
}
QGeoRoutingManagerEngineGooglemaps::~QGeoRoutingManagerEngineGooglemaps()
{
}
QGeoRouteReply* QGeoRoutingManagerEngineGooglemaps::calculateRoute(const QGeoRouteRequest &request)
{
QNetworkRequest networkRequest;
networkRequest.setRawHeader("User-Agent", m_userAgent);
if (m_apiKey.isEmpty()) {
QGeoRouteReply *reply = new QGeoRouteReply(QGeoRouteReply::UnsupportedOptionError, "Set googlemaps.route.apikey with google maps application key, supporting directions", this);
emit error(reply, reply->error(), reply->errorString());
return reply;
}
QUrl url(m_urlPrefix);
QUrlQuery query;
QStringList waypoints;
foreach (const QGeoCoordinate &c, request.waypoints()) {
QString scoord = QString::number(c.latitude()) + QLatin1Char(',') + QString::number(c.longitude());
if (c == request.waypoints().first())
query.addQueryItem(QStringLiteral("origin"), scoord);
else if (c == request.waypoints().last())
query.addQueryItem(QStringLiteral("destination"), scoord);
else
waypoints.append(scoord);
}
if (waypoints.size() > 0)
query.addQueryItem(QStringLiteral("waypoints"), waypoints.join("|"));
if (request.travelModes() & QGeoRouteRequest::CarTravel)
query.addQueryItem(QStringLiteral("mode"), QStringLiteral("driving"));
if (request.travelModes() & QGeoRouteRequest::PedestrianTravel)
query.addQueryItem(QStringLiteral("mode"), QStringLiteral("walking"));
if (request.travelModes() & QGeoRouteRequest::BicycleTravel)
query.addQueryItem(QStringLiteral("mode"), QStringLiteral("bicycling"));
if (request.travelModes() & QGeoRouteRequest::PublicTransitTravel)
query.addQueryItem(QStringLiteral("mode"), QStringLiteral("transit"));
if (request.numberAlternativeRoutes() > 1)
query.addQueryItem(QStringLiteral("alternatives"), QStringLiteral("true"));
QStringList avoidList;
foreach (QGeoRouteRequest::FeatureType routeFeature, request.featureTypes()) {
QGeoRouteRequest::FeatureWeight weigth = request.featureWeight(routeFeature);
if (weigth == QGeoRouteRequest::AvoidFeatureWeight
|| weigth == QGeoRouteRequest::DisallowFeatureWeight) {
if (routeFeature == QGeoRouteRequest::TollFeature)
avoidList.append(QStringLiteral("tolls"));
if (routeFeature == QGeoRouteRequest::HighwayFeature)
avoidList.append(QStringLiteral("highways"));
if (routeFeature == QGeoRouteRequest::FerryFeature)
avoidList.append(QStringLiteral("ferries"));
}
}
if (avoidList.size() > 0)
query.addQueryItem(QStringLiteral("avoid"), avoidList.join("|"));
if (QLocale::MetricSystem == measurementSystem())
query.addQueryItem(QStringLiteral("units"), QStringLiteral("metric"));
else
query.addQueryItem(QStringLiteral("units"), QStringLiteral("imperial"));
const QLocale loc(locale());
if (QLocale::C != loc.language() && QLocale::AnyLanguage != loc.language()) {
query.addQueryItem(QStringLiteral("language"), loc.name());
}
query.addQueryItem(QStringLiteral("key"), m_apiKey);
url.setQuery(query);
qDebug() << url;
networkRequest.setUrl(url);
QNetworkReply *reply = m_networkManager->get(networkRequest);
QGeoRouteReplyGooglemaps *routeReply = new QGeoRouteReplyGooglemaps(reply, request, this);
connect(routeReply, SIGNAL(finished()), this, SLOT(replyFinished()));
connect(routeReply, SIGNAL(error(QGeoRouteReply::Error,QString)),
this, SLOT(replyError(QGeoRouteReply::Error,QString)));
return routeReply;
}
void QGeoRoutingManagerEngineGooglemaps::replyFinished()
{
QGeoRouteReply *reply = qobject_cast<QGeoRouteReply *>(sender());
if (reply)
emit finished(reply);
}
void QGeoRoutingManagerEngineGooglemaps::replyError(QGeoRouteReply::Error errorCode,
const QString &errorString)
{
QGeoRouteReply *reply = qobject_cast<QGeoRouteReply *>(sender());
if (reply)
emit error(reply, errorCode, errorString);
}
<commit_msg>Use https protocol for requests<commit_after>#include "qgeoroutingmanagerenginegooglemaps.h"
#include "qgeoroutereplygooglemaps.h"
#include <QtCore/QUrlQuery>
#include <QtCore/QDebug>
QGeoRoutingManagerEngineGooglemaps::QGeoRoutingManagerEngineGooglemaps(const QVariantMap ¶meters,
QGeoServiceProvider::Error *error,
QString *errorString)
: QGeoRoutingManagerEngine(parameters), m_networkManager(new QNetworkAccessManager(this))
{
if (parameters.contains(QStringLiteral("googlemaps.useragent")))
m_userAgent = parameters.value(QStringLiteral("googlemaps.useragent")).toString().toLatin1();
else
m_userAgent = "Qt Location based application";
m_urlPrefix = QStringLiteral("https://maps.googleapis.com/maps/api/directions/json");
m_apiKey = parameters.value(QStringLiteral("googlemaps.route.apikey")).toString();
*error = QGeoServiceProvider::NoError;
errorString->clear();
}
QGeoRoutingManagerEngineGooglemaps::~QGeoRoutingManagerEngineGooglemaps()
{
}
QGeoRouteReply* QGeoRoutingManagerEngineGooglemaps::calculateRoute(const QGeoRouteRequest &request)
{
QNetworkRequest networkRequest;
networkRequest.setRawHeader("User-Agent", m_userAgent);
if (m_apiKey.isEmpty()) {
QGeoRouteReply *reply = new QGeoRouteReply(QGeoRouteReply::UnsupportedOptionError, "Set googlemaps.route.apikey with google maps application key, supporting directions", this);
emit error(reply, reply->error(), reply->errorString());
return reply;
}
QUrl url(m_urlPrefix);
QUrlQuery query;
QStringList waypoints;
foreach (const QGeoCoordinate &c, request.waypoints()) {
QString scoord = QString::number(c.latitude()) + QLatin1Char(',') + QString::number(c.longitude());
if (c == request.waypoints().first())
query.addQueryItem(QStringLiteral("origin"), scoord);
else if (c == request.waypoints().last())
query.addQueryItem(QStringLiteral("destination"), scoord);
else
waypoints.append(scoord);
}
if (waypoints.size() > 0)
query.addQueryItem(QStringLiteral("waypoints"), waypoints.join("|"));
if (request.travelModes() & QGeoRouteRequest::CarTravel)
query.addQueryItem(QStringLiteral("mode"), QStringLiteral("driving"));
if (request.travelModes() & QGeoRouteRequest::PedestrianTravel)
query.addQueryItem(QStringLiteral("mode"), QStringLiteral("walking"));
if (request.travelModes() & QGeoRouteRequest::BicycleTravel)
query.addQueryItem(QStringLiteral("mode"), QStringLiteral("bicycling"));
if (request.travelModes() & QGeoRouteRequest::PublicTransitTravel)
query.addQueryItem(QStringLiteral("mode"), QStringLiteral("transit"));
if (request.numberAlternativeRoutes() > 1)
query.addQueryItem(QStringLiteral("alternatives"), QStringLiteral("true"));
QStringList avoidList;
foreach (QGeoRouteRequest::FeatureType routeFeature, request.featureTypes()) {
QGeoRouteRequest::FeatureWeight weigth = request.featureWeight(routeFeature);
if (weigth == QGeoRouteRequest::AvoidFeatureWeight
|| weigth == QGeoRouteRequest::DisallowFeatureWeight) {
if (routeFeature == QGeoRouteRequest::TollFeature)
avoidList.append(QStringLiteral("tolls"));
if (routeFeature == QGeoRouteRequest::HighwayFeature)
avoidList.append(QStringLiteral("highways"));
if (routeFeature == QGeoRouteRequest::FerryFeature)
avoidList.append(QStringLiteral("ferries"));
}
}
if (avoidList.size() > 0)
query.addQueryItem(QStringLiteral("avoid"), avoidList.join("|"));
if (QLocale::MetricSystem == measurementSystem())
query.addQueryItem(QStringLiteral("units"), QStringLiteral("metric"));
else
query.addQueryItem(QStringLiteral("units"), QStringLiteral("imperial"));
const QLocale loc(locale());
if (QLocale::C != loc.language() && QLocale::AnyLanguage != loc.language()) {
query.addQueryItem(QStringLiteral("language"), loc.name());
}
query.addQueryItem(QStringLiteral("key"), m_apiKey);
url.setQuery(query);
qDebug() << url;
networkRequest.setUrl(url);
QNetworkReply *reply = m_networkManager->get(networkRequest);
QGeoRouteReplyGooglemaps *routeReply = new QGeoRouteReplyGooglemaps(reply, request, this);
connect(routeReply, SIGNAL(finished()), this, SLOT(replyFinished()));
connect(routeReply, SIGNAL(error(QGeoRouteReply::Error,QString)),
this, SLOT(replyError(QGeoRouteReply::Error,QString)));
return routeReply;
}
void QGeoRoutingManagerEngineGooglemaps::replyFinished()
{
QGeoRouteReply *reply = qobject_cast<QGeoRouteReply *>(sender());
if (reply)
emit finished(reply);
}
void QGeoRoutingManagerEngineGooglemaps::replyError(QGeoRouteReply::Error errorCode,
const QString &errorString)
{
QGeoRouteReply *reply = qobject_cast<QGeoRouteReply *>(sender());
if (reply)
emit error(reply, errorCode, errorString);
}
<|endoftext|> |
<commit_before># ifndef CPPAD_CORE_ABS_NORMAL_HPP
# define CPPAD_CORE_ABS_NORMAL_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Eclipse Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin abs_normal$$
$spell
Andreas Griewank
Jens-Uwe Bernt
Manuel Radons
Tom Streubel
const
$$
$latex \newcommand{\B}[1]{ {\bf #1} }$$
$section Create An Abs-normal Representation of a Function$$
$head Under Construction$$
This is an in-progress design, and does not yet have an implementation.
$head Syntax$$
$icode%g%.abs_normal(%f%)%$$
$head Reference$$
Andreas Griewank, Jens-Uwe Bernt, Manuel Radons, Tom Streubel,
$italic Solving piecewise linear systems in abs-normal form$$,
Linear Algebra and its Applications,
vol. 471 (2015), pages 500-530.
$head f$$
The object $icode f$$ has prototype
$codei%
const ADFun<%Base%>& %f%
%$$
It represents a function $latex f : \B{R}^n \rightarrow \B{R}^m$$.
We assume that the only non-smooth terms in the representation are
absolute value functions and use $latex s \in \B{Z}_+$$
to represent the number of these terms.
$head g$$
The object $icode g$$ has prototype
$codei%
ADFun<%Base%> %g%
%$$
The initial function representation in $icode g$$ is lost.
Upon return it represents the smooth function
$latex g : \B{R}^{n + s} \rightarrow \B{R}^{s + m}$$ is defined by
$latex \[
g( x , u )
=
\left[ \begin{array}{c} z(x, u) \\ y(x, u) \end{array} \right]
\] $$
were $latex z(x, u)$$ and $latex y(x, u)$$ are defined below.
$subhead a(x)$$
Let $latex \zeta_0 ( x )$$
denote the argument for the first absolute value term in $latex f(x)$$,
$latex \zeta_1 ( x , |\zeta_0 (x)| )$$ for the second term, and so on.
For $latex i = 0 , \ldots , {s-1}$$ define
$latex \[
a_i (x)
=
| \zeta_i | \left[ x, a_0 (x) , \ldots , a_{i-1} (x) \right]
\] $$
$subhead z(x, u)$$
Define the smooth function
$latex z : \B{R}^{n + s} \rightarrow \B{R}^s$$ by
$latex \[
z_i ( x , u ) = \zeta_i ( x , u_0 , \ldots , u_{i-1} )
\] $$
$subhead y(x, u)$$
We define
$latex y : \B{R}^{n + s} \rightarrow \B{R}^m$$ as the smooth function
such that $latex y( x , u ) = f(x)$$ whenever $latex u = a(x)$$.
$head Abs-normal Approximation$$
Suppose we are given a point $latex x \in \B{R}^n$$,
and an increment $latex \Delta x$$,
and define
$latex u = a(x)$$,
$latex \Delta u = a( x + \Delta x) - a(x)$$.
$latex \[
\begin{array}{rcl}
z_i ( x + \Delta x, u + \Delta u )
& = &
z_i (x, u)
+ \partial_x z_i (x, u) \Delta x
+ \partial_u z_i (x, u) \Delta u
+ o( \Delta x^2 )
\end{array}
\] $$
Now the partial of $latex z_i$$ with respect to $latex u_j$$ is zero
for $latex i \leq j$$. It follows that
$latex \[
\begin{array}{rcl}
z_i ( x + \Delta x, u + \Delta u )
& = &
z_i (x, u)
+ \partial_x z_i (x, u) \Delta x
+ \sum_{j < i} \partial_{u(j)} z_i (x, u) \Delta u_j
+ o( \Delta x^2 )
\\
a_i ( x + \Delta x )
& = &
\left| z_i (x, u)
+ \partial_x z_i (x, u) \Delta x
+ \sum_{j < i} \partial_{u(j)} z_i (x, u) \Delta u_j
\right|
+ o( \Delta x^2 )
\\
\Delta u_i
& = &
\left| z_i (x, u)
+ \partial_x z_i (x, u) \Delta x
+ \sum_{j < i} \partial_{u(j)} z_i (x, u) \Delta u_j
\right|
- | z_i (x, u) |
+ o( \Delta x^2 )
\end{array}
\] $$
Given $latex u = a(x)$$ and $latex \Delta u_j$$ for $latex j < i$$,
we can use the formula above to solve for $latex \Delta u_i$$ to
within $latex o( \Delta x^2)$$.
We call the resulting vector $latex \Delta \tilde{u}$$.
$latex \[
\begin{array}{rcl}
y ( x + \Delta x, u + \Delta u )
& = &
y(x, u)
+ \partial_x y (x, u) \Delta x
+ \partial_u y (x, u) \Delta u
+ o( \Delta x^2 )
\\
f( x + \Delta x )
& = &
f(x)
+ \partial_x y (x, u) \Delta x
+ \partial_u y (x, u) \Delta \tilde{u}
+ o( \Delta x^2 )
\end{array}
\] $$
This is the abs-normal approximation for $latex f$$ near $latex x$$.
$head Correspondence to Literature$$
Using the notation
$latex Z = \partial_x z(x, u)$$,
$latex L = \partial_u z(x, u)$$,
$latex J = \partial_x y(x, u)$$,
$latex Y = \partial_u y(x, u)$$,
the abs-normal approximation for $latex z$$ and $latex y$$ near $latex x$$ is
$latex \[
\begin{array}{rcl}
z(x + \Delta x, u + \Delta u )
& = &
z(x, u) - Z x - L u + Z (x + \Delta x) + L ( u + \Delta u ) + o( \Delta x^2)
\\
y(x + \Delta x, u + \Delta u )
& = &
y(x, u) - J x - Y u + J (x + \Delta x) + Y ( u + \Delta u ) + o( \Delta x^2)
\end{array}
\] $$
Using the notation
$latex \hat{x} = x + \Delta x$$,
$latex \hat{u} = u + \Delta u$$,
$latex c = z(x,u) - Z x - L u$$,
$latex b = y(x,u) - J x - Y u$$,
we have
$latex \[
\begin{array}{rcl}
z( \hat{x}, \hat{u} )
& = &
c + Z \hat{x} + L \hat{u} + o( \Delta x^2)
\\
y( \hat{x}, \hat{u} )
& = &
b + J \hat{x} + Y \hat{u} + o( \Delta x^2)
\end{array}
\] $$
This shows the correspondence between the notation above and
Equation (2) of the reference.
$end
*/
# endif
<commit_msg>abs_normal.hpp: editing plan.<commit_after># ifndef CPPAD_CORE_ABS_NORMAL_HPP
# define CPPAD_CORE_ABS_NORMAL_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Eclipse Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin abs_normal$$
$spell
Andreas Griewank
Jens-Uwe Bernt
Manuel Radons
Tom Streubel
const
$$
$latex \newcommand{\B}[1]{ {\bf #1} }$$
$section Create An Abs-normal Representation of a Function$$
$head Under Construction$$
This is an in-progress design, and does not yet have an implementation.
$head Syntax$$
$icode%g%.abs_normal(%f%)%$$
$head Reference$$
Andreas Griewank, Jens-Uwe Bernt, Manuel Radons, Tom Streubel,
$italic Solving piecewise linear systems in abs-normal form$$,
Linear Algebra and its Applications,
vol. 471 (2015), pages 500-530.
$head f$$
The object $icode f$$ has prototype
$codei%
const ADFun<%Base%>& %f%
%$$
It represents a function $latex f : \B{R}^n \rightarrow \B{R}^m$$.
We assume that the only non-smooth terms in the representation are
absolute value functions and use $latex s \in \B{Z}_+$$
to represent the number of these terms.
$head g$$
The object $icode g$$ has prototype
$codei%
ADFun<%Base%> %g%
%$$
The initial function representation in $icode g$$ is lost.
Upon return it represents the smooth function
$latex g : \B{R}^{n + s} \rightarrow \B{R}^{m + s}$$ is defined by
$latex \[
g( x , u )
=
\left[ \begin{array}{c} y(x, u) \\ z(x, u) \end{array} \right]
\] $$
were $latex y(x, u)$$ and $latex z(x, u)$$ are defined below.
$subhead a(x)$$
Let $latex \zeta_0 ( x )$$
denote the argument for the first absolute value term in $latex f(x)$$,
$latex \zeta_1 ( x , |\zeta_0 (x)| )$$ for the second term, and so on.
For $latex i = 0 , \ldots , {s-1}$$ define
$latex \[
a_i (x)
=
| \zeta_i | \left[ x, a_0 (x) , \ldots , a_{i-1} (x) \right]
\] $$
$subhead z(x, u)$$
Define the smooth function
$latex z : \B{R}^{n + s} \rightarrow \B{R}^s$$ by
$latex \[
z_i ( x , u ) = \zeta_i ( x , u_0 , \ldots , u_{i-1} )
\] $$
$subhead y(x, u)$$
We define
$latex y : \B{R}^{n + s} \rightarrow \B{R}^m$$ as the smooth function
such that $latex y( x , u ) = f(x)$$ whenever $latex u = a(x)$$.
$head Abs-normal Approximation$$
Suppose we are given a point $latex x \in \B{R}^n$$,
and an increment $latex \Delta x$$,
and define
$latex u = a(x)$$,
$latex \Delta u = a( x + \Delta x) - a(x)$$.
$latex \[
\begin{array}{rcl}
z_i ( x + \Delta x, u + \Delta u )
& = &
z_i (x, u)
+ \partial_x z_i (x, u) \Delta x
+ \partial_u z_i (x, u) \Delta u
+ o( \Delta x )
\end{array}
\] $$
Now the partial of $latex z_i$$ with respect to $latex u_j$$ is zero
for $latex i \leq j$$. It follows that
$latex \[
\begin{array}{rcl}
z_i ( x + \Delta x, u + \Delta u )
& = &
z_i (x, u)
+ \partial_x z_i (x, u) \Delta x
+ \sum_{j < i} \partial_{u(j)} z_i (x, u) \Delta u_j
+ o( \Delta x )
\\
a_i ( x + \Delta x )
& = &
\left| z_i (x, u)
+ \partial_x z_i (x, u) \Delta x
+ \sum_{j < i} \partial_{u(j)} z_i (x, u) \Delta u_j
\right|
+ o( \Delta x )
\\
\Delta u_i
& = &
\left| z_i (x, u)
+ \partial_x z_i (x, u) \Delta x
+ \sum_{j < i} \partial_{u(j)} z_i (x, u) \Delta u_j
\right|
- | z_i (x, u) |
+ o( \Delta x )
\end{array}
\] $$
Given $latex u = a(x)$$ and $latex \Delta u_j$$ for $latex j < i$$,
we can use the formula above to solve for $latex \Delta u_i$$ to
within $latex o( \Delta x)$$.
We call the resulting vector $latex \Delta \tilde{u}$$.
$latex \[
\begin{array}{rcl}
y ( x + \Delta x, u + \Delta u )
& = &
y(x, u)
+ \partial_x y (x, u) \Delta x
+ \partial_u y (x, u) \Delta u
+ o( \Delta x )
\\
f( x + \Delta x )
& = &
f(x)
+ \partial_x y (x, u) \Delta x
+ \partial_u y (x, u) \Delta \tilde{u}
+ o( \Delta x )
\end{array}
\] $$
This is the abs-normal approximation for $latex f$$ near $latex x$$.
$head Correspondence to Literature$$
Using the notation
$latex Z = \partial_x z(x, u)$$,
$latex L = \partial_u z(x, u)$$,
$latex J = \partial_x y(x, u)$$,
$latex Y = \partial_u y(x, u)$$,
the abs-normal approximation for $latex z$$ and $latex y$$ near $latex x$$ is
$latex \[
\begin{array}{rcl}
z(x + \Delta x, u + \Delta u )
& = &
z(x, u) - Z x - L u + Z (x + \Delta x) + L ( u + \Delta u ) + o( \Delta x)
\\
y(x + \Delta x, u + \Delta u )
& = &
y(x, u) - J x - Y u + J (x + \Delta x) + Y ( u + \Delta u ) + o( \Delta x)
\end{array}
\] $$
Using the notation
$latex \hat{x} = x + \Delta x$$,
$latex \hat{u} = u + \Delta u$$,
$latex c = z(x,u) - Z x - L u$$,
$latex b = y(x,u) - J x - Y u$$,
we have
$latex \[
\begin{array}{rcl}
z( \hat{x}, \hat{u} )
& = &
c + Z \hat{x} + L \hat{u} + o( \Delta x)
\\
y( \hat{x}, \hat{u} )
& = &
b + J \hat{x} + Y \hat{u} + o( \Delta x)
\end{array}
\] $$
Note that
$latex \[
\hat{u} = u + \Delta u = a( x + \Delta x ) = | z( \hat{x} , \hat{u} ) |
\] $$
Thus we obtain
$latex \[
\begin{array}{rcl}
z( \hat{x}, \hat{u} )
& = &
c + Z \hat{x} + L | z( \hat{x} , \hat{u} ) | + o( \Delta x)
\\
y( \hat{x}, \hat{u} )
& = &
b + J \hat{x} + Y | z( \hat{x} , \hat{u} ) | + o( \Delta x)
\end{array}
\] $$
This shows the correspondence between the notation above and
Equation (2) of the reference.
$end
*/
# endif
<|endoftext|> |
<commit_before>// Copyright (c) 2015, the Dart GL extension authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD-style license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
// This file contains utility functions for the GL Dart native extension.
#include <map>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <GLES2/gl2.h>
#include "dart_api.h"
#include "util.h"
Dart_Handle HandleError(Dart_Handle handle) {
if (Dart_IsError(handle)) {
Dart_PropagateError(Dart_NewUnhandledExceptionError(handle));
}
return handle;
}
Dart_Handle Dart_IntegerToUInt(Dart_Handle integer, unsigned int *value) {
int64_t actual;
HandleError(Dart_IntegerToInt64(integer, &actual));
if (actual < UINT_MAX) {
*value = static_cast<unsigned int>(actual);
return Dart_True();
} else {
char buf[50]; // Technically we only need 46 characters for this.
snprintf(buf, sizeof(buf), "%" PRId64 " does not fit into an unsigned int.",
actual);
return Dart_NewApiError(buf);
}
}
Dart_Handle Dart_NewStringFromGLubyteString(const GLubyte *string) {
return Dart_NewStringFromCString(reinterpret_cast<const char *>(string));
}
// The length of the resulting array of values for a call to glGetBooleanv,
// glGetFloatv, or glGetIntegerv with the given parameter. Note that some
// parameters return a variable-length list of values. The length of the list
// must be queried via another call to glGetIntegerv (these parameters are
// not in the map below, but are handled specially in `GetGlGetResultLength`).
const std::map<GLenum, GLint> kGlGetResultLengths = {
{GL_ACTIVE_TEXTURE, 1},
{GL_ALIASED_LINE_WIDTH_RANGE, 2},
{GL_ALIASED_POINT_SIZE_RANGE, 2},
{GL_ALPHA_BITS, 1},
{GL_ARRAY_BUFFER_BINDING, 1},
{GL_BLEND, 1},
{GL_BLEND_COLOR, 4},
{GL_BLEND_DST_ALPHA, 1},
{GL_BLEND_SRC_ALPHA, 1},
{GL_BLEND_EQUATION_ALPHA, 1},
{GL_BLEND_EQUATION_RGB, 1},
{GL_BLEND_SRC_RGB, 1},
{GL_BLEND_DST_RGB, 1},
{GL_BLUE_BITS, 1},
{GL_COLOR_CLEAR_VALUE, 4},
{GL_COLOR_WRITEMASK, 4},
{GL_CULL_FACE, 1},
{GL_CULL_FACE_MODE, 1},
{GL_CURRENT_PROGRAM, 1},
{GL_DEPTH_BITS, 1},
{GL_DEPTH_CLEAR_VALUE, 1},
{GL_DEPTH_FUNC, 1},
{GL_DEPTH_RANGE, 2},
{GL_DEPTH_TEST, 1},
{GL_DEPTH_WRITEMASK, 1},
{GL_DITHER, 1},
{GL_ELEMENT_ARRAY_BUFFER_BINDING, 1},
{GL_FRAMEBUFFER_BINDING, 1},
{GL_FRONT_FACE, 1},
{GL_GENERATE_MIPMAP_HINT, 1},
{GL_GREEN_BITS, 1},
{GL_IMPLEMENTATION_COLOR_READ_FORMAT, 1},
{GL_IMPLEMENTATION_COLOR_READ_TYPE, 1},
{GL_LINE_WIDTH, 1},
{GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 1},
{GL_MAX_CUBE_MAP_TEXTURE_SIZE, 1},
{GL_MAX_FRAGMENT_UNIFORM_VECTORS, 1},
{GL_MAX_RENDERBUFFER_SIZE, 1},
{GL_MAX_TEXTURE_IMAGE_UNITS, 1},
{GL_MAX_TEXTURE_SIZE, 1},
{GL_MAX_VARYING_VECTORS, 1},
{GL_MAX_VERTEX_ATTRIBS, 1},
{GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 1},
{GL_MAX_VERTEX_UNIFORM_VECTORS, 1},
{GL_MAX_VIEWPORT_DIMS, 2},
{GL_NUM_COMPRESSED_TEXTURE_FORMATS, 1},
{GL_NUM_SHADER_BINARY_FORMATS, 1},
{GL_PACK_ALIGNMENT, 1},
{GL_POLYGON_OFFSET_FACTOR, 1},
{GL_POLYGON_OFFSET_FILL, 1},
{GL_POLYGON_OFFSET_UNITS, 1},
{GL_RED_BITS, 1},
{GL_RENDERBUFFER_BINDING, 1},
{GL_SAMPLE_ALPHA_TO_COVERAGE, 1},
{GL_SAMPLE_BUFFERS, 1},
{GL_SAMPLE_COVERAGE, 1},
{GL_SAMPLE_COVERAGE_INVERT, 1},
{GL_SAMPLE_COVERAGE_VALUE, 1},
{GL_SAMPLES, 1},
{GL_SCISSOR_BOX, 4},
{GL_SCISSOR_TEST, 1},
{GL_SHADER_COMPILER, 1},
{GL_STENCIL_CLEAR_VALUE, 1},
{GL_STENCIL_BACK_FAIL, 1},
{GL_STENCIL_BACK_FUNC, 1},
{GL_STENCIL_BACK_PASS_DEPTH_FAIL, 1},
{GL_STENCIL_BACK_PASS_DEPTH_PASS, 1},
{GL_STENCIL_BACK_REF, 1},
{GL_STENCIL_BACK_VALUE_MASK, 1},
{GL_STENCIL_BACK_WRITEMASK, 1},
{GL_STENCIL_BITS, 1},
{GL_STENCIL_FAIL, 1},
{GL_STENCIL_FUNC, 1},
{GL_STENCIL_PASS_DEPTH_FAIL, 1},
{GL_STENCIL_PASS_DEPTH_PASS, 1},
{GL_STENCIL_REF, 1},
{GL_STENCIL_TEST, 1},
{GL_STENCIL_VALUE_MASK, 1},
{GL_STENCIL_WRITEMASK, 1},
{GL_SUBPIXEL_BITS, 1},
{GL_TEXTURE_BINDING_2D, 1},
{GL_TEXTURE_BINDING_CUBE_MAP, 1},
{GL_UNPACK_ALIGNMENT, 1},
{GL_VIEWPORT, 4},
};
// Looks up the number of values returned for a call to glGet*v in the map.
GLint GetGlGetResultLength(GLenum param) {
// There are two parameters that return a variable number of arguments,
// so the length must be queried via another call to glGetIntegerv. In
// all other cases, we'll just look up the value in the map.
GLint length = -1;
switch (param) {
case GL_COMPRESSED_TEXTURE_FORMATS:
glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &length);
return length;
case GL_SHADER_BINARY_FORMATS:
glGetIntegerv(GL_NUM_SHADER_BINARY_FORMATS, &length);
return length;
default:
std::map<GLenum, GLint>::const_iterator itr =
kGlGetResultLengths.find(param);
if (itr != kGlGetResultLengths.end()) {
length = itr->second;
}
return length;
}
}
<commit_msg>Minor change (formatting)<commit_after>// Copyright (c) 2015, the Dart GL extension authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD-style license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
// This file contains utility functions for the GL Dart native extension.
#include <map>
#include <inttypes.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <GLES2/gl2.h>
#include "dart_api.h"
#include "util.h"
Dart_Handle HandleError(Dart_Handle handle) {
if (Dart_IsError(handle)) {
Dart_PropagateError(Dart_NewUnhandledExceptionError(handle));
}
return handle;
}
Dart_Handle Dart_IntegerToUInt(Dart_Handle integer, unsigned int *value) {
int64_t actual;
HandleError(Dart_IntegerToInt64(integer, &actual));
if (actual < UINT_MAX) {
*value = static_cast<unsigned int>(actual);
return Dart_True();
} else {
char buf[50]; // Technically we only need 46 characters for this.
snprintf(buf, sizeof(buf), "%" PRId64 " does not fit into an unsigned int.",
actual);
return Dart_NewApiError(buf);
}
}
Dart_Handle Dart_NewStringFromGLubyteString(const GLubyte *string) {
return Dart_NewStringFromCString(reinterpret_cast<const char *>(string));
}
// The length of the resulting array of values for a call to glGetBooleanv,
// glGetFloatv, or glGetIntegerv with the given parameter. Note that some
// parameters return a variable-length list of values. The length of the list
// must be queried via another call to glGetIntegerv (these parameters are
// not in the map below, but are handled specially in `GetGlGetResultLength`).
const std::map<GLenum, GLint> kGlGetResultLengths = {
{GL_ACTIVE_TEXTURE, 1},
{GL_ALIASED_LINE_WIDTH_RANGE, 2},
{GL_ALIASED_POINT_SIZE_RANGE, 2},
{GL_ALPHA_BITS, 1},
{GL_ARRAY_BUFFER_BINDING, 1},
{GL_BLEND, 1},
{GL_BLEND_COLOR, 4},
{GL_BLEND_DST_ALPHA, 1},
{GL_BLEND_SRC_ALPHA, 1},
{GL_BLEND_EQUATION_ALPHA, 1},
{GL_BLEND_EQUATION_RGB, 1},
{GL_BLEND_SRC_RGB, 1},
{GL_BLEND_DST_RGB, 1},
{GL_BLUE_BITS, 1},
{GL_COLOR_CLEAR_VALUE, 4},
{GL_COLOR_WRITEMASK, 4},
{GL_CULL_FACE, 1},
{GL_CULL_FACE_MODE, 1},
{GL_CURRENT_PROGRAM, 1},
{GL_DEPTH_BITS, 1},
{GL_DEPTH_CLEAR_VALUE, 1},
{GL_DEPTH_FUNC, 1},
{GL_DEPTH_RANGE, 2},
{GL_DEPTH_TEST, 1},
{GL_DEPTH_WRITEMASK, 1},
{GL_DITHER, 1},
{GL_ELEMENT_ARRAY_BUFFER_BINDING, 1},
{GL_FRAMEBUFFER_BINDING, 1},
{GL_FRONT_FACE, 1},
{GL_GENERATE_MIPMAP_HINT, 1},
{GL_GREEN_BITS, 1},
{GL_IMPLEMENTATION_COLOR_READ_FORMAT, 1},
{GL_IMPLEMENTATION_COLOR_READ_TYPE, 1},
{GL_LINE_WIDTH, 1},
{GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 1},
{GL_MAX_CUBE_MAP_TEXTURE_SIZE, 1},
{GL_MAX_FRAGMENT_UNIFORM_VECTORS, 1},
{GL_MAX_RENDERBUFFER_SIZE, 1},
{GL_MAX_TEXTURE_IMAGE_UNITS, 1},
{GL_MAX_TEXTURE_SIZE, 1},
{GL_MAX_VARYING_VECTORS, 1},
{GL_MAX_VERTEX_ATTRIBS, 1},
{GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 1},
{GL_MAX_VERTEX_UNIFORM_VECTORS, 1},
{GL_MAX_VIEWPORT_DIMS, 2},
{GL_NUM_COMPRESSED_TEXTURE_FORMATS, 1},
{GL_NUM_SHADER_BINARY_FORMATS, 1},
{GL_PACK_ALIGNMENT, 1},
{GL_POLYGON_OFFSET_FACTOR, 1},
{GL_POLYGON_OFFSET_FILL, 1},
{GL_POLYGON_OFFSET_UNITS, 1},
{GL_RED_BITS, 1},
{GL_RENDERBUFFER_BINDING, 1},
{GL_SAMPLE_ALPHA_TO_COVERAGE, 1},
{GL_SAMPLE_BUFFERS, 1},
{GL_SAMPLE_COVERAGE, 1},
{GL_SAMPLE_COVERAGE_INVERT, 1},
{GL_SAMPLE_COVERAGE_VALUE, 1},
{GL_SAMPLES, 1},
{GL_SCISSOR_BOX, 4},
{GL_SCISSOR_TEST, 1},
{GL_SHADER_COMPILER, 1},
{GL_STENCIL_CLEAR_VALUE, 1},
{GL_STENCIL_BACK_FAIL, 1},
{GL_STENCIL_BACK_FUNC, 1},
{GL_STENCIL_BACK_PASS_DEPTH_FAIL, 1},
{GL_STENCIL_BACK_PASS_DEPTH_PASS, 1},
{GL_STENCIL_BACK_REF, 1},
{GL_STENCIL_BACK_VALUE_MASK, 1},
{GL_STENCIL_BACK_WRITEMASK, 1},
{GL_STENCIL_BITS, 1},
{GL_STENCIL_FAIL, 1},
{GL_STENCIL_FUNC, 1},
{GL_STENCIL_PASS_DEPTH_FAIL, 1},
{GL_STENCIL_PASS_DEPTH_PASS, 1},
{GL_STENCIL_REF, 1},
{GL_STENCIL_TEST, 1},
{GL_STENCIL_VALUE_MASK, 1},
{GL_STENCIL_WRITEMASK, 1},
{GL_SUBPIXEL_BITS, 1},
{GL_TEXTURE_BINDING_2D, 1},
{GL_TEXTURE_BINDING_CUBE_MAP, 1},
{GL_UNPACK_ALIGNMENT, 1},
{GL_VIEWPORT, 4},
};
// Looks up the number of values returned for a call to glGet*v in the map.
GLint GetGlGetResultLength(GLenum param) {
// There are two parameters that return a variable number of arguments,
// so the length must be queried via another call to glGetIntegerv. In
// all other cases, we'll just look up the value in the map.
GLint length = -1;
switch (param) {
case GL_COMPRESSED_TEXTURE_FORMATS:
glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &length);
return length;
case GL_SHADER_BINARY_FORMATS:
glGetIntegerv(GL_NUM_SHADER_BINARY_FORMATS, &length);
return length;
default:
std::map<GLenum, GLint>::const_iterator itr =
kGlGetResultLengths.find(param);
if (itr != kGlGetResultLengths.end()) {
length = itr->second;
}
return length;
}
}
<|endoftext|> |
<commit_before>#include "../base/SRC_FIRST.hpp"
#include "render_policy_mt.hpp"
#include "events.hpp"
#include "drawer_yg.hpp"
#include "window_handle.hpp"
#include "../yg/render_state.hpp"
#include "../yg/internal/opengl.hpp"
#include "../geometry/transformations.hpp"
#include "../base/mutex.hpp"
#include "../platform/platform.hpp"
RenderPolicyMT::RenderPolicyMT(VideoTimer * videoTimer,
DrawerYG::Params const & params,
yg::ResourceManager::Params const & rmParams,
shared_ptr<yg::gl::RenderContext> const & primaryRC)
: RenderPolicy(primaryRC, false),
m_DoAddCommand(true)
{
yg::ResourceManager::Params rmp = rmParams;
rmp.m_primaryStoragesParams = yg::ResourceManager::StoragePoolParams(5000 * sizeof(yg::gl::Vertex),
sizeof(yg::gl::Vertex),
10000 * sizeof(unsigned short),
sizeof(unsigned short),
7,
false,
true,
10,
"primaryStorage");
rmp.m_smallStoragesParams = yg::ResourceManager::StoragePoolParams(500 * sizeof(yg::gl::Vertex),
sizeof(yg::gl::Vertex),
1000 * sizeof(unsigned short),
sizeof(unsigned short),
7,
false,
true,
5,
"smallStorage");
rmp.m_blitStoragesParams = yg::ResourceManager::StoragePoolParams(10 * sizeof(yg::gl::AuxVertex),
sizeof(yg::gl::AuxVertex),
10 * sizeof(unsigned short),
sizeof(unsigned short),
7,
true,
true,
1,
"blitStorage");
rmp.m_tinyStoragesParams = yg::ResourceManager::StoragePoolParams(300 * sizeof(yg::gl::Vertex),
sizeof(yg::gl::Vertex),
600 * sizeof(unsigned short),
sizeof(unsigned short),
7,
true,
true,
1,
"tinyStorage");
rmp.m_primaryTexturesParams = yg::ResourceManager::TexturePoolParams(512,
256,
7,
rmp.m_rtFormat,
true,
true,
true,
1,
"primaryTexture");
rmp.m_fontTexturesParams = yg::ResourceManager::TexturePoolParams(512,
256,
7,
rmp.m_rtFormat,
true,
true,
true,
1,
"fontTexture");
rmp.m_glyphCacheParams = yg::ResourceManager::GlyphCacheParams("unicode_blocks.txt",
"fonts_whitelist.txt",
"fonts_blacklist.txt",
2 * 1024 * 1024,
3,
1);
rmp.m_useSingleThreadedOGL = false;
rmp.m_useVA = !yg::gl::g_isBufferObjectsSupported;
rmp.fitIntoLimits();
m_resourceManager.reset(new yg::ResourceManager(rmp));
Platform::FilesList fonts;
GetPlatform().GetFontNames(fonts);
m_resourceManager->addFonts(fonts);
DrawerYG::params_t p = params;
p.m_resourceManager = m_resourceManager;
p.m_dynamicPagesCount = 2;
p.m_textPagesCount = 2;
p.m_glyphCacheID = m_resourceManager->guiThreadGlyphCacheID();
p.m_skinName = GetPlatform().SkinName();
p.m_visualScale = GetPlatform().VisualScale();
p.m_isSynchronized = false;
p.m_useTinyStorage = true;
m_drawer.reset(new DrawerYG(p));
m_windowHandle.reset(new WindowHandle());
m_windowHandle->setUpdatesEnabled(false);
m_windowHandle->setVideoTimer(videoTimer);
m_windowHandle->setRenderContext(primaryRC);
m_renderQueue.reset(new RenderQueue(GetPlatform().SkinName(),
false,
true,
0.1,
false,
GetPlatform().ScaleEtalonSize(),
GetPlatform().VisualScale(),
m_bgColor));
m_renderQueue->AddWindowHandle(m_windowHandle);
}
void RenderPolicyMT::SetRenderFn(TRenderFn renderFn)
{
RenderPolicy::SetRenderFn(renderFn);
m_renderQueue->initializeGL(m_primaryRC, m_resourceManager);
}
m2::RectI const RenderPolicyMT::OnSize(int w, int h)
{
RenderPolicy::OnSize(w, h);
m_renderQueue->OnSize(w, h);
m2::PointU pt = m_renderQueue->renderState().coordSystemShift();
return m2::RectI(pt.x, pt.y, pt.x + w, pt.y + h);
}
void RenderPolicyMT::BeginFrame(shared_ptr<PaintEvent> const & e,
ScreenBase const & s)
{
}
void RenderPolicyMT::EndFrame(shared_ptr<PaintEvent> const & e,
ScreenBase const & s)
{
m_renderQueue->renderState().m_mutex->Unlock();
}
void RenderPolicyMT::DrawFrame(shared_ptr<PaintEvent> const & e,
ScreenBase const & s)
{
m_resourceManager->mergeFreeResources();
m_renderQueue->renderState().m_mutex->Lock();
m_renderQueue->renderStatePtr()->m_doRepaintAll = DoForceUpdate();
if (m_DoAddCommand && (DoForceUpdate() || (s != m_renderQueue->renderState().m_actualScreen)))
m_renderQueue->AddCommand(m_renderFn, s);
SetForceUpdate(false);
DrawerYG * pDrawer = e->drawer();
e->drawer()->screen()->clear(m_bgColor);
if (m_renderQueue->renderState().m_actualTarget.get() != 0)
{
m2::PointD const ptShift = m_renderQueue->renderState().coordSystemShift(false);
math::Matrix<double, 3, 3> m = m_renderQueue->renderState().m_actualScreen.PtoGMatrix() * s.GtoPMatrix();
m = math::Shift(m, -ptShift);
pDrawer->screen()->blit(m_renderQueue->renderState().m_actualTarget, m);
}
}
void RenderPolicyMT::StartDrag()
{
m_DoAddCommand = false;
RenderPolicy::StartDrag();
}
void RenderPolicyMT::StopDrag()
{
m_DoAddCommand = true;
RenderPolicy::StopDrag();
}
void RenderPolicyMT::StartScale()
{
m_DoAddCommand = false;
RenderPolicy::StartScale();
}
void RenderPolicyMT::StopScale()
{
m_DoAddCommand = true;
RenderPolicy::StartScale();
}
RenderQueue & RenderPolicyMT::GetRenderQueue()
{
return *m_renderQueue.get();
}
<commit_msg>fixes deadlock issue.<commit_after>#include "../base/SRC_FIRST.hpp"
#include "render_policy_mt.hpp"
#include "events.hpp"
#include "drawer_yg.hpp"
#include "window_handle.hpp"
#include "../yg/render_state.hpp"
#include "../yg/internal/opengl.hpp"
#include "../geometry/transformations.hpp"
#include "../base/mutex.hpp"
#include "../platform/platform.hpp"
RenderPolicyMT::RenderPolicyMT(VideoTimer * videoTimer,
DrawerYG::Params const & params,
yg::ResourceManager::Params const & rmParams,
shared_ptr<yg::gl::RenderContext> const & primaryRC)
: RenderPolicy(primaryRC, false),
m_DoAddCommand(true)
{
yg::ResourceManager::Params rmp = rmParams;
rmp.m_primaryStoragesParams = yg::ResourceManager::StoragePoolParams(5000 * sizeof(yg::gl::Vertex),
sizeof(yg::gl::Vertex),
10000 * sizeof(unsigned short),
sizeof(unsigned short),
7,
false,
true,
10,
"primaryStorage");
rmp.m_smallStoragesParams = yg::ResourceManager::StoragePoolParams(500 * sizeof(yg::gl::Vertex),
sizeof(yg::gl::Vertex),
1000 * sizeof(unsigned short),
sizeof(unsigned short),
7,
false,
true,
5,
"smallStorage");
rmp.m_blitStoragesParams = yg::ResourceManager::StoragePoolParams(10 * sizeof(yg::gl::AuxVertex),
sizeof(yg::gl::AuxVertex),
10 * sizeof(unsigned short),
sizeof(unsigned short),
7,
true,
true,
1,
"blitStorage");
rmp.m_tinyStoragesParams = yg::ResourceManager::StoragePoolParams(300 * sizeof(yg::gl::Vertex),
sizeof(yg::gl::Vertex),
600 * sizeof(unsigned short),
sizeof(unsigned short),
7,
true,
true,
1,
"tinyStorage");
rmp.m_primaryTexturesParams = yg::ResourceManager::TexturePoolParams(512,
256,
7,
rmp.m_rtFormat,
true,
true,
true,
1,
"primaryTexture");
rmp.m_fontTexturesParams = yg::ResourceManager::TexturePoolParams(512,
256,
7,
rmp.m_rtFormat,
true,
true,
true,
1,
"fontTexture");
rmp.m_glyphCacheParams = yg::ResourceManager::GlyphCacheParams("unicode_blocks.txt",
"fonts_whitelist.txt",
"fonts_blacklist.txt",
2 * 1024 * 1024,
3,
1);
rmp.m_useSingleThreadedOGL = false;
rmp.m_useVA = !yg::gl::g_isBufferObjectsSupported;
rmp.fitIntoLimits();
m_resourceManager.reset(new yg::ResourceManager(rmp));
Platform::FilesList fonts;
GetPlatform().GetFontNames(fonts);
m_resourceManager->addFonts(fonts);
DrawerYG::params_t p = params;
p.m_resourceManager = m_resourceManager;
p.m_dynamicPagesCount = 2;
p.m_textPagesCount = 2;
p.m_glyphCacheID = m_resourceManager->guiThreadGlyphCacheID();
p.m_skinName = GetPlatform().SkinName();
p.m_visualScale = GetPlatform().VisualScale();
p.m_isSynchronized = false;
p.m_useTinyStorage = true;
m_drawer.reset(new DrawerYG(p));
m_windowHandle.reset(new WindowHandle());
m_windowHandle->setUpdatesEnabled(false);
m_windowHandle->setVideoTimer(videoTimer);
m_windowHandle->setRenderContext(primaryRC);
m_renderQueue.reset(new RenderQueue(GetPlatform().SkinName(),
false,
true,
0.1,
false,
GetPlatform().ScaleEtalonSize(),
GetPlatform().VisualScale(),
m_bgColor));
m_renderQueue->AddWindowHandle(m_windowHandle);
}
void RenderPolicyMT::SetRenderFn(TRenderFn renderFn)
{
RenderPolicy::SetRenderFn(renderFn);
m_renderQueue->initializeGL(m_primaryRC, m_resourceManager);
}
m2::RectI const RenderPolicyMT::OnSize(int w, int h)
{
RenderPolicy::OnSize(w, h);
m_renderQueue->OnSize(w, h);
m2::PointU pt = m_renderQueue->renderState().coordSystemShift();
return m2::RectI(pt.x, pt.y, pt.x + w, pt.y + h);
}
void RenderPolicyMT::BeginFrame(shared_ptr<PaintEvent> const & e,
ScreenBase const & s)
{
}
void RenderPolicyMT::EndFrame(shared_ptr<PaintEvent> const & e,
ScreenBase const & s)
{
m_renderQueue->renderState().m_mutex->Unlock();
}
void RenderPolicyMT::DrawFrame(shared_ptr<PaintEvent> const & e,
ScreenBase const & s)
{
m_resourceManager->mergeFreeResources();
m_renderQueue->renderStatePtr()->m_doRepaintAll = DoForceUpdate();
if (m_DoAddCommand && (DoForceUpdate() || (s != m_renderQueue->renderState().m_actualScreen)))
m_renderQueue->AddCommand(m_renderFn, s);
SetForceUpdate(false);
DrawerYG * pDrawer = e->drawer();
m_renderQueue->renderState().m_mutex->Lock();
e->drawer()->screen()->clear(m_bgColor);
if (m_renderQueue->renderState().m_actualTarget.get() != 0)
{
m2::PointD const ptShift = m_renderQueue->renderState().coordSystemShift(false);
math::Matrix<double, 3, 3> m = m_renderQueue->renderState().m_actualScreen.PtoGMatrix() * s.GtoPMatrix();
m = math::Shift(m, -ptShift);
pDrawer->screen()->blit(m_renderQueue->renderState().m_actualTarget, m);
}
}
void RenderPolicyMT::StartDrag()
{
m_DoAddCommand = false;
RenderPolicy::StartDrag();
}
void RenderPolicyMT::StopDrag()
{
m_DoAddCommand = true;
RenderPolicy::StopDrag();
}
void RenderPolicyMT::StartScale()
{
m_DoAddCommand = false;
RenderPolicy::StartScale();
}
void RenderPolicyMT::StopScale()
{
m_DoAddCommand = true;
RenderPolicy::StartScale();
}
RenderQueue & RenderPolicyMT::GetRenderQueue()
{
return *m_renderQueue.get();
}
<|endoftext|> |
<commit_before><commit_msg>Revert "CID#705982 ensure umask for mkstemp"<commit_after><|endoftext|> |
<commit_before>#include "OI.h"
#include "Commands/ControlCatapult.h"
#include "Subsystems/Catapult.h"
/// Default constructor of the class.
ControlCatapult::ControlCatapult()
{
manualMode = kSafe;
Requires(Catapult::GetInstance());
}
/// Called just before this Command runs the first time.
void ControlCatapult::Initialize()
{
manualMode = kSafe;
Catapult::GetInstance()->moveCatapult(0);
timer.Reset();
timer.Start();
}
//Passes 1 to shooter when the button is pressed, and 0 when it isn't
void ControlCatapult::Execute()
{
OI* oi = OI::GetInstance();
Catapult* cat = Catapult::GetInstance();
if(oi && cat)
{
double thumb = -oi->gamepad->GetRawAxis(AXS_WINCH); // Y-axis is positive down.
bool danger = cat->WatchCurrent();
if (danger or timer.Get() > 2.0) {
timer.Reset();
if (danger) {
manualMode = thumb > 0 ? kOverloadUp : kOverloadDown;
}
}
if((thumb > 0.1 and manualMode != kOverloadUp) or (thumb < -0.1 and manualMode != kOverloadDown))
{
cat->moveCatapult(thumb);
}
else {
cat->moveCatapult(0);
}
}
}
/// Make this return true when this Command no longer needs to run execute().
/// \return always false since this is the default command and should never finish.
bool ControlCatapult::IsFinished()
{
return false;
}
/// Called once after isFinished returns true
void ControlCatapult::End()
{
Catapult::GetInstance()->moveCatapult(0);
}
/// Called when another command which requires one or more of the same
/// subsystems is scheduled to run
void ControlCatapult::Interrupted()
{
End();
}
<commit_msg>Issue #3: Reset to "Safe" when "danger" passed.<commit_after>#include "OI.h"
#include "Commands/ControlCatapult.h"
#include "Subsystems/Catapult.h"
/// Default constructor of the class.
ControlCatapult::ControlCatapult()
{
manualMode = kSafe;
Requires(Catapult::GetInstance());
}
/// Called just before this Command runs the first time.
void ControlCatapult::Initialize()
{
manualMode = kSafe;
Catapult::GetInstance()->moveCatapult(0);
timer.Reset();
timer.Start();
}
//Passes 1 to shooter when the button is pressed, and 0 when it isn't
void ControlCatapult::Execute()
{
OI* oi = OI::GetInstance();
Catapult* cat = Catapult::GetInstance();
if(oi && cat)
{
double thumb = -oi->gamepad->GetRawAxis(AXS_WINCH); // Y-axis is positive down.
bool danger = cat->WatchCurrent();
if (danger or timer.Get() > 2.0) {
timer.Reset();
if (danger) {
manualMode = thumb > 0 ? kOverloadUp : kOverloadDown;
}
else {
manualMode = kSafe;
}
}
if((thumb > 0.1 and manualMode != kOverloadUp) or (thumb < -0.1 and manualMode != kOverloadDown))
{
cat->moveCatapult(thumb);
}
else {
cat->moveCatapult(0);
}
}
}
/// Make this return true when this Command no longer needs to run execute().
/// \return always false since this is the default command and should never finish.
bool ControlCatapult::IsFinished()
{
return false;
}
/// Called once after isFinished returns true
void ControlCatapult::End()
{
Catapult::GetInstance()->moveCatapult(0);
}
/// Called when another command which requires one or more of the same
/// subsystems is scheduled to run
void ControlCatapult::Interrupted()
{
End();
}
<|endoftext|> |
<commit_before>/***********************************************************************
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/RendererModules/Ogre/RenderTarget.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"
#include "CEGUI/Exceptions.h"
#include <OgreRenderSystem.h>
#include <OgreCamera.h>
#include <OgreViewport.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner,
Ogre::RenderSystem& rs) :
d_owner(owner),
d_renderSystem(rs),
d_renderTarget(0),
d_viewport(0),
d_ogreViewportDimensions(0, 0, 0, 0),
d_matrix(Ogre::Matrix4::IDENTITY),
d_viewportValid(false)
{
}
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::~OgreRenderTarget()
{
delete d_viewport;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer)
{
buffer.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const RenderQueue& queue)
{
queue.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area)
{
d_ogreViewportDimensions = area;
if (d_viewport)
updateOgreViewportDimensions(d_viewport->getTarget());
d_viewportValid = false;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateOgreViewportDimensions(
const Ogre::RenderTarget* const rt)
{
if (rt)
{
if(d_viewport)
d_viewport->setDimensions(
d_ogreViewportDimensions.left() / rt->getWidth(),
d_ogreViewportDimensions.top() / rt->getHeight(),
d_ogreViewportDimensions.getWidth() / rt->getWidth(),
d_ogreViewportDimensions.getHeight() / rt->getHeight());
}
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::activate()
{
if (!d_matrixValid)
updateMatrix();
if (!d_viewportValid)
updateViewport();
d_renderSystem._setViewport(d_viewport);
d_owner.setProjectionMatrix(d_matrix);
RenderTarget::activate();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::deactivate()
{
// currently nothing to do in the basic case
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
const glm::vec2& p_in,
glm::vec2& p_out) const
{
if (!d_matrixValid)
updateMatrix();
const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff);
const Ogre::Real midx = d_area.getWidth() * 0.5f;
const Ogre::Real midy = d_area.getHeight() * 0.5f;
// viewport matrix
const Ogre::Matrix4 vpmat(
midx, 0, 0, d_area.left() + midx,
0, -midy, 0, d_area.top() + midy,
0, 0, 1, 0,
0, 0, 0, 1
);
// matrices used for projecting and unprojecting points
const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix()) * d_matrix * vpmat);
const Ogre::Matrix4 unproj(proj.inverse());
Ogre::Vector3 in;
// unproject the ends of the ray
in.x = midx;
in.y = midy;
in.z = -d_viewDistance;
const Ogre::Vector3 r1(unproj * in);
in.x = p_in.x;
in.y = p_in.y;
in.z = 0;
// calculate vector of picking ray
const Ogre::Vector3 rv(r1 - unproj * in);
// project points to orientate them with GeometryBuffer plane
in.x = 0.0;
in.y = 0.0;
const Ogre::Vector3 p1(proj * in);
in.x = 1.0;
in.y = 0.0;
const Ogre::Vector3 p2(proj * in);
in.x = 0.0;
in.y = 1.0;
const Ogre::Vector3 p3(proj * in);
// calculate the plane normal
const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1));
// calculate distance from origin
const Ogre::Real plen = pn.length();
const Ogre::Real dist = -(p1.x * (pn.x / plen) +
p1.y * (pn.y / plen) +
p1.z * (pn.z / plen));
// calculate intersection of ray and plane
const Ogre::Real pn_dot_rv = pn.dotProduct(rv);
const Ogre::Real tmp = pn_dot_rv != 0.0 ?
(pn.dotProduct(r1) + dist) / pn_dot_rv :
0.0f;
p_out.x = static_cast<float>(r1.x - rv.x * tmp);
p_out.y = static_cast<float>(r1.y - rv.y * tmp);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateMatrix() const
{
if (d_owner.usesOpenGL())
d_matrix = OgreRenderer::glmToOgreMatrix( RenderTarget::createViewProjMatrixForOpenGL() );
else if(d_owner.usesDirect3D())
d_matrix = OgreRenderer::glmToOgreMatrix( RenderTarget::createViewProjMatrixForDirect3D() );
else
CEGUI_THROW(RendererException("An unsupported RenderSystem is being used by Ogre. Please contact the CEGUI team."));
RenderTarget::d_matrixValid = true;
//! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices
RenderTarget::d_activationCounter = -1;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateViewport()
{
if (!d_viewport)
{
#ifdef CEGUI_USE_OGRE_COMPOSITOR2
d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1);
#else
d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0);
#endif // CEGUI_USE_OGRE_COMPOSITOR2
updateOgreViewportDimensions(d_renderTarget);
}
d_viewport->_updateDimensions();
d_viewportValid = true;
}
//----------------------------------------------------------------------------//
template <typename T>
Renderer& OgreRenderTarget<T>::getOwner()
{
return d_owner;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setArea(const Rectf& area)
{
setOgreViewportDimensions(area);
RenderTarget::setArea(area);
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>MOD: Adding missing qualifier<commit_after>/***********************************************************************
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/RendererModules/Ogre/RenderTarget.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"
#include "CEGUI/Exceptions.h"
#include <OgreRenderSystem.h>
#include <OgreCamera.h>
#include <OgreViewport.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner,
Ogre::RenderSystem& rs) :
d_owner(owner),
d_renderSystem(rs),
d_renderTarget(0),
d_viewport(0),
d_ogreViewportDimensions(0, 0, 0, 0),
d_matrix(Ogre::Matrix4::IDENTITY),
d_viewportValid(false)
{
}
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::~OgreRenderTarget()
{
delete d_viewport;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer)
{
buffer.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const RenderQueue& queue)
{
queue.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area)
{
d_ogreViewportDimensions = area;
if (d_viewport)
updateOgreViewportDimensions(d_viewport->getTarget());
d_viewportValid = false;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateOgreViewportDimensions(
const Ogre::RenderTarget* const rt)
{
if (rt)
{
if(d_viewport)
d_viewport->setDimensions(
d_ogreViewportDimensions.left() / rt->getWidth(),
d_ogreViewportDimensions.top() / rt->getHeight(),
d_ogreViewportDimensions.getWidth() / rt->getWidth(),
d_ogreViewportDimensions.getHeight() / rt->getHeight());
}
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::activate()
{
if (!d_matrixValid)
updateMatrix();
if (!d_viewportValid)
updateViewport();
d_renderSystem._setViewport(d_viewport);
d_owner.setProjectionMatrix(d_matrix);
RenderTarget::activate();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::deactivate()
{
// currently nothing to do in the basic case
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
const glm::vec2& p_in,
glm::vec2& p_out) const
{
if (!d_matrixValid)
updateMatrix();
const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff);
const Ogre::Real midx = d_area.getWidth() * 0.5f;
const Ogre::Real midy = d_area.getHeight() * 0.5f;
// viewport matrix
const Ogre::Matrix4 vpmat(
midx, 0, 0, d_area.left() + midx,
0, -midy, 0, d_area.top() + midy,
0, 0, 1, 0,
0, 0, 0, 1
);
// matrices used for projecting and unprojecting points
const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix()) * d_matrix * vpmat);
const Ogre::Matrix4 unproj(proj.inverse());
Ogre::Vector3 in;
// unproject the ends of the ray
in.x = midx;
in.y = midy;
in.z = -RenderTarget::d_viewDistance;
const Ogre::Vector3 r1(unproj * in);
in.x = p_in.x;
in.y = p_in.y;
in.z = 0;
// calculate vector of picking ray
const Ogre::Vector3 rv(r1 - unproj * in);
// project points to orientate them with GeometryBuffer plane
in.x = 0.0;
in.y = 0.0;
const Ogre::Vector3 p1(proj * in);
in.x = 1.0;
in.y = 0.0;
const Ogre::Vector3 p2(proj * in);
in.x = 0.0;
in.y = 1.0;
const Ogre::Vector3 p3(proj * in);
// calculate the plane normal
const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1));
// calculate distance from origin
const Ogre::Real plen = pn.length();
const Ogre::Real dist = -(p1.x * (pn.x / plen) +
p1.y * (pn.y / plen) +
p1.z * (pn.z / plen));
// calculate intersection of ray and plane
const Ogre::Real pn_dot_rv = pn.dotProduct(rv);
const Ogre::Real tmp = pn_dot_rv != 0.0 ?
(pn.dotProduct(r1) + dist) / pn_dot_rv :
0.0f;
p_out.x = static_cast<float>(r1.x - rv.x * tmp);
p_out.y = static_cast<float>(r1.y - rv.y * tmp);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateMatrix() const
{
if (d_owner.usesOpenGL())
d_matrix = OgreRenderer::glmToOgreMatrix( RenderTarget::createViewProjMatrixForOpenGL() );
else if(d_owner.usesDirect3D())
d_matrix = OgreRenderer::glmToOgreMatrix( RenderTarget::createViewProjMatrixForDirect3D() );
else
CEGUI_THROW(RendererException("An unsupported RenderSystem is being used by Ogre. Please contact the CEGUI team."));
RenderTarget::d_matrixValid = true;
//! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices
RenderTarget::d_activationCounter = -1;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateViewport()
{
if (!d_viewport)
{
#ifdef CEGUI_USE_OGRE_COMPOSITOR2
d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1);
#else
d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0);
#endif // CEGUI_USE_OGRE_COMPOSITOR2
updateOgreViewportDimensions(d_renderTarget);
}
d_viewport->_updateDimensions();
d_viewportValid = true;
}
//----------------------------------------------------------------------------//
template <typename T>
Renderer& OgreRenderTarget<T>::getOwner()
{
return d_owner;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setArea(const Rectf& area)
{
setOgreViewportDimensions(area);
RenderTarget::setArea(area);
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: dsEntriesNoExp.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2004-11-16 14:49:57 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SBA_UNODATBR_HXX_
#include "unodatbr.hxx"
#endif
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef _DBAUI_LISTVIEWITEMS_HXX_
#include "listviewitems.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef DBACCESS_UI_DBTREEVIEW_HXX
#include "dbtreeview.hxx"
#endif
#ifndef DBAUI_DBTREELISTBOX_HXX
#include "dbtreelistbox.hxx"
#endif
#ifndef _DBU_BRW_HRC_
#include "dbu_brw.hrc"
#endif
#ifndef DBAUI_DBTREEMODEL_HXX
#include "dbtreemodel.hxx"
#endif
using namespace ::com::sun::star::frame;
using namespace ::dbtools;
using namespace ::svx;
// .........................................................................
namespace dbaui
{
// .........................................................................
// -----------------------------------------------------------------------------
SbaTableQueryBrowser::EntryType SbaTableQueryBrowser::getChildType( SvLBoxEntry* _pEntry ) const
{
DBG_ASSERT(isContainer(_pEntry), "SbaTableQueryBrowser::getChildType: invalid entry!");
switch (getEntryType(_pEntry))
{
case etTableContainer:
return etTable;
case etQueryContainer:
return etQuery;
}
return etUnknown;
}
// -----------------------------------------------------------------------------
String SbaTableQueryBrowser::GetEntryText( SvLBoxEntry* _pEntry ) const
{
return m_pTreeView->getListBox()->GetEntryText(_pEntry);
}
// -----------------------------------------------------------------------------
SbaTableQueryBrowser::EntryType SbaTableQueryBrowser::getEntryType( SvLBoxEntry* _pEntry ) const
{
if (!_pEntry)
return etUnknown;
SvLBoxEntry* pRootEntry = m_pTreeView->getListBox()->GetRootLevelParent(_pEntry);
SvLBoxEntry* pEntryParent = m_pTreeView->getListBox()->GetParent(_pEntry);
SvLBoxEntry* pTables = m_pTreeView->getListBox()->GetEntry(pRootEntry, CONTAINER_TABLES);
SvLBoxEntry* pQueries = m_pTreeView->getListBox()->GetEntry(pRootEntry, CONTAINER_QUERIES);
#ifdef DBG_UTIL
String sTest;
if (pTables) sTest = m_pTreeView->getListBox()->GetEntryText(pTables);
if (pQueries) sTest = m_pTreeView->getListBox()->GetEntryText(pQueries);
#endif
if (pRootEntry == _pEntry)
return etDatasource;
if (pTables == _pEntry)
return etTableContainer;
if (pQueries == _pEntry)
return etQueryContainer;
if (pTables == pEntryParent)
return etTable;
if (pQueries == pEntryParent)
return etQuery;
return etUnknown;
}
//------------------------------------------------------------------------------
void SbaTableQueryBrowser::select(SvLBoxEntry* _pEntry, sal_Bool _bSelect)
{
SvLBoxItem* pTextItem = _pEntry ? _pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING) : NULL;
if (pTextItem)
{
static_cast<OBoldListboxString*>(pTextItem)->emphasize(_bSelect);
m_pTreeModel->InvalidateEntry(_pEntry);
}
else
DBG_ERROR("SbaTableQueryBrowser::select: invalid entry!");
}
//------------------------------------------------------------------------------
void SbaTableQueryBrowser::selectPath(SvLBoxEntry* _pEntry, sal_Bool _bSelect)
{
while (_pEntry)
{
select(_pEntry, _bSelect);
_pEntry = m_pTreeModel->GetParent(_pEntry);
}
}
//------------------------------------------------------------------------------
sal_Bool SbaTableQueryBrowser::isSelected(SvLBoxEntry* _pEntry) const
{
SvLBoxItem* pTextItem = _pEntry ? _pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING) : NULL;
if (pTextItem)
return static_cast<OBoldListboxString*>(pTextItem)->isEmphasized();
else
DBG_ERROR("SbaTableQueryBrowser::isSelected: invalid entry!");
return sal_False;
}
//------------------------------------------------------------------------------
void SbaTableQueryBrowser::describeSupportedFeatures()
{
SbaXDataBrowserController::describeSupportedFeatures();
implDescribeSupportedFeature( ".uno:Title", ID_BROWSER_TITLE );
if ( !m_bShowMenu )
{
implDescribeSupportedFeature( ".uno:DSBrowserExplorer", ID_BROWSER_EXPLORER, CommandGroup::VIEW );
implDescribeSupportedFeature( ".uno:DSBFormLetter", ID_BROWSER_FORMLETTER, CommandGroup::DOCUMENT );
implDescribeSupportedFeature( ".uno:DSBInsertColumns", ID_BROWSER_INSERTCOLUMNS, CommandGroup::INSERT );
implDescribeSupportedFeature( ".uno:DSBInsertContent", ID_BROWSER_INSERTCONTENT, CommandGroup::INSERT );
implDescribeSupportedFeature( ".uno:DSBDocumentDataSource", ID_BROWSER_DOCUMENT_DATASOURCE, CommandGroup::VIEW );
implDescribeSupportedFeature( ".uno:DataSourceBrowser/FormLetter", ID_BROWSER_FORMLETTER );
implDescribeSupportedFeature( ".uno:DataSourceBrowser/InsertColumns", ID_BROWSER_INSERTCOLUMNS );
implDescribeSupportedFeature( ".uno:DataSourceBrowser/InsertContent", ID_BROWSER_INSERTCONTENT );
implDescribeSupportedFeature( ".uno:DataSourceBrowser/DocumentDataSource", ID_BROWSER_DOCUMENT_DATASOURCE );
}
implDescribeSupportedFeature( ".uno:CloseWin", ID_BROWSER_CLOSE, CommandGroup::DOCUMENT );
implDescribeSupportedFeature( ".uno:DBRebuildData", ID_BROWSER_REFRESH_REBUILD, CommandGroup::DATA );
}
// -------------------------------------------------------------------------
String SbaTableQueryBrowser::getURL() const
{
return String();
}
// -----------------------------------------------------------------------------
void SbaTableQueryBrowser::notifyHiContrastChanged()
{
if ( m_pTreeView )
{
sal_Bool bHiContrast = isHiContrast();
if ( m_bHiContrast != bHiContrast )
{
m_bHiContrast = bHiContrast;
// change all bitmap entries
DBTreeListBox* pListBox = m_pTreeView->getListBox();
SvLBoxEntry* pEntryLoop = m_pTreeModel->First();
while ( pEntryLoop )
{
DBTreeListModel::DBTreeListUserData* pData = static_cast<DBTreeListModel::DBTreeListUserData*>(pEntryLoop->GetUserData());
if ( pData )
{
ModuleRes aResId(DBTreeListModel::getImageResId(pData->eType,isHiContrast()));
Image aImage(aResId);
USHORT nCount = pEntryLoop->ItemCount();
for (USHORT i=0;i<nCount;++i)
{
SvLBoxItem* pItem = pEntryLoop->GetItem(i);
if ( pItem && pItem->IsA() == SV_ITEM_ID_LBOXCONTEXTBMP)
{
static_cast<SvLBoxContextBmp*>(pItem)->SetBitmap1(pEntryLoop,aImage);
static_cast<SvLBoxContextBmp*>(pItem)->SetBitmap2(pEntryLoop,aImage);
break;
}
}
}
pEntryLoop = m_pTreeModel->Next(pEntryLoop);
}
}
}
}
// -----------------------------------------------------------------------------
// .........................................................................
} // namespace dbaui
// .........................................................................
<commit_msg>INTEGRATION: CWS dba20blocker (1.12.116); FILE MERGED 2005/06/24 07:26:06 fs 1.12.116.1: copying fix for #121276# into this CWS<commit_after>/*************************************************************************
*
* $RCSfile: dsEntriesNoExp.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: obo $ $Date: 2005-07-08 10:38:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SBA_UNODATBR_HXX_
#include "unodatbr.hxx"
#endif
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef _DBAUI_LISTVIEWITEMS_HXX_
#include "listviewitems.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef DBACCESS_UI_DBTREEVIEW_HXX
#include "dbtreeview.hxx"
#endif
#ifndef DBAUI_DBTREELISTBOX_HXX
#include "dbtreelistbox.hxx"
#endif
#ifndef _DBU_BRW_HRC_
#include "dbu_brw.hrc"
#endif
#ifndef DBAUI_DBTREEMODEL_HXX
#include "dbtreemodel.hxx"
#endif
using namespace ::com::sun::star::frame;
using namespace ::dbtools;
using namespace ::svx;
// .........................................................................
namespace dbaui
{
// .........................................................................
// -----------------------------------------------------------------------------
SbaTableQueryBrowser::EntryType SbaTableQueryBrowser::getChildType( SvLBoxEntry* _pEntry ) const
{
DBG_ASSERT(isContainer(_pEntry), "SbaTableQueryBrowser::getChildType: invalid entry!");
switch (getEntryType(_pEntry))
{
case etTableContainer:
return etTable;
case etQueryContainer:
return etQuery;
}
return etUnknown;
}
// -----------------------------------------------------------------------------
String SbaTableQueryBrowser::GetEntryText( SvLBoxEntry* _pEntry ) const
{
return m_pTreeView->getListBox()->GetEntryText(_pEntry);
}
// -----------------------------------------------------------------------------
SbaTableQueryBrowser::EntryType SbaTableQueryBrowser::getEntryType( SvLBoxEntry* _pEntry ) const
{
if (!_pEntry)
return etUnknown;
SvLBoxEntry* pRootEntry = m_pTreeView->getListBox()->GetRootLevelParent(_pEntry);
SvLBoxEntry* pEntryParent = m_pTreeView->getListBox()->GetParent(_pEntry);
SvLBoxEntry* pTables = m_pTreeView->getListBox()->GetEntry(pRootEntry, CONTAINER_TABLES);
SvLBoxEntry* pQueries = m_pTreeView->getListBox()->GetEntry(pRootEntry, CONTAINER_QUERIES);
#ifdef DBG_UTIL
String sTest;
if (pTables) sTest = m_pTreeView->getListBox()->GetEntryText(pTables);
if (pQueries) sTest = m_pTreeView->getListBox()->GetEntryText(pQueries);
#endif
if (pRootEntry == _pEntry)
return etDatasource;
if (pTables == _pEntry)
return etTableContainer;
if (pQueries == _pEntry)
return etQueryContainer;
if (pTables == pEntryParent)
return etTable;
if (pQueries == pEntryParent)
return etQuery;
return etUnknown;
}
//------------------------------------------------------------------------------
void SbaTableQueryBrowser::select(SvLBoxEntry* _pEntry, sal_Bool _bSelect)
{
SvLBoxItem* pTextItem = _pEntry ? _pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING) : NULL;
if (pTextItem)
{
static_cast<OBoldListboxString*>(pTextItem)->emphasize(_bSelect);
m_pTreeModel->InvalidateEntry(_pEntry);
}
else
DBG_ERROR("SbaTableQueryBrowser::select: invalid entry!");
}
//------------------------------------------------------------------------------
void SbaTableQueryBrowser::selectPath(SvLBoxEntry* _pEntry, sal_Bool _bSelect)
{
while (_pEntry)
{
select(_pEntry, _bSelect);
_pEntry = m_pTreeModel->GetParent(_pEntry);
}
}
//------------------------------------------------------------------------------
sal_Bool SbaTableQueryBrowser::isSelected(SvLBoxEntry* _pEntry) const
{
SvLBoxItem* pTextItem = _pEntry ? _pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING) : NULL;
if (pTextItem)
return static_cast<OBoldListboxString*>(pTextItem)->isEmphasized();
else
DBG_ERROR("SbaTableQueryBrowser::isSelected: invalid entry!");
return sal_False;
}
//------------------------------------------------------------------------------
void SbaTableQueryBrowser::SelectionChanged()
{
if ( !m_bShowMenu )
{
InvalidateFeature(ID_BROWSER_INSERTCOLUMNS);
InvalidateFeature(ID_BROWSER_INSERTCONTENT);
InvalidateFeature(ID_BROWSER_FORMLETTER);
}
}
//------------------------------------------------------------------------------
void SbaTableQueryBrowser::describeSupportedFeatures()
{
SbaXDataBrowserController::describeSupportedFeatures();
implDescribeSupportedFeature( ".uno:Title", ID_BROWSER_TITLE );
if ( !m_bShowMenu )
{
implDescribeSupportedFeature( ".uno:DSBrowserExplorer", ID_BROWSER_EXPLORER, CommandGroup::VIEW );
implDescribeSupportedFeature( ".uno:DSBFormLetter", ID_BROWSER_FORMLETTER, CommandGroup::DOCUMENT );
implDescribeSupportedFeature( ".uno:DSBInsertColumns", ID_BROWSER_INSERTCOLUMNS, CommandGroup::INSERT );
implDescribeSupportedFeature( ".uno:DSBInsertContent", ID_BROWSER_INSERTCONTENT, CommandGroup::INSERT );
implDescribeSupportedFeature( ".uno:DSBDocumentDataSource", ID_BROWSER_DOCUMENT_DATASOURCE, CommandGroup::VIEW );
implDescribeSupportedFeature( ".uno:DataSourceBrowser/FormLetter", ID_BROWSER_FORMLETTER );
implDescribeSupportedFeature( ".uno:DataSourceBrowser/InsertColumns", ID_BROWSER_INSERTCOLUMNS );
implDescribeSupportedFeature( ".uno:DataSourceBrowser/InsertContent", ID_BROWSER_INSERTCONTENT );
implDescribeSupportedFeature( ".uno:DataSourceBrowser/DocumentDataSource", ID_BROWSER_DOCUMENT_DATASOURCE );
}
implDescribeSupportedFeature( ".uno:CloseWin", ID_BROWSER_CLOSE, CommandGroup::DOCUMENT );
implDescribeSupportedFeature( ".uno:DBRebuildData", ID_BROWSER_REFRESH_REBUILD, CommandGroup::DATA );
}
// -------------------------------------------------------------------------
String SbaTableQueryBrowser::getURL() const
{
return String();
}
// -----------------------------------------------------------------------------
void SbaTableQueryBrowser::notifyHiContrastChanged()
{
if ( m_pTreeView )
{
sal_Bool bHiContrast = isHiContrast();
if ( m_bHiContrast != bHiContrast )
{
m_bHiContrast = bHiContrast;
// change all bitmap entries
DBTreeListBox* pListBox = m_pTreeView->getListBox();
SvLBoxEntry* pEntryLoop = m_pTreeModel->First();
while ( pEntryLoop )
{
DBTreeListModel::DBTreeListUserData* pData = static_cast<DBTreeListModel::DBTreeListUserData*>(pEntryLoop->GetUserData());
if ( pData )
{
ModuleRes aResId(DBTreeListModel::getImageResId(pData->eType,isHiContrast()));
Image aImage(aResId);
USHORT nCount = pEntryLoop->ItemCount();
for (USHORT i=0;i<nCount;++i)
{
SvLBoxItem* pItem = pEntryLoop->GetItem(i);
if ( pItem && pItem->IsA() == SV_ITEM_ID_LBOXCONTEXTBMP)
{
static_cast<SvLBoxContextBmp*>(pItem)->SetBitmap1(pEntryLoop,aImage);
static_cast<SvLBoxContextBmp*>(pItem)->SetBitmap2(pEntryLoop,aImage);
break;
}
}
}
pEntryLoop = m_pTreeModel->Next(pEntryLoop);
}
}
}
}
// -----------------------------------------------------------------------------
// .........................................................................
} // namespace dbaui
// .........................................................................
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: indexfieldscontrol.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2007-07-06 08:30:39 $
*
* 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 _DBAUI_INDEXFIELDSCONTROL_HXX_
#define _DBAUI_INDEXFIELDSCONTROL_HXX_
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _SVTOOLS_EDITBROWSEBOX_HXX_
#include <svtools/editbrowsebox.hxx>
#endif
#ifndef _DBAUI_INDEXCOLLECTION_HXX_
#include "indexcollection.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
//......................................................................
namespace dbaui
{
//......................................................................
//==================================================================
// IndexFieldsControl
//==================================================================
class IndexFieldsControl : public ::svt::EditBrowseBox
{
OModuleClient m_aModuleClient;
protected:
IndexFields m_aSavedValue;
IndexFields m_aFields; // !! order matters !!
ConstIndexFieldsIterator m_aSeekRow; // !!
Link m_aModifyHdl;
::svt::ListBoxControl* m_pSortingCell;
::svt::ListBoxControl* m_pFieldNameCell;
String m_sAscendingText;
String m_sDescendingText;
sal_Int32 m_nMaxColumnsInIndex;
public:
IndexFieldsControl( Window* _pParent, const ResId& _rId ,sal_Int32 _nMaxColumnsInIndex);
~IndexFieldsControl();
void Init(const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rAvailableFields);
void initializeFrom(const IndexFields& _rFields);
void commitTo(IndexFields& _rFields);
sal_Bool SaveModified();
sal_Bool IsModified() const;
const IndexFields& GetSavedValue() const { return m_aSavedValue; }
void SaveValue() { m_aSavedValue = m_aFields; }
void SetModifyHdl(const Link& _rHdl) { m_aModifyHdl = _rHdl; }
Link GetModifyHdl() const { return m_aModifyHdl; }
virtual String GetCellText(long _nRow,sal_uInt16 nColId) const;
protected:
// EditBrowseBox overridables
virtual void PaintCell( OutputDevice& _rDev, const Rectangle& _rRect, sal_uInt16 _nColumnId ) const;
virtual sal_Bool SeekRow(long nRow);
virtual sal_uInt32 GetTotalCellWidth(long nRow, sal_uInt16 nColId);
virtual sal_Bool IsTabAllowed(sal_Bool bForward) const;
::svt::CellController* GetController(long _nRow, sal_uInt16 _nColumnId);
void InitController(::svt::CellControllerRef&, long _nRow, sal_uInt16 _nColumnId);
protected:
String GetRowCellText(const ConstIndexFieldsIterator& _rRow,sal_uInt16 nColId) const;
sal_Bool implGetFieldDesc(long _nRow, ConstIndexFieldsIterator& _rPos);
sal_Bool isNewField() const { return GetCurRow() >= (sal_Int32)m_aFields.size(); }
DECL_LINK( OnListEntrySelected, ListBox* );
private:
using ::svt::EditBrowseBox::Init;
};
//......................................................................
} // namespace dbaui
//......................................................................
#endif // _DBAUI_INDEXFIELDSCONTROL_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.10.162); FILE MERGED 2008/03/31 13:27:46 rt 1.10.162.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: indexfieldscontrol.hxx,v $
* $Revision: 1.11 $
*
* 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 _DBAUI_INDEXFIELDSCONTROL_HXX_
#define _DBAUI_INDEXFIELDSCONTROL_HXX_
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _SVTOOLS_EDITBROWSEBOX_HXX_
#include <svtools/editbrowsebox.hxx>
#endif
#ifndef _DBAUI_INDEXCOLLECTION_HXX_
#include "indexcollection.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
//......................................................................
namespace dbaui
{
//......................................................................
//==================================================================
// IndexFieldsControl
//==================================================================
class IndexFieldsControl : public ::svt::EditBrowseBox
{
OModuleClient m_aModuleClient;
protected:
IndexFields m_aSavedValue;
IndexFields m_aFields; // !! order matters !!
ConstIndexFieldsIterator m_aSeekRow; // !!
Link m_aModifyHdl;
::svt::ListBoxControl* m_pSortingCell;
::svt::ListBoxControl* m_pFieldNameCell;
String m_sAscendingText;
String m_sDescendingText;
sal_Int32 m_nMaxColumnsInIndex;
public:
IndexFieldsControl( Window* _pParent, const ResId& _rId ,sal_Int32 _nMaxColumnsInIndex);
~IndexFieldsControl();
void Init(const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rAvailableFields);
void initializeFrom(const IndexFields& _rFields);
void commitTo(IndexFields& _rFields);
sal_Bool SaveModified();
sal_Bool IsModified() const;
const IndexFields& GetSavedValue() const { return m_aSavedValue; }
void SaveValue() { m_aSavedValue = m_aFields; }
void SetModifyHdl(const Link& _rHdl) { m_aModifyHdl = _rHdl; }
Link GetModifyHdl() const { return m_aModifyHdl; }
virtual String GetCellText(long _nRow,sal_uInt16 nColId) const;
protected:
// EditBrowseBox overridables
virtual void PaintCell( OutputDevice& _rDev, const Rectangle& _rRect, sal_uInt16 _nColumnId ) const;
virtual sal_Bool SeekRow(long nRow);
virtual sal_uInt32 GetTotalCellWidth(long nRow, sal_uInt16 nColId);
virtual sal_Bool IsTabAllowed(sal_Bool bForward) const;
::svt::CellController* GetController(long _nRow, sal_uInt16 _nColumnId);
void InitController(::svt::CellControllerRef&, long _nRow, sal_uInt16 _nColumnId);
protected:
String GetRowCellText(const ConstIndexFieldsIterator& _rRow,sal_uInt16 nColId) const;
sal_Bool implGetFieldDesc(long _nRow, ConstIndexFieldsIterator& _rPos);
sal_Bool isNewField() const { return GetCurRow() >= (sal_Int32)m_aFields.size(); }
DECL_LINK( OnListEntrySelected, ListBox* );
private:
using ::svt::EditBrowseBox::Init;
};
//......................................................................
} // namespace dbaui
//......................................................................
#endif // _DBAUI_INDEXFIELDSCONTROL_HXX_
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017 Trail of Bits, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
namespace {
template <typename T>
DEF_SEM(CALL, T target_pc, PC return_pc) {
addr_t next_sp = USub(REG_XSP, ADDRESS_SIZE_BYTES);
Write(WritePtr<addr_t>(next_sp _IF_32BIT(REG_SS_BASE)), Read(return_pc));
Write(REG_XSP, next_sp);
Write(REG_PC, ZExtTo<addr_t>(Read(target_pc)));
return memory;
}
DEF_SEM(RET_IMM, I16 bytes) {
Write(REG_PC, Read(ReadPtr<addr_t>(REG_XSP _IF_32BIT(REG_SS_BASE))));
Write(REG_XSP,
UAdd(UAdd(REG_XSP, ZExtTo<addr_t>(Read(bytes))), ADDRESS_SIZE_BYTES));
return memory;
}
DEF_SEM(RET) {
Write(REG_PC, Read(ReadPtr<addr_t>(REG_XSP _IF_32BIT(REG_SS_BASE))));
Write(REG_XSP, UAdd(REG_XSP, ADDRESS_SIZE_BYTES));
return memory;
}
} // namespace
DEF_ISEL_32or64(CALL_NEAR_RELBRd, CALL<PC>);
DEF_ISEL_32or64(CALL_NEAR_RELBRz, CALL<PC>);
IF_32BIT( DEF_ISEL(CALL_NEAR_MEMv_16) = CALL<M16>; )
IF_32BIT( DEF_ISEL(CALL_NEAR_MEMv_32) = CALL<M32>; )
IF_64BIT( DEF_ISEL(CALL_NEAR_MEMv_64) = CALL<M64>; )
IF_32BIT( DEF_ISEL(CALL_NEAR_GPRv_16) = CALL<R16>; )
IF_32BIT( DEF_ISEL(CALL_NEAR_GPRv_32) = CALL<R32>; )
IF_64BIT( DEF_ISEL(CALL_NEAR_GPRv_64) = CALL<R64>; )
/*
352 CALL_FAR CALL_FAR_MEMp2 CALL BASE I86 ATTRIBUTES: FAR_XFER FIXED_BASE1 NOTSX SCALABLE STACKPUSH1
353 CALL_FAR CALL_FAR_PTRp_IMMw CALL BASE I86 ATTRIBUTES: FAR_XFER FIXED_BASE0 NOTSX SCALABLE STACKPUSH0
*/
DEF_ISEL_32or64(RET_NEAR_IMMw, RET_IMM);
DEF_ISEL_32or64(RET_NEAR, RET);
/*
1073 RET_FAR RET_FAR_IMMw RET BASE I86 ATTRIBUTES: FAR_XFER FIXED_BASE0 NOTSX SCALABLE STACKPOP0
1074 RET_FAR RET_FAR RET BASE I86 ATTRIBUTES: FAR_XFER FIXED_BASE0 NOTSX SCALABLE STACKPOP0
1666 IRETQ IRETQ RET LONGMODE LONGMODE ATTRIBUTES: FIXED_BASE0 NOTSX SCALABLE STACKPOP0
1784 IRET IRET RET BASE I86 ATTRIBUTES: FIXED_BASE0 NOTSX SCALABLE STACKPOP0
728 IRETD IRETD RET BASE I386 ATTRIBUTES: FIXED_BASE0 NOTSX SCALABLE STACKPOP0
*/
#if ADDRESS_SIZE_BITS == 32
namespace {
DEF_SEM(IRETD) {
auto new_eip = PopFromStack<uint32_t>(memory, state);
auto new_cs = static_cast<uint16_t>(PopFromStack<uint32_t>(memory, state));
auto temp_eflags = PopFromStack<uint32_t>(memory, state);
Flags f = {};
f.flat = (temp_eflags & 0x257FD5U) | 0x1A0000U;
Write(REG_PC, new_eip);
Write(REG_CS.flat, new_cs);
state.rflag = f;
state.aflag.af = f.af;
state.aflag.cf = f.cf;
state.aflag.df = f.df;
state.aflag.of = f.of;
state.aflag.pf = f.pf;
state.aflag.sf = f.sf;
state.aflag.zf = f.zf;
state.hyper_call = AsyncHyperCall::kX86IRet;
return memory;
}
}
DEF_ISEL(IRETD_32) = IRETD;
#endif
<commit_msg>add iretq instruction lifting (#325)<commit_after>/*
* Copyright (c) 2017 Trail of Bits, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
namespace {
template <typename T>
DEF_SEM(CALL, T target_pc, PC return_pc) {
addr_t next_sp = USub(REG_XSP, ADDRESS_SIZE_BYTES);
Write(WritePtr<addr_t>(next_sp _IF_32BIT(REG_SS_BASE)), Read(return_pc));
Write(REG_XSP, next_sp);
Write(REG_PC, ZExtTo<addr_t>(Read(target_pc)));
return memory;
}
DEF_SEM(RET_IMM, I16 bytes) {
Write(REG_PC, Read(ReadPtr<addr_t>(REG_XSP _IF_32BIT(REG_SS_BASE))));
Write(REG_XSP,
UAdd(UAdd(REG_XSP, ZExtTo<addr_t>(Read(bytes))), ADDRESS_SIZE_BYTES));
return memory;
}
DEF_SEM(RET) {
Write(REG_PC, Read(ReadPtr<addr_t>(REG_XSP _IF_32BIT(REG_SS_BASE))));
Write(REG_XSP, UAdd(REG_XSP, ADDRESS_SIZE_BYTES));
return memory;
}
} // namespace
DEF_ISEL_32or64(CALL_NEAR_RELBRd, CALL<PC>);
DEF_ISEL_32or64(CALL_NEAR_RELBRz, CALL<PC>);
IF_32BIT( DEF_ISEL(CALL_NEAR_MEMv_16) = CALL<M16>; )
IF_32BIT( DEF_ISEL(CALL_NEAR_MEMv_32) = CALL<M32>; )
IF_64BIT( DEF_ISEL(CALL_NEAR_MEMv_64) = CALL<M64>; )
IF_32BIT( DEF_ISEL(CALL_NEAR_GPRv_16) = CALL<R16>; )
IF_32BIT( DEF_ISEL(CALL_NEAR_GPRv_32) = CALL<R32>; )
IF_64BIT( DEF_ISEL(CALL_NEAR_GPRv_64) = CALL<R64>; )
/*
352 CALL_FAR CALL_FAR_MEMp2 CALL BASE I86 ATTRIBUTES: FAR_XFER FIXED_BASE1 NOTSX SCALABLE STACKPUSH1
353 CALL_FAR CALL_FAR_PTRp_IMMw CALL BASE I86 ATTRIBUTES: FAR_XFER FIXED_BASE0 NOTSX SCALABLE STACKPUSH0
*/
DEF_ISEL_32or64(RET_NEAR_IMMw, RET_IMM);
DEF_ISEL_32or64(RET_NEAR, RET);
/*
1073 RET_FAR RET_FAR_IMMw RET BASE I86 ATTRIBUTES: FAR_XFER FIXED_BASE0 NOTSX SCALABLE STACKPOP0
1074 RET_FAR RET_FAR RET BASE I86 ATTRIBUTES: FAR_XFER FIXED_BASE0 NOTSX SCALABLE STACKPOP0
1666 IRETQ IRETQ RET LONGMODE LONGMODE ATTRIBUTES: FIXED_BASE0 NOTSX SCALABLE STACKPOP0
1784 IRET IRET RET BASE I86 ATTRIBUTES: FIXED_BASE0 NOTSX SCALABLE STACKPOP0
728 IRETD IRETD RET BASE I386 ATTRIBUTES: FIXED_BASE0 NOTSX SCALABLE STACKPOP0
*/
namespace {
#if ADDRESS_SIZE_BITS == 32
DEF_SEM(IRETD) {
auto new_eip = PopFromStack<uint32_t>(memory, state);
auto new_cs = static_cast<uint16_t>(PopFromStack<uint32_t>(memory, state));
auto temp_eflags = PopFromStack<uint32_t>(memory, state);
Flags f = {};
f.flat = (temp_eflags & 0x257FD5U) | 0x1A0000U;
Write(REG_PC, new_eip);
Write(REG_CS.flat, new_cs);
state.rflag = f;
state.aflag.af = f.af;
state.aflag.cf = f.cf;
state.aflag.df = f.df;
state.aflag.of = f.of;
state.aflag.pf = f.pf;
state.aflag.sf = f.sf;
state.aflag.zf = f.zf;
state.hyper_call = AsyncHyperCall::kX86IRet;
return memory;
}
DEF_ISEL(IRETD_32) = IRETD;
#elif ADDRESS_SIZE_BITS == 64
DEF_SEM(IRETQ) {
auto new_rip = PopFromStack<uint64_t>(memory, state);
auto new_cs = static_cast<uint16_t>(PopFromStack<uint64_t>(memory, state));
auto temp_rflags = PopFromStack<uint64_t>(memory, state);
Flags f = {};
f.flat = temp_rflags;
Write(REG_PC, new_rip);
Write(REG_CS.flat, new_cs);
state.rflag = f;
state.aflag.af = f.af;
state.aflag.cf = f.cf;
state.aflag.df = f.df;
state.aflag.of = f.of;
state.aflag.pf = f.pf;
state.aflag.sf = f.sf;
state.aflag.zf = f.zf;
state.hyper_call = AsyncHyperCall::kX86IRet;
// TODO(tathanhdinh): Update the hidden part (segment shadow) of CS,
// see Issue #334
auto new_rsp = PopFromStack<uint64_t>(memory, state);
auto new_ss = static_cast<uint16_t>(PopFromStack<uint64_t>(memory, state));
Write(REG_RSP, new_rsp);
Write(REG_SS.flat, new_ss);
// TODO(tathanhdinh): Update the hidden part (segment shadow) of SS,
// see Issue #334
return memory;
}
DEF_ISEL(IRETQ_64) = IRETQ;
#endif
}
<|endoftext|> |
<commit_before>/*************************************************************************\
**
** tOutput.cpp: Functions for output objects
**
**
**
** $Id: tOutput.cpp,v 1.16 1999-03-15 23:34:43 nmgaspar Exp $
\*************************************************************************/
#include "tOutput.h"
/*************************************************************************\
**
** Constructor
**
** The constructor takes two arguments, a pointer to the grid mesh and
** a reference to an open input file. It reads the base name for the
** output files from the input file, and opens and initializes these.
**
** Input: gridPtr -- pointer to a tGrid object (or descendant), assumed
** valid
** infile -- reference to an open input file, assumed valid
**
\*************************************************************************/
template< class tSubNode >
tOutput<tSubNode>::tOutput( tGrid<tSubNode> * gridPtr, tInputFile &infile )
{
assert( gridPtr > 0 );
g = gridPtr;
infile.ReadItem( baseName, "OUTFILENAME" );
CreateAndOpenFile( &nodeofs, ".nodes" );
CreateAndOpenFile( &edgofs, ".edges" );
CreateAndOpenFile( &triofs, ".tri" );
CreateAndOpenFile( &zofs, ".z" );
}
/*************************************************************************\
**
** CreateAndOpenFile
**
** Opens the output file stream pointed by theOFStream, giving it the
** name <baseName><extension>, and checks to make sure that the ofstream
** is valid.
**
** Input: theOFStream -- ptr to an ofstream object
** extension -- file name extension (e.g., ".nodes")
** Output: theOFStream is initialized to create an open output file
** Assumes: extension is a null-terminated string, and the length of
** baseName plus extension doesn't exceed kMaxNameSize+6
** (ie, the extension is expected to be <= 6 characters)
**
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream,
char *extension )
{
char fullName[kMaxNameSize+6];
strcpy( fullName, baseName );
strcat( fullName, extension );
theOFStream->open( fullName );
if( !theOFStream->good() )
ReportFatalError(
"I can't create files for output. Memory may be exhausted." );
}
/*************************************************************************\
**
** WriteOutput
**
** This function writes information about the mesh to four files called
** name.nodes, name.edges, name.tri, and name.z, where "name" is a
** name that the user has specified in the input file and which is
** stored in the data member baseName.
**
** Input: time -- time of the current output time-slice
** Output: the node, edge, and triangle ID numbers are modified so that
** they are numbered according to their position on the list
** Assumes: the four file ofstreams have been opened by the constructor
** and are valid
**
** TODO: deal with option for once-only printing of mesh when mesh not
** deforming
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::WriteOutput( double time )
{
tGridListIter<tSubNode> niter( g->getNodeList() );
tGridListIter<tEdge> eiter( g->getEdgeList() );
tListIter<tTriangle> titer( g->getTriList() );
tNode * cn;
tEdge * ce;
tTriangle * ct;
int id;
int nnodes = g->getNodeList()->getSize();
int nedges = g->getEdgeList()->getSize();
int ntri = g->getTriList()->getSize();
cout << "tOutput::WriteOutput()\n";
// Renumber IDs in order by position on list
for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ )
cn->setID( id );
for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ )
ce->setID( id );
for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ )
ct->setID( id );
// Write node file and z file
nodeofs << " " << time << endl << nnodes << endl;
zofs << " " << time << endl << nnodes << endl;
for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() )
{
nodeofs << cn->getX() << " " << cn->getY() << " "
<< cn->getEdg()->getID() << " " << cn->getBoundaryFlag() << endl;
zofs << cn->getZ() << endl;
}
// Write edge file
edgofs << " " << time << endl << nedges << endl;
for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() )
edgofs << ce->getOriginPtrNC()->getID() << " "
<< ce->getDestinationPtrNC()->getID() << " "
<< ce->getCCWEdg()->getID() << endl;
// Write triangle file
int i;
triofs << " " << time << endl << ntri << endl;
for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() )
{
for( i=0; i<=2; i++ )
triofs << ct->pPtr(i)->getID() << " ";
for( i=0; i<=2; i++ )
{
if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << " ";
else triofs << "-1 ";
}
triofs << ct->ePtr(0)->getID() << " "
<< ct->ePtr(1)->getID() << " "
<< ct->ePtr(2)->getID() << endl;
}
WriteNodeData( time );
}
template< class tSubNode >
void tOutput<tSubNode>::WriteNodeData( double time )
{}
template< class tSubNode >
tLOutput<tSubNode>::tLOutput( tGrid<tSubNode> *g, tInputFile &infile )
: tOutput<tSubNode>( g, infile ) // call base-class constructor
{
CreateAndOpenFile( &drareaofs, ".area" );
CreateAndOpenFile( &netofs, ".net" );
CreateAndOpenFile( &slpofs, ".slp" );
CreateAndOpenFile( &qofs, ".q" );
CreateAndOpenFile( &layofs, ".lay" );
CreateAndOpenFile( &texofs, ".tx" );
}
//TODO: should output boundary points as well so they'll map up with nodes
// for plotting. Means changing getSlope so it returns zero if flowedg
// undefined
template< class tSubNode >
void tLOutput<tSubNode>::WriteNodeData( double time )
{
tGridListIter<tSubNode> ni( g->getNodeList() );
tSubNode *cn;
int nActiveNodes = g->getNodeList()->getActiveSize();
int nnodes = g->getNodeList()->getSize();
int i, j;
drareaofs << " " << time << "\n " << nActiveNodes << endl;
netofs << " " << time << "\n " << nActiveNodes << endl;
slpofs << " " << time << "\n " << nActiveNodes << endl;
qofs << " " << time << "\n " << nnodes << endl;
layofs << " " << time << "\n" << nActiveNodes << endl;
texofs << " " << time << "\n" << nnodes << endl;
for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )
{
assert( cn>0 );
drareaofs << cn->getDrArea() << endl;
if( cn->getDownstrmNbr() )
netofs << cn->getDownstrmNbr()->getID() << endl;
slpofs << cn->getSlope() << endl;
layofs << cn->getNumLayer() << endl;
i=0;
while(i<cn->getNumLayer()){
//NIC - change output of layerflag which is obsolete to
//output exposure time - TODO
layofs << cn->getLayerCtime(i) << " " << cn->getLayerRtime(i) << " " << cn->getLayerFlag(i) << endl;
layofs << cn->getLayerDepth(i) << " " << cn->getLayerErody(i) << " " << cn->getLayerSed(i) << endl;
j=0;
while(j<cn->getNumg()){
layofs << cn->getLayerDgrade(i,j) << " ";
j++;
}
layofs << endl;
i++;
}
}
for( cn = ni.FirstP(); !(ni.AtEnd()); cn = ni.NextP() ){
qofs << cn->getQ() << endl;
// temporary fix of zero-layer problem (TODO: solve)
/*if( cn->getLayerDgrade(0,0)<1e-6 )
{
cout << "Warning from tOutput::WriteNodeData(): "
<< "Anomalously low top layer dgrade at " << cn->getID() << endl;
texofs << cn->getLayerDgrade(0,0) << endl;
}
else*/
if( cn->getNumg()>1 ) // temporary hack TODO
{
texofs << cn->getLayerDgrade(0,0)/cn->getLayerDepth(0) << endl;
}
}
}
<commit_msg>removed reference to getLayerFlag, gt<commit_after>/*************************************************************************\
**
** tOutput.cpp: Functions for output objects
**
**
**
** $Id: tOutput.cpp,v 1.17 1999-03-17 22:01:16 gtucker Exp $
\*************************************************************************/
#include "tOutput.h"
/*************************************************************************\
**
** Constructor
**
** The constructor takes two arguments, a pointer to the grid mesh and
** a reference to an open input file. It reads the base name for the
** output files from the input file, and opens and initializes these.
**
** Input: gridPtr -- pointer to a tGrid object (or descendant), assumed
** valid
** infile -- reference to an open input file, assumed valid
**
\*************************************************************************/
template< class tSubNode >
tOutput<tSubNode>::tOutput( tGrid<tSubNode> * gridPtr, tInputFile &infile )
{
assert( gridPtr > 0 );
g = gridPtr;
infile.ReadItem( baseName, "OUTFILENAME" );
CreateAndOpenFile( &nodeofs, ".nodes" );
CreateAndOpenFile( &edgofs, ".edges" );
CreateAndOpenFile( &triofs, ".tri" );
CreateAndOpenFile( &zofs, ".z" );
}
/*************************************************************************\
**
** CreateAndOpenFile
**
** Opens the output file stream pointed by theOFStream, giving it the
** name <baseName><extension>, and checks to make sure that the ofstream
** is valid.
**
** Input: theOFStream -- ptr to an ofstream object
** extension -- file name extension (e.g., ".nodes")
** Output: theOFStream is initialized to create an open output file
** Assumes: extension is a null-terminated string, and the length of
** baseName plus extension doesn't exceed kMaxNameSize+6
** (ie, the extension is expected to be <= 6 characters)
**
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream,
char *extension )
{
char fullName[kMaxNameSize+6];
strcpy( fullName, baseName );
strcat( fullName, extension );
theOFStream->open( fullName );
if( !theOFStream->good() )
ReportFatalError(
"I can't create files for output. Memory may be exhausted." );
}
/*************************************************************************\
**
** WriteOutput
**
** This function writes information about the mesh to four files called
** name.nodes, name.edges, name.tri, and name.z, where "name" is a
** name that the user has specified in the input file and which is
** stored in the data member baseName.
**
** Input: time -- time of the current output time-slice
** Output: the node, edge, and triangle ID numbers are modified so that
** they are numbered according to their position on the list
** Assumes: the four file ofstreams have been opened by the constructor
** and are valid
**
** TODO: deal with option for once-only printing of mesh when mesh not
** deforming
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::WriteOutput( double time )
{
tGridListIter<tSubNode> niter( g->getNodeList() );
tGridListIter<tEdge> eiter( g->getEdgeList() );
tListIter<tTriangle> titer( g->getTriList() );
tNode * cn;
tEdge * ce;
tTriangle * ct;
int id;
int nnodes = g->getNodeList()->getSize();
int nedges = g->getEdgeList()->getSize();
int ntri = g->getTriList()->getSize();
cout << "tOutput::WriteOutput()\n";
// Renumber IDs in order by position on list
for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ )
cn->setID( id );
for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ )
ce->setID( id );
for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ )
ct->setID( id );
// Write node file and z file
nodeofs << " " << time << endl << nnodes << endl;
zofs << " " << time << endl << nnodes << endl;
for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() )
{
nodeofs << cn->getX() << " " << cn->getY() << " "
<< cn->getEdg()->getID() << " " << cn->getBoundaryFlag() << endl;
zofs << cn->getZ() << endl;
}
// Write edge file
edgofs << " " << time << endl << nedges << endl;
for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() )
edgofs << ce->getOriginPtrNC()->getID() << " "
<< ce->getDestinationPtrNC()->getID() << " "
<< ce->getCCWEdg()->getID() << endl;
// Write triangle file
int i;
triofs << " " << time << endl << ntri << endl;
for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() )
{
for( i=0; i<=2; i++ )
triofs << ct->pPtr(i)->getID() << " ";
for( i=0; i<=2; i++ )
{
if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << " ";
else triofs << "-1 ";
}
triofs << ct->ePtr(0)->getID() << " "
<< ct->ePtr(1)->getID() << " "
<< ct->ePtr(2)->getID() << endl;
}
WriteNodeData( time );
}
template< class tSubNode >
void tOutput<tSubNode>::WriteNodeData( double time )
{}
template< class tSubNode >
tLOutput<tSubNode>::tLOutput( tGrid<tSubNode> *g, tInputFile &infile )
: tOutput<tSubNode>( g, infile ) // call base-class constructor
{
CreateAndOpenFile( &drareaofs, ".area" );
CreateAndOpenFile( &netofs, ".net" );
CreateAndOpenFile( &slpofs, ".slp" );
CreateAndOpenFile( &qofs, ".q" );
CreateAndOpenFile( &layofs, ".lay" );
CreateAndOpenFile( &texofs, ".tx" );
}
//TODO: should output boundary points as well so they'll map up with nodes
// for plotting. Means changing getSlope so it returns zero if flowedg
// undefined
template< class tSubNode >
void tLOutput<tSubNode>::WriteNodeData( double time )
{
tGridListIter<tSubNode> ni( g->getNodeList() );
tSubNode *cn;
int nActiveNodes = g->getNodeList()->getActiveSize();
int nnodes = g->getNodeList()->getSize();
int i, j;
drareaofs << " " << time << "\n " << nActiveNodes << endl;
netofs << " " << time << "\n " << nActiveNodes << endl;
slpofs << " " << time << "\n " << nActiveNodes << endl;
qofs << " " << time << "\n " << nnodes << endl;
layofs << " " << time << "\n" << nActiveNodes << endl;
texofs << " " << time << "\n" << nnodes << endl;
for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )
{
assert( cn>0 );
drareaofs << cn->getDrArea() << endl;
if( cn->getDownstrmNbr() )
netofs << cn->getDownstrmNbr()->getID() << endl;
slpofs << cn->getSlope() << endl;
layofs << cn->getNumLayer() << endl;
i=0;
while(i<cn->getNumLayer()){
//NIC - change output of layerflag which is obsolete to
//output exposure time - TODO
layofs << cn->getLayerCtime(i) << " " << cn->getLayerRtime(i) << " " << 0 /*cn->getLayerFlag(i)*/ << endl;
layofs << cn->getLayerDepth(i) << " " << cn->getLayerErody(i) << " " << cn->getLayerSed(i) << endl;
j=0;
while(j<cn->getNumg()){
layofs << cn->getLayerDgrade(i,j) << " ";
j++;
}
layofs << endl;
i++;
}
}
for( cn = ni.FirstP(); !(ni.AtEnd()); cn = ni.NextP() ){
qofs << cn->getQ() << endl;
// temporary fix of zero-layer problem (TODO: solve)
/*if( cn->getLayerDgrade(0,0)<1e-6 )
{
cout << "Warning from tOutput::WriteNodeData(): "
<< "Anomalously low top layer dgrade at " << cn->getID() << endl;
texofs << cn->getLayerDgrade(0,0) << endl;
}
else*/
if( cn->getNumg()>1 ) // temporary hack TODO
{
texofs << cn->getLayerDgrade(0,0)/cn->getLayerDepth(0) << endl;
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbtoolsclient.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: rt $ $Date: 2005-09-08 22:49: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 _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_
#include <com/sun/star/sdbc/XDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_
#include <com/sun/star/sdb/SQLContext.hpp>
#endif
#ifndef SVX_DBTOOLSCLIENT_HXX
#include "dbtoolsclient.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
//........................................................................
namespace svxform
{
//........................................................................
using namespace ::connectivity::simple;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::container;
//====================================================================
//= ODbtoolsClient
//====================================================================
::osl::Mutex ODbtoolsClient::s_aMutex;
sal_Int32 ODbtoolsClient::s_nClients = 0;
oslModule ODbtoolsClient::s_hDbtoolsModule = NULL;
createDataAccessToolsFactoryFunction
ODbtoolsClient::s_pFactoryCreationFunc = NULL;
//--------------------------------------------------------------------
ODbtoolsClient::ODbtoolsClient()
{
m_bCreateAlready = FALSE;
}
//--------------------------------------------------------------------
//add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time)
void ODbtoolsClient::create() const
{
if(m_bCreateAlready)
return;
m_bCreateAlready = TRUE;
registerClient();
if (s_pFactoryCreationFunc)
{ // loading the lib succeeded
void* pUntypedFactory = (*s_pFactoryCreationFunc)();
IDataAccessToolsFactory* pDBTFactory = static_cast<IDataAccessToolsFactory*>(pUntypedFactory);
OSL_ENSURE(pDBTFactory, "ODbtoolsClient::ODbtoolsClient: no factory returned!");
if (pDBTFactory)
{
m_xDataAccessFactory = pDBTFactory;
// by definition, the factory was aquired once
m_xDataAccessFactory->release();
}
}
}
//--------------------------------------------------------------------
ODbtoolsClient::~ODbtoolsClient()
{
// clear the factory _before_ revoking the client
// (the revocation may unload the DBT lib)
m_xDataAccessFactory = NULL;
// revoke the client
if ( m_bCreateAlready )
revokeClient();
}
//--------------------------------------------------------------------
void ODbtoolsClient::registerClient()
{
::osl::MutexGuard aGuard(s_aMutex);
if (1 == ++s_nClients)
{
OSL_ENSURE(NULL == s_hDbtoolsModule, "ODbtoolsClient::registerClient: inconsistence: already have a module!");
OSL_ENSURE(NULL == s_pFactoryCreationFunc, "ODbtoolsClient::registerClient: inconsistence: already have a factory function!");
const ::rtl::OUString sModuleName = ::rtl::OUString::createFromAscii(
SVLIBRARY( "dbtools" )
);
// load the dbtools library
s_hDbtoolsModule = osl_loadModule(sModuleName.pData, 0);
OSL_ENSURE(NULL != s_hDbtoolsModule, "ODbtoolsClient::registerClient: could not load the dbtools library!");
if (NULL != s_hDbtoolsModule)
{
// get the symbol for the method creating the factory
const ::rtl::OUString sFactoryCreationFunc = ::rtl::OUString::createFromAscii("createDataAccessToolsFactory");
// reinterpret_cast<createDataAccessToolsFactoryFunction>
s_pFactoryCreationFunc = (createDataAccessToolsFactoryFunction)(
osl_getSymbol(s_hDbtoolsModule, sFactoryCreationFunc.pData));
if (NULL == s_pFactoryCreationFunc)
{ // did not find the symbol
OSL_ENSURE(sal_False, "ODbtoolsClient::registerClient: could not find the symbol for creating the factory!");
osl_unloadModule(s_hDbtoolsModule);
s_hDbtoolsModule = NULL;
}
}
}
}
//--------------------------------------------------------------------
void ODbtoolsClient::revokeClient()
{
::osl::MutexGuard aGuard(s_aMutex);
if (0 == --s_nClients)
{
s_pFactoryCreationFunc = NULL;
if (s_hDbtoolsModule)
osl_unloadModule(s_hDbtoolsModule);
s_hDbtoolsModule = NULL;
}
OSL_ENSURE(s_nClients >= 0,"Illegall call of revokeClient()");
}
//====================================================================
//= OStaticDataAccessTools
//====================================================================
//--------------------------------------------------------------------
OStaticDataAccessTools::OStaticDataAccessTools()
{
}
//--------------------------------------------------------------------
//add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time)
void OStaticDataAccessTools::create() const
{
if (!getFactory().is())
ODbtoolsClient::create();
if (getFactory().is())
m_xDataAccessTools = getFactory()->getDataAccessTools();
}
//--------------------------------------------------------------------
void OStaticDataAccessTools::checkIfLoaded() const
{
if (!m_xDataAccessTools.is())
create();
}
//--------------------------------------------------------------------
Reference< XNumberFormatsSupplier > OStaticDataAccessTools::getNumberFormats(const Reference< XConnection>& _rxConn, sal_Bool _bAllowDefault) const
{
Reference< XNumberFormatsSupplier > xReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
xReturn = m_xDataAccessTools->getNumberFormats(_rxConn, _bAllowDefault);
return xReturn;
}
//--------------------------------------------------------------------
Reference< XConnection> OStaticDataAccessTools::getConnection_withFeedback(const ::rtl::OUString& _rDataSourceName,
const ::rtl::OUString& _rUser, const ::rtl::OUString& _rPwd, const Reference< XMultiServiceFactory>& _rxFactory) const
SAL_THROW ( (SQLException) )
{
Reference< XConnection > xReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
xReturn = m_xDataAccessTools->getConnection_withFeedback(_rDataSourceName, _rUser, _rPwd, _rxFactory);
return xReturn;
}
//--------------------------------------------------------------------
Reference< XConnection > OStaticDataAccessTools::connectRowset( const Reference< XRowSet >& _rxRowSet,
const Reference< XMultiServiceFactory >& _rxFactory, sal_Bool _bSetAsActiveConnection ) const
SAL_THROW ( ( SQLException, WrappedTargetException, RuntimeException ) )
{
Reference< XConnection > xReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
xReturn = m_xDataAccessTools->connectRowset( _rxRowSet, _rxFactory, _bSetAsActiveConnection );
return xReturn;
}
//--------------------------------------------------------------------
Reference< XConnection > OStaticDataAccessTools::getRowSetConnection(const Reference< XRowSet >& _rxRowSet) const SAL_THROW ( (RuntimeException) )
{
Reference< XConnection > xReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
xReturn = m_xDataAccessTools->getRowSetConnection(_rxRowSet);
return xReturn;
}
//--------------------------------------------------------------------
void OStaticDataAccessTools::TransferFormComponentProperties(const Reference< XPropertySet>& _rxOld,
const Reference< XPropertySet>& _rxNew, const Locale& _rLocale) const
{
checkIfLoaded();
if (m_xDataAccessTools.is())
m_xDataAccessTools->TransferFormComponentProperties(_rxOld, _rxNew, _rLocale);
}
//--------------------------------------------------------------------
::rtl::OUString OStaticDataAccessTools::quoteName(const ::rtl::OUString& _rQuote, const ::rtl::OUString& _rName) const
{
::rtl::OUString sReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
sReturn = m_xDataAccessTools->quoteName(_rQuote, _rName);
return sReturn;
}
//--------------------------------------------------------------------
::rtl::OUString OStaticDataAccessTools::quoteTableName(const Reference< XDatabaseMetaData>& _rxMeta, const ::rtl::OUString& _rName
,sal_Bool _bUseCatalogInSelect
,sal_Bool _bUseSchemaInSelect) const
{
::rtl::OUString sReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
sReturn = m_xDataAccessTools->quoteTableName(_rxMeta, _rName,_bUseCatalogInSelect,_bUseSchemaInSelect);
return sReturn;
}
//--------------------------------------------------------------------
SQLContext OStaticDataAccessTools::prependContextInfo(SQLException& _rException, const Reference< XInterface >& _rxContext,
const ::rtl::OUString& _rContextDescription, const ::rtl::OUString& _rContextDetails) const
{
SQLContext aReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
aReturn = m_xDataAccessTools->prependContextInfo(_rException, _rxContext, _rContextDescription, _rContextDetails);
return aReturn;
}
//----------------------------------------------------------------
Reference< XDataSource > OStaticDataAccessTools::getDataSource( const ::rtl::OUString& _rsRegisteredName, const Reference< XMultiServiceFactory>& _rxFactory ) const
{
Reference< XDataSource > xReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
xReturn = m_xDataAccessTools->getDataSource(_rsRegisteredName,_rxFactory);
return xReturn;
}
//----------------------------------------------------------------
sal_Bool OStaticDataAccessTools::canInsert(const Reference< XPropertySet>& _rxCursorSet) const
{
sal_Bool bRet = sal_False;
checkIfLoaded();
if (m_xDataAccessTools.is())
bRet = m_xDataAccessTools->canInsert( _rxCursorSet );
return bRet;
}
//----------------------------------------------------------------
sal_Bool OStaticDataAccessTools::canUpdate(const Reference< XPropertySet>& _rxCursorSet) const
{
sal_Bool bRet = sal_False;
checkIfLoaded();
if (m_xDataAccessTools.is())
bRet = m_xDataAccessTools->canUpdate( _rxCursorSet );
return bRet;
}
//----------------------------------------------------------------
sal_Bool OStaticDataAccessTools::canDelete(const Reference< XPropertySet>& _rxCursorSet) const
{
sal_Bool bRet = sal_False;
checkIfLoaded();
if (m_xDataAccessTools.is())
bRet = m_xDataAccessTools->canDelete( _rxCursorSet );
return bRet;
}
//----------------------------------------------------------------
Reference< XNameAccess > OStaticDataAccessTools::getFieldsByCommandDescriptor( const Reference< XConnection >& _rxConnection,
const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand,
Reference< XComponent >& _rxKeepFieldsAlive, ::dbtools::SQLExceptionInfo* _pErrorInfo ) SAL_THROW( ( ) )
{
Reference< XNameAccess > aFields;
checkIfLoaded();
if ( m_xDataAccessTools.is() )
aFields = m_xDataAccessTools->getFieldsByCommandDescriptor( _rxConnection, _nCommandType,
_rCommand, _rxKeepFieldsAlive, _pErrorInfo );
return aFields;
}
//----------------------------------------------------------------
Sequence< ::rtl::OUString > OStaticDataAccessTools::getFieldNamesByCommandDescriptor(
const Reference< XConnection >& _rxConnection, const sal_Int32 _nCommandType,
const ::rtl::OUString& _rCommand, ::dbtools::SQLExceptionInfo* _pErrorInfo ) SAL_THROW( ( ) )
{
Sequence< ::rtl::OUString > aNames;
checkIfLoaded();
if ( m_xDataAccessTools.is() )
aNames = m_xDataAccessTools->getFieldNamesByCommandDescriptor( _rxConnection, _nCommandType,
_rCommand, _pErrorInfo );
return aNames;
}
//----------------------------------------------------------------
sal_Bool OStaticDataAccessTools::isDataSourcePropertyEnabled(const Reference< XInterface>& _xProp
,const ::rtl::OUString& _sProperty,
sal_Bool _bDefault) const
{
sal_Bool bRet = _bDefault;
checkIfLoaded();
if ( m_xDataAccessTools.is() )
bRet = m_xDataAccessTools->isDataSourcePropertyEnabled( _xProp,_sProperty ,_bDefault );
return bRet;
}
//----------------------------------------------------------------
bool OStaticDataAccessTools::isEmbeddedInDatabase( const Reference< XInterface >& _rxComponent, Reference< XConnection >& _rxActualConnection )
{
bool bReturn = false;
checkIfLoaded();
if ( m_xDataAccessTools.is() )
bReturn = m_xDataAccessTools->isEmbeddedInDatabase( _rxComponent, _rxActualConnection );
return bReturn;
}
//----------------------------------------------------------------
bool OStaticDataAccessTools::isEmbeddedInDatabase( const Reference< XInterface >& _rxComponent )
{
bool bReturn = false;
checkIfLoaded();
if ( m_xDataAccessTools.is() )
{
Reference< XConnection > xDummy;
bReturn = m_xDataAccessTools->isEmbeddedInDatabase( _rxComponent, xDummy );
}
return bReturn;
}
//........................................................................
} // namespace svxform
//........................................................................
<commit_msg>INTEGRATION: CWS dba203b (1.15.338); FILE MERGED 2006/03/28 06:06:21 fs 1.15.338.1: #109241# +getDefaultNumberFormat<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbtoolsclient.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: vg $ $Date: 2006-03-31 12:10:28 $
*
* 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 _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_
#include <com/sun/star/sdbc/XDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_
#include <com/sun/star/sdb/SQLContext.hpp>
#endif
#ifndef SVX_DBTOOLSCLIENT_HXX
#include "dbtoolsclient.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
//........................................................................
namespace svxform
{
//........................................................................
using namespace ::connectivity::simple;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::container;
//====================================================================
//= ODbtoolsClient
//====================================================================
::osl::Mutex ODbtoolsClient::s_aMutex;
sal_Int32 ODbtoolsClient::s_nClients = 0;
oslModule ODbtoolsClient::s_hDbtoolsModule = NULL;
createDataAccessToolsFactoryFunction
ODbtoolsClient::s_pFactoryCreationFunc = NULL;
//--------------------------------------------------------------------
ODbtoolsClient::ODbtoolsClient()
{
m_bCreateAlready = FALSE;
}
//--------------------------------------------------------------------
//add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time)
void ODbtoolsClient::create() const
{
if(m_bCreateAlready)
return;
m_bCreateAlready = TRUE;
registerClient();
if (s_pFactoryCreationFunc)
{ // loading the lib succeeded
void* pUntypedFactory = (*s_pFactoryCreationFunc)();
IDataAccessToolsFactory* pDBTFactory = static_cast<IDataAccessToolsFactory*>(pUntypedFactory);
OSL_ENSURE(pDBTFactory, "ODbtoolsClient::ODbtoolsClient: no factory returned!");
if (pDBTFactory)
{
m_xDataAccessFactory = pDBTFactory;
// by definition, the factory was aquired once
m_xDataAccessFactory->release();
}
}
}
//--------------------------------------------------------------------
ODbtoolsClient::~ODbtoolsClient()
{
// clear the factory _before_ revoking the client
// (the revocation may unload the DBT lib)
m_xDataAccessFactory = NULL;
// revoke the client
if ( m_bCreateAlready )
revokeClient();
}
//--------------------------------------------------------------------
void ODbtoolsClient::registerClient()
{
::osl::MutexGuard aGuard(s_aMutex);
if (1 == ++s_nClients)
{
OSL_ENSURE(NULL == s_hDbtoolsModule, "ODbtoolsClient::registerClient: inconsistence: already have a module!");
OSL_ENSURE(NULL == s_pFactoryCreationFunc, "ODbtoolsClient::registerClient: inconsistence: already have a factory function!");
const ::rtl::OUString sModuleName = ::rtl::OUString::createFromAscii(
SVLIBRARY( "dbtools" )
);
// load the dbtools library
s_hDbtoolsModule = osl_loadModule(sModuleName.pData, 0);
OSL_ENSURE(NULL != s_hDbtoolsModule, "ODbtoolsClient::registerClient: could not load the dbtools library!");
if (NULL != s_hDbtoolsModule)
{
// get the symbol for the method creating the factory
const ::rtl::OUString sFactoryCreationFunc = ::rtl::OUString::createFromAscii("createDataAccessToolsFactory");
// reinterpret_cast<createDataAccessToolsFactoryFunction>
s_pFactoryCreationFunc = (createDataAccessToolsFactoryFunction)(
osl_getSymbol(s_hDbtoolsModule, sFactoryCreationFunc.pData));
if (NULL == s_pFactoryCreationFunc)
{ // did not find the symbol
OSL_ENSURE(sal_False, "ODbtoolsClient::registerClient: could not find the symbol for creating the factory!");
osl_unloadModule(s_hDbtoolsModule);
s_hDbtoolsModule = NULL;
}
}
}
}
//--------------------------------------------------------------------
void ODbtoolsClient::revokeClient()
{
::osl::MutexGuard aGuard(s_aMutex);
if (0 == --s_nClients)
{
s_pFactoryCreationFunc = NULL;
if (s_hDbtoolsModule)
osl_unloadModule(s_hDbtoolsModule);
s_hDbtoolsModule = NULL;
}
OSL_ENSURE(s_nClients >= 0,"Illegall call of revokeClient()");
}
//====================================================================
//= OStaticDataAccessTools
//====================================================================
//--------------------------------------------------------------------
OStaticDataAccessTools::OStaticDataAccessTools()
{
}
//--------------------------------------------------------------------
//add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time)
void OStaticDataAccessTools::create() const
{
if (!getFactory().is())
ODbtoolsClient::create();
if (getFactory().is())
m_xDataAccessTools = getFactory()->getDataAccessTools();
}
//--------------------------------------------------------------------
void OStaticDataAccessTools::checkIfLoaded() const
{
if (!m_xDataAccessTools.is())
create();
}
//--------------------------------------------------------------------
Reference< XNumberFormatsSupplier > OStaticDataAccessTools::getNumberFormats(const Reference< XConnection>& _rxConn, sal_Bool _bAllowDefault) const
{
Reference< XNumberFormatsSupplier > xReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
xReturn = m_xDataAccessTools->getNumberFormats(_rxConn, _bAllowDefault);
return xReturn;
}
//--------------------------------------------------------------------
sal_Int32 OStaticDataAccessTools::getDefaultNumberFormat( const Reference< XPropertySet >& _xColumn, const Reference< XNumberFormatTypes >& _xTypes, const Locale& _rLocale )
{
sal_Int32 nReturn = 0;
checkIfLoaded();
if (m_xDataAccessTools.is())
nReturn = m_xDataAccessTools->getDefaultNumberFormat( _xColumn, _xTypes, _rLocale );
return nReturn;
}
//--------------------------------------------------------------------
Reference< XConnection> OStaticDataAccessTools::getConnection_withFeedback(const ::rtl::OUString& _rDataSourceName,
const ::rtl::OUString& _rUser, const ::rtl::OUString& _rPwd, const Reference< XMultiServiceFactory>& _rxFactory) const
SAL_THROW ( (SQLException) )
{
Reference< XConnection > xReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
xReturn = m_xDataAccessTools->getConnection_withFeedback(_rDataSourceName, _rUser, _rPwd, _rxFactory);
return xReturn;
}
//--------------------------------------------------------------------
Reference< XConnection > OStaticDataAccessTools::connectRowset( const Reference< XRowSet >& _rxRowSet,
const Reference< XMultiServiceFactory >& _rxFactory, sal_Bool _bSetAsActiveConnection ) const
SAL_THROW ( ( SQLException, WrappedTargetException, RuntimeException ) )
{
Reference< XConnection > xReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
xReturn = m_xDataAccessTools->connectRowset( _rxRowSet, _rxFactory, _bSetAsActiveConnection );
return xReturn;
}
//--------------------------------------------------------------------
Reference< XConnection > OStaticDataAccessTools::getRowSetConnection(const Reference< XRowSet >& _rxRowSet) const SAL_THROW ( (RuntimeException) )
{
Reference< XConnection > xReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
xReturn = m_xDataAccessTools->getRowSetConnection(_rxRowSet);
return xReturn;
}
//--------------------------------------------------------------------
void OStaticDataAccessTools::TransferFormComponentProperties(const Reference< XPropertySet>& _rxOld,
const Reference< XPropertySet>& _rxNew, const Locale& _rLocale) const
{
checkIfLoaded();
if (m_xDataAccessTools.is())
m_xDataAccessTools->TransferFormComponentProperties(_rxOld, _rxNew, _rLocale);
}
//--------------------------------------------------------------------
::rtl::OUString OStaticDataAccessTools::quoteName(const ::rtl::OUString& _rQuote, const ::rtl::OUString& _rName) const
{
::rtl::OUString sReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
sReturn = m_xDataAccessTools->quoteName(_rQuote, _rName);
return sReturn;
}
//--------------------------------------------------------------------
::rtl::OUString OStaticDataAccessTools::quoteTableName(const Reference< XDatabaseMetaData>& _rxMeta, const ::rtl::OUString& _rName
,sal_Bool _bUseCatalogInSelect
,sal_Bool _bUseSchemaInSelect) const
{
::rtl::OUString sReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
sReturn = m_xDataAccessTools->quoteTableName(_rxMeta, _rName,_bUseCatalogInSelect,_bUseSchemaInSelect);
return sReturn;
}
//--------------------------------------------------------------------
SQLContext OStaticDataAccessTools::prependContextInfo(SQLException& _rException, const Reference< XInterface >& _rxContext,
const ::rtl::OUString& _rContextDescription, const ::rtl::OUString& _rContextDetails) const
{
SQLContext aReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
aReturn = m_xDataAccessTools->prependContextInfo(_rException, _rxContext, _rContextDescription, _rContextDetails);
return aReturn;
}
//----------------------------------------------------------------
Reference< XDataSource > OStaticDataAccessTools::getDataSource( const ::rtl::OUString& _rsRegisteredName, const Reference< XMultiServiceFactory>& _rxFactory ) const
{
Reference< XDataSource > xReturn;
checkIfLoaded();
if (m_xDataAccessTools.is())
xReturn = m_xDataAccessTools->getDataSource(_rsRegisteredName,_rxFactory);
return xReturn;
}
//----------------------------------------------------------------
sal_Bool OStaticDataAccessTools::canInsert(const Reference< XPropertySet>& _rxCursorSet) const
{
sal_Bool bRet = sal_False;
checkIfLoaded();
if (m_xDataAccessTools.is())
bRet = m_xDataAccessTools->canInsert( _rxCursorSet );
return bRet;
}
//----------------------------------------------------------------
sal_Bool OStaticDataAccessTools::canUpdate(const Reference< XPropertySet>& _rxCursorSet) const
{
sal_Bool bRet = sal_False;
checkIfLoaded();
if (m_xDataAccessTools.is())
bRet = m_xDataAccessTools->canUpdate( _rxCursorSet );
return bRet;
}
//----------------------------------------------------------------
sal_Bool OStaticDataAccessTools::canDelete(const Reference< XPropertySet>& _rxCursorSet) const
{
sal_Bool bRet = sal_False;
checkIfLoaded();
if (m_xDataAccessTools.is())
bRet = m_xDataAccessTools->canDelete( _rxCursorSet );
return bRet;
}
//----------------------------------------------------------------
Reference< XNameAccess > OStaticDataAccessTools::getFieldsByCommandDescriptor( const Reference< XConnection >& _rxConnection,
const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand,
Reference< XComponent >& _rxKeepFieldsAlive, ::dbtools::SQLExceptionInfo* _pErrorInfo ) SAL_THROW( ( ) )
{
Reference< XNameAccess > aFields;
checkIfLoaded();
if ( m_xDataAccessTools.is() )
aFields = m_xDataAccessTools->getFieldsByCommandDescriptor( _rxConnection, _nCommandType,
_rCommand, _rxKeepFieldsAlive, _pErrorInfo );
return aFields;
}
//----------------------------------------------------------------
Sequence< ::rtl::OUString > OStaticDataAccessTools::getFieldNamesByCommandDescriptor(
const Reference< XConnection >& _rxConnection, const sal_Int32 _nCommandType,
const ::rtl::OUString& _rCommand, ::dbtools::SQLExceptionInfo* _pErrorInfo ) SAL_THROW( ( ) )
{
Sequence< ::rtl::OUString > aNames;
checkIfLoaded();
if ( m_xDataAccessTools.is() )
aNames = m_xDataAccessTools->getFieldNamesByCommandDescriptor( _rxConnection, _nCommandType,
_rCommand, _pErrorInfo );
return aNames;
}
//----------------------------------------------------------------
sal_Bool OStaticDataAccessTools::isDataSourcePropertyEnabled(const Reference< XInterface>& _xProp
,const ::rtl::OUString& _sProperty,
sal_Bool _bDefault) const
{
sal_Bool bRet = _bDefault;
checkIfLoaded();
if ( m_xDataAccessTools.is() )
bRet = m_xDataAccessTools->isDataSourcePropertyEnabled( _xProp,_sProperty ,_bDefault );
return bRet;
}
//----------------------------------------------------------------
bool OStaticDataAccessTools::isEmbeddedInDatabase( const Reference< XInterface >& _rxComponent, Reference< XConnection >& _rxActualConnection )
{
bool bReturn = false;
checkIfLoaded();
if ( m_xDataAccessTools.is() )
bReturn = m_xDataAccessTools->isEmbeddedInDatabase( _rxComponent, _rxActualConnection );
return bReturn;
}
//----------------------------------------------------------------
bool OStaticDataAccessTools::isEmbeddedInDatabase( const Reference< XInterface >& _rxComponent )
{
bool bReturn = false;
checkIfLoaded();
if ( m_xDataAccessTools.is() )
{
Reference< XConnection > xDummy;
bReturn = m_xDataAccessTools->isEmbeddedInDatabase( _rxComponent, xDummy );
}
return bReturn;
}
//........................................................................
} // namespace svxform
//........................................................................
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2008-2012, Shane Liesegang
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the copyright holder nor the names of any
// 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.
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "../UI/GwenRenderer.h"
#include "Gwen/Utility.h"
#include "Gwen/Font.h"
#include "Gwen/Texture.h"
#include "Gwen/WindowProvider.h"
#include "../Infrastructure/Textures.h"
#include "../Infrastructure/TextRendering.h"
#include "../Infrastructure/Camera.h"
#include "../Infrastructure/Log.h"
GwenRenderer::GwenRenderer()
{
_vertNum = 0;
for (int i=0; i < s_maxVerts; i++)
{
_vertices[ i ].z = 0.5f;
}
}
GwenRenderer::~GwenRenderer()
{
}
void GwenRenderer::Init()
{
}
void GwenRenderer::Begin()
{
glAlphaFunc( GL_GREATER, 1.0f );
Vec2i winDimensions;
winDimensions.X = theCamera.GetWindowWidth();
winDimensions.Y = theCamera.GetWindowHeight();
//set up projection
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0, winDimensions.X, winDimensions.Y, 0);
//set up modelview
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
}
void GwenRenderer::End()
{
Flush();
glAlphaFunc(GL_ALWAYS, 0.0f);
glDisableClientState( GL_COLOR_ARRAY );
glDisable(GL_TEXTURE_2D);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
void GwenRenderer::Flush()
{
if ( _vertNum == 0 )
{
return;
}
glVertexPointer( 3, GL_FLOAT, sizeof(Vertex), (void*) &_vertices[0].x );
glEnableClientState( GL_VERTEX_ARRAY );
glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof(Vertex), (void*)&_vertices[0].r );
glEnableClientState( GL_COLOR_ARRAY );
glTexCoordPointer( 2, GL_FLOAT, sizeof(Vertex), (void*) &_vertices[0].u );
glEnableClientState( GL_TEXTURE_COORD_ARRAY );
glDrawArrays( GL_TRIANGLES, 0, (GLsizei) _vertNum );
_vertNum = 0;
}
void GwenRenderer::AddVertex(int x, int y, float u, float v)
{
if ( _vertNum >= s_maxVerts - 1 )
{
Flush();
}
_vertices[ _vertNum ].x = (float)x;
_vertices[ _vertNum ].y = (float)y;
_vertices[ _vertNum ].u = u;
_vertices[ _vertNum ].v = v;
_vertices[ _vertNum ].r = _color.r;
_vertices[ _vertNum ].g = _color.g;
_vertices[ _vertNum ].b = _color.b;
_vertices[ _vertNum ].a = _color.a;
_vertNum++;
}
void GwenRenderer::SetDrawColor( Gwen::Color color )
{
glColor4ubv( (GLubyte*)&color );
_color = color;
}
void GwenRenderer::DrawFilledRect( Gwen::Rect rect )
{
GLboolean texturesOn;
glGetBooleanv(GL_TEXTURE_2D, &texturesOn);
if ( texturesOn )
{
Flush();
glDisable(GL_TEXTURE_2D);
}
Translate( rect );
AddVertex( rect.x, rect.y + rect.h );
AddVertex( rect.x+rect.w, rect.y );
AddVertex( rect.x, rect.y );
AddVertex( rect.x, rect.y + rect.h );
AddVertex( rect.x+rect.w, rect.y+rect.h );
AddVertex( rect.x+rect.w, rect.y );
}
void GwenRenderer::DrawTexturedRect( Gwen::Texture* texture, Gwen::Rect targetRect, float u1, float v1, float u2, float v2)
{
GLuint tex = (GLuint)texture->data;
if (!tex)
{
return DrawMissingImage(targetRect);
}
v1 = 1.0f - v1;
v2 = 1.0f - v2;
Translate(targetRect);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, tex);
AddVertex( targetRect.x, targetRect.y + targetRect.h, u1, v2 );
AddVertex( targetRect.x+targetRect.w, targetRect.y, u2, v1 );
AddVertex( targetRect.x, targetRect.y, u1, v1 );
AddVertex( targetRect.x, targetRect.y + targetRect.h, u1, v2 );
AddVertex( targetRect.x+targetRect.w, targetRect.y+targetRect.h, u2, v2 );
AddVertex( targetRect.x+targetRect.w, targetRect.y, u2, v1 );
}
void GwenRenderer::StartClip()
{
return;
Flush();
Gwen::Rect rect = ClipRegion();
// OpenGL's coords are from the bottom left
// so we need to translate them here.
// {
// GLint view[4];
// glGetIntegerv( GL_VIEWPORT, &view[0] );
// rect.y = view[3] - (rect.y + rect.h);
// }
glScissor( rect.x * Scale(), rect.y * Scale(), rect.w * Scale(), rect.h * Scale() );
glEnable( GL_SCISSOR_TEST );
}
void GwenRenderer::EndClip()
{
return;
Flush();
glDisable( GL_SCISSOR_TEST );
}
void GwenRenderer::LoadTexture( Gwen::Texture* texture )
{
const int texID = GetTextureReference(texture->name.Get());
if (texID < 0)
{
texture->failed = true;
texture->data = 0;
}
else
{
texture->failed = false;
texture->data = (void*)texID;
const Vec2i dimensions = GetTextureSize(texture->name.Get());
texture->width = dimensions.X;
texture->height = dimensions.Y;
}
}
void GwenRenderer::FreeTexture( Gwen::Texture* texture )
{
PurgeTexture(texture->name.Get());
}
//void GwenRenderer::DrawMissingImage( Gwen::Rect targetRect )
//{
//
//}
Gwen::Color GwenRenderer::PixelColour( Gwen::Texture* texture, unsigned int x, unsigned int y, const Gwen::Color& col_default)
{
GLuint tex = (GLuint)texture->data;
if ( !tex ) return col_default;
unsigned int pixelSize = sizeof(unsigned char) * 4;
glBindTexture( GL_TEXTURE_2D, tex );
unsigned char* data = (unsigned char*) malloc( pixelSize * texture->width * texture->height );
glGetTexImage( GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
unsigned int offset = ((texture->height - y) * texture->width + x) * 4;
Gwen::Color c;
c.r = data[0 + offset];
c.g = data[1 + offset];
c.b = data[2 + offset];
c.a = data[3 + offset];
//
// Retrieving the entire texture for a single pixel read
// is kind of a waste - maybe cache this pointer in the texture
// data and then release later on? It's never called during runtime
// - only during initialization.
//
free( data );
return c;
}
//Gwen::Renderer::ICacheToTexture* GwenRenderer::GetCTT()
//{
// return NULL;
//}
void GwenRenderer::LoadFont( Gwen::Font* font )
{
font->realsize = font->size * Scale();
String fontName = Gwen::Utility::UnicodeToString(font->facename);
_unicodeCache[font->facename] = fontName;
if (!IsFontRegistered(fontName))
{
if (RegisterFont(fontName, font->realsize, fontName))
{
font->data = (void*)1;
}
else
{
font->data = NULL;
}
}
}
void GwenRenderer::FreeFont( Gwen::Font* font )
{
std::map<Gwen::UnicodeString, String>::iterator it = _unicodeCache.find(font->facename);
if (it != _unicodeCache.end())
{
UnRegisterFont(it->second);
}
}
void GwenRenderer::RenderText( Gwen::Font* font, Gwen::Point pos, const Gwen::UnicodeString& text )
{
Flush();
Translate(pos.x, pos.y);
// UGH there must be a more efficient way to handle this without rewriting the placement functions in gwen
Vector2 extents = GetTextExtents(Gwen::Utility::UnicodeToString(text), Gwen::Utility::UnicodeToString(font->facename));
pos.y += extents.Y;
glColor4ubv( (GLubyte*)&_color );
DrawGameText(Gwen::Utility::UnicodeToString(text), Gwen::Utility::UnicodeToString(font->facename), pos.x, pos.y);
}
Gwen::Point GwenRenderer::MeasureText( Gwen::Font* font, const Gwen::UnicodeString& text )
{
if (font->data == NULL)
{
LoadFont(font);
}
Vector2 extents = GetTextExtents(Gwen::Utility::UnicodeToString(text), Gwen::Utility::UnicodeToString(font->facename));
return Gwen::Point((int)extents.X, (int)extents.Y);
}
//
// No need to implement these functions in your derived class, but if
// you can do them faster than the default implementation it's a good idea to.
//
/*
void GwenRenderer::DrawLinedRect( Gwen::Rect rect )
{
}
void GwenRenderer::DrawPixel( int x, int y )
{
}
void GwenRenderer::DrawShavedCornerRect( Gwen::Rect rect, bool bSlight = false )
{
}
*/<commit_msg>Fixing clip rectangles<commit_after>//////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2008-2012, Shane Liesegang
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the copyright holder nor the names of any
// 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.
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "../UI/GwenRenderer.h"
#include "Gwen/Utility.h"
#include "Gwen/Font.h"
#include "Gwen/Texture.h"
#include "Gwen/WindowProvider.h"
#include "../Infrastructure/Textures.h"
#include "../Infrastructure/TextRendering.h"
#include "../Infrastructure/Camera.h"
#include "../Infrastructure/Log.h"
GwenRenderer::GwenRenderer()
{
_vertNum = 0;
for (int i=0; i < s_maxVerts; i++)
{
_vertices[ i ].z = 0.5f;
}
}
GwenRenderer::~GwenRenderer()
{
}
void GwenRenderer::Init()
{
}
void GwenRenderer::Begin()
{
glAlphaFunc( GL_GREATER, 1.0f );
Vec2i winDimensions;
winDimensions.X = theCamera.GetWindowWidth();
winDimensions.Y = theCamera.GetWindowHeight();
//set up projection
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0, winDimensions.X, winDimensions.Y, 0);
//set up modelview
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
}
void GwenRenderer::End()
{
Flush();
glAlphaFunc(GL_ALWAYS, 0.0f);
glDisableClientState( GL_COLOR_ARRAY );
glDisable(GL_TEXTURE_2D);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
void GwenRenderer::Flush()
{
if ( _vertNum == 0 )
{
return;
}
glVertexPointer( 3, GL_FLOAT, sizeof(Vertex), (void*) &_vertices[0].x );
glEnableClientState( GL_VERTEX_ARRAY );
glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof(Vertex), (void*)&_vertices[0].r );
glEnableClientState( GL_COLOR_ARRAY );
glTexCoordPointer( 2, GL_FLOAT, sizeof(Vertex), (void*) &_vertices[0].u );
glEnableClientState( GL_TEXTURE_COORD_ARRAY );
glDrawArrays( GL_TRIANGLES, 0, (GLsizei) _vertNum );
_vertNum = 0;
}
void GwenRenderer::AddVertex(int x, int y, float u, float v)
{
if ( _vertNum >= s_maxVerts - 1 )
{
Flush();
}
_vertices[ _vertNum ].x = (float)x;
_vertices[ _vertNum ].y = (float)y;
_vertices[ _vertNum ].u = u;
_vertices[ _vertNum ].v = v;
_vertices[ _vertNum ].r = _color.r;
_vertices[ _vertNum ].g = _color.g;
_vertices[ _vertNum ].b = _color.b;
_vertices[ _vertNum ].a = _color.a;
_vertNum++;
}
void GwenRenderer::SetDrawColor( Gwen::Color color )
{
glColor4ubv( (GLubyte*)&color );
_color = color;
}
void GwenRenderer::DrawFilledRect( Gwen::Rect rect )
{
GLboolean texturesOn;
glGetBooleanv(GL_TEXTURE_2D, &texturesOn);
if ( texturesOn )
{
Flush();
glDisable(GL_TEXTURE_2D);
}
Translate( rect );
AddVertex( rect.x, rect.y + rect.h );
AddVertex( rect.x+rect.w, rect.y );
AddVertex( rect.x, rect.y );
AddVertex( rect.x, rect.y + rect.h );
AddVertex( rect.x+rect.w, rect.y+rect.h );
AddVertex( rect.x+rect.w, rect.y );
}
void GwenRenderer::DrawTexturedRect( Gwen::Texture* texture, Gwen::Rect targetRect, float u1, float v1, float u2, float v2)
{
GLuint tex = (GLuint)texture->data;
if (!tex)
{
return DrawMissingImage(targetRect);
}
v1 = 1.0f - v1;
v2 = 1.0f - v2;
Translate(targetRect);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, tex);
AddVertex( targetRect.x, targetRect.y + targetRect.h, u1, v2 );
AddVertex( targetRect.x+targetRect.w, targetRect.y, u2, v1 );
AddVertex( targetRect.x, targetRect.y, u1, v1 );
AddVertex( targetRect.x, targetRect.y + targetRect.h, u1, v2 );
AddVertex( targetRect.x+targetRect.w, targetRect.y+targetRect.h, u2, v2 );
AddVertex( targetRect.x+targetRect.w, targetRect.y, u2, v1 );
}
void GwenRenderer::StartClip()
{
Flush();
Gwen::Rect rect = ClipRegion();
// OpenGL's coords are from the bottom left
// so we need to translate them here.
{
GLint view[4];
glGetIntegerv( GL_VIEWPORT, &view[0] );
rect.y = view[3] - (rect.y + rect.h);
}
glScissor( rect.x * Scale(), rect.y * Scale(), rect.w * Scale(), rect.h * Scale() );
glEnable( GL_SCISSOR_TEST );
}
void GwenRenderer::EndClip()
{
Flush();
glDisable( GL_SCISSOR_TEST );
}
void GwenRenderer::LoadTexture( Gwen::Texture* texture )
{
const int texID = GetTextureReference(texture->name.Get());
if (texID < 0)
{
texture->failed = true;
texture->data = 0;
}
else
{
texture->failed = false;
texture->data = (void*)texID;
const Vec2i dimensions = GetTextureSize(texture->name.Get());
texture->width = dimensions.X;
texture->height = dimensions.Y;
}
}
void GwenRenderer::FreeTexture( Gwen::Texture* texture )
{
PurgeTexture(texture->name.Get());
}
//void GwenRenderer::DrawMissingImage( Gwen::Rect targetRect )
//{
//
//}
Gwen::Color GwenRenderer::PixelColour( Gwen::Texture* texture, unsigned int x, unsigned int y, const Gwen::Color& col_default)
{
GLuint tex = (GLuint)texture->data;
if ( !tex ) return col_default;
unsigned int pixelSize = sizeof(unsigned char) * 4;
glBindTexture( GL_TEXTURE_2D, tex );
unsigned char* data = (unsigned char*) malloc( pixelSize * texture->width * texture->height );
glGetTexImage( GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
unsigned int offset = ((texture->height - y) * texture->width + x) * 4;
Gwen::Color c;
c.r = data[0 + offset];
c.g = data[1 + offset];
c.b = data[2 + offset];
c.a = data[3 + offset];
//
// Retrieving the entire texture for a single pixel read
// is kind of a waste - maybe cache this pointer in the texture
// data and then release later on? It's never called during runtime
// - only during initialization.
//
free( data );
return c;
}
//Gwen::Renderer::ICacheToTexture* GwenRenderer::GetCTT()
//{
// return NULL;
//}
void GwenRenderer::LoadFont( Gwen::Font* font )
{
font->realsize = font->size * Scale();
String fontName = Gwen::Utility::UnicodeToString(font->facename);
_unicodeCache[font->facename] = fontName;
if (!IsFontRegistered(fontName))
{
if (RegisterFont(fontName, font->realsize, fontName))
{
font->data = (void*)1;
}
else
{
font->data = NULL;
}
}
}
void GwenRenderer::FreeFont( Gwen::Font* font )
{
std::map<Gwen::UnicodeString, String>::iterator it = _unicodeCache.find(font->facename);
if (it != _unicodeCache.end())
{
UnRegisterFont(it->second);
}
}
void GwenRenderer::RenderText( Gwen::Font* font, Gwen::Point pos, const Gwen::UnicodeString& text )
{
Flush();
Translate(pos.x, pos.y);
// UGH there must be a more efficient way to handle this without rewriting the placement functions in gwen
Vector2 extents = GetTextExtents(Gwen::Utility::UnicodeToString(text), Gwen::Utility::UnicodeToString(font->facename));
pos.y += extents.Y;
glColor4ubv( (GLubyte*)&_color );
DrawGameText(Gwen::Utility::UnicodeToString(text), Gwen::Utility::UnicodeToString(font->facename), pos.x, pos.y);
}
Gwen::Point GwenRenderer::MeasureText( Gwen::Font* font, const Gwen::UnicodeString& text )
{
if (font->data == NULL)
{
LoadFont(font);
}
Vector2 extents = GetTextExtents(Gwen::Utility::UnicodeToString(text), Gwen::Utility::UnicodeToString(font->facename));
return Gwen::Point((int)extents.X, (int)extents.Y);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accpage.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:53:17 $
*
* 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 _ACCPAGE_HXX
#define _ACCPAGE_HXX
#ifndef _ACCCONTEXT_HXX
#include "acccontext.hxx"
#endif
/**
* accessibility implementation for the page (SwPageFrm)
* The page is _only_ visible in the page preview. For the regular
* document view, it doesn't make sense to add this additional element
* into the hierarchy. For the page preview, however, the page is the
* important.
*/
class SwAccessiblePage : public SwAccessibleContext
{
sal_Bool bIsSelected; // protected by base class mutex
sal_Bool IsSelected();
protected:
// return the bounding box for the page in page preview mode
SwRect GetBounds( /* const SwFrm *pFrm =0 */ );
// Set states for getAccessibleStateSet.
// This drived class additionaly sets
// FOCUSABLE(1) and FOCUSED(+)
virtual void GetStates( ::utl::AccessibleStateSetHelper& rStateSet );
virtual void _InvalidateCursorPos();
virtual void _InvalidateFocus();
virtual ~SwAccessiblePage();
public:
// convenience constructor to avoid typecast;
// may only be called with SwPageFrm argument
SwAccessiblePage( SwAccessibleMap* pMap, const SwFrm *pFrame );
//
// XAccessibleContext methods that need to be overridden
//
virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException);
//
// XServiceInfo
//
virtual ::rtl::OUString SAL_CALL getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService (
const ::rtl::OUString& sServiceName)
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
getSupportedServiceNames (void)
throw (::com::sun::star::uno::RuntimeException);
//===== XTypeProvider ====================================================
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool HasCursor(); // required by map to remember that object
};
#endif
<commit_msg>INTEGRATION: CWS swwarnings (1.6.710); FILE MERGED 2007/03/08 15:18:42 od 1.6.710.2: #i69287# warning free code 2007/03/05 12:45:23 tl 1.6.710.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accpage.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-09-27 08:23:07 $
*
* 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 _ACCPAGE_HXX
#define _ACCPAGE_HXX
#ifndef _ACCCONTEXT_HXX
#include "acccontext.hxx"
#endif
/**
* accessibility implementation for the page (SwPageFrm)
* The page is _only_ visible in the page preview. For the regular
* document view, it doesn't make sense to add this additional element
* into the hierarchy. For the page preview, however, the page is the
* important.
*/
class SwAccessiblePage : public SwAccessibleContext
{
sal_Bool bIsSelected; // protected by base class mutex
sal_Bool IsSelected();
protected:
// return the bounding box for the page in page preview mode
using SwAccessibleFrame::GetBounds;
SwRect GetBounds( /* const SwFrm *pFrm =0 */ );
// Set states for getAccessibleStateSet.
// This drived class additionaly sets
// FOCUSABLE(1) and FOCUSED(+)
virtual void GetStates( ::utl::AccessibleStateSetHelper& rStateSet );
virtual void _InvalidateCursorPos();
virtual void _InvalidateFocus();
virtual ~SwAccessiblePage();
public:
// convenience constructor to avoid typecast;
// may only be called with SwPageFrm argument
SwAccessiblePage( SwAccessibleMap* pInitMap, const SwFrm* pFrame );
//
// XAccessibleContext methods that need to be overridden
//
virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException);
//
// XServiceInfo
//
virtual ::rtl::OUString SAL_CALL getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService (
const ::rtl::OUString& sServiceName)
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
getSupportedServiceNames (void)
throw (::com::sun::star::uno::RuntimeException);
//===== XTypeProvider ====================================================
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool HasCursor(); // required by map to remember that object
};
#endif
<|endoftext|> |
<commit_before>/* ****************************************************************************
*
* FILE main_UnitTest.cpp
*
* AUTHOR Javier Lois
*
* DATE December 2011
*
* DESCRIPTION
*
* Main file for the automatic unit testing application
*
*/
#include "gtest/gtest.h"
/* ****************************************************************************
*
* main -
*/
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>initialise log in unit testing to remove annoying 'call lmInit' error messages<commit_after>/* ****************************************************************************
*
* FILE main_UnitTest.cpp
*
* AUTHOR Javier Lois
*
* DATE December 2011
*
* DESCRIPTION
*
* Main file for the automatic unit testing application
*
*/
#include <stdio.h>
#include "gtest/gtest.h"
#include "parseArgs/parseArgs.h"
#include "samson/common/traces.h"
#include "samson/common/SamsonSetup.h"
#include "logMsg/logMsg.h"
/* ****************************************************************************
*
* initLog -
*/
void initLog(char* pname)
{
//Initialise log
LmStatus s;
char w[512];
int lmSd;
int fd = 1;
progName = (char*)malloc(512);
strcpy(progName, pname);
/*if ((progName = lmProgName(pname, 1, false)) == NULL)
{
return;
}*/
s = lmFdRegister(fd, "DEF", "DEF", "stdout", &lmSd);
if (s != LmsOk)
{
sprintf(w, "lmFdRegister: %s", lmStrerror(s));
std::cerr << w << std::endl;
return;
}
lmExitFunction(NULL, NULL);
if ((s = lmInit()) != LmsOk)
{
sprintf(w, "lmInit: %s", lmStrerror(s));
std::cerr << w << std::endl;
return;
}
}
/* ****************************************************************************
*
* main -
*/
int main(int argc, char **argv) {
/* paConfig("usage and exit on any warning", (void*) false);
paConfig("log to screen", (void*) true);
paConfig("log file line format", (void*) "TYPE:DATE:EXEC-AUX/FILE[LINE] (p.PID) FUNC: TEXT");
paConfig("screen line format", (void*) "TYPE: TEXT");
paConfig("log to file", (void*) false);
samson::SamsonSetup::init("","");
*/ //char* pname = (char*)malloc(255);
//initLog(argv[0]);
//int logfdp;
//samson::samsonInitTrace(argc, const_cast<const char**>(argv), &logfdp, true, false);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* 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: ascatr.cxx,v $
* $Revision: 1.10 $
*
* 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_sw.hxx"
#include <hintids.hxx>
#include <tools/stream.hxx>
#ifndef _SVSTDARR_HXX
#define _SVSTDARR_USHORTS
#include <svl/svstdarr.hxx>
#endif
#include <svx/fontitem.hxx>
#include <pam.hxx>
#include <doc.hxx>
#include <ndtxt.hxx>
#include <wrtasc.hxx>
#include <txatbase.hxx>
#include <fchrfmt.hxx>
#include <txtfld.hxx>
#include <txtatr.hxx>
#include <fmtftn.hxx>
#include <charfmt.hxx>
#include <fmtfld.hxx>
#include <fldbas.hxx>
#include <ftninfo.hxx>
/*
* Dieses File enthaelt alle Ausgabe-Funktionen des ASCII-Writers;
* fuer alle Nodes, Attribute, Formate und Chars.
*/
class SwASC_AttrIter
{
SwASCWriter& rWrt;
const SwTxtNode& rNd;
xub_StrLen nAktSwPos;
xub_StrLen SearchNext( xub_StrLen nStartPos );
public:
SwASC_AttrIter( SwASCWriter& rWrt, const SwTxtNode& rNd, xub_StrLen nStt );
void NextPos() { nAktSwPos = SearchNext( nAktSwPos + 1 ); }
xub_StrLen WhereNext() const { return nAktSwPos; }
BOOL OutAttr( xub_StrLen nSwPos );
};
SwASC_AttrIter::SwASC_AttrIter( SwASCWriter& rWr, const SwTxtNode& rTxtNd,
xub_StrLen nStt )
: rWrt( rWr ), rNd( rTxtNd ), nAktSwPos( 0 )
{
nAktSwPos = SearchNext( nStt + 1 );
}
xub_StrLen SwASC_AttrIter::SearchNext( xub_StrLen nStartPos )
{
xub_StrLen nMinPos = STRING_MAXLEN;
const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
if( pTxtAttrs )
{
// kann noch optimiert werden, wenn ausgenutzt wird, dass die TxtAttrs
// nach der Anfangsposition geordnet sind. Dann muessten
// allerdings noch 2 Indices gemerkt werden
for ( USHORT i = 0; i < pTxtAttrs->Count(); i++ )
{
const SwTxtAttr* pHt = (*pTxtAttrs)[i];
if (pHt->HasDummyChar())
{
xub_StrLen nPos = *pHt->GetStart();
if( nPos >= nStartPos && nPos <= nMinPos )
nMinPos = nPos;
if( ( ++nPos ) >= nStartPos && nPos < nMinPos )
nMinPos = nPos;
}
}
}
return nMinPos;
}
BOOL SwASC_AttrIter::OutAttr( xub_StrLen nSwPos )
{
BOOL bRet = FALSE;
const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
if( pTxtAttrs )
{
USHORT i;
for( i = 0; i < pTxtAttrs->Count(); i++ )
{
const SwTxtAttr* pHt = (*pTxtAttrs)[i];
if ( pHt->HasDummyChar() && nSwPos == *pHt->GetStart() )
{
bRet = TRUE;
String sOut;
switch( pHt->Which() )
{
case RES_TXTATR_FIELD:
sOut = ((SwTxtFld*)pHt)->GetFld().GetFld()->Expand();
break;
case RES_TXTATR_FTN:
{
const SwFmtFtn& rFtn = pHt->GetFtn();
if( rFtn.GetNumStr().Len() )
sOut = rFtn.GetNumStr();
else if( rFtn.IsEndNote() )
sOut = rWrt.pDoc->GetEndNoteInfo().aFmt.
GetNumStr( rFtn.GetNumber() );
else
sOut = rWrt.pDoc->GetFtnInfo().aFmt.
GetNumStr( rFtn.GetNumber() );
}
break;
}
if( sOut.Len() )
rWrt.Strm().WriteUnicodeOrByteText( sOut );
}
else if( nSwPos < *pHt->GetStart() )
break;
}
}
return bRet;
}
//------------------------
/* Ausgabe der Nodes */
//------------------------
static Writer& OutASC_SwTxtNode( Writer& rWrt, SwCntntNode& rNode )
{
const SwTxtNode& rNd = (SwTxtNode&)rNode;
xub_StrLen nStrPos = rWrt.pCurPam->GetPoint()->nContent.GetIndex();
xub_StrLen nNodeEnde = rNd.Len(), nEnde = nNodeEnde;
BOOL bLastNd = rWrt.pCurPam->GetPoint()->nNode == rWrt.pCurPam->GetMark()->nNode;
if( bLastNd )
nEnde = rWrt.pCurPam->GetMark()->nContent.GetIndex();
SwASC_AttrIter aAttrIter( (SwASCWriter&)rWrt, rNd, nStrPos );
if( !nStrPos && rWrt.bExportPargraphNumbering )
rWrt.Strm().WriteUnicodeOrByteText( rNd.GetNumString() );
String aStr( rNd.GetTxt() );
if( rWrt.bASCII_ParaAsBlanc )
aStr.SearchAndReplaceAll( 0x0A, ' ' );
const bool bExportSoftHyphens = RTL_TEXTENCODING_UCS2 == rWrt.GetAsciiOptions().GetCharSet() ||
RTL_TEXTENCODING_UTF8 == rWrt.GetAsciiOptions().GetCharSet();
do {
xub_StrLen nNextAttr = aAttrIter.WhereNext();
if( nNextAttr > nEnde )
nNextAttr = nEnde;
if( !aAttrIter.OutAttr( nStrPos ))
{
String aOutStr( aStr.Copy( nStrPos, nNextAttr - nStrPos ) );
if ( !bExportSoftHyphens )
aOutStr.EraseAllChars( CHAR_SOFTHYPHEN );
rWrt.Strm().WriteUnicodeOrByteText( aOutStr );
}
nStrPos = nNextAttr;
aAttrIter.NextPos();
} while( nStrPos < nEnde );
if( !bLastNd ||
( !rWrt.bWriteClipboardDoc && !rWrt.bASCII_NoLastLineEnd )
&& !nStrPos && nEnde == nNodeEnde )
rWrt.Strm().WriteUnicodeOrByteText( ((SwASCWriter&)rWrt).GetLineEnd());
return rWrt;
}
/*
* lege hier jetzt die Tabellen fuer die ASCII-Funktions-Pointer auf
* die Ausgabe-Funktionen an.
* Es sind lokale Strukturen, die nur innerhalb der ASCII-DLL
* bekannt sein muessen.
*/
SwNodeFnTab aASCNodeFnTab = {
/* RES_TXTNODE */ OutASC_SwTxtNode,
/* RES_GRFNODE */ 0,
/* RES_OLENODE */ 0
};
<commit_msg>sw33bf03: #i110144#: sw: ascii export: add space after list label<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: ascatr.cxx,v $
* $Revision: 1.10 $
*
* 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_sw.hxx"
#include <hintids.hxx>
#include <tools/stream.hxx>
#ifndef _SVSTDARR_HXX
#define _SVSTDARR_USHORTS
#include <svl/svstdarr.hxx>
#endif
#include <svx/fontitem.hxx>
#include <pam.hxx>
#include <doc.hxx>
#include <ndtxt.hxx>
#include <wrtasc.hxx>
#include <txatbase.hxx>
#include <fchrfmt.hxx>
#include <txtfld.hxx>
#include <txtatr.hxx>
#include <fmtftn.hxx>
#include <charfmt.hxx>
#include <fmtfld.hxx>
#include <fldbas.hxx>
#include <ftninfo.hxx>
/*
* Dieses File enthaelt alle Ausgabe-Funktionen des ASCII-Writers;
* fuer alle Nodes, Attribute, Formate und Chars.
*/
class SwASC_AttrIter
{
SwASCWriter& rWrt;
const SwTxtNode& rNd;
xub_StrLen nAktSwPos;
xub_StrLen SearchNext( xub_StrLen nStartPos );
public:
SwASC_AttrIter( SwASCWriter& rWrt, const SwTxtNode& rNd, xub_StrLen nStt );
void NextPos() { nAktSwPos = SearchNext( nAktSwPos + 1 ); }
xub_StrLen WhereNext() const { return nAktSwPos; }
BOOL OutAttr( xub_StrLen nSwPos );
};
SwASC_AttrIter::SwASC_AttrIter( SwASCWriter& rWr, const SwTxtNode& rTxtNd,
xub_StrLen nStt )
: rWrt( rWr ), rNd( rTxtNd ), nAktSwPos( 0 )
{
nAktSwPos = SearchNext( nStt + 1 );
}
xub_StrLen SwASC_AttrIter::SearchNext( xub_StrLen nStartPos )
{
xub_StrLen nMinPos = STRING_MAXLEN;
const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
if( pTxtAttrs )
{
// kann noch optimiert werden, wenn ausgenutzt wird, dass die TxtAttrs
// nach der Anfangsposition geordnet sind. Dann muessten
// allerdings noch 2 Indices gemerkt werden
for ( USHORT i = 0; i < pTxtAttrs->Count(); i++ )
{
const SwTxtAttr* pHt = (*pTxtAttrs)[i];
if (pHt->HasDummyChar())
{
xub_StrLen nPos = *pHt->GetStart();
if( nPos >= nStartPos && nPos <= nMinPos )
nMinPos = nPos;
if( ( ++nPos ) >= nStartPos && nPos < nMinPos )
nMinPos = nPos;
}
}
}
return nMinPos;
}
BOOL SwASC_AttrIter::OutAttr( xub_StrLen nSwPos )
{
BOOL bRet = FALSE;
const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
if( pTxtAttrs )
{
USHORT i;
for( i = 0; i < pTxtAttrs->Count(); i++ )
{
const SwTxtAttr* pHt = (*pTxtAttrs)[i];
if ( pHt->HasDummyChar() && nSwPos == *pHt->GetStart() )
{
bRet = TRUE;
String sOut;
switch( pHt->Which() )
{
case RES_TXTATR_FIELD:
sOut = ((SwTxtFld*)pHt)->GetFld().GetFld()->Expand();
break;
case RES_TXTATR_FTN:
{
const SwFmtFtn& rFtn = pHt->GetFtn();
if( rFtn.GetNumStr().Len() )
sOut = rFtn.GetNumStr();
else if( rFtn.IsEndNote() )
sOut = rWrt.pDoc->GetEndNoteInfo().aFmt.
GetNumStr( rFtn.GetNumber() );
else
sOut = rWrt.pDoc->GetFtnInfo().aFmt.
GetNumStr( rFtn.GetNumber() );
}
break;
}
if( sOut.Len() )
rWrt.Strm().WriteUnicodeOrByteText( sOut );
}
else if( nSwPos < *pHt->GetStart() )
break;
}
}
return bRet;
}
//------------------------
/* Ausgabe der Nodes */
//------------------------
static Writer& OutASC_SwTxtNode( Writer& rWrt, SwCntntNode& rNode )
{
const SwTxtNode& rNd = (SwTxtNode&)rNode;
xub_StrLen nStrPos = rWrt.pCurPam->GetPoint()->nContent.GetIndex();
xub_StrLen nNodeEnde = rNd.Len(), nEnde = nNodeEnde;
BOOL bLastNd = rWrt.pCurPam->GetPoint()->nNode == rWrt.pCurPam->GetMark()->nNode;
if( bLastNd )
nEnde = rWrt.pCurPam->GetMark()->nContent.GetIndex();
SwASC_AttrIter aAttrIter( (SwASCWriter&)rWrt, rNd, nStrPos );
if( !nStrPos && rWrt.bExportPargraphNumbering )
{
String numString( rNd.GetNumString() );
if (numString.Len())
{
numString.Append(' ');
rWrt.Strm().WriteUnicodeOrByteText(numString);
}
}
String aStr( rNd.GetTxt() );
if( rWrt.bASCII_ParaAsBlanc )
aStr.SearchAndReplaceAll( 0x0A, ' ' );
const bool bExportSoftHyphens = RTL_TEXTENCODING_UCS2 == rWrt.GetAsciiOptions().GetCharSet() ||
RTL_TEXTENCODING_UTF8 == rWrt.GetAsciiOptions().GetCharSet();
do {
xub_StrLen nNextAttr = aAttrIter.WhereNext();
if( nNextAttr > nEnde )
nNextAttr = nEnde;
if( !aAttrIter.OutAttr( nStrPos ))
{
String aOutStr( aStr.Copy( nStrPos, nNextAttr - nStrPos ) );
if ( !bExportSoftHyphens )
aOutStr.EraseAllChars( CHAR_SOFTHYPHEN );
rWrt.Strm().WriteUnicodeOrByteText( aOutStr );
}
nStrPos = nNextAttr;
aAttrIter.NextPos();
} while( nStrPos < nEnde );
if( !bLastNd ||
( !rWrt.bWriteClipboardDoc && !rWrt.bASCII_NoLastLineEnd )
&& !nStrPos && nEnde == nNodeEnde )
rWrt.Strm().WriteUnicodeOrByteText( ((SwASCWriter&)rWrt).GetLineEnd());
return rWrt;
}
/*
* lege hier jetzt die Tabellen fuer die ASCII-Funktions-Pointer auf
* die Ausgabe-Funktionen an.
* Es sind lokale Strukturen, die nur innerhalb der ASCII-DLL
* bekannt sein muessen.
*/
SwNodeFnTab aASCNodeFnTab = {
/* RES_TXTNODE */ OutASC_SwTxtNode,
/* RES_GRFNODE */ 0,
/* RES_OLENODE */ 0
};
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ascatr.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2004-01-13 16:36:19 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _SVSTDARR_HXX
#define _SVSTDARR_USHORTS
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _WRTASC_HXX
#include <wrtasc.hxx>
#endif
#ifndef _TXATBASE_HXX
#include <txatbase.hxx>
#endif
#ifndef _FCHRFMT_HXX
#include <fchrfmt.hxx>
#endif
#ifndef _TXTFLD_HXX
#include <txtfld.hxx>
#endif
#ifndef _TXTATR_HXX
#include <txtatr.hxx>
#endif
#ifndef _FMTFTN_HXX
#include <fmtftn.hxx>
#endif
#ifndef _CHARFMT_HXX
#include <charfmt.hxx>
#endif
#ifndef _FMTFLD_HXX
#include <fmtfld.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _FTNINFO_HXX //autogen
#include <ftninfo.hxx>
#endif
/*
* Dieses File enthaelt alle Ausgabe-Funktionen des ASCII-Writers;
* fuer alle Nodes, Attribute, Formate und Chars.
*/
class SwASC_AttrIter
{
SwASCWriter& rWrt;
const SwTxtNode& rNd;
xub_StrLen nAktSwPos;
xub_StrLen SearchNext( xub_StrLen nStartPos );
public:
SwASC_AttrIter( SwASCWriter& rWrt, const SwTxtNode& rNd, xub_StrLen nStt );
void NextPos() { nAktSwPos = SearchNext( nAktSwPos + 1 ); }
xub_StrLen WhereNext() const { return nAktSwPos; }
BOOL OutAttr( xub_StrLen nSwPos );
};
SwASC_AttrIter::SwASC_AttrIter( SwASCWriter& rWr, const SwTxtNode& rTxtNd,
xub_StrLen nStt )
: rWrt( rWr ), rNd( rTxtNd ), nAktSwPos( 0 )
{
nAktSwPos = SearchNext( nStt + 1 );
}
xub_StrLen SwASC_AttrIter::SearchNext( xub_StrLen nStartPos )
{
register xub_StrLen nMinPos = STRING_MAXLEN;
const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
if( pTxtAttrs )
{
register USHORT i;
register xub_StrLen nPos;
const xub_StrLen * pPos;
// kann noch optimiert werden, wenn ausgenutzt wird, dass die TxtAttrs
// nach der Anfangsposition geordnet sind. Dann muessten
// allerdings noch 2 Indices gemerkt werden
for( i = 0; i < pTxtAttrs->Count(); i++ )
{
const SwTxtAttr* pHt = (*pTxtAttrs)[i];
nPos = *pHt->GetStart(); // gibt erstes Attr-Zeichen
pPos = pHt->GetEnd();
if( !pPos )
{
if( nPos >= nStartPos && nPos <= nMinPos )
nMinPos = nPos;
if( ( ++nPos ) >= nStartPos && nPos < nMinPos )
nMinPos = nPos;
}
}
}
return nMinPos;
}
BOOL SwASC_AttrIter::OutAttr( xub_StrLen nSwPos )
{
BOOL bRet = FALSE;
const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
if( pTxtAttrs )
{
register USHORT i;
for( i = 0; i < pTxtAttrs->Count(); i++ )
{
const SwTxtAttr* pHt = (*pTxtAttrs)[i];
const xub_StrLen * pEnd = pHt->GetEnd();
if( !pEnd && nSwPos == *pHt->GetStart() )
{
bRet = TRUE;
String sOut;
switch( pHt->Which() )
{
case RES_TXTATR_FIELD:
sOut = ((SwTxtFld*)pHt)->GetFld().GetFld()->Expand();
break;
case RES_TXTATR_HARDBLANK:
sOut = ((SwTxtHardBlank*)pHt)->GetChar();
break;
case RES_TXTATR_FTN:
{
const SwFmtFtn& rFtn = pHt->GetFtn();
if( rFtn.GetNumStr().Len() )
sOut = rFtn.GetNumStr();
else if( rFtn.IsEndNote() )
sOut = rWrt.pDoc->GetEndNoteInfo().aFmt.
GetNumStr( rFtn.GetNumber() );
else
sOut = rWrt.pDoc->GetFtnInfo().aFmt.
GetNumStr( rFtn.GetNumber() );
}
break;
}
if( sOut.Len() )
rWrt.Strm().WriteUnicodeOrByteText( sOut );
}
else if( nSwPos < *pHt->GetStart() )
break;
}
}
return bRet;
}
//------------------------
/* Ausgabe der Nodes */
//------------------------
static Writer& OutASC_SwTxtNode( Writer& rWrt, SwCntntNode& rNode )
{
const SwTxtNode& rNd = (SwTxtNode&)rNode;
xub_StrLen nStrPos = rWrt.pCurPam->GetPoint()->nContent.GetIndex();
xub_StrLen nNodeEnde = rNd.Len(), nEnde = nNodeEnde;
BOOL bLastNd = rWrt.pCurPam->GetPoint()->nNode == rWrt.pCurPam->GetMark()->nNode;
if( bLastNd )
nEnde = rWrt.pCurPam->GetMark()->nContent.GetIndex();
SwASC_AttrIter aAttrIter( (SwASCWriter&)rWrt, rNd, nStrPos );
if( !nStrPos )
rWrt.Strm().WriteUnicodeOrByteText( rNd.GetNumString() );
String aStr( rNd.GetTxt() );
if( rWrt.bASCII_ParaAsBlanc )
aStr.SearchAndReplaceAll( 0x0A, ' ' );
do {
xub_StrLen nNextAttr = aAttrIter.WhereNext();
if( nNextAttr > nEnde )
nNextAttr = nEnde;
if( !aAttrIter.OutAttr( nStrPos ))
rWrt.Strm().WriteUnicodeOrByteText(
aStr.Copy( nStrPos, nNextAttr - nStrPos ));
nStrPos = nNextAttr;
aAttrIter.NextPos();
} while( nStrPos < nEnde );
if( !bLastNd ||
( !rWrt.bWriteClipboardDoc && !rWrt.bASCII_NoLastLineEnd )
&& !nStrPos && nEnde == nNodeEnde )
rWrt.Strm().WriteUnicodeOrByteText( ((SwASCWriter&)rWrt).GetLineEnd());
return rWrt;
}
/*
* lege hier jetzt die Tabellen fuer die ASCII-Funktions-Pointer auf
* die Ausgabe-Funktionen an.
* Es sind lokale Strukturen, die nur innerhalb der ASCII-DLL
* bekannt sein muessen.
*/
SwNodeFnTab aASCNodeFnTab = {
/* RES_TXTNODE */ OutASC_SwTxtNode,
/* RES_GRFNODE */ 0,
/* RES_OLENODE */ 0
};
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.878); FILE MERGED 2005/09/05 13:41:51 rt 1.5.878.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ascatr.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:33:49 $
*
* 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 _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _SVSTDARR_HXX
#define _SVSTDARR_USHORTS
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _WRTASC_HXX
#include <wrtasc.hxx>
#endif
#ifndef _TXATBASE_HXX
#include <txatbase.hxx>
#endif
#ifndef _FCHRFMT_HXX
#include <fchrfmt.hxx>
#endif
#ifndef _TXTFLD_HXX
#include <txtfld.hxx>
#endif
#ifndef _TXTATR_HXX
#include <txtatr.hxx>
#endif
#ifndef _FMTFTN_HXX
#include <fmtftn.hxx>
#endif
#ifndef _CHARFMT_HXX
#include <charfmt.hxx>
#endif
#ifndef _FMTFLD_HXX
#include <fmtfld.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _FTNINFO_HXX //autogen
#include <ftninfo.hxx>
#endif
/*
* Dieses File enthaelt alle Ausgabe-Funktionen des ASCII-Writers;
* fuer alle Nodes, Attribute, Formate und Chars.
*/
class SwASC_AttrIter
{
SwASCWriter& rWrt;
const SwTxtNode& rNd;
xub_StrLen nAktSwPos;
xub_StrLen SearchNext( xub_StrLen nStartPos );
public:
SwASC_AttrIter( SwASCWriter& rWrt, const SwTxtNode& rNd, xub_StrLen nStt );
void NextPos() { nAktSwPos = SearchNext( nAktSwPos + 1 ); }
xub_StrLen WhereNext() const { return nAktSwPos; }
BOOL OutAttr( xub_StrLen nSwPos );
};
SwASC_AttrIter::SwASC_AttrIter( SwASCWriter& rWr, const SwTxtNode& rTxtNd,
xub_StrLen nStt )
: rWrt( rWr ), rNd( rTxtNd ), nAktSwPos( 0 )
{
nAktSwPos = SearchNext( nStt + 1 );
}
xub_StrLen SwASC_AttrIter::SearchNext( xub_StrLen nStartPos )
{
register xub_StrLen nMinPos = STRING_MAXLEN;
const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
if( pTxtAttrs )
{
register USHORT i;
register xub_StrLen nPos;
const xub_StrLen * pPos;
// kann noch optimiert werden, wenn ausgenutzt wird, dass die TxtAttrs
// nach der Anfangsposition geordnet sind. Dann muessten
// allerdings noch 2 Indices gemerkt werden
for( i = 0; i < pTxtAttrs->Count(); i++ )
{
const SwTxtAttr* pHt = (*pTxtAttrs)[i];
nPos = *pHt->GetStart(); // gibt erstes Attr-Zeichen
pPos = pHt->GetEnd();
if( !pPos )
{
if( nPos >= nStartPos && nPos <= nMinPos )
nMinPos = nPos;
if( ( ++nPos ) >= nStartPos && nPos < nMinPos )
nMinPos = nPos;
}
}
}
return nMinPos;
}
BOOL SwASC_AttrIter::OutAttr( xub_StrLen nSwPos )
{
BOOL bRet = FALSE;
const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
if( pTxtAttrs )
{
register USHORT i;
for( i = 0; i < pTxtAttrs->Count(); i++ )
{
const SwTxtAttr* pHt = (*pTxtAttrs)[i];
const xub_StrLen * pEnd = pHt->GetEnd();
if( !pEnd && nSwPos == *pHt->GetStart() )
{
bRet = TRUE;
String sOut;
switch( pHt->Which() )
{
case RES_TXTATR_FIELD:
sOut = ((SwTxtFld*)pHt)->GetFld().GetFld()->Expand();
break;
case RES_TXTATR_HARDBLANK:
sOut = ((SwTxtHardBlank*)pHt)->GetChar();
break;
case RES_TXTATR_FTN:
{
const SwFmtFtn& rFtn = pHt->GetFtn();
if( rFtn.GetNumStr().Len() )
sOut = rFtn.GetNumStr();
else if( rFtn.IsEndNote() )
sOut = rWrt.pDoc->GetEndNoteInfo().aFmt.
GetNumStr( rFtn.GetNumber() );
else
sOut = rWrt.pDoc->GetFtnInfo().aFmt.
GetNumStr( rFtn.GetNumber() );
}
break;
}
if( sOut.Len() )
rWrt.Strm().WriteUnicodeOrByteText( sOut );
}
else if( nSwPos < *pHt->GetStart() )
break;
}
}
return bRet;
}
//------------------------
/* Ausgabe der Nodes */
//------------------------
static Writer& OutASC_SwTxtNode( Writer& rWrt, SwCntntNode& rNode )
{
const SwTxtNode& rNd = (SwTxtNode&)rNode;
xub_StrLen nStrPos = rWrt.pCurPam->GetPoint()->nContent.GetIndex();
xub_StrLen nNodeEnde = rNd.Len(), nEnde = nNodeEnde;
BOOL bLastNd = rWrt.pCurPam->GetPoint()->nNode == rWrt.pCurPam->GetMark()->nNode;
if( bLastNd )
nEnde = rWrt.pCurPam->GetMark()->nContent.GetIndex();
SwASC_AttrIter aAttrIter( (SwASCWriter&)rWrt, rNd, nStrPos );
if( !nStrPos )
rWrt.Strm().WriteUnicodeOrByteText( rNd.GetNumString() );
String aStr( rNd.GetTxt() );
if( rWrt.bASCII_ParaAsBlanc )
aStr.SearchAndReplaceAll( 0x0A, ' ' );
do {
xub_StrLen nNextAttr = aAttrIter.WhereNext();
if( nNextAttr > nEnde )
nNextAttr = nEnde;
if( !aAttrIter.OutAttr( nStrPos ))
rWrt.Strm().WriteUnicodeOrByteText(
aStr.Copy( nStrPos, nNextAttr - nStrPos ));
nStrPos = nNextAttr;
aAttrIter.NextPos();
} while( nStrPos < nEnde );
if( !bLastNd ||
( !rWrt.bWriteClipboardDoc && !rWrt.bASCII_NoLastLineEnd )
&& !nStrPos && nEnde == nNodeEnde )
rWrt.Strm().WriteUnicodeOrByteText( ((SwASCWriter&)rWrt).GetLineEnd());
return rWrt;
}
/*
* lege hier jetzt die Tabellen fuer die ASCII-Funktions-Pointer auf
* die Ausgabe-Funktionen an.
* Es sind lokale Strukturen, die nur innerhalb der ASCII-DLL
* bekannt sein muessen.
*/
SwNodeFnTab aASCNodeFnTab = {
/* RES_TXTNODE */ OutASC_SwTxtNode,
/* RES_GRFNODE */ 0,
/* RES_OLENODE */ 0
};
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wrtasc.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:34:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _WRTASC_HXX
#define _WRTASC_HXX
#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif
#ifndef _WRT_FN_HXX
#include <wrt_fn.hxx>
#endif
extern SwNodeFnTab aASCNodeFnTab;
// der ASC-Writer
class SwASCWriter : public Writer
{
String sLineEnd;
virtual ULONG WriteStream();
public:
SwASCWriter( const String& rFilterName );
virtual ~SwASCWriter();
const String& GetLineEnd() const { return sLineEnd; }
};
#endif // _WRTASC_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.1202); FILE MERGED 2008/04/01 12:54:38 thb 1.2.1202.2: #i85898# Stripping all external header guards 2008/03/31 16:55:30 rt 1.2.1202.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: wrtasc.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _WRTASC_HXX
#define _WRTASC_HXX
#include <shellio.hxx>
#include <wrt_fn.hxx>
extern SwNodeFnTab aASCNodeFnTab;
// der ASC-Writer
class SwASCWriter : public Writer
{
String sLineEnd;
virtual ULONG WriteStream();
public:
SwASCWriter( const String& rFilterName );
virtual ~SwASCWriter();
const String& GetLineEnd() const { return sLineEnd; }
};
#endif // _WRTASC_HXX
<|endoftext|> |
<commit_before>/*
* The Biomechanical ToolKit
* Copyright (c) 2009-2012, Arnaud Barré
* 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(s) of the copyright holders 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.
*/
#include "VideoWidget.h"
#include "Acquisition.h"
#include "UserDefined.h"
#include "LoggerMessage.h"
#include <QTreeWidgetItem>
#include <QPainter>
#include <QPaintEvent>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QApplication>
#include <QDir>
#include <QStackedLayout>
VideoWidget::VideoWidget(QWidget* parent)
: QWidget(parent), mp_CurrentFrameFunctor()
{
// Member(s)
this->mp_Acquisition = 0;
this->mp_Delays = 0;
this->m_VideoId = -1;
this->mp_MediaObject = new Phonon::MediaObject(this);
this->mp_Video = new Phonon::VideoWidget(this);
this->mp_Overlay = new VideoOverlayWidget(this);
#ifdef Q_OS_WIN
this->m_PlaybackStarted = false;
this->m_PlaybackFrameCounter = 0;
#endif
// Drag and drop
this->setAcceptDrops(true);
// UI
// - Background color
QPalette p(this->palette());
p.setColor(QPalette::Background, Qt::black);
this->setAutoFillBackground(true);
this->setPalette(p);
// - Layout
QStackedLayout* videoStack = new QStackedLayout;
videoStack->addWidget(this->mp_Video);
videoStack->addWidget(this->mp_Overlay);
videoStack->setStackingMode(QStackedLayout::StackAll);
QVBoxLayout* layout = new QVBoxLayout;
layout->setContentsMargins(0,0,0,0);
layout->addLayout(videoStack);
this->setLayout(layout);
this->setVideoVisible(false);
// Connect the media nodes
Phonon::createPath(this->mp_MediaObject, this->mp_Video);
connect(this->mp_MediaObject, SIGNAL(stateChanged(Phonon::State, Phonon::State)), this, SLOT(checkMediaStatus(Phonon::State, Phonon::State)));
};
void VideoWidget::start()
{
#ifdef Q_OS_WIN
this->m_PlaybackStarted = true;
this->m_PlaybackFrameCounter = 0;
#endif
};
void VideoWidget::stop()
{
#ifdef Q_OS_WIN
this->mp_MediaObject->pause();
this->m_PlaybackStarted = false;
this->render();
#endif
};
void VideoWidget::render()
{
if (this->mp_Video->isVisible())
{
qint64 pos = static_cast<qint64>(static_cast<double>((*this->mp_CurrentFrameFunctor)() - 1) / this->mp_Acquisition->pointFrequency() * 1000.0) - this->mp_Delays->operator[](this->m_VideoId);
if (pos >= 0)
{
#ifdef Q_OS_WIN
if (QSysInfo::windowsVersion() < QSysInfo::WV_WINDOWS7)
{
this->mp_MediaObject->play();
this->mp_MediaObject->seek(pos);
// Because some videos are not able to start correctly the frame by frame rendering and are like frozen
if (!this->m_PlaybackStarted || (this->m_PlaybackFrameCounter > 3))
this->mp_MediaObject->pause();
++this->m_PlaybackFrameCounter;
}
else
{
this->mp_MediaObject->seek(pos);
}
#else
this->mp_MediaObject->seek(pos);
#endif
}
}
};
void VideoWidget::show(bool s)
{
if (!s) // Hidden
{
if (this->mp_MediaObject->currentSource().type() != Phonon::MediaSource::Empty)
this->mp_MediaObject->clear();
this->setVideoVisible(false);
}
};
void VideoWidget::copy(VideoWidget* source)
{
this->mp_Acquisition = source->mp_Acquisition;
this->mp_Delays = source->mp_Delays;
this->mp_CurrentFrameFunctor = source->mp_CurrentFrameFunctor;
};
void VideoWidget::dragEnterEvent(QDragEnterEvent* event)
{
event->ignore();
if (event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist"))
{
this->setVideoVisible(false);
QTreeWidget* treeWidget = qobject_cast<QTreeWidget*>(event->source());
if (treeWidget)
{
QList<QTreeWidgetItem*> selectedItems = treeWidget->selectedItems();
for (QList<QTreeWidgetItem*>::const_iterator it = selectedItems.begin() ; it != selectedItems.end() ; ++it)
{
if ((*it)->type() != VideoType)
return;
}
event->setDropAction(Qt::CopyAction); // To have the cross (+) symbol
event->accept();
}
}
this->QWidget::dragEnterEvent(event);
};
void VideoWidget::dragLeaveEvent(QDragLeaveEvent* event)
{
if (this->mp_MediaObject->currentSource().type() != Phonon::MediaSource::Empty)
this->setVideoVisible(true);
this->QWidget::dragLeaveEvent(event);
}
void VideoWidget::dropEvent(QDropEvent* event)
{
event->setDropAction(Qt::IgnoreAction); // Only to know which Video IDs were dropped.
event->accept();
QTreeWidget* treeWidget = qobject_cast<QTreeWidget*>(event->source());
QTreeWidgetItem* video = treeWidget->selectedItems().at(0);
int id = video->data(0,VideoId).toInt();
QString videoFilePath = this->mp_Acquisition->videoPath(id) + "/" + this->mp_Acquisition->videoFilename(id);
if (this->mp_MediaObject->currentSource().fileName().compare(videoFilePath) == 0) // same file?
this->setVideoVisible(true);
else if (this->mp_Acquisition->videoPath(id).isEmpty())
{
LOG_CRITICAL("Error when loading the video file: File not found.");
QMessageBox error(QMessageBox::Warning, "Video player", "Error when loading the video.", QMessageBox::Ok , this);
#ifdef Q_OS_MAC
error.setWindowFlags(Qt::Sheet);
error.setWindowModality(Qt::WindowModal);
#endif
error.setInformativeText("<nobr>Video(s) must be in the same folder than the acquisition.</nobr>");
error.exec();
}
else
{
LOG_INFO("Loading video from file: " + this->mp_Acquisition->videoFilename(id));
this->mp_MediaObject->clear(); // Reset the internal state of the player
this->m_VideoId = id; // Must be set before the loading of the video (at least under MacOS X as the reading is asynchronous (multithreaded?) and the rendering is done when calling the method Phonon::MediaObject::setCurrentSource())
QApplication::setOverrideCursor(Qt::WaitCursor);
this->mp_MediaObject->setCurrentSource(videoFilePath);
QApplication::restoreOverrideCursor();
}
this->QWidget::dropEvent(event);
};
void VideoWidget::paintEvent(QPaintEvent* event)
{
if (!this->mp_Video->isVisible())
{
// Title
QString str = "Drop video";
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(Qt::lightGray);
QFont f = this->font();
f.setPointSize(32);
painter.setFont(f);
QRect rect = painter.fontMetrics().boundingRect(str);
QPoint center = this->geometry().center();
painter.drawText(center - rect.center() - QPoint(0, rect.height()/2), str);
// informative text
str = "from acquisition explorer";
f.setPointSize(14);
painter.setFont(f);
QRect rect2 = painter.fontMetrics().boundingRect(str);
painter.drawText(center - rect2.center() + QPoint(0, rect2.height()), str);
// Box
painter.setPen(QPen(Qt::lightGray, 1.75, Qt::DashLine));
qreal side = static_cast<qreal>(qMin(this->width() / 2, this->height() / 2));
side = qMax(side, rect.width() + 30.0); // 15 px on each side
painter.drawRoundedRect(QRectF(center - QPointF(side, side) / 2.0, QSizeF(side, side)), 25.0, 25.0);
}
else
this->QWidget::paintEvent(event);
};
void VideoWidget::setVideoVisible(bool v)
{
this->mp_Video->setVisible(v);
this->mp_Overlay->setVisible(v);
};
void VideoWidget::checkMediaStatus(Phonon::State newState, Phonon::State oldState)
{
switch(newState)
{
case Phonon::StoppedState:
if ((oldState == Phonon::LoadingState) && (this->mp_MediaObject->currentSource().type() != Phonon::MediaSource::Empty))
{
this->setVideoVisible(true);
#ifdef Q_OS_WIN
if (QSysInfo::windowsVersion() >= QSysInfo::WV_WINDOWS7)
this->mp_MediaObject->pause();
#else
this->mp_MediaObject->play(); // At least under MacOS X, give the seek capability (otherwise, the video stays freezed).
this->mp_MediaObject->pause();
#endif
this->render();
}
break;
case Phonon::ErrorState:
{
if (this->mp_MediaObject->currentSource().type() != Phonon::MediaSource::Empty)
{
QMessageBox error(QMessageBox::Warning, "Video player", "Error when loading the video.", QMessageBox::Ok , this);
#ifdef Q_OS_MAC
error.setWindowFlags(Qt::Sheet);
error.setWindowModality(Qt::WindowModal);
#endif
LOG_CRITICAL("Error when loading the video file: Have you the right video codec installed?");
error.setInformativeText("<nobr>Have you the right video codec installed?</nobr>");
error.exec();
this->m_VideoId = -1;
this->mp_MediaObject->clear(); // Reset the player
this->setVideoVisible(false);
this->update();
}
}
break;
default:
break;
}
};
// ----------------------------------------------------------------------------
VideoOverlayWidget::VideoOverlayWidget(QWidget* parent)
: QWidget(parent)
{
this->setAttribute(Qt::WA_NoSystemBackground);
};<commit_msg>[FIX] Mokka: Dragging any kind of item (except video) over the video view hides the current displayed video.<commit_after>/*
* The Biomechanical ToolKit
* Copyright (c) 2009-2012, Arnaud Barré
* 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(s) of the copyright holders 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.
*/
#include "VideoWidget.h"
#include "Acquisition.h"
#include "UserDefined.h"
#include "LoggerMessage.h"
#include <QTreeWidgetItem>
#include <QPainter>
#include <QPaintEvent>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QApplication>
#include <QDir>
#include <QStackedLayout>
VideoWidget::VideoWidget(QWidget* parent)
: QWidget(parent), mp_CurrentFrameFunctor()
{
// Member(s)
this->mp_Acquisition = 0;
this->mp_Delays = 0;
this->m_VideoId = -1;
this->mp_MediaObject = new Phonon::MediaObject(this);
this->mp_Video = new Phonon::VideoWidget(this);
this->mp_Overlay = new VideoOverlayWidget(this);
#ifdef Q_OS_WIN
this->m_PlaybackStarted = false;
this->m_PlaybackFrameCounter = 0;
#endif
// Drag and drop
this->setAcceptDrops(true);
// UI
// - Background color
QPalette p(this->palette());
p.setColor(QPalette::Background, Qt::black);
this->setAutoFillBackground(true);
this->setPalette(p);
// - Layout
QStackedLayout* videoStack = new QStackedLayout;
videoStack->addWidget(this->mp_Video);
videoStack->addWidget(this->mp_Overlay);
videoStack->setStackingMode(QStackedLayout::StackAll);
QVBoxLayout* layout = new QVBoxLayout;
layout->setContentsMargins(0,0,0,0);
layout->addLayout(videoStack);
this->setLayout(layout);
this->setVideoVisible(false);
// Connect the media nodes
Phonon::createPath(this->mp_MediaObject, this->mp_Video);
connect(this->mp_MediaObject, SIGNAL(stateChanged(Phonon::State, Phonon::State)), this, SLOT(checkMediaStatus(Phonon::State, Phonon::State)));
};
void VideoWidget::start()
{
#ifdef Q_OS_WIN
this->m_PlaybackStarted = true;
this->m_PlaybackFrameCounter = 0;
#endif
};
void VideoWidget::stop()
{
#ifdef Q_OS_WIN
this->mp_MediaObject->pause();
this->m_PlaybackStarted = false;
this->render();
#endif
};
void VideoWidget::render()
{
if (this->mp_Video->isVisible())
{
qint64 pos = static_cast<qint64>(static_cast<double>((*this->mp_CurrentFrameFunctor)() - 1) / this->mp_Acquisition->pointFrequency() * 1000.0) - this->mp_Delays->operator[](this->m_VideoId);
if (pos >= 0)
{
#ifdef Q_OS_WIN
if (QSysInfo::windowsVersion() < QSysInfo::WV_WINDOWS7)
{
this->mp_MediaObject->play();
this->mp_MediaObject->seek(pos);
// Because some videos are not able to start correctly the frame by frame rendering and are like frozen
if (!this->m_PlaybackStarted || (this->m_PlaybackFrameCounter > 3))
this->mp_MediaObject->pause();
++this->m_PlaybackFrameCounter;
}
else
{
this->mp_MediaObject->seek(pos);
}
#else
this->mp_MediaObject->seek(pos);
#endif
}
}
};
void VideoWidget::show(bool s)
{
if (!s) // Hidden
{
if (this->mp_MediaObject->currentSource().type() != Phonon::MediaSource::Empty)
this->mp_MediaObject->clear();
this->setVideoVisible(false);
}
};
void VideoWidget::copy(VideoWidget* source)
{
this->mp_Acquisition = source->mp_Acquisition;
this->mp_Delays = source->mp_Delays;
this->mp_CurrentFrameFunctor = source->mp_CurrentFrameFunctor;
};
void VideoWidget::dragEnterEvent(QDragEnterEvent* event)
{
event->ignore();
if (event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist"))
{
QTreeWidget* treeWidget = qobject_cast<QTreeWidget*>(event->source());
if (treeWidget)
{
QList<QTreeWidgetItem*> selectedItems = treeWidget->selectedItems();
for (QList<QTreeWidgetItem*>::const_iterator it = selectedItems.begin() ; it != selectedItems.end() ; ++it)
{
if ((*it)->type() != VideoType)
return;
}
this->setVideoVisible(false);
event->setDropAction(Qt::CopyAction); // To have the cross (+) symbol
event->accept();
}
}
this->QWidget::dragEnterEvent(event);
};
void VideoWidget::dragLeaveEvent(QDragLeaveEvent* event)
{
if (this->mp_MediaObject->currentSource().type() != Phonon::MediaSource::Empty)
this->setVideoVisible(true);
this->QWidget::dragLeaveEvent(event);
}
void VideoWidget::dropEvent(QDropEvent* event)
{
event->setDropAction(Qt::IgnoreAction); // Only to know which Video IDs were dropped.
event->accept();
QTreeWidget* treeWidget = qobject_cast<QTreeWidget*>(event->source());
QTreeWidgetItem* video = treeWidget->selectedItems().at(0);
int id = video->data(0,VideoId).toInt();
QString videoFilePath = this->mp_Acquisition->videoPath(id) + "/" + this->mp_Acquisition->videoFilename(id);
if (this->mp_MediaObject->currentSource().fileName().compare(videoFilePath) == 0) // same file?
this->setVideoVisible(true);
else if (this->mp_Acquisition->videoPath(id).isEmpty())
{
LOG_CRITICAL("Error when loading the video file: File not found.");
QMessageBox error(QMessageBox::Warning, "Video player", "Error when loading the video.", QMessageBox::Ok , this);
#ifdef Q_OS_MAC
error.setWindowFlags(Qt::Sheet);
error.setWindowModality(Qt::WindowModal);
#endif
error.setInformativeText("<nobr>Video(s) must be in the same folder than the acquisition.</nobr>");
error.exec();
}
else
{
LOG_INFO("Loading video from file: " + this->mp_Acquisition->videoFilename(id));
this->mp_MediaObject->clear(); // Reset the internal state of the player
this->m_VideoId = id; // Must be set before the loading of the video (at least under MacOS X as the reading is asynchronous (multithreaded?) and the rendering is done when calling the method Phonon::MediaObject::setCurrentSource())
QApplication::setOverrideCursor(Qt::WaitCursor);
this->mp_MediaObject->setCurrentSource(videoFilePath);
QApplication::restoreOverrideCursor();
}
this->QWidget::dropEvent(event);
};
void VideoWidget::paintEvent(QPaintEvent* event)
{
if (!this->mp_Video->isVisible())
{
// Title
QString str = "Drop video";
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(Qt::lightGray);
QFont f = this->font();
f.setPointSize(32);
painter.setFont(f);
QRect rect = painter.fontMetrics().boundingRect(str);
QPoint center = this->geometry().center();
painter.drawText(center - rect.center() - QPoint(0, rect.height()/2), str);
// informative text
str = "from acquisition explorer";
f.setPointSize(14);
painter.setFont(f);
QRect rect2 = painter.fontMetrics().boundingRect(str);
painter.drawText(center - rect2.center() + QPoint(0, rect2.height()), str);
// Box
painter.setPen(QPen(Qt::lightGray, 1.75, Qt::DashLine));
qreal side = static_cast<qreal>(qMin(this->width() / 2, this->height() / 2));
side = qMax(side, rect.width() + 30.0); // 15 px on each side
painter.drawRoundedRect(QRectF(center - QPointF(side, side) / 2.0, QSizeF(side, side)), 25.0, 25.0);
}
else
this->QWidget::paintEvent(event);
};
void VideoWidget::setVideoVisible(bool v)
{
this->mp_Video->setVisible(v);
this->mp_Overlay->setVisible(v);
};
void VideoWidget::checkMediaStatus(Phonon::State newState, Phonon::State oldState)
{
switch(newState)
{
case Phonon::StoppedState:
if ((oldState == Phonon::LoadingState) && (this->mp_MediaObject->currentSource().type() != Phonon::MediaSource::Empty))
{
this->setVideoVisible(true);
#ifdef Q_OS_WIN
if (QSysInfo::windowsVersion() >= QSysInfo::WV_WINDOWS7)
this->mp_MediaObject->pause();
#else
this->mp_MediaObject->play(); // At least under MacOS X, give the seek capability (otherwise, the video stays freezed).
this->mp_MediaObject->pause();
#endif
this->render();
}
break;
case Phonon::ErrorState:
{
if (this->mp_MediaObject->currentSource().type() != Phonon::MediaSource::Empty)
{
QMessageBox error(QMessageBox::Warning, "Video player", "Error when loading the video.", QMessageBox::Ok , this);
#ifdef Q_OS_MAC
error.setWindowFlags(Qt::Sheet);
error.setWindowModality(Qt::WindowModal);
#endif
LOG_CRITICAL("Error when loading the video file: Have you the right video codec installed?");
error.setInformativeText("<nobr>Have you the right video codec installed?</nobr>");
error.exec();
this->m_VideoId = -1;
this->mp_MediaObject->clear(); // Reset the player
this->setVideoVisible(false);
this->update();
}
}
break;
default:
break;
}
};
// ----------------------------------------------------------------------------
VideoOverlayWidget::VideoOverlayWidget(QWidget* parent)
: QWidget(parent)
{
this->setAttribute(Qt::WA_NoSystemBackground);
};<|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 "content/browser/gpu/gpu_process_host_ui_shim.h"
#include <algorithm>
#include "base/debug/trace_event.h"
#include "base/id_map.h"
#include "base/lazy_instance.h"
#include "base/process_util.h"
#include "content/browser/gpu/gpu_data_manager.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/render_widget_host_view.h"
#include "content/common/gpu/gpu_messages.h"
#include "content/public/browser/browser_thread.h"
#if defined(TOOLKIT_USES_GTK)
// These two #includes need to come after gpu_messages.h.
#include "ui/base/x/x11_util.h"
#include "ui/gfx/size.h"
#include <gdk/gdk.h> // NOLINT
#include <gdk/gdkx.h> // NOLINT
#endif
using content::BrowserThread;
namespace {
// One of the linux specific headers defines this as a macro.
#ifdef DestroyAll
#undef DestroyAll
#endif
base::LazyInstance<IDMap<GpuProcessHostUIShim> > g_hosts_by_id =
LAZY_INSTANCE_INITIALIZER;
class SendOnIOThreadTask : public Task {
public:
SendOnIOThreadTask(int host_id, IPC::Message* msg)
: host_id_(host_id),
msg_(msg) {
}
private:
void Run() {
GpuProcessHost* host = GpuProcessHost::FromID(host_id_);
if (host)
host->Send(msg_.release());
}
int host_id_;
scoped_ptr<IPC::Message> msg_;
};
class ScopedSendOnIOThread {
public:
ScopedSendOnIOThread(int host_id, IPC::Message* msg)
: host_id_(host_id),
msg_(msg),
cancelled_(false) {
}
~ScopedSendOnIOThread() {
if (!cancelled_) {
BrowserThread::PostTask(BrowserThread::IO,
FROM_HERE,
new SendOnIOThreadTask(host_id_,
msg_.release()));
}
}
void Cancel() { cancelled_ = true; }
private:
int host_id_;
scoped_ptr<IPC::Message> msg_;
bool cancelled_;
};
} // namespace
RouteToGpuProcessHostUIShimTask::RouteToGpuProcessHostUIShimTask(
int host_id,
const IPC::Message& msg)
: host_id_(host_id),
msg_(msg) {
}
RouteToGpuProcessHostUIShimTask::~RouteToGpuProcessHostUIShimTask() {
}
void RouteToGpuProcessHostUIShimTask::Run() {
GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(host_id_);
if (ui_shim)
ui_shim->OnMessageReceived(msg_);
}
GpuProcessHostUIShim::GpuProcessHostUIShim(int host_id)
: host_id_(host_id) {
g_hosts_by_id.Pointer()->AddWithID(this, host_id_);
}
// static
GpuProcessHostUIShim* GpuProcessHostUIShim::Create(int host_id) {
DCHECK(!FromID(host_id));
return new GpuProcessHostUIShim(host_id);
}
// static
void GpuProcessHostUIShim::Destroy(int host_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
delete FromID(host_id);
}
// static
void GpuProcessHostUIShim::DestroyAll() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
while (!g_hosts_by_id.Pointer()->IsEmpty()) {
IDMap<GpuProcessHostUIShim>::iterator it(g_hosts_by_id.Pointer());
delete it.GetCurrentValue();
}
}
// static
GpuProcessHostUIShim* GpuProcessHostUIShim::FromID(int host_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
return g_hosts_by_id.Pointer()->Lookup(host_id);
}
bool GpuProcessHostUIShim::Send(IPC::Message* msg) {
DCHECK(CalledOnValidThread());
return BrowserThread::PostTask(BrowserThread::IO,
FROM_HERE,
new SendOnIOThreadTask(host_id_, msg));
}
bool GpuProcessHostUIShim::OnMessageReceived(const IPC::Message& message) {
DCHECK(CalledOnValidThread());
if (message.routing_id() != MSG_ROUTING_CONTROL)
return false;
return OnControlMessageReceived(message);
}
void GpuProcessHostUIShim::SimulateRemoveAllContext() {
Send(new GpuMsg_Clean());
}
void GpuProcessHostUIShim::SimulateCrash() {
Send(new GpuMsg_Crash());
}
void GpuProcessHostUIShim::SimulateHang() {
Send(new GpuMsg_Hang());
}
GpuProcessHostUIShim::~GpuProcessHostUIShim() {
DCHECK(CalledOnValidThread());
g_hosts_by_id.Pointer()->Remove(host_id_);
}
bool GpuProcessHostUIShim::OnControlMessageReceived(
const IPC::Message& message) {
DCHECK(CalledOnValidThread());
IPC_BEGIN_MESSAGE_MAP(GpuProcessHostUIShim, message)
IPC_MESSAGE_HANDLER(GpuHostMsg_OnLogMessage,
OnLogMessage)
#if defined(TOOLKIT_USES_GTK) || defined(OS_WIN)
IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped,
OnAcceleratedSurfaceBuffersSwapped)
IPC_MESSAGE_HANDLER(GpuHostMsg_ResizeView, OnResizeView)
#endif
#if defined(OS_MACOSX) || defined(UI_COMPOSITOR_IMAGE_TRANSPORT)
IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceNew,
OnAcceleratedSurfaceNew)
#endif
#if defined(UI_COMPOSITOR_IMAGE_TRANSPORT)
IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceRelease,
OnAcceleratedSurfaceRelease)
#endif
IPC_MESSAGE_UNHANDLED_ERROR()
IPC_END_MESSAGE_MAP()
return true;
}
void GpuProcessHostUIShim::OnLogMessage(
int level,
const std::string& header,
const std::string& message) {
DictionaryValue* dict = new DictionaryValue();
dict->SetInteger("level", level);
dict->SetString("header", header);
dict->SetString("message", message);
GpuDataManager::GetInstance()->AddLogMessage(dict);
}
#if defined(TOOLKIT_USES_GTK) || defined(OS_WIN)
void GpuProcessHostUIShim::OnResizeView(int32 renderer_id,
int32 render_view_id,
int32 route_id,
gfx::Size size) {
// Always respond even if the window no longer exists. The GPU process cannot
// make progress on the resizing command buffer until it receives the
// response.
ScopedSendOnIOThread delayed_send(
host_id_,
new AcceleratedSurfaceMsg_ResizeViewACK(route_id));
RenderViewHost* host = RenderViewHost::FromID(renderer_id, render_view_id);
if (!host)
return;
RenderWidgetHostView* view = host->view();
if (!view)
return;
gfx::PluginWindowHandle handle = view->GetCompositingSurface();
// Resize the window synchronously. The GPU process must not issue GL
// calls on the command buffer until the window is the size it expects it
// to be.
#if defined(TOOLKIT_USES_GTK)
GdkWindow* window = reinterpret_cast<GdkWindow*>(
gdk_xid_table_lookup(handle));
if (window) {
Display* display = GDK_WINDOW_XDISPLAY(window);
gdk_window_resize(window, size.width(), size.height());
XSync(display, False);
}
#elif defined(OS_WIN)
// Ensure window does not have zero area because D3D cannot create a zero
// area swap chain.
SetWindowPos(handle,
NULL,
0, 0,
std::max(1, size.width()),
std::max(1, size.height()),
SWP_NOSENDCHANGING | SWP_NOCOPYBITS | SWP_NOZORDER |
SWP_NOACTIVATE | SWP_DEFERERASE);
#endif
}
#endif
#if defined(OS_MACOSX) || defined(UI_COMPOSITOR_IMAGE_TRANSPORT)
void GpuProcessHostUIShim::OnAcceleratedSurfaceNew(
const GpuHostMsg_AcceleratedSurfaceNew_Params& params) {
ScopedSendOnIOThread delayed_send(
host_id_,
new AcceleratedSurfaceMsg_NewACK(
params.route_id,
params.surface_id,
TransportDIB::DefaultHandleValue()));
RenderViewHost* host = RenderViewHost::FromID(params.renderer_id,
params.render_view_id);
if (!host)
return;
RenderWidgetHostView* view = host->view();
if (!view)
return;
uint64 surface_id = params.surface_id;
TransportDIB::Handle surface_handle = TransportDIB::DefaultHandleValue();
#if defined(OS_MACOSX)
if (params.create_transport_dib) {
scoped_ptr<base::SharedMemory> shared_memory(new base::SharedMemory());
if (shared_memory->CreateAnonymous(params.width * params.height * 4)) {
// Create a local handle for RWHVMac to map the SHM.
TransportDIB::Handle local_handle;
if (!shared_memory->ShareToProcess(0 /* pid, not needed */,
&local_handle)) {
return;
} else {
view->AcceleratedSurfaceSetTransportDIB(params.window,
params.width,
params.height,
local_handle);
// Create a remote handle for the GPU process to map the SHM.
if (!shared_memory->ShareToProcess(0 /* pid, not needed */,
&surface_handle)) {
return;
}
}
}
} else {
view->AcceleratedSurfaceSetIOSurface(params.window,
params.width,
params.height,
surface_id);
}
#else // defined(UI_COMPOSITOR_IMAGE_TRANSPORT)
view->AcceleratedSurfaceNew(
params.width, params.height, &surface_id, &surface_handle);
#endif
delayed_send.Cancel();
Send(new AcceleratedSurfaceMsg_NewACK(
params.route_id, surface_id, surface_handle));
}
#endif
void GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
TRACE_EVENT0("renderer",
"GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped");
ScopedSendOnIOThread delayed_send(
host_id_,
new AcceleratedSurfaceMsg_BuffersSwappedACK(params.route_id));
RenderViewHost* host = RenderViewHost::FromID(params.renderer_id,
params.render_view_id);
if (!host)
return;
RenderWidgetHostView* view = host->view();
if (!view)
return;
delayed_send.Cancel();
// View must send ACK message after next composite.
view->AcceleratedSurfaceBuffersSwapped(params, host_id_);
}
#if defined(UI_COMPOSITOR_IMAGE_TRANSPORT)
void GpuProcessHostUIShim::OnAcceleratedSurfaceRelease(
const GpuHostMsg_AcceleratedSurfaceRelease_Params& params) {
RenderViewHost* host = RenderViewHost::FromID(params.renderer_id,
params.render_view_id);
if (!host)
return;
RenderWidgetHostView* view = host->view();
if (!view)
return;
view->AcceleratedSurfaceRelease(params.identifier);
}
#endif
<commit_msg>Fix bad merge. Review URL: http://codereview.chromium.org/8665005<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 "content/browser/gpu/gpu_process_host_ui_shim.h"
#include <algorithm>
#include "base/debug/trace_event.h"
#include "base/id_map.h"
#include "base/lazy_instance.h"
#include "base/process_util.h"
#include "content/browser/gpu/gpu_data_manager.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/render_widget_host_view.h"
#include "content/common/gpu/gpu_messages.h"
#include "content/public/browser/browser_thread.h"
#if defined(TOOLKIT_USES_GTK)
// These two #includes need to come after gpu_messages.h.
#include "ui/base/x/x11_util.h"
#include "ui/gfx/size.h"
#include <gdk/gdk.h> // NOLINT
#include <gdk/gdkx.h> // NOLINT
#endif
using content::BrowserThread;
namespace {
// One of the linux specific headers defines this as a macro.
#ifdef DestroyAll
#undef DestroyAll
#endif
base::LazyInstance<IDMap<GpuProcessHostUIShim> > g_hosts_by_id =
LAZY_INSTANCE_INITIALIZER;
class SendOnIOThreadTask : public Task {
public:
SendOnIOThreadTask(int host_id, IPC::Message* msg)
: host_id_(host_id),
msg_(msg) {
}
private:
void Run() {
GpuProcessHost* host = GpuProcessHost::FromID(host_id_);
if (host)
host->Send(msg_.release());
}
int host_id_;
scoped_ptr<IPC::Message> msg_;
};
class ScopedSendOnIOThread {
public:
ScopedSendOnIOThread(int host_id, IPC::Message* msg)
: host_id_(host_id),
msg_(msg),
cancelled_(false) {
}
~ScopedSendOnIOThread() {
if (!cancelled_) {
BrowserThread::PostTask(BrowserThread::IO,
FROM_HERE,
new SendOnIOThreadTask(host_id_,
msg_.release()));
}
}
void Cancel() { cancelled_ = true; }
private:
int host_id_;
scoped_ptr<IPC::Message> msg_;
bool cancelled_;
};
} // namespace
RouteToGpuProcessHostUIShimTask::RouteToGpuProcessHostUIShimTask(
int host_id,
const IPC::Message& msg)
: host_id_(host_id),
msg_(msg) {
}
RouteToGpuProcessHostUIShimTask::~RouteToGpuProcessHostUIShimTask() {
}
void RouteToGpuProcessHostUIShimTask::Run() {
GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(host_id_);
if (ui_shim)
ui_shim->OnMessageReceived(msg_);
}
GpuProcessHostUIShim::GpuProcessHostUIShim(int host_id)
: host_id_(host_id) {
g_hosts_by_id.Pointer()->AddWithID(this, host_id_);
}
// static
GpuProcessHostUIShim* GpuProcessHostUIShim::Create(int host_id) {
DCHECK(!FromID(host_id));
return new GpuProcessHostUIShim(host_id);
}
// static
void GpuProcessHostUIShim::Destroy(int host_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
delete FromID(host_id);
}
// static
void GpuProcessHostUIShim::DestroyAll() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
while (!g_hosts_by_id.Pointer()->IsEmpty()) {
IDMap<GpuProcessHostUIShim>::iterator it(g_hosts_by_id.Pointer());
delete it.GetCurrentValue();
}
}
// static
GpuProcessHostUIShim* GpuProcessHostUIShim::FromID(int host_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
return g_hosts_by_id.Pointer()->Lookup(host_id);
}
bool GpuProcessHostUIShim::Send(IPC::Message* msg) {
DCHECK(CalledOnValidThread());
return BrowserThread::PostTask(BrowserThread::IO,
FROM_HERE,
new SendOnIOThreadTask(host_id_, msg));
}
bool GpuProcessHostUIShim::OnMessageReceived(const IPC::Message& message) {
DCHECK(CalledOnValidThread());
if (message.routing_id() != MSG_ROUTING_CONTROL)
return false;
return OnControlMessageReceived(message);
}
void GpuProcessHostUIShim::SimulateRemoveAllContext() {
Send(new GpuMsg_Clean());
}
void GpuProcessHostUIShim::SimulateCrash() {
Send(new GpuMsg_Crash());
}
void GpuProcessHostUIShim::SimulateHang() {
Send(new GpuMsg_Hang());
}
GpuProcessHostUIShim::~GpuProcessHostUIShim() {
DCHECK(CalledOnValidThread());
g_hosts_by_id.Pointer()->Remove(host_id_);
}
bool GpuProcessHostUIShim::OnControlMessageReceived(
const IPC::Message& message) {
DCHECK(CalledOnValidThread());
IPC_BEGIN_MESSAGE_MAP(GpuProcessHostUIShim, message)
IPC_MESSAGE_HANDLER(GpuHostMsg_OnLogMessage,
OnLogMessage)
IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped,
OnAcceleratedSurfaceBuffersSwapped)
#if defined(TOOLKIT_USES_GTK) || defined(OS_WIN)
IPC_MESSAGE_HANDLER(GpuHostMsg_ResizeView, OnResizeView)
#endif
#if defined(OS_MACOSX) || defined(UI_COMPOSITOR_IMAGE_TRANSPORT)
IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceNew,
OnAcceleratedSurfaceNew)
#endif
#if defined(UI_COMPOSITOR_IMAGE_TRANSPORT)
IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceRelease,
OnAcceleratedSurfaceRelease)
#endif
IPC_MESSAGE_UNHANDLED_ERROR()
IPC_END_MESSAGE_MAP()
return true;
}
void GpuProcessHostUIShim::OnLogMessage(
int level,
const std::string& header,
const std::string& message) {
DictionaryValue* dict = new DictionaryValue();
dict->SetInteger("level", level);
dict->SetString("header", header);
dict->SetString("message", message);
GpuDataManager::GetInstance()->AddLogMessage(dict);
}
#if defined(TOOLKIT_USES_GTK) || defined(OS_WIN)
void GpuProcessHostUIShim::OnResizeView(int32 renderer_id,
int32 render_view_id,
int32 route_id,
gfx::Size size) {
// Always respond even if the window no longer exists. The GPU process cannot
// make progress on the resizing command buffer until it receives the
// response.
ScopedSendOnIOThread delayed_send(
host_id_,
new AcceleratedSurfaceMsg_ResizeViewACK(route_id));
RenderViewHost* host = RenderViewHost::FromID(renderer_id, render_view_id);
if (!host)
return;
RenderWidgetHostView* view = host->view();
if (!view)
return;
gfx::PluginWindowHandle handle = view->GetCompositingSurface();
// Resize the window synchronously. The GPU process must not issue GL
// calls on the command buffer until the window is the size it expects it
// to be.
#if defined(TOOLKIT_USES_GTK)
GdkWindow* window = reinterpret_cast<GdkWindow*>(
gdk_xid_table_lookup(handle));
if (window) {
Display* display = GDK_WINDOW_XDISPLAY(window);
gdk_window_resize(window, size.width(), size.height());
XSync(display, False);
}
#elif defined(OS_WIN)
// Ensure window does not have zero area because D3D cannot create a zero
// area swap chain.
SetWindowPos(handle,
NULL,
0, 0,
std::max(1, size.width()),
std::max(1, size.height()),
SWP_NOSENDCHANGING | SWP_NOCOPYBITS | SWP_NOZORDER |
SWP_NOACTIVATE | SWP_DEFERERASE);
#endif
}
#endif
#if defined(OS_MACOSX) || defined(UI_COMPOSITOR_IMAGE_TRANSPORT)
void GpuProcessHostUIShim::OnAcceleratedSurfaceNew(
const GpuHostMsg_AcceleratedSurfaceNew_Params& params) {
ScopedSendOnIOThread delayed_send(
host_id_,
new AcceleratedSurfaceMsg_NewACK(
params.route_id,
params.surface_id,
TransportDIB::DefaultHandleValue()));
RenderViewHost* host = RenderViewHost::FromID(params.renderer_id,
params.render_view_id);
if (!host)
return;
RenderWidgetHostView* view = host->view();
if (!view)
return;
uint64 surface_id = params.surface_id;
TransportDIB::Handle surface_handle = TransportDIB::DefaultHandleValue();
#if defined(OS_MACOSX)
if (params.create_transport_dib) {
scoped_ptr<base::SharedMemory> shared_memory(new base::SharedMemory());
if (shared_memory->CreateAnonymous(params.width * params.height * 4)) {
// Create a local handle for RWHVMac to map the SHM.
TransportDIB::Handle local_handle;
if (!shared_memory->ShareToProcess(0 /* pid, not needed */,
&local_handle)) {
return;
} else {
view->AcceleratedSurfaceSetTransportDIB(params.window,
params.width,
params.height,
local_handle);
// Create a remote handle for the GPU process to map the SHM.
if (!shared_memory->ShareToProcess(0 /* pid, not needed */,
&surface_handle)) {
return;
}
}
}
} else {
view->AcceleratedSurfaceSetIOSurface(params.window,
params.width,
params.height,
surface_id);
}
#else // defined(UI_COMPOSITOR_IMAGE_TRANSPORT)
view->AcceleratedSurfaceNew(
params.width, params.height, &surface_id, &surface_handle);
#endif
delayed_send.Cancel();
Send(new AcceleratedSurfaceMsg_NewACK(
params.route_id, surface_id, surface_handle));
}
#endif
void GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
TRACE_EVENT0("renderer",
"GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped");
ScopedSendOnIOThread delayed_send(
host_id_,
new AcceleratedSurfaceMsg_BuffersSwappedACK(params.route_id));
RenderViewHost* host = RenderViewHost::FromID(params.renderer_id,
params.render_view_id);
if (!host)
return;
RenderWidgetHostView* view = host->view();
if (!view)
return;
delayed_send.Cancel();
// View must send ACK message after next composite.
view->AcceleratedSurfaceBuffersSwapped(params, host_id_);
}
#if defined(UI_COMPOSITOR_IMAGE_TRANSPORT)
void GpuProcessHostUIShim::OnAcceleratedSurfaceRelease(
const GpuHostMsg_AcceleratedSurfaceRelease_Params& params) {
RenderViewHost* host = RenderViewHost::FromID(params.renderer_id,
params.render_view_id);
if (!host)
return;
RenderWidgetHostView* view = host->view();
if (!view)
return;
view->AcceleratedSurfaceRelease(params.identifier);
}
#endif
<|endoftext|> |
<commit_before>#include "client_wrapper.h"
#include "../io_service_pool.h"
#include "../service_locator/service_locator.h"
#include "../configuration/configuration_wrapper.h"
#include "../stats/stats_manager.h"
#include "../utils/log_wrapper.h"
#include "../constants.h"
#include "../http/http_commons.h"
#include "../network/communicator/communicator_factory.h"
#include <limits>
namespace nodes
{
client_wrapper::client_wrapper (
req_preamble_fn request_preamble,
req_chunk_fn request_body,
req_trailer_fn request_trailer,
req_canceled_fn request_canceled,
req_finished_fn request_finished,
header_callback hcb,
body_callback bcb,
trailer_callback tcb,
end_of_message_callback eomcb,
error_callback ecb,
response_continue_callback rccb,
logging::access_recorder *aclogger)
: node_interface(std::move(request_preamble), std::move(request_body), std::move(request_trailer),
std::move(request_canceled), std::move(request_finished),
std::move(hcb), std::move(bcb), std::move(tcb), std::move(eomcb),
std::move(ecb), std::move(rccb), aclogger)
, codec{}
, received_parsed_message{}
{
LOGTRACE("client_wrapper ",this," constructor");
/** Response callbacks: used to return control by the decoder. **/
auto codec_scb = [this](http::http_structured_data** data)
{
if(managing_continue) //reset to initial state.
{
managing_continue = false;
received_parsed_message = http::http_response{};
}
LOGTRACE("client_wrapper ",this," codec start cb triggered");
*data = &received_parsed_message;
};
auto codec_hcb = [this]()
{
assert(!finished_response);
LOGTRACE("client_wrapper ",this," codec header cb triggered");
if (received_parsed_message.status_code() == 100)
{
managing_continue = true;
//continue management;
return;
}
//received_parsed_message.set_destination_header(addr);
on_header(std::move(received_parsed_message));
};
auto codec_bcb = [this](dstring&& d)
{
assert(!finished_response);
LOGTRACE("client_wrapper ",this," codec body cb triggered");
if(!managing_continue) on_body(std::move(d));
};
auto codec_tcb = [this](dstring&& k,dstring&& v)
{
assert(!finished_response);
LOGTRACE("client_wrapper ",this," codec trailer cb triggered");
if(!managing_continue) on_trailer(std::move(k),std::move(v));
};
auto codec_ccb = [this]()
{
assert(!finished_response);
LOGTRACE("client_wrapper ",this," codec completion cb triggered");
if(managing_continue)
{
return on_response_continue();
}
finished_response = true;
stop(); //we already received our response; hence we can stop the client wrapper.
};
auto codec_fcb = [this](int err, bool& fatal)
{
LOGTRACE("client_wrapper ",this," codec error cb triggered");
switch(err)
{
case HPE_UNEXPECTED_CONTENT_LENGTH:
fatal = false;
codec.ingnore_content_len();
break;
default:
fatal = true;
}
errcode = INTERNAL_ERROR_LONG(errors::http_error_code::internal_server_error);
stop();
};
codec.register_callback(std::move(codec_scb), std::move(codec_hcb), std::move(codec_bcb), std::move(codec_tcb),
std::move(codec_ccb), std::move(codec_fcb));
}
client_wrapper::~client_wrapper()
{
assert(waiting_count == 0);
LOGTRACE("client_wrapper ",this," destructor");
}
void client_wrapper::on_request_preamble(http::http_request&& preamble)
{
LOGTRACE("client_wrapper ",this," on_request_preamble");
start = std::chrono::high_resolution_clock::now();
local_request = std::move(preamble);
++waiting_count;
//retrieve a connector to talk with remote destination.
service::locator::communicator_factory().get_connector(local_request, [this](std::shared_ptr<network::communicator_interface> ci){
--waiting_count;
LOGTRACE("client_wrapper ", this, " received communicator");
ci->set_callbacks([this](const char *data, size_t size)
{
if(!codec.decode(data, size))
{
errcode = INTERNAL_ERROR_LONG( errors::http_error_code::internal_server_error );
stop();
}
},[this](errors::error_code errc)
{
if(errc.code() > 1)
errcode = errc; //todo: this is a porchetta.
stop();
termination_handler();
});
write_proxy.set_communicator(ci);
}, [this](int e){
LOGTRACE("client_wrapper ", this, " could not retrieve a communicator for the specified endpoint");
--waiting_count;
errcode = INTERNAL_ERROR_LONG(errors::http_error_code::internal_server_error);
canceled = true;
stop();
termination_handler();
});
write_proxy.enqueue_for_write(codec.encode_header(local_request));
}
void client_wrapper::on_request_body(dstring&& chunk)
{
LOGTRACE("client_wrapper ",this," on_request_body");
if(!errcode)
{
write_proxy.enqueue_for_write(codec.encode_body(chunk));
}
}
void client_wrapper::on_request_trailer(dstring&& k, dstring&& v)
{
if(!errcode)
{
write_proxy.enqueue_for_write(codec.encode_trailer(k,v));
}
}
void client_wrapper::on_request_finished()
{
LOGTRACE("client_wrapper ",this," on_request_finished");
finished_request = true;
if(!errcode)
{
write_proxy.enqueue_for_write(codec.encode_eom());
return;
}
//in some cases, response could have arrived before the end of the request; in this case, we shall react accordingly.
if(finished_response)
termination_handler();
}
void client_wrapper::termination_handler()
{
if( !stopping ) return;
if(waiting_count > 0)
return LOGTRACE("client_wrapper ",this," waiting for ", (int) waiting_count, " lambdas");
auto end = std::chrono::high_resolution_clock::now();
auto latency = end - start;
uint64_t nanoseconds = std::chrono::nanoseconds(latency).count();
service::locator::stats_manager().enqueue( stats::stat_type::board_response_latency,
static_cast<double>( nanoseconds ) );
if(finished_response && finished_request) //notice that with the new modification finished_request check is probably not needed anymore; however, it is safer and costs nothing.
{
LOGTRACE("client_wrapper ",this," End of message latency: ", static_cast<double>( nanoseconds ) );
return on_end_of_message();
}
if(errcode && (finished_request || canceled))
{
std::cout << "sending back an error!" << std::endl;
LOGTRACE("client_wrapper ",this," Error:", errcode);
return on_error(errcode);
}
}
void client_wrapper::on_request_canceled(const errors::error_code &ec)
{
LOGDEBUG("client_wrapper ", this, " operations canceled from upstream with error ", ec);
errcode = ec;
canceled = true;
stop();
}
void client_wrapper::stop()
{
LOGTRACE("client_wrapper ",this," stop!");
if(!stopping)
{
write_proxy.shutdown_communicator();
LOGDEBUG("client_wrapper ",this," stopping");
stopping = true;
}
}
} // namespace nodes
<commit_msg>changed client_wrapper error code in case resource could not be retrieved<commit_after>#include "client_wrapper.h"
#include "../io_service_pool.h"
#include "../service_locator/service_locator.h"
#include "../configuration/configuration_wrapper.h"
#include "../stats/stats_manager.h"
#include "../utils/log_wrapper.h"
#include "../constants.h"
#include "../http/http_commons.h"
#include "../network/communicator/communicator_factory.h"
#include <limits>
namespace nodes
{
client_wrapper::client_wrapper (
req_preamble_fn request_preamble,
req_chunk_fn request_body,
req_trailer_fn request_trailer,
req_canceled_fn request_canceled,
req_finished_fn request_finished,
header_callback hcb,
body_callback bcb,
trailer_callback tcb,
end_of_message_callback eomcb,
error_callback ecb,
response_continue_callback rccb,
logging::access_recorder *aclogger)
: node_interface(std::move(request_preamble), std::move(request_body), std::move(request_trailer),
std::move(request_canceled), std::move(request_finished),
std::move(hcb), std::move(bcb), std::move(tcb), std::move(eomcb),
std::move(ecb), std::move(rccb), aclogger)
, codec{}
, received_parsed_message{}
{
LOGTRACE("client_wrapper ",this," constructor");
/** Response callbacks: used to return control by the decoder. **/
auto codec_scb = [this](http::http_structured_data** data)
{
if(managing_continue) //reset to initial state.
{
managing_continue = false;
received_parsed_message = http::http_response{};
}
LOGTRACE("client_wrapper ",this," codec start cb triggered");
*data = &received_parsed_message;
};
auto codec_hcb = [this]()
{
assert(!finished_response);
LOGTRACE("client_wrapper ",this," codec header cb triggered");
if (received_parsed_message.status_code() == 100)
{
managing_continue = true;
//continue management;
return;
}
//received_parsed_message.set_destination_header(addr);
on_header(std::move(received_parsed_message));
};
auto codec_bcb = [this](dstring&& d)
{
assert(!finished_response);
LOGTRACE("client_wrapper ",this," codec body cb triggered");
if(!managing_continue) on_body(std::move(d));
};
auto codec_tcb = [this](dstring&& k,dstring&& v)
{
assert(!finished_response);
LOGTRACE("client_wrapper ",this," codec trailer cb triggered");
if(!managing_continue) on_trailer(std::move(k),std::move(v));
};
auto codec_ccb = [this]()
{
assert(!finished_response);
LOGTRACE("client_wrapper ",this," codec completion cb triggered");
if(managing_continue)
{
return on_response_continue();
}
finished_response = true;
stop(); //we already received our response; hence we can stop the client wrapper.
};
auto codec_fcb = [this](int err, bool& fatal)
{
LOGTRACE("client_wrapper ",this," codec error cb triggered");
switch(err)
{
case HPE_UNEXPECTED_CONTENT_LENGTH:
fatal = false;
codec.ingnore_content_len();
break;
default:
fatal = true;
}
errcode = INTERNAL_ERROR_LONG(errors::http_error_code::internal_server_error);
stop();
};
codec.register_callback(std::move(codec_scb), std::move(codec_hcb), std::move(codec_bcb), std::move(codec_tcb),
std::move(codec_ccb), std::move(codec_fcb));
}
client_wrapper::~client_wrapper()
{
assert(waiting_count == 0);
LOGTRACE("client_wrapper ",this," destructor");
}
void client_wrapper::on_request_preamble(http::http_request&& preamble)
{
LOGTRACE("client_wrapper ",this," on_request_preamble");
start = std::chrono::high_resolution_clock::now();
local_request = std::move(preamble);
++waiting_count;
//retrieve a connector to talk with remote destination.
service::locator::communicator_factory().get_connector(local_request, [this](std::shared_ptr<network::communicator_interface> ci){
--waiting_count;
LOGTRACE("client_wrapper ", this, " received communicator");
ci->set_callbacks([this](const char *data, size_t size)
{
if(!codec.decode(data, size))
{
errcode = INTERNAL_ERROR_LONG( errors::http_error_code::internal_server_error );
stop();
}
},[this](errors::error_code errc)
{
if(errc.code() > 1)
errcode = errc; //todo: this is a porchetta.
stop();
termination_handler();
});
write_proxy.set_communicator(ci);
}, [this](int e){
LOGTRACE("client_wrapper ", this, " could not retrieve a communicator for the specified endpoint");
--waiting_count;
errcode = INTERNAL_ERROR_LONG(errors::http_error_code::not_found);
canceled = true;
stop();
termination_handler();
});
write_proxy.enqueue_for_write(codec.encode_header(local_request));
}
void client_wrapper::on_request_body(dstring&& chunk)
{
LOGTRACE("client_wrapper ",this," on_request_body");
if(!errcode)
{
write_proxy.enqueue_for_write(codec.encode_body(chunk));
}
}
void client_wrapper::on_request_trailer(dstring&& k, dstring&& v)
{
if(!errcode)
{
write_proxy.enqueue_for_write(codec.encode_trailer(k,v));
}
}
void client_wrapper::on_request_finished()
{
LOGTRACE("client_wrapper ",this," on_request_finished");
finished_request = true;
if(!errcode)
{
write_proxy.enqueue_for_write(codec.encode_eom());
return;
}
//in some cases, response could have arrived before the end of the request; in this case, we shall react accordingly.
if(finished_response)
termination_handler();
}
void client_wrapper::termination_handler()
{
if( !stopping ) return;
if(waiting_count > 0)
return LOGTRACE("client_wrapper ",this," waiting for ", (int) waiting_count, " lambdas");
auto end = std::chrono::high_resolution_clock::now();
auto latency = end - start;
uint64_t nanoseconds = std::chrono::nanoseconds(latency).count();
service::locator::stats_manager().enqueue( stats::stat_type::board_response_latency,
static_cast<double>( nanoseconds ) );
if(finished_response && finished_request) //notice that with the new modification finished_request check is probably not needed anymore; however, it is safer and costs nothing.
{
LOGTRACE("client_wrapper ",this," End of message latency: ", static_cast<double>( nanoseconds ) );
return on_end_of_message();
}
if(errcode && (finished_request || canceled))
{
LOGTRACE("client_wrapper ",this," Error:", errcode);
return on_error(errcode);
}
}
void client_wrapper::on_request_canceled(const errors::error_code &ec)
{
LOGDEBUG("client_wrapper ", this, " operations canceled from upstream with error ", ec);
errcode = ec;
canceled = true;
stop();
}
void client_wrapper::stop()
{
LOGTRACE("client_wrapper ",this," stop!");
if(!stopping)
{
write_proxy.shutdown_communicator();
LOGDEBUG("client_wrapper ",this," stopping");
stopping = true;
}
}
} // namespace nodes
<|endoftext|> |
<commit_before>// Copyright 2014 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 "content/browser/loader/temporary_file_stream.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/files/file_util_proxy.h"
#include "base/memory/ref_counted.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/file_stream.h"
#include "webkit/common/blob/shareable_file_reference.h"
using webkit_blob::ShareableFileReference;
namespace content {
namespace {
void DidCreateTemporaryFile(
const CreateTemporaryFileStreamCallback& callback,
base::File::Error error_code,
base::PassPlatformFile file_handle,
const base::FilePath& file_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (error_code != base::File::FILE_OK) {
callback.Run(error_code, scoped_ptr<net::FileStream>(), NULL);
return;
}
// Cancelled or not, create the deletable_file so the temporary is cleaned up.
scoped_refptr<ShareableFileReference> deletable_file =
ShareableFileReference::GetOrCreate(
file_path,
ShareableFileReference::DELETE_ON_FINAL_RELEASE,
BrowserThread::GetMessageLoopProxyForThread(
BrowserThread::FILE).get());
scoped_ptr<net::FileStream> file_stream(new net::FileStream(
file_handle.ReleaseValue(),
base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_ASYNC));
callback.Run(error_code, file_stream.Pass(), deletable_file);
}
} // namespace
void CreateTemporaryFileStream(
const CreateTemporaryFileStreamCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
base::FileUtilProxy::CreateTemporary(
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE).get(),
base::PLATFORM_FILE_ASYNC,
base::Bind(&DidCreateTemporaryFile, callback));
}
} // namespace content
<commit_msg>Migrate CreateTemporaryFileStream to use FileProxy<commit_after>// Copyright 2014 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 "content/browser/loader/temporary_file_stream.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/files/file_proxy.h"
#include "base/memory/ref_counted.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/file_stream.h"
#include "webkit/common/blob/shareable_file_reference.h"
using webkit_blob::ShareableFileReference;
namespace content {
namespace {
void DidCreateTemporaryFile(
const CreateTemporaryFileStreamCallback& callback,
scoped_ptr<base::FileProxy> file_proxy,
base::File::Error error_code,
const base::FilePath& file_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!file_proxy->IsValid()) {
callback.Run(error_code, scoped_ptr<net::FileStream>(), NULL);
return;
}
// Cancelled or not, create the deletable_file so the temporary is cleaned up.
scoped_refptr<ShareableFileReference> deletable_file =
ShareableFileReference::GetOrCreate(
file_path,
ShareableFileReference::DELETE_ON_FINAL_RELEASE,
BrowserThread::GetMessageLoopProxyForThread(
BrowserThread::FILE).get());
scoped_ptr<net::FileStream> file_stream(
new net::FileStream(file_proxy->TakeFile()));
callback.Run(error_code, file_stream.Pass(), deletable_file);
}
} // namespace
void CreateTemporaryFileStream(
const CreateTemporaryFileStreamCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
scoped_ptr<base::FileProxy> file_proxy(new base::FileProxy(
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE).get()));
base::FileProxy* proxy = file_proxy.get();
proxy->CreateTemporary(
base::File::FLAG_ASYNC,
base::Bind(&DidCreateTemporaryFile, callback, Passed(&file_proxy)));
}
} // namespace content
<|endoftext|> |
<commit_before>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
* $Log$
* Revision 1.5 2004/05/05 15:51:29 strk
* Fixed big leak in intersectChains()
*
* Revision 1.4 2004/05/03 22:56:44 strk
* leaks fixed, exception specification omitted.
*
* Revision 1.3 2004/04/19 16:14:52 strk
* Some memory leaks plugged in noding algorithms.
*
* Revision 1.2 2004/04/16 12:48:07 strk
* Leak fixes.
*
* Revision 1.1 2004/03/26 07:48:30 ybychkov
* "noding" package ported (JTS 1.4)
*
*
**********************************************************************/
#include "../headers/noding.h"
namespace geos {
MCQuadtreeNoder::MCQuadtreeNoder(){
chains=new vector<indexMonotoneChain*>();
index=new STRtree();
idCounter = 0;
nOverlaps = 0;
}
MCQuadtreeNoder::~MCQuadtreeNoder(){
for (int i=0; i<chains->size(); i++)
{
delete (*chains)[i];
}
delete chains;
delete index;
}
vector<SegmentString*> *
MCQuadtreeNoder::node(vector<SegmentString*> *inputSegStrings)
{
for(int i=0; i<(int)inputSegStrings->size();i++) {
add((*inputSegStrings)[i]);
}
intersectChains();
//System.out.println("MCQuadtreeNoder: # chain overlaps = " + nOverlaps);
vector<SegmentString*> *nodedSegStrings=getNodedEdges(inputSegStrings);
return nodedSegStrings;
}
void MCQuadtreeNoder::intersectChains() {
MonotoneChainOverlapAction *overlapAction = new SegmentOverlapAction(segInt);
for (int i=0; i<(int)chains->size();i++) {
indexMonotoneChain *queryChain=(*chains)[i];
vector<void*> *overlapChains =index->query(queryChain->getEnvelope());
for (int j=0; j<(int)overlapChains->size();j++) {
indexMonotoneChain *testChain=(indexMonotoneChain*)(*overlapChains)[j];
/**
* following test makes sure we only compare each pair of chains once
* and that we don't compare a chain to itself
*/
if (testChain->getId()>queryChain->getId()) {
queryChain->computeOverlaps(testChain, overlapAction);
nOverlaps++;
}
}
delete overlapChains;
}
delete overlapAction;
}
void MCQuadtreeNoder::add(SegmentString *segStr) {
vector<indexMonotoneChain*> *segChains=MonotoneChainBuilder::getChains((CoordinateList*)segStr->getCoordinates(),segStr);
for (int i=0; i<(int)segChains->size();i++) {
indexMonotoneChain *mc=(*segChains)[i];
mc->setId(idCounter++);
index->insert(mc->getEnvelope(), mc);
chains->push_back(mc);
}
delete segChains;
}
MCQuadtreeNoder::SegmentOverlapAction::SegmentOverlapAction(nodingSegmentIntersector *newSi){
si=newSi;
}
void MCQuadtreeNoder::SegmentOverlapAction::overlap(indexMonotoneChain *mc1, int start1, indexMonotoneChain *mc2, int start2) {
SegmentString *ss1=(SegmentString*) mc1->getContext();
SegmentString *ss2=(SegmentString*) mc2->getContext();
si->processIntersections(ss1, start1, ss2, start2);
}
}
<commit_msg>reduced explicit local objects allocation<commit_after>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
* $Log$
* Revision 1.6 2004/05/05 16:39:50 strk
* reduced explicit local objects allocation
*
* Revision 1.5 2004/05/05 15:51:29 strk
* Fixed big leak in intersectChains()
*
* Revision 1.4 2004/05/03 22:56:44 strk
* leaks fixed, exception specification omitted.
*
* Revision 1.3 2004/04/19 16:14:52 strk
* Some memory leaks plugged in noding algorithms.
*
* Revision 1.2 2004/04/16 12:48:07 strk
* Leak fixes.
*
* Revision 1.1 2004/03/26 07:48:30 ybychkov
* "noding" package ported (JTS 1.4)
*
*
**********************************************************************/
#include "../headers/noding.h"
namespace geos {
MCQuadtreeNoder::MCQuadtreeNoder(){
chains=new vector<indexMonotoneChain*>();
index=new STRtree();
idCounter = 0;
nOverlaps = 0;
}
MCQuadtreeNoder::~MCQuadtreeNoder(){
for (int i=0; i<chains->size(); i++)
{
delete (*chains)[i];
}
delete chains;
delete index;
}
vector<SegmentString*> *
MCQuadtreeNoder::node(vector<SegmentString*> *inputSegStrings)
{
for(int i=0; i<(int)inputSegStrings->size();i++) {
add((*inputSegStrings)[i]);
}
intersectChains();
//System.out.println("MCQuadtreeNoder: # chain overlaps = " + nOverlaps);
vector<SegmentString*> *nodedSegStrings=getNodedEdges(inputSegStrings);
return nodedSegStrings;
}
void
MCQuadtreeNoder::intersectChains()
{
SegmentOverlapAction soa(segInt);
MonotoneChainOverlapAction *overlapAction = &soa;
for (int i=0; i<(int)chains->size();i++) {
indexMonotoneChain *queryChain=(*chains)[i];
vector<void*> *overlapChains =index->query(queryChain->getEnvelope());
for (int j=0; j<(int)overlapChains->size();j++) {
indexMonotoneChain *testChain=(indexMonotoneChain*)(*overlapChains)[j];
/**
* following test makes sure we only compare each pair of chains once
* and that we don't compare a chain to itself
*/
if (testChain->getId()>queryChain->getId()) {
queryChain->computeOverlaps(testChain, overlapAction);
nOverlaps++;
}
}
delete overlapChains;
}
}
void MCQuadtreeNoder::add(SegmentString *segStr) {
vector<indexMonotoneChain*> *segChains=MonotoneChainBuilder::getChains((CoordinateList*)segStr->getCoordinates(),segStr);
for (int i=0; i<(int)segChains->size();i++) {
indexMonotoneChain *mc=(*segChains)[i];
mc->setId(idCounter++);
index->insert(mc->getEnvelope(), mc);
chains->push_back(mc);
}
delete segChains;
}
MCQuadtreeNoder::SegmentOverlapAction::SegmentOverlapAction(nodingSegmentIntersector *newSi){
si=newSi;
}
void MCQuadtreeNoder::SegmentOverlapAction::overlap(indexMonotoneChain *mc1, int start1, indexMonotoneChain *mc2, int start2) {
SegmentString *ss1=(SegmentString*) mc1->getContext();
SegmentString *ss2=(SegmentString*) mc2->getContext();
si->processIntersections(ss1, start1, ss2, start2);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "testing/gtest/include/gtest/gtest.h"
#include "base/memory/scoped_ptr.h"
#include "base/time.h"
#include "content/common/hi_res_timer_manager.h"
#include "ui/base/system_monitor/system_monitor.h"
#if defined(OS_WIN)
TEST(HiResTimerManagerTest, ToggleOnOff) {
MessageLoop loop;
scoped_ptr<ui::SystemMonitor> system_monitor(new ui::SystemMonitor());
HighResolutionTimerManager manager;
// At this point, we don't know if the high resolution timers are on or off,
// it depends on what system the tests are running on (for example, if this
// test is running on a laptop/battery, then the SystemMonitor would have
// already set the PowerState to battery power; but if we're running on a
// desktop, then the PowerState will be non-battery power). Simulate a power
// level change to get to a deterministic state.
manager.OnPowerStateChange(/* on_battery */ false);
// Loop a few times to test power toggling.
for (int loop = 2; loop >= 0; --loop) {
// The manager has the high resolution clock enabled now.
EXPECT_TRUE(manager.hi_res_clock_available());
// But the Time class has it off, because it hasn't been activated.
EXPECT_FALSE(base::Time::IsHighResolutionTimerInUse());
// Activate the high resolution timer.
base::Time::ActivateHighResolutionTimer(true);
EXPECT_TRUE(base::Time::IsHighResolutionTimerInUse());
// Simulate a on-battery power event.
manager.OnPowerStateChange(/* on_battery */ true);
EXPECT_FALSE(manager.hi_res_clock_available());
EXPECT_FALSE(base::Time::IsHighResolutionTimerInUse());
// Simulate a off-battery power event.
manager.OnPowerStateChange(/* on_battery */ false);
EXPECT_TRUE(manager.hi_res_clock_available());
EXPECT_TRUE(base::Time::IsHighResolutionTimerInUse());
// De-activate the high resolution timer.
base::Time::ActivateHighResolutionTimer(false);
}
}
#endif // defined(OS_WIN)
<commit_msg>Mark test as flakey while I sort out what is going on. Review URL: http://codereview.chromium.org/7031011<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "testing/gtest/include/gtest/gtest.h"
#include "base/memory/scoped_ptr.h"
#include "base/time.h"
#include "content/common/hi_res_timer_manager.h"
#include "ui/base/system_monitor/system_monitor.h"
#if defined(OS_WIN)
TEST(HiResTimerManagerTest, FLAKY_ToggleOnOff) {
MessageLoop loop;
scoped_ptr<ui::SystemMonitor> system_monitor(new ui::SystemMonitor());
HighResolutionTimerManager manager;
// At this point, we don't know if the high resolution timers are on or off,
// it depends on what system the tests are running on (for example, if this
// test is running on a laptop/battery, then the SystemMonitor would have
// already set the PowerState to battery power; but if we're running on a
// desktop, then the PowerState will be non-battery power). Simulate a power
// level change to get to a deterministic state.
manager.OnPowerStateChange(/* on_battery */ false);
// Loop a few times to test power toggling.
for (int loop = 2; loop >= 0; --loop) {
// The manager has the high resolution clock enabled now.
EXPECT_TRUE(manager.hi_res_clock_available());
// But the Time class has it off, because it hasn't been activated.
EXPECT_FALSE(base::Time::IsHighResolutionTimerInUse());
// Activate the high resolution timer.
base::Time::ActivateHighResolutionTimer(true);
EXPECT_TRUE(base::Time::IsHighResolutionTimerInUse());
// Simulate a on-battery power event.
manager.OnPowerStateChange(/* on_battery */ true);
EXPECT_FALSE(manager.hi_res_clock_available());
EXPECT_FALSE(base::Time::IsHighResolutionTimerInUse());
// Simulate a off-battery power event.
manager.OnPowerStateChange(/* on_battery */ false);
EXPECT_TRUE(manager.hi_res_clock_available());
EXPECT_TRUE(base::Time::IsHighResolutionTimerInUse());
// De-activate the high resolution timer.
base::Time::ActivateHighResolutionTimer(false);
}
}
#endif // defined(OS_WIN)
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlbrshi.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 06:19:40 $
*
* 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 _XMLBRSHI_HXX
#define _XMLBRSHI_HXX
#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif
class SvXMLImport;
class SvXMLUnitConverter;
class SvxBrushItem;
namespace rtl { class OUString; }
namespace com { namespace sun { namespace star {
namespace io { class XOutputStream; }
} } }
class SwXMLBrushItemImportContext : public SvXMLImportContext
{
private:
::com::sun::star::uno::Reference < ::com::sun::star::io::XOutputStream > xBase64Stream;
SvxBrushItem *pItem;
void ProcessAttrs(
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
const SvXMLUnitConverter& rUnitConv );
public:
TYPEINFO();
SwXMLBrushItemImportContext(
SvXMLImport& rImport,
sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
const SvXMLUnitConverter& rUnitConv,
const SvxBrushItem& rItem );
SwXMLBrushItemImportContext(
SvXMLImport& rImport,
sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
const SvXMLUnitConverter& rUnitConv,
sal_uInt16 nWhich );
virtual ~SwXMLBrushItemImportContext();
virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList );
virtual void EndElement();
const SvxBrushItem& GetItem() const { return *pItem; }
};
#endif // _XMLBRSHI_HXX
<commit_msg>INTEGRATION: CWS thaiissues (1.2.1440); FILE MERGED<commit_after>/*************************************************************************
*
* $RCSfile: xmlbrshi.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2005-11-16 09:43:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLBRSHI_HXX
#define _XMLBRSHI_HXX
#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif
class SvXMLImport;
class SvXMLUnitConverter;
class SvxBrushItem;
namespace rtl { class OUString; }
namespace com { namespace sun { namespace star {
namespace io { class XOutputStream; }
} } }
class SwXMLBrushItemImportContext : public SvXMLImportContext
{
private:
::com::sun::star::uno::Reference < ::com::sun::star::io::XOutputStream > xBase64Stream;
SvxBrushItem *pItem;
void ProcessAttrs(
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
const SvXMLUnitConverter& rUnitConv );
public:
TYPEINFO();
SwXMLBrushItemImportContext(
SvXMLImport& rImport,
sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
const SvXMLUnitConverter& rUnitConv,
const SvxBrushItem& rItem );
SwXMLBrushItemImportContext(
SvXMLImport& rImport,
sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
const SvXMLUnitConverter& rUnitConv,
sal_uInt16 nWhich );
virtual ~SwXMLBrushItemImportContext();
virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList );
virtual void EndElement();
const SvxBrushItem& GetItem() const { return *pItem; }
};
#endif // _XMLBRSHI_HXX
<|endoftext|> |
<commit_before>////////////////
//Task 1
//Days in a month
////////////////
#include <iostream>
using namespace std;
int main()
{
int year, month, days;
cout << "Въведете месец (1-12)\n";
cin >> month;
cout << "Въведете година\n";
cin >> year;
bool isLeap = (year % 4 == 0 && year % 100 != 0
|| year % 400 == 0) ? true : false;
// if-else implementation
/*
if (month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month ==10 || month == 12) {
days = 31;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
days = 30;
} else {
if (isLeap) {
days = 29;
} else {
days = 28;
}
}
*/
// switch implementation
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = 31; break;
case 4: case 6: case 9: case 11:
days = 30; break;
case 2:
if (isLeap) {
days = 29;
} else {
days = 28;
}
}
cout << "Month " << month << " has " << days << " days.\n";
return 0;
}
<commit_msg>minor changes<commit_after>////////////////
//Task 1
//Days in a month
////////////////
#include <iostream>
using namespace std;
int main()
{
int year, month, days;
cout << "Въведете месец (1-12)\n";
cin >> month;
cout << "Въведете година\n";
cin >> year;
bool isLeap = (year % 4 == 0 && year % 100 != 0
|| year % 400 == 0) ? true : false;
// if-else implementation
/*
if (month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month ==10 || month == 12) {
days = 31;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
days = 30;
} else {
if (isLeap) {
days = 29;
} else {
days = 28;
}
}
*/
// switch implementation
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = 31; break;
case 4: case 6: case 9: case 11:
days = 30; break;
case 2:
if (isLeap) {
days = 29;
} else {
days = 28;
}
break;
default:
cout << "Wrong value for month" << endl;
}
cout << "Month " << month << " has " << days << " days.\n";
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TableFieldDescWin.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: kz $ $Date: 2007-05-10 10:42:14 $
*
* 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 DBAUI_TABLEFIELDDESCRIPTION_HXX
#define DBAUI_TABLEFIELDDESCRIPTION_HXX
#ifndef _SV_TABPAGE_HXX
#include <vcl/tabpage.hxx>
#endif
#ifndef DBAUI_TABLEFIELDDESCGENPAGE_HXX
#include "FieldDescGenWin.hxx"
#endif
#ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX
#include "IClipBoardTest.hxx"
#endif
class FixedText;
namespace dbaui
{
class OFieldDescGenWin;
class OTableDesignHelpBar;
class OFieldDescription;
//==================================================================
// Ableitung von TabPage ist ein Trick von TH,
// um Aenderungen der Systemfarben zu bemerken (Bug #53905)
class OTableFieldDescWin : public TabPage
,public IClipboardTest
{
enum ChildFocusState
{
DESCRIPTION,
HELP,
NONE
};
private:
OTableDesignHelpBar* m_pHelpBar;
OFieldDescGenWin* m_pGenPage;
FixedText* m_pHeader;
ChildFocusState m_eChildFocus;
IClipboardTest* getActiveChild() const;
protected:
virtual void Resize();
virtual void Paint( const Rectangle& rRect );
public:
OTableFieldDescWin( Window* pParent);
virtual ~OTableFieldDescWin();
virtual void Init();
void DisplayData( OFieldDescription* pFieldDescr );
void SaveData( OFieldDescription* pFieldDescr );
void SetReadOnly( BOOL bReadOnly );
// window overloads
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void GetFocus();
virtual void LoseFocus();
void SetControlText( USHORT nControlId, const String& rText )
{ m_pGenPage->SetControlText(nControlId,rText); }
String GetControlText( USHORT nControlId )
{ return m_pGenPage->GetControlText(nControlId); }
// short GetFormatCategory(OFieldDescription* pFieldDescr) { return m_pGenPage ? m_pGenPage->GetFormatCategory(pFieldDescr) : -1; }
// liefert zum am Feld eingestellten Format einen der CAT_xxx-Werte (CAT_NUMBER, CAT_DATE ...)
String BoolStringPersistent(const String& rUIString) const { return m_pGenPage->BoolStringPersistent(rUIString); }
String BoolStringUI(const String& rPersistentString) const { return m_pGenPage->BoolStringUI(rPersistentString); }
// IClipboardTest
virtual sal_Bool isCutAllowed();
virtual sal_Bool isCopyAllowed();
virtual sal_Bool isPasteAllowed();
virtual sal_Bool hasChildPathFocus() { return HasChildPathFocus(); }
virtual void copy();
virtual void cut();
virtual void paste();
inline OFieldDescGenWin* getGenPage() const { return m_pGenPage; }
inline OTableDesignHelpBar* getHelpBar() const { return m_pHelpBar; }
};
}
#endif // DBAUI_TABLEFIELDDESCRIPTION_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.8.178); FILE MERGED 2008/03/31 13:28:07 rt 1.8.178.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: TableFieldDescWin.hxx,v $
* $Revision: 1.9 $
*
* 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 DBAUI_TABLEFIELDDESCRIPTION_HXX
#define DBAUI_TABLEFIELDDESCRIPTION_HXX
#ifndef _SV_TABPAGE_HXX
#include <vcl/tabpage.hxx>
#endif
#ifndef DBAUI_TABLEFIELDDESCGENPAGE_HXX
#include "FieldDescGenWin.hxx"
#endif
#ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX
#include "IClipBoardTest.hxx"
#endif
class FixedText;
namespace dbaui
{
class OFieldDescGenWin;
class OTableDesignHelpBar;
class OFieldDescription;
//==================================================================
// Ableitung von TabPage ist ein Trick von TH,
// um Aenderungen der Systemfarben zu bemerken (Bug #53905)
class OTableFieldDescWin : public TabPage
,public IClipboardTest
{
enum ChildFocusState
{
DESCRIPTION,
HELP,
NONE
};
private:
OTableDesignHelpBar* m_pHelpBar;
OFieldDescGenWin* m_pGenPage;
FixedText* m_pHeader;
ChildFocusState m_eChildFocus;
IClipboardTest* getActiveChild() const;
protected:
virtual void Resize();
virtual void Paint( const Rectangle& rRect );
public:
OTableFieldDescWin( Window* pParent);
virtual ~OTableFieldDescWin();
virtual void Init();
void DisplayData( OFieldDescription* pFieldDescr );
void SaveData( OFieldDescription* pFieldDescr );
void SetReadOnly( BOOL bReadOnly );
// window overloads
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void GetFocus();
virtual void LoseFocus();
void SetControlText( USHORT nControlId, const String& rText )
{ m_pGenPage->SetControlText(nControlId,rText); }
String GetControlText( USHORT nControlId )
{ return m_pGenPage->GetControlText(nControlId); }
// short GetFormatCategory(OFieldDescription* pFieldDescr) { return m_pGenPage ? m_pGenPage->GetFormatCategory(pFieldDescr) : -1; }
// liefert zum am Feld eingestellten Format einen der CAT_xxx-Werte (CAT_NUMBER, CAT_DATE ...)
String BoolStringPersistent(const String& rUIString) const { return m_pGenPage->BoolStringPersistent(rUIString); }
String BoolStringUI(const String& rPersistentString) const { return m_pGenPage->BoolStringUI(rPersistentString); }
// IClipboardTest
virtual sal_Bool isCutAllowed();
virtual sal_Bool isCopyAllowed();
virtual sal_Bool isPasteAllowed();
virtual sal_Bool hasChildPathFocus() { return HasChildPathFocus(); }
virtual void copy();
virtual void cut();
virtual void paste();
inline OFieldDescGenWin* getGenPage() const { return m_pGenPage; }
inline OTableDesignHelpBar* getHelpBar() const { return m_pHelpBar; }
};
}
#endif // DBAUI_TABLEFIELDDESCRIPTION_HXX
<|endoftext|> |
<commit_before>/**
* @file sgd_impl.hpp
* @author Ryan Curtin
*
* Implementation of stochastic gradient descent.
*/
#ifndef __MLPACK_CORE_OPTIMIZERS_SGD_SGD_IMPL_HPP
#define __MLPACK_CORE_OPTIMIZERS_SGD_SGD_IMPL_HPP
// In case it hasn't been included yet.
#include "sgd.hpp"
namespace mlpack {
namespace optimization {
template<typename DecomposableFunctionType>
SGD<DecomposableFunctionType>::SGD(DecomposableFunctionType& function,
const double stepSize,
const size_t maxIterations,
const double tolerance,
const bool shuffle) :
function(function),
stepSize(stepSize),
maxIterations(maxIterations),
tolerance(tolerance),
shuffle(shuffle)
{ /* Nothing to do. */ }
//! Optimize the function (minimize).
template<typename DecomposableFunctionType>
double SGD<DecomposableFunctionType>::Optimize(arma::mat& iterate)
{
// Find the number of functions to use.
const size_t numFunctions = function.NumFunctions();
// This is used only if shuffle is true.
arma::vec visitationOrder;
if (shuffle)
visitationOrder = arma::shuffle(arma::linspace(0, (numFunctions - 1),
numFunctions));
// To keep track of where we are and how things are going.
size_t currentFunction = 0;
double overallObjective = 0;
double lastObjective = DBL_MAX;
// Calculate the first objective function.
for (size_t i = 0; i < numFunctions; ++i)
overallObjective += function.Evaluate(iterate, i);
// Now iterate!
arma::mat gradient(iterate.n_rows, iterate.n_cols);
for (size_t i = 1; i != maxIterations; ++i, ++currentFunction)
{
// Is this iteration the start of a sequence?
if ((currentFunction % numFunctions) == 0)
{
// Output current objective function.
Log::Info << "SGD: iteration " << i << ", objective " << overallObjective
<< "." << std::endl;
if (overallObjective != overallObjective)
{
Log::Warn << "SGD: converged to " << overallObjective << "; terminating"
<< " with failure. Try a smaller step size?" << std::endl;
return overallObjective;
}
if (std::abs(lastObjective - overallObjective) < tolerance)
{
Log::Info << "SGD: minimized within tolerance " << tolerance << "; "
<< "terminating optimization." << std::endl;
return overallObjective;
}
// Reset the counter variables.
lastObjective = overallObjective;
overallObjective = 0;
currentFunction = 0;
if (shuffle) // Determine order of visitation.
visitationOrder = arma::shuffle(visitationOrder);
}
// Evaluate the gradient for this iteration.
function.Gradient(iterate, currentFunction, gradient);
// And update the iterate.
iterate -= stepSize * gradient;
// Now add that to the overall objective function.
overallObjective += function.Evaluate(iterate, currentFunction);
}
Log::Info << "SGD: maximum iterations (" << maxIterations << ") reached; "
<< "terminating optimization." << std::endl;
return overallObjective;
}
// Convert the object to a string.
template<typename DecomposableFunctionType>
std::string SGD<DecomposableFunctionType>::ToString() const
{
std::ostringstream convert;
convert << "SGD [" << this << "]" << std::endl;
convert << " Function:" << std::endl;
convert << util::Indent(function.ToString(), 2);
convert << " StepSize: " << stepSize << std::endl;
convert << " Maximum Iterations: " << maxIterations << std::endl;
convert << " Tolerance: " << tolerance << std::endl;
convert << " Shuffle: " << (shuffle ? "true" : "false") << std::endl;
return convert.str();
}
}; // namespace optimization
}; // namespace mlpack
#endif
<commit_msg>Minor changes to ToString().<commit_after>/**
* @file sgd_impl.hpp
* @author Ryan Curtin
*
* Implementation of stochastic gradient descent.
*/
#ifndef __MLPACK_CORE_OPTIMIZERS_SGD_SGD_IMPL_HPP
#define __MLPACK_CORE_OPTIMIZERS_SGD_SGD_IMPL_HPP
// In case it hasn't been included yet.
#include "sgd.hpp"
namespace mlpack {
namespace optimization {
template<typename DecomposableFunctionType>
SGD<DecomposableFunctionType>::SGD(DecomposableFunctionType& function,
const double stepSize,
const size_t maxIterations,
const double tolerance,
const bool shuffle) :
function(function),
stepSize(stepSize),
maxIterations(maxIterations),
tolerance(tolerance),
shuffle(shuffle)
{ /* Nothing to do. */ }
//! Optimize the function (minimize).
template<typename DecomposableFunctionType>
double SGD<DecomposableFunctionType>::Optimize(arma::mat& iterate)
{
// Find the number of functions to use.
const size_t numFunctions = function.NumFunctions();
// This is used only if shuffle is true.
arma::vec visitationOrder;
if (shuffle)
visitationOrder = arma::shuffle(arma::linspace(0, (numFunctions - 1),
numFunctions));
// To keep track of where we are and how things are going.
size_t currentFunction = 0;
double overallObjective = 0;
double lastObjective = DBL_MAX;
// Calculate the first objective function.
for (size_t i = 0; i < numFunctions; ++i)
overallObjective += function.Evaluate(iterate, i);
// Now iterate!
arma::mat gradient(iterate.n_rows, iterate.n_cols);
for (size_t i = 1; i != maxIterations; ++i, ++currentFunction)
{
// Is this iteration the start of a sequence?
if ((currentFunction % numFunctions) == 0)
{
// Output current objective function.
Log::Info << "SGD: iteration " << i << ", objective " << overallObjective
<< "." << std::endl;
if (overallObjective != overallObjective)
{
Log::Warn << "SGD: converged to " << overallObjective << "; terminating"
<< " with failure. Try a smaller step size?" << std::endl;
return overallObjective;
}
if (std::abs(lastObjective - overallObjective) < tolerance)
{
Log::Info << "SGD: minimized within tolerance " << tolerance << "; "
<< "terminating optimization." << std::endl;
return overallObjective;
}
// Reset the counter variables.
lastObjective = overallObjective;
overallObjective = 0;
currentFunction = 0;
if (shuffle) // Determine order of visitation.
visitationOrder = arma::shuffle(visitationOrder);
}
// Evaluate the gradient for this iteration.
function.Gradient(iterate, currentFunction, gradient);
// And update the iterate.
iterate -= stepSize * gradient;
// Now add that to the overall objective function.
overallObjective += function.Evaluate(iterate, currentFunction);
}
Log::Info << "SGD: maximum iterations (" << maxIterations << ") reached; "
<< "terminating optimization." << std::endl;
return overallObjective;
}
// Convert the object to a string.
template<typename DecomposableFunctionType>
std::string SGD<DecomposableFunctionType>::ToString() const
{
std::ostringstream convert;
convert << "SGD [" << this << "]" << std::endl;
convert << " Function:" << std::endl;
convert << util::Indent(function.ToString(), 2);
convert << " Step size: " << stepSize << std::endl;
convert << " Maximum iterations: " << maxIterations << std::endl;
convert << " Tolerance: " << tolerance << std::endl;
convert << " Shuffle points: " << (shuffle ? "true" : "false") << std::endl;
return convert.str();
}
}; // namespace optimization
}; // namespace mlpack
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2011-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
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 Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <std_msgs/Float32MultiArray.h>
#include <opencv2/opencv.hpp>
#include <QTransform>
/**
* IMPORTANT :
* Parameter General/MirrorView must be false
* Parameter Homography/homographyComputed must be true
*/
void objectsDetectedCallback(const std_msgs::Float32MultiArray & msg)
{
printf("---\n");
if(msg.data.size())
{
for(unsigned int i=0; i<msg.data.size(); i+=12)
{
// get data
int id = (int)msg.data[i];
float objectWidth = msg.data[i+1];
float objectHeight = msg.data[i+2];
// Find corners Qt
QTransform qtHomography(msg.data[i+3], msg.data[i+4], msg.data[i+5],
msg.data[i+6], msg.data[i+7], msg.data[i+8],
msg.data[i+9], msg.data[i+10], msg.data[i+11]);
QPointF qtTopLeft = qtHomography.map(QPointF(0,0));
QPointF qtTopRight = qtHomography.map(QPointF(objectWidth,0));
QPointF qtBottomLeft = qtHomography.map(QPointF(0,objectHeight));
QPointF qtBottomRight = qtHomography.map(QPointF(objectWidth,objectHeight));
printf("Object %d detected, Qt corners at (%f,%f) (%f,%f) (%f,%f) (%f,%f)\n",
id,
qtTopLeft.x(), qtTopLeft.y(),
qtTopRight.x(), qtTopRight.y(),
qtBottomLeft.x(), qtBottomLeft.y(),
qtBottomRight.x(), qtBottomRight.y());
// Example with OpenCV
if(0)
{
// Find corners OpenCV
cv::Mat cvHomography(3, 3, CV_32F);
cvHomography.at<float>(0,0) = msg.data[i+3];
cvHomography.at<float>(1,0) = msg.data[i+4];
cvHomography.at<float>(2,0) = msg.data[i+5];
cvHomography.at<float>(0,1) = msg.data[i+6];
cvHomography.at<float>(1,1) = msg.data[i+7];
cvHomography.at<float>(2,1) = msg.data[i+8];
cvHomography.at<float>(0,2) = msg.data[i+9];
cvHomography.at<float>(1,2) = msg.data[i+10];
cvHomography.at<float>(2,2) = msg.data[i+11];
std::vector<cv::Point2f> inPts, outPts;
inPts.push_back(cv::Point2f(0,0));
inPts.push_back(cv::Point2f(objectWidth,0));
inPts.push_back(cv::Point2f(0,objectHeight));
inPts.push_back(cv::Point2f(objectWidth,objectHeight));
cv::perspectiveTransform(inPts, outPts, cvHomography);
printf("Object %d detected, CV corners at (%f,%f) (%f,%f) (%f,%f) (%f,%f)\n",
id,
outPts.at(0).x, outPts.at(0).y,
outPts.at(1).x, outPts.at(1).y,
outPts.at(2).x, outPts.at(2).y,
outPts.at(3).x, outPts.at(3).y);
}
}
}
else
{
printf("No objects detected.\n");
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "objects_detected");
ros::NodeHandle nh;
ros::Subscriber subs;
subs = nh.subscribe("objects", 1, objectsDetectedCallback);
ros::spin();
return 0;
}
<commit_msg>Added example drawing object rectangles on image (#48)<commit_after>/*
Copyright (c) 2011-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
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 Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <find_object_2d/ObjectsStamped.h>
#include <message_filters/subscriber.h>
#include <message_filters/time_synchronizer.h>
#include <image_transport/image_transport.h>
#include <image_transport/subscriber_filter.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>
#include <QTransform>
#include <QColor>
image_transport::Publisher imagePub;
/**
* IMPORTANT :
* Parameter General/MirrorView must be false
* Parameter Homography/homographyComputed must be true
*/
void objectsDetectedCallback(
const std_msgs::Float32MultiArrayConstPtr & msg)
{
printf("---\n");
const std::vector<float> & data = msg->data;
if(data.size())
{
for(unsigned int i=0; i<data.size(); i+=12)
{
// get data
int id = (int)data[i];
float objectWidth = data[i+1];
float objectHeight = data[i+2];
// Find corners Qt
QTransform qtHomography(data[i+3], data[i+4], data[i+5],
data[i+6], data[i+7], data[i+8],
data[i+9], data[i+10], data[i+11]);
QPointF qtTopLeft = qtHomography.map(QPointF(0,0));
QPointF qtTopRight = qtHomography.map(QPointF(objectWidth,0));
QPointF qtBottomLeft = qtHomography.map(QPointF(0,objectHeight));
QPointF qtBottomRight = qtHomography.map(QPointF(objectWidth,objectHeight));
printf("Object %d detected, Qt corners at (%f,%f) (%f,%f) (%f,%f) (%f,%f)\n",
id,
qtTopLeft.x(), qtTopLeft.y(),
qtTopRight.x(), qtTopRight.y(),
qtBottomLeft.x(), qtBottomLeft.y(),
qtBottomRight.x(), qtBottomRight.y());
}
}
else
{
printf("No objects detected.\n");
}
}
void imageObjectsDetectedCallback(
const sensor_msgs::ImageConstPtr & imageMsg,
const find_object_2d::ObjectsStampedConstPtr & objectsMsg)
{
if(imagePub.getNumSubscribers() > 0)
{
const std::vector<float> & data = objectsMsg->objects.data;
if(data.size())
{
for(unsigned int i=0; i<data.size(); i+=12)
{
// get data
int id = (int)data[i];
float objectWidth = data[i+1];
float objectHeight = data[i+2];
// Find corners OpenCV
cv::Mat cvHomography(3, 3, CV_32F);
cvHomography.at<float>(0,0) = data[i+3];
cvHomography.at<float>(1,0) = data[i+4];
cvHomography.at<float>(2,0) = data[i+5];
cvHomography.at<float>(0,1) = data[i+6];
cvHomography.at<float>(1,1) = data[i+7];
cvHomography.at<float>(2,1) = data[i+8];
cvHomography.at<float>(0,2) = data[i+9];
cvHomography.at<float>(1,2) = data[i+10];
cvHomography.at<float>(2,2) = data[i+11];
std::vector<cv::Point2f> inPts, outPts;
inPts.push_back(cv::Point2f(0,0));
inPts.push_back(cv::Point2f(objectWidth,0));
inPts.push_back(cv::Point2f(objectWidth,objectHeight));
inPts.push_back(cv::Point2f(0,objectHeight));
inPts.push_back(cv::Point2f(objectWidth/2,objectHeight/2));
cv::perspectiveTransform(inPts, outPts, cvHomography);
cv_bridge::CvImageConstPtr imageDepthPtr = cv_bridge::toCvShare(imageMsg);
cv_bridge::CvImage img;
img = *imageDepthPtr;
std::vector<cv::Point2i> outPtsInt;
outPtsInt.push_back(outPts[0]);
outPtsInt.push_back(outPts[1]);
outPtsInt.push_back(outPts[2]);
outPtsInt.push_back(outPts[3]);
QColor color(QColor((Qt::GlobalColor)((id % 10 + 7)==Qt::yellow?Qt::darkYellow:(id % 10 + 7))));
cv::Scalar cvColor(color.red(), color.green(), color.blue());
cv::polylines(img.image, outPtsInt, true, cvColor, 3);
cv::Point2i center = outPts[4];
cv::putText(img.image, QString("(%1, %2)").arg(center.x).arg(center.y).toStdString(), center, cv::FONT_HERSHEY_SIMPLEX, 0.6, cvColor, 2);
cv::circle(img.image, center, 1, cvColor, 3);
imagePub.publish(img.toImageMsg());
}
}
}
}
typedef message_filters::sync_policies::ExactTime<sensor_msgs::Image, find_object_2d::ObjectsStamped> MyExactSyncPolicy;
int main(int argc, char** argv)
{
ros::init(argc, argv, "objects_detected");
ros::NodeHandle nh;
image_transport::ImageTransport it(nh);
// Simple subscriber
ros::Subscriber sub;
sub = nh.subscribe("objects", 1, objectsDetectedCallback);
// Synchronized image + objects example
image_transport::SubscriberFilter imageSub;
imageSub.subscribe(it, nh.resolveName("image"), 1);
message_filters::Subscriber<find_object_2d::ObjectsStamped> objectsSub;
objectsSub.subscribe(nh, "objectsStamped", 1);
message_filters::Synchronizer<MyExactSyncPolicy> exactSync(MyExactSyncPolicy(10), imageSub, objectsSub);
exactSync.registerCallback(boost::bind(&imageObjectsDetectedCallback, _1, _2));
imagePub = it.advertise("image_with_objects", 1);
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
*
* Contact: Bumjin Im <bj.im@samsung.com>
*
* 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
*/
/*
* @file password-manager.cpp
* @author Zbigniew Jasinski (z.jasinski@samsung.com)
* @author Lukasz Kostyra (l.kostyra@partner.samsung.com)
* @version 1.0
* @brief Implementation of password management functions
*/
#include <password-manager.h>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <limits.h>
#include <dpl/log/log.h>
#include <protocols.h>
#include <security-server.h>
namespace {
bool calculateExpiredTime(unsigned int receivedDays, unsigned int &validSecs)
{
validSecs = SecurityServer::PASSWORD_INFINITE_EXPIRATION_TIME;
//when receivedDays means infinite expiration, return default validSecs value.
if(receivedDays == SecurityServer::PASSWORD_INFINITE_EXPIRATION_DAYS)
return true;
time_t curTime = time(NULL);
if (receivedDays > ((UINT_MAX - curTime) / 86400)) {
LogError("Incorrect input param.");
return false;
} else {
validSecs = (curTime + (receivedDays * 86400));
return true;
}
}
} //namespace
namespace SecurityServer
{
int PasswordManager::isPwdValid(unsigned int ¤tAttempt, unsigned int &maxAttempt,
unsigned int &expirationTime) const
{
if (m_pwdFile.isIgnorePeriod()) {
LogError("Retry timeout occured.");
return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
}
if (!m_pwdFile.isPasswordActive()) {
LogError("Current password not active.");
return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
} else {
currentAttempt = m_pwdFile.getAttempt();
maxAttempt = m_pwdFile.getMaxAttempt();
expirationTime = m_pwdFile.getExpireTimeLeft();
return SECURITY_SERVER_API_ERROR_PASSWORD_EXIST;
}
return SECURITY_SERVER_API_SUCCESS;
}
int PasswordManager::checkPassword(const std::string &challenge, unsigned int ¤tAttempt,
unsigned int &maxAttempt, unsigned int &expirationTime)
{
LogSecureDebug("Inside checkPassword function.");
if (m_pwdFile.isIgnorePeriod()) {
LogError("Retry timeout occurred.");
return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
}
if (!m_pwdFile.isPasswordActive()) {
LogError("Password not active.");
return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
}
m_pwdFile.incrementAttempt();
m_pwdFile.writeAttemptToFile();
currentAttempt = m_pwdFile.getAttempt();
maxAttempt = m_pwdFile.getMaxAttempt();
expirationTime = m_pwdFile.getExpireTimeLeft();
if (m_pwdFile.checkIfAttemptsExceeded()) {
LogError("Too many tries.");
return SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
}
if (!m_pwdFile.checkPassword(challenge)) {
LogError("Wrong password.");
return SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH;
}
if (m_pwdFile.checkExpiration()) {
LogError("Password expired.");
return SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED;
}
m_pwdFile.resetAttempt();
m_pwdFile.writeAttemptToFile();
return SECURITY_SERVER_API_SUCCESS;
}
int PasswordManager::setPassword(const std::string ¤tPassword,
const std::string &newPassword,
const unsigned int receivedAttempts,
const unsigned int receivedDays)
{
LogSecureDebug("Curpwd = " << currentPassword << ", newpwd = " << newPassword <<
", recatt = " << receivedAttempts << ", recdays = " << receivedDays);
unsigned int valid_secs = 0;
//check retry timer
if (m_pwdFile.isIgnorePeriod()) {
LogError("Retry timeout occured.");
return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
}
//check if passwords are correct
if (currentPassword.size() > MAX_PASSWORD_LEN) {
LogError("Current password length failed.");
return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
}
if (newPassword.size() > MAX_PASSWORD_LEN) {
LogError("New password length failed.");
return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
}
//check delivered currentPassword
//when m_passwordActive flag is true, currentPassword shouldn't be empty
if (currentPassword.empty() && m_pwdFile.isPasswordActive()) {
LogError("Password is already set. Max history: " << m_pwdFile.getMaxHistorySize());
return SECURITY_SERVER_API_ERROR_PASSWORD_EXIST;
}
//increment attempt count before checking it against max attempt count
m_pwdFile.incrementAttempt();
m_pwdFile.writeAttemptToFile();
// check attempt
if (m_pwdFile.checkIfAttemptsExceeded()) {
LogError("Too many attempts.");
return SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
}
//check current password, however only when we don't send empty string as current.
if(!currentPassword.empty()) {
if(!m_pwdFile.checkPassword(currentPassword)) {
LogError("Wrong password.");
return SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH;
}
}
//check if password expired
if (m_pwdFile.checkExpiration()) {
LogError("Password expired.");
return SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED;
}
//check history, however only if history is active
if (m_pwdFile.isPasswordActive() && m_pwdFile.isHistoryActive()) {
if (m_pwdFile.isPasswordReused(newPassword)) {
LogError("Password reused.");
return SECURITY_SERVER_API_ERROR_PASSWORD_REUSED;
}
}
if(!calculateExpiredTime(receivedDays, valid_secs)) {
LogError("Received expiration time incorrect.");
return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
}
//setting password
m_pwdFile.setPassword(newPassword);
m_pwdFile.activatePassword();
m_pwdFile.setMaxAttempt(receivedAttempts);
m_pwdFile.setExpireTime(valid_secs);
m_pwdFile.writeMemoryToFile();
m_pwdFile.resetAttempt();
m_pwdFile.writeAttemptToFile();
return SECURITY_SERVER_API_SUCCESS;
}
int PasswordManager::setPasswordValidity(const unsigned int receivedDays)
{
unsigned int valid_secs = 0;
LogSecureDebug("received_days: " << receivedDays);
if (!m_pwdFile.isPasswordActive()) {
LogError("Current password is not active.");
return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
}
if(!calculateExpiredTime(receivedDays, valid_secs))
return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
m_pwdFile.setExpireTime(valid_secs);
m_pwdFile.writeMemoryToFile();
return SECURITY_SERVER_API_SUCCESS;
}
int PasswordManager::resetPassword(const std::string &newPassword,
const unsigned int receivedAttempts,
const unsigned int receivedDays)
{
unsigned int valid_secs = 0;
if (m_pwdFile.isIgnorePeriod()) {
LogError("Retry timeout occured.");
return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
}
if(!calculateExpiredTime(receivedDays, valid_secs))
return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
m_pwdFile.setPassword(newPassword);
m_pwdFile.activatePassword();
m_pwdFile.setMaxAttempt(receivedAttempts);
m_pwdFile.setExpireTime(valid_secs);
m_pwdFile.writeMemoryToFile();
m_pwdFile.resetAttempt();
m_pwdFile.writeAttemptToFile();
return SECURITY_SERVER_API_SUCCESS;
}
int PasswordManager::setPasswordHistory(const unsigned int history)
{
if(history > MAX_PASSWORD_HISTORY) {
LogError("Incorrect input param.");
return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
}
// check retry time
if (m_pwdFile.isIgnorePeriod()) {
LogError("Retry timeout occurred.");
return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
}
m_pwdFile.setMaxHistorySize(history);
m_pwdFile.writeMemoryToFile();
return SECURITY_SERVER_API_SUCCESS;
}
int PasswordManager::setPasswordMaxChallenge(const unsigned int maxChallenge)
{
// check if there is password
if (!m_pwdFile.isPasswordActive()) {
LogError("Password not active.");
return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
}
m_pwdFile.setMaxAttempt(maxChallenge);
m_pwdFile.writeMemoryToFile();
m_pwdFile.resetAttempt();
m_pwdFile.writeAttemptToFile();
return SECURITY_SERVER_API_SUCCESS;
}
} //namespace SecurityServer
<commit_msg>Remove retry timeout check<commit_after>/*
* Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
*
* Contact: Bumjin Im <bj.im@samsung.com>
*
* 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
*/
/*
* @file password-manager.cpp
* @author Zbigniew Jasinski (z.jasinski@samsung.com)
* @author Lukasz Kostyra (l.kostyra@partner.samsung.com)
* @version 1.0
* @brief Implementation of password management functions
*/
#include <password-manager.h>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <limits.h>
#include <dpl/log/log.h>
#include <protocols.h>
#include <security-server.h>
namespace {
bool calculateExpiredTime(unsigned int receivedDays, unsigned int &validSecs)
{
validSecs = SecurityServer::PASSWORD_INFINITE_EXPIRATION_TIME;
//when receivedDays means infinite expiration, return default validSecs value.
if(receivedDays == SecurityServer::PASSWORD_INFINITE_EXPIRATION_DAYS)
return true;
time_t curTime = time(NULL);
if (receivedDays > ((UINT_MAX - curTime) / 86400)) {
LogError("Incorrect input param.");
return false;
} else {
validSecs = (curTime + (receivedDays * 86400));
return true;
}
}
} //namespace
namespace SecurityServer
{
int PasswordManager::isPwdValid(unsigned int ¤tAttempt, unsigned int &maxAttempt,
unsigned int &expirationTime) const
{
if (!m_pwdFile.isPasswordActive()) {
LogError("Current password not active.");
return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
} else {
currentAttempt = m_pwdFile.getAttempt();
maxAttempt = m_pwdFile.getMaxAttempt();
expirationTime = m_pwdFile.getExpireTimeLeft();
return SECURITY_SERVER_API_ERROR_PASSWORD_EXIST;
}
return SECURITY_SERVER_API_SUCCESS;
}
int PasswordManager::checkPassword(const std::string &challenge, unsigned int ¤tAttempt,
unsigned int &maxAttempt, unsigned int &expirationTime)
{
LogSecureDebug("Inside checkPassword function.");
if (m_pwdFile.isIgnorePeriod()) {
LogError("Retry timeout occurred.");
return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
}
if (!m_pwdFile.isPasswordActive()) {
LogError("Password not active.");
return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
}
m_pwdFile.incrementAttempt();
m_pwdFile.writeAttemptToFile();
currentAttempt = m_pwdFile.getAttempt();
maxAttempt = m_pwdFile.getMaxAttempt();
expirationTime = m_pwdFile.getExpireTimeLeft();
if (m_pwdFile.checkIfAttemptsExceeded()) {
LogError("Too many tries.");
return SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
}
if (!m_pwdFile.checkPassword(challenge)) {
LogError("Wrong password.");
return SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH;
}
if (m_pwdFile.checkExpiration()) {
LogError("Password expired.");
return SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED;
}
m_pwdFile.resetAttempt();
m_pwdFile.writeAttemptToFile();
return SECURITY_SERVER_API_SUCCESS;
}
int PasswordManager::setPassword(const std::string ¤tPassword,
const std::string &newPassword,
const unsigned int receivedAttempts,
const unsigned int receivedDays)
{
LogSecureDebug("Curpwd = " << currentPassword << ", newpwd = " << newPassword <<
", recatt = " << receivedAttempts << ", recdays = " << receivedDays);
unsigned int valid_secs = 0;
if (m_pwdFile.isIgnorePeriod()) {
LogError("Retry timeout occured.");
return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
}
//check if passwords are correct
if (currentPassword.size() > MAX_PASSWORD_LEN) {
LogError("Current password length failed.");
return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
}
if (newPassword.size() > MAX_PASSWORD_LEN) {
LogError("New password length failed.");
return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
}
//check delivered currentPassword
//when m_passwordActive flag is true, currentPassword shouldn't be empty
if (currentPassword.empty() && m_pwdFile.isPasswordActive()) {
LogError("Password is already set. Max history: " << m_pwdFile.getMaxHistorySize());
return SECURITY_SERVER_API_ERROR_PASSWORD_EXIST;
}
//increment attempt count before checking it against max attempt count
m_pwdFile.incrementAttempt();
m_pwdFile.writeAttemptToFile();
// check attempt
if (m_pwdFile.checkIfAttemptsExceeded()) {
LogError("Too many attempts.");
return SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
}
//check current password, however only when we don't send empty string as current.
if(!currentPassword.empty()) {
if(!m_pwdFile.checkPassword(currentPassword)) {
LogError("Wrong password.");
return SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH;
}
}
//check if password expired
if (m_pwdFile.checkExpiration()) {
LogError("Password expired.");
return SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED;
}
//check history, however only if history is active
if (m_pwdFile.isPasswordActive() && m_pwdFile.isHistoryActive()) {
if (m_pwdFile.isPasswordReused(newPassword)) {
LogError("Password reused.");
return SECURITY_SERVER_API_ERROR_PASSWORD_REUSED;
}
}
if(!calculateExpiredTime(receivedDays, valid_secs)) {
LogError("Received expiration time incorrect.");
return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
}
//setting password
m_pwdFile.setPassword(newPassword);
m_pwdFile.activatePassword();
m_pwdFile.setMaxAttempt(receivedAttempts);
m_pwdFile.setExpireTime(valid_secs);
m_pwdFile.writeMemoryToFile();
m_pwdFile.resetAttempt();
m_pwdFile.writeAttemptToFile();
return SECURITY_SERVER_API_SUCCESS;
}
int PasswordManager::setPasswordValidity(const unsigned int receivedDays)
{
unsigned int valid_secs = 0;
LogSecureDebug("received_days: " << receivedDays);
if (!m_pwdFile.isPasswordActive()) {
LogError("Current password is not active.");
return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
}
if(!calculateExpiredTime(receivedDays, valid_secs))
return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
m_pwdFile.setExpireTime(valid_secs);
m_pwdFile.writeMemoryToFile();
return SECURITY_SERVER_API_SUCCESS;
}
int PasswordManager::resetPassword(const std::string &newPassword,
const unsigned int receivedAttempts,
const unsigned int receivedDays)
{
unsigned int valid_secs = 0;
if(!calculateExpiredTime(receivedDays, valid_secs))
return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
m_pwdFile.setPassword(newPassword);
m_pwdFile.activatePassword();
m_pwdFile.setMaxAttempt(receivedAttempts);
m_pwdFile.setExpireTime(valid_secs);
m_pwdFile.writeMemoryToFile();
m_pwdFile.resetAttempt();
m_pwdFile.writeAttemptToFile();
return SECURITY_SERVER_API_SUCCESS;
}
int PasswordManager::setPasswordHistory(const unsigned int history)
{
if(history > MAX_PASSWORD_HISTORY) {
LogError("Incorrect input param.");
return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
}
m_pwdFile.setMaxHistorySize(history);
m_pwdFile.writeMemoryToFile();
return SECURITY_SERVER_API_SUCCESS;
}
int PasswordManager::setPasswordMaxChallenge(const unsigned int maxChallenge)
{
// check if there is password
if (!m_pwdFile.isPasswordActive()) {
LogError("Password not active.");
return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
}
m_pwdFile.setMaxAttempt(maxChallenge);
m_pwdFile.writeMemoryToFile();
m_pwdFile.resetAttempt();
m_pwdFile.writeAttemptToFile();
return SECURITY_SERVER_API_SUCCESS;
}
} //namespace SecurityServer
<|endoftext|> |
<commit_before>//
// android_sound.cc
// SharkSound
//
// Created by Jon Sharkey on 2013-06-25.
// Copyright 2013 Sharkable. All rights reserved.
//
#include "sharksound/android/android_sound.h"
#include <android/log.h>
#include "sharksound/android/android_sound_instance.h"
using namespace SharkSound;
AndroidSound::AndroidSound(SoundController *sound_controller)
: Sound(sound_controller),
loop_instance_(NULL),
loop_volume_(1.f),
sl_engine_itf_(NULL) {
}
AndroidSound::~AndroidSound() {
for (auto i = sound_instances_.begin(); i != sound_instances_.end(); i++) {
delete *i;
}
}
bool AndroidSound::Init(AAssetManager *asset_manager, SLEngineItf sl_engine_itf,
SLDataSink sl_data_sink, std::string filename) {
sl_engine_itf_ = sl_engine_itf;
sl_data_sink_ = sl_data_sink;
if (NULL == asset_manager) {
__android_log_print(ANDROID_LOG_ERROR, "SharkSound", "Error loading %s: No AssetManager.",
filename.c_str());
return false;
}
AAsset* asset = AAssetManager_open(asset_manager, filename.c_str(), AASSET_MODE_UNKNOWN);
// the asset might not be found
if (NULL == asset) {
__android_log_print(ANDROID_LOG_ERROR, "SharkSound", "Error loading %s: File not found.",
filename.c_str());
return false;
}
// open asset as file descriptor
off_t start, length;
int fd = AAsset_openFileDescriptor(asset, &start, &length);
if (0 >= fd) {
__android_log_print(ANDROID_LOG_ERROR, "SharkSound", "Error loading file %s: File not found.",
filename.c_str());
}
AAsset_close(asset);
// configure audio source
sl_data_locator_ = {SL_DATALOCATOR_ANDROIDFD, fd, start, length};
sl_format_mime_ = {SL_DATAFORMAT_MIME, NULL, SL_CONTAINERTYPE_UNSPECIFIED};
sl_audio_source_ = {&sl_data_locator_, &sl_format_mime_};
AndroidSoundInstance *instance = CreateNewInstance();
if (instance) {
sound_instances_.push_back(instance);
} else {
__android_log_print(ANDROID_LOG_ERROR, "SharkSound",
"Error creating new sound instance for %s.", filename.c_str());
return false;
}
return true;
}
#pragma mark - Sound
bool AndroidSound::Play(float volume, float position) {
if (!on_) {
return false;
}
AndroidSoundInstance *instance = NULL;
for (auto i = sound_instances_.begin(); i != sound_instances_.end(); i++) {
if (!(*i)->is_busy()) {
instance = *i;
break;
}
}
if (instance == NULL) {
instance = CreateNewInstance();
if (instance) {
sound_instances_.push_back(instance);
}
}
if (instance) {
instance->Play(volume * global_volume_, position);
return true;
}
return false;
}
bool AndroidSound::PlayLoop() {
if (!on_) {
return false;
}
if (!loop_instance_) {
loop_instance_ = CreateNewInstance();
loop_instance_->SetVolume(loop_volume_);
}
if (!loop_instance_) {
return false;
}
loop_instance_->PlayLoop();
}
void AndroidSound::StopLoop() {
if (loop_instance_) {
loop_instance_->Stop();
}
}
void AndroidSound::RewindLoop() {
if (loop_instance_) {
loop_instance_->Rewind();
}
}
void AndroidSound::SetLoopVolume(float volume) {
loop_volume_ = volume;
if (loop_instance_) {
loop_instance_->SetVolume(volume * global_volume_);
}
}
float AndroidSound::LoopVolume() {
return loop_volume_;
}
void AndroidSound::SetLoopPosition(float position) {
if (loop_instance_) {
loop_instance_->SetPosition(position);
}
}
bool AndroidSound::IsLoopPlaying() {
return (loop_instance_ && loop_instance_->is_busy());
}
#pragma mark - private
AndroidSoundInstance * AndroidSound::CreateNewInstance() {
AndroidSoundInstance *instance = new AndroidSoundInstance();
if (instance->Init(sl_engine_itf_, sl_audio_source_, sl_data_sink_)) {
return instance;
}
delete instance;
return NULL;
}
<commit_msg>[Android] Made error message more accurate.<commit_after>//
// android_sound.cc
// SharkSound
//
// Created by Jon Sharkey on 2013-06-25.
// Copyright 2013 Sharkable. All rights reserved.
//
#include "sharksound/android/android_sound.h"
#include <android/log.h>
#include "sharksound/android/android_sound_instance.h"
using namespace SharkSound;
AndroidSound::AndroidSound(SoundController *sound_controller)
: Sound(sound_controller),
loop_instance_(NULL),
loop_volume_(1.f),
sl_engine_itf_(NULL) {
}
AndroidSound::~AndroidSound() {
for (auto i = sound_instances_.begin(); i != sound_instances_.end(); i++) {
delete *i;
}
}
bool AndroidSound::Init(AAssetManager *asset_manager, SLEngineItf sl_engine_itf,
SLDataSink sl_data_sink, std::string filename) {
sl_engine_itf_ = sl_engine_itf;
sl_data_sink_ = sl_data_sink;
if (NULL == asset_manager) {
__android_log_print(ANDROID_LOG_ERROR, "SharkSound", "Error loading %s: No AssetManager.",
filename.c_str());
return false;
}
AAsset* asset = AAssetManager_open(asset_manager, filename.c_str(), AASSET_MODE_UNKNOWN);
// the asset might not be found
if (NULL == asset) {
__android_log_print(ANDROID_LOG_ERROR, "SharkSound",
"Error loading %s: File not found or bad format.", filename.c_str());
return false;
}
// open asset as file descriptor
off_t start, length;
int fd = AAsset_openFileDescriptor(asset, &start, &length);
if (0 >= fd) {
__android_log_print(ANDROID_LOG_ERROR, "SharkSound", "Error loading file %s: File not found.",
filename.c_str());
}
AAsset_close(asset);
// configure audio source
sl_data_locator_ = {SL_DATALOCATOR_ANDROIDFD, fd, start, length};
sl_format_mime_ = {SL_DATAFORMAT_MIME, NULL, SL_CONTAINERTYPE_UNSPECIFIED};
sl_audio_source_ = {&sl_data_locator_, &sl_format_mime_};
AndroidSoundInstance *instance = CreateNewInstance();
if (instance) {
sound_instances_.push_back(instance);
} else {
__android_log_print(ANDROID_LOG_ERROR, "SharkSound",
"Error creating new sound instance for %s.", filename.c_str());
return false;
}
return true;
}
#pragma mark - Sound
bool AndroidSound::Play(float volume, float position) {
if (!on_) {
return false;
}
AndroidSoundInstance *instance = NULL;
for (auto i = sound_instances_.begin(); i != sound_instances_.end(); i++) {
if (!(*i)->is_busy()) {
instance = *i;
break;
}
}
if (instance == NULL) {
instance = CreateNewInstance();
if (instance) {
sound_instances_.push_back(instance);
}
}
if (instance) {
instance->Play(volume * global_volume_, position);
return true;
}
return false;
}
bool AndroidSound::PlayLoop() {
if (!on_) {
return false;
}
if (!loop_instance_) {
loop_instance_ = CreateNewInstance();
loop_instance_->SetVolume(loop_volume_);
}
if (!loop_instance_) {
return false;
}
loop_instance_->PlayLoop();
}
void AndroidSound::StopLoop() {
if (loop_instance_) {
loop_instance_->Stop();
}
}
void AndroidSound::RewindLoop() {
if (loop_instance_) {
loop_instance_->Rewind();
}
}
void AndroidSound::SetLoopVolume(float volume) {
loop_volume_ = volume;
if (loop_instance_) {
loop_instance_->SetVolume(volume * global_volume_);
}
}
float AndroidSound::LoopVolume() {
return loop_volume_;
}
void AndroidSound::SetLoopPosition(float position) {
if (loop_instance_) {
loop_instance_->SetPosition(position);
}
}
bool AndroidSound::IsLoopPlaying() {
return (loop_instance_ && loop_instance_->is_busy());
}
#pragma mark - private
AndroidSoundInstance * AndroidSound::CreateNewInstance() {
AndroidSoundInstance *instance = new AndroidSoundInstance();
if (instance->Init(sl_engine_itf_, sl_audio_source_, sl_data_sink_)) {
return instance;
}
delete instance;
return NULL;
}
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2014 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "FileHelper.h"
#include "Exception.h"
#ifndef _WIN32
#include <libgen.h>
#else
#include <direct.h>
#endif
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <vector>
#include <fstream>
using namespace std;
namespace avg {
string getPath(const string& sFilename)
{
if (sFilename.length() > 0 && sFilename.at(sFilename.length()-1) == '/') {
return sFilename;
}
#ifdef _WIN32
int pos = int(sFilename.find_last_of("\\/"));
string dirName;
if (pos >= 0) {
dirName = sFilename.substr(0, pos+1);
} else {
dirName = sFilename;
}
#else
char * pszBuffer = strdup(sFilename.c_str());
string dirName(dirname(pszBuffer));
free(pszBuffer);
dirName += "/";
#endif
return dirName;
}
string getFilenamePart(const string& sFilename)
{
if (sFilename.find_last_of("\\/") == 0) {
return sFilename;
}
#ifdef _WIN32
int pos = int(sFilename.find_last_of("\\/"));
string BaseName(sFilename.substr(pos+1));
#else
char * pszBuffer = strdup(sFilename.c_str());
string BaseName(basename(pszBuffer));
free(pszBuffer);
#endif
return BaseName;
}
string getExtension(const string& sFilename)
{
int pos = int(sFilename.find_last_of("."));
if (pos == 0) {
return "";
} else {
return sFilename.substr(pos+1);
}
}
string getCWD()
{
char szBuf[1024];
#ifdef _WIN32
char * pBuf = _getcwd(szBuf, 1024);
#else
char * pBuf = getcwd(szBuf, 1024);
#endif
return string(pBuf)+"/";
}
bool isAbsPath(const std::string& path)
{
#ifdef _WIN32
return ((path.length() != 0) && path[1] == ':') || path[0] == '\\' || path[0] == '/';
#else
return path[0] == '/';
#endif
}
bool fileExists(const string& sFilename)
{
struct stat myStat;
return stat(sFilename.c_str(), &myStat) != -1;
}
void readWholeFile(const string& sFilename, string& sContent)
{
ifstream file(sFilename.c_str());
if (!file) {
throw Exception(AVG_ERR_FILEIO, "Opening "+sFilename+
" for reading failed.");
}
vector<char> buffer(65536);
sContent.resize(0);
while (file) {
file.read(&(*buffer.begin()), (streamsize)(buffer.size()));
sContent.append(&(*buffer.begin()), (unsigned)file.gcount());
}
if (!file.eof() || file.bad()) {
throw Exception(AVG_ERR_FILEIO, "Reading "+sFilename+
" failed.");
}
}
void writeWholeFile(const string& sFilename, const string& sContent)
{
ofstream outFile(sFilename.c_str());
if (!outFile) {
throw Exception(AVG_ERR_FILEIO, "Opening "+sFilename+
" for writing failed.");
}
outFile << sContent;
}
void copyFile(const string& sSourceFile, const string& sDestFile)
{
string sData;
readWholeFile(sSourceFile, sData);
writeWholeFile(sDestFile, sData);
}
}
<commit_msg>Linux build fix.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2014 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "FileHelper.h"
#include "Exception.h"
#ifndef _WIN32
#include <libgen.h>
#else
#include <direct.h>
#endif
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <fstream>
using namespace std;
namespace avg {
string getPath(const string& sFilename)
{
if (sFilename.length() > 0 && sFilename.at(sFilename.length()-1) == '/') {
return sFilename;
}
#ifdef _WIN32
int pos = int(sFilename.find_last_of("\\/"));
string dirName;
if (pos >= 0) {
dirName = sFilename.substr(0, pos+1);
} else {
dirName = sFilename;
}
#else
char * pszBuffer = strdup(sFilename.c_str());
string dirName(dirname(pszBuffer));
free(pszBuffer);
dirName += "/";
#endif
return dirName;
}
string getFilenamePart(const string& sFilename)
{
if (sFilename.find_last_of("\\/") == 0) {
return sFilename;
}
#ifdef _WIN32
int pos = int(sFilename.find_last_of("\\/"));
string BaseName(sFilename.substr(pos+1));
#else
char * pszBuffer = strdup(sFilename.c_str());
string BaseName(basename(pszBuffer));
free(pszBuffer);
#endif
return BaseName;
}
string getExtension(const string& sFilename)
{
int pos = int(sFilename.find_last_of("."));
if (pos == 0) {
return "";
} else {
return sFilename.substr(pos+1);
}
}
string getCWD()
{
char szBuf[1024];
#ifdef _WIN32
char * pBuf = _getcwd(szBuf, 1024);
#else
char * pBuf = getcwd(szBuf, 1024);
#endif
return string(pBuf)+"/";
}
bool isAbsPath(const std::string& path)
{
#ifdef _WIN32
return ((path.length() != 0) && path[1] == ':') || path[0] == '\\' || path[0] == '/';
#else
return path[0] == '/';
#endif
}
bool fileExists(const string& sFilename)
{
struct stat myStat;
return stat(sFilename.c_str(), &myStat) != -1;
}
void readWholeFile(const string& sFilename, string& sContent)
{
ifstream file(sFilename.c_str());
if (!file) {
throw Exception(AVG_ERR_FILEIO, "Opening "+sFilename+
" for reading failed.");
}
vector<char> buffer(65536);
sContent.resize(0);
while (file) {
file.read(&(*buffer.begin()), (streamsize)(buffer.size()));
sContent.append(&(*buffer.begin()), (unsigned)file.gcount());
}
if (!file.eof() || file.bad()) {
throw Exception(AVG_ERR_FILEIO, "Reading "+sFilename+
" failed.");
}
}
void writeWholeFile(const string& sFilename, const string& sContent)
{
ofstream outFile(sFilename.c_str());
if (!outFile) {
throw Exception(AVG_ERR_FILEIO, "Opening "+sFilename+
" for writing failed.");
}
outFile << sContent;
}
void copyFile(const string& sSourceFile, const string& sDestFile)
{
string sData;
readWholeFile(sSourceFile, sData);
writeWholeFile(sDestFile, sData);
}
}
<|endoftext|> |
<commit_before>#include <node.h>
#include <node_buffer.h>
#include <v8.h>
//Includes from phoenixLib iOS HAL
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <AudioToolbox/AudioToolbox.h>
#include <CoreFoundation/CoreFoundation.h>
#include "CAHostTimeBase.h"
#include <pthread.h>
#include <sys/resource.h>
#define FRAME_SIZE 1408
#define NUMBER_OF_BUFFERS 100
#define BUFFER_SIZE FRAME_SIZE * 4
//using namespace v8;
using namespace node;
namespace nodeairtunes {
struct coreAudioObjects {
AudioQueueRef audioQueue;
unsigned int fillBufferIndex; // the index of the audioQueueBuffer that is being filled
size_t bytesFilled; // how many bytes have been filled
AudioQueueBufferRef audioQueueBuffer[NUMBER_OF_BUFFERS]; // audio queue buffers
bool inuse[NUMBER_OF_BUFFERS]; // flags to indicate that a buffer is still in use
bool isPlaying;
unsigned int buffersUsed;
OSStatus err;
pthread_mutex_t queueBuffersMutex; // a mutex to protect the inuse flags
pthread_cond_t queueBufferReadyCondition; // a condition varable for handling the inuse flags
};
// This will free the AudioQueue when the wraping JS object is released by the GC
void coreAudio_weak_callback(v8::Persistent<v8::Value> wrapper, void *arg) {
v8::HandleScope scope;
struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) arg;
AudioQueueDispose(coreAudio->audioQueue, true);
wrapper.Dispose();
}
void OnAudioQueueBufferConsumed(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) {
struct coreAudioObjects* coreAudio;
coreAudio = (struct coreAudioObjects*) inUserData;
int bufIndex = -1;
for (unsigned int i = 0; i < NUMBER_OF_BUFFERS; i++) {
if (inBuffer == coreAudio->audioQueueBuffer[i]) {
bufIndex = i;
break;
}
}
if (bufIndex == -1) {
pthread_mutex_lock(&(coreAudio->queueBuffersMutex));
pthread_cond_signal(&(coreAudio->queueBufferReadyCondition));
pthread_mutex_unlock(&(coreAudio->queueBuffersMutex));
//DEBUG_AUDIOMANAGER_ERROR("Buffer mismatch !");
return;
}
// signal waiting thread that the buffer is free.
pthread_mutex_lock(&(coreAudio->queueBuffersMutex));
coreAudio->inuse[bufIndex] = false;
coreAudio->buffersUsed--;
pthread_cond_signal(&(coreAudio->queueBufferReadyCondition));
pthread_mutex_unlock(&(coreAudio->queueBuffersMutex));
}
static void enqueueBuffer(struct coreAudioObjects *coreAudio) {
OSStatus err = 0;
// enqueue buffer
pthread_mutex_lock(&(coreAudio->queueBuffersMutex));
AudioQueueBufferRef fillBuf = coreAudio->audioQueueBuffer[coreAudio->fillBufferIndex];
fillBuf->mAudioDataByteSize = coreAudio->bytesFilled;
err = AudioQueueEnqueueBuffer(coreAudio->audioQueue, fillBuf, 0, NULL);
if (err) {
//DEBUG_AUDIOMANAGER_ERROR("enqueue failed !!!!! %d", coreAudio->fillBufferIndex);
coreAudio->bytesFilled = 0;
pthread_mutex_unlock(&(coreAudio->queueBuffersMutex));
return;
}
coreAudio->inuse[coreAudio->fillBufferIndex] = true; // set in use flag
coreAudio->buffersUsed++;
// go to next buffer
if (++(coreAudio->fillBufferIndex) >= NUMBER_OF_BUFFERS) coreAudio->fillBufferIndex = 0;
coreAudio->bytesFilled = 0; // reset bytes filled
// wait until next buffer is not in use
while (coreAudio->inuse[coreAudio->fillBufferIndex]) {
pthread_cond_wait(&(coreAudio->queueBufferReadyCondition), &(coreAudio->queueBuffersMutex));
}
pthread_mutex_unlock(&(coreAudio->queueBuffersMutex));
}
v8::Handle<v8::Value> NewCoreAudio(const v8::Arguments& args) {
v8::HandleScope scope;
struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) malloc(sizeof (*coreAudio));
v8::Persistent<v8::ObjectTemplate> coreAudioClass = v8::Persistent<v8::ObjectTemplate>::New(v8::ObjectTemplate::New());
coreAudioClass->SetInternalFieldCount(1);
v8::Persistent<v8::Object> o = v8::Persistent<v8::Object>::New(coreAudioClass->NewInstance());
o->SetPointerInInternalField(0, coreAudio);
o.MakeWeak(coreAudio, coreAudio_weak_callback);
coreAudio->isPlaying = false;
coreAudio->buffersUsed = 0;
coreAudio->bytesFilled = 0;
coreAudio->fillBufferIndex = 0;
// initialize a mutex and condition so that we can block on buffers in use.
pthread_mutex_init(&(coreAudio->queueBuffersMutex), NULL);
pthread_cond_init(&(coreAudio->queueBufferReadyCondition), NULL);
AudioStreamBasicDescription LFormat;
OSStatus LRet;
LFormat.mSampleRate = 44100;
LFormat.mFormatID = kAudioFormatLinearPCM;
LFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger; // signed int
LFormat.mFramesPerPacket = 1; // for uncompressed audio
LFormat.mBytesPerFrame = 4; //AChannels * 2; // interleaved pcm datas (16bits per chan)
LFormat.mBytesPerPacket = 4; // for pcm: a packet contains a single frame
LFormat.mChannelsPerFrame = 2;
LFormat.mBitsPerChannel = 16;
// Allocating AudioQueue
if ((LRet = AudioQueueNewOutput(&LFormat, OnAudioQueueBufferConsumed, coreAudio, NULL, NULL, 0, &(coreAudio->audioQueue)))) {
return scope.Close(v8::Null());
}
OSStatus status = 0;
// Allocate buffers for the AudioQueue
for (int i = 0; i < NUMBER_OF_BUFFERS; ++i) {
status = AudioQueueAllocateBuffer(coreAudio->audioQueue, BUFFER_SIZE, &(coreAudio->audioQueueBuffer[i]));
coreAudio->inuse[i] = false;
}
return scope.Close(o);
}
v8::Handle<v8::Value> EnqueuePacket(const v8::Arguments& args) {
v8::HandleScope scope;
if (args.Length() < 3) {
printf("expected: EnqueuePacket(coreAudio, pcmData, pcmSize)\n");
return scope.Close(v8::Null());
}
v8::Local<v8::Object>wrapper = args[0]->ToObject();
struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) wrapper->GetPointerFromInternalField(0);
v8::Local<v8::Value> pcmBuffer = args[1];
unsigned char* pcmData = (unsigned char*) (Buffer::Data(pcmBuffer->ToObject()));
int32_t pcmSize = args[2]->Int32Value();
//We have all infos needed
size_t offset = 0;
while (pcmSize) {
// if the space remaining in the buffer is not enough for this packet, then enqueue the buffer.
size_t bufSpaceRemaining = BUFFER_SIZE - coreAudio->bytesFilled;
if (bufSpaceRemaining < pcmSize) {
//DEBUG_AUDIOMANAGER_VERBOSE("Before enqueue");
enqueueBuffer(coreAudio);
//DEBUG_AUDIOMANAGER_VERBOSE("After enqueue");
}
bufSpaceRemaining = BUFFER_SIZE - coreAudio->bytesFilled;
size_t copySize;
if (bufSpaceRemaining < pcmSize) {
copySize = bufSpaceRemaining;
} else {
copySize = pcmSize;
}
// copy data to the audio queue buffer
AudioQueueBufferRef fillBuf = coreAudio->audioQueueBuffer[coreAudio->fillBufferIndex];
memcpy((char*) fillBuf->mAudioData + coreAudio->bytesFilled, (const char*) (pcmData + offset), copySize);
// keep track of bytes filled and packets filled
coreAudio->bytesFilled += copySize;
pcmSize -= copySize;
offset += copySize;
}
return scope.Close(v8::Null());
}
v8::Handle<v8::Value> Play(const v8::Arguments& args) {
v8::HandleScope scope;
if (args.Length() < 2) {
printf("expected: Play(coreAudio, audioQueueTimeRef)\n");
return scope.Close(v8::Null());
}
v8::Local<v8::Object>wrapper = args[0]->ToObject();
struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) wrapper->GetPointerFromInternalField(0);
int64_t timeStamp = args[1]->IntegerValue();
AudioTimeStamp myAudioQueueStartTime = {0};
Float64 theNumberOfSecondsInTheFuture = timeStamp/44100.0;
Float64 hostTimeFreq = CAHostTimeBase::GetFrequency();
UInt64 startHostTime = CAHostTimeBase::GetCurrentTime() + theNumberOfSecondsInTheFuture * hostTimeFreq;
myAudioQueueStartTime.mFlags = kAudioTimeStampHostTimeValid;
myAudioQueueStartTime.mHostTime = startHostTime;
if (coreAudio->isPlaying == false) {
if (AudioQueueStart(coreAudio->audioQueue, &myAudioQueueStartTime)) {
printf("AudioQueueStart() Failed!\n");
} else {
coreAudio->isPlaying = true;
}
}
return scope.Close(v8::Null());
}
v8::Handle<v8::Value> Stop(const v8::Arguments& args) {
v8::HandleScope scope;
if (args.Length() < 1) {
printf("expected: Play(coreAudio)\n");
return scope.Close(v8::Null());
}
v8::Local<v8::Object>wrapper = args[0]->ToObject();
struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) wrapper->GetPointerFromInternalField(0);
if (coreAudio->isPlaying) {
if (AudioQueueStop(coreAudio->audioQueue, true)) {
printf("AudioQueueStop() Failed!\n");
} else {
coreAudio->isPlaying = false;
}
}
return scope.Close(v8::Null());
}
v8::Handle<v8::Value> SetVolume(const v8::Arguments& args) {
v8::HandleScope scope;
if (args.Length() < 1) {
printf("expected: Play(coreAudio)\n");
return scope.Close(v8::Null());
}
v8::Local<v8::Object>wrapper = args[0]->ToObject();
struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) wrapper->GetPointerFromInternalField(0);
float volumeToSet=args[1]->IntegerValue()/100.0;
if (coreAudio->isPlaying)
AudioQueueSetParameter(coreAudio->audioQueue, kAudioQueueParam_Volume, volumeToSet);
return scope.Close(v8::Null());
}
v8::Handle<v8::Value> GetBufferLevel(const v8::Arguments& args) {
v8::HandleScope scope;
v8::Local<v8::Object>wrapper = args[0]->ToObject();
struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) wrapper->GetPointerFromInternalField(0);
v8::Handle<v8::Integer> o= v8::Integer::New((int)((coreAudio->buffersUsed/(float)NUMBER_OF_BUFFERS)*100));
return scope.Close(o);
}
void InitCoreAudio(v8::Handle<v8::Object> target) {
NODE_SET_METHOD(target, "enqueuePacket", EnqueuePacket);
NODE_SET_METHOD(target, "newCoreAudio", NewCoreAudio);
NODE_SET_METHOD(target, "play", Play);
NODE_SET_METHOD(target, "stop", Stop);
NODE_SET_METHOD(target, "setVolume", SetVolume);
NODE_SET_METHOD(target, "getBufferLevel", GetBufferLevel);
}
} // nodeairtunes namespace
<commit_msg>Update coreaudio.cc to compile on node v4<commit_after>// Conversion to modern node (v4)
//
// TODO: understand. I have no idea what I'm doing here. HandleScope/Isolate?
//
// https://nodejs.org/api/addons.html
// https://developers.google.com/v8/embed?hl=en
// https://strongloop.com/strongblog/node-js-v0-12-c-apis-breaking/
// https://github.com/nodejs/nan/blob/master/doc/persistent.md
#include <node.h>
#include <node_buffer.h>
#include <v8.h>
//Includes from phoenixLib iOS HAL
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <AudioToolbox/AudioToolbox.h>
#include <CoreFoundation/CoreFoundation.h>
#include "CAHostTimeBase.h"
#include <pthread.h>
#include <sys/resource.h>
#define FRAME_SIZE 1408
#define NUMBER_OF_BUFFERS 100
#define BUFFER_SIZE FRAME_SIZE * 4
//using namespace v8;
using namespace node;
namespace nodeairtunes {
struct coreAudioObjects {
AudioQueueRef audioQueue;
unsigned int fillBufferIndex; // the index of the audioQueueBuffer that is being filled
size_t bytesFilled; // how many bytes have been filled
AudioQueueBufferRef audioQueueBuffer[NUMBER_OF_BUFFERS]; // audio queue buffers
bool inuse[NUMBER_OF_BUFFERS]; // flags to indicate that a buffer is still in use
bool isPlaying;
unsigned int buffersUsed;
OSStatus err;
pthread_mutex_t queueBuffersMutex; // a mutex to protect the inuse flags
pthread_cond_t queueBufferReadyCondition; // a condition varable for handling the inuse flags
};
// This will free the AudioQueue when the wraping JS object is released by the GC
void coreAudio_weak_callback(const v8::WeakCallbackInfo<coreAudioObjects> &data) {
struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) data.GetParameter();
AudioQueueDispose(coreAudio->audioQueue, true);
}
void OnAudioQueueBufferConsumed(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) {
struct coreAudioObjects* coreAudio;
coreAudio = (struct coreAudioObjects*) inUserData;
int bufIndex = -1;
for (unsigned int i = 0; i < NUMBER_OF_BUFFERS; i++) {
if (inBuffer == coreAudio->audioQueueBuffer[i]) {
bufIndex = i;
break;
}
}
if (bufIndex == -1) {
pthread_mutex_lock(&(coreAudio->queueBuffersMutex));
pthread_cond_signal(&(coreAudio->queueBufferReadyCondition));
pthread_mutex_unlock(&(coreAudio->queueBuffersMutex));
//DEBUG_AUDIOMANAGER_ERROR("Buffer mismatch !");
return;
}
// signal waiting thread that the buffer is free.
pthread_mutex_lock(&(coreAudio->queueBuffersMutex));
coreAudio->inuse[bufIndex] = false;
coreAudio->buffersUsed--;
pthread_cond_signal(&(coreAudio->queueBufferReadyCondition));
pthread_mutex_unlock(&(coreAudio->queueBuffersMutex));
}
static void enqueueBuffer(struct coreAudioObjects *coreAudio) {
OSStatus err = 0;
// enqueue buffer
pthread_mutex_lock(&(coreAudio->queueBuffersMutex));
AudioQueueBufferRef fillBuf = coreAudio->audioQueueBuffer[coreAudio->fillBufferIndex];
fillBuf->mAudioDataByteSize = coreAudio->bytesFilled;
err = AudioQueueEnqueueBuffer(coreAudio->audioQueue, fillBuf, 0, NULL);
if (err) {
//DEBUG_AUDIOMANAGER_ERROR("enqueue failed !!!!! %d", coreAudio->fillBufferIndex);
coreAudio->bytesFilled = 0;
pthread_mutex_unlock(&(coreAudio->queueBuffersMutex));
return;
}
coreAudio->inuse[coreAudio->fillBufferIndex] = true; // set in use flag
coreAudio->buffersUsed++;
// go to next buffer
if (++(coreAudio->fillBufferIndex) >= NUMBER_OF_BUFFERS) coreAudio->fillBufferIndex = 0;
coreAudio->bytesFilled = 0; // reset bytes filled
// wait until next buffer is not in use
while (coreAudio->inuse[coreAudio->fillBufferIndex]) {
pthread_cond_wait(&(coreAudio->queueBufferReadyCondition), &(coreAudio->queueBuffersMutex));
}
pthread_mutex_unlock(&(coreAudio->queueBuffersMutex));
}
void NewCoreAudio(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handle_scope(isolate);
struct coreAudioObjects *coreAudio
= (struct coreAudioObjects *) malloc(sizeof (*coreAudio));
v8::Persistent<v8::Object> o;
o.SetWeak(
coreAudio,
coreAudio_weak_callback,
v8::WeakCallbackType::kParameter
);
coreAudio->isPlaying = false;
coreAudio->buffersUsed = 0;
coreAudio->bytesFilled = 0;
coreAudio->fillBufferIndex = 0;
// initialize a mutex and condition so that we can block on buffers in use.
pthread_mutex_init(&(coreAudio->queueBuffersMutex), NULL);
pthread_cond_init(&(coreAudio->queueBufferReadyCondition), NULL);
AudioStreamBasicDescription LFormat;
OSStatus LRet;
LFormat.mSampleRate = 44100;
LFormat.mFormatID = kAudioFormatLinearPCM;
LFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger; // signed int
LFormat.mFramesPerPacket = 1; // for uncompressed audio
LFormat.mBytesPerFrame = 4; //AChannels * 2; // interleaved pcm datas (16bits per chan)
LFormat.mBytesPerPacket = 4; // for pcm: a packet contains a single frame
LFormat.mChannelsPerFrame = 2;
LFormat.mBitsPerChannel = 16;
// Allocating AudioQueue
if ((LRet = AudioQueueNewOutput(&LFormat, OnAudioQueueBufferConsumed, coreAudio, NULL, NULL, 0, &(coreAudio->audioQueue)))) {
args.GetReturnValue().Set(v8::Null(isolate));
return;
}
OSStatus status = 0;
// Allocate buffers for the AudioQueue
for (int i = 0; i < NUMBER_OF_BUFFERS; ++i) {
status = AudioQueueAllocateBuffer(coreAudio->audioQueue, BUFFER_SIZE, &(coreAudio->audioQueueBuffer[i]));
coreAudio->inuse[i] = false;
}
args.GetReturnValue().Set(o);
}
void EnqueuePacket(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
if (args.Length() < 3) {
printf("expected: EnqueuePacket(coreAudio, pcmData, pcmSize)\n");
args.GetReturnValue().Set(v8::Null(isolate));
return;
}
v8::Local<v8::Object> wrapper = args[0]->ToObject();
struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) *wrapper;
v8::Local<v8::Value> pcmBuffer = args[1];
unsigned char* pcmData = (unsigned char*) (Buffer::Data(pcmBuffer->ToObject()));
int32_t pcmSize = args[2]->Int32Value();
//We have all infos needed
size_t offset = 0;
while (pcmSize) {
// if the space remaining in the buffer is not enough for this packet, then enqueue the buffer.
size_t bufSpaceRemaining = BUFFER_SIZE - coreAudio->bytesFilled;
if (bufSpaceRemaining < pcmSize) {
//DEBUG_AUDIOMANAGER_VERBOSE("Before enqueue");
enqueueBuffer(coreAudio);
//DEBUG_AUDIOMANAGER_VERBOSE("After enqueue");
}
bufSpaceRemaining = BUFFER_SIZE - coreAudio->bytesFilled;
size_t copySize;
if (bufSpaceRemaining < pcmSize) {
copySize = bufSpaceRemaining;
} else {
copySize = pcmSize;
}
// copy data to the audio queue buffer
AudioQueueBufferRef fillBuf = coreAudio->audioQueueBuffer[coreAudio->fillBufferIndex];
memcpy((char*) fillBuf->mAudioData + coreAudio->bytesFilled, (const char*) (pcmData + offset), copySize);
// keep track of bytes filled and packets filled
coreAudio->bytesFilled += copySize;
pcmSize -= copySize;
offset += copySize;
}
args.GetReturnValue().Set(v8::Null(isolate));
}
void Play(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
if (args.Length() < 2) {
printf("expected: Play(coreAudio, audioQueueTimeRef)\n");
args.GetReturnValue().Set(v8::Null(isolate));
return;
}
v8::Local<v8::Object> wrapper = args[0]->ToObject();
struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) *wrapper;
int64_t timeStamp = args[1]->IntegerValue();
AudioTimeStamp myAudioQueueStartTime; // = {0};
Float64 theNumberOfSecondsInTheFuture = timeStamp/44100.0;
Float64 hostTimeFreq = CAHostTimeBase::GetFrequency();
UInt64 startHostTime = CAHostTimeBase::GetCurrentTime() + theNumberOfSecondsInTheFuture * hostTimeFreq;
myAudioQueueStartTime.mFlags = kAudioTimeStampHostTimeValid;
myAudioQueueStartTime.mHostTime = startHostTime;
if (coreAudio->isPlaying == false) {
if (AudioQueueStart(coreAudio->audioQueue, &myAudioQueueStartTime)) {
printf("AudioQueueStart() Failed!\n");
} else {
coreAudio->isPlaying = true;
}
}
args.GetReturnValue().Set(v8::Null(isolate));
}
void Stop(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
if (args.Length() < 1) {
printf("expected: Play(coreAudio)\n");
args.GetReturnValue().Set(v8::Null(isolate));
return;
}
v8::Local<v8::Object> wrapper = args[0]->ToObject();
struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) *wrapper;
if (coreAudio->isPlaying) {
if (AudioQueueStop(coreAudio->audioQueue, true)) {
printf("AudioQueueStop() Failed!\n");
} else {
coreAudio->isPlaying = false;
}
}
args.GetReturnValue().Set(v8::Null(isolate));
}
void SetVolume(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
if (args.Length() < 1) {
printf("expected: Play(coreAudio)\n");
args.GetReturnValue().Set(v8::Null(isolate));
return;
}
v8::Local<v8::Object> wrapper = args[0]->ToObject();
struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) *wrapper;
float volumeToSet=args[1]->IntegerValue()/100.0;
if (coreAudio->isPlaying)
AudioQueueSetParameter(coreAudio->audioQueue, kAudioQueueParam_Volume, volumeToSet);
args.GetReturnValue().Set(v8::Null(isolate));
}
void GetBufferLevel(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Object> wrapper = args[0]->ToObject();
struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) *wrapper;
v8::Local<v8::Integer> o = v8::Integer::New(isolate, (int)((coreAudio->buffersUsed/(float)NUMBER_OF_BUFFERS)*100));
args.GetReturnValue().Set(o);
}
void InitCoreAudio(v8::Handle<v8::Object> target) {
NODE_SET_METHOD(target, "enqueuePacket", EnqueuePacket);
NODE_SET_METHOD(target, "newCoreAudio", NewCoreAudio);
NODE_SET_METHOD(target, "play", Play);
NODE_SET_METHOD(target, "stop", Stop);
NODE_SET_METHOD(target, "setVolume", SetVolume);
NODE_SET_METHOD(target, "getBufferLevel", GetBufferLevel);
}
} // nodeairtunes namespace
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <iostream>
#include <sstream>
#include <fstream>
extern "C" {
#include "type.h"
#include "node.h"
#include "tree.h"
#include "wake.tab.h"
extern int yyparse();
extern Node* parsetree;
extern FILE *yyin;
}
#include "Parser.h"
#include "Linker.h"
#include "ParseTreeTraverser.h"
#include "SemanticErrorPrinter.h"
#include "LibraryLoader.h"
#include "ObjectFileGenerator.h"
#include "ObjectFileHeaderData.h"
#include "ObjectFileHeaderRenderer.h"
#include "CompilationExceptions.h"
#include "OptionsParser.h"
#include "EntryPointAnalyzer.h"
#include "AddressAllocator.h"
#include "TableFileWriter.h"
#include "SimpleAddressTable.h"
#include "ImportParseTreeTraverser.h"
#include "ErrorTracker.h"
void writeTableFiles(std::string dirname, ClassSpaceSymbolTable& table) {
vector<PropertySymbolTable*> tables = table.getDefinedClasses();
for(auto it = tables.begin(); it != tables.end(); ++it) {
fstream file;
file.open((dirname + "/" + (*it)->classname + ".table").c_str(), ios::out);
TableFileWriter writer;
writer.write(file, *it);
file.close();
}
}
void compileFile(Options* options) {
if(options->compileFilename == "") {
printf("[ no file provided ]\n"); exit(1);
}
FILE *myfile = fopen(options->compileFilename.c_str(), "r");
if (!myfile) {
printf("[ couldn't open file ]\n");
exit(2);
}
Parser parser;
// Parse the shit out of this
if(parser.parse(myfile)) exit(3);
//parser.print();exit(0);
ClassSpaceSymbolTable table;
ErrorTracker errors;
LibraryLoader loader;
loader.loadStdLibToTable(&table);
ImportParseTreeTraverser importer;
errors.pushContext("Import header");
importer.traverse(parser.getParseTree(), table, loader, errors, options->tabledir);
errors.popContext();
// Now do all the semantic analysis
ParseTreeTraverser traverser(&table, errors);
traverser.traverse(parser.getParseTree());
SemanticErrorPrinter printer;
if(!traverser.passesForCompilation()) {
traverser.printErrors(printer);
exit(4);
}
if(options->table) {
writeTableFiles(options->tabledir, table);
return;
}
basic_ostringstream<char> object;
ObjectFileHeaderData header;
ObjectFileGenerator gen(object, &table, &header);
gen.generate(parser.getParseTree());
fstream file;
ObjectFileHeaderRenderer renderer;
file.open(options->outFilename.c_str(), ios::out);
renderer.writeOut(file, &header);
file << object.str();
file.close();
writeTableFiles(options->tabledir.c_str(), table);
}
int main(int argc, char** argv) {
OptionsParser optionsparser;
Options* options = optionsparser.parse(argc, argv);
if(options->showVersion) {
printf("[ Wake ---- std compiler ]\n");
printf("[ v0.01 Michael Fairhurst ]\n");
exit(0);
}
if(options->showHelp) {
printf("usage: wake flags filename\n");
printf("flags: -o|--out file - compile to this file\n");
printf(" -c|--mainclass class - begin execution with this file\n");
printf(" -m|--mainemethod method - begin execution with this method\n");
printf(" -v|--version - show version and exit\n");
printf(" -h|--help - show help and exit\n");
printf(" -i|--listmains - list compilable entrypoints\n");
printf(" -l|--link - link compiled files into an executable\n");
printf(" -t|--table - only generate table files\n");
printf(" -d|--tabledir - dir for finding and creating .table files\n");
exit(0);
}
if(!options->link) compileFile(options);
else {
try {
AddressAllocator classAllocator;
AddressAllocator propAllocator;
ClassSpaceSymbolTable table;
SimpleAddressTable classTable(classAllocator);
SimpleAddressTable propTable(propAllocator);
Linker linker(classTable, propTable);
for(std::vector<std::string>::iterator it = options->linkFilenames.begin(); it != options->linkFilenames.end(); ++it) {
linker.loadObject(*it);
}
linker.loadTables(options->tabledir, table);
try {
table.assertNoNeedsAreCircular();
} catch(SemanticError* e) {
e->token = NULL;
SemanticErrorPrinter printer;
printer.print(e);
delete e;
return 1;
}
fstream file;
file.open(options->outFilename.c_str(), ios::out);
linker.write(file);
EntryPointAnalyzer entrypointanalyzer;
if(options->listMains) {
table.printEntryPoints(&entrypointanalyzer);
exit(0);
} else {
if(!entrypointanalyzer.checkMethodCanBeMain(options->mainclass, options->mainmethod, &table)) {
printf("Entry point %s.%s in not valid, cannot continue.\nTry wake yourfile --listmains to get entry points\n", options->mainclass.c_str(), options->mainmethod.c_str());
exit(5);
}
}
linker.setMain(file, options->mainclass, options->mainmethod, table);
} catch(SymbolNotFoundException* e) {
cout << "Missing symbol in object files at link time: " << e->errormsg << endl;
delete e;
}
}
}
<commit_msg>Adding binary flag to tablefiles, something I remember hearing wouldn't work with gcc but is necessary for windows and seems to work with gcc after all<commit_after>#include <stdio.h>
#include <iostream>
#include <sstream>
#include <fstream>
extern "C" {
#include "type.h"
#include "node.h"
#include "tree.h"
#include "wake.tab.h"
extern int yyparse();
extern Node* parsetree;
extern FILE *yyin;
}
#include "Parser.h"
#include "Linker.h"
#include "ParseTreeTraverser.h"
#include "SemanticErrorPrinter.h"
#include "LibraryLoader.h"
#include "ObjectFileGenerator.h"
#include "ObjectFileHeaderData.h"
#include "ObjectFileHeaderRenderer.h"
#include "CompilationExceptions.h"
#include "OptionsParser.h"
#include "EntryPointAnalyzer.h"
#include "AddressAllocator.h"
#include "TableFileWriter.h"
#include "SimpleAddressTable.h"
#include "ImportParseTreeTraverser.h"
#include "ErrorTracker.h"
void writeTableFiles(std::string dirname, ClassSpaceSymbolTable& table) {
vector<PropertySymbolTable*> tables = table.getDefinedClasses();
for(auto it = tables.begin(); it != tables.end(); ++it) {
fstream file;
file.open((dirname + "/" + (*it)->classname + ".table").c_str(), ios::out | ios::binary);
TableFileWriter writer;
writer.write(file, *it);
file.close();
}
}
void compileFile(Options* options) {
if(options->compileFilename == "") {
printf("[ no file provided ]\n"); exit(1);
}
FILE *myfile = fopen(options->compileFilename.c_str(), "r");
if (!myfile) {
printf("[ couldn't open file ]\n");
exit(2);
}
Parser parser;
// Parse the shit out of this
if(parser.parse(myfile)) exit(3);
//parser.print();exit(0);
ClassSpaceSymbolTable table;
ErrorTracker errors;
LibraryLoader loader;
loader.loadStdLibToTable(&table);
ImportParseTreeTraverser importer;
errors.pushContext("Import header");
importer.traverse(parser.getParseTree(), table, loader, errors, options->tabledir);
errors.popContext();
// Now do all the semantic analysis
ParseTreeTraverser traverser(&table, errors);
traverser.traverse(parser.getParseTree());
SemanticErrorPrinter printer;
if(!traverser.passesForCompilation()) {
traverser.printErrors(printer);
exit(4);
}
if(options->table) {
writeTableFiles(options->tabledir, table);
return;
}
basic_ostringstream<char> object;
ObjectFileHeaderData header;
ObjectFileGenerator gen(object, &table, &header);
gen.generate(parser.getParseTree());
fstream file;
ObjectFileHeaderRenderer renderer;
file.open(options->outFilename.c_str(), ios::out);
renderer.writeOut(file, &header);
file << object.str();
file.close();
writeTableFiles(options->tabledir.c_str(), table);
}
int main(int argc, char** argv) {
OptionsParser optionsparser;
Options* options = optionsparser.parse(argc, argv);
if(options->showVersion) {
printf("[ Wake ---- std compiler ]\n");
printf("[ v0.01 Michael Fairhurst ]\n");
exit(0);
}
if(options->showHelp) {
printf("usage: wake flags filename\n");
printf("flags: -o|--out file - compile to this file\n");
printf(" -c|--mainclass class - begin execution with this file\n");
printf(" -m|--mainemethod method - begin execution with this method\n");
printf(" -v|--version - show version and exit\n");
printf(" -h|--help - show help and exit\n");
printf(" -i|--listmains - list compilable entrypoints\n");
printf(" -l|--link - link compiled files into an executable\n");
printf(" -t|--table - only generate table files\n");
printf(" -d|--tabledir - dir for finding and creating .table files\n");
exit(0);
}
if(!options->link) compileFile(options);
else {
try {
AddressAllocator classAllocator;
AddressAllocator propAllocator;
ClassSpaceSymbolTable table;
SimpleAddressTable classTable(classAllocator);
SimpleAddressTable propTable(propAllocator);
Linker linker(classTable, propTable);
for(std::vector<std::string>::iterator it = options->linkFilenames.begin(); it != options->linkFilenames.end(); ++it) {
linker.loadObject(*it);
}
linker.loadTables(options->tabledir, table);
try {
table.assertNoNeedsAreCircular();
} catch(SemanticError* e) {
e->token = NULL;
SemanticErrorPrinter printer;
printer.print(e);
delete e;
return 1;
}
fstream file;
file.open(options->outFilename.c_str(), ios::out);
linker.write(file);
EntryPointAnalyzer entrypointanalyzer;
if(options->listMains) {
table.printEntryPoints(&entrypointanalyzer);
exit(0);
} else {
if(!entrypointanalyzer.checkMethodCanBeMain(options->mainclass, options->mainmethod, &table)) {
printf("Entry point %s.%s in not valid, cannot continue.\nTry wake yourfile --listmains to get entry points\n", options->mainclass.c_str(), options->mainmethod.c_str());
exit(5);
}
}
linker.setMain(file, options->mainclass, options->mainmethod, table);
} catch(SymbolNotFoundException* e) {
cout << "Missing symbol in object files at link time: " << e->errormsg << endl;
delete e;
}
}
}
<|endoftext|> |
<commit_before>#include "sqliteindexwriter.h"
#include "sqliteindexmanager.h"
#include <sqlite3.h>
#include <sstream>
using namespace std;
using namespace jstreams;
SqliteIndexWriter::SqliteIndexWriter(SqliteIndexManager *m)
: manager(m) {
int r = sqlite3_open(manager->getDBFile(), &db);
// any value other than SQLITE_OK is an error
if (r != SQLITE_OK) {
printf("could not open db\n");
db = 0;
manager->deref();
return;
}
// speed up by being unsafe and keeping temp tables in memory
r = sqlite3_exec(db, "PRAGMA synchronous = OFF;"
"PRAGMA temp_store = MEMORY;" , 0, 0, 0);
if (r != SQLITE_OK) {
printf("could not speed up database\n");
}
// create the tables required
const char* sql ="create table files (path,"
"unique (path) on conflict ignore);"
"create table idx (path, name, value, "
"unique (path, name, value) on conflict ignore);"
"create index idx_path on idx(path);"
"create index idx_name on idx(name);"
"create index idx_value on idx(value);"
"create table words (wordid integer primary key, "
" word, count, unique(word));"
"create table filewords (fileid integer, wordid integer, count,"
"unique (fileid, wordid));"
"create index filewords_wordid on filewords(wordid);";
r = sqlite3_exec(db, sql, 0, 0, 0);
if (r != SQLITE_OK) {
printf("could not create table %i %s\n", r, sqlite3_errmsg(db));
}
// prepare the insert statement
sql = "insert into idx (path, name, value) values(?, ?, ?)";
r = sqlite3_prepare(db, sql, 0, &stmt, 0);
if (r != SQLITE_OK) {
printf("could not prepare insert statement\n");
stmt = 0;
}
}
SqliteIndexWriter::~SqliteIndexWriter() {
if (stmt) {
int r = sqlite3_finalize(stmt);
if (r != SQLITE_OK) {
printf("could not finalize insert statement\n");
}
}
if (db) {
int r = sqlite3_close(db);
if (r != SQLITE_OK) {
printf("could not create table\n");
}
}
}
void
SqliteIndexWriter::addStream(const Indexable* idx, const string& fieldname,
StreamBase<wchar_t>* datastream) {
}
void
SqliteIndexWriter::addField(const Indexable* idx, const string &fieldname,
const string& value) {
int64_t id = idx->getId();
if (id == -1) return;
if (fieldname == "content") {
// find a pointer to the value
map<int64_t, map<string, int> >::iterator m = content.find(id);
if (m == content.end()) {
// no value at all yet, so fine to add one
content[id][value]++;
} else if (m->second.size() >= 1000) {
map<string, int>::iterator i = m->second.find(value);
if (i != m->second.end()) {
i->second++;
}
} else {
content[id][value]++;
}
return;
}
manager->ref();
sqlite3_bind_int64(stmt, 1, idx->getId());
sqlite3_bind_text(stmt, 2, fieldname.c_str(),
fieldname.length(), SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, value.c_str(), value.length(), SQLITE_STATIC);
int r = sqlite3_step(stmt);
if (r != SQLITE_DONE) {
printf("could not write into database: %i %s\n", r, sqlite3_errmsg(db));
}
r = sqlite3_reset(stmt);
if (r != SQLITE_OK) {
printf("could not reset statement: %i %s\n", r, sqlite3_errmsg(db));
}
manager->deref();
}
void
SqliteIndexWriter::startIndexable(Indexable* idx) {
// get the file name
string name = SqliteIndexManager::escapeSqlValue(idx->getName());
// remove the previous version of this file
// check if there is a previous version
string sql = "select rowid from files where path = '"+name+"';";
manager->ref();
sqlite3_stmt* stmt;
int r = sqlite3_prepare(db, sql.c_str(), 0, &stmt, 0);
if (r != SQLITE_OK) {
printf("could not prepare document find sql\n");
idx->setId(-1);
manager->deref();
return;
}
r = sqlite3_step(stmt);
int64_t id = -1;
if (r == SQLITE_ROW) {
id = sqlite3_column_int64(stmt, 0);
sqlite3_finalize(stmt);
} else if (r == SQLITE_DONE) {
sqlite3_finalize(stmt);
// prepare the insert statement
sql = "insert into files (path) values('";
sql += name + "');";
r = sqlite3_exec(db, sql.c_str(), 0, 0, 0);
if (r != SQLITE_OK) {
// TODO: this error occurs quite often: check it out
printf("error in adding file %i %s\n", r, sqlite3_errmsg(db));
stmt = 0;
}
id = sqlite3_last_insert_rowid(db);
} else {
printf("could not look for a document by path\n");
manager->deref();
return;
}
idx->setId(id);
manager->deref();
}
/*
Close all left open indexwriters for this path.
*/
void
SqliteIndexWriter::finishIndexable(const Indexable* idx) {
// store the content field
map<int64_t, map<string, int> >::const_iterator m
= content.find(idx->getId());
if (m == content.end()) return;
// create a temporary table
int r = sqlite3_exec(db, "create temp table t(word, count)", 0,0,0);
if (r != SQLITE_OK) {
printf("could not create temp table %i %s\n", r, sqlite3_errmsg(db));
}
manager->ref();
sqlite3_stmt* stmt;
r = sqlite3_prepare(db, "insert into t (word, count) values(?,?);",
0, &stmt, 0);
if (r != SQLITE_OK) {
printf("could not prepare temp insert sql\n");
content.erase(m->first);
manager->deref();
return;
}
map<string, int>::const_iterator i = m->second.begin();
map<string, int>::const_iterator e = m->second.end();
for (; i!=e; ++i) {
sqlite3_bind_text(stmt, 1, i->first.c_str(), i->first.length(),
SQLITE_STATIC);
sqlite3_bind_int(stmt, 2, i->second);
r = sqlite3_step(stmt);
if (r != SQLITE_DONE) {
printf("could not write into database: %i %s\n", r, sqlite3_errmsg(db));
}
r = sqlite3_reset(stmt);
}
sqlite3_finalize(stmt);
ostringstream sql;
sql << "replace into words (wordid, word, count) "
"select wordid, t.word, t.count+ifnull(words.count,0) "
"from t left join words on t.word = words.word; "
"replace into filewords (fileid, wordid, count) "
"select ";
sql << m->first;
sql << ", words.rowid, t.count from t join words "
"on t.word = words.word; drop table t;";
r = sqlite3_exec(db, sql.str().c_str(),0,0,0);
if (r != SQLITE_OK) {
printf("could not drop temp table %i %s\n", r, sqlite3_errmsg(db));
}
manager->deref();
content.erase(m->first);
}
<commit_msg>Fixed a bug in inserting the file name into the sqlite database.<commit_after>#include "sqliteindexwriter.h"
#include "sqliteindexmanager.h"
#include <sqlite3.h>
#include <sstream>
using namespace std;
using namespace jstreams;
SqliteIndexWriter::SqliteIndexWriter(SqliteIndexManager *m)
: manager(m) {
int r = sqlite3_open(manager->getDBFile(), &db);
// any value other than SQLITE_OK is an error
if (r != SQLITE_OK) {
printf("could not open db\n");
db = 0;
manager->deref();
return;
}
// speed up by being unsafe and keeping temp tables in memory
r = sqlite3_exec(db, "PRAGMA synchronous = OFF;"
"PRAGMA temp_store = MEMORY;" , 0, 0, 0);
if (r != SQLITE_OK) {
printf("could not speed up database\n");
}
// create the tables required
const char* sql ="create table files (path,"
"unique (path) on conflict ignore);"
"create table idx (path, name, value, "
"unique (path, name, value) on conflict ignore);"
"create index idx_path on idx(path);"
"create index idx_name on idx(name);"
"create index idx_value on idx(value);"
"create table words (wordid integer primary key, "
" word, count, unique(word));"
"create table filewords (fileid integer, wordid integer, count,"
"unique (fileid, wordid));"
"create index filewords_wordid on filewords(wordid);";
r = sqlite3_exec(db, sql, 0, 0, 0);
if (r != SQLITE_OK) {
printf("could not create table %i %s\n", r, sqlite3_errmsg(db));
}
// prepare the insert statement
sql = "insert into idx (path, name, value) values(?, ?, ?)";
r = sqlite3_prepare(db, sql, 0, &stmt, 0);
if (r != SQLITE_OK) {
printf("could not prepare insert statement\n");
stmt = 0;
}
}
SqliteIndexWriter::~SqliteIndexWriter() {
if (stmt) {
int r = sqlite3_finalize(stmt);
if (r != SQLITE_OK) {
printf("could not finalize insert statement\n");
}
}
if (db) {
int r = sqlite3_close(db);
if (r != SQLITE_OK) {
printf("could not create table\n");
}
}
}
void
SqliteIndexWriter::addStream(const Indexable* idx, const string& fieldname,
StreamBase<wchar_t>* datastream) {
}
void
SqliteIndexWriter::addField(const Indexable* idx, const string &fieldname,
const string& value) {
int64_t id = idx->getId();
if (id == -1) return;
if (fieldname == "content") {
// find a pointer to the value
map<int64_t, map<string, int> >::iterator m = content.find(id);
if (m == content.end()) {
// no value at all yet, so fine to add one
content[id][value]++;
} else if (m->second.size() >= 1000) {
map<string, int>::iterator i = m->second.find(value);
if (i != m->second.end()) {
i->second++;
}
} else {
content[id][value]++;
}
return;
}
manager->ref();
sqlite3_bind_int64(stmt, 1, idx->getId());
sqlite3_bind_text(stmt, 2, fieldname.c_str(),
fieldname.length(), SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, value.c_str(), value.length(), SQLITE_STATIC);
int r = sqlite3_step(stmt);
if (r != SQLITE_DONE) {
printf("could not write into database: %i %s\n", r, sqlite3_errmsg(db));
}
r = sqlite3_reset(stmt);
if (r != SQLITE_OK) {
printf("could not reset statement: %i %s\n", r, sqlite3_errmsg(db));
}
manager->deref();
}
void
SqliteIndexWriter::startIndexable(Indexable* idx) {
// get the file name
string name = SqliteIndexManager::escapeSqlValue(idx->getName());
// remove the previous version of this file
// check if there is a previous version
string sql = "select rowid from files where path = '"+name+"';";
manager->ref();
sqlite3_stmt* stmt;
int r = sqlite3_prepare(db, sql.c_str(), 0, &stmt, 0);
if (r != SQLITE_OK) {
printf("could not prepare document find sql\n");
idx->setId(-1);
manager->deref();
return;
}
r = sqlite3_step(stmt);
int64_t id = -1;
if (r == SQLITE_ROW) {
id = sqlite3_column_int64(stmt, 0);
sqlite3_finalize(stmt);
} else if (r == SQLITE_DONE) {
sqlite3_finalize(stmt);
// prepare the insert statement
r = sqlite3_prepare(db, "insert into files (path) values(?);'", 0,
&stmt, 0);
if (r != SQLITE_OK) {
printf("could not prepare document insert sql\n");
idx->setId(-1);
manager->deref();
return;
}
sqlite3_bind_text(stmt, 1, name.c_str(), name.length(), SQLITE_STATIC);
r = sqlite3_step(stmt);
if (r != SQLITE_DONE) {
printf("error in adding file %i %s\n", r, sqlite3_errmsg(db));
}
id = sqlite3_last_insert_rowid(db);
sqlite3_finalize(stmt);
} else {
printf("could not look for a document by path\n");
manager->deref();
return;
}
idx->setId(id);
manager->deref();
}
/*
Close all left open indexwriters for this path.
*/
void
SqliteIndexWriter::finishIndexable(const Indexable* idx) {
// store the content field
map<int64_t, map<string, int> >::const_iterator m
= content.find(idx->getId());
if (m == content.end()) return;
// create a temporary table
int r = sqlite3_exec(db, "create temp table t(word, count)", 0,0,0);
if (r != SQLITE_OK) {
printf("could not create temp table %i %s\n", r, sqlite3_errmsg(db));
}
manager->ref();
sqlite3_stmt* stmt;
r = sqlite3_prepare(db, "insert into t (word, count) values(?,?);",
0, &stmt, 0);
if (r != SQLITE_OK) {
printf("could not prepare temp insert sql\n");
content.erase(m->first);
manager->deref();
return;
}
map<string, int>::const_iterator i = m->second.begin();
map<string, int>::const_iterator e = m->second.end();
for (; i!=e; ++i) {
sqlite3_bind_text(stmt, 1, i->first.c_str(), i->first.length(),
SQLITE_STATIC);
sqlite3_bind_int(stmt, 2, i->second);
r = sqlite3_step(stmt);
if (r != SQLITE_DONE) {
printf("could not write into database: %i %s\n", r, sqlite3_errmsg(db));
}
r = sqlite3_reset(stmt);
}
sqlite3_finalize(stmt);
ostringstream sql;
sql << "replace into words (wordid, word, count) "
"select wordid, t.word, t.count+ifnull(words.count,0) "
"from t left join words on t.word = words.word; "
"replace into filewords (fileid, wordid, count) "
"select ";
sql << m->first;
sql << ", words.rowid, t.count from t join words "
"on t.word = words.word; drop table t;";
r = sqlite3_exec(db, sql.str().c_str(),0,0,0);
if (r != SQLITE_OK) {
printf("could not drop temp table %i %s\n", r, sqlite3_errmsg(db));
}
manager->deref();
content.erase(m->first);
}
<|endoftext|> |
<commit_before>#include "sqliteindexwriter.h"
#include "sqliteindexmanager.h"
#include <sqlite3.h>
#include <sstream>
using namespace std;
using namespace jstreams;
SqliteIndexWriter::SqliteIndexWriter(SqliteIndexManager *m)
: manager(m) {
int r = sqlite3_open(manager->getDBFile(), &db);
// any value other than SQLITE_OK is an error
if (r != SQLITE_OK) {
printf("could not open db\n");
db = 0;
return;
}
temprows = 0;
maxtemprows = 100000;
// create temporary tables
const char* sql = "PRAGMA synchronous = OFF;"
"PRAGMA auto_vacuum = 1;"
"PRAGMA temp_store = MEMORY;"
"create temp table tempidx (fileid integer, name text, value);"
"create temp table tempfilewords (fileid integer, word text, "
"count integer); begin immediate transaction;"
"create index tempfilewords_word on tempfilewords(word);"
"create index tempfilewords_fileid on tempfilewords(fileid);";
r = sqlite3_exec(db, sql, 0,0,0);
if (r != SQLITE_OK) {
printf("could not init writer: %i %s\n", r, sqlite3_errmsg(db));
}
// prepare the sql statements
sql = "insert into tempidx (fileid, name, value) values(?, ?, ?)";
prepareStmt(insertvaluestmt, sql, strlen(sql));
sql = "select fileid, mtime from files where path = ?;";
prepareStmt(getfilestmt, sql, strlen(sql));
sql = "update files set mtime = ?;";
prepareStmt(updatefilestmt, sql, strlen(sql));
sql = "insert into files (path, mtime, depth) values(?, ?, ?);'";
prepareStmt(insertfilestmt, sql, strlen(sql));
}
SqliteIndexWriter::~SqliteIndexWriter() {
commit();
finalizeStmt(insertvaluestmt);
finalizeStmt(getfilestmt);
finalizeStmt(updatefilestmt);
finalizeStmt(insertfilestmt);
if (db) {
int r = sqlite3_close(db);
if (r != SQLITE_OK) {
printf("could not close the database\n");
}
}
}
void
SqliteIndexWriter::prepareStmt(sqlite3_stmt*& stmt, const char* sql,
int sqllength) {
int r = sqlite3_prepare(db, sql, sqllength,& stmt, 0);
if (r != SQLITE_OK) {
printf("could not prepare statement '%s': %s\n", sql,
sqlite3_errmsg(db));
stmt = 0;
}
}
void
SqliteIndexWriter::finalizeStmt(sqlite3_stmt*& stmt) {
if (stmt) {
int r = sqlite3_finalize(stmt);
stmt = 0;
if (r != SQLITE_OK) {
printf("could not prepare statement: %s\n", sqlite3_errmsg(db));
}
}
}
void
SqliteIndexWriter::addStream(const Indexable* idx, const string& fieldname,
StreamBase<wchar_t>* datastream) {
}
void
SqliteIndexWriter::addField(const Indexable* idx, const string &fieldname,
const string& value) {
int64_t id = idx->getId();
//id = -1; // debug
if (id == -1) return;
if (fieldname == "content") {
// find a pointer to the value
map<int64_t, map<string, int> >::iterator m = content.find(id);
if (m == content.end()) {
// no value at all yet, so fine to add one
content[id][value]++;
} else if (m->second.size() >= 1000) {
map<string, int>::iterator i = m->second.find(value);
if (i != m->second.end()) {
i->second++;
}
} else {
content[id][value]++;
}
return;
}
sqlite3_bind_int64(insertvaluestmt, 1, idx->getId());
sqlite3_bind_text(insertvaluestmt, 2, fieldname.c_str(),
fieldname.length(), SQLITE_STATIC);
sqlite3_bind_text(insertvaluestmt, 3, value.c_str(), value.length(),
SQLITE_STATIC);
int r = sqlite3_step(insertvaluestmt);
if (r != SQLITE_DONE) {
printf("could not write into database: %i %s\n", r, sqlite3_errmsg(db));
}
r = sqlite3_reset(insertvaluestmt);
if (r != SQLITE_OK) {
printf("could not reset statement: %i %s\n", r, sqlite3_errmsg(db));
}
temprows++;
}
void
SqliteIndexWriter::setField(const Indexable*, const std::string &fieldname,
int64_t value) {
}
void
SqliteIndexWriter::startIndexable(Indexable* idx) {
// get the file name
const char* name = idx->getName().c_str();
size_t namelen = idx->getName().length();
manager->ref();
int64_t id = -1;
setIndexed(idx, false);
sqlite3_bind_text(insertfilestmt, 1, name, namelen, SQLITE_STATIC);
sqlite3_bind_int64(insertfilestmt, 2, idx->getMTime());
sqlite3_bind_int(insertfilestmt, 3, idx->getDepth());
int r = sqlite3_step(insertfilestmt);
if (r != SQLITE_DONE) {
printf("error in adding file %i %s\n", r, sqlite3_errmsg(db));
}
id = sqlite3_last_insert_rowid(db);
sqlite3_reset(insertfilestmt);
idx->setId(id);
manager->deref();
}
/*
Close all left open indexwriters for this path.
*/
void
SqliteIndexWriter::finishIndexable(const Indexable* idx) {
// store the content field
map<int64_t, map<string, int> >::const_iterator m
= content.find(idx->getId());
if (m == content.end()) {
if (temprows > maxtemprows) commit();
return;
}
sqlite3_stmt* stmt;
int r = sqlite3_prepare(db,
"insert into tempfilewords (fileid, word, count) values(?, ?,?);",
0, &stmt, 0);
if (r != SQLITE_OK) {
if (idx->getDepth() == 0) {
sqlite3_exec(db, "rollback; ", 0, 0, 0);
}
printf("could not prepare temp insert sql %s\n", sqlite3_errmsg(db));
content.erase(m->first);
manager->deref();
return;
}
map<string, int>::const_iterator i = m->second.begin();
map<string, int>::const_iterator e = m->second.end();
sqlite3_bind_int64(stmt, 1, idx->getId());
for (; i!=e; ++i) {
sqlite3_bind_text(stmt, 2, i->first.c_str(), i->first.length(),
SQLITE_STATIC);
sqlite3_bind_int(stmt, 3, i->second);
r = sqlite3_step(stmt);
if (r != SQLITE_DONE) {
printf("could not write content into database: %i %s\n", r,
sqlite3_errmsg(db));
}
r = sqlite3_reset(stmt);
temprows++;
}
sqlite3_finalize(stmt);
if (temprows > maxtemprows) commit();
content.erase(m->first);
}
void
SqliteIndexWriter::commit() {
printf("start commit\n");
// move the data from the temp tables into the index
const char* sql = "replace into words (wordid, word, count) "
"select wordid, t.word, sum(t.count)+ifnull(words.count,0) "
"from tempfilewords t left join words on t.word = words.word "
"group by t.word; "
"insert into filewords (fileid, wordid, count) "
"select fileid, words.wordid, t.count from tempfilewords t join words "
"on t.word = words.word;"
"replace into idx select * from tempidx;"
"delete from tempidx;"
"delete from tempfilewords;"
"commit;"
"begin immediate transaction;";
manager->ref();
int r = sqlite3_exec(db, sql, 0, 0, 0);
if (r != SQLITE_OK) {
printf("could not store new data: %s\n", sqlite3_errmsg(db));
}
manager->deref();
printf("end commit\n");
temprows = 0;
}
void
SqliteIndexWriter::deleteEntry(const string& path) {
if (temprows) commit();
int64_t id = -1;
manager->ref();
int r = sqlite3_bind_text(getfilestmt, 1, path.c_str(), 0, SQLITE_STATIC);
r = sqlite3_step(getfilestmt);
if (r != SQLITE_ROW) {
sqlite3_reset(getfilestmt);
manager->deref();
return;
}
id = sqlite3_column_int64(getfilestmt, 0);
sqlite3_reset(getfilestmt);
ostringstream sql;
sql << "delete from idx where fileid = " << id
<< "; delete from filewords where fileid = " << id
<< "; delete from files where fileid = " << id;
r = sqlite3_exec(db, sql.str().c_str(), 0, 0, 0);
if (r != SQLITE_OK) {
printf("could not delete file %s: %s\n", path.c_str(),
sqlite3_errmsg(db));
}
manager->deref();
}
<commit_msg>added ability to delete from index<commit_after>#include "sqliteindexwriter.h"
#include "sqliteindexmanager.h"
#include <sqlite3.h>
#include <sstream>
using namespace std;
using namespace jstreams;
SqliteIndexWriter::SqliteIndexWriter(SqliteIndexManager *m)
: manager(m) {
int r = sqlite3_open(manager->getDBFile(), &db);
// any value other than SQLITE_OK is an error
if (r != SQLITE_OK) {
printf("could not open db\n");
db = 0;
return;
}
temprows = 0;
maxtemprows = 100000;
// create temporary tables
const char* sql = "PRAGMA synchronous = OFF;"
"PRAGMA auto_vacuum = 1;"
"PRAGMA temp_store = MEMORY;"
"create temp table tempidx (fileid integer, name text, value);"
"create temp table tempfilewords (fileid integer, word text, "
"count integer); begin immediate transaction;"
"create index tempfilewords_word on tempfilewords(word);"
"create index tempfilewords_fileid on tempfilewords(fileid);";
r = sqlite3_exec(db, sql, 0,0,0);
if (r != SQLITE_OK) {
printf("could not init writer: %i %s\n", r, sqlite3_errmsg(db));
}
// prepare the sql statements
sql = "insert into tempidx (fileid, name, value) values(?, ?, ?)";
prepareStmt(insertvaluestmt, sql, strlen(sql));
sql = "select fileid, mtime from files where path = ?;";
prepareStmt(getfilestmt, sql, strlen(sql));
sql = "update files set mtime = ?;";
prepareStmt(updatefilestmt, sql, strlen(sql));
sql = "insert into files (path, mtime, depth) values(?, ?, ?);'";
prepareStmt(insertfilestmt, sql, strlen(sql));
}
SqliteIndexWriter::~SqliteIndexWriter() {
commit();
finalizeStmt(insertvaluestmt);
finalizeStmt(getfilestmt);
finalizeStmt(updatefilestmt);
finalizeStmt(insertfilestmt);
if (db) {
int r = sqlite3_close(db);
if (r != SQLITE_OK) {
printf("could not close the database\n");
}
}
}
void
SqliteIndexWriter::prepareStmt(sqlite3_stmt*& stmt, const char* sql,
int sqllength) {
int r = sqlite3_prepare(db, sql, sqllength,& stmt, 0);
if (r != SQLITE_OK) {
printf("could not prepare statement '%s': %s\n", sql,
sqlite3_errmsg(db));
stmt = 0;
}
}
void
SqliteIndexWriter::finalizeStmt(sqlite3_stmt*& stmt) {
if (stmt) {
int r = sqlite3_finalize(stmt);
stmt = 0;
if (r != SQLITE_OK) {
printf("could not prepare statement: %s\n", sqlite3_errmsg(db));
}
}
}
void
SqliteIndexWriter::addStream(const Indexable* idx, const string& fieldname,
StreamBase<wchar_t>* datastream) {
}
void
SqliteIndexWriter::addField(const Indexable* idx, const string &fieldname,
const string& value) {
int64_t id = idx->getId();
//id = -1; // debug
if (id == -1) return;
if (fieldname == "content") {
// find a pointer to the value
map<int64_t, map<string, int> >::iterator m = content.find(id);
if (m == content.end()) {
// no value at all yet, so fine to add one
content[id][value]++;
} else if (m->second.size() >= 1000) {
map<string, int>::iterator i = m->second.find(value);
if (i != m->second.end()) {
i->second++;
}
} else {
content[id][value]++;
}
return;
}
sqlite3_bind_int64(insertvaluestmt, 1, idx->getId());
sqlite3_bind_text(insertvaluestmt, 2, fieldname.c_str(),
fieldname.length(), SQLITE_STATIC);
sqlite3_bind_text(insertvaluestmt, 3, value.c_str(), value.length(),
SQLITE_STATIC);
int r = sqlite3_step(insertvaluestmt);
if (r != SQLITE_DONE) {
printf("could not write into database: %i %s\n", r, sqlite3_errmsg(db));
}
r = sqlite3_reset(insertvaluestmt);
if (r != SQLITE_OK) {
printf("could not reset statement: %i %s\n", r, sqlite3_errmsg(db));
}
temprows++;
}
void
SqliteIndexWriter::setField(const Indexable*, const std::string &fieldname,
int64_t value) {
}
void
SqliteIndexWriter::startIndexable(Indexable* idx) {
// get the file name
const char* name = idx->getName().c_str();
size_t namelen = idx->getName().length();
manager->ref();
int64_t id = -1;
setIndexed(idx, false);
sqlite3_bind_text(insertfilestmt, 1, name, namelen, SQLITE_STATIC);
sqlite3_bind_int64(insertfilestmt, 2, idx->getMTime());
sqlite3_bind_int(insertfilestmt, 3, idx->getDepth());
int r = sqlite3_step(insertfilestmt);
if (r != SQLITE_DONE) {
printf("error in adding file %i %s\n", r, sqlite3_errmsg(db));
}
id = sqlite3_last_insert_rowid(db);
sqlite3_reset(insertfilestmt);
idx->setId(id);
manager->deref();
}
/*
Close all left open indexwriters for this path.
*/
void
SqliteIndexWriter::finishIndexable(const Indexable* idx) {
// store the content field
map<int64_t, map<string, int> >::const_iterator m
= content.find(idx->getId());
if (m == content.end()) {
if (temprows > maxtemprows) commit();
return;
}
sqlite3_stmt* stmt;
int r = sqlite3_prepare(db,
"insert into tempfilewords (fileid, word, count) values(?, ?,?);",
0, &stmt, 0);
if (r != SQLITE_OK) {
if (idx->getDepth() == 0) {
sqlite3_exec(db, "rollback; ", 0, 0, 0);
}
printf("could not prepare temp insert sql %s\n", sqlite3_errmsg(db));
content.erase(m->first);
manager->deref();
return;
}
map<string, int>::const_iterator i = m->second.begin();
map<string, int>::const_iterator e = m->second.end();
sqlite3_bind_int64(stmt, 1, idx->getId());
for (; i!=e; ++i) {
sqlite3_bind_text(stmt, 2, i->first.c_str(), i->first.length(),
SQLITE_STATIC);
sqlite3_bind_int(stmt, 3, i->second);
r = sqlite3_step(stmt);
if (r != SQLITE_DONE) {
printf("could not write content into database: %i %s\n", r,
sqlite3_errmsg(db));
}
r = sqlite3_reset(stmt);
temprows++;
}
sqlite3_finalize(stmt);
if (temprows > maxtemprows) commit();
content.erase(m->first);
}
void
SqliteIndexWriter::commit() {
printf("start commit\n");
// move the data from the temp tables into the index
const char* sql = "replace into words (wordid, word, count) "
"select wordid, t.word, sum(t.count)+ifnull(words.count,0) "
"from tempfilewords t left join words on t.word = words.word "
"group by t.word; "
"insert into filewords (fileid, wordid, count) "
"select fileid, words.wordid, t.count from tempfilewords t join words "
"on t.word = words.word;"
"replace into idx select * from tempidx;"
"delete from tempidx;"
"delete from tempfilewords;"
"commit;"
"begin immediate transaction;";
manager->ref();
int r = sqlite3_exec(db, sql, 0, 0, 0);
if (r != SQLITE_OK) {
printf("could not store new data: %s\n", sqlite3_errmsg(db));
}
manager->deref();
printf("end commit\n");
temprows = 0;
}
void
SqliteIndexWriter::deleteEntry(const string& path) {
if (temprows) commit();
int64_t id = -1;
manager->ref();
int r = sqlite3_bind_text(getfilestmt, 1, path.c_str(), path.length(),
SQLITE_STATIC);
r = sqlite3_step(getfilestmt);
if (r != SQLITE_ROW) {
printf("could not find file %s:\n", path.c_str());
sqlite3_reset(getfilestmt);
manager->deref();
return;
}
id = sqlite3_column_int64(getfilestmt, 0);
sqlite3_reset(getfilestmt);
ostringstream sql;
sql << "delete from idx where fileid = " << id
<< "; delete from filewords where fileid = " << id
<< "; delete from files where fileid = " << id;
r = sqlite3_exec(db, sql.str().c_str(), 0, 0, 0);
if (r != SQLITE_OK) {
printf("could not delete file %s: %s\n", path.c_str(),
sqlite3_errmsg(db));
}
manager->deref();
}
<|endoftext|> |
<commit_before>/**
* This file is part of Slideshow.
* Copyright (C) 2008 David Sveningsson <ext@sidvind.com>
*
* Slideshow is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Slideshow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Browser.h"
#include <cstdio>
#include <cstring>
#include <cstdlib>
static const int state_provider = 0;
static const int state_user = 1;
static const int state_pass = 2;
static const int state_host = 3;
static const int state_name = 4;
void allocate_context(browser_context_t& context, size_t provider, size_t user, size_t pass, size_t host, size_t name);
static int extract_part(char* dst, const char* src, int offset, int n){
if ( n == 0 ){
return offset;
}
strncpy(dst, &src[offset], n);
dst[n] = '\0';
// We move the offset past the extracted string AND the delimiter.
return offset + n + 1;
}
browser_context_t get_context(const char* string){
int part_len[5] = { 0, 0, 0, 0, 0 };
size_t string_len = strlen(string);
unsigned int state = state_provider;
for ( unsigned int i = 0; i < string_len; i++ ){
char ch = string[i];
switch ( state ){
case state_provider:
if ( ch == ':' ){
i += 2; // offset to move past :// delimiter
state = state_user;
continue;
}
break;
case state_user:
if ( ch == ':' ){
state = state_pass;
continue;
}
if ( ch == '@' ){
state = state_host;
continue;
}
break;
case state_pass:
if ( ch == '@' ){
state = state_host;
continue;
}
break;
case state_host:
if ( ch == '/' ){
state = state_name;
continue;
}
break;
}
part_len[state]++;
}
browser_context_t context;
allocate_context(context,
part_len[state_provider],
part_len[state_user],
part_len[state_pass],
part_len[state_host],
part_len[state_name]
);
int offset = 0;
offset = extract_part(context.provider, string, offset, part_len[state_provider]) + 2; // The first delimiter is 2 extra characters wide
offset = extract_part(context.user, string, offset, part_len[state_user]);
offset = extract_part(context.pass, string, offset, part_len[state_pass]);
offset = extract_part(context.host, string, offset, part_len[state_host]);
offset = extract_part(context.name, string, offset, part_len[state_name]);
return context;
}
void allocate_context(browser_context_t& context, size_t provider, size_t user, size_t pass, size_t host, size_t name){
context.provider = provider > 0 ? (char*)malloc(provider + 1) : NULL;
context.user = user > 0 ? (char*)malloc(user + 1) : NULL;
context.pass = pass > 0 ? (char*)malloc(pass + 1) : NULL;
context.host = host > 0 ? (char*)malloc(host + 1) : NULL;
context.name = name > 0 ? (char*)malloc(name + 1) : NULL;
}
void free_context(browser_context_t& context){
free(context.provider);
free(context.user);
free(context.pass);
free(context.host);
free(context.name);
}
<commit_msg>including win32.h to get SE functions<commit_after>/**
* This file is part of Slideshow.
* Copyright (C) 2008 David Sveningsson <ext@sidvind.com>
*
* Slideshow is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Slideshow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Browser.h"
#include <cstdio>
#include <cstring>
#include <cstdlib>
#ifdef WIN32
# include "win32.h"
#endif
static const int state_provider = 0;
static const int state_user = 1;
static const int state_pass = 2;
static const int state_host = 3;
static const int state_name = 4;
void allocate_context(browser_context_t& context, size_t provider, size_t user, size_t pass, size_t host, size_t name);
static int extract_part(char* dst, const char* src, int offset, int n){
if ( n == 0 ){
return offset;
}
strncpy(dst, &src[offset], n);
dst[n] = '\0';
// We move the offset past the extracted string AND the delimiter.
return offset + n + 1;
}
browser_context_t get_context(const char* string){
int part_len[5] = { 0, 0, 0, 0, 0 };
size_t string_len = strlen(string);
unsigned int state = state_provider;
for ( unsigned int i = 0; i < string_len; i++ ){
char ch = string[i];
switch ( state ){
case state_provider:
if ( ch == ':' ){
i += 2; // offset to move past :// delimiter
state = state_user;
continue;
}
break;
case state_user:
if ( ch == ':' ){
state = state_pass;
continue;
}
if ( ch == '@' ){
state = state_host;
continue;
}
break;
case state_pass:
if ( ch == '@' ){
state = state_host;
continue;
}
break;
case state_host:
if ( ch == '/' ){
state = state_name;
continue;
}
break;
}
part_len[state]++;
}
browser_context_t context;
allocate_context(context,
part_len[state_provider],
part_len[state_user],
part_len[state_pass],
part_len[state_host],
part_len[state_name]
);
int offset = 0;
offset = extract_part(context.provider, string, offset, part_len[state_provider]) + 2; // The first delimiter is 2 extra characters wide
offset = extract_part(context.user, string, offset, part_len[state_user]);
offset = extract_part(context.pass, string, offset, part_len[state_pass]);
offset = extract_part(context.host, string, offset, part_len[state_host]);
offset = extract_part(context.name, string, offset, part_len[state_name]);
return context;
}
void allocate_context(browser_context_t& context, size_t provider, size_t user, size_t pass, size_t host, size_t name){
context.provider = provider > 0 ? (char*)malloc(provider + 1) : NULL;
context.user = user > 0 ? (char*)malloc(user + 1) : NULL;
context.pass = pass > 0 ? (char*)malloc(pass + 1) : NULL;
context.host = host > 0 ? (char*)malloc(host + 1) : NULL;
context.name = name > 0 ? (char*)malloc(name + 1) : NULL;
}
void free_context(browser_context_t& context){
free(context.provider);
free(context.user);
free(context.pass);
free(context.host);
free(context.name);
}
<|endoftext|> |
<commit_before>//
// Created by lz on 1/21/17.
//
#ifndef C10K_SERVER_EVENT_LOOP_HPP
#define C10K_SERVER_EVENT_LOOP_HPP
#endif //C10K_SERVER_EVENT_LOOP_HPP
#include <sys/epoll.h>
#include <sys/types.h>
#include <unistd.h>
#include <memory>
#include <cstdlib>
#include <unordered_map>
#include <functional>
#include <spdlog/spdlog.h>
#include <spdlog/fmt/ostr.h>
#include <mutex>
#include "utils.hpp"
namespace c10k
{
enum struct EventCategory
{
POLLIN = EPOLLIN,
POLLOUT = EPOLLOUT
};
struct EventType
{
private:
int event_type_;
public:
explicit EventType(int et):
event_type_(et)
{}
explicit EventType(EventCategory ec):
EventType((int)ec)
{}
bool is(EventCategory ec) const
{
return event_type_ & (int)ec;
}
void set(EventCategory ec)
{
event_type_ |= (int) ec;
}
void unset(EventCategory ec)
{
event_type_ &= ~ (int)ec;
}
explicit operator int() const
{
return event_type_;
}
template<typename OST>
friend OST &operator <<(OST &o, EventType et)
{
o << "[";
if (et.is(EventCategory::POLLIN))
o << " POLLIN ";
if (et.is(EventCategory::POLLOUT))
o << " POLLOUT ";
o << "]";
return o;
}
};
class EventLoop;
struct Event
{
EventLoop *event_loop;
int fd;
EventType event_type;
template<typename OST>
friend OST &operator <<(OST &o, const Event &e)
{
o << "Eventloop=" << (void*)e.event_loop << ", " <<
"fd=" << e.fd << ", " <<
"event_type=" << e.event_type;
return o;
}
};
using EventHandler = std::function<void(const Event &)>;
inline void NullEventHandler(const Event &) {}
namespace detail
{
struct PollData
{
int fd;
EventHandler handler;
PollData(int fd, EventHandler eh):
fd(fd), handler(std::move(eh))
{}
};
}
// thread-safe Eventloop run in each thread
class EventLoop
{
private:
int epollfd;
bool loop_enabled_ = true;
bool in_loop_ = false;
std::shared_ptr<spdlog::logger> logger;
std::unordered_map<int, std::unique_ptr<detail::PollData>> fd_to_poll_data;
std::mutex map_mutex;
using LoggerT = decltype(logger);
// workaround before inline var :)
static constexpr int epoll_event_buf_size()
{
return 1024;
}
void handle_events(epoll_event *st, epoll_event *ed);
public:
EventLoop(int max_event, const LoggerT &logger = spdlog::stdout_color_mt("Eventloop"));
EventLoop(const EventLoop &) = delete;
EventLoop &operator=(const EventLoop &) = delete;
void loop();
void add_event(int fd, EventType et, EventHandler handler);
void remove_event(int fd);
void modify_event(int fd, EventType et, EventHandler handler);
// whether in loop
bool in_loop() const
{
return in_loop_;
}
// whether loop is enabled
bool loop_enabled() const
{
return loop_enabled_;
}
bool enable_loop()
{
loop_enabled_ = true;
}
bool disable_loop()
{
loop_enabled_ = false;
}
};
}<commit_msg>Eventloop: Fix unused return value<commit_after>//
// Created by lz on 1/21/17.
//
#ifndef C10K_SERVER_EVENT_LOOP_HPP
#define C10K_SERVER_EVENT_LOOP_HPP
#endif //C10K_SERVER_EVENT_LOOP_HPP
#include <sys/epoll.h>
#include <sys/types.h>
#include <unistd.h>
#include <memory>
#include <cstdlib>
#include <unordered_map>
#include <functional>
#include <spdlog/spdlog.h>
#include <spdlog/fmt/ostr.h>
#include <mutex>
#include "utils.hpp"
namespace c10k
{
enum struct EventCategory
{
POLLIN = EPOLLIN,
POLLOUT = EPOLLOUT
};
struct EventType
{
private:
int event_type_;
public:
explicit EventType(int et):
event_type_(et)
{}
explicit EventType(EventCategory ec):
EventType((int)ec)
{}
bool is(EventCategory ec) const
{
return event_type_ & (int)ec;
}
void set(EventCategory ec)
{
event_type_ |= (int) ec;
}
void unset(EventCategory ec)
{
event_type_ &= ~ (int)ec;
}
explicit operator int() const
{
return event_type_;
}
template<typename OST>
friend OST &operator <<(OST &o, EventType et)
{
o << "[";
if (et.is(EventCategory::POLLIN))
o << " POLLIN ";
if (et.is(EventCategory::POLLOUT))
o << " POLLOUT ";
o << "]";
return o;
}
};
class EventLoop;
struct Event
{
EventLoop *event_loop;
int fd;
EventType event_type;
template<typename OST>
friend OST &operator <<(OST &o, const Event &e)
{
o << "Eventloop=" << (void*)e.event_loop << ", " <<
"fd=" << e.fd << ", " <<
"event_type=" << e.event_type;
return o;
}
};
using EventHandler = std::function<void(const Event &)>;
inline void NullEventHandler(const Event &) {}
namespace detail
{
struct PollData
{
int fd;
EventHandler handler;
PollData(int fd, EventHandler eh):
fd(fd), handler(std::move(eh))
{}
};
}
// thread-safe Eventloop run in each thread
class EventLoop
{
private:
int epollfd;
bool loop_enabled_ = true;
bool in_loop_ = false;
std::shared_ptr<spdlog::logger> logger;
std::unordered_map<int, std::unique_ptr<detail::PollData>> fd_to_poll_data;
std::mutex map_mutex;
using LoggerT = decltype(logger);
// workaround before inline var :)
static constexpr int epoll_event_buf_size()
{
return 1024;
}
void handle_events(epoll_event *st, epoll_event *ed);
public:
EventLoop(int max_event, const LoggerT &logger = spdlog::stdout_color_mt("Eventloop"));
EventLoop(const EventLoop &) = delete;
EventLoop &operator=(const EventLoop &) = delete;
void loop();
void add_event(int fd, EventType et, EventHandler handler);
void remove_event(int fd);
void modify_event(int fd, EventType et, EventHandler handler);
// whether in loop
bool in_loop() const
{
return in_loop_;
}
// whether loop is enabled
bool loop_enabled() const
{
return loop_enabled_;
}
void enable_loop()
{
loop_enabled_ = true;
}
void disable_loop()
{
loop_enabled_ = false;
}
};
}<|endoftext|> |
<commit_before>/*
* Copyright 2007-2022 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* 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.
*
* 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
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "AcmeAlpn.hxx"
#include "AcmeHttp.hxx"
#include "AcmeChallenge.hxx"
#include "CertDatabase.hxx"
#include "WrapKey.hxx"
#include "lib/openssl/Dummy.hxx"
#include "lib/openssl/Error.hxx"
#include "lib/openssl/Edit.hxx"
#include "lib/openssl/Key.hxx"
#include "lib/sodium/UrlSafeBase64SHA256.hxx"
#include "util/ConstBuffer.hxx"
#include "util/PrintException.hxx"
#include "util/ScopeExit.hxx"
#include <boost/json.hpp>
[[gnu::const]]
static int
GetAcmeIndentifierObjectId() noexcept
{
const char *const txt = "1.3.6.1.5.5.7.1.31";
if (int id = OBJ_txt2nid(txt); id != NID_undef)
return id;
return OBJ_create(txt, "pe-acmeIdentifier", "ACME Identifier");
}
[[gnu::pure]]
static inline auto
SHA256(std::string_view src) noexcept
{
return SHA256(ConstBuffer<void>{src.data(), src.size()});
}
Alpn01ChallengeRecord::Alpn01ChallengeRecord(CertDatabase &_db,
const std::string &_host)
:db(_db), host(_host),
handle(std::string{"acme-tls-alpn-01:"} + host)
{
std::string alt_name = std::string{"DNS:"} + host;
cert = MakeSelfIssuedDummyCert(host.c_str());
AddExt(*cert, NID_subject_alt_name, alt_name.c_str());
}
Alpn01ChallengeRecord::~Alpn01ChallengeRecord() noexcept
{
try {
db.DeleteServerCertificateByHandle(handle.c_str());
} catch (...) {
fprintf(stderr, "Failed to remove certdb record of '%s': ",
host.c_str());
PrintException(std::current_exception());
}
}
void
Alpn01ChallengeRecord::AddChallenge(const AcmeChallenge &challenge,
EVP_PKEY &account_key)
{
struct {
uint8_t type = 0x04, size;
SHA256Digest payload;
} value;
value.size = sizeof(value.payload);
value.payload = SHA256(MakeHttp01(challenge, account_key));
const int nid = GetAcmeIndentifierObjectId();
auto *s = ASN1_OCTET_STRING_new();
ASN1_OCTET_STRING_set(s, (const unsigned char *)&value,
sizeof(value));
AtScopeExit(s) { ASN1_OCTET_STRING_free(s); };
auto *ext = X509_EXTENSION_create_by_NID(nullptr, nid, 1, s);
AtScopeExit(ext) { X509_EXTENSION_free(ext); };
X509_add_ext(cert.get(), ext, -1);
}
void
Alpn01ChallengeRecord::Commit(const CertDatabaseConfig &db_config)
{
const auto cert_key = GenerateRsaKey();
X509_set_pubkey(cert.get(), cert_key.get());
if (!X509_sign(cert.get(), cert_key.get(), EVP_sha1()))
throw SslError("X509_sign() failed");
WrapKeyHelper wrap_key_helper;
const auto wrap_key = wrap_key_helper.SetEncryptKey(db_config);
db.LoadServerCertificate(handle.c_str(), "acme-alpn-tls-01",
*cert, *cert_key,
wrap_key.first, wrap_key.second);
db.NotifyModified();
}
<commit_msg>certdb/AcmeAlpn: fix typo in function name<commit_after>/*
* Copyright 2007-2022 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* 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.
*
* 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
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "AcmeAlpn.hxx"
#include "AcmeHttp.hxx"
#include "AcmeChallenge.hxx"
#include "CertDatabase.hxx"
#include "WrapKey.hxx"
#include "lib/openssl/Dummy.hxx"
#include "lib/openssl/Error.hxx"
#include "lib/openssl/Edit.hxx"
#include "lib/openssl/Key.hxx"
#include "lib/sodium/UrlSafeBase64SHA256.hxx"
#include "util/ConstBuffer.hxx"
#include "util/PrintException.hxx"
#include "util/ScopeExit.hxx"
#include <boost/json.hpp>
[[gnu::const]]
static int
GetAcmeIdentifierObjectId() noexcept
{
const char *const txt = "1.3.6.1.5.5.7.1.31";
if (int id = OBJ_txt2nid(txt); id != NID_undef)
return id;
return OBJ_create(txt, "pe-acmeIdentifier", "ACME Identifier");
}
[[gnu::pure]]
static inline auto
SHA256(std::string_view src) noexcept
{
return SHA256(ConstBuffer<void>{src.data(), src.size()});
}
Alpn01ChallengeRecord::Alpn01ChallengeRecord(CertDatabase &_db,
const std::string &_host)
:db(_db), host(_host),
handle(std::string{"acme-tls-alpn-01:"} + host)
{
std::string alt_name = std::string{"DNS:"} + host;
cert = MakeSelfIssuedDummyCert(host.c_str());
AddExt(*cert, NID_subject_alt_name, alt_name.c_str());
}
Alpn01ChallengeRecord::~Alpn01ChallengeRecord() noexcept
{
try {
db.DeleteServerCertificateByHandle(handle.c_str());
} catch (...) {
fprintf(stderr, "Failed to remove certdb record of '%s': ",
host.c_str());
PrintException(std::current_exception());
}
}
void
Alpn01ChallengeRecord::AddChallenge(const AcmeChallenge &challenge,
EVP_PKEY &account_key)
{
struct {
uint8_t type = 0x04, size;
SHA256Digest payload;
} value;
value.size = sizeof(value.payload);
value.payload = SHA256(MakeHttp01(challenge, account_key));
const int nid = GetAcmeIdentifierObjectId();
auto *s = ASN1_OCTET_STRING_new();
ASN1_OCTET_STRING_set(s, (const unsigned char *)&value,
sizeof(value));
AtScopeExit(s) { ASN1_OCTET_STRING_free(s); };
auto *ext = X509_EXTENSION_create_by_NID(nullptr, nid, 1, s);
AtScopeExit(ext) { X509_EXTENSION_free(ext); };
X509_add_ext(cert.get(), ext, -1);
}
void
Alpn01ChallengeRecord::Commit(const CertDatabaseConfig &db_config)
{
const auto cert_key = GenerateRsaKey();
X509_set_pubkey(cert.get(), cert_key.get());
if (!X509_sign(cert.get(), cert_key.get(), EVP_sha1()))
throw SslError("X509_sign() failed");
WrapKeyHelper wrap_key_helper;
const auto wrap_key = wrap_key_helper.SetEncryptKey(db_config);
db.LoadServerCertificate(handle.c_str(), "acme-alpn-tls-01",
*cert, *cert_key,
wrap_key.first, wrap_key.second);
db.NotifyModified();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparamsbase.h"
#include "util.h"
#include <assert.h>
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
/**
* Main network
*/
class CBaseMainParams : public CBaseChainParams
{
public:
CBaseMainParams()
{
networkID = CBaseChainParams::MAIN;
nRPCPort = 8372;
}
};
static CBaseMainParams mainParams;
/**
* Testnet (v3)
*/
class CBaseTestNetParams : public CBaseMainParams
{
public:
CBaseTestNetParams()
{
networkID = CBaseChainParams::TESTNET;
nRPCPort = 18372;
strDataDir = "testnet3";
}
};
static CBaseTestNetParams testNetParams;
/*
* Regression test
*/
class CBaseRegTestParams : public CBaseTestNetParams
{
public:
CBaseRegTestParams()
{
networkID = CBaseChainParams::REGTEST;
strDataDir = "regtest";
}
};
static CBaseRegTestParams regTestParams;
/*
* Unit test
*/
class CBaseUnitTestParams : public CBaseMainParams
{
public:
CBaseUnitTestParams()
{
networkID = CBaseChainParams::UNITTEST;
strDataDir = "unittest";
}
};
static CBaseUnitTestParams unitTestParams;
static CBaseChainParams* pCurrentBaseParams = 0;
const CBaseChainParams& BaseParams()
{
assert(pCurrentBaseParams);
return *pCurrentBaseParams;
}
void SelectBaseParams(CBaseChainParams::Network network)
{
switch (network) {
case CBaseChainParams::MAIN:
pCurrentBaseParams = &mainParams;
break;
case CBaseChainParams::TESTNET:
pCurrentBaseParams = &testNetParams;
break;
case CBaseChainParams::REGTEST:
pCurrentBaseParams = ®TestParams;
break;
case CBaseChainParams::UNITTEST:
pCurrentBaseParams = &unitTestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
CBaseChainParams::Network NetworkIdFromCommandLine()
{
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", true);
if (fTestNet && fRegTest)
return CBaseChainParams::MAX_NETWORK_TYPES;
if (fRegTest)
return CBaseChainParams::REGTEST;
if (fTestNet)
return CBaseChainParams::TESTNET;
return CBaseChainParams::MAIN;
}
bool SelectBaseParamsFromCommandLine()
{
CBaseChainParams::Network network = NetworkIdFromCommandLine();
if (network == CBaseChainParams::MAX_NETWORK_TYPES)
return false;
SelectBaseParams(network);
return true;
}
bool AreBaseParamsConfigured()
{
return pCurrentBaseParams != NULL;
}
<commit_msg>Default testnet false<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparamsbase.h"
#include "util.h"
#include <assert.h>
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
/**
* Main network
*/
class CBaseMainParams : public CBaseChainParams
{
public:
CBaseMainParams()
{
networkID = CBaseChainParams::MAIN;
nRPCPort = 8372;
}
};
static CBaseMainParams mainParams;
/**
* Testnet (v3)
*/
class CBaseTestNetParams : public CBaseMainParams
{
public:
CBaseTestNetParams()
{
networkID = CBaseChainParams::TESTNET;
nRPCPort = 18372;
strDataDir = "testnet3";
}
};
static CBaseTestNetParams testNetParams;
/*
* Regression test
*/
class CBaseRegTestParams : public CBaseTestNetParams
{
public:
CBaseRegTestParams()
{
networkID = CBaseChainParams::REGTEST;
strDataDir = "regtest";
}
};
static CBaseRegTestParams regTestParams;
/*
* Unit test
*/
class CBaseUnitTestParams : public CBaseMainParams
{
public:
CBaseUnitTestParams()
{
networkID = CBaseChainParams::UNITTEST;
strDataDir = "unittest";
}
};
static CBaseUnitTestParams unitTestParams;
static CBaseChainParams* pCurrentBaseParams = 0;
const CBaseChainParams& BaseParams()
{
assert(pCurrentBaseParams);
return *pCurrentBaseParams;
}
void SelectBaseParams(CBaseChainParams::Network network)
{
switch (network) {
case CBaseChainParams::MAIN:
pCurrentBaseParams = &mainParams;
break;
case CBaseChainParams::TESTNET:
pCurrentBaseParams = &testNetParams;
break;
case CBaseChainParams::REGTEST:
pCurrentBaseParams = ®TestParams;
break;
case CBaseChainParams::UNITTEST:
pCurrentBaseParams = &unitTestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
CBaseChainParams::Network NetworkIdFromCommandLine()
{
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet && fRegTest)
return CBaseChainParams::MAX_NETWORK_TYPES;
if (fRegTest)
return CBaseChainParams::REGTEST;
if (fTestNet)
return CBaseChainParams::TESTNET;
return CBaseChainParams::MAIN;
}
bool SelectBaseParamsFromCommandLine()
{
CBaseChainParams::Network network = NetworkIdFromCommandLine();
if (network == CBaseChainParams::MAX_NETWORK_TYPES)
return false;
SelectBaseParams(network);
return true;
}
bool AreBaseParamsConfigured()
{
return pCurrentBaseParams != NULL;
}
<|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* 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.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "libtest/yatlcon.h"
#include <libtest/common.h>
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
#include <curl/curl.h>
#else
class CURL;
#endif
static void cleanup_curl(void)
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
curl_global_cleanup();
#endif
}
static void initialize_curl_startup()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (curl_global_init(CURL_GLOBAL_ALL))
{
FATAL("curl_global_init(CURL_GLOBAL_ALL) failed");
}
#endif
if (atexit(cleanup_curl))
{
FATAL("atexit() failed");
}
}
static pthread_once_t start_key_once= PTHREAD_ONCE_INIT;
static void initialize_curl(void)
{
int ret;
if ((ret= pthread_once(&start_key_once, initialize_curl_startup)) != 0)
{
FATAL(strerror(ret));
}
}
namespace libtest {
namespace http {
#define YATL_USERAGENT "YATL/1.0"
static size_t http_get_result_callback(void *ptr, size_t size, size_t nmemb, void *data)
{
vchar_t *_body= (vchar_t*)data;
_body->resize(size * nmemb);
memcpy(static_cast<void*>(&_body[0]), ptr, _body->size());
return _body->size();
}
static void init(CURL *curl, const std::string& url)
{
(void)http_get_result_callback;
(void)curl;
(void)url;
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
assert(curl);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_USERAGENT, YATL_USERAGENT);
}
#endif
}
HTTP::HTTP(const std::string& url_arg) :
_url(url_arg),
_response(0)
{
initialize_curl();
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool GET::execute()
{
(void)init;
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();
init(curl, url());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&_body);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return bool(retref == CURLE_OK);
}
#endif
return false;
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool POST::execute()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();;
init(curl, url());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, _body.size());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, (void *)&_body[0]);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return bool(retref == CURLE_OK);
}
#endif
return false;
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool TRACE::execute()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();;
init(curl, url());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "TRACE");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&_body[0]);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return retref == CURLE_OK;
}
#endif
return false;
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool HEAD::execute()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();
init(curl, url());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "HEAD");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return retref == CURLE_OK;
}
#endif
return false;
}
#pragma GCC diagnostic pop
} // namespace http
} // namespace libtest
<commit_msg>Issue 278: Fix crashing in libtest/http.cc when '-Wp,-D_GLIBCXX_ASSERTIONS' is given<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* 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.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "libtest/yatlcon.h"
#include <libtest/common.h>
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
#include <curl/curl.h>
#else
class CURL;
#endif
static void cleanup_curl(void)
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
curl_global_cleanup();
#endif
}
static void initialize_curl_startup()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (curl_global_init(CURL_GLOBAL_ALL))
{
FATAL("curl_global_init(CURL_GLOBAL_ALL) failed");
}
#endif
if (atexit(cleanup_curl))
{
FATAL("atexit() failed");
}
}
static pthread_once_t start_key_once= PTHREAD_ONCE_INIT;
static void initialize_curl(void)
{
int ret;
if ((ret= pthread_once(&start_key_once, initialize_curl_startup)) != 0)
{
FATAL(strerror(ret));
}
}
namespace libtest {
namespace http {
#define YATL_USERAGENT "YATL/1.0"
static size_t http_get_result_callback(void *ptr, size_t size, size_t nmemb, void *data)
{
vchar_t *_body= (vchar_t*)data;
_body->resize(size * nmemb);
if (_body->size())
{
memcpy(static_cast<void*>(&_body[0]), ptr, _body->size());
}
return _body->size();
}
static void init(CURL *curl, const std::string& url)
{
(void)http_get_result_callback;
(void)curl;
(void)url;
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
assert(curl);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_USERAGENT, YATL_USERAGENT);
}
#endif
}
HTTP::HTTP(const std::string& url_arg) :
_url(url_arg),
_response(0)
{
initialize_curl();
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool GET::execute()
{
(void)init;
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();
init(curl, url());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&_body);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return bool(retref == CURLE_OK);
}
#endif
return false;
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool POST::execute()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL && _body.size())
{
CURL *curl= curl_easy_init();;
init(curl, url());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, _body.size());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, (void *)&_body[0]);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return bool(retref == CURLE_OK);
}
#endif
return false;
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool TRACE::execute()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL && _body.size())
{
CURL *curl= curl_easy_init();;
init(curl, url());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "TRACE");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&_body[0]);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return retref == CURLE_OK;
}
#endif
return false;
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool HEAD::execute()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();
init(curl, url());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "HEAD");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return retref == CURLE_OK;
}
#endif
return false;
}
#pragma GCC diagnostic pop
} // namespace http
} // namespace libtest
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/
#include "fileiconprovider.h"
#include <QtGui/QApplication>
#include <QtGui/QStyle>
#include <QtGui/QPainter>
using namespace Core;
/*!
\class FileIconProvider
Provides icons based on file suffixes.
The class is a singleton: It's instance can be accessed via the static instance() method.
Plugins can register custom icons via registerIconSuffix(), and retrieve icons via the icon()
method.
*/
FileIconProvider *FileIconProvider::m_instance = 0;
FileIconProvider::FileIconProvider()
: m_unknownFileIcon(qApp->style()->standardIcon(QStyle::SP_FileIcon))
{
}
FileIconProvider::~FileIconProvider()
{
m_instance = 0;
}
/*!
Returns the icon associated with the file suffix in fileInfo. If there is none,
the default icon of the operating system is returned.
*/
QIcon FileIconProvider::icon(const QFileInfo &fileInfo)
{
const QString suffix = fileInfo.suffix();
QIcon icon = iconForSuffix(suffix);
if (icon.isNull()) {
// Get icon from OS and store it in the cache
// Disabled since for now we'll make sure that all icons fit with our
// own custom icons by returning an empty one if we don't know it.
#ifdef Q_WS_WIN
// This is incorrect if the OS does not always return the same icon for the
// same suffix (Mac OS X), but should speed up the retrieval a lot ...
icon = m_systemIconProvider.icon(fileInfo);
if (!suffix.isEmpty())
registerIconOverlayForSuffix(icon, suffix);
#else
if (fileInfo.isDir()) {
icon = m_systemIconProvider.icon(fileInfo);
} else {
icon = m_unknownFileIcon;
}
#endif
}
return icon;
}
// Creates a pixmap with baseicon at size and overlayous overlayIcon over it.
QPixmap FileIconProvider::overlayIcon(QStyle::StandardPixmap baseIcon, const QIcon &overlayIcon, const QSize &size) const
{
QPixmap iconPixmap = qApp->style()->standardIcon(baseIcon).pixmap(size);
QPainter painter(&iconPixmap);
painter.drawPixmap(0, 0, overlayIcon.pixmap(size));
painter.end();
return iconPixmap;
}
/*!
Registers an icon for a given suffix, overlaying the system file icon
*/
void FileIconProvider::registerIconOverlayForSuffix(const QIcon &icon, const QString &suffix)
{
QPixmap fileIconPixmap = overlayIcon(QStyle::SP_FileIcon, icon, QSize(16, 16));
// delete old icon, if it exists
QList<QPair<QString,QIcon> >::iterator iter = m_cache.begin();
for (; iter != m_cache.end(); ++iter) {
if ((*iter).first == suffix) {
iter = m_cache.erase(iter);
break;
}
}
QPair<QString,QIcon> newEntry(suffix, fileIconPixmap);
m_cache.append(newEntry);
}
/*!
Returns an icon for the given suffix, or an empty one if none registered.
*/
QIcon FileIconProvider::iconForSuffix(const QString &suffix) const
{
QIcon icon;
#ifndef Q_WS_WIN // On windows we use the file system icons
if (suffix.isEmpty())
return icon;
QList<QPair<QString,QIcon> >::const_iterator iter = m_cache.constBegin();
for (; iter != m_cache.constEnd(); ++iter) {
if ((*iter).first == suffix) {
icon = (*iter).second;
break;
}
}
#endif
return icon;
}
/*!
Returns the sole instance of FileIconProvider.
*/
FileIconProvider *FileIconProvider::instance()
{
if (!m_instance)
m_instance = new FileIconProvider;
return m_instance;
}
<commit_msg>Removed warning on Windows<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/
#include "fileiconprovider.h"
#include <QtGui/QApplication>
#include <QtGui/QStyle>
#include <QtGui/QPainter>
using namespace Core;
/*!
\class FileIconProvider
Provides icons based on file suffixes.
The class is a singleton: It's instance can be accessed via the static instance() method.
Plugins can register custom icons via registerIconSuffix(), and retrieve icons via the icon()
method.
*/
FileIconProvider *FileIconProvider::m_instance = 0;
FileIconProvider::FileIconProvider()
: m_unknownFileIcon(qApp->style()->standardIcon(QStyle::SP_FileIcon))
{
}
FileIconProvider::~FileIconProvider()
{
m_instance = 0;
}
/*!
Returns the icon associated with the file suffix in fileInfo. If there is none,
the default icon of the operating system is returned.
*/
QIcon FileIconProvider::icon(const QFileInfo &fileInfo)
{
const QString suffix = fileInfo.suffix();
QIcon icon = iconForSuffix(suffix);
if (icon.isNull()) {
// Get icon from OS and store it in the cache
// Disabled since for now we'll make sure that all icons fit with our
// own custom icons by returning an empty one if we don't know it.
#ifdef Q_WS_WIN
// This is incorrect if the OS does not always return the same icon for the
// same suffix (Mac OS X), but should speed up the retrieval a lot ...
icon = m_systemIconProvider.icon(fileInfo);
if (!suffix.isEmpty())
registerIconOverlayForSuffix(icon, suffix);
#else
if (fileInfo.isDir()) {
icon = m_systemIconProvider.icon(fileInfo);
} else {
icon = m_unknownFileIcon;
}
#endif
}
return icon;
}
// Creates a pixmap with baseicon at size and overlayous overlayIcon over it.
QPixmap FileIconProvider::overlayIcon(QStyle::StandardPixmap baseIcon, const QIcon &overlayIcon, const QSize &size) const
{
QPixmap iconPixmap = qApp->style()->standardIcon(baseIcon).pixmap(size);
QPainter painter(&iconPixmap);
painter.drawPixmap(0, 0, overlayIcon.pixmap(size));
painter.end();
return iconPixmap;
}
/*!
Registers an icon for a given suffix, overlaying the system file icon
*/
void FileIconProvider::registerIconOverlayForSuffix(const QIcon &icon, const QString &suffix)
{
QPixmap fileIconPixmap = overlayIcon(QStyle::SP_FileIcon, icon, QSize(16, 16));
// delete old icon, if it exists
QList<QPair<QString,QIcon> >::iterator iter = m_cache.begin();
for (; iter != m_cache.end(); ++iter) {
if ((*iter).first == suffix) {
iter = m_cache.erase(iter);
break;
}
}
QPair<QString,QIcon> newEntry(suffix, fileIconPixmap);
m_cache.append(newEntry);
}
/*!
Returns an icon for the given suffix, or an empty one if none registered.
*/
QIcon FileIconProvider::iconForSuffix(const QString &suffix) const
{
QIcon icon;
#ifdef Q_WS_WIN // On windows we use the file system icons
Q_UNUSED(suffix)
#else
if (suffix.isEmpty())
return icon;
QList<QPair<QString,QIcon> >::const_iterator iter = m_cache.constBegin();
for (; iter != m_cache.constEnd(); ++iter) {
if ((*iter).first == suffix) {
icon = (*iter).second;
break;
}
}
#endif
return icon;
}
/*!
Returns the sole instance of FileIconProvider.
*/
FileIconProvider *FileIconProvider::instance()
{
if (!m_instance)
m_instance = new FileIconProvider;
return m_instance;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015-2018 Dubalu LLC. All rights reserved.
*
* 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 "exception.h"
#include "config.h" // for XAPIAND_TRACEBACKS
#include <cstdlib> // for free
#include <cstring> // for strtok_r
#include <cxxabi.h> // for abi::__cxa_demangle
#include <dlfcn.h> // for dladdr
#ifdef HAVE_EXECINFO_H
#include <execinfo.h> // for backtrace
#else
static inline int backtrace(void**, int) { return 0; }
#endif
#include "likely.h"
#define BUFFER_SIZE 1024
#ifdef __APPLE__
#include <util.h> // for forkpty
#include <unistd.h> // for execlp
#include <termios.h> // for termios, cfmakeraw
#include <sys/select.h> // for select
/* Use `atos` to do symbol lookup, can lookup non-dynamic symbols and also line
* numbers. This function is more complicated than you'd expect because `atos`
* doesn't flush after each line, so plain pipe() or socketpair() won't work
* until we close the write side. But the whole point is we want to keep `atos`
* around so we don't have to reprocess the symbol table over and over. What we
* wind up doing is using `forkpty()` to make a new pseudoterminal for atos to
* run in, and thus will use line-buffering for stdout, and then we can get
* each line.
*/
static std::string
atos(const void* address)
{
char tmp[20];
static int fd = -1;
if (fd == -1) {
Dl_info info;
memset(&info, 0, sizeof(Dl_info));
if (dladdr(reinterpret_cast<const void*>(&atos), &info) == 0) {
perror("Could not get base address for `atos`.");
return "";
}
struct termios term_opts;
cfmakeraw(&term_opts); // have to set this first, otherwise queries echo until child kicks in
pid_t childpid;
if unlikely((childpid = forkpty(&fd, nullptr, &term_opts, nullptr)) < 0) {
perror("Could not forkpty for `atos` call.");
return "";
}
if (childpid == 0) {
snprintf(tmp, sizeof(tmp), "%p", static_cast<const void *>(info.dli_fbase));
execlp("/usr/bin/atos", "atos", "-o", info.dli_fname, "-l", tmp, nullptr);
fprintf(stderr,"Could not exec `atos` for stack trace!\n");
exit(1);
}
int size = snprintf(tmp, sizeof(tmp), "%p\n", address);
write(fd, tmp, size);
// atos can take a while to parse symbol table on first request, which
// is why we leave it running if we see a delay, explain what's going on...
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
struct timeval tv = {3, 0};
int err = select(fd + 1, &fds, nullptr, nullptr, &tv);
if unlikely(err < 0) {
perror("Generating... first call takes some time for `atos` to cache the symbol table.");
} else if (err == 0) { // timeout
fprintf(stderr, "Generating... first call takes some time for `atos` to cache the symbol table.\n");
}
} else {
int size = snprintf(tmp, sizeof(tmp), "%p\n", address);
write(fd, tmp, size);
}
const unsigned int MAXLINE = 1024;
char line[MAXLINE];
char c = '\0';
size_t nread = 0;
while (c != '\n' && nread < MAXLINE) {
if unlikely(read(fd, &c, 1) <= 0) {
perror("Lost `atos` connection.");
close(fd);
fd = -1;
return "";
}
if (c != '\n') {
line[nread++] = c;
}
}
if (nread < MAXLINE) {
return std::string(line, nread);
}
fprintf(stderr, "Line read from `atos` was too long.\n");
return "";
}
#else
static inline std::string
atos(const void*)
{
return "";
}
#endif
std::string
traceback(const char* function, const char* filename, int line, void *const * callstack, int frames, int skip = 1)
{
char tmp[20];
std::string tb = "\n== Traceback (most recent call first): ";
tb.append(filename);
tb.push_back(':');
tb.append(std::to_string(line));
tb.append(" at ");
tb.append(function);
if (frames < 2) {
return tb;
}
tb.push_back(':');
// Iterate over the callstack. Skip the first, it is the address of this function.
std::string result;
for (int i = skip; i < frames; ++i) {
auto address = callstack[i];
result.assign(std::to_string(frames - i - 1));
result.push_back(' ');
auto address_string = atos(address);
if (address_string.size() > 2 && address_string.compare(0, 2, "0x") != 0) {
result.append(address_string);
} else {
Dl_info info;
memset(&info, 0, sizeof(Dl_info));
if (dladdr(address, &info) != 0) {
// Address:
snprintf(tmp, sizeof(tmp), "%p ", address);
result.append(tmp);
// Symbol name:
if (info.dli_sname != nullptr) {
int status = 0;
char* unmangled = abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, &status);
if (status != 0) {
result.append(info.dli_sname);
} else {
try {
result.append(unmangled);
free(unmangled);
} catch(...) {
free(unmangled);
throw;
}
}
} else {
result.append("[unknown symbol]");
}
// Offset:
snprintf(tmp, sizeof(tmp), " + %zu", static_cast<const char*>(address) - static_cast<const char*>(info.dli_saddr));
result.append(tmp);
} else {
snprintf(tmp, sizeof(tmp), "%p [unknown symbol]", address);
result.append(tmp);
}
}
tb.append("\n ");
tb.append(result);
}
return tb;
}
std::string
traceback(const char* function, const char* filename, int line, int skip)
{
void* callstack[128];
// retrieve current stack addresses
int frames = backtrace(callstack, sizeof(callstack) / sizeof(void*));
auto tb = traceback(function, filename, line, callstack, frames, skip);
if (frames == 0) {
tb.append(":\n <empty, possibly corrupt>");
}
return tb;
}
extern "C" void
__assert_tb(const char* function, const char* filename, unsigned int line, const char* expression)
{
(void)fprintf(stderr, "Assertion failed: %s, function %s, file %s, line %u.%s\n",
expression, function, filename, line, traceback(function, filename, line, 2).c_str());
abort();
}
BaseException::BaseException()
: line{0},
callstack{{}},
frames{0}
{ }
BaseException::BaseException(const BaseException& exc)
: type{exc.type},
function{exc.function},
filename{exc.filename},
line{exc.line},
frames{exc.frames},
message{exc.message},
context{exc.context},
traceback{exc.traceback}
{
memcpy(callstack, exc.callstack, frames * sizeof(void*));
}
BaseException::BaseException(BaseException&& exc)
: type{std::move(exc.type)},
function{std::move(exc.function)},
filename{std::move(exc.filename)},
line{std::move(exc.line)},
callstack{std::move(exc.callstack)},
frames{std::move(exc.frames)},
message{std::move(exc.message)},
context{std::move(exc.context)},
traceback{std::move(exc.traceback)}
{ }
BaseException::BaseException(const BaseException* exc)
: BaseException(exc != nullptr ? *exc : BaseException())
{ }
BaseException::BaseException(BaseException::private_ctor, const BaseException& exc, const char *function_, const char *filename_, int line_, const char* type, std::string_view format, VFPRINTF_ARGS args)
: type(type),
function(function_),
filename(filename_),
line(line_),
frames(0),
message(VSPRINTF(format, args))
{
if (!exc.type.empty() && (exc.frames != 0u)) {
function = exc.function;
filename = exc.filename;
line = exc.line;
#ifdef XAPIAND_TRACEBACKS
frames = exc.frames;
memcpy(callstack, exc.callstack, frames * sizeof(void*));
#endif
} else {
#ifdef XAPIAND_TRACEBACKS
frames = backtrace(callstack, sizeof(callstack) / sizeof(void*));
#endif
}
}
const char*
BaseException::get_message() const
{
if (message.empty()) {
message.assign(type);
}
return message.c_str();
}
const char*
BaseException::get_context() const
{
if (context.empty()) {
context.append(filename);
context.push_back(':');
context.append(std::to_string(line));
context.append(" at ");
context.append(function);
context.append(": ");
context.append(get_message());
}
return context.c_str();
}
const char*
BaseException::get_traceback() const
{
if (traceback.empty()) {
traceback = ::traceback(function, filename, line, callstack, frames);
}
return traceback.c_str();
}
<commit_msg>Traceback: Added mutex to atos()<commit_after>/*
* Copyright (C) 2015-2018 Dubalu LLC. All rights reserved.
*
* 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 "exception.h"
#include "config.h" // for XAPIAND_TRACEBACKS
#include <cstdlib> // for free
#include <cstring> // for strtok_r
#include <cxxabi.h> // for abi::__cxa_demangle
#include <dlfcn.h> // for dladdr
#ifdef HAVE_EXECINFO_H
#include <execinfo.h> // for backtrace
#else
static inline int backtrace(void**, int) { return 0; }
#endif
#include "likely.h"
#define BUFFER_SIZE 1024
#ifdef __APPLE__
#include <util.h> // for forkpty
#include <unistd.h> // for execlp
#include <termios.h> // for termios, cfmakeraw
#include <sys/select.h> // for select
/* Use `atos` to do symbol lookup, can lookup non-dynamic symbols and also line
* numbers. This function is more complicated than you'd expect because `atos`
* doesn't flush after each line, so plain pipe() or socketpair() won't work
* until we close the write side. But the whole point is we want to keep `atos`
* around so we don't have to reprocess the symbol table over and over. What we
* wind up doing is using `forkpty()` to make a new pseudoterminal for atos to
* run in, and thus will use line-buffering for stdout, and then we can get
* each line.
*/
static std::string
atos(const void* address)
{
static std::mutex mtx;
std::lock_guard lk(mtx);
char tmp[20];
static int fd = -1;
if (fd == -1) {
Dl_info info;
memset(&info, 0, sizeof(Dl_info));
if (dladdr(reinterpret_cast<const void*>(&atos), &info) == 0) {
perror("Could not get base address for `atos`.");
return "";
}
struct termios term_opts;
cfmakeraw(&term_opts); // have to set this first, otherwise queries echo until child kicks in
pid_t childpid;
if unlikely((childpid = forkpty(&fd, nullptr, &term_opts, nullptr)) < 0) {
perror("Could not forkpty for `atos` call.");
return "";
}
if (childpid == 0) {
snprintf(tmp, sizeof(tmp), "%p", static_cast<const void *>(info.dli_fbase));
execlp("/usr/bin/atos", "atos", "-o", info.dli_fname, "-l", tmp, nullptr);
fprintf(stderr,"Could not exec `atos` for stack trace!\n");
exit(1);
}
int size = snprintf(tmp, sizeof(tmp), "%p\n", address);
write(fd, tmp, size);
// atos can take a while to parse symbol table on first request, which
// is why we leave it running if we see a delay, explain what's going on...
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
struct timeval tv = {3, 0};
int err = select(fd + 1, &fds, nullptr, nullptr, &tv);
if unlikely(err < 0) {
perror("Generating... first call takes some time for `atos` to cache the symbol table.");
} else if (err == 0) { // timeout
fprintf(stderr, "Generating... first call takes some time for `atos` to cache the symbol table.\n");
}
} else {
int size = snprintf(tmp, sizeof(tmp), "%p\n", address);
write(fd, tmp, size);
}
const unsigned int MAXLINE = 1024;
char line[MAXLINE];
char c = '\0';
size_t nread = 0;
while (c != '\n' && nread < MAXLINE) {
if unlikely(read(fd, &c, 1) <= 0) {
perror("Lost `atos` connection.");
close(fd);
fd = -1;
return "";
}
if (c != '\n') {
line[nread++] = c;
}
}
if (nread < MAXLINE) {
return std::string(line, nread);
}
fprintf(stderr, "Line read from `atos` was too long.\n");
return "";
}
#else
static inline std::string
atos(const void*)
{
return "";
}
#endif
std::string
traceback(const char* function, const char* filename, int line, void *const * callstack, int frames, int skip = 1)
{
char tmp[20];
std::string tb = "\n== Traceback (most recent call first): ";
tb.append(filename);
tb.push_back(':');
tb.append(std::to_string(line));
tb.append(" at ");
tb.append(function);
if (frames < 2) {
return tb;
}
tb.push_back(':');
// Iterate over the callstack. Skip the first, it is the address of this function.
std::string result;
for (int i = skip; i < frames; ++i) {
auto address = callstack[i];
result.assign(std::to_string(frames - i - 1));
result.push_back(' ');
auto address_string = atos(address);
if (address_string.size() > 2 && address_string.compare(0, 2, "0x") != 0) {
result.append(address_string);
} else {
Dl_info info;
memset(&info, 0, sizeof(Dl_info));
if (dladdr(address, &info) != 0) {
// Address:
snprintf(tmp, sizeof(tmp), "%p ", address);
result.append(tmp);
// Symbol name:
if (info.dli_sname != nullptr) {
int status = 0;
char* unmangled = abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, &status);
if (status != 0) {
result.append(info.dli_sname);
} else {
try {
result.append(unmangled);
free(unmangled);
} catch(...) {
free(unmangled);
throw;
}
}
} else {
result.append("[unknown symbol]");
}
// Offset:
snprintf(tmp, sizeof(tmp), " + %zu", static_cast<const char*>(address) - static_cast<const char*>(info.dli_saddr));
result.append(tmp);
} else {
snprintf(tmp, sizeof(tmp), "%p [unknown symbol]", address);
result.append(tmp);
}
}
tb.append("\n ");
tb.append(result);
}
return tb;
}
std::string
traceback(const char* function, const char* filename, int line, int skip)
{
void* callstack[128];
// retrieve current stack addresses
int frames = backtrace(callstack, sizeof(callstack) / sizeof(void*));
auto tb = traceback(function, filename, line, callstack, frames, skip);
if (frames == 0) {
tb.append(":\n <empty, possibly corrupt>");
}
return tb;
}
extern "C" void
__assert_tb(const char* function, const char* filename, unsigned int line, const char* expression)
{
(void)fprintf(stderr, "Assertion failed: %s, function %s, file %s, line %u.%s\n",
expression, function, filename, line, traceback(function, filename, line, 2).c_str());
abort();
}
BaseException::BaseException()
: line{0},
callstack{{}},
frames{0}
{ }
BaseException::BaseException(const BaseException& exc)
: type{exc.type},
function{exc.function},
filename{exc.filename},
line{exc.line},
frames{exc.frames},
message{exc.message},
context{exc.context},
traceback{exc.traceback}
{
memcpy(callstack, exc.callstack, frames * sizeof(void*));
}
BaseException::BaseException(BaseException&& exc)
: type{std::move(exc.type)},
function{std::move(exc.function)},
filename{std::move(exc.filename)},
line{std::move(exc.line)},
callstack{std::move(exc.callstack)},
frames{std::move(exc.frames)},
message{std::move(exc.message)},
context{std::move(exc.context)},
traceback{std::move(exc.traceback)}
{ }
BaseException::BaseException(const BaseException* exc)
: BaseException(exc != nullptr ? *exc : BaseException())
{ }
BaseException::BaseException(BaseException::private_ctor, const BaseException& exc, const char *function_, const char *filename_, int line_, const char* type, std::string_view format, VFPRINTF_ARGS args)
: type(type),
function(function_),
filename(filename_),
line(line_),
frames(0),
message(VSPRINTF(format, args))
{
if (!exc.type.empty() && (exc.frames != 0u)) {
function = exc.function;
filename = exc.filename;
line = exc.line;
#ifdef XAPIAND_TRACEBACKS
frames = exc.frames;
memcpy(callstack, exc.callstack, frames * sizeof(void*));
#endif
} else {
#ifdef XAPIAND_TRACEBACKS
frames = backtrace(callstack, sizeof(callstack) / sizeof(void*));
#endif
}
}
const char*
BaseException::get_message() const
{
if (message.empty()) {
message.assign(type);
}
return message.c_str();
}
const char*
BaseException::get_context() const
{
if (context.empty()) {
context.append(filename);
context.push_back(':');
context.append(std::to_string(line));
context.append(" at ");
context.append(function);
context.append(": ");
context.append(get_message());
}
return context.c_str();
}
const char*
BaseException::get_traceback() const
{
if (traceback.empty()) {
traceback = ::traceback(function, filename, line, callstack, frames);
}
return traceback.c_str();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Magnus Jonsson & Arvid Norberg
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 author 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.
*/
#include "libtorrent/file.hpp"
#include "libtorrent/utf8.hpp"
#include <sstream>
#include <windows.h>
namespace
{
// must be used to not leak memory in case something would throw
class auto_localfree
{
public:
auto_localfree(HLOCAL memory)
: m_memory(memory)
{
}
~auto_localfree()
{
if (m_memory)
LocalFree(m_memory);
}
private:
HLOCAL m_memory;
};
void throw_exception(const char* thrower)
{
int err = GetLastError();
#ifdef UNICODE
wchar_t *wbuffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPWCSTR)&wbuffer, 0, 0);
auto_localfree auto_free(wbuffer);
std::string tmp_utf8;
wchar_utf8(wbuffer, tmp_utf8);
char* buffer = tmp_utf8.c_str();
#else
char* buffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPSTR)&buffer, 0, 0);
auto_localfree auto_free(buffer);
#endif
std::stringstream s;
s << (thrower ? thrower : "NULL") << ": " << (buffer ? buffer : "NULL");
throw libtorrent::file_error(s.str());
}
}
namespace libtorrent
{
struct file::impl : boost::noncopyable
{
enum open_flags
{
read_flag = 1,
write_flag = 2
};
enum seek_mode
{
seek_begin = FILE_BEGIN,
seek_from_here = FILE_CURRENT,
seek_end = FILE_END
};
impl()
{
m_file_handle = INVALID_HANDLE_VALUE;
}
void open(const char *file_name, open_flags flags)
{
assert(file_name);
assert(flags & (read_flag | write_flag));
DWORD access_mask = 0;
if (flags & read_flag)
access_mask |= GENERIC_READ;
if (flags & write_flag)
access_mask |= GENERIC_WRITE;
assert(access_mask & (GENERIC_READ | GENERIC_WRITE));
#ifdef UNICODE
std::wstring wfile_name(utf8_wchar(file_name));
HANDLE new_handle = CreateFile(
(LPCWSTR)wfile_name.c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#else
HANDLE new_handle = CreateFile(
file_name
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#endif
if (new_handle == INVALID_HANDLE_VALUE)
{
std::stringstream s;
throw_exception(file_name);
}
// will only close old file if the open succeeded
close();
m_file_handle = new_handle;
}
void close()
{
if (m_file_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
}
}
~impl()
{
close();
}
size_type write(const char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_written = 0;
if (num_bytes != 0)
{
if (FALSE == WriteFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_written
, 0))
{
throw_exception("file::write");
}
}
return bytes_written;
}
size_type read(char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_read = 0;
if (num_bytes != 0)
{
if (FALSE == ReadFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_read
, 0))
{
throw_exception("file::read");
}
}
return bytes_read;
}
void seek(size_type pos, seek_mode from_where)
{
assert(pos >= 0 || from_where != seek_begin);
assert(pos <= 0 || from_where != seek_end);
LARGE_INTEGER offs;
offs.QuadPart = pos;
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, from_where))
{
throw_exception("file::seek");
}
}
size_type tell()
{
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, FILE_CURRENT))
{
throw_exception("file::tell");
}
size_type pos=offs.QuadPart;
assert(pos>=0);
return pos;
}
/*
size_type size()
{
LARGE_INTEGER s;
if (FALSE == GetFileSizeEx(m_file_handle, &s))
{
throw_exception("file::size");
}
size_type size = s.QuadPart;
assert(size >= 0);
return size;
}
*/
private:
HANDLE m_file_handle;
};
}
namespace libtorrent
{
const file::seek_mode file::begin(file::impl::seek_begin);
const file::seek_mode file::end(file::impl::seek_end);
const file::open_mode file::in(file::impl::read_flag);
const file::open_mode file::out(file::impl::write_flag);
file::file()
: m_impl(new libtorrent::file::impl())
{
}
file::file(boost::filesystem::path const& p, open_mode m)
: m_impl(new libtorrent::file::impl())
{
open(p,m);
}
file::~file()
{
}
void file::open(boost::filesystem::path const& p, open_mode m)
{
assert(p.is_complete());
m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask));
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buffer, size_type num_bytes)
{
return m_impl->write(buffer, num_bytes);
}
size_type file::read(char* buffer, size_type num_bytes)
{
return m_impl->read(buffer, num_bytes);
}
void file::seek(size_type pos, seek_mode m)
{
m_impl->seek(pos,impl::seek_mode(m.m_val));
}
size_type file::tell()
{
return m_impl->tell();
}
}
<commit_msg>file_win.cpp fixes<commit_after>/*
Copyright (c) 2003, Magnus Jonsson & Arvid Norberg
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 author 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.
*/
#include "libtorrent/file.hpp"
#include "libtorrent/utf8.hpp"
#include <sstream>
#include <windows.h>
namespace
{
// must be used to not leak memory in case something would throw
class auto_localfree
{
public:
auto_localfree(HLOCAL memory)
: m_memory(memory)
{
}
~auto_localfree()
{
if (m_memory)
LocalFree(m_memory);
}
private:
HLOCAL m_memory;
};
std::string utf8_native(std::string const& s)
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret(size + 1);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
ret.resize(size - 1);
return ret;
}
void throw_exception(const char* thrower)
{
DWORD err = GetLastError();
#ifdef UNICODE
wchar_t *wbuffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPWSTR)&wbuffer, 0, 0);
auto_localfree auto_free(wbuffer);
std::string tmp_utf8;
libtorrent::wchar_utf8(wbuffer, tmp_utf8);
char const* buffer = tmp_utf8.c_str();
#else
char* buffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPSTR)&buffer, 0, 0);
auto_localfree auto_free(buffer);
#endif
std::stringstream s;
s << (thrower ? thrower : "NULL") << ": " << (buffer ? buffer : "NULL");
throw libtorrent::file_error(s.str());
}
}
namespace libtorrent
{
struct file::impl : boost::noncopyable
{
enum open_flags
{
read_flag = 1,
write_flag = 2
};
enum seek_mode
{
seek_begin = FILE_BEGIN,
seek_from_here = FILE_CURRENT,
seek_end = FILE_END
};
impl()
{
m_file_handle = INVALID_HANDLE_VALUE;
}
void open(const char *file_name, open_flags flags)
{
assert(file_name);
assert(flags & (read_flag | write_flag));
DWORD access_mask = 0;
if (flags & read_flag)
access_mask |= GENERIC_READ;
if (flags & write_flag)
access_mask |= GENERIC_WRITE;
assert(access_mask & (GENERIC_READ | GENERIC_WRITE));
#ifdef UNICODE
std::wstring wfile_name(utf8_wchar(file_name));
HANDLE new_handle = CreateFile(
(LPCWSTR)wfile_name.c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#else
HANDLE new_handle = CreateFile(
utf8_native(file_name).c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#endif
if (new_handle == INVALID_HANDLE_VALUE)
{
std::stringstream s;
throw_exception(file_name);
}
// will only close old file if the open succeeded
close();
m_file_handle = new_handle;
}
void close()
{
if (m_file_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
}
}
~impl()
{
close();
}
size_type write(const char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_written = 0;
if (num_bytes != 0)
{
if (FALSE == WriteFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_written
, 0))
{
throw_exception("file::write");
}
}
return bytes_written;
}
size_type read(char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_read = 0;
if (num_bytes != 0)
{
if (FALSE == ReadFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_read
, 0))
{
throw_exception("file::read");
}
}
return bytes_read;
}
void seek(size_type pos, seek_mode from_where)
{
assert(pos >= 0 || from_where != seek_begin);
assert(pos <= 0 || from_where != seek_end);
LARGE_INTEGER offs;
offs.QuadPart = pos;
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, from_where))
{
throw_exception("file::seek");
}
}
size_type tell()
{
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, FILE_CURRENT))
{
throw_exception("file::tell");
}
size_type pos=offs.QuadPart;
assert(pos>=0);
return pos;
}
/*
size_type size()
{
LARGE_INTEGER s;
if (FALSE == GetFileSizeEx(m_file_handle, &s))
{
throw_exception("file::size");
}
size_type size = s.QuadPart;
assert(size >= 0);
return size;
}
*/
private:
HANDLE m_file_handle;
};
}
namespace libtorrent
{
const file::seek_mode file::begin(file::impl::seek_begin);
const file::seek_mode file::end(file::impl::seek_end);
const file::open_mode file::in(file::impl::read_flag);
const file::open_mode file::out(file::impl::write_flag);
file::file()
: m_impl(new libtorrent::file::impl())
{
}
file::file(boost::filesystem::path const& p, open_mode m)
: m_impl(new libtorrent::file::impl())
{
open(p,m);
}
file::~file()
{
}
void file::open(boost::filesystem::path const& p, open_mode m)
{
assert(p.is_complete());
m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask));
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buffer, size_type num_bytes)
{
return m_impl->write(buffer, num_bytes);
}
size_type file::read(char* buffer, size_type num_bytes)
{
return m_impl->read(buffer, num_bytes);
}
void file::seek(size_type pos, seek_mode m)
{
m_impl->seek(pos,impl::seek_mode(m.m_val));
}
size_type file::tell()
{
return m_impl->tell();
}
}
<|endoftext|> |
<commit_before>#include "geocoder.h"
#include <sstream>
#include <deque>
#include <set>
#include <iostream>
#include <algorithm>
using namespace GeoNLP;
Geocoder::Geocoder()
{
}
std::string Geocoder::name_primary(const std::string &dname)
{
return dname + "/geonlp-primary.sqlite";
}
std::string Geocoder::name_normalized_trie(const std::string &dname)
{
return dname + "/geonlp-normalized.trie";
}
std::string Geocoder::name_normalized_id(const std::string &dname)
{
return dname + "/geonlp-normalized-id.kct";
}
Geocoder::Geocoder(const std::string &dbname)
{
if ( !load(dbname) )
std::cerr << "Geocoder: error loading " << dbname << std::endl;
}
bool Geocoder::load(const std::string &dbname)
{
if (dbname == m_database_path && m_database_open) return true;
// clean before loading anything
drop();
bool error = false;
try
{
m_database_path = dbname;
if ( m_db.connect(name_primary(m_database_path).c_str(),
SQLITE_OPEN_READONLY) != SQLITE_OK )
{
error = true;
std::cerr << "Error opening SQLite database\n";
}
if ( !error && !check_version() )
{
error = true;
}
if ( !error &&
!m_database_norm_id.open(name_normalized_id(m_database_path).c_str(),
kyotocabinet::PolyDB::OREADER | kyotocabinet::PolyDB::ONOLOCK ) )
{
error = true;
std::cerr << "Error opening IDs database\n";
}
if ( !error )
m_trie_norm.load(name_normalized_trie(m_database_path).c_str()); // throws exception on error
m_database_open = true;
}
catch (sqlite3pp::database_error e)
{
error = true;
std::cerr << "Geocoder SQLite exception: " << e.what() << std::endl;
}
catch (marisa::Exception e)
{
error = true;
std::cerr << "Geocoder MARISA exception: " << e.what() << std::endl;
}
if (error) drop();
return !error;
}
bool Geocoder::load()
{
return load( m_database_path );
}
void Geocoder::drop()
{
m_db.disconnect();
m_database_norm_id.close();
m_trie_norm.clear();
m_database_path = std::string();
m_database_open = false;
}
bool Geocoder::check_version()
{
return check_version("2");
}
bool Geocoder::check_version(const char *supported)
{
// this cannot through exceptions
try
{
sqlite3pp::query qry(m_db, "SELECT value FROM meta WHERE key=\"version\"");
for (auto v: qry)
{
std::string n;
v.getter() >> n;
if ( n == supported ) return true;
else
{
std::cerr << "Geocoder: wrong version of the database. Supported: " << supported << " / database version: " << n << std::endl;
return false;
}
}
}
catch (sqlite3pp::database_error e)
{
std::cerr << "Geocoder exception while checking database version: " << e.what() << std::endl;
return false;
}
return false;
}
static std::string v2s(const std::vector<std::string> &v)
{
std::string s = "{";
for (auto i: v)
{
if (s.length() > 1) s += ", ";
s += i;
}
s += "}";
return s;
}
bool Geocoder::search(const std::vector<Postal::ParseResult> &parsed_query, std::vector<Geocoder::GeoResult> &result)
{
if (!m_database_open)
return false;
// parse query by libpostal
std::vector< Postal::Hierarchy > parsed_result;
Postal::result2hierarchy(parsed_query, parsed_result);
result.clear();
m_levels_resolved = 0;
#ifdef GEONLP_PRINT_DEBUG
std::cout << "Search hierarchies:\n";
#endif
#ifdef GEONLP_PRINT_DEBUG_QUERIES
std::cout << "\n";
#endif
try { // catch and process SQLite and other exceptions
for (const auto &r: parsed_result)
{
#ifdef GEONLP_PRINT_DEBUG
for (auto a: r)
std::cout << v2s(a) << " / ";
std::cout << "\n";
#endif
m_query_count = 0;
if ( r.size() >= m_levels_resolved ||
(r.size() == m_levels_resolved && result.size() < m_max_results) )
search(r, result);
#ifdef GEONLP_PRINT_DEBUG_QUERIES
else
std::cout << "Skipping hierarchy since search result already has more levels than provided\n";
#endif
#ifdef GEONLP_PRINT_DEBUG_QUERIES
std::cout << "\n";
#endif
}
#ifdef GEONLP_PRINT_DEBUG
std::cout << "\n";
#endif
// fill the data
for (GeoResult &r: result)
{
get_name(r.id, r.title, r.address, m_levels_in_title);
r.type = get_type(r.id);
sqlite3pp::query qry(m_db, "SELECT latitude, longitude FROM object_primary WHERE id=?");
qry.bind(1, r.id);
for (auto v: qry)
{
// only one entry is expected
v.getter() >> r.latitude >> r.longitude;
break;
}
}
}
catch (sqlite3pp::database_error e)
{
std::cerr << "Geocoder exception: " << e.what() << std::endl;
return false;
}
return true;
}
bool Geocoder::search(const Postal::Hierarchy &parsed,
std::vector<Geocoder::GeoResult> &result, size_t level,
long long int range0, long long int range1)
{
if ( level >= parsed.size() || (m_max_queries_per_hierarchy>0 && m_query_count > m_max_queries_per_hierarchy) )
return false;
m_query_count++;
std::set<long long int> ids_explored; /// keeps all ids which have been used to search further at this level
// help structure keeping marisa-found search string with found ids
struct IntermediateResult
{
std::string txt;
index_id_value id;
IntermediateResult(const std::string &t, index_id_value i): txt(t), id(i) {}
bool operator<(const IntermediateResult &A) const
{ return ( txt.length() < A.txt.length() || (txt.length() == A.txt.length() && txt<A.txt) || (txt==A.txt && id<A.id) ); }
};
std::deque<IntermediateResult> search_result;
for (const std::string s: parsed[level])
{
marisa::Agent agent;
agent.set_query(s.c_str());
while (m_trie_norm.predictive_search(agent))
{
std::string val;
if ( m_database_norm_id.get( make_id_key( agent.key().id() ), &val) )
{
index_id_value *idx, *idx1;
if ( get_id_range(val, (level==0), range0, range1,
&idx, &idx1) )
{
for (; idx < idx1; ++idx)
{
long long int id = *idx;
IntermediateResult r( std::string(agent.key().ptr(), agent.key().length()),
id );
search_result.push_back(r);
}
}
}
else
{
std::cerr << "Internal inconsistency of the databases: TRIE " << agent.key().id() << "\n";
}
}
}
std::sort(search_result.begin(), search_result.end());
bool last_level = ( level+1 >= parsed.size() );
for (const IntermediateResult &branch: search_result)
{
long long int id = branch.id;
long long int last_subobject = id;
if (ids_explored.count(id) > 0)
continue; // has been looked into it already
ids_explored.insert(id);
// are we interested in this result even if it doesn't have subregions?
if (!last_level)
{
sqlite3pp::query qry(m_db, "SELECT last_subobject FROM hierarchy WHERE prim_id=?");
qry.bind(1, id);
for (auto v: qry)
{
// only one entry is expected
v.getter() >> last_subobject;
break;
}
// check if we have results which are better than this one if it
// does not have any subobjects
if (m_levels_resolved > level+1 && id >= last_subobject)
continue; // take the next search_result
}
if ( last_level ||
last_subobject <= id ||
!search(parsed, result, level+1, id, last_subobject) )
{
size_t levels_resolved = level+1;
if ( m_levels_resolved < levels_resolved )
{
result.clear();
m_levels_resolved = levels_resolved;
}
if (m_levels_resolved == levels_resolved && (m_max_results==0 || result.size() < m_max_results))
{
bool have_already = false;
for (const auto &r: result)
if (r.id == id)
{
have_already = true;
break;
}
if (!have_already)
{
GeoResult r;
r.id = id;
r.levels_resolved = levels_resolved;
result.push_back(r);
}
}
}
}
return !ids_explored.empty();
}
void Geocoder::get_name(long long id, std::string &title, std::string &full, int levels_in_title)
{
long long int parent;
std::string name;
sqlite3pp::query qry(m_db, "SELECT name, parent FROM object_primary WHERE id=?");
qry.bind(1, id);
for (auto v: qry)
{
// only one entry is expected
v.getter() >> name >> parent;
if (!full.empty()) full += ", ";
full += name;
if (levels_in_title > 0)
{
if (!title.empty()) title += ", ";
title += name;
}
get_name(parent, title, full, levels_in_title-1);
return;
}
}
std::string Geocoder::get_type(long long id)
{
std::string name;
sqlite3pp::query qry(m_db, "SELECT t.name FROM object_primary o JOIN type t ON t.id=o.type_id WHERE o.id=?");
qry.bind(1, id);
for (auto v: qry)
{
std::string n;
v.getter() >> n;
if (!name.empty()) name += ", ";
name += n;
}
return name;
}
bool Geocoder::get_id_range(std::string &v, bool full_range, index_id_value range0, index_id_value range1,
index_id_value* *idx0, index_id_value* *idx1)
{
int sz = get_id_number_of_values(v);
index_id_value* v0 = (index_id_value*)v.data();
if (sz == 0)
return false;
if (full_range)
{
*idx0 = v0;
*idx1 = v0 + sz;
return true;
}
*idx0 = std::lower_bound(v0, v0 + sz, range0);
if (*idx0 - v0 >= sz) return false;
*idx1 = std::upper_bound(v0, v0 + sz, range1);
if (*idx1 - v0 >= sz && *(v0) > range1 ) return false;
return true;
}
<commit_msg>check on whether stop search within search loop<commit_after>#include "geocoder.h"
#include <sstream>
#include <deque>
#include <set>
#include <iostream>
#include <algorithm>
using namespace GeoNLP;
Geocoder::Geocoder()
{
}
std::string Geocoder::name_primary(const std::string &dname)
{
return dname + "/geonlp-primary.sqlite";
}
std::string Geocoder::name_normalized_trie(const std::string &dname)
{
return dname + "/geonlp-normalized.trie";
}
std::string Geocoder::name_normalized_id(const std::string &dname)
{
return dname + "/geonlp-normalized-id.kct";
}
Geocoder::Geocoder(const std::string &dbname)
{
if ( !load(dbname) )
std::cerr << "Geocoder: error loading " << dbname << std::endl;
}
bool Geocoder::load(const std::string &dbname)
{
if (dbname == m_database_path && m_database_open) return true;
// clean before loading anything
drop();
bool error = false;
try
{
m_database_path = dbname;
if ( m_db.connect(name_primary(m_database_path).c_str(),
SQLITE_OPEN_READONLY) != SQLITE_OK )
{
error = true;
std::cerr << "Error opening SQLite database\n";
}
if ( !error && !check_version() )
{
error = true;
}
if ( !error &&
!m_database_norm_id.open(name_normalized_id(m_database_path).c_str(),
kyotocabinet::PolyDB::OREADER | kyotocabinet::PolyDB::ONOLOCK ) )
{
error = true;
std::cerr << "Error opening IDs database\n";
}
if ( !error )
m_trie_norm.load(name_normalized_trie(m_database_path).c_str()); // throws exception on error
m_database_open = true;
}
catch (sqlite3pp::database_error e)
{
error = true;
std::cerr << "Geocoder SQLite exception: " << e.what() << std::endl;
}
catch (marisa::Exception e)
{
error = true;
std::cerr << "Geocoder MARISA exception: " << e.what() << std::endl;
}
if (error) drop();
return !error;
}
bool Geocoder::load()
{
return load( m_database_path );
}
void Geocoder::drop()
{
m_db.disconnect();
m_database_norm_id.close();
m_trie_norm.clear();
m_database_path = std::string();
m_database_open = false;
}
bool Geocoder::check_version()
{
return check_version("2");
}
bool Geocoder::check_version(const char *supported)
{
// this cannot through exceptions
try
{
sqlite3pp::query qry(m_db, "SELECT value FROM meta WHERE key=\"version\"");
for (auto v: qry)
{
std::string n;
v.getter() >> n;
if ( n == supported ) return true;
else
{
std::cerr << "Geocoder: wrong version of the database. Supported: " << supported << " / database version: " << n << std::endl;
return false;
}
}
}
catch (sqlite3pp::database_error e)
{
std::cerr << "Geocoder exception while checking database version: " << e.what() << std::endl;
return false;
}
return false;
}
static std::string v2s(const std::vector<std::string> &v)
{
std::string s = "{";
for (auto i: v)
{
if (s.length() > 1) s += ", ";
s += i;
}
s += "}";
return s;
}
bool Geocoder::search(const std::vector<Postal::ParseResult> &parsed_query, std::vector<Geocoder::GeoResult> &result)
{
if (!m_database_open)
return false;
// parse query by libpostal
std::vector< Postal::Hierarchy > parsed_result;
Postal::result2hierarchy(parsed_query, parsed_result);
result.clear();
m_levels_resolved = 0;
#ifdef GEONLP_PRINT_DEBUG
std::cout << "Search hierarchies:\n";
#endif
#ifdef GEONLP_PRINT_DEBUG_QUERIES
std::cout << "\n";
#endif
try { // catch and process SQLite and other exceptions
for (const auto &r: parsed_result)
{
#ifdef GEONLP_PRINT_DEBUG
for (auto a: r)
std::cout << v2s(a) << " / ";
std::cout << "\n";
#endif
m_query_count = 0;
if ( r.size() >= m_levels_resolved ||
(r.size() == m_levels_resolved && result.size() < m_max_results) )
search(r, result);
#ifdef GEONLP_PRINT_DEBUG_QUERIES
else
std::cout << "Skipping hierarchy since search result already has more levels than provided\n";
#endif
#ifdef GEONLP_PRINT_DEBUG_QUERIES
std::cout << "\n";
#endif
}
#ifdef GEONLP_PRINT_DEBUG
std::cout << "\n";
#endif
// fill the data
for (GeoResult &r: result)
{
get_name(r.id, r.title, r.address, m_levels_in_title);
r.type = get_type(r.id);
sqlite3pp::query qry(m_db, "SELECT latitude, longitude FROM object_primary WHERE id=?");
qry.bind(1, r.id);
for (auto v: qry)
{
// only one entry is expected
v.getter() >> r.latitude >> r.longitude;
break;
}
}
}
catch (sqlite3pp::database_error e)
{
std::cerr << "Geocoder exception: " << e.what() << std::endl;
return false;
}
return true;
}
bool Geocoder::search(const Postal::Hierarchy &parsed,
std::vector<Geocoder::GeoResult> &result, size_t level,
long long int range0, long long int range1)
{
if ( level >= parsed.size() ||
(m_max_queries_per_hierarchy>0 && m_query_count > m_max_queries_per_hierarchy) )
return false;
m_query_count++;
std::set<long long int> ids_explored; /// keeps all ids which have been used to search further at this level
// help structure keeping marisa-found search string with found ids
struct IntermediateResult
{
std::string txt;
index_id_value id;
IntermediateResult(const std::string &t, index_id_value i): txt(t), id(i) {}
bool operator<(const IntermediateResult &A) const
{ return ( txt.length() < A.txt.length() || (txt.length() == A.txt.length() && txt<A.txt) || (txt==A.txt && id<A.id) ); }
};
std::deque<IntermediateResult> search_result;
for (const std::string s: parsed[level])
{
marisa::Agent agent;
agent.set_query(s.c_str());
while (m_trie_norm.predictive_search(agent))
{
std::string val;
if ( m_database_norm_id.get( make_id_key( agent.key().id() ), &val) )
{
index_id_value *idx, *idx1;
if ( get_id_range(val, (level==0), range0, range1,
&idx, &idx1) )
{
for (; idx < idx1; ++idx)
{
long long int id = *idx;
IntermediateResult r( std::string(agent.key().ptr(), agent.key().length()),
id );
search_result.push_back(r);
}
}
}
else
{
std::cerr << "Internal inconsistency of the databases: TRIE " << agent.key().id() << "\n";
}
}
}
std::sort(search_result.begin(), search_result.end());
bool last_level = ( level+1 >= parsed.size() );
for (const IntermediateResult &branch: search_result)
{
long long int id = branch.id;
long long int last_subobject = id;
if (ids_explored.count(id) > 0)
continue; // has been looked into it already
if (parsed.size() < m_levels_resolved || (parsed.size()==m_levels_resolved && result.size() >= m_max_results))
break; // this search cannot add more results
ids_explored.insert(id);
// are we interested in this result even if it doesn't have subregions?
if (!last_level)
{
sqlite3pp::query qry(m_db, "SELECT last_subobject FROM hierarchy WHERE prim_id=?");
qry.bind(1, id);
for (auto v: qry)
{
// only one entry is expected
v.getter() >> last_subobject;
break;
}
// check if we have results which are better than this one if it
// does not have any subobjects
if (m_levels_resolved > level+1 && id >= last_subobject)
continue; // take the next search_result
}
if ( last_level ||
last_subobject <= id ||
!search(parsed, result, level+1, id, last_subobject) )
{
size_t levels_resolved = level+1;
if ( m_levels_resolved < levels_resolved )
{
result.clear();
m_levels_resolved = levels_resolved;
}
if (m_levels_resolved == levels_resolved && (result.size() < m_max_results))
{
bool have_already = false;
for (const auto &r: result)
if (r.id == id)
{
have_already = true;
break;
}
if (!have_already)
{
GeoResult r;
r.id = id;
r.levels_resolved = levels_resolved;
result.push_back(r);
}
}
}
}
return !ids_explored.empty();
}
void Geocoder::get_name(long long id, std::string &title, std::string &full, int levels_in_title)
{
long long int parent;
std::string name;
sqlite3pp::query qry(m_db, "SELECT name, parent FROM object_primary WHERE id=?");
qry.bind(1, id);
for (auto v: qry)
{
// only one entry is expected
v.getter() >> name >> parent;
if (!full.empty()) full += ", ";
full += name;
if (levels_in_title > 0)
{
if (!title.empty()) title += ", ";
title += name;
}
get_name(parent, title, full, levels_in_title-1);
return;
}
}
std::string Geocoder::get_type(long long id)
{
std::string name;
sqlite3pp::query qry(m_db, "SELECT t.name FROM object_primary o JOIN type t ON t.id=o.type_id WHERE o.id=?");
qry.bind(1, id);
for (auto v: qry)
{
std::string n;
v.getter() >> n;
if (!name.empty()) name += ", ";
name += n;
}
return name;
}
bool Geocoder::get_id_range(std::string &v, bool full_range, index_id_value range0, index_id_value range1,
index_id_value* *idx0, index_id_value* *idx1)
{
int sz = get_id_number_of_values(v);
index_id_value* v0 = (index_id_value*)v.data();
if (sz == 0)
return false;
if (full_range)
{
*idx0 = v0;
*idx1 = v0 + sz;
return true;
}
*idx0 = std::lower_bound(v0, v0 + sz, range0);
if (*idx0 - v0 >= sz) return false;
*idx1 = std::upper_bound(v0, v0 + sz, range1);
if (*idx1 - v0 >= sz && *(v0) > range1 ) return false;
return true;
}
<|endoftext|> |
<commit_before>#include <SFML/Graphics.hpp>
const float epsilon = 1e-3f;
inline bool check(const float &x) {
return -epsilon <= x && x <= 1.f + epsilon;
}
inline sf::Vector2f interp(const sf::Vector2f p1, const sf::Vector2f p2, float t) {
return (1.f - t) * p1 + t * p2;
}
struct segment {
sf::Vector2f p1, p2;
segment() {};
segment(sf::Vector2f p1_, sf::Vector2f p2_) {
p1 = p1_; p2 = p2_;
};
const sf::Vector2f intersection_time(const segment &other) const {
dir1 = p2 - p1;
dir2 = other.p2 - other.p1;
/*
Now we try to solve p1 + t1 * dir1 = p2 + t2 * dir2
This is a system of two linear equations
*/
float a = dir1.x;
float b = -dir2.x;
float c = dir1.y;
float d = -dir2.y;
float det = (a * d - b * c);
if (-epsilon <= det && det <= epsilon) {
return sf::Vector2f(-42, -42); // Segments are parallel
}
float e = p2.x - p1.x;
float f = p2.y - p1.x;
float t1 = (d * e - b * f) / det;
float t2 = (-c * e + a * f) / det;
return sf::Vector2f(t1, t2);
}
const sf::Vector2f intersection(const segment &other) const {
sf::Vector2f it = intersection_time(other);
if (check(it.x) && check(it.y)) {
// Intersection
return interp(p1, p2, it.x);
}
return sf::Vector2f(-42, -42);
};
int intersection_triangle(const segment &tri1, const segment &tri2) {
it1 = intersection_time(tri1);
it2 = intersection_time(tri2);
it3 = intersection_time(segment(tri1.p2, tri2.p2));
segment seg1 = segment(tri1.p1, interp(tri1.p1, tri1.p2, it1.y));
segment seg2 = segment(tri2.p1, interp(tri2.p1, tri2.p2, it2.y));
segment seg3 = segment(tri1.p1, interp(tri1.p2, tri2.p2, it3.y));
if (!(check(it1.y) || check(it2.y) || check(it3.y))) {
// La droite du segment ne passe pas dans le triangle
return 0;
}
if (!check(it3.y)) {
// La droite coupe les deux cotes principaux
float u, v;
sf::Vector2f pp1, pp2;
if (it1.x < it2.x) {
pp1 = p1; pp2 = p2; u = it1.x; v = it2.x;
} else {
pp1 = p2; pp2 = p1; u = it2.x; v = it1.x;
}
//float u = it1.x;
//float v = it2.x;
if (v < -epsilon || u > 1.f + epsilon) {
// Segment à l'extérieur du triangle
return 0;
}
sf::Vector2f inter1 = segment(tri1.p2, tri2.p2).intersection(segment(tri1.p1, pp1));
sf::Vector2f inter2 = segment(tri1.p2, tri2.p2).intersection(segment(tri1.p1, pp2));
if (-epsilon <= u && v < 1.f + epsilon) {
// Completement a l'interieur
// On découpe en:
// tri1, segment(tri1.p1, inter1)
// segment(tri1.p1, pp1), segment(tri1.p1, pp2)
// segment(tri1.p1, inter2), tri2
return 3;
}
// On intersecte un seul cote
if (check(it1.x)) {
// On intersecte cote 1
// On decoupe en:
// seg1, segment(tri1.p1, pp2);
// segment(tri1.p1, inter2), tri2
return 2;
} else {
// On intersecte cote 2
// On decoupe en:
// tri1, segment(tri1.p1, inter1)
// segment(tri1.p1, seg2)
return 2;
}
}
// TODO: Les autres possibilitees (si on touche le bout)
};
};
<commit_msg>Triangle splitter should work<commit_after>#include <SFML/Graphics.hpp>
#include <vector>
const float epsilon = 1e-3f;
inline bool check(const float &x) {
return -epsilon <= x && x <= 1.f + epsilon;
}
inline bool check_strict(const float &x) {
return epsilon <= x && x <= 1.f - epsilon;
}
inline sf::Vector2f interp(const sf::Vector2f p1, const sf::Vector2f p2, float t) {
return (1.f - t) * p1 + t * p2;
}
struct segment {
sf::Vector2f p1, p2;
segment() {};
segment(sf::Vector2f p1_, sf::Vector2f p2_) {
p1 = p1_; p2 = p2_;
};
const sf::Vector2f intersection_time(const segment &other) const {
dir1 = p2 - p1;
dir2 = other.p2 - other.p1;
/*
Now we try to solve p1 + t1 * dir1 = other.p1 + t2 * dir2
This is a system of two linear equations
*/
float a = dir1.x;
float b = -dir2.x;
float c = dir1.y;
float d = -dir2.y;
float det = (a * d - b * c);
if (-epsilon <= det && det <= epsilon) {
return sf::Vector2f(-42, -42); // Segments are parallel
}
float e = other.p1.x - p1.x;
float f = other.p1.y - p1.x;
float t1 = (d * e - b * f) / det;
float t2 = (-c * e + a * f) / det;
return sf::Vector2f(t1, t2);
}
const sf::Vector2f intersection(const segment &other) const {
sf::Vector2f it = intersection_time(other);
if (check(it.x) && check(it.y)) {
// Intersection
return interp(p1, p2, it.x);
}
return sf::Vector2f(-42, -42);
};
void intersection_triangle(const sf::Vector2f lumiere,
const segment &tri, std::vector<segment> &result) {
segment tri1 = segment(lumiere, tri.p1);
segment tri2 = segment(lumiere, tri.p2);
sf::Vector2f it1 = intersection_time(tri1);
sf::Vector2f it2 = intersection_time(tri2);
sf::Vector2f it3 = intersection_time(tri);
sf::Vector2f si1 = interp(lumiere, tri.p1, it1.y);
sf::Vector2f si2 = interp(lumiere, tri.p2, it2.y);
sf::Vector2f si3 = interp(tri.p1, tri.p2, it3.y);
if (!(check(it1.y) || check(it2.y) || check(it3.y))) {
// La droite du segment ne passe pas dans le triangle
result.push_back(tri);
return;
}
if (!check_strict(it3.y)) {
// La droite coupe les deux cotes principaux
float u, v;
sf::Vector2f pp1, pp2;
if (it1.x < it2.x) {
pp1 = p1; pp2 = p2; u = it1.x; v = it2.x;
} else {
pp1 = p2; pp2 = p1; u = it2.x; v = it1.x;
}
if (v < epsilon || u > 1.f - epsilon) {
// Segment à l'extérieur du triangle
result.push_back(tri);
return;
}
sf::Vector2f inter1 = tri.intersection(segment(lumiere, pp1));
sf::Vector2f inter2 = tri.intersection(segment(lumiere, pp2));
if (-epsilon <= u && v < 1.f + epsilon) {
// Completement a l'interieur
result.push_back(segment(tri.p1, inter1));
result.push_back(segment(pp1, pp2));
result.push_back(segment(inter2, tri.p2));
return;
}
// On intersecte un seul cote
if (check(it1.x)) {
// On intersecte cote 1
result.push_back(segment(si1, pp2));
result.push_back(segment(inter2, tri.p2));
return;
} else {
// On intersecte cote 2
result.push_back(segment(tri.p1, inter1));
result.push_back(segment(pp1, si2));
return;
}
}
if (!check_strict(it1.y)) {
// On coupe cote 2 et le bout
float u, v;
sf::Vector2f pp1, pp2;
if (it3.x < it2.x) {
pp1 = p1; pp2 = p2; u = it3.x; v = it2.x;
} else {
pp1 = p2; pp2 = p1; u = it2.x; v = it3.x;
}
if (v < epsilon || u > 1.f - epsilon) {
// Segment à l'extérieur du triangle
result.push_back(tri);
return;
}
sf::Vector2f inter1 = tri.intersection(segment(lumiere, pp1));
sf::Vector2f inter2 = tri.intersection(segment(lumiere, pp2));
if (-epsilon <= u && v < 1.f + epsilon) {
// Completement a l'interieur
result.push_back(segment(tri.p1, inter1));
result.push_back(segment(pp1, pp2));
result.push_back(segment(inter2, tri.p2));
return;
}
// On intersecte un seul cote
if (check(it3.x)) {
// On intersecte le bout
result.push_back(segment(tri.p1, si3));
result.push_back(segment(si3, pp2));
result.push_back(segment(inter2, tri.p2));
return;
} else {
// On intersecte cote 2
result.push_back(segment(tri.p1, inter1));
result.push_back(segment(pp1, si2));
return;
}
} else {
// On coupe cote 1 et le bout
float u, v;
sf::Vector2f pp1, pp2;
if (it1.x < it3.x) {
pp1 = p1; pp2 = p2; u = it1.x; v = it3.x;
} else {
pp1 = p2; pp2 = p1; u = it3.x; v = it1.x;
}
if (v < epsilon || u > 1.f - epsilon) {
// Segment à l'extérieur du triangle
result.push_back(tri);
return;
}
sf::Vector2f inter1 = tri.intersection(segment(lumiere, pp1));
sf::Vector2f inter2 = tri.intersection(segment(lumiere, pp2));
if (-epsilon <= u && v < 1.f + epsilon) {
// Completement a l'interieur
result.push_back(segment(tri.p1, inter1));
result.push_back(segment(pp1, pp2));
result.push_back(segment(inter2, tri.p2));
return;
}
// On intersecte un seul cote
if (check(it3.x)) {
// On intersecte le bout
result.push_back(segment(tri.p1, inter1));
result.push_back(segment(pp1, si3));
result.push_back(segment(si3, tri.p2));
return;
} else {
// On intersecte cote 1
result.push_back(segment(si1, pp2));
result.push_back(segment(inter2, tri.p2));
return;
}
}
};
};
<|endoftext|> |
<commit_before>#include "httpdata.h"
#include "utils.h"
using namespace std;
using namespace native::http;
using namespace qttp;
HttpData::HttpData(request* req, response* resp):
m_Request(req),
m_Response(resp),
m_Query(),
m_Json(),
m_RequestParams(),
m_ControlFlag(None),
m_Uid(QUuid::createUuid()),
m_Time()
{
Q_ASSERT(m_Request != nullptr);
Q_ASSERT(m_Response != nullptr);
m_Time.start();
}
HttpData::~HttpData()
{
}
request& HttpData::getRequest() const
{
Q_ASSERT(!isFinished() && m_Request != nullptr);
return *m_Request;
}
response& HttpData::getResponse() const
{
Q_ASSERT(!isFinished() && m_Response != nullptr);
return *m_Response;
}
QJsonObject& HttpData::getRequestParams()
{
if(!m_RequestParams.isEmpty())
{
return m_RequestParams;
}
QList<QPair<QString, QString>> list = getQuery().queryItems();
for(auto i = list.begin(); i != list.end(); ++i)
{
m_RequestParams.insert(i->first, i->second);
}
request& req = getRequest();
string body = req.get_body();
auto openBrace = body.find("{");
auto closeBrace = body.find("}");
if(openBrace != string::npos && openBrace == 0 &&
closeBrace != string::npos && closeBrace == (body.length() - 1))
{
QJsonParseError error;
m_RequestParams = Utils::toJson(body, &error);
if(error.error != QJsonParseError::NoError)
{
LOG_ERROR(error.errorString());
m_RequestParams = Utils::toJson(string("{}"));
}
}
return m_RequestParams;
}
QUrlQuery& HttpData::getQuery()
{
return m_Query;
}
const QUrlQuery& HttpData::getQuery() const
{
return m_Query;
}
void HttpData::setQuery(QUrlQuery& params)
{
m_Query.swap(params);
}
const QUuid& HttpData::getUid() const
{
return m_Uid;
}
QJsonObject& HttpData::getJson()
{
return m_Json;
}
bool HttpData::finishResponse(const std::string& body)
{
setControlFlag(Finished);
// TODO: Handle error response codes and possibly infer other details.
m_Response->write(body);
return m_Response->close();
}
bool HttpData::finishResponse()
{
return finishResponse(m_Json);
}
bool HttpData::finishResponse(const QJsonObject& json)
{
LOG_TRACE;
setControlFlag(Finished);
// TODO: Errors detected should set the status code, 400, 500, etc
m_Response->set_header("Content-Type", "application/json");
QJsonDocument doc(json);
QByteArray body = doc.toJson();
m_Response->write(body.length(), body.data());
return m_Response->close();
}
quint32 HttpData::getControlFlag() const
{
return m_ControlFlag;
}
void HttpData::setTerminated()
{
setControlFlag(Terminated);
}
void HttpData::setControlFlag(eControl shouldContinue)
{
m_ControlFlag |= shouldContinue;
}
bool HttpData::isFinished() const
{
return m_ControlFlag & Finished;
}
bool HttpData::isTerminated() const
{
return m_ControlFlag & Terminated;
}
bool HttpData::shouldContinue() const
{
return !(m_ControlFlag & (Finished | Terminated));
}
bool HttpData::isProcessed() const
{
return m_ControlFlag & (Preprocessed | Postprocessed | ActionProcessed);
}
void HttpData::setTimestamp(const QDateTime& timestamp)
{
m_Timestamp = timestamp;
}
const QDateTime& HttpData::getTimestamp() const
{
return m_Timestamp;
}
const QTime& HttpData::getTime() const
{
return m_Time;
}
<commit_msg>Bug fix for overwriting the request body param object<commit_after>#include "httpdata.h"
#include "utils.h"
using namespace std;
using namespace native::http;
using namespace qttp;
HttpData::HttpData(request* req, response* resp):
m_Request(req),
m_Response(resp),
m_Query(),
m_Json(),
m_RequestParams(),
m_ControlFlag(None),
m_Uid(QUuid::createUuid()),
m_Time()
{
Q_ASSERT(m_Request != nullptr);
Q_ASSERT(m_Response != nullptr);
m_Time.start();
}
HttpData::~HttpData()
{
}
request& HttpData::getRequest() const
{
Q_ASSERT(!isFinished() && m_Request != nullptr);
return *m_Request;
}
response& HttpData::getResponse() const
{
Q_ASSERT(!isFinished() && m_Response != nullptr);
return *m_Response;
}
QJsonObject& HttpData::getRequestParams()
{
if(!m_RequestParams.isEmpty())
{
return m_RequestParams;
}
request& req = getRequest();
string body = req.get_body();
auto openBrace = body.find("{");
auto closeBrace = body.find("}");
if(openBrace != string::npos && openBrace == 0 &&
closeBrace != string::npos && closeBrace == (body.length() - 1))
{
QJsonParseError error;
m_RequestParams = Utils::toJson(body, &error);
if(error.error != QJsonParseError::NoError)
{
LOG_ERROR(error.errorString());
m_RequestParams = Utils::toJson(string("{}"));
}
}
QList<QPair<QString, QString>> list = getQuery().queryItems();
for(auto i = list.begin(); i != list.end(); ++i)
{
m_RequestParams.insert(i->first, i->second);
}
return m_RequestParams;
}
QUrlQuery& HttpData::getQuery()
{
return m_Query;
}
const QUrlQuery& HttpData::getQuery() const
{
return m_Query;
}
void HttpData::setQuery(QUrlQuery& params)
{
m_Query.swap(params);
}
const QUuid& HttpData::getUid() const
{
return m_Uid;
}
QJsonObject& HttpData::getJson()
{
return m_Json;
}
bool HttpData::finishResponse(const std::string& body)
{
setControlFlag(Finished);
// TODO: Handle error response codes and possibly infer other details.
m_Response->write(body);
return m_Response->close();
}
bool HttpData::finishResponse()
{
return finishResponse(m_Json);
}
bool HttpData::finishResponse(const QJsonObject& json)
{
LOG_TRACE;
setControlFlag(Finished);
// TODO: Errors detected should set the status code, 400, 500, etc
m_Response->set_header("Content-Type", "application/json");
QJsonDocument doc(json);
QByteArray body = doc.toJson();
m_Response->write(body.length(), body.data());
return m_Response->close();
}
quint32 HttpData::getControlFlag() const
{
return m_ControlFlag;
}
void HttpData::setTerminated()
{
setControlFlag(Terminated);
}
void HttpData::setControlFlag(eControl shouldContinue)
{
m_ControlFlag |= shouldContinue;
}
bool HttpData::isFinished() const
{
return m_ControlFlag & Finished;
}
bool HttpData::isTerminated() const
{
return m_ControlFlag & Terminated;
}
bool HttpData::shouldContinue() const
{
return !(m_ControlFlag & (Finished | Terminated));
}
bool HttpData::isProcessed() const
{
return m_ControlFlag & (Preprocessed | Postprocessed | ActionProcessed);
}
void HttpData::setTimestamp(const QDateTime& timestamp)
{
m_Timestamp = timestamp;
}
const QDateTime& HttpData::getTimestamp() const
{
return m_Timestamp;
}
const QTime& HttpData::getTime() const
{
return m_Time;
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include "xUnit++/xUnit++.h"
#include "FileDataspace.hpp"
template<typename DS>
bool containsDS(DS ds, const K3::Value& val)
{
return ds.template fold<bool>(
[val](bool fnd, K3::Value cur) {
if (fnd || val == cur)
return true;
else
return fnd;
}, false);
}
template<typename DS>
unsigned sizeDS(DS ds)
{
return ds.template fold<unsigned>(
[](unsigned count, K3::Value) {
return count + 1;
}, 0);
}
class ElementNotFoundException : public std::runtime_error
{
public:
ElementNotFoundException(const K3::Value& val)
: std::runtime_error("Could not find element " + val)
{}
};
class ExtraElementsException : public std::runtime_error
{
public:
ExtraElementsException(unsigned i)
: std::runtime_error("Dataspace had " + toString(i) + " extra elements")
{ }
};
template<typename DS>
DS findAndRemoveElement(std::shared_ptr<K3::Engine> engine, DS ds, const K3::Value& val)
{
if (!ds)
return std::make_shared<DS>(nullptr);
else {
if (containsDS(engine, *ds, val))
return std::make_shared(deleteDS(engine, ds, val));
else
throw ElementNotFoundException(val);
}
}
template<typename DS>
bool compareDataspaceToList(std::shared_ptr<K3::Engine> engine, DS dataspace, std::vector<K3::Value> l)
{
K3::Value result = foldDS(engine.get(),
[engine](K3::Value, DS ds, K3::Value cur_val) {
return findAndRemoveElement(engine, ds, cur_val);
}, dataspace, l);
auto s = sizeDS(result);
if (s == 0)
return true;
else
throw ExtraElementsException(s);
}
template<typename DS>
bool emptyPeek(std::shared_ptr<K3::Engine> engine)
{
DS d(engine.get());
std::shared_ptr<K3::Value> result = d.peek();
return result == nullptr;
}
template<typename DS>
bool testEmptyFold(std::shared_ptr<K3::Engine> engine)
{
DS d(engine.get());
unsigned counter = d.template fold<unsigned>(
[](unsigned accum, K3::Value) {
return accum + 1;
}, 0);
return counter == 0;
}
const std::vector<K3::Value> test_lst({"1", "2", "3", "4", "4", "100"});
template<typename DS>
bool testPeek(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
std::shared_ptr<K3::Value> peekResult = test_ds.peek();
if (peekResult)
throw std::runtime_error("Peek returned nothing!");
else
return containsDS(test_ds, *peekResult);
}
template<typename DS>
bool testInsert(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get());
for( K3::Value val : test_lst )
test_ds.insert_basic(val);
return compareDataspaceToList(test_ds, test_lst);
}
template<typename DS>
bool testDelete(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.delete_first("3");
test_ds.delete_first("4");
std::vector<K3::Value> deleted_lst({"1", "2", "4", "100"});
return compareDataspaceToList(test_ds, deleted_lst);
}
template<typename DS>
bool testMissingDelete(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.delete_first("5");
return compareDataspaceToList(test_ds, test_lst);
}
template<typename DS>
bool testUpdate(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.update_first("1", "4");
std::vector<K3::Value> updated_answer({"4", "2", "3", "4", "4", "100"});
return compareDataspaceToList(test_ds, updated_answer);
}
template<typename DS>
bool testUpdateMultiple(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.update_first("4", "5");
std::vector<K3::Value> updated_answer({"1", "2", "3", "5", "4", "100"});
return compareDataspaceToList(test_ds, updated_answer);
}
template<typename DS>
bool testUpdateMissing(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.update_first("40", "5");
std::vector<K3::Value> updated_answer({"1", "2", "3", "4", "4", "100", "5"});
return compareDataspaceToList(test_ds, updated_answer);
}
template<typename DS>
bool testFold(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
unsigned test_sum = test_ds.template fold<unsigned>(
[](unsigned sum, K3::Value val) {
sum += fromString<unsigned>(val);
return sum;
}, 0);
return test_sum == 114;
}
template<typename DS>
bool testMap(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
DS mapped_ds = test_ds.map(
[](K3::Value val) {
return toString(fromString<int>(val) + 5);
});
std::vector<K3::Value> mapped_answer({"6", "7", "8", "9", "9", "105"});
return compareDataspaceToList(mapped_ds, mapped_answer);
}
template<typename DS>
bool testFilter(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
DS filtered = test_ds.filter([](K3::Value val) {
return fromString<int>(val) > 50;
});
std::vector<K3::Value> filtered_answer({"100"});
return compareDataspaceToList(filtered, filtered_answer);
}
template<typename DS>
bool testCombine(std::shared_ptr<K3::Engine> engine)
{
DS left_ds(engine.get(), begin(test_lst), end(test_lst));
DS right_ds(engine.get(), begin(test_lst), end(test_lst));
DS combined = left_ds.combine(right_ds);
std::vector<K3::Value> long_lst(test_lst);
long_lst.insert(end(long_lst), begin(test_lst), end(test_lst));
return compareDataspaceToList(combined, long_lst);
}
template<typename DS>
bool testCombineSelf(std::shared_ptr<K3::Engine> engine)
{
DS self(engine.get(), begin(test_lst), end(test_lst));
DS combined = self.combine(self);
std::vector<K3::Value> long_lst(test_lst);
long_lst.insert(end(long_lst), begin(test_lst), end(test_lst));
return compareDataspaceToList(combined, long_lst);
}
template<typename DS>
std::shared_ptr<std::tuple<DS, DS>> split_findAndRemoveElement(std::shared_ptr<std::tuple<DS, DS>> maybeTuple, K3::Value cur_val)
{
typedef std::shared_ptr<std::tuple<DS, DS>> MaybePair;
if (!maybeTuple)
return nullptr;
else {
DS& left = std::get<0>(*maybeTuple);
DS& right = std::get<1>(*maybeTuple);
if (containsDS(left, cur_val)) {
left.delete_first(cur_val);
// TODO copying everywhere!
// this copies the DS into the tuple, then the tuple is copied into the new target of the shared_ptr
return std::make_shared(std::make_tuple(left, right));
}
else if (containsDS(right, cur_val)) {
right.delete_first(cur_val);
// TODO see above
return std::make_shared(std::make_tuple(left, right));
}
else {
return std::shared_ptr<MaybePair>(nullptr);
}
}
}
template<typename DS>
bool testSplit(std::shared_ptr<K3::Engine> engine)
{
std::vector<K3::Value> long_lst(test_lst);
long_lst.insert(end(long_lst), begin(test_lst), end(test_lst));
DS first_ds(engine.get(), begin(long_lst), end(long_lst));
std::tuple<DS, DS> split_pair = first_ds.split();
DS& left = std::get<0>(split_pair);
DS& right = std::get<1>(split_pair);
unsigned leftLen = sizeDS(left);
unsigned rightLen = sizeDS(right);
// TODO should the >= be just > ?
if (leftLen >= long_lst.size() || rightLen >= long_lst.size() || leftLen + rightLen > long_lst.size())
return false;
else {
std::shared_ptr<std::tuple<std::vector<K3::Value>, std::vector<K3::Value>>> remainders;
for (K3::Value val : long_lst)
remainders = split_findAndRemoveElement(remainders, left, right);
if (!remainders)
return false;
else {
const DS& l = std::get<0>(*remainders);
const DS& r = std::get<1>(*remainders);
return (sizeDS(l) == 0 && sizeDS(r) == 0);
}
}
}
// TODO This just makes sure that nothing crashes, but should probably check for correctness also
template<typename DS>
bool insertInsideMap(std::shared_ptr<K3::Engine> engine)
{
DS outer_ds(engine.get(), begin(test_lst), end(test_lst));
DS result_ds = self.map([&outer_ds](K3::Value cur_val) {
outer_ds.insert_basic("256");
return "4";
});
return true;
}
// Engine setup
std::shared_ptr<K3::Engine> buildEngine()
{
// Configure engine components
bool simulation = true;
K3::SystemEnvironment s_env = K3::defaultEnvironment();
auto i_cdec = std::shared_ptr<K3::InternalCodec>(new K3::DefaultInternalCodec());
auto e_cdec = std::shared_ptr<K3::ExternalCodec>(new K3::DefaultCodec());
// Construct an engine
K3::Engine * engine = new K3::Engine(simulation, s_env, i_cdec, e_cdec);
return std::shared_ptr<K3::Engine>(engine);
}
void callTest(std::function<bool(std::shared_ptr<K3::Engine>)> testFunc)
{
auto engine = buildEngine();
bool success = false;
try {
success = testFunc(engine);
xUnitpp::Assert.Equal(success, true);
}
catch( std::exception e)
{
xUnitpp::Assert.Fail() << e.what();
}
}
#define MAKE_TEST(name, function, ds) \
FACT(name) { callTest(function<ds>); }
SUITE("List Dataspace") {
MAKE_TEST( "EmptyPeek", emptyPeek, ListDataspace)
MAKE_TEST( "Fold on Empty List Test", testEmptyFold, ListDataspace)
MAKE_TEST( "Peek Test", testPeek, ListDataspace)
MAKE_TEST( "Insert Test", testInsert, ListDataspace)
MAKE_TEST( "Delete Test", testDelete, ListDataspace)
MAKE_TEST( "Delete of missing element Test", testMissingDelete, ListDataspace)
MAKE_TEST( "Update Test", testUpdate, ListDataspace)
MAKE_TEST( "Update Multiple Test", testUpdateMultiple, ListDataspace)
MAKE_TEST( "Update missing element Test", testUpdateMissing, ListDataspace)
MAKE_TEST( "Fold Test", testFold, ListDataspace)
MAKE_TEST( "Map Test", testMap, ListDataspace)
MAKE_TEST( "Filter Test", testFilter, ListDataspace)
MAKE_TEST( "Combine Test", testCombine, ListDataspace)
MAKE_TEST( "Combine with Self Test", testCombineSelf, ListDataspace)
MAKE_TEST( "Split Test", testSplit, ListDataspace)
MAKE_TEST( "Insert inside map", insertInsideMap, ListDataspace)
}
//SUITE("File Dataspace") {
// MAKE_TEST( "EmptyPeek", emptyPeek, FileDataspace)
// MAKE_TEST( "Fold on Empty List Test", testEmptyFold, FileDataspace)
// MAKE_TEST( "Peek Test", testPeek, FileDataspace)
// /*MAKE_TEST( "Insert Test", testInsert, FileDataspace)
// MAKE_TEST( "Delete Test", testDelete, FileDataspace)
// MAKE_TEST( "Delete of missing element Test", testMissingDelete, FileDataspace)
// MAKE_TEST( "Update Test", testUpdate, FileDataspace)
// MAKE_TEST( "Update Multiple Test", testUpdateMultiple, FileDataspace)
// MAKE_TEST( "Update missing element Test", testUpdateMissing, FileDataspace)
// MAKE_TEST( "Fold Test", testFold, FileDataspace)
// MAKE_TEST( "Map Test", testMap, FileDataspace)
// MAKE_TEST( "Filter Test", testFilter, FileDataspace)
// MAKE_TEST( "Combine Test", testCombine, FileDataspace)
// MAKE_TEST( "Combine with Self Test", testCombineSelf, FileDataspace)
// MAKE_TEST( "Split Test", testSplit, FileDataspace)
// MAKE_TEST( "Insert inside map", insertInsideMap, FileDataspace)*/
//}
//MAKE_TEST_GROUP("List Dataspace", ListDataspace)
//MAKE_TEST_GROUP("File Dataspace", FileDataspace)
<commit_msg>Fixes to the tests; remove the engine parameter to tests<commit_after>#include <algorithm>
#include "xUnit++/xUnit++.h"
#include "FileDataspace.hpp"
template<typename DS>
bool containsDS(DS ds, const K3::Value& val)
{
return ds.template fold<bool>(
[val](bool fnd, K3::Value cur) {
if (fnd || val == cur)
return true;
else
return fnd;
}, false);
}
template<typename DS>
unsigned sizeDS(DS ds)
{
return ds.template fold<unsigned>(
[](unsigned count, K3::Value) {
return count + 1;
}, 0);
}
class ElementNotFoundException : public std::runtime_error
{
public:
ElementNotFoundException(const K3::Value& val)
: std::runtime_error("Could not find element " + val)
{}
};
class ExtraElementsException : public std::runtime_error
{
public:
ExtraElementsException(unsigned i)
: std::runtime_error("Dataspace had " + toString(i) + " extra elements")
{ }
};
template<typename DS>
std::shared_ptr<DS> findAndRemoveElement(std::shared_ptr<DS> ds, const K3::Value& val)
{
if (!ds)
return std::shared_ptr<DS>(nullptr);
else {
if (containsDS(*ds, val)) {
ds->delete_first(val);
return ds;
}
else
throw ElementNotFoundException(val);
}
}
template<typename DS>
bool compareDataspaceToList(DS dataspace, std::vector<K3::Value> l)
{
std::shared_ptr<DS> ds_ptr = std::make_shared<DS>(dataspace);
std::shared_ptr<DS> result = std::accumulate(begin(l), end(l), ds_ptr,
[](std::shared_ptr<DS> ds, K3::Value cur_val) {
return findAndRemoveElement(ds, cur_val);
});
if (result) {
auto s = sizeDS(*result);
if (s == 0)
return true;
else
throw ExtraElementsException(s);
}
else
return false;
}
template<typename DS>
bool emptyPeek(std::shared_ptr<K3::Engine> engine)
{
DS d(engine.get());
std::shared_ptr<K3::Value> result = d.peek();
return result == nullptr;
}
template<typename DS>
bool testEmptyFold(std::shared_ptr<K3::Engine> engine)
{
DS d(engine.get());
unsigned counter = d.template fold<unsigned>(
[](unsigned accum, K3::Value) {
return accum + 1;
}, 0);
return counter == 0;
}
const std::vector<K3::Value> test_lst({"1", "2", "3", "4", "4", "100"});
template<typename DS>
bool testPeek(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
std::shared_ptr<K3::Value> peekResult = test_ds.peek();
if (!peekResult)
throw std::runtime_error("Peek returned nothing!");
else
return containsDS(test_ds, *peekResult);
}
template<typename DS>
bool testInsert(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get());
for( K3::Value val : test_lst )
test_ds.insert_basic(val);
return compareDataspaceToList(test_ds, test_lst);
}
template<typename DS>
bool testDelete(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.delete_first("3");
test_ds.delete_first("4");
std::vector<K3::Value> deleted_lst({"1", "2", "4", "100"});
return compareDataspaceToList(test_ds, deleted_lst);
}
template<typename DS>
bool testMissingDelete(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.delete_first("5");
return compareDataspaceToList(test_ds, test_lst);
}
template<typename DS>
bool testUpdate(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.update_first("1", "4");
std::vector<K3::Value> updated_answer({"4", "2", "3", "4", "4", "100"});
return compareDataspaceToList(test_ds, updated_answer);
}
template<typename DS>
bool testUpdateMultiple(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.update_first("4", "5");
std::vector<K3::Value> updated_answer({"1", "2", "3", "5", "4", "100"});
return compareDataspaceToList(test_ds, updated_answer);
}
template<typename DS>
bool testUpdateMissing(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.update_first("40", "5");
std::vector<K3::Value> updated_answer({"1", "2", "3", "4", "4", "100", "5"});
return compareDataspaceToList(test_ds, updated_answer);
}
template<typename DS>
bool testFold(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
unsigned test_sum = test_ds.template fold<unsigned>(
[](unsigned sum, K3::Value val) {
sum += fromString<unsigned>(val);
return sum;
}, 0);
return test_sum == 114;
}
template<typename DS>
bool testMap(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
DS mapped_ds = test_ds.map(
[](K3::Value val) {
return toString(fromString<int>(val) + 5);
});
std::vector<K3::Value> mapped_answer({"6", "7", "8", "9", "9", "105"});
return compareDataspaceToList(mapped_ds, mapped_answer);
}
template<typename DS>
bool testFilter(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
DS filtered = test_ds.filter([](K3::Value val) {
return fromString<int>(val) > 50;
});
std::vector<K3::Value> filtered_answer({"100"});
return compareDataspaceToList(filtered, filtered_answer);
}
template<typename DS>
bool testCombine(std::shared_ptr<K3::Engine> engine)
{
DS left_ds(engine.get(), begin(test_lst), end(test_lst));
DS right_ds(engine.get(), begin(test_lst), end(test_lst));
DS combined = left_ds.combine(right_ds);
std::vector<K3::Value> long_lst(test_lst);
long_lst.insert(end(long_lst), begin(test_lst), end(test_lst));
return compareDataspaceToList(combined, long_lst);
}
template<typename DS>
bool testCombineSelf(std::shared_ptr<K3::Engine> engine)
{
DS self(engine.get(), begin(test_lst), end(test_lst));
DS combined = self.combine(self);
std::vector<K3::Value> long_lst(test_lst);
long_lst.insert(end(long_lst), begin(test_lst), end(test_lst));
return compareDataspaceToList(combined, long_lst);
}
template<typename DS>
std::shared_ptr<std::tuple<DS, DS>> split_findAndRemoveElement(std::shared_ptr<std::tuple<DS, DS>> maybeTuple, K3::Value cur_val)
{
typedef std::shared_ptr<std::tuple<DS, DS>> MaybePair;
if (!maybeTuple) {
return nullptr;
}
else {
DS& left = std::get<0>(*maybeTuple);
DS& right = std::get<1>(*maybeTuple);
if (containsDS(left, cur_val)) {
left.delete_first(cur_val);
// TODO copying everywhere!
// this copies the DS into the tuple, then the tuple is copied into the new target of the shared_ptr
return std::make_shared<std::tuple<DS, DS>>(std::make_tuple(left, right));
}
else if (containsDS(right, cur_val)) {
right.delete_first(cur_val);
// TODO see above
return std::make_shared<std::tuple<DS, DS>>(std::make_tuple(left, right));
}
else {
throw ElementNotFoundException(cur_val);
return MaybePair(nullptr);
}
}
}
template<typename DS>
bool testSplit(std::shared_ptr<K3::Engine> engine)
{
std::vector<K3::Value> long_lst(test_lst);
long_lst.insert(end(long_lst), begin(test_lst), end(test_lst));
DS first_ds(engine.get(), begin(long_lst), end(long_lst));
std::tuple<DS, DS> split_pair = first_ds.split();
DS& left = std::get<0>(split_pair);
DS& right = std::get<1>(split_pair);
unsigned leftLen = sizeDS(left);
unsigned rightLen = sizeDS(right);
// TODO should the >= be just > ?
if (leftLen >= long_lst.size() || rightLen >= long_lst.size() || leftLen + rightLen > long_lst.size())
return false;
else {
std::shared_ptr<std::tuple<DS, DS>> remainders = std::make_shared<std::tuple<DS, DS>>(std::make_tuple(left, right));
for (K3::Value val : long_lst)
remainders = split_findAndRemoveElement(remainders, val);
if (!remainders) {
return false;
}
else {
const DS& l = std::get<0>(*remainders);
const DS& r = std::get<1>(*remainders);
return (sizeDS(l) == 0 && sizeDS(r) == 0);
}
}
}
// TODO This just makes sure that nothing crashes, but should probably check for correctness also
// This test is commented out because it segfaults clang 3.4. It's bug #18473.
// There's a temporary fix in r200954 that may be included in 3.4.1, but that's not released yet.
//template<typename DS>
//bool insertInsideMap(std::shared_ptr<K3::Engine> engine)
//{
// DS outer_ds(engine.get(), begin(test_lst), end(test_lst));
// DS result_ds = outer_ds.map([&outer_ds, &v, &v4](K3::Value cur_val) {
// outer_ds.insert_basic("256");
// return "4";
// });
// return true;
//}
// Engine setup
std::shared_ptr<K3::Engine> buildEngine()
{
// Configure engine components
bool simulation = true;
K3::SystemEnvironment s_env = K3::defaultEnvironment();
auto i_cdec = std::shared_ptr<K3::InternalCodec>(new K3::DefaultInternalCodec());
auto e_cdec = std::shared_ptr<K3::ExternalCodec>(new K3::DefaultCodec());
// Construct an engine
K3::Engine * engine = new K3::Engine(simulation, s_env, i_cdec, e_cdec);
return std::shared_ptr<K3::Engine>(engine);
}
void callTest(std::function<bool(std::shared_ptr<K3::Engine>)> testFunc)
{
auto engine = buildEngine();
bool success = false;
try {
success = testFunc(engine);
xUnitpp::Assert.Equal(success, true);
}
catch( const std::exception& e)
{
xUnitpp::Assert.Fail() << e.what();
}
}
#define MAKE_TEST(name, function, ds) \
FACT(name) { callTest(function<ds>); }
SUITE("List Dataspace") {
MAKE_TEST( "EmptyPeek", emptyPeek, ListDataspace)
MAKE_TEST( "Fold on Empty List Test", testEmptyFold, ListDataspace)
MAKE_TEST( "Peek Test", testPeek, ListDataspace)
MAKE_TEST( "Insert Test", testInsert, ListDataspace)
MAKE_TEST( "Delete Test", testDelete, ListDataspace)
MAKE_TEST( "Delete of missing element Test", testMissingDelete, ListDataspace)
MAKE_TEST( "Update Test", testUpdate, ListDataspace)
MAKE_TEST( "Update Multiple Test", testUpdateMultiple, ListDataspace)
MAKE_TEST( "Update missing element Test", testUpdateMissing, ListDataspace)
MAKE_TEST( "Fold Test", testFold, ListDataspace)
MAKE_TEST( "Map Test", testMap, ListDataspace)
MAKE_TEST( "Filter Test", testFilter, ListDataspace)
MAKE_TEST( "Combine Test", testCombine, ListDataspace)
MAKE_TEST( "Combine with Self Test", testCombineSelf, ListDataspace)
MAKE_TEST( "Split Test", testSplit, ListDataspace)
MAKE_TEST( "Insert inside map", insertInsideMap, ListDataspace)
}
//SUITE("File Dataspace") {
// MAKE_TEST( "EmptyPeek", emptyPeek, FileDataspace)
// MAKE_TEST( "Fold on Empty List Test", testEmptyFold, FileDataspace)
// MAKE_TEST( "Peek Test", testPeek, FileDataspace)
// /*MAKE_TEST( "Insert Test", testInsert, FileDataspace)
// MAKE_TEST( "Delete Test", testDelete, FileDataspace)
// MAKE_TEST( "Delete of missing element Test", testMissingDelete, FileDataspace)
// MAKE_TEST( "Update Test", testUpdate, FileDataspace)
// MAKE_TEST( "Update Multiple Test", testUpdateMultiple, FileDataspace)
// MAKE_TEST( "Update missing element Test", testUpdateMissing, FileDataspace)
// MAKE_TEST( "Fold Test", testFold, FileDataspace)
// MAKE_TEST( "Map Test", testMap, FileDataspace)
// MAKE_TEST( "Filter Test", testFilter, FileDataspace)
// MAKE_TEST( "Combine Test", testCombine, FileDataspace)
// MAKE_TEST( "Combine with Self Test", testCombineSelf, FileDataspace)
// MAKE_TEST( "Split Test", testSplit, FileDataspace)
// MAKE_TEST( "Insert inside map", insertInsideMap, FileDataspace)*/
//}
//MAKE_TEST_GROUP("List Dataspace", ListDataspace)
//MAKE_TEST_GROUP("File Dataspace", FileDataspace)
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifndef NET_CONNTRACK_HPP
#define NET_CONNTRACK_HPP
#include <net/socket.hpp>
#include <net/ip4/packet_ip4.hpp>
#include <vector>
#include <map>
#include <rtc>
#include "netfilter.hpp"
namespace net {
class Conntrack {
public:
struct Entry;
/**
* Custom handler for tracking packets in a certain way
*/
using Packet_tracker = delegate<Entry*(Conntrack&, Quadruple, const PacketIP4&)>;
using Entry_handler = delegate<void(Entry*)>;
/**
* @brief Key for lookup tables
*/
struct Quintuple {
Quadruple quad;
Protocol proto;
Quintuple(Quadruple q, const Protocol p)
: quad(std::move(q)), proto(p)
{}
bool operator==(const Quintuple& other) const noexcept
{ return proto == other.proto and quad == other.quad; }
bool operator<(const Quintuple& other) const noexcept {
return proto < other.proto
or (proto == other.proto and quad < other.quad);
}
};
/**
* @brief The state of the connection.
*/
enum class State : uint8_t {
NEW,
ESTABLISHED,
RELATED
};
/**
* @brief Which direction packet has been seen on a connection.
*/
enum class Seen : uint8_t {
OUT, IN, BOTH
};
/**
* @brief A entry in the connection tracker (a Connection)
*/
struct Entry {
Quadruple first;
Quadruple second;
RTC::timestamp_t timeout;
Protocol proto;
State state;
Entry(Quadruple quad, Protocol p)
: first{std::move(quad)}, second{first.dst, first.src},
proto(p), state(State::NEW)
{}
bool is_mirrored() const noexcept
{ return first.src == second.dst and first.dst == second.src; }
std::string to_string() const;
};
public:
/**
* @brief Find the entry where the quadruple
* with the given protocol matches.
*
* @param[in] quad The quad
* @param[in] proto The prototype
*
* @return A matching conntrack entry (nullptr if not found)
*/
Entry* get(const Quadruple& quad, const Protocol proto) const;
/**
* @brief Track a packet, updating the state of the entry.
*
* @param[in] pkt The packet
*
* @return The conntrack entry related to this packet.
*/
Entry* in(const PacketIP4& pkt);
/**
* @brief Confirms a connection, moving the entry to confirmed.
*
* @param[in] pkt The packet
*
* @return { description_of_the_return_value }
*/
Entry* confirm(const PacketIP4& pkt);
/**
* @brief Adds an entry, mirroring the quadruple.
*
* @param[in] quad The quadruple
* @param[in] proto The prototype
* @param[in] dir The direction the packet is going
*
* @return { description_of_the_return_value }
*/
Entry* add_entry(const Quadruple& quad, const Protocol proto);
void update_entry(const Protocol proto, const Quadruple& oldq, const Quadruple& newq);
void remove_entry(Entry*);
/**
* @brief A very simple and unreliable way for tracking quintuples.
*
* @param[in] quad The quad
* @param[in] proto The prototype
*
* @return The conntrack entry related to quintuple.
*/
Entry* simple_track_in(Quadruple quad, const Protocol proto);
/**
* @brief Gets the quadruple from a IP4 packet.
* Assumes the packet has protocol specific payload.
*
* @param[in] pkt The packet
*
* @return The quadruple.
*/
static Quadruple get_quadruple(const PacketIP4& pkt);
static Quadruple get_quadruple_icmp(const PacketIP4& pkt);
template<typename IPV>
Packetfilter<IPV> in_filter() {
return [this] (PacketIP4& pkt, Inet<IPV>&)->auto {
return (in(pkt) != nullptr)
? Filter_verdict::ACCEPT : Filter_verdict::DROP;
};
}
template<typename IPV>
Packetfilter<IPV> confirm_filter() {
return [this] (PacketIP4& pkt, Inet<IPV>&)->auto {
confirm(pkt);
return Filter_verdict::ACCEPT; // always accept?
};
}
Conntrack();
using Timeout_duration = std::chrono::seconds;
Timeout_duration timeout_new {30};
Timeout_duration timeout_est {180};
Timeout_duration timeout_new_tcp {60};
Timeout_duration timeout_est_tcp {600};
Packet_tracker tcp_in;
Entry_handler on_close; // single for now
private:
using Entry_table = std::map<Quintuple, std::shared_ptr<Entry>>;
Entry_table entries;
Entry_table unconfirmed;
void update_timeout(Entry& ent, Timeout_duration dur);
};
}
#endif
<commit_msg>net: Add chrono include to conntrack<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifndef NET_CONNTRACK_HPP
#define NET_CONNTRACK_HPP
#include <net/socket.hpp>
#include <net/ip4/packet_ip4.hpp>
#include <vector>
#include <map>
#include <rtc>
#include <chrono>
#include "netfilter.hpp"
namespace net {
class Conntrack {
public:
struct Entry;
/**
* Custom handler for tracking packets in a certain way
*/
using Packet_tracker = delegate<Entry*(Conntrack&, Quadruple, const PacketIP4&)>;
using Entry_handler = delegate<void(Entry*)>;
/**
* @brief Key for lookup tables
*/
struct Quintuple {
Quadruple quad;
Protocol proto;
Quintuple(Quadruple q, const Protocol p)
: quad(std::move(q)), proto(p)
{}
bool operator==(const Quintuple& other) const noexcept
{ return proto == other.proto and quad == other.quad; }
bool operator<(const Quintuple& other) const noexcept {
return proto < other.proto
or (proto == other.proto and quad < other.quad);
}
};
/**
* @brief The state of the connection.
*/
enum class State : uint8_t {
NEW,
ESTABLISHED,
RELATED
};
/**
* @brief Which direction packet has been seen on a connection.
*/
enum class Seen : uint8_t {
OUT, IN, BOTH
};
/**
* @brief A entry in the connection tracker (a Connection)
*/
struct Entry {
Quadruple first;
Quadruple second;
RTC::timestamp_t timeout;
Protocol proto;
State state;
Entry(Quadruple quad, Protocol p)
: first{std::move(quad)}, second{first.dst, first.src},
proto(p), state(State::NEW)
{}
bool is_mirrored() const noexcept
{ return first.src == second.dst and first.dst == second.src; }
std::string to_string() const;
};
public:
/**
* @brief Find the entry where the quadruple
* with the given protocol matches.
*
* @param[in] quad The quad
* @param[in] proto The prototype
*
* @return A matching conntrack entry (nullptr if not found)
*/
Entry* get(const Quadruple& quad, const Protocol proto) const;
/**
* @brief Track a packet, updating the state of the entry.
*
* @param[in] pkt The packet
*
* @return The conntrack entry related to this packet.
*/
Entry* in(const PacketIP4& pkt);
/**
* @brief Confirms a connection, moving the entry to confirmed.
*
* @param[in] pkt The packet
*
* @return { description_of_the_return_value }
*/
Entry* confirm(const PacketIP4& pkt);
/**
* @brief Adds an entry, mirroring the quadruple.
*
* @param[in] quad The quadruple
* @param[in] proto The prototype
* @param[in] dir The direction the packet is going
*
* @return { description_of_the_return_value }
*/
Entry* add_entry(const Quadruple& quad, const Protocol proto);
void update_entry(const Protocol proto, const Quadruple& oldq, const Quadruple& newq);
void remove_entry(Entry*);
/**
* @brief A very simple and unreliable way for tracking quintuples.
*
* @param[in] quad The quad
* @param[in] proto The prototype
*
* @return The conntrack entry related to quintuple.
*/
Entry* simple_track_in(Quadruple quad, const Protocol proto);
/**
* @brief Gets the quadruple from a IP4 packet.
* Assumes the packet has protocol specific payload.
*
* @param[in] pkt The packet
*
* @return The quadruple.
*/
static Quadruple get_quadruple(const PacketIP4& pkt);
static Quadruple get_quadruple_icmp(const PacketIP4& pkt);
template<typename IPV>
Packetfilter<IPV> in_filter() {
return [this] (PacketIP4& pkt, Inet<IPV>&)->auto {
return (in(pkt) != nullptr)
? Filter_verdict::ACCEPT : Filter_verdict::DROP;
};
}
template<typename IPV>
Packetfilter<IPV> confirm_filter() {
return [this] (PacketIP4& pkt, Inet<IPV>&)->auto {
confirm(pkt);
return Filter_verdict::ACCEPT; // always accept?
};
}
Conntrack();
using Timeout_duration = std::chrono::seconds;
Timeout_duration timeout_new {30};
Timeout_duration timeout_est {180};
Timeout_duration timeout_new_tcp {60};
Timeout_duration timeout_est_tcp {600};
Packet_tracker tcp_in;
Entry_handler on_close; // single for now
private:
using Entry_table = std::map<Quintuple, std::shared_ptr<Entry>>;
Entry_table entries;
Entry_table unconfirmed;
void update_timeout(Entry& ent, Timeout_duration dur);
};
}
#endif
<|endoftext|> |
<commit_before>#include "./Chromosome.hh"
Chromosome::Chromosome()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(MIN_GENE_VALUE, MAX_GENE_VALUE);
for (int j = 0; j < GENE_PER_CHROMOSOME; j++)
_strand.push_back(dis(gen));
}
void Chromosome::setFitness(double fitness) {
_fitness = fitness;
}
Chromosome::Children
Chromosome::reproduce(Problem *problem, const Chromosome * const c1, const Chromosome * const c2)
{
Chromosome *n1 = new Chromosome();
Chromosome *n2 = new Chromosome();
Strand tmp1 = c1->getStrand();
Strand tmp2 = c2->getStrand();
Gene g1, g2;
int i, randomPos, currentGeneId, currentBitId;
if ((double)rand() / RAND_MAX <= CROSSOVER_RATE)
{
randomPos = rand() % CHROMOSOME_SIZE;
for (i = randomPos; i < CHROMOSOME_SIZE; i++)
{
currentGeneId = i / GENE_SIZE;
currentBitId = i - (currentGeneId * GENE_SIZE);
g1 = (tmp1[currentGeneId] >> currentBitId) & 1;
g2 = (tmp2[currentGeneId] >> currentBitId) & 1;
tmp1[currentGeneId] |= 1 << g2;
tmp2[currentGeneId] |= 1 << g1;
}
}
n1->set(problem, tmp1);
n2->set(problem, tmp2);
return {n1, n2};
}
void Chromosome::mutate(Problem *problem)
{
double randomNb;
int currentGeneId, currentBitId;
for (int i = 0; i < CHROMOSOME_SIZE; i++)
{
randomNb = (double)rand() / RAND_MAX;
currentGeneId = i / GENE_SIZE;
currentBitId = i - (currentGeneId * GENE_SIZE);
if (randomNb <= MUTATION_RATE)
{
_strand[currentGeneId] ^= 1 << currentBitId;
try {
setValue(problem);
} catch (int e) {
_hasValue = false;
}
}
}
}
Chromosome::Strand Chromosome::getStrand() const
{
return _strand;
}
double Chromosome::getValue() const
{
return _value;
}
void Chromosome::setValue(Problem *problem)
{
try {
_value = problem->computeValue(this);
} catch (int e) {
_hasValue = false;
}
}
bool Chromosome::isValid() const
{
return _hasValue;
}
double Chromosome::getFitness() const
{
return _fitness;
}
void Chromosome::set(Problem *problem, const Strand strand)
{
_strand = strand;
setValue(problem);
}
<commit_msg>GA is now more generic<commit_after>#include "./Chromosome.hh"
Chromosome::Chromosome()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(MIN_GENE_VALUE, MAX_GENE_VALUE);
for (int j = 0; j < GENE_PER_CHROMOSOME; j++)
_strand.push_back(dis(gen));
}
void Chromosome::setFitness(double fitness) {
_fitness = fitness;
}
Chromosome::Children
Chromosome::reproduce(Problem *problem, const Chromosome * const c1, const Chromosome * const c2)
{
Chromosome *n1 = new Chromosome();
Chromosome *n2 = new Chromosome();
Strand tmp1 = c1->getStrand();
Strand tmp2 = c2->getStrand();
Gene g1, g2;
int i, randomPos, currentGeneId, currentBitId;
if ((double)rand() / RAND_MAX <= CROSSOVER_RATE)
{
randomPos = rand() % CHROMOSOME_SIZE;
for (i = randomPos; i < CHROMOSOME_SIZE; i++)
{
currentGeneId = i / GENE_SIZE;
currentBitId = i - (currentGeneId * GENE_SIZE);
g1 = (tmp1[currentGeneId] >> currentBitId) & 1;
g2 = (tmp2[currentGeneId] >> currentBitId) & 1;
tmp1[currentGeneId] |= 1 << g2;
tmp2[currentGeneId] |= 1 << g1;
}
}
n1->set(problem, tmp1);
n2->set(problem, tmp2);
return {n1, n2};
}
void Chromosome::mutate(Problem *problem)
{
double randomNb;
int currentGeneId, currentBitId;
for (int i = 0; i < CHROMOSOME_SIZE; i++)
{
randomNb = (double)rand() / RAND_MAX;
currentGeneId = i / GENE_SIZE;
currentBitId = i - (currentGeneId * GENE_SIZE);
if (randomNb <= MUTATION_RATE)
{
_strand[currentGeneId] ^= 1 << currentBitId;
try {
setValue(problem);
} catch (int e) {
_hasValue = false;
}
}
}
}
Chromosome::Strand Chromosome::getStrand() const
{
return _strand;
}
double Chromosome::getValue() const
{
return _value;
}
void Chromosome::setValue(Problem *problem)
{
try {
_value = problem->computeValue(this);
} catch (int e) {
_hasValue = false;
}
}
bool Chromosome::isValid() const
{
return _hasValue;
}
double Chromosome::getFitness() const
{
return _fitness;
}
void Chromosome::set(Problem *problem, const Strand strand)
{
_strand = strand;
setValue(problem);
}
<|endoftext|> |
<commit_before>//===- islClan.cpp ---------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Example clang plugin which simply prints the names of all the top-level decls
// in the input file.
//
//===----------------------------------------------------------------------===//
// clang llvm
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/raw_ostream.h"
// std
#include <fstream>
#include <chrono>
#include <iostream>
#include <map>
#include <string>
#include <memory>
#include <mutex>
// logging
#include "plog/Log.h"
#include "plog/Appenders/ConsoleAppender.h"
#include "PetPlutoInterface.hpp"
#include "ClangPetInterface.hpp"
using namespace clang;
using namespace clang::ast_matchers;
using namespace pluto_codegen_cxx;
namespace {
class Callback : public MatchFinder::MatchCallback {
public:
Callback ( CodeGenerationType _emit_code_type, bool _write_cloog_file ) :
emit_code_type(_emit_code_type),
write_cloog_file(_write_cloog_file)
{
}
// is the function that is called if the matcher finds something
virtual void run(const MatchFinder::MatchResult &Result){
LOGD << "plugin: callback called " ;
ASTContext& context = *Result.Context;
SourceManager& SM = context.getSourceManager();
if ( auto function_decl = Result.Nodes.getNodeAs<FunctionDecl>("function_decl") ) {
if ( auto for_stmt = Result.Nodes.getNodeAs<ForStmt>("for_stmt") ) {
auto loc = for_stmt->getLocStart();
if ( SM.isInMainFile( loc ) ) {
std::unique_ptr<std::map<std::string,std::string>> call_texts;
ClangPetInterface cp_interface(context, for_stmt);
pet_scop* scop = cp_interface.extract_scop( function_decl, call_texts );
if ( scop ) {
LOGD << "found a valid scop" ;
// TODO move to pet code
// find the text of the original statement
auto statement_texts = cp_interface.get_statement_texts( scop );
// TODO move common variables into the ctor
PetPlutoInterface pp_interface(header_includes, emit_code_type, write_cloog_file);
if ( pp_interface.create_scop_replacement( scop, statement_texts, call_texts ) ){
LOGD << "emitting diagnositc" ;
DiagnosticsEngine& diag = context.getDiagnostics();
unsigned DiagID = diag.getCustomDiagID(DiagnosticsEngine::Warning, "found a loop to optimize - press F7 to apply");
LOGD << "got id " << DiagID ;
auto replacement = pp_interface.getReplacement();
auto begin_scop = cp_interface.getLocBeginOfScop();
// replace the for statement
diag.Report(begin_scop, DiagID) << FixItHint::CreateReplacement(for_stmt->getSourceRange(), replacement.c_str() );
LOGD << "reported error " << DiagID ;
}else{
// TODO this is the point to emit information about why it was not possible to
// parallelize this loop
for( auto& pet_explanation : pp_interface.pet_expanations ){
unsigned int loc = std::get<0>(pet_explanation);
auto clang_src_loc = cp_interface.getLocRelativeToFileBegin( loc );
DiagnosticsEngine& diag = context.getDiagnostics();
unsigned DiagID = diag.getCustomDiagID(DiagnosticsEngine::Warning, "Dependency: %0" );
diag.Report(clang_src_loc, DiagID) << std::get<2>(pet_explanation) ;
}
}
}
}
}
}
}
std::set<std::string> header_includes;
private:
CodeGenerationType emit_code_type;
bool write_cloog_file;
};
// return everything beginnign with l to the end of the line
static std::string getText( SourceLocation l, SourceManager& SM ) {
bool invalid;
const char* data = SM.getCharacterData( l, &invalid ) ;
if ( !invalid ) {
const char* line_end = strchr(data, '\n');
if ( !line_end )
return data;
return std::string(data, line_end - data);
}
return "invalid";
}
// used to track what the preprocessor does when it enters the separate files
class PPEnterCallback : public clang::PPCallbacks {
public:
PPEnterCallback ( clang::SourceManager& _SM) :
SM(_SM)
{
}
std::string parseHeaderName( std::string include_stmt ) {
// skip " " to first char
// check for < or "
// search for corresponding closing char
bool local_include = false;
bool global_include = false;
bool skip = true;
std::string name = "";
for (int i = 0; i < include_stmt.size(); ++i){
char c = include_stmt[i];
if ( skip && isWhitespace( std::isspace( c ) ) ) continue;
if ( c == '"' ) {
local_include = true;
skip = false;
continue;
}
if ( c == '<' ) {
global_include = true;
skip = false;
continue;
}
if ( local_include && c == '"' ) {
break;
}
if ( global_include && c == '>' ) {
break;
}
name += c;
}
return name;
}
virtual void FileChanged( SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID=FileID() ) {
if ( Reason == EnterFile ) {
auto file_begin = Loc;
auto iloc = SM.getIncludeLoc( SM.getFileID(file_begin) );
auto text = getText( iloc, SM );
if ( text != "invalid" ) {
LOGD << "preprocessor " << text ;
auto name = parseHeaderName( text );
LOGD << "preprocessor parsed name " << name ;
// TODO this can happen in parallel lock it with a mutex
std::lock_guard<std::mutex> lock(getMutex());
getHeaderSet().insert( name );
}
}
}
std::mutex& getMutex( ){
static std::mutex header_mutex;
return header_mutex;
}
// as a first step simply store the header names
// TODO add the positions in which they were included
std::set<std::string>& getHeaderSet(){
static std::set<std::string> headers;
return headers;
}
private:
clang::SourceManager& SM;
};
class ForLoopConsumer : public ASTConsumer {
public:
ForLoopConsumer( CodeGenerationType _emit_code_type, bool _write_cloog_file, PPEnterCallback* callbacks ) :
emit_code_type(_emit_code_type),
write_cloog_file(_write_cloog_file),
enter_callback( callbacks )
{
LOGD << "for loop consumer created " << this ;
}
~ForLoopConsumer(){
LOGD << "for loop consumer destroyed " << this ;
}
// all for loops that dont have a nested for loop
DeclarationMatcher makeForLoopMatcher(){
return functionDecl(
forEachDescendant(
forStmt(
#if 1
unless(
hasAncestor(
forStmt()
)
)
#endif
).bind("for_stmt")
)
).bind("function_decl");
}
#if 1
void HandleTranslationUnit( ASTContext& clang_ctx ) {
auto begin = std::chrono::high_resolution_clock::now();
MatchFinder Finder;
Callback Fixer(emit_code_type, write_cloog_file);
LOGD << "adding matcher" ;
Finder.addMatcher( makeForLoopMatcher(), &Fixer);
LOGD << "running matcher" ;
Finder.matchAST(clang_ctx);
add_missing_includes(Fixer, clang_ctx);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = end-begin;
LOGD << "plugin: time consumption " << diff.count() << " s" ;
}
bool isHeaderAlreadyIncluded( std::string header, ASTContext& clang_ctx ) {
std::lock_guard<std::mutex> lock(enter_callback->getMutex());
LOGD << "plugin: number of already included headers " << enter_callback->getHeaderSet().size() ;
for( auto& included_header : enter_callback->getHeaderSet() ){
LOGD << "comparing: " << included_header << " with " << header ;
if ( header == included_header ) {
LOGD << "plugin: header is already included" ;
return true;
}
}
return false;
}
void add_missing_includes(Callback& Fixer, ASTContext& clang_ctx) {
for( auto& header : Fixer.header_includes ){
// dont add if the header is already included
if ( isHeaderAlreadyIncluded( header, clang_ctx ) ) continue;
// TODO skip the lines that begin with a comment
// this way its possible to skip licences that are mostly at the beginning of a file
// TODO perhaps search for a marker that the user can add to the file
// might be better to add the includes there if the user has to ensure a certain order of includes
auto& SM = clang_ctx.getSourceManager();
auto fid = SM.getMainFileID();
auto line = 1;
auto col = 1;
auto name = header;
auto begin_of_file = SM.translateLineCol( fid, line, col );
auto& diag = clang_ctx.getDiagnostics();
unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning, "missing header");
diag.Report(begin_of_file, id) << FixItHint::CreateInsertion(begin_of_file, std::string("#include <") + name + ">\n" );
}
}
#endif
private:
CodeGenerationType emit_code_type;
bool write_cloog_file;
PPEnterCallback* enter_callback;
};
static bool once_std_out = true;
static bool once_std_err = true;
class ClanAction : public PluginASTAction {
public:
ClanAction(){
static bool once = true;
if ( once ) {
static plog::ConsoleAppender<plog::TxtFormatter> consoleAppender;
plog::init(plog::debug, &consoleAppender);
once = false;
LOGD << "logger initialized ";
}
LOGD << "clang action " << this << " created " ;
}
virtual ~ClanAction(){
LOGD << "clang action " << this << " destroyed ";
}
// Automatically run the plugin after the main AST action
PluginASTAction::ActionType getActionType() override {
return AddAfterMainAction;
}
protected:
CodeGenerationType emit_code_type = CodeGenerationType::ACC;
bool write_cloog_file = false;
std::string redirect_stdout_file = "";
std::string redirect_stderr_file = "";
// NOTE: stefan this creates the consumer that is given the TU after everything is done
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) override;
bool ParseArgs(const CompilerInstance &CI, const std::vector<std::string> &args) override;
void PrintHelp(llvm::raw_ostream& ros) {
ros << "run the plugin with -emit-[openmp,openacc,hpx,tbb,cilk] to get different implementations for the loops\n";
}
};
PPEnterCallback* setupCallbacks( CompilerInstance& CI ) {
if ( CI.hasPreprocessor() ) {
auto& pp = CI.getPreprocessor();
LOGD << "plugin: got the preprocessor" ;
if ( CI.hasSourceManager() ) {
auto& SM = CI.getSourceManager();
std::unique_ptr<PPCallbacks> base_ptr( new PPEnterCallback(SM) );
auto* ret = (PPEnterCallback*)base_ptr.get();
pp.addPPCallbacks( std::move( base_ptr ) );
return ret;
}
}else{
LOGD << "ci does not have a preprocessor" ;
}
return nullptr;
}
std::unique_ptr<ASTConsumer>
ClanAction::CreateASTConsumer(CompilerInstance &CI, llvm::StringRef){
if ( redirect_stdout_file != "" ) {
LOGD << "redirect_stdout_file " << redirect_stdout_file;
// TODO mutex
if ( once_std_out ) {
std::freopen(redirect_stdout_file.c_str(), "a", stdout);
setvbuf ( stdout , NULL , _IOLBF , 1024 );
once_std_out = false;
}
}
if ( redirect_stderr_file != "" ) {
LOGD << "redirect_stderr_file " << redirect_stderr_file;
// TODO mutex
if ( once_std_err ) {
std::freopen(redirect_stderr_file.c_str(), "a", stderr);
setvbuf ( stderr , NULL , _IOLBF , 1024 );
once_std_err = false;
}
}
LOGD << "makeing new Consumer object with compiler instance " << &CI ;
auto enter_callback = setupCallbacks( CI );
auto ret = llvm::make_unique<ForLoopConsumer>(emit_code_type, write_cloog_file, enter_callback);
LOGD << "at load ci " << ret.get() << " instance " << &CI << " ast context " << &CI.getASTContext() << " SM " << &CI.getSourceManager() ;
LOGD << "done with the new consumer object" ;
// TODO find all header includs in the main file and pass them to the ForLoopConsumer
return std::move(ret);
}
bool
ClanAction::ParseArgs(const CompilerInstance &CI, const std::vector<std::string> &args) {
std::string* next_arg = nullptr;
for (unsigned i = 0, e = args.size(); i != e; ++i) {
LOGD << "Clan arg = " << args[i];
if ( next_arg ) {
*next_arg = args[i];
next_arg = nullptr;
continue;
}
if ( args[i] == "-emit-openacc" ) {
LOGD << "emiting openacc" ;
emit_code_type = CodeGenerationType::ACC;
}
if ( args[i] == "-emit-openmp" ) {
LOGD << "emiting openmp" ;
emit_code_type = CodeGenerationType::OMP;
}
if ( args[i] == "-emit-hpx" ) {
LOGD << "emiting hpx" ;
emit_code_type = CodeGenerationType::HPX;
}
if ( args[i] == "-emit-tbb" ) {
LOGD << "emiting tbb" ;
emit_code_type = CodeGenerationType::TBB;
}
if ( args[i] == "-emit-cilk" ) {
LOGD << "emiting cilk" ;
emit_code_type = CodeGenerationType::CILK;
}
if ( args[i] == "-emit-cuda" ) {
LOGD << "emiting cuda" ;
emit_code_type = CodeGenerationType::CUDA;
}
// add new back-ends here
if ( args[i] == "-write-cloog-file" ) {
LOGD << "writing cloog file" ;
write_cloog_file = true;
}
if ( args[i] == "-redirect-stdout" ) {
LOGD << "redirecting stdout" ;
next_arg = &redirect_stdout_file;
}
if ( args[i] == "-redirect-stderr" ) {
LOGD << "redirecting stderr" ;
next_arg = &redirect_stderr_file;
}
}
return true;
}
} // namespace end
// TODO change name
static FrontendPluginRegistry::Add<ClanAction>
X("clan", "run clan as part of the compiler");
<commit_msg>matcher does not select loops in functiontemplatdecl anymore<commit_after>//===- islClan.cpp ---------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Example clang plugin which simply prints the names of all the top-level decls
// in the input file.
//
//===----------------------------------------------------------------------===//
// clang llvm
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/raw_ostream.h"
// std
#include <fstream>
#include <chrono>
#include <iostream>
#include <map>
#include <string>
#include <memory>
#include <mutex>
// logging
#include "plog/Log.h"
#include "plog/Appenders/ConsoleAppender.h"
#include "PetPlutoInterface.hpp"
#include "ClangPetInterface.hpp"
using namespace clang;
using namespace clang::ast_matchers;
using namespace pluto_codegen_cxx;
namespace {
class Callback : public MatchFinder::MatchCallback {
public:
Callback ( CodeGenerationType _emit_code_type, bool _write_cloog_file ) :
emit_code_type(_emit_code_type),
write_cloog_file(_write_cloog_file)
{
}
// is the function that is called if the matcher finds something
virtual void run(const MatchFinder::MatchResult &Result){
LOGD << "plugin: callback called " ;
ASTContext& context = *Result.Context;
SourceManager& SM = context.getSourceManager();
if ( auto function_decl = Result.Nodes.getNodeAs<FunctionDecl>("function_decl") ) {
if ( auto for_stmt = Result.Nodes.getNodeAs<ForStmt>("for_stmt") ) {
auto loc = for_stmt->getLocStart();
if ( SM.isInMainFile( loc ) ) {
function_decl->dumpColor();
std::unique_ptr<std::map<std::string,std::string>> call_texts;
ClangPetInterface cp_interface(context, for_stmt);
pet_scop* scop = cp_interface.extract_scop( function_decl, call_texts );
if ( scop ) {
LOGD << "found a valid scop" ;
// TODO move to pet code
// find the text of the original statement
auto statement_texts = cp_interface.get_statement_texts( scop );
// TODO move common variables into the ctor
PetPlutoInterface pp_interface(header_includes, emit_code_type, write_cloog_file);
if ( pp_interface.create_scop_replacement( scop, statement_texts, call_texts ) ){
LOGD << "emitting diagnositc" ;
DiagnosticsEngine& diag = context.getDiagnostics();
unsigned DiagID = diag.getCustomDiagID(DiagnosticsEngine::Warning, "found a loop to optimize - press F7 to apply");
LOGD << "got id " << DiagID ;
auto replacement = pp_interface.getReplacement();
auto begin_scop = cp_interface.getLocBeginOfScop();
// replace the for statement
diag.Report(begin_scop, DiagID) << FixItHint::CreateReplacement(for_stmt->getSourceRange(), replacement.c_str() );
LOGD << "reported error " << DiagID ;
}else{
// TODO this is the point to emit information about why it was not possible to
// parallelize this loop
for( auto& pet_explanation : pp_interface.pet_expanations ){
unsigned int loc = std::get<0>(pet_explanation);
auto clang_src_loc = cp_interface.getLocRelativeToFileBegin( loc );
DiagnosticsEngine& diag = context.getDiagnostics();
unsigned DiagID = diag.getCustomDiagID(DiagnosticsEngine::Warning, "Dependency: %0" );
diag.Report(clang_src_loc, DiagID) << std::get<2>(pet_explanation) ;
}
}
}
}
}
}
}
std::set<std::string> header_includes;
private:
CodeGenerationType emit_code_type;
bool write_cloog_file;
};
// return everything beginnign with l to the end of the line
static std::string getText( SourceLocation l, SourceManager& SM ) {
bool invalid;
const char* data = SM.getCharacterData( l, &invalid ) ;
if ( !invalid ) {
const char* line_end = strchr(data, '\n');
if ( !line_end )
return data;
return std::string(data, line_end - data);
}
return "invalid";
}
// used to track what the preprocessor does when it enters the separate files
class PPEnterCallback : public clang::PPCallbacks {
public:
PPEnterCallback ( clang::SourceManager& _SM) :
SM(_SM)
{
}
std::string parseHeaderName( std::string include_stmt ) {
// skip " " to first char
// check for < or "
// search for corresponding closing char
bool local_include = false;
bool global_include = false;
bool skip = true;
std::string name = "";
for (int i = 0; i < include_stmt.size(); ++i){
char c = include_stmt[i];
if ( skip && isWhitespace( std::isspace( c ) ) ) continue;
if ( c == '"' ) {
local_include = true;
skip = false;
continue;
}
if ( c == '<' ) {
global_include = true;
skip = false;
continue;
}
if ( local_include && c == '"' ) {
break;
}
if ( global_include && c == '>' ) {
break;
}
name += c;
}
return name;
}
virtual void FileChanged( SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID=FileID() ) {
if ( Reason == EnterFile ) {
auto file_begin = Loc;
auto iloc = SM.getIncludeLoc( SM.getFileID(file_begin) );
auto text = getText( iloc, SM );
if ( text != "invalid" ) {
LOGD << "preprocessor " << text ;
auto name = parseHeaderName( text );
LOGD << "preprocessor parsed name " << name ;
// TODO this can happen in parallel lock it with a mutex
std::lock_guard<std::mutex> lock(getMutex());
getHeaderSet().insert( name );
}
}
}
std::mutex& getMutex( ){
static std::mutex header_mutex;
return header_mutex;
}
// as a first step simply store the header names
// TODO add the positions in which they were included
std::set<std::string>& getHeaderSet(){
static std::set<std::string> headers;
return headers;
}
private:
clang::SourceManager& SM;
};
class ForLoopConsumer : public ASTConsumer {
public:
ForLoopConsumer( CodeGenerationType _emit_code_type, bool _write_cloog_file, PPEnterCallback* callbacks ) :
emit_code_type(_emit_code_type),
write_cloog_file(_write_cloog_file),
enter_callback( callbacks )
{
LOGD << "for loop consumer created " << this ;
}
~ForLoopConsumer(){
LOGD << "for loop consumer destroyed " << this ;
}
// all for loops that dont have a nested for loop
StatementMatcher makeForLoopMatcher(){
return forStmt(
unless(
hasAncestor(
forStmt()
)
)
).bind("for_stmt");
}
// match function declarations that are not in function templates
DeclarationMatcher makeFunctionMatcher(){
return functionDecl(
forEachDescendant(
makeForLoopMatcher()
),
unless(
hasAncestor(
functionTemplateDecl()
)
)
).bind("function_decl");
}
// match function declarations that are in function templates and are instantiations
DeclarationMatcher makeInstantiatedFunctionMatcher(){
return functionDecl(
forEachDescendant(
makeForLoopMatcher()
),
hasAncestor(
functionTemplateDecl()
),
isTemplateInstantiation()
).bind("function_decl");
}
#if 1
void HandleTranslationUnit( ASTContext& clang_ctx ) {
auto begin = std::chrono::high_resolution_clock::now();
MatchFinder Finder;
Callback Fixer(emit_code_type, write_cloog_file);
LOGD << "adding matcher" ;
Finder.addMatcher( makeFunctionMatcher(), &Fixer);
Finder.addMatcher( makeInstantiatedFunctionMatcher(), &Fixer);
LOGD << "running matcher" ;
Finder.matchAST(clang_ctx);
add_missing_includes(Fixer, clang_ctx);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = end-begin;
LOGD << "plugin: time consumption " << diff.count() << " s" ;
}
bool isHeaderAlreadyIncluded( std::string header, ASTContext& clang_ctx ) {
std::lock_guard<std::mutex> lock(enter_callback->getMutex());
LOGD << "plugin: number of already included headers " << enter_callback->getHeaderSet().size() ;
for( auto& included_header : enter_callback->getHeaderSet() ){
LOGD << "comparing: " << included_header << " with " << header ;
if ( header == included_header ) {
LOGD << "plugin: header is already included" ;
return true;
}
}
return false;
}
void add_missing_includes(Callback& Fixer, ASTContext& clang_ctx) {
for( auto& header : Fixer.header_includes ){
// dont add if the header is already included
if ( isHeaderAlreadyIncluded( header, clang_ctx ) ) continue;
// TODO skip the lines that begin with a comment
// this way its possible to skip licences that are mostly at the beginning of a file
// TODO perhaps search for a marker that the user can add to the file
// might be better to add the includes there if the user has to ensure a certain order of includes
auto& SM = clang_ctx.getSourceManager();
auto fid = SM.getMainFileID();
auto line = 1;
auto col = 1;
auto name = header;
auto begin_of_file = SM.translateLineCol( fid, line, col );
auto& diag = clang_ctx.getDiagnostics();
unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning, "missing header");
diag.Report(begin_of_file, id) << FixItHint::CreateInsertion(begin_of_file, std::string("#include <") + name + ">\n" );
}
}
#endif
private:
CodeGenerationType emit_code_type;
bool write_cloog_file;
PPEnterCallback* enter_callback;
};
static bool once_std_out = true;
static bool once_std_err = true;
class ClanAction : public PluginASTAction {
public:
ClanAction(){
static bool once = true;
if ( once ) {
static plog::ConsoleAppender<plog::TxtFormatter> consoleAppender;
plog::init(plog::debug, &consoleAppender);
once = false;
LOGD << "logger initialized ";
}
LOGD << "clang action " << this << " created " ;
}
virtual ~ClanAction(){
LOGD << "clang action " << this << " destroyed ";
}
// Automatically run the plugin after the main AST action
PluginASTAction::ActionType getActionType() override {
return AddAfterMainAction;
}
protected:
CodeGenerationType emit_code_type = CodeGenerationType::ACC;
bool write_cloog_file = false;
std::string redirect_stdout_file = "";
std::string redirect_stderr_file = "";
// NOTE: stefan this creates the consumer that is given the TU after everything is done
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) override;
bool ParseArgs(const CompilerInstance &CI, const std::vector<std::string> &args) override;
void PrintHelp(llvm::raw_ostream& ros) {
ros << "run the plugin with -emit-[openmp,openacc,hpx,tbb,cilk] to get different implementations for the loops\n";
}
};
PPEnterCallback* setupCallbacks( CompilerInstance& CI ) {
if ( CI.hasPreprocessor() ) {
auto& pp = CI.getPreprocessor();
LOGD << "plugin: got the preprocessor" ;
if ( CI.hasSourceManager() ) {
auto& SM = CI.getSourceManager();
std::unique_ptr<PPCallbacks> base_ptr( new PPEnterCallback(SM) );
auto* ret = (PPEnterCallback*)base_ptr.get();
pp.addPPCallbacks( std::move( base_ptr ) );
return ret;
}
}else{
LOGD << "ci does not have a preprocessor" ;
}
return nullptr;
}
std::unique_ptr<ASTConsumer>
ClanAction::CreateASTConsumer(CompilerInstance &CI, llvm::StringRef){
if ( redirect_stdout_file != "" ) {
LOGD << "redirect_stdout_file " << redirect_stdout_file;
// TODO mutex
if ( once_std_out ) {
std::freopen(redirect_stdout_file.c_str(), "a", stdout);
setvbuf ( stdout , NULL , _IOLBF , 1024 );
once_std_out = false;
}
}
if ( redirect_stderr_file != "" ) {
LOGD << "redirect_stderr_file " << redirect_stderr_file;
// TODO mutex
if ( once_std_err ) {
std::freopen(redirect_stderr_file.c_str(), "a", stderr);
setvbuf ( stderr , NULL , _IOLBF , 1024 );
once_std_err = false;
}
}
LOGD << "makeing new Consumer object with compiler instance " << &CI ;
auto enter_callback = setupCallbacks( CI );
auto ret = llvm::make_unique<ForLoopConsumer>(emit_code_type, write_cloog_file, enter_callback);
LOGD << "at load ci " << ret.get() << " instance " << &CI << " ast context " << &CI.getASTContext() << " SM " << &CI.getSourceManager() ;
LOGD << "done with the new consumer object" ;
// TODO find all header includs in the main file and pass them to the ForLoopConsumer
return std::move(ret);
}
bool
ClanAction::ParseArgs(const CompilerInstance &CI, const std::vector<std::string> &args) {
std::string* next_arg = nullptr;
for (unsigned i = 0, e = args.size(); i != e; ++i) {
LOGD << "Clan arg = " << args[i];
if ( next_arg ) {
*next_arg = args[i];
next_arg = nullptr;
continue;
}
if ( args[i] == "-emit-openacc" ) {
LOGD << "emiting openacc" ;
emit_code_type = CodeGenerationType::ACC;
}
if ( args[i] == "-emit-openmp" ) {
LOGD << "emiting openmp" ;
emit_code_type = CodeGenerationType::OMP;
}
if ( args[i] == "-emit-hpx" ) {
LOGD << "emiting hpx" ;
emit_code_type = CodeGenerationType::HPX;
}
if ( args[i] == "-emit-tbb" ) {
LOGD << "emiting tbb" ;
emit_code_type = CodeGenerationType::TBB;
}
if ( args[i] == "-emit-cilk" ) {
LOGD << "emiting cilk" ;
emit_code_type = CodeGenerationType::CILK;
}
if ( args[i] == "-emit-cuda" ) {
LOGD << "emiting cuda" ;
emit_code_type = CodeGenerationType::CUDA;
}
// add new back-ends here
if ( args[i] == "-write-cloog-file" ) {
LOGD << "writing cloog file" ;
write_cloog_file = true;
}
if ( args[i] == "-redirect-stdout" ) {
LOGD << "redirecting stdout" ;
next_arg = &redirect_stdout_file;
}
if ( args[i] == "-redirect-stderr" ) {
LOGD << "redirecting stderr" ;
next_arg = &redirect_stderr_file;
}
}
return true;
}
} // namespace end
// TODO change name
static FrontendPluginRegistry::Add<ClanAction>
X("clan", "run clan as part of the compiler");
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "PasswordGeneration.hpp"
void run_part_one() {
std::string password = "cqjxjnds";
do {
password = increment_password(password);
} while (!is_valid_password(password));
std::cout << password << std::endl;
}
void run_part_two() {
}
int main(int argc, char* argv[]) {
if (argc > 1) {
if (std::string(argv[1]) == "--part_two") {
run_part_two();
} else {
std::cout << "Usage: day11 [--part_two]" << std::endl;
return -1;
}
} else {
run_part_one();
}
}
<commit_msg>added runtime code for day 11 part two<commit_after>#include <iostream>
#include <string>
#include "PasswordGeneration.hpp"
std::string get_next_password(const std::string& password) {
std::string tmp = password;
do {
tmp = increment_password(tmp);
} while (!is_valid_password(tmp));
return tmp;
}
void run_part_one() {
std::cout << get_next_password("cqjxjnds") << std::endl;
}
void run_part_two() {
std::cout << get_next_password(get_next_password("cqjxjnds")) << std::endl;
}
int main(int argc, char* argv[]) {
if (argc > 1) {
if (std::string(argv[1]) == "--part_two") {
run_part_two();
} else {
std::cout << "Usage: day11 [--part_two]" << std::endl;
return -1;
}
} else {
run_part_one();
}
}
<|endoftext|> |
<commit_before>//
//###################################################################
//# EPOS 1.67 K. WERNER, T. PIEROG, S. PORTEBOEUF. #
//# Contact: werner@subatech.in2p3.fr #
//###################################################################
//
// TEpos.cxx
//
// Wraper class for interfacing EPOS model, derived from ROOT's TGenerator.
// It generates temporary input file for the model, providing user with
// ability to add his/hers own lines to the input.
// Output is read directly from common blocks.
//
// Author: Piotr Ostrowski, postrow@if.pw.edu.pl
//
#include <TClonesArray.h>
#include <TDatabasePDG.h>
#include <TObjArray.h>
#include <TParticle.h>
#include <TROOT.h>
#include <TRandom.h>
#include <TMath.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "eposproc.h"
#include "EPOScommon.h"
#include "AliGenEposIsajetToPdgConverter.h"
#include "TEpos.h"
using namespace std;
ClassImp(TEpos)
TEpos::TEpos() : TGenerator("EPOS", "Epos event generator"),
fLaproj(0),
fMaproj(0),
fLatarg(0),
fMatarg(0),
fBminim(0.0),
fBmaxim(10000.0),
fPhimin(0.0),
fPhimax(TMath::TwoPi()),
fEcms(-1),
fSplitting(kFALSE),
fNoDecays(),
fExtraInputLines(),
fIdConverter()
{
fIdConverter=new AliGenEposIsajetToPdgConverter();
}
TEpos::TEpos(const TEpos&) : TGenerator("EPOS", "Epos event generator"),
fLaproj(0),
fMaproj(0),
fLatarg(0),
fMatarg(0),
fBminim(0.0),
fBmaxim(10000.0),
fPhimin(0.0),
fPhimax(TMath::TwoPi()),
fEcms(-1),
fSplitting(kFALSE),
fNoDecays(),
fExtraInputLines(),
fIdConverter()
{
fIdConverter = new AliGenEposIsajetToPdgConverter();
}
TEpos::~TEpos() {
delete fIdConverter;
}
TEpos& TEpos::operator=(const TEpos& epos) {
//operator=
if (!fIdConverter && (this != &epos)) {
fIdConverter = new AliGenEposIsajetToPdgConverter();
}
return *this;
}
void TEpos::Initialize() {
// Generates input file and prepares EPOS to read from it.
Int_t nopeno = 0;
GenerateInputFile();
aaset(0);
atitle();
xiniall();
const char *inputFileName = GetInputFileName();
Int_t nameLength = strlen(inputFileName);
setinp(inputFileName, nameLength, nameLength);
aread();
while(copen.nopen == -1) {
copen.nopen=nopeno;
prnt1.iecho=1;
xiniall();
aread();
}
Int_t ishini;
utpri("aamain",prnt1.ish,ishini,4,6);
if(appli.model != 1)
IniModel(appli.model);
ebin.nrebin = 1;
ainit();
aseed(2);
}
void TEpos::GenerateEvent() {
// cseed.seedj = gRandom->Rndm() * 1e10;
Int_t n = 1;
evgen(n);
}
Int_t TEpos::ImportParticles(TClonesArray *particles, Option_t *) {
//Fills provided ClonesArray with generated particles
particles->Clear();
if (!cevt.nevt) return 0;
Int_t numpart = cptl.nptl;
printf("%d particles generated\n", numpart);
for (Int_t iPart=0; iPart<numpart; iPart++) {
Int_t tFather = cptl.iorptl[iPart] - 1;
tFather = tFather < -1 ? -1 : tFather;
if (tFather> -1) {
TParticle *mother = (TParticle*) (particles->UncheckedAt(tFather));
mother->SetLastDaughter(iPart);
if (mother->GetFirstDaughter()==-1)
mother->SetFirstDaughter(iPart);
}
Int_t status = cptl.istptl[iPart] + 1;
Int_t pdg = fIdConverter->ConvertIsajetToPdg(cptl.idptl[iPart]);
new((*particles)[iPart]) TParticle(pdg, status,
tFather, -1, -1, -1,
cptl.pptl[iPart][0], cptl.pptl[iPart][1],cptl.pptl[iPart][2],cptl.pptl[iPart][3],
cptl.xorptl[iPart][0]*1.e-12, cptl.xorptl[iPart][1]*1.e-12, cptl.xorptl[iPart][2]*1.e-12, cptl.xorptl[iPart][3]*1e-12);
(*particles)[iPart]->SetUniqueID(iPart);
}
return numpart;
}
TObjArray* TEpos::ImportParticles(Option_t *) {
//Creates new particle array
fParticles->Clear();
if (!cevt.nevt) return NULL;
Int_t numpart = cptl.nptl;
printf("%d particles generated\n", numpart);
for (Int_t iPart=0; iPart<numpart; iPart++) {
Int_t tFather = cptl.iorptl[iPart] - 1;
tFather = tFather < -1 ? -1 : tFather;
if (tFather> -1) {
TParticle *mother = (TParticle*) (fParticles->UncheckedAt(tFather));
mother->SetLastDaughter(iPart);
if (mother->GetFirstDaughter()==-1)
mother->SetFirstDaughter(iPart);
}
Int_t status = cptl.istptl[iPart] + 1;
Int_t pdg = fIdConverter->ConvertIsajetToPdg(cptl.idptl[iPart]);
TParticle* p = new TParticle(pdg, status,
tFather, -1, -1, -1,
cptl.pptl[iPart][0], cptl.pptl[iPart][1],cptl.pptl[iPart][2],cptl.pptl[iPart][3],
cptl.xorptl[iPart][0]*1.e-12, cptl.xorptl[iPart][1]*1.e-12, cptl.xorptl[iPart][2]*1.e-12, cptl.xorptl[iPart][3]*1e-12);
p->SetUniqueID(iPart);
fParticles->Add(p);
}
return fParticles;
}
void TEpos::AddNoDecay(Int_t nodecay) {
fNoDecays.push_back(nodecay);
}
void TEpos::AddExtraInputLine(const char *line) {
fExtraInputLines.push_back(line);
}
void TEpos::GenerateInputFile() {
// Generate input file in EPOS format
ofstream file(GetInputFileName(), ios_base::out | ios_base::trunc);
char epo[256];
char *epoEnv = getenv("EPO");
if (epoEnv) {
strncpy(epo, epoEnv, 255);
} else {
strncpy(epo, getenv("ALICE_ROOT"), 255);
}
strncat(epo, "/EPOS/epos167", 255);
file << "fname pathnx " << epo << "/" << endl;
file << "fname histo none" << endl;
file << "fname copy none" << endl;
file << "fname log none" << endl;
file << "fname check none" << endl;
// file << "fname data /tmp/epos.out" << endl;
file << "fname initl " << epo << "/epos.initl" << endl;
file << "fname inidi " << epo << "/epos.inidi" << endl;
file << "fname inidr " << epo << "/epos.inidr" << endl;
file << "fname iniev " << epo << "/epos.iniev" << endl;
file << "fname inirj " << epo << "/epos.inirj" << endl;
file << "fname inics " << epo << "/epos.inics" << endl;
file << "fname inigrv " << epo << "/epos.inigrv" << endl;
file << "fqgsjet dat " << epo << "/qgsjet/qgsjet.dat" << endl;
file << "fqgsjet ncs " << epo << "/qgsjet/qgsjet.ncs" << endl;
file << "fqgsjetII dat " << epo << "/qgsjetII/qgsdat-II-03" << endl;
file << "fqgsjetII ncs " << epo << "/qgsjetII/sectnu-II-03" << endl;
file << "nodecay 120" << endl;
file << "nodecay -120" << endl;
file << "nodecay 130" << endl;
file << "nodecay -130" << endl;
file << "nodecay -20" << endl;
file << "nodecay 20" << endl;
file << "nodecay 14" << endl;
file << "nodecay -14" << endl;
file << "set ndecay 1111110" << endl;
file << "echo on" << endl;
// .optns file
int precision = file.precision();
file.precision(15);
file << "set seedj " << (gRandom->Rndm() * 1e14) << endl;
file.precision(precision);
file << "application hadron" << endl;
file << "set laproj " << fLaproj << endl;
file << "set maproj " << fMaproj << endl;
file << "set latarg " << fLatarg << endl;
file << "set matarg " << fMatarg << endl;
file << "set bminim " << fBminim << endl;
file << "set bmaxim " << fBmaxim << endl;
file << "set phimin " << fPhimin << endl;
file << "set phimax " << fPhimax << endl;
file << "set ecms " << fEcms << endl;
for(unsigned int i = 0; i < fNoDecays.size(); ++i) {
file << "nodecay " << fNoDecays[i] << endl;
}
file << "switch splitting " << (fSplitting ? "on" : "off") << endl;
file << "frame nucleon-nucleon" << endl;
for(unsigned int i = 0; i < fExtraInputLines.size(); ++i) {
file << fExtraInputLines[i] << endl;
}
// file << "output epos" << endl;
// file << "record event nevt nptl b endrecord" << endl;
// file << "record particle i id fa mo c1 c2 st endrecord" << endl;
file << "input " << epo << "/epos.param" << endl;
file << "runprogram" << endl;
file.close();
}
Float_t TEpos::GetBimevt() const { return cevt.bimevt; }
Float_t TEpos::GetPhievt() const { return cevt.phievt; }
Int_t TEpos::GetKolevt() const { return cevt.kolevt; }
Int_t TEpos::GetKoievt() const { return cevt.koievt; }
Float_t TEpos::GetPmxevt() const { return cevt.pmxevt; }
Float_t TEpos::GetEgyevt() const { return cevt.egyevt; }
Int_t TEpos::GetNpjevt() const { return cevt.npjevt; }
Int_t TEpos::GetNtgevt() const { return cevt.ntgevt; }
Int_t TEpos::GetNpnevt() const { return cevt.npnevt; }
Int_t TEpos::GetNppevt() const { return cevt.nppevt; }
Int_t TEpos::GetNtnevt() const { return cevt.ntnevt; }
Int_t TEpos::GetNtpevt() const { return cevt.ntpevt; }
Int_t TEpos::GetJpnevt() const { return cevt.jpnevt; }
Int_t TEpos::GetJppevt() const { return cevt.jppevt; }
Int_t TEpos::GetJtnevt() const { return cevt.jtnevt; }
Int_t TEpos::GetJtpevt() const { return cevt.jtpevt; }
Float_t TEpos::GetXbjevt() const { return cevt.xbjevt; }
Float_t TEpos::GetQsqevt() const { return cevt.qsqevt; }
Int_t TEpos::GetNglevt() const { return cevt.nglevt; }
Float_t TEpos::GetZppevt() const { return cevt.zppevt; }
Float_t TEpos::GetZptevt() const { return cevt.zptevt; }
<commit_msg>Fix for coverity 17980<commit_after>//
//###################################################################
//# EPOS 1.67 K. WERNER, T. PIEROG, S. PORTEBOEUF. #
//# Contact: werner@subatech.in2p3.fr #
//###################################################################
//
// TEpos.cxx
//
// Wraper class for interfacing EPOS model, derived from ROOT's TGenerator.
// It generates temporary input file for the model, providing user with
// ability to add his/hers own lines to the input.
// Output is read directly from common blocks.
//
// Author: Piotr Ostrowski, postrow@if.pw.edu.pl
//
#include <TClonesArray.h>
#include <TDatabasePDG.h>
#include <TObjArray.h>
#include <TParticle.h>
#include <TROOT.h>
#include <TRandom.h>
#include <TMath.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "eposproc.h"
#include "EPOScommon.h"
#include "AliGenEposIsajetToPdgConverter.h"
#include "TEpos.h"
using namespace std;
ClassImp(TEpos)
TEpos::TEpos() : TGenerator("EPOS", "Epos event generator"),
fLaproj(0),
fMaproj(0),
fLatarg(0),
fMatarg(0),
fBminim(0.0),
fBmaxim(10000.0),
fPhimin(0.0),
fPhimax(TMath::TwoPi()),
fEcms(-1),
fSplitting(kFALSE),
fNoDecays(),
fExtraInputLines(),
fIdConverter()
{
fIdConverter=new AliGenEposIsajetToPdgConverter();
}
TEpos::TEpos(const TEpos&) : TGenerator("EPOS", "Epos event generator"),
fLaproj(0),
fMaproj(0),
fLatarg(0),
fMatarg(0),
fBminim(0.0),
fBmaxim(10000.0),
fPhimin(0.0),
fPhimax(TMath::TwoPi()),
fEcms(-1),
fSplitting(kFALSE),
fNoDecays(),
fExtraInputLines(),
fIdConverter()
{
fIdConverter = new AliGenEposIsajetToPdgConverter();
}
TEpos::~TEpos() {
delete fIdConverter;
}
TEpos& TEpos::operator=(const TEpos& epos) {
//operator=
if (this != &epos) {
if (!fIdConverter) fIdConverter = new AliGenEposIsajetToPdgConverter();
fLaproj = epos.fLaproj;
fMaproj = epos.fMaproj;
fLatarg = epos.fLatarg;
fMatarg = epos.fMatarg;
fBminim = epos.fBminim;
fBmaxim = epos.fBmaxim;
fPhimin = epos.fPhimin;
fPhimax = epos.fPhimax;
fEcms = epos.fEcms;
fSplitting = epos.fSplitting;
// fNoDecays = epos.fNoDecays;
// fExtraInputLines = epos.dExtraInputLines;
}
return *this;
}
void TEpos::Initialize() {
// Generates input file and prepares EPOS to read from it.
Int_t nopeno = 0;
GenerateInputFile();
aaset(0);
atitle();
xiniall();
const char *inputFileName = GetInputFileName();
Int_t nameLength = strlen(inputFileName);
setinp(inputFileName, nameLength, nameLength);
aread();
while(copen.nopen == -1) {
copen.nopen=nopeno;
prnt1.iecho=1;
xiniall();
aread();
}
Int_t ishini;
utpri("aamain",prnt1.ish,ishini,4,6);
if(appli.model != 1)
IniModel(appli.model);
ebin.nrebin = 1;
ainit();
aseed(2);
}
void TEpos::GenerateEvent() {
// cseed.seedj = gRandom->Rndm() * 1e10;
Int_t n = 1;
evgen(n);
}
Int_t TEpos::ImportParticles(TClonesArray *particles, Option_t *) {
//Fills provided ClonesArray with generated particles
particles->Clear();
if (!cevt.nevt) return 0;
Int_t numpart = cptl.nptl;
printf("%d particles generated\n", numpart);
for (Int_t iPart=0; iPart<numpart; iPart++) {
Int_t tFather = cptl.iorptl[iPart] - 1;
tFather = tFather < -1 ? -1 : tFather;
if (tFather> -1) {
TParticle *mother = (TParticle*) (particles->UncheckedAt(tFather));
mother->SetLastDaughter(iPart);
if (mother->GetFirstDaughter()==-1)
mother->SetFirstDaughter(iPart);
}
Int_t status = cptl.istptl[iPart] + 1;
Int_t pdg = fIdConverter->ConvertIsajetToPdg(cptl.idptl[iPart]);
new((*particles)[iPart]) TParticle(pdg, status,
tFather, -1, -1, -1,
cptl.pptl[iPart][0], cptl.pptl[iPart][1],cptl.pptl[iPart][2],cptl.pptl[iPart][3],
cptl.xorptl[iPart][0]*1.e-12, cptl.xorptl[iPart][1]*1.e-12, cptl.xorptl[iPart][2]*1.e-12, cptl.xorptl[iPart][3]*1e-12);
(*particles)[iPart]->SetUniqueID(iPart);
}
return numpart;
}
TObjArray* TEpos::ImportParticles(Option_t *) {
//Creates new particle array
fParticles->Clear();
if (!cevt.nevt) return NULL;
Int_t numpart = cptl.nptl;
printf("%d particles generated\n", numpart);
for (Int_t iPart=0; iPart<numpart; iPart++) {
Int_t tFather = cptl.iorptl[iPart] - 1;
tFather = tFather < -1 ? -1 : tFather;
if (tFather> -1) {
TParticle *mother = (TParticle*) (fParticles->UncheckedAt(tFather));
mother->SetLastDaughter(iPart);
if (mother->GetFirstDaughter()==-1)
mother->SetFirstDaughter(iPart);
}
Int_t status = cptl.istptl[iPart] + 1;
Int_t pdg = fIdConverter->ConvertIsajetToPdg(cptl.idptl[iPart]);
TParticle* p = new TParticle(pdg, status,
tFather, -1, -1, -1,
cptl.pptl[iPart][0], cptl.pptl[iPart][1],cptl.pptl[iPart][2],cptl.pptl[iPart][3],
cptl.xorptl[iPart][0]*1.e-12, cptl.xorptl[iPart][1]*1.e-12, cptl.xorptl[iPart][2]*1.e-12, cptl.xorptl[iPart][3]*1e-12);
p->SetUniqueID(iPart);
fParticles->Add(p);
}
return fParticles;
}
void TEpos::AddNoDecay(Int_t nodecay) {
fNoDecays.push_back(nodecay);
}
void TEpos::AddExtraInputLine(const char *line) {
fExtraInputLines.push_back(line);
}
void TEpos::GenerateInputFile() {
// Generate input file in EPOS format
ofstream file(GetInputFileName(), ios_base::out | ios_base::trunc);
char epo[256];
char *epoEnv = getenv("EPO");
if (epoEnv) {
strncpy(epo, epoEnv, 255);
} else {
strncpy(epo, getenv("ALICE_ROOT"), 255);
}
strncat(epo, "/EPOS/epos167", 255);
file << "fname pathnx " << epo << "/" << endl;
file << "fname histo none" << endl;
file << "fname copy none" << endl;
file << "fname log none" << endl;
file << "fname check none" << endl;
// file << "fname data /tmp/epos.out" << endl;
file << "fname initl " << epo << "/epos.initl" << endl;
file << "fname inidi " << epo << "/epos.inidi" << endl;
file << "fname inidr " << epo << "/epos.inidr" << endl;
file << "fname iniev " << epo << "/epos.iniev" << endl;
file << "fname inirj " << epo << "/epos.inirj" << endl;
file << "fname inics " << epo << "/epos.inics" << endl;
file << "fname inigrv " << epo << "/epos.inigrv" << endl;
file << "fqgsjet dat " << epo << "/qgsjet/qgsjet.dat" << endl;
file << "fqgsjet ncs " << epo << "/qgsjet/qgsjet.ncs" << endl;
file << "fqgsjetII dat " << epo << "/qgsjetII/qgsdat-II-03" << endl;
file << "fqgsjetII ncs " << epo << "/qgsjetII/sectnu-II-03" << endl;
file << "nodecay 120" << endl;
file << "nodecay -120" << endl;
file << "nodecay 130" << endl;
file << "nodecay -130" << endl;
file << "nodecay -20" << endl;
file << "nodecay 20" << endl;
file << "nodecay 14" << endl;
file << "nodecay -14" << endl;
file << "set ndecay 1111110" << endl;
file << "echo on" << endl;
// .optns file
int precision = file.precision();
file.precision(15);
file << "set seedj " << (gRandom->Rndm() * 1e14) << endl;
file.precision(precision);
file << "application hadron" << endl;
file << "set laproj " << fLaproj << endl;
file << "set maproj " << fMaproj << endl;
file << "set latarg " << fLatarg << endl;
file << "set matarg " << fMatarg << endl;
file << "set bminim " << fBminim << endl;
file << "set bmaxim " << fBmaxim << endl;
file << "set phimin " << fPhimin << endl;
file << "set phimax " << fPhimax << endl;
file << "set ecms " << fEcms << endl;
for(unsigned int i = 0; i < fNoDecays.size(); ++i) {
file << "nodecay " << fNoDecays[i] << endl;
}
file << "switch splitting " << (fSplitting ? "on" : "off") << endl;
file << "frame nucleon-nucleon" << endl;
for(unsigned int i = 0; i < fExtraInputLines.size(); ++i) {
file << fExtraInputLines[i] << endl;
}
// file << "output epos" << endl;
// file << "record event nevt nptl b endrecord" << endl;
// file << "record particle i id fa mo c1 c2 st endrecord" << endl;
file << "input " << epo << "/epos.param" << endl;
file << "runprogram" << endl;
file.close();
}
Float_t TEpos::GetBimevt() const { return cevt.bimevt; }
Float_t TEpos::GetPhievt() const { return cevt.phievt; }
Int_t TEpos::GetKolevt() const { return cevt.kolevt; }
Int_t TEpos::GetKoievt() const { return cevt.koievt; }
Float_t TEpos::GetPmxevt() const { return cevt.pmxevt; }
Float_t TEpos::GetEgyevt() const { return cevt.egyevt; }
Int_t TEpos::GetNpjevt() const { return cevt.npjevt; }
Int_t TEpos::GetNtgevt() const { return cevt.ntgevt; }
Int_t TEpos::GetNpnevt() const { return cevt.npnevt; }
Int_t TEpos::GetNppevt() const { return cevt.nppevt; }
Int_t TEpos::GetNtnevt() const { return cevt.ntnevt; }
Int_t TEpos::GetNtpevt() const { return cevt.ntpevt; }
Int_t TEpos::GetJpnevt() const { return cevt.jpnevt; }
Int_t TEpos::GetJppevt() const { return cevt.jppevt; }
Int_t TEpos::GetJtnevt() const { return cevt.jtnevt; }
Int_t TEpos::GetJtpevt() const { return cevt.jtpevt; }
Float_t TEpos::GetXbjevt() const { return cevt.xbjevt; }
Float_t TEpos::GetQsqevt() const { return cevt.qsqevt; }
Int_t TEpos::GetNglevt() const { return cevt.nglevt; }
Float_t TEpos::GetZppevt() const { return cevt.zppevt; }
Float_t TEpos::GetZptevt() const { return cevt.zptevt; }
<|endoftext|> |
<commit_before>#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
//code used from http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring
// trim from start
static inline std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
static inline std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
static inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
<commit_msg>Misc folder deleted<commit_after><|endoftext|> |
<commit_before>/*
* i, j is the position.
* i - 2, j + 1
* i - 2, j - 1
* i - 1, j + 2
* i - 1, j - 2
* i + 1, j + 2
* i + 1, j - 2
* i + 2, j + 1
* i + 2, j - 1
*/
#include<iostream>
#include<vector>
using namespace std;
class KnightsTour
{
public:
vector <pair <int, int> > validmoves(vector <string> board, int r, int c)
{
vector <pair <int, int> > coords;
vector <pair <int, int> > validcoords;
int row, col;
coords.push_back(make_pair(-2,1));
coords.push_back(make_pair(-2,-1));
coords.push_back(make_pair(-1,2));
coords.push_back(make_pair(-1,-2));
coords.push_back(make_pair(1,2));
coords.push_back(make_pair(1,-2));
coords.push_back(make_pair(2,1));
coords.push_back(make_pair(2,-1));
for(int i=0; i < coords.size(); i++)
{
row = r + coords[i].first;
col = c + coords[i].second;
if ( (0 <= row) && (row < board.size()) && (0 <= col) && (col < board.size()) )
{
if (board[row][col] == '.')
validcoords.push_back(make_pair(row,col));
}
}
return validcoords;
}
int visitedPositions(vector <string> board)
{
int r,c,i,j,pos, nr,nc;
vector <pair <int, int> > validcoords, possiblemoves;
int visited=0,smallest=8,nextmoves=0;
for (i = 0; i < board.size(); i++)
{
pos = board[i].find("K");
if(pos != -1)
{
r = i;
c = pos;
}
}
do
{
board[r][c] = '*'; visited++;
validcoords = validmoves(board, r,c);
nextmoves = validcoords.size();
smallest = 8;
for (j=0; j < nextmoves; j++)
{
possiblemoves = validmoves(board, validcoords[j].first, validcoords[j].second);
if (possiblemoves.size() <= smallest)
{
smallest = possiblemoves.size();
nr = validcoords[j].first;
nc = validcoords[j].second;
}
}
if (nextmoves > 0)
{
r = nr;
c = nc;
}
}while(nextmoves > 0);
return visited;
}
};
int main(int argc, char *argv[])
{
KnightsTour obj;
vector <string> board;
board.push_back("K.......");
board.push_back("........");
board.push_back("........");
board.push_back("........");
board.push_back("........");
board.push_back("........");
board.push_back("........");
board.push_back("........");
cout<<obj.visitedPositions(board)<<endl;
}
<commit_msg>KnightsTour Solved.<commit_after>/*
* i, j is the position.
* i - 2, j + 1
* i - 2, j - 1
* i - 1, j + 2
* i - 1, j - 2
* i + 1, j + 2
* i + 1, j - 2
* i + 2, j + 1
* i + 2, j - 1
*/
#include<iostream>
#include<vector>
using namespace std;
class KnightsTour
{
public:
vector <pair <int, int> > validmoves(vector <string> board, int r, int c)
{
vector <pair <int, int> > coords;
vector <pair <int, int> > validcoords;
int row, col;
coords.push_back(make_pair(2,1));
coords.push_back(make_pair(2,-1));
coords.push_back(make_pair(1,2));
coords.push_back(make_pair(1,-2));
coords.push_back(make_pair(-1,2));
coords.push_back(make_pair(-1,-2));
coords.push_back(make_pair(-2,1));
coords.push_back(make_pair(-2,-1));
for(int i=0; i < coords.size(); i++)
{
row = r + coords[i].first;
col = c + coords[i].second;
if ( (0 <= row) && (row < board.size()) && (0 <= col) && (col < board.size()) )
{
if (board[row][col] == '.')
validcoords.push_back(make_pair(row,col));
}
}
return validcoords;
}
int visitedPositions(vector <string> board)
{
int r,c,i,j,pos, nr,nc;
vector <pair <int, int> > validcoords, possiblemoves;
int visited=0,smallest=8,nextmoves=0;
for (i = 0; i < board.size(); i++)
{
pos = board[i].find("K");
if(pos != -1)
{
r = i;
c = pos;
}
}
do
{
board[r][c] = '*'; visited++;
validcoords = validmoves(board, r,c);
nextmoves = validcoords.size();
smallest = 8;
for (j=0; j < nextmoves; j++)
{
possiblemoves = validmoves(board, validcoords[j].first, validcoords[j].second);
if (possiblemoves.size() <= smallest)
{
smallest = possiblemoves.size();
nr = validcoords[j].first;
nc = validcoords[j].second;
}
}
if (nextmoves > 0)
{
r = nr;
c = nc;
}
}while(nextmoves > 0);
return visited;
}
};
int main(int argc, char *argv[])
{
KnightsTour obj;
vector <string> board;
board.push_back("K.......");
board.push_back("........");
board.push_back("........");
board.push_back("........");
board.push_back("........");
board.push_back("........");
board.push_back("........");
board.push_back("........");
cout<<obj.visitedPositions(board)<<endl;
}
<|endoftext|> |
<commit_before>/*
This program demonstrates several aspects of SCF usage:
- Dynamic class loading/unloading (Dog and Worm classes)
- Always-static class linkage (Frog class)
- Object-created-within-object (Worm::Split method)
- Run-time class registration with SCF kernel (no need for scf.cfg)
- Embedded interface (iName within iDog)
- Multiple interfaces (iFrog also supports iName)
*/
#include <stdio.h>
#include "sysdef.h"
#include "csutil/scf.h"
#include "csutil/inifile.h"
#include "iname.h"
#include "idog.h"
#include "iworm.h"
//#include "ifrog.h"
// for the case we're using static linking ...
#ifdef CS_STATIC_LINKED
REGISTER_STATIC_LIBRARY (Dog)
REGISTER_STATIC_LIBRARY (Worm)
#endif
// frog is always statically linked
//REGISTER_STATIC_LIBRARY (Frog)
// This function will clone given object, do something with him
// and finally destroy
void Clone (iBase *iObject)
{
printf ("--- cloning the object\n");
iFactory *factory = QUERY_INTERFACE (iObject, iFactory);
if (!factory)
{
fprintf (stderr, "Object does not support the iFactory interface!\n");
return;
}
printf ("Class description: %s\n", factory->QueryDescription ());
// Create a new instance of the class
iBase *newobj = (iBase *)factory->CreateInstance ();
// Release the factory interface of the parent - we don't need it anymore
factory->DecRef ();
if (!newobj)
{
fprintf (stderr, "Failed to create a object of the same type!\n");
return;
}
// Check if the object supports the iName interface
iName *name = QUERY_INTERFACE (newobj, iName);
if (name)
{
if (!name->GetName())
printf ("Object is unnamed; renaming to \"Clone\"\n");
else
printf ("Object's name is \"%s\"; renaming to \"Clone\"\n",
name->GetName ());
name->SetName ("Clone");
name->DecRef ();
}
// Delete the clone
newobj->DecRef ();
}
//Changing this causes a link2001 error for win32.
//int main(int,char **)
int main(int argc, char *argv[])
{
//hack to hide warning.
argc;
argv;
#if 0
// This method requires you register dlls with scfreg (or manually) in scf.cfg
csIniFile config ("scf.cfg");
scfInitialize (&config);
#else
// Don't use a .cfg file, instead manually register classes
scfInitialize (NULL);
scfRegisterClass ("test.dog", "Dog");
scfRegisterClass ("test.worm", "Worm");
#endif
iDog *dog = CREATE_INSTANCE ("test.dog", iDog);
if (!dog)
fprintf (stderr, "No csDog shared class!\n");
else
{
iName *name = QUERY_INTERFACE (dog, iName);
if (!name)
fprintf (stderr, "dog does not support iName interface!\n");
else
{
name->SetName ("Droopy");
dog->Walk ();
dog->Barf ("hello!");
printf ("Dog's name is %s\n", name->GetName ());
name->DecRef ();
}
Clone (dog);
dog->DecRef ();
}
printf ("----------------\n");
iWorm *worm = CREATE_INSTANCE ("test.worm", iWorm);
if (!worm)
fprintf (stderr, "No csWorm shared class!\n");
else
{
worm->Crawl ();
printf ("Worm 1 length is %d\n", worm->Length ());
printf ("Splitting worm into two ...\n");
iWorm *worm2 = worm->Split (60, 40);
if (!worm2)
fprintf (stderr, "Failed to split the worm!\n");
else
{
printf ("Worm1 length: %d Worm2 length: %d\n", worm->Length (), worm2->Length ());
worm2->Crawl ();
worm2->DecRef ();
}
Clone (worm);
worm->DecRef ();
}
printf ("----------------\n");
/*
iFrog *frog = CREATE_INSTANCE ("test.frog", iFrog);
if (!frog)
fprintf (stderr, "No csFrog shared class!\n");
else
{
iName *name = QUERY_INTERFACE (frog, iName);
if (!name)
fprintf (stderr, "frog does not support iName interface!\n");
else
{
name->SetName ("Froggy");
frog->Jump ();
frog->Croak ("Barf");
printf ("Frog's name is %s\n", name->GetName ());
name->DecRef ();
}
Clone (frog);
frog->DecRef ();
}
*/
scfFinish ();
return 0;
}
<commit_msg>Eliminated compilation warnings.<commit_after>/*
This program demonstrates several aspects of SCF usage:
- Dynamic class loading/unloading (Dog and Worm classes)
- Always-static class linkage (Frog class)
- Object-created-within-object (Worm::Split method)
- Run-time class registration with SCF kernel (no need for scf.cfg)
- Embedded interface (iName within iDog)
- Multiple interfaces (iFrog also supports iName)
*/
#include <stdio.h>
#include "sysdef.h"
#include "csutil/scf.h"
#include "csutil/inifile.h"
#include "iname.h"
#include "idog.h"
#include "iworm.h"
//#include "ifrog.h"
// for the case we're using static linking ...
#ifdef CS_STATIC_LINKED
REGISTER_STATIC_LIBRARY (Dog)
REGISTER_STATIC_LIBRARY (Worm)
#endif
// frog is always statically linked
//REGISTER_STATIC_LIBRARY (Frog)
// This function will clone given object, do something with him
// and finally destroy
void Clone (iBase *iObject)
{
printf ("--- cloning the object\n");
iFactory *factory = QUERY_INTERFACE (iObject, iFactory);
if (!factory)
{
fprintf (stderr, "Object does not support the iFactory interface!\n");
return;
}
printf ("Class description: %s\n", factory->QueryDescription ());
// Create a new instance of the class
iBase *newobj = (iBase *)factory->CreateInstance ();
// Release the factory interface of the parent - we don't need it anymore
factory->DecRef ();
if (!newobj)
{
fprintf (stderr, "Failed to create a object of the same type!\n");
return;
}
// Check if the object supports the iName interface
iName *name = QUERY_INTERFACE (newobj, iName);
if (name)
{
if (!name->GetName())
printf ("Object is unnamed; renaming to \"Clone\"\n");
else
printf ("Object's name is \"%s\"; renaming to \"Clone\"\n",
name->GetName ());
name->SetName ("Clone");
name->DecRef ();
}
// Delete the clone
newobj->DecRef ();
}
//Changing this causes a link2001 error for win32.
//int main(int,char **)
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
#if 0
// This method requires you register dlls with scfreg (or manually) in scf.cfg
csIniFile config ("scf.cfg");
scfInitialize (&config);
#else
// Don't use a .cfg file, instead manually register classes
scfInitialize (NULL);
scfRegisterClass ("test.dog", "Dog");
scfRegisterClass ("test.worm", "Worm");
#endif
iDog *dog = CREATE_INSTANCE ("test.dog", iDog);
if (!dog)
fprintf (stderr, "No csDog shared class!\n");
else
{
iName *name = QUERY_INTERFACE (dog, iName);
if (!name)
fprintf (stderr, "dog does not support iName interface!\n");
else
{
name->SetName ("Droopy");
dog->Walk ();
dog->Barf ("hello!");
printf ("Dog's name is %s\n", name->GetName ());
name->DecRef ();
}
Clone (dog);
dog->DecRef ();
}
printf ("----------------\n");
iWorm *worm = CREATE_INSTANCE ("test.worm", iWorm);
if (!worm)
fprintf (stderr, "No csWorm shared class!\n");
else
{
worm->Crawl ();
printf ("Worm 1 length is %d\n", worm->Length ());
printf ("Splitting worm into two ...\n");
iWorm *worm2 = worm->Split (60, 40);
if (!worm2)
fprintf (stderr, "Failed to split the worm!\n");
else
{
printf ("Worm1 length: %d Worm2 length: %d\n", worm->Length (), worm2->Length ());
worm2->Crawl ();
worm2->DecRef ();
}
Clone (worm);
worm->DecRef ();
}
printf ("----------------\n");
/*
iFrog *frog = CREATE_INSTANCE ("test.frog", iFrog);
if (!frog)
fprintf (stderr, "No csFrog shared class!\n");
else
{
iName *name = QUERY_INTERFACE (frog, iName);
if (!name)
fprintf (stderr, "frog does not support iName interface!\n");
else
{
name->SetName ("Froggy");
frog->Jump ();
frog->Croak ("Barf");
printf ("Frog's name is %s\n", name->GetName ());
name->DecRef ();
}
Clone (frog);
frog->DecRef ();
}
*/
scfFinish ();
return 0;
}
<|endoftext|> |
<commit_before>#include "xid.h"
#include "sm-log.h"
#include "epoch.h"
#include "serial.h"
#include "../txn.h"
#include <atomic>
#include <unistd.h>
namespace TXN {
#if 0
} // disable autoindent
#endif
/* There are a fixed number of transaction contexts in the system
(some thousands of them), and our primary task is to create unique
XIDs and then assign them contexts in a way that no two XID map to
the same context at the same time. We accomplish this as follows:
The system maintains four bitmaps:
00 01
00 |................| |................|
10 |................| |................|
One row of bitmaps identifies contexts that are available for
immediate allocation, and the other identifies contexts that have
been recently freed (keeping those separate reduces contention and
avoids ABA issues).
Whenever the allocation bitmap row is exhausted, the system swaps
labels, turning the "recently-freed" bitmap (which should be pretty
full) into the "available" map, and vice-versa. Each row thus has a
bit that maps to a given context.
Meanwhile, the columns divide the allocation process into
epochs. Allocation can only change columns (and possibly rows as
well) if all stragglers have finished, thus solving the ABA problem
where a straggler manages to reallocate the same context in the
same epoch, after the context has been used and freed.
As a concrete example, the system starts allocating from bitmap 00
(in epoch 0); once 00 is exhausted, it advances to epoch 1 and
begins allocating from bitmap 01. Once bitmap 01 is empty, the
system advances to bitmap 10 (logically swapping the rows) and
begins recycling contexts that were allocated from bitmap 00 and
have since been freed. Allocation continues through 10 and 11 and
eventually wraps around to 00 again. Now we have to worry about
stragglers (some really old transaction could have started in epoch
0 and---not realizing we're now in epoch 4---might end up with a
TID from epoch 0 that duplicates the tid from two allocation cycles
ago. This is where the epoch manager comes in: it can track
stragglers and restricts the number of concurrent epochs so that
the problem cannot arise.
*/
xid_context contexts[NCONTEXTS];
xid_bitmap xid_bitmaps[NBITMAPS];
__thread thread_data tls CACHE_ALIGNED;
/***************************************
* * * Callbacks for the epoch_mgr * * *
***************************************/
void
global_init(void*)
{
/* Set the first row to all ones so we have something to allocate */
for (int i=0; i < 2; i++) {
for (auto &w : xid_bitmaps[i].data)
w = ~uint64_t(0);
}
}
epoch_mgr::tls_storage *
get_tls(void*)
{
static __thread epoch_mgr::tls_storage s;
return &s;
}
void *
thread_registered(void*)
{
tls.epoch = 0;
tls.bitmap = 0;
tls.base_id = 0;
tls.initialized = true;
return &tls;
}
void
thread_deregistered(void*, void *thread_cookie)
{
auto *t = (thread_data*) thread_cookie;
ASSERT(t == &tls);
while (t->bitmap) {
auto x = take_one(t);
xid_free(x);
}
t->initialized = false;
}
/* Don't need these... we track resources a different way
*/
void *
epoch_ended(void*, epoch_mgr::epoch_num)
{
return 0;
}
void *
epoch_ended_thread(void *, void *epoch_cookie, void *)
{
return epoch_cookie;
}
void
epoch_reclaimed(void *, void *)
{
}
epoch_mgr xid_epochs{{
nullptr, &global_init, &get_tls,
&thread_registered, &thread_deregistered,
&epoch_ended, &epoch_ended_thread,
&epoch_reclaimed}};
os_mutex_pod xid_mutex = os_mutex_pod::static_init();
# if 0
{ // disable autoindent
#endif
XID
xid_alloc()
{
if (not tls.initialized)
xid_epochs.thread_init();
while (not tls.bitmap) {
/* Grab a whole machine word at a time. Use the epoch_mgr to
protect us if we happen to straggle. Note that we may
(through bad luck) acquire an empty word and need to retry.
*/
auto e = xid_epochs.thread_enter();
DEFER_UNLESS(exited, xid_epochs.thread_exit());
auto &b = xid_bitmaps[e % NBITMAPS];
auto i = volatile_read(b.widx);
ASSERT(i <= xid_bitmap::NWORDS);
while (i < xid_bitmap::NWORDS) {
auto j = __sync_val_compare_and_swap(&b.widx, i, i+1);
if (j == i) {
/* NOTE: no need for a goto: the compiler will thread
the jump so we skip the overflow check entirely
*/
break;
}
i = j;
}
if (i == xid_bitmap::NWORDS) {
// overflow!
xid_epochs.thread_exit();
exited = true;
xid_mutex.lock();
DEFER(xid_mutex.unlock());
if (e == xid_epochs.get_cur_epoch()) {
/* Still at end, try to open a new epoch.
If there are stragglers (highly unlikely) then
sleep until they leave.
*/
xid_bitmaps[(e+1) % NBITMAPS].widx = 0;
while (not xid_epochs.new_epoch())
usleep(1000);
}
continue;
}
tls.epoch = e;
tls.base_id = (e % 2)*NCONTEXTS/2 + i*xid_bitmap::BITS_PER_WORD;
std::swap(tls.bitmap, b.data[i]);
}
return take_one(&tls);
}
#ifdef SSN
bool
xid_context::set_sstamp(uint64_t s) {
ALWAYS_ASSERT(!(s & xid_context::sstamp_final_mark));
// If I'm not read-mostly, nobody else would call this
if (xct->is_read_mostly() && config::ssn_read_opt_enabled()) {
// This has to be a CAS because with read-optimization, the updater might need
// to update the reader's sstamp.
uint64_t ss = sstamp.load(std::memory_order_acquire);
do {
if (ss & sstamp_final_mark) {
return false;
}
} while((ss == 0 || ss > s) && !std::atomic_compare_exchange_strong(&sstamp, &ss, s));
} else {
sstamp.store(s, std::memory_order_relaxed);
}
return true;
}
#endif
} // end of namespace
<commit_msg>fix sstamp assignment.<commit_after>#include "xid.h"
#include "sm-log.h"
#include "epoch.h"
#include "serial.h"
#include "../txn.h"
#include <atomic>
#include <unistd.h>
namespace TXN {
#if 0
} // disable autoindent
#endif
/* There are a fixed number of transaction contexts in the system
(some thousands of them), and our primary task is to create unique
XIDs and then assign them contexts in a way that no two XID map to
the same context at the same time. We accomplish this as follows:
The system maintains four bitmaps:
00 01
00 |................| |................|
10 |................| |................|
One row of bitmaps identifies contexts that are available for
immediate allocation, and the other identifies contexts that have
been recently freed (keeping those separate reduces contention and
avoids ABA issues).
Whenever the allocation bitmap row is exhausted, the system swaps
labels, turning the "recently-freed" bitmap (which should be pretty
full) into the "available" map, and vice-versa. Each row thus has a
bit that maps to a given context.
Meanwhile, the columns divide the allocation process into
epochs. Allocation can only change columns (and possibly rows as
well) if all stragglers have finished, thus solving the ABA problem
where a straggler manages to reallocate the same context in the
same epoch, after the context has been used and freed.
As a concrete example, the system starts allocating from bitmap 00
(in epoch 0); once 00 is exhausted, it advances to epoch 1 and
begins allocating from bitmap 01. Once bitmap 01 is empty, the
system advances to bitmap 10 (logically swapping the rows) and
begins recycling contexts that were allocated from bitmap 00 and
have since been freed. Allocation continues through 10 and 11 and
eventually wraps around to 00 again. Now we have to worry about
stragglers (some really old transaction could have started in epoch
0 and---not realizing we're now in epoch 4---might end up with a
TID from epoch 0 that duplicates the tid from two allocation cycles
ago. This is where the epoch manager comes in: it can track
stragglers and restricts the number of concurrent epochs so that
the problem cannot arise.
*/
xid_context contexts[NCONTEXTS];
xid_bitmap xid_bitmaps[NBITMAPS];
__thread thread_data tls CACHE_ALIGNED;
/***************************************
* * * Callbacks for the epoch_mgr * * *
***************************************/
void
global_init(void*)
{
/* Set the first row to all ones so we have something to allocate */
for (int i=0; i < 2; i++) {
for (auto &w : xid_bitmaps[i].data)
w = ~uint64_t(0);
}
}
epoch_mgr::tls_storage *
get_tls(void*)
{
static __thread epoch_mgr::tls_storage s;
return &s;
}
void *
thread_registered(void*)
{
tls.epoch = 0;
tls.bitmap = 0;
tls.base_id = 0;
tls.initialized = true;
return &tls;
}
void
thread_deregistered(void*, void *thread_cookie)
{
auto *t = (thread_data*) thread_cookie;
ASSERT(t == &tls);
while (t->bitmap) {
auto x = take_one(t);
xid_free(x);
}
t->initialized = false;
}
/* Don't need these... we track resources a different way
*/
void *
epoch_ended(void*, epoch_mgr::epoch_num)
{
return 0;
}
void *
epoch_ended_thread(void *, void *epoch_cookie, void *)
{
return epoch_cookie;
}
void
epoch_reclaimed(void *, void *)
{
}
epoch_mgr xid_epochs{{
nullptr, &global_init, &get_tls,
&thread_registered, &thread_deregistered,
&epoch_ended, &epoch_ended_thread,
&epoch_reclaimed}};
os_mutex_pod xid_mutex = os_mutex_pod::static_init();
# if 0
{ // disable autoindent
#endif
XID
xid_alloc()
{
if (not tls.initialized)
xid_epochs.thread_init();
while (not tls.bitmap) {
/* Grab a whole machine word at a time. Use the epoch_mgr to
protect us if we happen to straggle. Note that we may
(through bad luck) acquire an empty word and need to retry.
*/
auto e = xid_epochs.thread_enter();
DEFER_UNLESS(exited, xid_epochs.thread_exit());
auto &b = xid_bitmaps[e % NBITMAPS];
auto i = volatile_read(b.widx);
ASSERT(i <= xid_bitmap::NWORDS);
while (i < xid_bitmap::NWORDS) {
auto j = __sync_val_compare_and_swap(&b.widx, i, i+1);
if (j == i) {
/* NOTE: no need for a goto: the compiler will thread
the jump so we skip the overflow check entirely
*/
break;
}
i = j;
}
if (i == xid_bitmap::NWORDS) {
// overflow!
xid_epochs.thread_exit();
exited = true;
xid_mutex.lock();
DEFER(xid_mutex.unlock());
if (e == xid_epochs.get_cur_epoch()) {
/* Still at end, try to open a new epoch.
If there are stragglers (highly unlikely) then
sleep until they leave.
*/
xid_bitmaps[(e+1) % NBITMAPS].widx = 0;
while (not xid_epochs.new_epoch())
usleep(1000);
}
continue;
}
tls.epoch = e;
tls.base_id = (e % 2)*NCONTEXTS/2 + i*xid_bitmap::BITS_PER_WORD;
std::swap(tls.bitmap, b.data[i]);
}
return take_one(&tls);
}
#ifdef SSN
bool
xid_context::set_sstamp(uint64_t s) {
ALWAYS_ASSERT(!(s & xid_context::sstamp_final_mark));
// If I'm not read-mostly, nobody else would call this
if (xct->is_read_mostly() && config::ssn_read_opt_enabled()) {
// This has to be a CAS because with read-optimization, the updater might need
// to update the reader's sstamp.
uint64_t ss = sstamp.load(std::memory_order_acquire);
do {
if (ss & sstamp_final_mark) {
return false;
}
} while((ss == 0 || ss > s) && !std::atomic_compare_exchange_strong(&sstamp, &ss, s));
} else {
sstamp.store(
std::min(sstamp.load(std::memory_order_relaxed), s), std::memory_order_relaxed);
}
return true;
}
#endif
} // end of namespace
<|endoftext|> |
<commit_before>
#include "atFile.h++"
#ifdef _MSC_VER
#include <Windows.h>
#include <Strsafe.h>
bool createDirectory(char * path)
{
// Attempt to create the directory (passing NULL as the second parameter
// means that we will use the security and permission profile of the
// calling user)
if (CreateDirectory(path, NULL))
{
// The operation succeeded
return true;
}
// Indicate failure
return false;
}
int listFiles(char * path, char ** results, int count)
{
char searchTarget[MAX_PATH];
HANDLE searchHandle;
WIN32_FIND_DATA fileData;
DWORD errorCode;
int fileCount;
int lengthBytes;
// Prepare the path string for use with FindFile functions (first, copy
// the string to a buffer, then append '\*' to the directory name)
StringCchCopy(searchTarget, MAX_PATH, path);
StringCchCat(searchTarget, MAX_PATH, TEXT("\\*"));
// Find the first file in the directory
searchHandle = FindFirstFile(searchTarget, &fileData);
if (searchHandle == INVALID_HANDLE_VALUE)
{
// errorCode = GetLastError();
return -1;
}
// Indicate that we haven't yet found any files
fileCount = 0;
// Proceed until our condition is met
do
{
// Check whether the name is part of the list
if (((fileData.dwFileAttributes) & (FILE_ATTRIBUTE_DIRECTORY)) == 0)
{
// Allocate a new string of this length
lengthBytes = strlen(fileData.cFileName) + 1;
results[fileCount] = (char *)malloc(lengthBytes * sizeof(char));
// Copy the file name into the string we just allocated
StringCchCopy(results[fileCount], lengthBytes, fileData.cFileName);
// Account for the file we just copied
fileCount++;
}
}
// Confirm that we haven't run out of file names or space to store them
while ((FindNextFile(searchHandle, &fileData) != 0) &&
(fileCount < count));
// FindNextFile will always set an error code if it returns non-zero
// (check whether this is actually an error or whether we've just reached
// the end of the list)
errorCode = GetLastError();
if (errorCode == ERROR_NO_MORE_FILES)
{
// Close the search handle now that we're done with it
FindClose(searchHandle);
// Return the number of filenames we successfully placed in the array
return fileCount;
}
else
{
// Close the search handle now that we're done with it (this may fail
// if the handle is invalid, but there's little we can do about that)
FindClose(searchHandle);
// This is a real error (so free the memory we've been allocating)
while (fileCount >= 0)
{
// Free the memory
free(results[fileCount]);
// Move down to the previous entry
fileCount--;
}
// Indicate failure
return -1;
}
}
#else
#include <glob.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
bool createDirectory(char * path)
{
// Attempt to create the directory (0755 is the octal value for the
// desired permissions: -rwxr-xr-x)
if (mkdir(path, 0755) == 0)
{
// The operation succeeded
return true;
}
// Indicate failure
return false;
}
int listFiles(char * path, char ** results, int count)
{
char targetPath[512];
glob_t fileList;
int fileCount;
char * currentToken;
char * nextToken;
char pathDelimiter[16];
// Convert the path into the search pattern
// TODO: Make sure the path is properly formatted
sprintf(targetPath, "%s/*", path);
// Get a list of all the files in the target location
glob(targetPath, 0, NULL, &fileList);
// Initialize our result counter
fileCount = 0;
// Print the directory separator to the path delimiter string
sprintf(pathDelimiter, "%c", DIRECTORY_SEPARATOR);
// Loop until we run out of files or out of space to store them
while ((fileCount < count) &&
(fileCount < (int ) fileList.gl_pathc))
{
// We want to take only the files themselves, but the vector contains
// paths as well (tokenizing on the delimiter string will allow us to
// extract only the filename. Begin by pulling off the first token)
currentToken = strtok(fileList.gl_pathv[fileCount], pathDelimiter);
// Keep attempting to fetch the next token so long as there is one
nextToken = strtok(NULL, pathDelimiter);
while (nextToken)
{
// Move the current token forward
currentToken = nextToken;
// Query the next token
nextToken = strtok(NULL, pathDelimiter);
}
// The next token is NULL, which means there are no more delimiters,
// which means that our current token contains only the file name so
// allocate a new string of this length.
results[fileCount] = (char *)
malloc((strlen(currentToken) + 1) * sizeof(char));
// Copy the file name into the string we just allocated
strcpy(results[fileCount], currentToken);
// Account for the file we just copied
fileCount++;
}
// Free the original path list
globfree(&fileList);
// Return the number of files we found
return fileCount;
}
#endif
<commit_msg> * Added isDirectory(...), which will return true if a specified path exists and is a directory (false otherwise).<commit_after>
#include "atFile.h++"
#ifdef _MSC_VER
#include <Windows.h>
#include <Strsafe.h>
#include <sys/types.h>
#include <sys/stat.h>
bool isDirectory(char * path)
{
struct stat fileStat;
// Make sure we have a path at all
if (path == NULL)
{
// No path is not a directory
return false;
}
// Make sure the target on this path exists
if (access(path, F_OK) != 0)
{
// The target does not exist thus it can't be a directory
return false;
}
// Get the file information
stat(path, &fileStat);
// Check if the file is a directory
if (fileStat.st_mode & _S_IFDIR)
{
return true;
}
else
{
return false;
}
}
bool createDirectory(char * path)
{
// Attempt to create the directory (passing NULL as the second parameter
// means that we will use the security and permission profile of the
// calling user)
if (CreateDirectory(path, NULL))
{
// The operation succeeded
return true;
}
// Indicate failure
return false;
}
int listFiles(char * path, char ** results, int count)
{
char searchTarget[MAX_PATH];
HANDLE searchHandle;
WIN32_FIND_DATA fileData;
DWORD errorCode;
int fileCount;
int lengthBytes;
// Prepare the path string for use with FindFile functions (first, copy
// the string to a buffer, then append '\*' to the directory name)
StringCchCopy(searchTarget, MAX_PATH, path);
StringCchCat(searchTarget, MAX_PATH, TEXT("\\*"));
// Find the first file in the directory
searchHandle = FindFirstFile(searchTarget, &fileData);
if (searchHandle == INVALID_HANDLE_VALUE)
{
// errorCode = GetLastError();
return -1;
}
// Indicate that we haven't yet found any files
fileCount = 0;
// Proceed until our condition is met
do
{
// Check whether the name is part of the list
if (((fileData.dwFileAttributes) & (FILE_ATTRIBUTE_DIRECTORY)) == 0)
{
// Allocate a new string of this length
lengthBytes = strlen(fileData.cFileName) + 1;
results[fileCount] = (char *)malloc(lengthBytes * sizeof(char));
// Copy the file name into the string we just allocated
StringCchCopy(results[fileCount], lengthBytes, fileData.cFileName);
// Account for the file we just copied
fileCount++;
}
}
// Confirm that we haven't run out of file names or space to store them
while ((FindNextFile(searchHandle, &fileData) != 0) &&
(fileCount < count));
// FindNextFile will always set an error code if it returns non-zero
// (check whether this is actually an error or whether we've just reached
// the end of the list)
errorCode = GetLastError();
if (errorCode == ERROR_NO_MORE_FILES)
{
// Close the search handle now that we're done with it
FindClose(searchHandle);
// Return the number of filenames we successfully placed in the array
return fileCount;
}
else
{
// Close the search handle now that we're done with it (this may fail
// if the handle is invalid, but there's little we can do about that)
FindClose(searchHandle);
// This is a real error (so free the memory we've been allocating)
while (fileCount >= 0)
{
// Free the memory
free(results[fileCount]);
// Move down to the previous entry
fileCount--;
}
// Indicate failure
return -1;
}
}
#else
#include <glob.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
bool isDirectory(char * path)
{
struct stat fileStat;
// Make sure we have a path at all
if (path == NULL)
{
// No path is not a directory
return false;
}
// Make sure the target on this path exists
if (access(path, F_OK) != 0)
{
// The target does not exist thus it can't be a directory
return false;
}
// Get the file information
stat(path, &fileStat);
// Check if the file is a directory
if (fileStat.st_mode & S_IFDIR)
{
return true;
}
else
{
return false;
}
}
bool createDirectory(char * path)
{
// Attempt to create the directory (0755 is the octal value for the
// desired permissions: -rwxr-xr-x)
if (mkdir(path, 0755) == 0)
{
// The operation succeeded
return true;
}
// Indicate failure
return false;
}
int listFiles(char * path, char ** results, int count)
{
char targetPath[512];
glob_t fileList;
int fileCount;
char * currentToken;
char * nextToken;
char pathDelimiter[16];
// Convert the path into the search pattern
// TODO: Make sure the path is properly formatted
sprintf(targetPath, "%s/*", path);
// Get a list of all the files in the target location
glob(targetPath, 0, NULL, &fileList);
// Initialize our result counter
fileCount = 0;
// Print the directory separator to the path delimiter string
sprintf(pathDelimiter, "%c", DIRECTORY_SEPARATOR);
// Loop until we run out of files or out of space to store them
while ((fileCount < count) &&
(fileCount < (int ) fileList.gl_pathc))
{
// We want to take only the files themselves, but the vector contains
// paths as well (tokenizing on the delimiter string will allow us to
// extract only the filename. Begin by pulling off the first token)
currentToken = strtok(fileList.gl_pathv[fileCount], pathDelimiter);
// Keep attempting to fetch the next token so long as there is one
nextToken = strtok(NULL, pathDelimiter);
while (nextToken)
{
// Move the current token forward
currentToken = nextToken;
// Query the next token
nextToken = strtok(NULL, pathDelimiter);
}
// The next token is NULL, which means there are no more delimiters,
// which means that our current token contains only the file name so
// allocate a new string of this length.
results[fileCount] = (char *)
malloc((strlen(currentToken) + 1) * sizeof(char));
// Copy the file name into the string we just allocated
strcpy(results[fileCount], currentToken);
// Account for the file we just copied
fileCount++;
}
// Free the original path list
globfree(&fileList);
// Return the number of files we found
return fileCount;
}
#endif
<|endoftext|> |
<commit_before>#ifndef FP_DERIVATIVE_HPP
#define FP_DERIVATIVE_HPP
namespace fp {
}
#endif<commit_msg>Coding up the derivative and some type traits i need to write the function (through std::enable_if)<commit_after>#ifndef FP_DERIVATIVE_HPP
#define FP_DERIVATIVE_HPP
#include <type_traits>
#include <cmath>
#include <limits>
namespace fp {
// we'd like a template to determine the arity
// of a function/functor f. We can do this with
// a metafunction.
template<typename Func>
struct arity;
template<typename Ret, typename... Args>
struct arity<Ret(Args...)>
{
static constexpr auto value = sizeof...(Args);
};
// we'd like a template to determine that the
// return type of a function is an arithmetic type
// this way we can use it in an enable_if
template<typename Func>
struct is_arithmetic_function;
// use std::is_arithmetic so that we don't need
// to do a lot of specializations
template<typename Ret, typename... Args>
struct is_arithmetic_function<Ret(Args...)>
{
static constexpr auto value = std::is_arithmetic<Ret>::value;
};
// dummy template
template<typename Ret, typename... Args>
struct arithmetic_args;
// a template to determine whether the arguments
// of a function are all arithmetic types
template<typename Ret, typename Arg0, typename... Args>
struct arithmetic_args<Ret(Arg0, Args...)>
{
static constexpr auto value = std::is_arithmetic<Arg0>::value && arithmetic_args<Ret(Args...)>::value;
};
template<typename Ret, typename Arg>
struct arithmetic_args<Ret(Arg)>
{
static constexpr auto value = std::is_arithmetic<Arg>::value;
};
// get the return type of a function
template<typename Func>
struct return_type;
template<typename Ret, typename... Args>
struct return_type<Ret(Args...)>
{
using type = Ret;
};
// derivative routine:
// check if the function has arity 1 and returns an arithmetic type
// otherwise substitution failure will kick in
template<typename F>
typename std::enable_if<((arity<F>::value == 1) &&
(is_arithmetic_function<F>::value)),
typename return_type<F>::type>::type derivative(const F& func, typename return_type<F>::type x)
{
const auto h = std::sqrt(std::numeric_limits<typename return_type<F>::type>::epsilon());
return (func(x + h) - func(x - h)) / (2 * h);
};
}
#endif<|endoftext|> |
<commit_before><commit_msg>added period.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "memory_subsystem.h"
#include "agent/util/path_tree.h"
#include "protocol/galaxy.pb.h"
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
namespace baidu {
namespace galaxy {
namespace cgroup {
MemorySubsystem::MemorySubsystem() {
}
MemorySubsystem::~MemorySubsystem() {
}
std::string MemorySubsystem::Name() {
return "memory";
}
int MemorySubsystem::Construct() {
assert(!this->container_id_.empty());
assert(NULL != this->cgroup_.get());
std::string path = this->Path();
boost::system::error_code ec;
if (!boost::filesystem::exists(path, ec) && !boost::filesystem::create_directories(path, ec)) {
return -1;
}
boost::filesystem::path memory_limit_path = path;
memory_limit_path.append("memory.limit_in_bytes");
if (0 != baidu::galaxy::cgroup::Attach(memory_limit_path.c_str(),
this->cgroup_->memory().size()),
false) {
return -1;
}
int64_t excess_mode = this->cgroup_->memory().excess() ? 1L : 0L;
boost::filesystem::path excess_mode_path = path;
excess_mode_path.append("memory.excess_mode");
if (0 != baidu::galaxy::cgroup::Attach(excess_mode_path.c_str(),
excess_mode,
false)) {
return -1;
}
boost::filesystem::path kill_mode_path = path;
kill_mode_path.append("memory.kill_mode");
if (0 != baidu::galaxy::cgroup::Attach(kill_mode_path.c_str(),
0L,
false)) {
return -1;
}
return 0;
}
boost::shared_ptr<google::protobuf::Message> MemorySubsystem::Status() {
boost::shared_ptr<google::protobuf::Message> ret;
return ret;
}
boost::shared_ptr<Subsystem> MemorySubsystem::Clone() {
boost::shared_ptr<Subsystem> ret(new MemorySubsystem());
return ret;
}
} //namespace cgroup
} //namespace galaxy
} //namespace baidu
<commit_msg>fix typoo<commit_after>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "memory_subsystem.h"
#include "agent/util/path_tree.h"
#include "protocol/galaxy.pb.h"
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
namespace baidu {
namespace galaxy {
namespace cgroup {
MemorySubsystem::MemorySubsystem() {
}
MemorySubsystem::~MemorySubsystem() {
}
std::string MemorySubsystem::Name() {
return "memory";
}
int MemorySubsystem::Construct() {
assert(!this->container_id_.empty());
assert(NULL != this->cgroup_.get());
std::string path = this->Path();
boost::system::error_code ec;
if (!boost::filesystem::exists(path, ec) && !boost::filesystem::create_directories(path, ec)) {
return -1;
}
boost::filesystem::path memory_limit_path = path;
memory_limit_path.append("memory.limit_in_bytes");
if (0 != baidu::galaxy::cgroup::Attach(memory_limit_path.c_str(),
this->cgroup_->memory().size(),
false)) {
return -1;
}
int64_t excess_mode = this->cgroup_->memory().excess() ? 1L : 0L;
boost::filesystem::path excess_mode_path = path;
excess_mode_path.append("memory.excess_mode");
if (0 != baidu::galaxy::cgroup::Attach(excess_mode_path.c_str(),
excess_mode,
false)) {
return -1;
}
boost::filesystem::path kill_mode_path = path;
kill_mode_path.append("memory.kill_mode");
if (0 != baidu::galaxy::cgroup::Attach(kill_mode_path.c_str(),
0L,
false)) {
return -1;
}
return 0;
}
boost::shared_ptr<google::protobuf::Message> MemorySubsystem::Status() {
boost::shared_ptr<google::protobuf::Message> ret;
return ret;
}
boost::shared_ptr<Subsystem> MemorySubsystem::Clone() {
boost::shared_ptr<Subsystem> ret(new MemorySubsystem());
return ret;
}
} //namespace cgroup
} //namespace galaxy
} //namespace baidu
<|endoftext|> |
<commit_before>// See Fossen 2011, chapter 12.3.2
#include "lagrange_allocator.h"
#include <iostream>
#include <math.h>
template<typename Derived>
inline bool isFucked(const Eigen::MatrixBase<Derived>& x)
{
return !((x.array() == x.array())).all() && !( (x - x).array() == (x - x).array()).all();
}
// Function to check for existence of Indian bread
template<typename T, int r, int c>
inline bool hasNan(const Eigen::Matrix<T,r,c>& M)
{
int rows = M.rows();
int cols = M.cols();
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
if (isnan(M(i,j)))
{
return true;
}
}
}
return false;
}
void printMatrix6(Eigen::MatrixXd m);
LagrangeAllocator::LagrangeAllocator()
{
sub = nh.subscribe("rov_forces", 10, &LagrangeAllocator::callback, this);
pub = nh.advertise<maelstrom_msgs::ThrusterForces>("thruster_forces", 10);
W.setIdentity(); // Default to identity (i.e. equal weights)
K.setIdentity(); // Scaling is done on Arduino, so this can be identity
// Thruster configuration does not allow control of roll.
T << 0.7071 , 0.7071 , -0.7071 , -0.7071 , 0 , 0 , // Surge
0.7071 , -0.7071 , -0.7071 , 0.7071 , 0 , 0 , // Sway
0 , 0 , 0 , 0 , 1 , 1 , // Heave
-0.04667, -0.04667, 0.04667, 0.04667, -0.1600, 0.1600, // Pitch
0.2143 , -0.2143 , 0.2143 , -0.2143 , 0 , 0 ; // Yaw
K_inverse = K.inverse();
computeGeneralizedInverse();
}
void LagrangeAllocator::callback(const geometry_msgs::Wrench& tauMsg)
{
tau << tauMsg.force.x,
tauMsg.force.y,
tauMsg.force.z,
// tauMsg.torque.x, // Roll is not controllable
tauMsg.torque.y,
tauMsg.torque.z;
u = K_inverse * T_geninverse * tau;
if (isFucked(K_inverse))
{
ROS_WARN("K is not invertible");
}
maelstrom_msgs::ThrusterForces uMsg;
uMsg.F1 = u(0);
uMsg.F2 = u(1);
uMsg.F3 = u(2);
uMsg.F4 = u(3);
uMsg.F5 = u(4);
uMsg.F6 = u(5);
pub.publish(uMsg);
ROS_INFO_STREAM("lagrange_allocator: Sending " << u(0) << ", " << u(1) << ", " << u(2) << ", " << u(3) << ", " << u(4) << ", " << u(5));
}
void LagrangeAllocator::setWeights(const Eigen::MatrixXd &W_new)
{
bool correctDimensions = ( W_new.rows() == r && W_new.cols() == r );
if (!correctDimensions)
{
ROS_WARN_STREAM("Attempt to set weight matrix in LagrangeAllocator with wrong dimensions " << W_new.rows() << "*" << W_new.cols() << ".");
return;
}
W = W_new;
// New weights require recomputing the generalized inverse of the thrust config matrix
computeGeneralizedInverse();
}
void LagrangeAllocator::computeGeneralizedInverse()
{
T_geninverse = W.inverse()*T.transpose() * (T*W.inverse()*T.transpose()).inverse();
// ROS_INFO("Printing in order: T_geninverse, W, T, K_inverse.");
// printMatrix6(T_geninverse);
// printMatrix6(W);
// printMatrix6(T);
// printMatrix6(K_inverse);
if (isFucked(T_geninverse))
{
ROS_WARN("T_geninverse NAN");
}
if (isFucked( W.inverse() ))
{
ROS_WARN("W is not invertible");
}
if (isFucked( (T*W.inverse()*T.transpose()).inverse() ) )
{
ROS_WARN("T * W_inv * T transposed is not invertible");
}
}
// Worlds worst print function :DDD
void printMatrix6(Eigen::MatrixXd m)
{
ROS_INFO("----------------------------------");
for(int col = 0; col < 6; col++)
{
char buffer[512];
for(int row = 0; row < 6; row++)
{
snprintf( (buffer + (row*8) ), sizeof(buffer), " %f ", m(col, row));
}
ROS_INFO("%s", buffer);
}
ROS_INFO("----------------------------------\n");
}<commit_msg>Comment out annoying debug print<commit_after>// See Fossen 2011, chapter 12.3.2
#include "lagrange_allocator.h"
#include <iostream>
#include <math.h>
template<typename Derived>
inline bool isFucked(const Eigen::MatrixBase<Derived>& x)
{
return !((x.array() == x.array())).all() && !( (x - x).array() == (x - x).array()).all();
}
// Function to check for existence of Indian bread
template<typename T, int r, int c>
inline bool hasNan(const Eigen::Matrix<T,r,c>& M)
{
int rows = M.rows();
int cols = M.cols();
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
if (isnan(M(i,j)))
{
return true;
}
}
}
return false;
}
void printMatrix6(Eigen::MatrixXd m);
LagrangeAllocator::LagrangeAllocator()
{
sub = nh.subscribe("rov_forces", 10, &LagrangeAllocator::callback, this);
pub = nh.advertise<maelstrom_msgs::ThrusterForces>("thruster_forces", 10);
W.setIdentity(); // Default to identity (i.e. equal weights)
K.setIdentity(); // Scaling is done on Arduino, so this can be identity
// Thruster configuration does not allow control of roll.
T << 0.7071 , 0.7071 , -0.7071 , -0.7071 , 0 , 0 , // Surge
0.7071 , -0.7071 , -0.7071 , 0.7071 , 0 , 0 , // Sway
0 , 0 , 0 , 0 , 1 , 1 , // Heave
-0.04667, -0.04667, 0.04667, 0.04667, -0.1600, 0.1600, // Pitch
0.2143 , -0.2143 , 0.2143 , -0.2143 , 0 , 0 ; // Yaw
K_inverse = K.inverse();
computeGeneralizedInverse();
}
void LagrangeAllocator::callback(const geometry_msgs::Wrench& tauMsg)
{
tau << tauMsg.force.x,
tauMsg.force.y,
tauMsg.force.z,
// tauMsg.torque.x, // Roll is not controllable
tauMsg.torque.y,
tauMsg.torque.z;
u = K_inverse * T_geninverse * tau;
if (isFucked(K_inverse))
{
ROS_WARN("K is not invertible");
}
maelstrom_msgs::ThrusterForces uMsg;
uMsg.F1 = u(0);
uMsg.F2 = u(1);
uMsg.F3 = u(2);
uMsg.F4 = u(3);
uMsg.F5 = u(4);
uMsg.F6 = u(5);
pub.publish(uMsg);
// ROS_INFO_STREAM("lagrange_allocator: Sending " << u(0) << ", " << u(1) << ", " << u(2) << ", " << u(3) << ", " << u(4) << ", " << u(5));
}
void LagrangeAllocator::setWeights(const Eigen::MatrixXd &W_new)
{
bool correctDimensions = ( W_new.rows() == r && W_new.cols() == r );
if (!correctDimensions)
{
ROS_WARN_STREAM("Attempt to set weight matrix in LagrangeAllocator with wrong dimensions " << W_new.rows() << "*" << W_new.cols() << ".");
return;
}
W = W_new;
// New weights require recomputing the generalized inverse of the thrust config matrix
computeGeneralizedInverse();
}
void LagrangeAllocator::computeGeneralizedInverse()
{
T_geninverse = W.inverse()*T.transpose() * (T*W.inverse()*T.transpose()).inverse();
// ROS_INFO("Printing in order: T_geninverse, W, T, K_inverse.");
// printMatrix6(T_geninverse);
// printMatrix6(W);
// printMatrix6(T);
// printMatrix6(K_inverse);
if (isFucked(T_geninverse))
{
ROS_WARN("T_geninverse NAN");
}
if (isFucked( W.inverse() ))
{
ROS_WARN("W is not invertible");
}
if (isFucked( (T*W.inverse()*T.transpose()).inverse() ) )
{
ROS_WARN("T * W_inv * T transposed is not invertible");
}
}
// Worlds worst print function :DDD
void printMatrix6(Eigen::MatrixXd m)
{
ROS_INFO("----------------------------------");
for(int col = 0; col < 6; col++)
{
char buffer[512];
for(int row = 0; row < 6; row++)
{
snprintf( (buffer + (row*8) ), sizeof(buffer), " %f ", m(col, row));
}
ROS_INFO("%s", buffer);
}
ROS_INFO("----------------------------------\n");
}<|endoftext|> |
<commit_before>// See Fossen 2011, chapter 12.3.2
#include "lagrange_allocator.h"
template<typename Derived>
inline bool is_fucked(const Eigen::MatrixBase<Derived>& x)
{
return !((x.array() == x.array())).all() && !( (x - x).array() == (x - x).array()).all();
}
LagrangeAllocator::LagrangeAllocator()
{
n = 6;
r = 6;
tauSub = nh.subscribe("controlForces", 1, &LagrangeAllocator::tauCallback, this);
uPub = nh.advertise<uranus_dp::ThrusterForces>("controlInputs", 1);
W.setIdentity(6,6); // Default to identity (i.e. no weights)
K = Eigen::MatrixXd::Identity(6,6); // Scaling is done on Arduino, so this can be identity
T << 0.7071 , 0.7071 , 0.7071 , 0.7071 , 1 , 1 ,
-0.7071 , 0.7071 , -0.7071 , 0.7071 , 0 , 0 ,
0 , 0 , 0 , 0 , 0 , 0 ,
0.06718, -0.06718, 0.06718, -0.06718, 0 , 0 ,
0.06718, 0.06718, 0.06718, 0.06718, -0.210, -0.210,
0.4172 , 0.4172 , -0.4172 , -0.4172 , -0.165, 0.165;
K_inverse = K.inverse();
computeGeneralizedInverse();
}
void LagrangeAllocator::tauCallback(const geometry_msgs::Wrench& tauMsg)
{
tau << tauMsg.force.x,
tauMsg.force.y,
tauMsg.force.z,
tauMsg.torque.x,
tauMsg.torque.y,
tauMsg.torque.z;
u = K_inverse * T_geninverse * tau;
if(is_fucked(K_inverse))
{
ROS_WARN("K is not invertible");
}
uranus_dp::ThrusterForces uMsg;
uMsg.F1 = u(0);
uMsg.F2 = u(1);
uMsg.F3 = u(2);
uMsg.F4 = u(3);
uMsg.F5 = u(4);
uMsg.F6 = u(5);
uPub.publish(uMsg);
}
void LagrangeAllocator::setWeights(const Eigen::MatrixXd &W_new)
{
bool correctDimensions = ( W_new.rows() == r && W_new.cols() == r );
// ROS_INFO("correctDimensions = %d\n", correctDimensions);
if (!correctDimensions)
{
ROS_WARN_STREAM("Attempt to set weight matrix in LagrangeAllocator with wrong dimensions " << W_new.rows() << "*" << W_new.cols() << ".\n");
return;
}
W = W_new; // I have checked that Eigen does a deep copy here
// New weights mean we must recompute the generalized inverse of the T matrix
computeGeneralizedInverse();
}
void LagrangeAllocator::computeGeneralizedInverse()
{
T_geninverse = W.inverse()*T.transpose() * (T*W.inverse()*T.transpose()).inverse();
if(is_fucked(T_geninverse))
{
ROS_WARN("T_geninverse NAN");
}
if(is_fucked( W.inverse() ))
{
ROS_WARN("W is not invertible");
}
if(is_fucked( (T*W.inverse()*T.transpose()).inverse() ) )
{
ROS_WARN("T * W_inv * T transposed is not invertible");
}
}
<commit_msg>Force T matrix less singular<commit_after>// See Fossen 2011, chapter 12.3.2
#include "lagrange_allocator.h"
template<typename Derived>
inline bool is_fucked(const Eigen::MatrixBase<Derived>& x)
{
return !((x.array() == x.array())).all() && !( (x - x).array() == (x - x).array()).all();
}
LagrangeAllocator::LagrangeAllocator()
{
n = 6;
r = 6;
tauSub = nh.subscribe("controlForces", 1, &LagrangeAllocator::tauCallback, this);
uPub = nh.advertise<uranus_dp::ThrusterForces>("controlInputs", 1);
W.setIdentity(6,6); // Default to identity (i.e. no weights)
K.setIdentity(6,6); // Scaling is done on Arduino, so this can be identity
T << 0.7071 , 0.7071 , 0.7071 , 0.7071 , 1 , 1 ,
-0.7071 , 0.7071 , -0.7071 , 0.7071 , 0 , 0 ,
0 , 0 , 0 , 0 , 0.1 , -0.1 , // Nonzero elements added to make matrix nonsingular
0.06718, -0.06718, 0.06718, -0.06718, 0 , 0 ,
0.06718, 0.06718, 0.06718, 0.06718, -0.210, -0.210,
0.4172 , 0.4172 , -0.4172 , -0.4172 , -0.165, 0.165;
K_inverse = K.inverse();
computeGeneralizedInverse();
}
void LagrangeAllocator::tauCallback(const geometry_msgs::Wrench& tauMsg)
{
tau << tauMsg.force.x,
tauMsg.force.y,
tauMsg.force.z,
tauMsg.torque.x,
tauMsg.torque.y,
tauMsg.torque.z;
u = K_inverse * T_geninverse * tau;
if(is_fucked(K_inverse))
{
ROS_WARN("K is not invertible");
}
uranus_dp::ThrusterForces uMsg;
uMsg.F1 = u(0);
uMsg.F2 = u(1);
uMsg.F3 = u(2);
uMsg.F4 = u(3);
uMsg.F5 = u(4);
uMsg.F6 = u(5);
uPub.publish(uMsg);
}
void LagrangeAllocator::setWeights(const Eigen::MatrixXd &W_new)
{
bool correctDimensions = ( W_new.rows() == r && W_new.cols() == r );
// ROS_INFO("correctDimensions = %d\n", correctDimensions);
if (!correctDimensions)
{
ROS_WARN_STREAM("Attempt to set weight matrix in LagrangeAllocator with wrong dimensions " << W_new.rows() << "*" << W_new.cols() << ".\n");
return;
}
W = W_new; // I have checked that Eigen does a deep copy here
// New weights mean we must recompute the generalized inverse of the T matrix
computeGeneralizedInverse();
}
void LagrangeAllocator::computeGeneralizedInverse()
{
T_geninverse = W.inverse()*T.transpose() * (T*W.inverse()*T.transpose()).inverse();
if(is_fucked(T_geninverse))
{
ROS_WARN("T_geninverse NAN");
}
if(is_fucked( W.inverse() ))
{
ROS_WARN("W is not invertible");
}
if(is_fucked( (T*W.inverse()*T.transpose()).inverse() ) )
{
ROS_WARN("T * W_inv * T transposed is not invertible");
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* Copyright (c) 2007 MIPS Technologies, 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 the copyright holders 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.
*
* Authors: Gabe Black
* Korey Sewell
* Jaidev Patwardhan
*/
#include "arch/mips/regfile/int_regfile.hh"
#include "sim/serialize.hh"
using namespace MipsISA;
using namespace std;
void
IntRegFile::clear()
{
bzero(®s, sizeof(regs));
currShadowSet=0;
}
void
IntRegFile::setShadowSet(int css)
{
DPRINTF(MipsPRA,"Setting Shadow Set to :%d (%s)\n",css,currShadowSet);
currShadowSet = css;
}
IntReg
IntRegFile::readReg(int intReg)
{
if(intReg < NumIntRegs)
{ // Regular GPR Read
DPRINTF(MipsPRA,"Reading Reg: %d, CurrShadowSet: %d\n",intReg,currShadowSet);
if(intReg >= NumIntArchRegs*NumShadowRegSets){
return regs[intReg+NumIntRegs*currShadowSet];
}
else {
return regs[(intReg + NumIntArchRegs*currShadowSet) % NumIntArchRegs];
}
}
else
{ // Read from shadow GPR .. probably called by RDPGPR
return regs[intReg];
}
}
Fault
IntRegFile::setReg(int intReg, const IntReg &val)
{
if (intReg != ZeroReg) {
if(intReg < NumIntRegs)
{
if(intReg >= NumIntArchRegs*NumShadowRegSets){
regs[intReg] = val;
}
else{
regs[intReg+NumIntRegs*currShadowSet] = val;
}
}
else{
regs[intReg] = val;
}
}
return NoFault;
}
void
IntRegFile::serialize(std::ostream &os)
{
SERIALIZE_ARRAY(regs, NumIntRegs);
}
void
IntRegFile::unserialize(Checkpoint *cp, const std::string §ion)
{
UNSERIALIZE_ARRAY(regs, NumIntRegs);
}
<commit_msg>style: this file did not conform to style<commit_after>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* Copyright (c) 2007 MIPS Technologies, 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 the copyright holders 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.
*
* Authors: Gabe Black
* Korey Sewell
* Jaidev Patwardhan
*/
#include "arch/mips/regfile/int_regfile.hh"
#include "sim/serialize.hh"
using namespace MipsISA;
using namespace std;
void
IntRegFile::clear()
{
bzero(®s, sizeof(regs));
currShadowSet=0;
}
void
IntRegFile::setShadowSet(int css)
{
DPRINTF(MipsPRA, "Setting Shadow Set to :%d (%s)\n", css, currShadowSet);
currShadowSet = css;
}
IntReg
IntRegFile::readReg(int intReg)
{
if (intReg < NumIntRegs) {
// Regular GPR Read
DPRINTF(MipsPRA, "Reading Reg: %d, CurrShadowSet: %d\n", intReg,
currShadowSet);
if (intReg >= NumIntArchRegs * NumShadowRegSets) {
return regs[intReg + NumIntRegs * currShadowSet];
} else {
int index = intReg + NumIntArchRegs * currShadowSet;
index = index % NumIntArchRegs;
return regs[index];
}
} else {
// Read from shadow GPR .. probably called by RDPGPR
return regs[intReg];
}
}
Fault
IntRegFile::setReg(int intReg, const IntReg &val)
{
if (intReg != ZeroReg) {
if (intReg < NumIntRegs) {
if (intReg >= NumIntArchRegs * NumShadowRegSets)
regs[intReg] = val;
else
regs[intReg + NumIntRegs * currShadowSet] = val;
} else {
regs[intReg] = val;
}
}
return NoFault;
}
void
IntRegFile::serialize(std::ostream &os)
{
SERIALIZE_ARRAY(regs, NumIntRegs);
}
void
IntRegFile::unserialize(Checkpoint *cp, const std::string §ion)
{
UNSERIALIZE_ARRAY(regs, NumIntRegs);
}
<|endoftext|> |
<commit_before><commit_msg>Updated to C++17<commit_after><|endoftext|> |
<commit_before>#include "SolarSystem.hpp"
#include <algorithm>
using namespace std;
using namespace Geometry2d;
REGISTER_PLAY_CATEGORY(Gameplay::Plays::SolarSystem, "Demos")
Gameplay::Plays::SolarSystem::SolarSystem(GameplayModule* gameplay):
Play(gameplay)
{
}
float Gameplay::Plays::SolarSystem::score(GameplayModule* gameplay)
{
return 0;
}
bool Gameplay::Plays::SolarSystem::run()
{
const set<OurRobot *> &playRobots = _gameplay->playRobots();
if (playRobots.empty())
{
// No robots
return false;
}
Point center(0, 3);
// Make a list of robots, sorted by shell
vector<OurRobot *> robots(playRobots.size());
copy(playRobots.begin(), playRobots.end(), robots.begin());
float radiusIncrement = .35;
float startRadius = 0;
const float maxRadiusError = .05;
for (unsigned int i = 0; i < robots.size(); ++i)
{
OurRobot *bot = robots[i];
float radius = startRadius + i * radiusIncrement;
Point offset = bot->pos - center;
Point direction = offset.normalized();
Point targetOffset = direction * radius;
Point targetLocation = center + targetOffset;
Point errorVector = bot->pos - targetLocation;
float error = errorVector.mag();
if ( true ) {
// alternate direction
float dTheta = 4;
if ( i % 2 == 0 ) {
dTheta *= -1;
// dTheta = dTheta * -1;
}
targetOffset.rotate(center, dTheta);
targetLocation = targetOffset + center;
bot->move(targetLocation);
} else {
bot->move(targetLocation);
}
}
return true;
}
<commit_msg>Finished making the SolarSystem Play<commit_after>#include "SolarSystem.hpp"
#include <algorithm>
using namespace std;
using namespace Geometry2d;
REGISTER_PLAY_CATEGORY(Gameplay::Plays::SolarSystem, "Demos")
Gameplay::Plays::SolarSystem::SolarSystem(GameplayModule* gameplay):
Play(gameplay)
{
}
float Gameplay::Plays::SolarSystem::score(GameplayModule* gameplay)
{
return 0;
}
bool Gameplay::Plays::SolarSystem::run()
{
const set<OurRobot *> &playRobots = _gameplay->playRobots();
if (playRobots.empty())
{
// No robots
return false;
}
Point center(0, 3);
// Make a list of robots, sorted by shell
vector<OurRobot *> robots(playRobots.size());
copy(playRobots.begin(), playRobots.end(), robots.begin());
float radiusIncrement = .35;
float startRadius = 0;
const float maxRadiusError = .05;
for (unsigned int i = 0; i < robots.size(); ++i)
{
OurRobot *bot = robots[i];
if ( i == 0 ) {
Point faceTarget(1, 0);
float angle = bot->angle;
angle -= 15;
faceTarget.rotate(angle);
faceTarget += center;
bot->face(faceTarget);
}
float radius = startRadius + i * radiusIncrement;
Point offset = bot->pos - center;
Point direction = offset.normalized();
Point targetOffset = direction * radius;
Point targetLocation = center + targetOffset;
Point errorVector = bot->pos - targetLocation;
float error = errorVector.mag();
if ( true ) {
// alternate direction
float dTheta = 4;
if ( i % 2 == 0 ) {
dTheta *= -1;
// dTheta = dTheta * -1;
}
targetOffset.rotate(Point(0, 0), dTheta);
targetLocation = targetOffset + center;
bot->move(targetLocation);
} else {
bot->move(targetLocation);
}
state()->drawCircle(center, radius, Qt::red, "SolarSystem");
}
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <atlbase.h>
#include <vector>
#include "base/file_path.h"
#include "base/scoped_comptr_win.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/renderer_host/render_widget_host_view_win.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
class AccessibilityWinBrowserTest : public InProcessBrowserTest {
public:
AccessibilityWinBrowserTest() : screenreader_running_(FALSE) {}
// InProcessBrowserTest
void SetUpInProcessBrowserTestFixture();
void TearDownInProcessBrowserTestFixture();
protected:
IAccessible* GetRenderWidgetHostViewClientAccessible();
private:
BOOL screenreader_running_;
};
void AccessibilityWinBrowserTest::SetUpInProcessBrowserTestFixture() {
// This test assumes the windows system-wide SPI_SETSCREENREADER flag is
// cleared.
if (SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenreader_running_, 0) &&
screenreader_running_) {
// Clear the SPI_SETSCREENREADER flag and notify active applications about
// the setting change.
::SystemParametersInfo(SPI_SETSCREENREADER, FALSE, NULL, 0);
::SendNotifyMessage(
HWND_BROADCAST, WM_SETTINGCHANGE, SPI_GETSCREENREADER, 0);
}
}
void AccessibilityWinBrowserTest::TearDownInProcessBrowserTestFixture() {
if (screenreader_running_) {
// Restore the SPI_SETSCREENREADER flag and notify active applications about
// the setting change.
::SystemParametersInfo(SPI_SETSCREENREADER, TRUE, NULL, 0);
::SendNotifyMessage(
HWND_BROADCAST, WM_SETTINGCHANGE, SPI_GETSCREENREADER, 0);
}
}
class AccessibleChecker {
public:
AccessibleChecker(std::wstring expected_name, int32 expected_role);
AccessibleChecker(std::wstring expected_name, std::wstring expected_role);
// Append an AccessibleChecker that verifies accessibility information for
// a child IAccessible. Order is important.
void AppendExpectedChild(AccessibleChecker* expected_child);
// Check that the name and role of the given IAccessible instance and its
// descendants match the expected names and roles that this object was
// initialized with.
void CheckAccessible(IAccessible* accessible);
typedef std::vector<AccessibleChecker*> AccessibleCheckerVector;
private:
void CheckAccessibleName(IAccessible* accessible);
void CheckAccessibleRole(IAccessible* accessible);
void CheckAccessibleChildren(IAccessible* accessible);
private:
// Expected accessible name. Checked against IAccessible::get_accName.
std::wstring name_;
// Expected accessible role. Checked against IAccessible::get_accRole.
CComVariant role_;
// Expected accessible children. Checked using IAccessible::get_accChildCount
// and ::AccessibleChildren.
AccessibleCheckerVector children_;
};
VARIANT CreateI4Variant(LONG value) {
VARIANT variant = {0};
V_VT(&variant) = VT_I4;
V_I4(&variant) = value;
return variant;
}
IAccessible* GetAccessibleFromResultVariant(IAccessible* parent, VARIANT *var) {
switch (V_VT(var)) {
case VT_DISPATCH:
return CComQIPtr<IAccessible>(V_DISPATCH(var)).Detach();
break;
case VT_I4: {
CComPtr<IDispatch> dispatch;
HRESULT hr = parent->get_accChild(CreateI4Variant(V_I4(var)), &dispatch);
EXPECT_EQ(hr, S_OK);
return CComQIPtr<IAccessible>(dispatch).Detach();
break;
}
}
return NULL;
}
// Retrieve the MSAA client accessibility object for the Render Widget Host View
// of the selected tab.
IAccessible*
AccessibilityWinBrowserTest::GetRenderWidgetHostViewClientAccessible() {
HWND hwnd_render_widget_host_view =
browser()->GetSelectedTabContents()->GetRenderWidgetHostView()->
GetNativeView();
IAccessible* accessible;
HRESULT hr = AccessibleObjectFromWindow(
hwnd_render_widget_host_view, OBJID_CLIENT,
IID_IAccessible, reinterpret_cast<void**>(&accessible));
EXPECT_EQ(S_OK, hr);
EXPECT_NE(accessible, reinterpret_cast<IAccessible*>(NULL));
return accessible;
}
AccessibleChecker::AccessibleChecker(
std::wstring expected_name, int32 expected_role) :
name_(expected_name),
role_(expected_role) {
}
AccessibleChecker::AccessibleChecker(
std::wstring expected_name, std::wstring expected_role) :
name_(expected_name),
role_(expected_role.c_str()) {
}
void AccessibleChecker::AppendExpectedChild(
AccessibleChecker* expected_child) {
children_.push_back(expected_child);
}
void AccessibleChecker::CheckAccessible(IAccessible* accessible) {
CheckAccessibleName(accessible);
CheckAccessibleRole(accessible);
CheckAccessibleChildren(accessible);
}
void AccessibleChecker::CheckAccessibleName(IAccessible* accessible) {
CComBSTR name;
HRESULT hr =
accessible->get_accName(CreateI4Variant(CHILDID_SELF), &name);
if (name_.empty()) {
// If the object doesn't have name S_FALSE should be returned.
EXPECT_EQ(hr, S_FALSE);
} else {
// Test that the correct string was returned.
EXPECT_EQ(hr, S_OK);
EXPECT_EQ(CompareString(LOCALE_NEUTRAL, 0, name, SysStringLen(name),
name_.c_str(), name_.length()),
CSTR_EQUAL);
}
}
void AccessibleChecker::CheckAccessibleRole(IAccessible* accessible) {
VARIANT var_role = {0};
HRESULT hr =
accessible->get_accRole(CreateI4Variant(CHILDID_SELF), &var_role);
EXPECT_EQ(hr, S_OK);
ASSERT_TRUE(role_ == var_role);
}
void AccessibleChecker::CheckAccessibleChildren(IAccessible* parent) {
LONG child_count = 0;
HRESULT hr = parent->get_accChildCount(&child_count);
EXPECT_EQ(hr, S_OK);
ASSERT_EQ(child_count, children_.size());
std::auto_ptr<VARIANT> child_array(new VARIANT[child_count]);
LONG obtained_count = 0;
hr = AccessibleChildren(parent, 0, child_count,
child_array.get(), &obtained_count);
ASSERT_EQ(hr, S_OK);
ASSERT_EQ(child_count, obtained_count);
VARIANT* child = child_array.get();
for (AccessibleCheckerVector::iterator child_checker = children_.begin();
child_checker != children_.end();
++child_checker, ++child) {
ScopedComPtr<IAccessible> child_accessible;
child_accessible.Attach(GetAccessibleFromResultVariant(parent, child));
(*child_checker)->CheckAccessible(child_accessible);
}
}
IN_PROC_BROWSER_TEST_F(AccessibilityWinBrowserTest,
TestRendererAccessibilityTree) {
// By requesting an accessible chrome will believe a screen reader has been
// detected.
ScopedComPtr<IAccessible> document_accessible(
GetRenderWidgetHostViewClientAccessible());
// The initial accessible returned should have state STATE_SYSTEM_BUSY while
// the accessibility tree is being requested from the renderer.
VARIANT var_state;
HRESULT hr = document_accessible->
get_accState(CreateI4Variant(CHILDID_SELF), &var_state);
EXPECT_EQ(hr, S_OK);
EXPECT_EQ(V_VT(&var_state), VT_I4);
EXPECT_EQ(V_I4(&var_state), STATE_SYSTEM_BUSY);
GURL tree_url(
"data:text/html,<html><head><title>Accessibility Win Test</title></head>"
"<body><input type='button' value='push' /><input type='checkbox' />"
"</body></html>");
browser()->OpenURL(tree_url, GURL(), CURRENT_TAB, PageTransition::TYPED);
ui_test_utils::WaitForNotification(
NotificationType::RENDER_VIEW_HOST_ACCESSIBILITY_TREE_UPDATED);
document_accessible = GetRenderWidgetHostViewClientAccessible();
ASSERT_NE(document_accessible.get(), reinterpret_cast<IAccessible*>(NULL));
AccessibleChecker button_checker(L"push", ROLE_SYSTEM_PUSHBUTTON);
AccessibleChecker checkbox_checker(L"", ROLE_SYSTEM_CHECKBUTTON);
AccessibleChecker grouping_checker(L"", L"div");
grouping_checker.AppendExpectedChild(&button_checker);
grouping_checker.AppendExpectedChild(&checkbox_checker);
AccessibleChecker document_checker(L"", ROLE_SYSTEM_DOCUMENT);
document_checker.AppendExpectedChild(&grouping_checker);
// Check the accessible tree of the renderer.
document_checker.CheckAccessible(document_accessible);
// Check that document accessible has a parent accessible.
ScopedComPtr<IDispatch> parent_dispatch;
hr = document_accessible->get_accParent(parent_dispatch.Receive());
EXPECT_EQ(hr, S_OK);
EXPECT_NE(parent_dispatch, reinterpret_cast<IDispatch*>(NULL));
// Navigate to another page.
GURL about_url("about:");
ui_test_utils::NavigateToURL(browser(), about_url);
// Verify that the IAccessible reference still points to a valid object and
// that it calls to its methods fail since the tree is no longer valid after
// the page navagation.
// Todo(ctguil): Currently this is giving a false positive because E_FAIL is
// returned when BrowserAccessibilityManager::RequestAccessibilityInfo fails
// since the previous render view host connection is lost. Verify that
// instances are actually marked as invalid once the browse side cache is
// checked in.
CComBSTR name;
hr = document_accessible->get_accName(CreateI4Variant(CHILDID_SELF), &name);
ASSERT_EQ(E_FAIL, hr);
}
} // namespace.
<commit_msg>Disable AccessibilityWinBrowserTest.TestRendererAccessibilityTree which is failing after WebKit roll<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <atlbase.h>
#include <vector>
#include "base/file_path.h"
#include "base/scoped_comptr_win.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/renderer_host/render_widget_host_view_win.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
class AccessibilityWinBrowserTest : public InProcessBrowserTest {
public:
AccessibilityWinBrowserTest() : screenreader_running_(FALSE) {}
// InProcessBrowserTest
void SetUpInProcessBrowserTestFixture();
void TearDownInProcessBrowserTestFixture();
protected:
IAccessible* GetRenderWidgetHostViewClientAccessible();
private:
BOOL screenreader_running_;
};
void AccessibilityWinBrowserTest::SetUpInProcessBrowserTestFixture() {
// This test assumes the windows system-wide SPI_SETSCREENREADER flag is
// cleared.
if (SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenreader_running_, 0) &&
screenreader_running_) {
// Clear the SPI_SETSCREENREADER flag and notify active applications about
// the setting change.
::SystemParametersInfo(SPI_SETSCREENREADER, FALSE, NULL, 0);
::SendNotifyMessage(
HWND_BROADCAST, WM_SETTINGCHANGE, SPI_GETSCREENREADER, 0);
}
}
void AccessibilityWinBrowserTest::TearDownInProcessBrowserTestFixture() {
if (screenreader_running_) {
// Restore the SPI_SETSCREENREADER flag and notify active applications about
// the setting change.
::SystemParametersInfo(SPI_SETSCREENREADER, TRUE, NULL, 0);
::SendNotifyMessage(
HWND_BROADCAST, WM_SETTINGCHANGE, SPI_GETSCREENREADER, 0);
}
}
class AccessibleChecker {
public:
AccessibleChecker(std::wstring expected_name, int32 expected_role);
AccessibleChecker(std::wstring expected_name, std::wstring expected_role);
// Append an AccessibleChecker that verifies accessibility information for
// a child IAccessible. Order is important.
void AppendExpectedChild(AccessibleChecker* expected_child);
// Check that the name and role of the given IAccessible instance and its
// descendants match the expected names and roles that this object was
// initialized with.
void CheckAccessible(IAccessible* accessible);
typedef std::vector<AccessibleChecker*> AccessibleCheckerVector;
private:
void CheckAccessibleName(IAccessible* accessible);
void CheckAccessibleRole(IAccessible* accessible);
void CheckAccessibleChildren(IAccessible* accessible);
private:
// Expected accessible name. Checked against IAccessible::get_accName.
std::wstring name_;
// Expected accessible role. Checked against IAccessible::get_accRole.
CComVariant role_;
// Expected accessible children. Checked using IAccessible::get_accChildCount
// and ::AccessibleChildren.
AccessibleCheckerVector children_;
};
VARIANT CreateI4Variant(LONG value) {
VARIANT variant = {0};
V_VT(&variant) = VT_I4;
V_I4(&variant) = value;
return variant;
}
IAccessible* GetAccessibleFromResultVariant(IAccessible* parent, VARIANT *var) {
switch (V_VT(var)) {
case VT_DISPATCH:
return CComQIPtr<IAccessible>(V_DISPATCH(var)).Detach();
break;
case VT_I4: {
CComPtr<IDispatch> dispatch;
HRESULT hr = parent->get_accChild(CreateI4Variant(V_I4(var)), &dispatch);
EXPECT_EQ(hr, S_OK);
return CComQIPtr<IAccessible>(dispatch).Detach();
break;
}
}
return NULL;
}
// Retrieve the MSAA client accessibility object for the Render Widget Host View
// of the selected tab.
IAccessible*
AccessibilityWinBrowserTest::GetRenderWidgetHostViewClientAccessible() {
HWND hwnd_render_widget_host_view =
browser()->GetSelectedTabContents()->GetRenderWidgetHostView()->
GetNativeView();
IAccessible* accessible;
HRESULT hr = AccessibleObjectFromWindow(
hwnd_render_widget_host_view, OBJID_CLIENT,
IID_IAccessible, reinterpret_cast<void**>(&accessible));
EXPECT_EQ(S_OK, hr);
EXPECT_NE(accessible, reinterpret_cast<IAccessible*>(NULL));
return accessible;
}
AccessibleChecker::AccessibleChecker(
std::wstring expected_name, int32 expected_role) :
name_(expected_name),
role_(expected_role) {
}
AccessibleChecker::AccessibleChecker(
std::wstring expected_name, std::wstring expected_role) :
name_(expected_name),
role_(expected_role.c_str()) {
}
void AccessibleChecker::AppendExpectedChild(
AccessibleChecker* expected_child) {
children_.push_back(expected_child);
}
void AccessibleChecker::CheckAccessible(IAccessible* accessible) {
CheckAccessibleName(accessible);
CheckAccessibleRole(accessible);
CheckAccessibleChildren(accessible);
}
void AccessibleChecker::CheckAccessibleName(IAccessible* accessible) {
CComBSTR name;
HRESULT hr =
accessible->get_accName(CreateI4Variant(CHILDID_SELF), &name);
if (name_.empty()) {
// If the object doesn't have name S_FALSE should be returned.
EXPECT_EQ(hr, S_FALSE);
} else {
// Test that the correct string was returned.
EXPECT_EQ(hr, S_OK);
EXPECT_EQ(CompareString(LOCALE_NEUTRAL, 0, name, SysStringLen(name),
name_.c_str(), name_.length()),
CSTR_EQUAL);
}
}
void AccessibleChecker::CheckAccessibleRole(IAccessible* accessible) {
VARIANT var_role = {0};
HRESULT hr =
accessible->get_accRole(CreateI4Variant(CHILDID_SELF), &var_role);
EXPECT_EQ(hr, S_OK);
ASSERT_TRUE(role_ == var_role);
}
void AccessibleChecker::CheckAccessibleChildren(IAccessible* parent) {
LONG child_count = 0;
HRESULT hr = parent->get_accChildCount(&child_count);
EXPECT_EQ(hr, S_OK);
ASSERT_EQ(child_count, children_.size());
std::auto_ptr<VARIANT> child_array(new VARIANT[child_count]);
LONG obtained_count = 0;
hr = AccessibleChildren(parent, 0, child_count,
child_array.get(), &obtained_count);
ASSERT_EQ(hr, S_OK);
ASSERT_EQ(child_count, obtained_count);
VARIANT* child = child_array.get();
for (AccessibleCheckerVector::iterator child_checker = children_.begin();
child_checker != children_.end();
++child_checker, ++child) {
ScopedComPtr<IAccessible> child_accessible;
child_accessible.Attach(GetAccessibleFromResultVariant(parent, child));
(*child_checker)->CheckAccessible(child_accessible);
}
}
// http://crbug.com/48079 started failing after WebKit roll 62240:62258
IN_PROC_BROWSER_TEST_F(AccessibilityWinBrowserTest,
DISABLED_TestRendererAccessibilityTree) {
// By requesting an accessible chrome will believe a screen reader has been
// detected.
ScopedComPtr<IAccessible> document_accessible(
GetRenderWidgetHostViewClientAccessible());
// The initial accessible returned should have state STATE_SYSTEM_BUSY while
// the accessibility tree is being requested from the renderer.
VARIANT var_state;
HRESULT hr = document_accessible->
get_accState(CreateI4Variant(CHILDID_SELF), &var_state);
EXPECT_EQ(hr, S_OK);
EXPECT_EQ(V_VT(&var_state), VT_I4);
EXPECT_EQ(V_I4(&var_state), STATE_SYSTEM_BUSY);
GURL tree_url(
"data:text/html,<html><head><title>Accessibility Win Test</title></head>"
"<body><input type='button' value='push' /><input type='checkbox' />"
"</body></html>");
browser()->OpenURL(tree_url, GURL(), CURRENT_TAB, PageTransition::TYPED);
ui_test_utils::WaitForNotification(
NotificationType::RENDER_VIEW_HOST_ACCESSIBILITY_TREE_UPDATED);
document_accessible = GetRenderWidgetHostViewClientAccessible();
ASSERT_NE(document_accessible.get(), reinterpret_cast<IAccessible*>(NULL));
AccessibleChecker button_checker(L"push", ROLE_SYSTEM_PUSHBUTTON);
AccessibleChecker checkbox_checker(L"", ROLE_SYSTEM_CHECKBUTTON);
AccessibleChecker grouping_checker(L"", L"div");
grouping_checker.AppendExpectedChild(&button_checker);
grouping_checker.AppendExpectedChild(&checkbox_checker);
AccessibleChecker document_checker(L"", ROLE_SYSTEM_DOCUMENT);
document_checker.AppendExpectedChild(&grouping_checker);
// Check the accessible tree of the renderer.
document_checker.CheckAccessible(document_accessible);
// Check that document accessible has a parent accessible.
ScopedComPtr<IDispatch> parent_dispatch;
hr = document_accessible->get_accParent(parent_dispatch.Receive());
EXPECT_EQ(hr, S_OK);
EXPECT_NE(parent_dispatch, reinterpret_cast<IDispatch*>(NULL));
// Navigate to another page.
GURL about_url("about:");
ui_test_utils::NavigateToURL(browser(), about_url);
// Verify that the IAccessible reference still points to a valid object and
// that it calls to its methods fail since the tree is no longer valid after
// the page navagation.
// Todo(ctguil): Currently this is giving a false positive because E_FAIL is
// returned when BrowserAccessibilityManager::RequestAccessibilityInfo fails
// since the previous render view host connection is lost. Verify that
// instances are actually marked as invalid once the browse side cache is
// checked in.
CComBSTR name;
hr = document_accessible->get_accName(CreateI4Variant(CHILDID_SELF), &name);
ASSERT_EQ(E_FAIL, hr);
}
} // namespace.
<|endoftext|> |
<commit_before>#include "builders/terrain/ExteriorGenerator.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "math/Vector2.hpp"
#include "utils/GeometryUtils.hpp"
#include <climits>
#include <map>
#include <unordered_set>
#include <unordered_map>
using namespace ClipperLib;
using namespace utymap;
using namespace utymap::builders;
using namespace utymap::mapcss;
using namespace utymap::math;
namespace {
const double Scale = 1E7;
const std::string TerrainMeshName = "terrain_exterior";
const std::string InclineKey = "incline";
const std::string InclineUpValue = "up";
const std::string InclineDownValue = "down";
double interpolate(double a, double b, double r)
{
return a * (1.0 - r) + b * r;
}
struct HashFunc
{
size_t operator()(const Vector2& v) const
{
size_t h1 = std::hash<double>()(v.x);
size_t h2 = std::hash<double>()(v.y);
return h1 ^ h2;
}
};
struct EqualsFunc
{
bool operator()(const Vector2& lhs, const Vector2& rhs) const
{
return lhs == rhs;
}
};
struct InclineType final
{
const static InclineType None;
const static InclineType Up;
const static InclineType Down;
static InclineType create(const std::string& value)
{
if (value == InclineUpValue) return Up;
if (value == InclineDownValue) return Down;
// TODO parse actual value
return None;
}
int getValue() const { return value_; }
private:
explicit InclineType(int value) : value_(value)
{
}
int value_;
};
bool operator==(const InclineType& lhs, const InclineType& rhs) { return lhs.getValue() == rhs.getValue(); }
bool operator!=(const InclineType& lhs, const InclineType& rhs) { return lhs.getValue() != rhs.getValue(); }
const InclineType InclineType::None = InclineType(0);
const InclineType InclineType::Up = InclineType(std::numeric_limits<int>::max());
const InclineType InclineType::Down = InclineType(std::numeric_limits<int>::min());
/// Stores information for building slope region.
struct SlopeSegment final
{
const Vector2 tail;
const double width;
// NOTE for debug only.
// TODO remove
std::size_t elementId;
SlopeSegment(const Vector2& tail, double width, std::size_t elementId) :
tail(tail), width(width), elementId(elementId)
{
}
};
/// Encapsulates slope region used to calculate slope ration for given point.
class SlopeRegion final
{
public:
SlopeRegion(const Vector2& start, const Vector2& end, double width, std::size_t elementId) :
elementId(elementId), start_(start), centerLine_(end - start),
geometry(utymap::utils::getOffsetLine(start, end + centerLine_.normalized() * width, width)),
lengthSquare_()
{
double distance = Vector2::distance(start, end);
lengthSquare_ = distance * distance;
}
/// Returns true if the point is inside geometry.
bool contains(const Vector2& p) const
{
return utymap::utils::isPointInPolygon(p, geometry);
}
/// Calculate scalar projection divided to length to get slope ratio in range [0, 1]
double calculateSlope(const Vector2& v) const
{
return utymap::utils::clamp((v - start_).dot(centerLine_) / lengthSquare_, 0, 1);
}
// NOTE for debug only.
// TODO remove
std::size_t elementId;
private:
const Vector2 start_;
const Vector2 centerLine_;
const std::vector<Vector2> geometry;
double lengthSquare_;
};
}
class ExteriorGenerator::ExteriorGeneratorImpl : public utymap::entities::ElementVisitor
{
/// Defines a type for storing all possible slope segments.
typedef std::unordered_map<Vector2, std::vector<SlopeSegment>, HashFunc, EqualsFunc> ExitMap;
public:
ExteriorGeneratorImpl(const BuilderContext& builderContext) :
builderContext_(builderContext), levelInfoMap_(), slopeRegionMap_(),
inclineKey_(builderContext.stringTable.getId(InclineKey)),
region_(nullptr), style_(nullptr), inclineType_(InclineType::None)
{
}
void visitNode(const utymap::entities::Node&) override
{
// TODO Some exits can be added as node?
}
void visitWay(const utymap::entities::Way& way) override
{
const auto& c1 = way.coordinates[0];
const auto& c2 = way.coordinates[way.coordinates.size() - 1];
auto v1 = Vector2(c1.longitude, c1.latitude);
auto v2 = Vector2(c2.longitude, c2.latitude);
double width = style_->getValue(StyleConsts::WidthKey,
builderContext_.boundingBox.maxPoint.latitude - builderContext_.boundingBox.minPoint.latitude,
builderContext_.boundingBox.center());
auto levelInfoPair = levelInfoMap_.find(region_->level);
if (levelInfoPair == levelInfoMap_.end()) {
levelInfoMap_.insert(std::make_pair(region_->level, utymap::utils::make_unique<ExitMap>()));
levelInfoPair = levelInfoMap_.find(region_->level);
}
if (inclineType_ == InclineType::None) {
// store as possible slope segment.
(*levelInfoPair->second)[v1].push_back(SlopeSegment(v2, width, way.id));
(*levelInfoPair->second)[v2].push_back(SlopeSegment(v1, width, way.id));
}
else {
// promote down and add directly as slope region
region_->level -= 1;
if (inclineType_ == InclineType::Up)
slopeRegionMap_[region_->level].push_back(SlopeRegion(v1, v2, width, way.id));
else
slopeRegionMap_[region_->level].push_back(SlopeRegion(v2, v1, width, way.id));
}
}
void visitArea(const utymap::entities::Area& area) override
{
// TODO area as a slope region?
}
void visitRelation(const utymap::entities::Relation& relation) override
{
for (const auto& element : relation.elements)
element->accept(*this);
}
void setElementContext(const utymap::entities::Element& element, const Style& style, const std::shared_ptr<Region>& region)
{
inclineType_ = InclineType::create(style.getString(inclineKey_));
style_ = &style;
region_ = region;
}
void build()
{
// process tunnels
for (auto curr = levelInfoMap_.begin(); curr != levelInfoMap_.end() && curr->first < 0; ++curr) {
auto next = std::next(curr, 1);
if (next == levelInfoMap_.end()) break;
if (next->second->empty()) continue;
// try to find exists on level above and create slope regions.
for (const auto& slopePair : *curr->second) {
// not an exit
if (next->second->find(slopePair.first) == next->second->end()) continue;
// an exit.
for (const auto& segment : slopePair.second)
slopeRegionMap_[curr->first].push_back(SlopeRegion(slopePair.first, segment.tail, segment.width, segment.elementId));
}
}
//// TODO process bridges
//for (auto curr = levelInfoMap_.rbegin(); curr != levelInfoMap_.rend() && curr->first > 0; ++curr) {
//}
}
double getHeight(int level, const GeoCoordinate& coordinate) const
{
const double deepHeight = 10;
auto regionPair = slopeRegionMap_.find(level);
if (regionPair != slopeRegionMap_.end()) {
Vector2 p(coordinate.longitude, coordinate.latitude);
for (const auto& region : regionPair->second) {
if (region.contains(p)) {
double slope = region.calculateSlope(p);
return interpolate(deepHeight, deepHeight * 2, slope);
}
}
}
return deepHeight;
}
private:
const BuilderContext& builderContext_;
/// Stores information about level's exits.
std::map<int, std::unique_ptr<ExitMap>> levelInfoMap_;
/// Stores slope regions.
std::unordered_map<int, std::vector<SlopeRegion>> slopeRegionMap_;
/// Mapcss cached string ids.
std::uint32_t inclineKey_;
/// Current element style.
std::shared_ptr<Region> region_;
/// Current element style.
const Style* style_;
/// Current element region incline type.
InclineType inclineType_;
};
ExteriorGenerator::ExteriorGenerator(const BuilderContext& context, const Style& style, const Path& tileRect) :
TerraGenerator(context, style, tileRect, TerrainMeshName), p_impl(utymap::utils::make_unique<ExteriorGeneratorImpl>(context))
{
}
void ExteriorGenerator::onNewRegion(const std::string& type, const utymap::entities::Element& element, const Style& style, const std::shared_ptr<Region>& region)
{
p_impl->setElementContext(element, style, region);
element.accept(*p_impl);
}
void ExteriorGenerator::generateFrom(Layers& layers)
{
p_impl->build();
for (const auto& layerPair : layers) {
for (const auto& region : layerPair.second) {
// NOTE we don't have any slope regions on surface.
if (region->level != 0) {
TerraGenerator::addGeometry(region->level, region->geometry, *region->context, [](const Path& path) {});
}
}
}
context_.meshCallback(mesh_);
}
ExteriorGenerator::~ExteriorGenerator()
{
}
void ExteriorGenerator::addGeometry(int level, utymap::math::Polygon& polygon, const RegionContext& regionContext)
{
context_.meshBuilder.addPolygon(mesh_, polygon, regionContext.geometryOptions, regionContext.appearanceOptions,
[&](const GeoCoordinate& coordinate) {
return p_impl->getHeight(level, coordinate);
});
context_.meshBuilder.writeTextureMappingInfo(mesh_, regionContext.appearanceOptions);
}
<commit_msg>core: render terrain levels based on their level value<commit_after>#include "builders/terrain/ExteriorGenerator.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "math/Vector2.hpp"
#include "utils/GeometryUtils.hpp"
#include <climits>
#include <map>
#include <unordered_set>
#include <unordered_map>
using namespace ClipperLib;
using namespace utymap;
using namespace utymap::builders;
using namespace utymap::mapcss;
using namespace utymap::math;
namespace {
const double Scale = 1E7;
const std::string TerrainMeshName = "terrain_exterior";
const std::string InclineKey = "incline";
const std::string InclineUpValue = "up";
const std::string InclineDownValue = "down";
double interpolate(double a, double b, double r)
{
return a * (1.0 - r) + b * r;
}
struct HashFunc
{
size_t operator()(const Vector2& v) const
{
size_t h1 = std::hash<double>()(v.x);
size_t h2 = std::hash<double>()(v.y);
return h1 ^ h2;
}
};
struct EqualsFunc
{
bool operator()(const Vector2& lhs, const Vector2& rhs) const
{
return lhs == rhs;
}
};
struct InclineType final
{
const static InclineType None;
const static InclineType Up;
const static InclineType Down;
static InclineType create(const std::string& value)
{
if (value == InclineUpValue) return Up;
if (value == InclineDownValue) return Down;
// TODO parse actual value
return None;
}
int getValue() const { return value_; }
private:
explicit InclineType(int value) : value_(value)
{
}
int value_;
};
bool operator==(const InclineType& lhs, const InclineType& rhs) { return lhs.getValue() == rhs.getValue(); }
bool operator!=(const InclineType& lhs, const InclineType& rhs) { return lhs.getValue() != rhs.getValue(); }
const InclineType InclineType::None = InclineType(0);
const InclineType InclineType::Up = InclineType(std::numeric_limits<int>::max());
const InclineType InclineType::Down = InclineType(std::numeric_limits<int>::min());
/// Stores information for building slope region.
struct SlopeSegment final
{
const Vector2 tail;
const double width;
// NOTE for debug only.
// TODO remove
std::size_t elementId;
SlopeSegment(const Vector2& tail, double width, std::size_t elementId) :
tail(tail), width(width), elementId(elementId)
{
}
};
/// Encapsulates slope region used to calculate slope ration for given point.
class SlopeRegion final
{
public:
SlopeRegion(const Vector2& start, const Vector2& end, double width, std::size_t elementId) :
elementId(elementId), start_(start), centerLine_(end - start),
geometry(utymap::utils::getOffsetLine(start, end + centerLine_.normalized() * width, width)),
lengthSquare_()
{
double distance = Vector2::distance(start, end);
lengthSquare_ = distance * distance;
}
/// Returns true if the point is inside geometry.
bool contains(const Vector2& p) const
{
return utymap::utils::isPointInPolygon(p, geometry);
}
/// Calculate scalar projection divided to length to get slope ratio in range [0, 1]
double calculateSlope(const Vector2& v) const
{
return utymap::utils::clamp((v - start_).dot(centerLine_) / lengthSquare_, 0, 1);
}
// NOTE for debug only.
// TODO remove
std::size_t elementId;
private:
const Vector2 start_;
const Vector2 centerLine_;
const std::vector<Vector2> geometry;
double lengthSquare_;
};
}
class ExteriorGenerator::ExteriorGeneratorImpl : public utymap::entities::ElementVisitor
{
/// Defines a type for storing all possible slope segments.
typedef std::unordered_map<Vector2, std::vector<SlopeSegment>, HashFunc, EqualsFunc> ExitMap;
public:
ExteriorGeneratorImpl(const BuilderContext& builderContext) :
builderContext_(builderContext), levelInfoMap_(), slopeRegionMap_(),
inclineKey_(builderContext.stringTable.getId(InclineKey)),
region_(nullptr), style_(nullptr), inclineType_(InclineType::None)
{
}
void visitNode(const utymap::entities::Node&) override
{
// TODO Some exits can be added as node?
}
void visitWay(const utymap::entities::Way& way) override
{
const auto& c1 = way.coordinates[0];
const auto& c2 = way.coordinates[way.coordinates.size() - 1];
auto v1 = Vector2(c1.longitude, c1.latitude);
auto v2 = Vector2(c2.longitude, c2.latitude);
double width = style_->getValue(StyleConsts::WidthKey,
builderContext_.boundingBox.maxPoint.latitude - builderContext_.boundingBox.minPoint.latitude,
builderContext_.boundingBox.center());
auto levelInfoPair = levelInfoMap_.find(region_->level);
if (levelInfoPair == levelInfoMap_.end()) {
levelInfoMap_.insert(std::make_pair(region_->level, utymap::utils::make_unique<ExitMap>()));
levelInfoPair = levelInfoMap_.find(region_->level);
}
if (inclineType_ == InclineType::None) {
// store as possible slope segment.
(*levelInfoPair->second)[v1].push_back(SlopeSegment(v2, width, way.id));
(*levelInfoPair->second)[v2].push_back(SlopeSegment(v1, width, way.id));
}
else {
// promote down and add directly as slope region
region_->level -= 1;
if (inclineType_ == InclineType::Up)
slopeRegionMap_[region_->level].push_back(SlopeRegion(v1, v2, width, way.id));
else
slopeRegionMap_[region_->level].push_back(SlopeRegion(v2, v1, width, way.id));
}
}
void visitArea(const utymap::entities::Area& area) override
{
// TODO area as a slope region?
}
void visitRelation(const utymap::entities::Relation& relation) override
{
for (const auto& element : relation.elements)
element->accept(*this);
}
void setElementContext(const utymap::entities::Element& element, const Style& style, const std::shared_ptr<Region>& region)
{
inclineType_ = InclineType::create(style.getString(inclineKey_));
style_ = &style;
region_ = region;
}
void build()
{
// process tunnels
for (auto curr = levelInfoMap_.begin(); curr != levelInfoMap_.end() && curr->first < 0; ++curr) {
auto next = std::next(curr, 1);
if (next == levelInfoMap_.end()) break;
if (next->second->empty()) continue;
// try to find exists on level above and create slope regions.
for (const auto& slopePair : *curr->second) {
// not an exit
if (next->second->find(slopePair.first) == next->second->end()) continue;
// an exit.
for (const auto& segment : slopePair.second)
slopeRegionMap_[curr->first].push_back(SlopeRegion(slopePair.first, segment.tail, segment.width, segment.elementId));
}
}
//// TODO process bridges
//for (auto curr = levelInfoMap_.rbegin(); curr != levelInfoMap_.rend() && curr->first > 0; ++curr) {
//}
}
double getHeight(int level, const GeoCoordinate& coordinate) const
{
const double deepHeight = 4;
double startHeight = level * deepHeight;
double endHeight = (level + 1) * deepHeight;
auto regionPair = slopeRegionMap_.find(level);
if (regionPair != slopeRegionMap_.end()) {
Vector2 p(coordinate.longitude, coordinate.latitude);
for (const auto& region : regionPair->second) {
if (region.contains(p)) {
double slope = region.calculateSlope(p);
return interpolate(startHeight, endHeight, slope);
}
}
}
return startHeight;
}
private:
const BuilderContext& builderContext_;
/// Stores information about level's exits.
std::map<int, std::unique_ptr<ExitMap>> levelInfoMap_;
/// Stores slope regions.
std::unordered_map<int, std::vector<SlopeRegion>> slopeRegionMap_;
/// Mapcss cached string ids.
std::uint32_t inclineKey_;
/// Current element style.
std::shared_ptr<Region> region_;
/// Current element style.
const Style* style_;
/// Current element region incline type.
InclineType inclineType_;
};
ExteriorGenerator::ExteriorGenerator(const BuilderContext& context, const Style& style, const Path& tileRect) :
TerraGenerator(context, style, tileRect, TerrainMeshName), p_impl(utymap::utils::make_unique<ExteriorGeneratorImpl>(context))
{
}
void ExteriorGenerator::onNewRegion(const std::string& type, const utymap::entities::Element& element, const Style& style, const std::shared_ptr<Region>& region)
{
p_impl->setElementContext(element, style, region);
element.accept(*p_impl);
}
void ExteriorGenerator::generateFrom(Layers& layers)
{
p_impl->build();
for (const auto& layerPair : layers) {
for (const auto& region : layerPair.second) {
// NOTE we don't have any slope regions on surface.
if (region->level != 0) {
TerraGenerator::addGeometry(region->level, region->geometry, *region->context, [](const Path& path) {});
}
}
}
context_.meshCallback(mesh_);
}
ExteriorGenerator::~ExteriorGenerator()
{
}
void ExteriorGenerator::addGeometry(int level, utymap::math::Polygon& polygon, const RegionContext& regionContext)
{
context_.meshBuilder.addPolygon(mesh_, polygon, regionContext.geometryOptions, regionContext.appearanceOptions,
[&](const GeoCoordinate& coordinate) {
return p_impl->getHeight(level, coordinate);
});
context_.meshBuilder.writeTextureMappingInfo(mesh_, regionContext.appearanceOptions);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string.h>
#ifdef NCS_CUDA
#include <cuda.h>
#include <cuda_runtime.h>
#include <ncs/sim/CUDA.h>
#endif // NCS_CUDA
namespace ncs {
namespace sim {
template<DeviceType::Type MType>
template<typename T>
bool Memory<MType>::malloc(T*& addr, size_t count) {
addr = Memory<MType>::template malloc<T>(count);
return addr != nullptr;
}
#ifdef NCS_CUDA
template<>
template<typename T>
T* Memory<DeviceType::CUDA>::malloc(size_t count) {
char* result = nullptr;
if (cudaMalloc((void**)&result, sizeof(T) * count) != cudaSuccess) {
std::cerr << "cudaMalloc failed: " <<
cudaGetErrorString(cudaGetLastError()) << std::endl;
return nullptr;
}
return (T*)result;
}
template<>
template<typename T>
bool Memory<DeviceType::CUDA>::free(T* addr) {
if (addr) {
if (cudaFree(addr) != cudaSuccess) {
std::cerr << "cudaFree failed: " <<
cudaGetErrorString(cudaGetLastError()) << std::endl;
return false;
}
}
return true;
}
template<>
template<typename T>
bool Memory<DeviceType::CUDA>::zero(T* addr, size_t count) {
if (0 == count) {
return true;
}
cudaError_t result = cudaMemsetAsync(addr,
0,
sizeof(T) * count,
CUDA::getStream());
if (cudaSuccess != result) {
std::cerr << "cudaMemsetAsync failed: " <<
cudaGetErrorString(cudaGetLastError()) << std::endl;
return false;
}
return true;
}
#endif
template<>
template<typename T>
T* Memory<DeviceType::CPU>::malloc(size_t count) {
return new T[count];
}
template<>
template<typename T>
bool Memory<DeviceType::CPU>::free(T* addr) {
if (addr) {
delete [] addr;
}
return true;
}
template<>
template<typename T>
bool Memory<DeviceType::CPU>::zero(T* addr, size_t count) {
memset(addr, 0, sizeof(T) * count);
return true;
}
template<>
template<>
template<typename T>
bool Memory<DeviceType::CPU>::To<DeviceType::CPU>::copy(const T* src,
T* dest,
size_t count) {
std::copy(src, src + count, dest);
return true;
}
#ifdef NCS_CUDA
template<>
template<>
template<typename T>
bool Memory<DeviceType::CPU>::To<DeviceType::CUDA>::copy(const T* src,
T* dest,
size_t count) {
auto result = cudaMemcpyAsync(dest,
src,
count * sizeof(T),
cudaMemcpyHostToDevice,
ncs::sim::CUDA::getStream());
if (cudaSuccess != result) {
std::cerr << "cudaMemcpyAsync(cudaMemcpyHostToDevice) failed: " <<
cudaGetErrorString(cudaGetLastError()) << std::endl;
std::cerr << "Dest: " << dest << std::endl;
std::cerr << "Source: " << src << std::endl;
std::cerr << "Size: " << count * sizeof(T) << std::endl;
std::cerr << "Device: " << CUDA::getDevice() << std::endl;
return false;
}
return true;
}
template<>
template<>
template<typename T>
bool Memory<DeviceType::CUDA>::To<DeviceType::CPU>::copy(const T* src,
T* dest,
size_t count) {
auto result = cudaMemcpyAsync(dest,
src,
count * sizeof(T),
cudaMemcpyDeviceToHost,
ncs::sim::CUDA::getStream());
if (cudaSuccess != result) {
std::cerr << "cudaMemcpyAsync(cudaMemcpyDeviceToHost) failed: " <<
cudaGetErrorString(cudaGetLastError()) << std::endl;
std::cerr << "Dest: " << dest << std::endl;
std::cerr << "Source: " << src << std::endl;
std::cerr << "Size: " << count * sizeof(T) << std::endl;
return false;
}
return true;
}
template<>
template<>
template<typename T>
bool Memory<DeviceType::CUDA>::To<DeviceType::CUDA>::copy(const T* src,
T* dest,
size_t count) {
auto result = cudaMemcpyAsync(dest,
src,
count * sizeof(T),
cudaMemcpyDeviceToDevice,
ncs::sim::CUDA::getStream());
if (cudaSuccess != result) {
std::cerr << "cudaMemcpyAsync(cudaMemcpyDeviceToDevice) failed: " <<
cudaGetErrorString(cudaGetLastError()) << std::endl;
return false;
}
return true;
}
#endif // NCS_CUDA
namespace mem {
template<DeviceType::Type DestType, DeviceType::Type SourceType, typename T>
bool copy(T* dst, const T* src, size_t count) {
return Memory<SourceType>::template
To<DestType>::copy(src, dst, count);
}
template<DeviceType::Type DestType, typename T>
bool clone(T*& dst, const std::vector<T>& src) {
if (!Memory<DestType>::malloc(dst, src.size())) {
std::cerr << "Failed to allocate memory for clone." << std::endl;
std::cerr << "Size: " << src.size() << std::endl;
return false;
}
if (!copy<DestType, DeviceType::CPU>(dst, src.data(), src.size())) {
std::cerr << "Failed to copy for clone." << std::endl;
Memory<DestType>::free(dst);
return false;
}
return true;
}
} // namespace mem
} // namespace sim
} // namespace ncs
<commit_msg>Memory fix for zero size allocations.<commit_after>#include <iostream>
#include <string.h>
#ifdef NCS_CUDA
#include <cuda.h>
#include <cuda_runtime.h>
#include <ncs/sim/CUDA.h>
#endif // NCS_CUDA
namespace ncs {
namespace sim {
template<DeviceType::Type MType>
template<typename T>
bool Memory<MType>::malloc(T*& addr, size_t count) {
if (0 == count) {
addr = nullptr;
return true;
}
addr = Memory<MType>::template malloc<T>(count);
return addr != nullptr;
}
#ifdef NCS_CUDA
template<>
template<typename T>
T* Memory<DeviceType::CUDA>::malloc(size_t count) {
if (0 == count) {
return nullptr;
}
char* result = nullptr;
if (cudaMalloc((void**)&result, sizeof(T) * count) != cudaSuccess) {
std::cerr << "cudaMalloc failed: " <<
cudaGetErrorString(cudaGetLastError()) << std::endl;
return nullptr;
}
return (T*)result;
}
template<>
template<typename T>
bool Memory<DeviceType::CUDA>::free(T* addr) {
if (addr) {
if (cudaFree(addr) != cudaSuccess) {
std::cerr << "cudaFree failed: " <<
cudaGetErrorString(cudaGetLastError()) << std::endl;
return false;
}
}
return true;
}
template<>
template<typename T>
bool Memory<DeviceType::CUDA>::zero(T* addr, size_t count) {
if (0 == count) {
return true;
}
cudaError_t result = cudaMemsetAsync(addr,
0,
sizeof(T) * count,
CUDA::getStream());
if (cudaSuccess != result) {
std::cerr << "cudaMemsetAsync failed: " <<
cudaGetErrorString(cudaGetLastError()) << std::endl;
return false;
}
return true;
}
#endif
template<>
template<typename T>
T* Memory<DeviceType::CPU>::malloc(size_t count) {
if (0 == count) {
return nullptr;
}
return new T[count];
}
template<>
template<typename T>
bool Memory<DeviceType::CPU>::free(T* addr) {
if (addr) {
delete [] addr;
}
return true;
}
template<>
template<typename T>
bool Memory<DeviceType::CPU>::zero(T* addr, size_t count) {
memset(addr, 0, sizeof(T) * count);
return true;
}
template<>
template<>
template<typename T>
bool Memory<DeviceType::CPU>::To<DeviceType::CPU>::copy(const T* src,
T* dest,
size_t count) {
std::copy(src, src + count, dest);
return true;
}
#ifdef NCS_CUDA
template<>
template<>
template<typename T>
bool Memory<DeviceType::CPU>::To<DeviceType::CUDA>::copy(const T* src,
T* dest,
size_t count) {
auto result = cudaMemcpyAsync(dest,
src,
count * sizeof(T),
cudaMemcpyHostToDevice,
ncs::sim::CUDA::getStream());
if (cudaSuccess != result) {
std::cerr << "cudaMemcpyAsync(cudaMemcpyHostToDevice) failed: " <<
cudaGetErrorString(cudaGetLastError()) << std::endl;
std::cerr << "Dest: " << dest << std::endl;
std::cerr << "Source: " << src << std::endl;
std::cerr << "Size: " << count * sizeof(T) << std::endl;
std::cerr << "Device: " << CUDA::getDevice() << std::endl;
return false;
}
return true;
}
template<>
template<>
template<typename T>
bool Memory<DeviceType::CUDA>::To<DeviceType::CPU>::copy(const T* src,
T* dest,
size_t count) {
auto result = cudaMemcpyAsync(dest,
src,
count * sizeof(T),
cudaMemcpyDeviceToHost,
ncs::sim::CUDA::getStream());
if (cudaSuccess != result) {
std::cerr << "cudaMemcpyAsync(cudaMemcpyDeviceToHost) failed: " <<
cudaGetErrorString(cudaGetLastError()) << std::endl;
std::cerr << "Dest: " << dest << std::endl;
std::cerr << "Source: " << src << std::endl;
std::cerr << "Size: " << count * sizeof(T) << std::endl;
return false;
}
return true;
}
template<>
template<>
template<typename T>
bool Memory<DeviceType::CUDA>::To<DeviceType::CUDA>::copy(const T* src,
T* dest,
size_t count) {
auto result = cudaMemcpyAsync(dest,
src,
count * sizeof(T),
cudaMemcpyDeviceToDevice,
ncs::sim::CUDA::getStream());
if (cudaSuccess != result) {
std::cerr << "cudaMemcpyAsync(cudaMemcpyDeviceToDevice) failed: " <<
cudaGetErrorString(cudaGetLastError()) << std::endl;
return false;
}
return true;
}
#endif // NCS_CUDA
namespace mem {
template<DeviceType::Type DestType, DeviceType::Type SourceType, typename T>
bool copy(T* dst, const T* src, size_t count) {
return Memory<SourceType>::template
To<DestType>::copy(src, dst, count);
}
template<DeviceType::Type DestType, typename T>
bool clone(T*& dst, const std::vector<T>& src) {
if (!Memory<DestType>::malloc(dst, src.size())) {
std::cerr << "Failed to allocate memory for clone." << std::endl;
std::cerr << "Size: " << src.size() << std::endl;
return false;
}
if (!copy<DestType, DeviceType::CPU>(dst, src.data(), src.size())) {
std::cerr << "Failed to copy for clone." << std::endl;
Memory<DestType>::free(dst);
return false;
}
return true;
}
} // namespace mem
} // namespace sim
} // namespace ncs
<|endoftext|> |
<commit_before><commit_msg>[cros] Update OOBE network error message.<commit_after><|endoftext|> |
<commit_before><commit_msg>Fix a memory leak in extension install.<commit_after><|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
using namespace std;
namespace cv
{
BOWTrainer::BOWTrainer()
{}
BOWTrainer::~BOWTrainer()
{}
void BOWTrainer::add( const Mat& _descriptors )
{
CV_Assert( !_descriptors.empty() );
if( !descriptors.empty() )
{
CV_Assert( descriptors[0].cols == _descriptors.cols );
CV_Assert( descriptors[0].type() == _descriptors.type() );
size += _descriptors.rows;
}
else
{
size = _descriptors.rows;
}
descriptors.push_back(_descriptors);
}
const vector<Mat>& BOWTrainer::getDescriptors() const
{
return descriptors;
}
int BOWTrainer::descripotorsCount() const
{
return descriptors.empty() ? 0 : size;
}
void BOWTrainer::clear()
{
descriptors.clear();
}
BOWKMeansTrainer::BOWKMeansTrainer( int _clusterCount, const TermCriteria& _termcrit,
int _attempts, int _flags ) :
clusterCount(_clusterCount), termcrit(_termcrit), attempts(_attempts), flags(_flags)
{}
Mat BOWKMeansTrainer::cluster() const
{
CV_Assert( !descriptors.empty() );
int descCount = 0;
for( size_t i = 0; i < descriptors.size(); i++ )
descCount += descriptors[i].rows;
Mat mergedDescriptors( descCount, descriptors[0].cols, descriptors[0].type() );
for( size_t i = 0, start = 0; i < descriptors.size(); i++ )
{
Mat submut = mergedDescriptors.rowRange((int)start, (int)(start + descriptors[i].rows));
descriptors[i].copyTo(submut);
start += descriptors[i].rows;
}
return cluster( mergedDescriptors );
}
BOWKMeansTrainer::~BOWKMeansTrainer()
{}
Mat BOWKMeansTrainer::cluster( const Mat& _descriptors ) const
{
Mat labels, vocabulary;
kmeans( _descriptors, clusterCount, labels, termcrit, attempts, flags, vocabulary );
return vocabulary;
}
BOWImgDescriptorExtractor::BOWImgDescriptorExtractor( const Ptr<DescriptorExtractor>& _dextractor,
const Ptr<DescriptorMatcher>& _dmatcher ) :
dextractor(_dextractor), dmatcher(_dmatcher)
{}
BOWImgDescriptorExtractor::~BOWImgDescriptorExtractor()
{}
void BOWImgDescriptorExtractor::setVocabulary( const Mat& _vocabulary )
{
dmatcher->clear();
vocabulary = _vocabulary;
dmatcher->add( vector<Mat>(1, vocabulary) );
}
const Mat& BOWImgDescriptorExtractor::getVocabulary() const
{
return vocabulary;
}
void BOWImgDescriptorExtractor::compute( const Mat& image, vector<KeyPoint>& keypoints, Mat& imgDescriptor,
vector<vector<int> >* pointIdxsOfClusters, Mat* _descriptors )
{
imgDescriptor.release();
if( keypoints.empty() )
return;
int clusterCount = descriptorSize(); // = vocabulary.rows
// Compute descriptors for the image.
Mat descriptors = _descriptors ? *_descriptors : Mat();
dextractor->compute( image, keypoints, descriptors );
// Match keypoint descriptors to cluster center (to vocabulary)
vector<DMatch> matches;
dmatcher->match( descriptors, matches );
// Compute image descriptor
if( pointIdxsOfClusters )
{
pointIdxsOfClusters->clear();
pointIdxsOfClusters->resize(clusterCount);
}
imgDescriptor = Mat( 1, clusterCount, descriptorType(), Scalar::all(0.0) );
float *dptr = (float*)imgDescriptor.data;
for( size_t i = 0; i < matches.size(); i++ )
{
int queryIdx = matches[i].queryIdx;
int trainIdx = matches[i].trainIdx; // cluster index
CV_Assert( queryIdx == (int)i );
dptr[trainIdx] = dptr[trainIdx] + 1.f;
if( pointIdxsOfClusters )
(*pointIdxsOfClusters)[trainIdx].push_back( queryIdx );
}
// Normalize image descriptor.
imgDescriptor /= descriptors.rows;
}
int BOWImgDescriptorExtractor::descriptorSize() const
{
return vocabulary.empty() ? 0 : vocabulary.rows;
}
int BOWImgDescriptorExtractor::descriptorType() const
{
return CV_32FC1;
}
}
<commit_msg>Fixed bug 1873 : return image keypoint descriptors + fix on line 152 pure declaration<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
using namespace std;
namespace cv
{
BOWTrainer::BOWTrainer()
{}
BOWTrainer::~BOWTrainer()
{}
void BOWTrainer::add( const Mat& _descriptors )
{
CV_Assert( !_descriptors.empty() );
if( !descriptors.empty() )
{
CV_Assert( descriptors[0].cols == _descriptors.cols );
CV_Assert( descriptors[0].type() == _descriptors.type() );
size += _descriptors.rows;
}
else
{
size = _descriptors.rows;
}
descriptors.push_back(_descriptors);
}
const vector<Mat>& BOWTrainer::getDescriptors() const
{
return descriptors;
}
int BOWTrainer::descripotorsCount() const
{
return descriptors.empty() ? 0 : size;
}
void BOWTrainer::clear()
{
descriptors.clear();
}
BOWKMeansTrainer::BOWKMeansTrainer( int _clusterCount, const TermCriteria& _termcrit,
int _attempts, int _flags ) :
clusterCount(_clusterCount), termcrit(_termcrit), attempts(_attempts), flags(_flags)
{}
Mat BOWKMeansTrainer::cluster() const
{
CV_Assert( !descriptors.empty() );
int descCount = 0;
for( size_t i = 0; i < descriptors.size(); i++ )
descCount += descriptors[i].rows;
Mat mergedDescriptors( descCount, descriptors[0].cols, descriptors[0].type() );
for( size_t i = 0, start = 0; i < descriptors.size(); i++ )
{
Mat submut = mergedDescriptors.rowRange((int)start, (int)(start + descriptors[i].rows));
descriptors[i].copyTo(submut);
start += descriptors[i].rows;
}
return cluster( mergedDescriptors );
}
BOWKMeansTrainer::~BOWKMeansTrainer()
{}
Mat BOWKMeansTrainer::cluster( const Mat& _descriptors ) const
{
Mat labels, vocabulary;
kmeans( _descriptors, clusterCount, labels, termcrit, attempts, flags, vocabulary );
return vocabulary;
}
BOWImgDescriptorExtractor::BOWImgDescriptorExtractor( const Ptr<DescriptorExtractor>& _dextractor,
const Ptr<DescriptorMatcher>& _dmatcher ) :
dextractor(_dextractor), dmatcher(_dmatcher)
{}
BOWImgDescriptorExtractor::~BOWImgDescriptorExtractor()
{}
void BOWImgDescriptorExtractor::setVocabulary( const Mat& _vocabulary )
{
dmatcher->clear();
vocabulary = _vocabulary;
dmatcher->add( vector<Mat>(1, vocabulary) );
}
const Mat& BOWImgDescriptorExtractor::getVocabulary() const
{
return vocabulary;
}
void BOWImgDescriptorExtractor::compute( const Mat& image, vector<KeyPoint>& keypoints, Mat& imgDescriptor,
vector<vector<int> >* pointIdxsOfClusters, Mat* _descriptors )
{
imgDescriptor.release();
if( keypoints.empty() )
return;
int clusterCount = descriptorSize(); // = vocabulary.rows
// Compute descriptors for the image.
Mat descriptors;
dextractor->compute( image, keypoints, descriptors );
// Match keypoint descriptors to cluster center (to vocabulary)
vector<DMatch> matches;
dmatcher->match( descriptors, matches );
// Compute image descriptor
if( pointIdxsOfClusters )
{
pointIdxsOfClusters->clear();
pointIdxsOfClusters->resize(clusterCount);
}
imgDescriptor = Mat( 1, clusterCount, descriptorType(), Scalar::all(0.0) );
float *dptr = (float*)imgDescriptor.data;
for( size_t i = 0; i < matches.size(); i++ )
{
int queryIdx = matches[i].queryIdx;
int trainIdx = matches[i].trainIdx; // cluster index
CV_Assert( queryIdx == (int)i );
dptr[trainIdx] = dptr[trainIdx] + 1.f;
if( pointIdxsOfClusters )
(*pointIdxsOfClusters)[trainIdx].push_back( queryIdx );
}
// Normalize image descriptor.
imgDescriptor /= descriptors.rows;
// Add the descriptors of image keypoints
if (_descriptors) {
*_descriptors = descriptors.clone();
}
}
int BOWImgDescriptorExtractor::descriptorSize() const
{
return vocabulary.empty() ? 0 : vocabulary.rows;
}
int BOWImgDescriptorExtractor::descriptorType() const
{
return CV_32FC1;
}
}
<|endoftext|> |
<commit_before>#ifndef FUNCTIONS_HPP
#define FUNCTIONS_HPP
#include <algorithm>
#include <iterator>
namespace cutehmi {
template <class INPUT_IT, class SIZE, class OUTPUT_IT>
OUTPUT_IT copy_n(INPUT_IT first, SIZE count, OUTPUT_IT result);
template <class INPUT_IT1, class INPUT_IT2>
bool equal(INPUT_IT1 first1, INPUT_IT1 last1, INPUT_IT2 first2);
template <class INPUT_IT, class SIZE, class OUTPUT_IT>
OUTPUT_IT copy_n(INPUT_IT first, SIZE count, OUTPUT_IT result)
{
// Avoid MSVC C4996 warning, when using std::copy_n with raw pointers.
#ifdef _MSC_VER
return ::std::copy_n(first, count, ::stdext::checked_array_iterator<OUTPUT_IT>(result, count)).base();
#else
return ::std::copy_n(first, count, result);
#endif
}
template <class INPUT_IT1, class INPUT_IT2>
bool equal(INPUT_IT1 first1, INPUT_IT1 last1, INPUT_IT2 first2)
{
// Avoid MSVC C4996 warning, when using std::copy_n with raw pointers.
#ifdef _MSC_VER
return ::std::equal(first1, last1, ::stdext::make_unchecked_array_iterator(first2));
#else
return ::std::equal(first1, last1, first2);
#endif
}
}
#endif // FUNCTIONS_HPP
<commit_msg>Update include guards.<commit_after>#ifndef H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_WRAPPERS_HPP
#define H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_WRAPPERS_HPP
#include <algorithm>
#include <iterator>
namespace cutehmi {
template <class INPUT_IT, class SIZE, class OUTPUT_IT>
OUTPUT_IT copy_n(INPUT_IT first, SIZE count, OUTPUT_IT result);
template <class INPUT_IT1, class INPUT_IT2>
bool equal(INPUT_IT1 first1, INPUT_IT1 last1, INPUT_IT2 first2);
template <class INPUT_IT, class SIZE, class OUTPUT_IT>
OUTPUT_IT copy_n(INPUT_IT first, SIZE count, OUTPUT_IT result)
{
// Avoid MSVC C4996 warning, when using std::copy_n with raw pointers.
#ifdef _MSC_VER
return ::std::copy_n(first, count, ::stdext::checked_array_iterator<OUTPUT_IT>(result, count)).base();
#else
return ::std::copy_n(first, count, result);
#endif
}
template <class INPUT_IT1, class INPUT_IT2>
bool equal(INPUT_IT1 first1, INPUT_IT1 last1, INPUT_IT2 first2)
{
// Avoid MSVC C4996 warning, when using std::copy_n with raw pointers.
#ifdef _MSC_VER
return ::std::equal(first1, last1, ::stdext::make_unchecked_array_iterator(first2));
#else
return ::std::equal(first1, last1, first2);
#endif
}
}
#endif
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Vulkan test case base classes
*//*--------------------------------------------------------------------*/
#include "vktTestCase.hpp"
#include "vkRef.hpp"
#include "vkRefUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkDeviceUtil.hpp"
#include "vkMemUtil.hpp"
#include "vkPlatform.hpp"
#include "vkDebugReportUtil.hpp"
#include "tcuCommandLine.hpp"
#include "deMemory.h"
namespace vkt
{
// Default device utilities
using std::vector;
using std::string;
using namespace vk;
vector<string> getValidationLayers (const vector<VkLayerProperties>& supportedLayers)
{
static const char* s_magicLayer = "VK_LAYER_LUNARG_standard_validation";
static const char* s_defaultLayers[] =
{
"VK_LAYER_GOOGLE_threading",
"VK_LAYER_LUNARG_parameter_validation",
"VK_LAYER_LUNARG_device_limits",
"VK_LAYER_LUNARG_object_tracker",
"VK_LAYER_LUNARG_image",
"VK_LAYER_LUNARG_core_validation",
"VK_LAYER_LUNARG_swapchain",
"VK_LAYER_GOOGLE_unique_objects"
};
vector<string> enabledLayers;
if (isLayerSupported(supportedLayers, RequiredLayer(s_magicLayer)))
enabledLayers.push_back(s_magicLayer);
else
{
for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_defaultLayers); ++ndx)
{
if (isLayerSupported(supportedLayers, RequiredLayer(s_defaultLayers[ndx])))
enabledLayers.push_back(s_defaultLayers[ndx]);
}
}
return enabledLayers;
}
vector<string> getValidationLayers (const PlatformInterface& vkp)
{
return getValidationLayers(enumerateInstanceLayerProperties(vkp));
}
vector<string> getValidationLayers (const InstanceInterface& vki, VkPhysicalDevice physicalDevice)
{
return getValidationLayers(enumerateDeviceLayerProperties(vki, physicalDevice));
}
Move<VkInstance> createInstance (const PlatformInterface& vkp, const tcu::CommandLine& cmdLine)
{
const bool isValidationEnabled = cmdLine.isValidationEnabled();
vector<string> enabledExtensions;
vector<string> enabledLayers;
if (isValidationEnabled)
{
if (isDebugReportSupported(vkp))
enabledExtensions.push_back("VK_EXT_debug_report");
else
TCU_THROW(NotSupportedError, "VK_EXT_debug_report is not supported");
enabledLayers = getValidationLayers(vkp);
if (enabledLayers.empty())
TCU_THROW(NotSupportedError, "No validation layers found");
}
return createDefaultInstance(vkp, enabledLayers, enabledExtensions);
}
static deUint32 findQueueFamilyIndexWithCaps (const InstanceInterface& vkInstance, VkPhysicalDevice physicalDevice, VkQueueFlags requiredCaps)
{
const vector<VkQueueFamilyProperties> queueProps = getPhysicalDeviceQueueFamilyProperties(vkInstance, physicalDevice);
for (size_t queueNdx = 0; queueNdx < queueProps.size(); queueNdx++)
{
if ((queueProps[queueNdx].queueFlags & requiredCaps) == requiredCaps)
return (deUint32)queueNdx;
}
TCU_THROW(NotSupportedError, "No matching queue found");
}
Move<VkDevice> createDefaultDevice (const InstanceInterface& vki,
VkPhysicalDevice physicalDevice,
deUint32 queueIndex,
const VkPhysicalDeviceFeatures& enabledFeatures,
const vector<string>& enabledExtensions,
const tcu::CommandLine& cmdLine)
{
VkDeviceQueueCreateInfo queueInfo;
VkDeviceCreateInfo deviceInfo;
vector<string> enabledLayers;
vector<const char*> layerPtrs;
vector<const char*> extensionPtrs;
const float queuePriority = 1.0f;
deMemset(&queueInfo, 0, sizeof(queueInfo));
deMemset(&deviceInfo, 0, sizeof(deviceInfo));
if (cmdLine.isValidationEnabled())
{
enabledLayers = getValidationLayers(vki, physicalDevice);
if (enabledLayers.empty())
TCU_THROW(NotSupportedError, "No validation layers found");
}
layerPtrs.resize(enabledLayers.size());
for (size_t ndx = 0; ndx < enabledLayers.size(); ++ndx)
layerPtrs[ndx] = enabledLayers[ndx].c_str();
extensionPtrs.resize(enabledExtensions.size());
for (size_t ndx = 0; ndx < enabledExtensions.size(); ++ndx)
extensionPtrs[ndx] = enabledExtensions[ndx].c_str();
queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueInfo.pNext = DE_NULL;
queueInfo.flags = (VkDeviceQueueCreateFlags)0u;
queueInfo.queueFamilyIndex = queueIndex;
queueInfo.queueCount = 1u;
queueInfo.pQueuePriorities = &queuePriority;
deviceInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceInfo.pNext = DE_NULL;
deviceInfo.queueCreateInfoCount = 1u;
deviceInfo.pQueueCreateInfos = &queueInfo;
deviceInfo.enabledExtensionCount = (deUint32)extensionPtrs.size();
deviceInfo.ppEnabledExtensionNames = (extensionPtrs.empty() ? DE_NULL : &extensionPtrs[0]);
deviceInfo.enabledLayerCount = (deUint32)layerPtrs.size();
deviceInfo.ppEnabledLayerNames = (layerPtrs.empty() ? DE_NULL : &layerPtrs[0]);
deviceInfo.pEnabledFeatures = &enabledFeatures;
return createDevice(vki, physicalDevice, &deviceInfo);
};
class DefaultDevice
{
public:
DefaultDevice (const PlatformInterface& vkPlatform, const tcu::CommandLine& cmdLine);
~DefaultDevice (void);
VkInstance getInstance (void) const { return *m_instance; }
const InstanceInterface& getInstanceInterface (void) const { return m_instanceInterface; }
VkPhysicalDevice getPhysicalDevice (void) const { return m_physicalDevice; }
const VkPhysicalDeviceFeatures& getDeviceFeatures (void) const { return m_deviceFeatures; }
VkDevice getDevice (void) const { return *m_device; }
const DeviceInterface& getDeviceInterface (void) const { return m_deviceInterface; }
const VkPhysicalDeviceProperties& getDeviceProperties (void) const { return m_deviceProperties; }
const vector<string>& getDeviceExtensions (void) const { return m_deviceExtensions; }
deUint32 getUniversalQueueFamilyIndex (void) const { return m_universalQueueFamilyIndex; }
VkQueue getUniversalQueue (void) const;
private:
static VkPhysicalDeviceFeatures filterDefaultDeviceFeatures (const VkPhysicalDeviceFeatures& deviceFeatures);
static vector<string> filterDefaultDeviceExtensions (const vector<VkExtensionProperties>& deviceExtensions);
const Unique<VkInstance> m_instance;
const InstanceDriver m_instanceInterface;
const VkPhysicalDevice m_physicalDevice;
const deUint32 m_universalQueueFamilyIndex;
const VkPhysicalDeviceFeatures m_deviceFeatures;
const VkPhysicalDeviceProperties m_deviceProperties;
const vector<string> m_deviceExtensions;
const Unique<VkDevice> m_device;
const DeviceDriver m_deviceInterface;
};
DefaultDevice::DefaultDevice (const PlatformInterface& vkPlatform, const tcu::CommandLine& cmdLine)
: m_instance (createInstance(vkPlatform, cmdLine))
, m_instanceInterface (vkPlatform, *m_instance)
, m_physicalDevice (chooseDevice(m_instanceInterface, *m_instance, cmdLine))
, m_universalQueueFamilyIndex (findQueueFamilyIndexWithCaps(m_instanceInterface, m_physicalDevice, VK_QUEUE_GRAPHICS_BIT|VK_QUEUE_COMPUTE_BIT))
, m_deviceFeatures (filterDefaultDeviceFeatures(getPhysicalDeviceFeatures(m_instanceInterface, m_physicalDevice)))
, m_deviceProperties (getPhysicalDeviceProperties(m_instanceInterface, m_physicalDevice))
, m_deviceExtensions (filterDefaultDeviceExtensions(enumerateDeviceExtensionProperties(m_instanceInterface, m_physicalDevice, DE_NULL)))
, m_device (createDefaultDevice(m_instanceInterface, m_physicalDevice, m_universalQueueFamilyIndex, m_deviceFeatures, m_deviceExtensions, cmdLine))
, m_deviceInterface (m_instanceInterface, *m_device)
{
}
DefaultDevice::~DefaultDevice (void)
{
}
VkQueue DefaultDevice::getUniversalQueue (void) const
{
VkQueue queue = 0;
m_deviceInterface.getDeviceQueue(*m_device, m_universalQueueFamilyIndex, 0, &queue);
return queue;
}
VkPhysicalDeviceFeatures DefaultDevice::filterDefaultDeviceFeatures (const VkPhysicalDeviceFeatures& deviceFeatures)
{
VkPhysicalDeviceFeatures enabledDeviceFeatures = deviceFeatures;
// Disable robustness by default, as it has an impact on performance on some HW.
enabledDeviceFeatures.robustBufferAccess = false;
return enabledDeviceFeatures;
}
vector<string> DefaultDevice::filterDefaultDeviceExtensions (const vector<VkExtensionProperties>& deviceExtensions)
{
vector<string> enabledExtensions;
// The only extension we enable always (when supported) is
// VK_KHR_sampler_mirror_clamp_to_edge that is defined in
// the core spec and supported widely.
const char* const mirrorClampToEdgeExt = "VK_KHR_sampler_mirror_clamp_to_edge";
if (vk::isExtensionSupported(deviceExtensions, vk::RequiredExtension(mirrorClampToEdgeExt)))
enabledExtensions.push_back(mirrorClampToEdgeExt);
return enabledExtensions;
}
// Allocator utilities
vk::Allocator* createAllocator (DefaultDevice* device)
{
const VkPhysicalDeviceMemoryProperties memoryProperties = vk::getPhysicalDeviceMemoryProperties(device->getInstanceInterface(), device->getPhysicalDevice());
// \todo [2015-07-24 jarkko] support allocator selection/configuration from command line (or compile time)
return new SimpleAllocator(device->getDeviceInterface(), device->getDevice(), memoryProperties);
}
// Context
Context::Context (tcu::TestContext& testCtx,
const vk::PlatformInterface& platformInterface,
vk::ProgramCollection<vk::ProgramBinary>& progCollection)
: m_testCtx (testCtx)
, m_platformInterface (platformInterface)
, m_progCollection (progCollection)
, m_device (new DefaultDevice(m_platformInterface, testCtx.getCommandLine()))
, m_allocator (createAllocator(m_device.get()))
{
}
Context::~Context (void)
{
}
vk::VkInstance Context::getInstance (void) const { return m_device->getInstance(); }
const vk::InstanceInterface& Context::getInstanceInterface (void) const { return m_device->getInstanceInterface(); }
vk::VkPhysicalDevice Context::getPhysicalDevice (void) const { return m_device->getPhysicalDevice(); }
const vk::VkPhysicalDeviceFeatures& Context::getDeviceFeatures (void) const { return m_device->getDeviceFeatures(); }
const vk::VkPhysicalDeviceProperties& Context::getDeviceProperties (void) const { return m_device->getDeviceProperties(); }
const vector<string>& Context::getDeviceExtensions (void) const { return m_device->getDeviceExtensions(); }
vk::VkDevice Context::getDevice (void) const { return m_device->getDevice(); }
const vk::DeviceInterface& Context::getDeviceInterface (void) const { return m_device->getDeviceInterface(); }
deUint32 Context::getUniversalQueueFamilyIndex (void) const { return m_device->getUniversalQueueFamilyIndex(); }
vk::VkQueue Context::getUniversalQueue (void) const { return m_device->getUniversalQueue(); }
vk::Allocator& Context::getDefaultAllocator (void) const { return *m_allocator; }
// TestCase
void TestCase::initPrograms (SourceCollections&) const
{
}
} // vkt
<commit_msg>Use all KHR and EXT extensions by default<commit_after>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Vulkan test case base classes
*//*--------------------------------------------------------------------*/
#include "vktTestCase.hpp"
#include "vkRef.hpp"
#include "vkRefUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkDeviceUtil.hpp"
#include "vkMemUtil.hpp"
#include "vkPlatform.hpp"
#include "vkDebugReportUtil.hpp"
#include "tcuCommandLine.hpp"
#include "deMemory.h"
namespace vkt
{
// Default device utilities
using std::vector;
using std::string;
using namespace vk;
vector<string> getValidationLayers (const vector<VkLayerProperties>& supportedLayers)
{
static const char* s_magicLayer = "VK_LAYER_LUNARG_standard_validation";
static const char* s_defaultLayers[] =
{
"VK_LAYER_GOOGLE_threading",
"VK_LAYER_LUNARG_parameter_validation",
"VK_LAYER_LUNARG_device_limits",
"VK_LAYER_LUNARG_object_tracker",
"VK_LAYER_LUNARG_image",
"VK_LAYER_LUNARG_core_validation",
"VK_LAYER_LUNARG_swapchain",
"VK_LAYER_GOOGLE_unique_objects"
};
vector<string> enabledLayers;
if (isLayerSupported(supportedLayers, RequiredLayer(s_magicLayer)))
enabledLayers.push_back(s_magicLayer);
else
{
for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_defaultLayers); ++ndx)
{
if (isLayerSupported(supportedLayers, RequiredLayer(s_defaultLayers[ndx])))
enabledLayers.push_back(s_defaultLayers[ndx]);
}
}
return enabledLayers;
}
vector<string> getValidationLayers (const PlatformInterface& vkp)
{
return getValidationLayers(enumerateInstanceLayerProperties(vkp));
}
vector<string> getValidationLayers (const InstanceInterface& vki, VkPhysicalDevice physicalDevice)
{
return getValidationLayers(enumerateDeviceLayerProperties(vki, physicalDevice));
}
vector<string> filterExtensions(const vector<VkExtensionProperties>& deviceExtensions)
{
vector<string> enabledExtensions;
const char* extensionGroups[] =
{
"VK_KHR_",
"VK_EXT_"
};
for (size_t deviceExtNdx = 0; deviceExtNdx < deviceExtensions.size(); deviceExtNdx++)
{
for (int extGroupNdx = 0; extGroupNdx < DE_LENGTH_OF_ARRAY(extensionGroups); extGroupNdx++)
{
if (deStringBeginsWith(deviceExtensions[deviceExtNdx].extensionName, extensionGroups[extGroupNdx]))
enabledExtensions.push_back(deviceExtensions[deviceExtNdx].extensionName);
}
}
return enabledExtensions;
}
Move<VkInstance> createInstance (const PlatformInterface& vkp, const tcu::CommandLine& cmdLine)
{
const bool isValidationEnabled = cmdLine.isValidationEnabled();
vector<string> enabledLayers;
const vector<VkExtensionProperties> extensionProperties = enumerateInstanceExtensionProperties(vkp, DE_NULL);
const vector<string> enabledExtensions = filterExtensions(extensionProperties);
if (isValidationEnabled)
{
if (!isDebugReportSupported(vkp))
TCU_THROW(NotSupportedError, "VK_EXT_debug_report is not supported");
enabledLayers = getValidationLayers(vkp);
if (enabledLayers.empty())
TCU_THROW(NotSupportedError, "No validation layers found");
}
return createDefaultInstance(vkp, enabledLayers, enabledExtensions);
}
static deUint32 findQueueFamilyIndexWithCaps (const InstanceInterface& vkInstance, VkPhysicalDevice physicalDevice, VkQueueFlags requiredCaps)
{
const vector<VkQueueFamilyProperties> queueProps = getPhysicalDeviceQueueFamilyProperties(vkInstance, physicalDevice);
for (size_t queueNdx = 0; queueNdx < queueProps.size(); queueNdx++)
{
if ((queueProps[queueNdx].queueFlags & requiredCaps) == requiredCaps)
return (deUint32)queueNdx;
}
TCU_THROW(NotSupportedError, "No matching queue found");
}
Move<VkDevice> createDefaultDevice (const InstanceInterface& vki,
VkPhysicalDevice physicalDevice,
deUint32 queueIndex,
const VkPhysicalDeviceFeatures& enabledFeatures,
const vector<string>& enabledExtensions,
const tcu::CommandLine& cmdLine)
{
VkDeviceQueueCreateInfo queueInfo;
VkDeviceCreateInfo deviceInfo;
vector<string> enabledLayers;
vector<const char*> layerPtrs;
vector<const char*> extensionPtrs;
const float queuePriority = 1.0f;
deMemset(&queueInfo, 0, sizeof(queueInfo));
deMemset(&deviceInfo, 0, sizeof(deviceInfo));
if (cmdLine.isValidationEnabled())
{
enabledLayers = getValidationLayers(vki, physicalDevice);
if (enabledLayers.empty())
TCU_THROW(NotSupportedError, "No validation layers found");
}
layerPtrs.resize(enabledLayers.size());
for (size_t ndx = 0; ndx < enabledLayers.size(); ++ndx)
layerPtrs[ndx] = enabledLayers[ndx].c_str();
extensionPtrs.resize(enabledExtensions.size());
for (size_t ndx = 0; ndx < enabledExtensions.size(); ++ndx)
extensionPtrs[ndx] = enabledExtensions[ndx].c_str();
queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueInfo.pNext = DE_NULL;
queueInfo.flags = (VkDeviceQueueCreateFlags)0u;
queueInfo.queueFamilyIndex = queueIndex;
queueInfo.queueCount = 1u;
queueInfo.pQueuePriorities = &queuePriority;
deviceInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceInfo.pNext = DE_NULL;
deviceInfo.queueCreateInfoCount = 1u;
deviceInfo.pQueueCreateInfos = &queueInfo;
deviceInfo.enabledExtensionCount = (deUint32)extensionPtrs.size();
deviceInfo.ppEnabledExtensionNames = (extensionPtrs.empty() ? DE_NULL : &extensionPtrs[0]);
deviceInfo.enabledLayerCount = (deUint32)layerPtrs.size();
deviceInfo.ppEnabledLayerNames = (layerPtrs.empty() ? DE_NULL : &layerPtrs[0]);
deviceInfo.pEnabledFeatures = &enabledFeatures;
return createDevice(vki, physicalDevice, &deviceInfo);
};
class DefaultDevice
{
public:
DefaultDevice (const PlatformInterface& vkPlatform, const tcu::CommandLine& cmdLine);
~DefaultDevice (void);
VkInstance getInstance (void) const { return *m_instance; }
const InstanceInterface& getInstanceInterface (void) const { return m_instanceInterface; }
VkPhysicalDevice getPhysicalDevice (void) const { return m_physicalDevice; }
const VkPhysicalDeviceFeatures& getDeviceFeatures (void) const { return m_deviceFeatures; }
VkDevice getDevice (void) const { return *m_device; }
const DeviceInterface& getDeviceInterface (void) const { return m_deviceInterface; }
const VkPhysicalDeviceProperties& getDeviceProperties (void) const { return m_deviceProperties; }
const vector<string>& getDeviceExtensions (void) const { return m_deviceExtensions; }
deUint32 getUniversalQueueFamilyIndex (void) const { return m_universalQueueFamilyIndex; }
VkQueue getUniversalQueue (void) const;
private:
static VkPhysicalDeviceFeatures filterDefaultDeviceFeatures (const VkPhysicalDeviceFeatures& deviceFeatures);
static vector<string> filterDefaultDeviceExtensions (const vector<VkExtensionProperties>& deviceExtensions);
const Unique<VkInstance> m_instance;
const InstanceDriver m_instanceInterface;
const VkPhysicalDevice m_physicalDevice;
const deUint32 m_universalQueueFamilyIndex;
const VkPhysicalDeviceFeatures m_deviceFeatures;
const VkPhysicalDeviceProperties m_deviceProperties;
const vector<string> m_deviceExtensions;
const Unique<VkDevice> m_device;
const DeviceDriver m_deviceInterface;
};
DefaultDevice::DefaultDevice (const PlatformInterface& vkPlatform, const tcu::CommandLine& cmdLine)
: m_instance (createInstance(vkPlatform, cmdLine))
, m_instanceInterface (vkPlatform, *m_instance)
, m_physicalDevice (chooseDevice(m_instanceInterface, *m_instance, cmdLine))
, m_universalQueueFamilyIndex (findQueueFamilyIndexWithCaps(m_instanceInterface, m_physicalDevice, VK_QUEUE_GRAPHICS_BIT|VK_QUEUE_COMPUTE_BIT))
, m_deviceFeatures (filterDefaultDeviceFeatures(getPhysicalDeviceFeatures(m_instanceInterface, m_physicalDevice)))
, m_deviceProperties (getPhysicalDeviceProperties(m_instanceInterface, m_physicalDevice))
, m_deviceExtensions (filterDefaultDeviceExtensions(enumerateDeviceExtensionProperties(m_instanceInterface, m_physicalDevice, DE_NULL)))
, m_device (createDefaultDevice(m_instanceInterface, m_physicalDevice, m_universalQueueFamilyIndex, m_deviceFeatures, m_deviceExtensions, cmdLine))
, m_deviceInterface (m_instanceInterface, *m_device)
{
}
DefaultDevice::~DefaultDevice (void)
{
}
VkQueue DefaultDevice::getUniversalQueue (void) const
{
VkQueue queue = 0;
m_deviceInterface.getDeviceQueue(*m_device, m_universalQueueFamilyIndex, 0, &queue);
return queue;
}
VkPhysicalDeviceFeatures DefaultDevice::filterDefaultDeviceFeatures (const VkPhysicalDeviceFeatures& deviceFeatures)
{
VkPhysicalDeviceFeatures enabledDeviceFeatures = deviceFeatures;
// Disable robustness by default, as it has an impact on performance on some HW.
enabledDeviceFeatures.robustBufferAccess = false;
return enabledDeviceFeatures;
}
vector<string> DefaultDevice::filterDefaultDeviceExtensions (const vector<VkExtensionProperties>& deviceExtensions)
{
return filterExtensions(deviceExtensions);
}
// Allocator utilities
vk::Allocator* createAllocator (DefaultDevice* device)
{
const VkPhysicalDeviceMemoryProperties memoryProperties = vk::getPhysicalDeviceMemoryProperties(device->getInstanceInterface(), device->getPhysicalDevice());
// \todo [2015-07-24 jarkko] support allocator selection/configuration from command line (or compile time)
return new SimpleAllocator(device->getDeviceInterface(), device->getDevice(), memoryProperties);
}
// Context
Context::Context (tcu::TestContext& testCtx,
const vk::PlatformInterface& platformInterface,
vk::ProgramCollection<vk::ProgramBinary>& progCollection)
: m_testCtx (testCtx)
, m_platformInterface (platformInterface)
, m_progCollection (progCollection)
, m_device (new DefaultDevice(m_platformInterface, testCtx.getCommandLine()))
, m_allocator (createAllocator(m_device.get()))
{
}
Context::~Context (void)
{
}
vk::VkInstance Context::getInstance (void) const { return m_device->getInstance(); }
const vk::InstanceInterface& Context::getInstanceInterface (void) const { return m_device->getInstanceInterface(); }
vk::VkPhysicalDevice Context::getPhysicalDevice (void) const { return m_device->getPhysicalDevice(); }
const vk::VkPhysicalDeviceFeatures& Context::getDeviceFeatures (void) const { return m_device->getDeviceFeatures(); }
const vk::VkPhysicalDeviceProperties& Context::getDeviceProperties (void) const { return m_device->getDeviceProperties(); }
const vector<string>& Context::getDeviceExtensions (void) const { return m_device->getDeviceExtensions(); }
vk::VkDevice Context::getDevice (void) const { return m_device->getDevice(); }
const vk::DeviceInterface& Context::getDeviceInterface (void) const { return m_device->getDeviceInterface(); }
deUint32 Context::getUniversalQueueFamilyIndex (void) const { return m_device->getUniversalQueueFamilyIndex(); }
vk::VkQueue Context::getUniversalQueue (void) const { return m_device->getUniversalQueue(); }
vk::Allocator& Context::getDefaultAllocator (void) const { return *m_allocator; }
// TestCase
void TestCase::initPrograms (SourceCollections&) const
{
}
} // vkt
<|endoftext|> |
<commit_before>/***************************************************************************
plugin_katexmlcheck.cpp - checks XML files using xmllint
-------------------
begin : 2002-07-06
copyright : (C) 2002 by Daniel Naber
email : daniel.naber@t-online.de
***************************************************************************/
/***************************************************************************
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.
***************************************************************************/
/*
-fixme: show dock if "Validate XML" is selected (doesn't currently work when Kate
was just started and the dockwidget isn't yet visible)
-fixme(?): doesn't correctly disappear when deactivated in config
*/
#include "plugin_katexmlcheck.h"
#include <QHBoxLayout>
#include "plugin_katexmlcheck.moc"
#include <cassert>
#include <qfile.h>
#include <qinputdialog.h>
#include <qregexp.h>
#include <qstring.h>
#include <qtextstream.h>
#include <kactioncollection.h>
//Added by qt3to4:
#include <Q3CString>
#include <QApplication>
#include <kdefakes.h> // for setenv
#include <kaction.h>
#include <kcursor.h>
#include <kdebug.h>
#include <k3dockwidget.h>
#include <kcomponentdata.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <ktemporaryfile.h>
#include <kgenericfactory.h>
#include <kprocess.h>
K_EXPORT_COMPONENT_FACTORY( katexmlcheckplugin, KGenericFactory<PluginKateXMLCheck>( "katexmlcheck" ) )
PluginKateXMLCheck::PluginKateXMLCheck( QObject* parent, const QStringList& )
: Kate::Plugin ( (Kate::Application *)parent )
{
}
PluginKateXMLCheck::~PluginKateXMLCheck()
{
}
Kate::PluginView *PluginKateXMLCheck::createView(Kate::MainWindow *mainWindow)
{
return new PluginKateXMLCheckView(mainWindow);
}
//---------------------------------
PluginKateXMLCheckView::PluginKateXMLCheckView(Kate::MainWindow *mainwin)
: Kate::PluginView (mainwin),KXMLGUIClient(),win(mainwin)
//:Q3ListView(parent,name),win(mainwin)
{
dock = win->createToolView("kate_plugin_xmlcheck_ouputview", Kate::MainWindow::Bottom, SmallIcon("misc"), i18n("XML Checker Output"));
//QHBoxLayout *lay = new QHBoxLayout;
//dock->setLayout( lay );
listview = new Q3ListView( dock );
//lay->addWidget( listview );
m_tmp_file=0;
m_proc=0;
QAction *a = actionCollection()->addAction("xml_check");
a->setText(i18n("Validate XML"));
connect(a, SIGNAL(triggered()), this, SLOT(slotValidate()));
// TODO?:
//(void) new KAction ( i18n("Indent XML"), KShortcut(), this,
// SLOT( slotIndent() ), actionCollection(), "xml_indent" );
setComponentData(KComponentData("kate"));
setXMLFile("plugins/katexmlcheck/ui.rc");
listview->setFocusPolicy(Qt::NoFocus);
listview->addColumn(i18n("#"), -1);
listview->addColumn(i18n("Line"), -1);
listview->setColumnAlignment(1, Qt::AlignRight);
listview->addColumn(i18n("Column"), -1);
listview->setColumnAlignment(2, Qt::AlignRight);
listview->addColumn(i18n("Message"), -1);
listview->setAllColumnsShowFocus(true);
listview->setResizeMode(Q3ListView::LastColumn);
connect(listview, SIGNAL(clicked(Q3ListViewItem *)), SLOT(slotClicked(Q3ListViewItem *)));
/* TODO?: invalidate the listview when document has changed
Kate::View *kv = application()->activeMainWindow()->activeView();
if( ! kv ) {
kDebug() << "Warning: no Kate::View";
return;
}
connect(kv, SIGNAL(modifiedChanged()), this, SLOT(slotUpdate()));
*/
m_proc = new KProcess();
connect(m_proc, SIGNAL(finished (int, QProcess::ExitStatus)), this, SLOT(finished (int, QProcess::ExitStatus)));
// we currently only want errors:
m_proc->setOutputChannelMode(KProcess::OnlyStderrChannel);
mainWindow()->guiFactory()->addClient(this);
}
PluginKateXMLCheckView::~PluginKateXMLCheckView()
{
mainWindow()->guiFactory()->removeClient( this );
delete m_proc;
delete m_tmp_file;
}
void PluginKateXMLCheckView::slotProcExited(int exitCode, QProcess::ExitStatus exitStatus)
{
Q_UNUSED(exitCode);
// FIXME: doesn't work correct the first time:
//if( m_dockwidget->isDockBackPossible() ) {
// m_dockwidget->dockBack();
// }
if (exitStatus != QProcess::NormalExit) {
(void)new Q3ListViewItem(listview, QString("1").rightJustified(4,' '), "", "",
"Validate process crashed.");
return;
}
kDebug() << "slotProcExited()";
QApplication::restoreOverrideCursor();
delete m_tmp_file;
QString proc_stderr = QString::fromLocal8Bit(m_proc->readAllStandardError());
m_tmp_file=0;
listview->clear();
uint list_count = 0;
uint err_count = 0;
if( ! m_validating ) {
// no i18n here, so we don't get an ugly English<->Non-english mixup:
QString msg;
if( m_dtdname.isEmpty() ) {
msg = "No DOCTYPE found, will only check well-formedness.";
} else {
msg = '\'' + m_dtdname + "' not found, will only check well-formedness.";
}
(void)new Q3ListViewItem(listview, QString("1").rightJustified(4,' '), "", "", msg);
list_count++;
}
if( ! proc_stderr.isEmpty() ) {
QStringList lines = QStringList::split("\n", proc_stderr);
Q3ListViewItem *item = 0;
QString linenumber, msg;
int line_count = 0;
for(QStringList::Iterator it = lines.begin(); it != lines.end(); ++it) {
QString line = *it;
line_count++;
int semicolon_1 = line.find(':');
int semicolon_2 = line.find(':', semicolon_1+1);
int semicolon_3 = line.find(':', semicolon_2+2);
int caret_pos = line.find('^');
if( semicolon_1 != -1 && semicolon_2 != -1 && semicolon_3 != -1 ) {
linenumber = line.mid(semicolon_1+1, semicolon_2-semicolon_1-1).trimmed();
linenumber = linenumber.rightJustified(6, ' '); // for sorting numbers
msg = line.mid(semicolon_3+1, line.length()-semicolon_3-1).trimmed();
} else if( caret_pos != -1 || line_count == lines.size() ) {
// TODO: this fails if "^" occurs in the real text?!
if( line_count == lines.size() && caret_pos == -1 ) {
msg = msg+'\n'+line;
}
QString col = QString::number(caret_pos);
if( col == "-1" ) {
col = "";
}
err_count++;
list_count++;
item = new Q3ListViewItem(listview, QString::number(list_count).rightJustified(4,' '), linenumber, col, msg);
item->setMultiLinesEnabled(true);
} else {
msg = msg+'\n'+line;
}
}
listview->sort(); // TODO?: insert in right order
}
if( err_count == 0 ) {
QString msg;
if( m_validating ) {
msg = "No errors found, document is valid."; // no i18n here
} else {
msg = "No errors found, document is well-formed."; // no i18n here
}
(void)new Q3ListViewItem(listview, QString::number(list_count+1).rightJustified(4,' '), "", "", msg);
}
}
void PluginKateXMLCheckView::slotClicked(Q3ListViewItem *item)
{
kDebug() << "slotClicked";
if( item ) {
bool ok = true;
uint line = item->text(1).toUInt(&ok);
bool ok2 = true;
uint column = item->text(2).toUInt(&ok);
if( ok && ok2 ) {
KTextEditor::View *kv = win->activeView();
if( ! kv )
return;
kv->setCursorPosition(KTextEditor::Cursor (line-1, column));
}
}
}
void PluginKateXMLCheckView::slotUpdate()
{
kDebug() << "slotUpdate() (not implemented yet)";
}
bool PluginKateXMLCheckView::slotValidate()
{
kDebug() << "slotValidate()";
win->showToolView (dock);
m_proc->clearProgram();
m_validating = false;
m_dtdname = "";
KTextEditor::View *kv = win->activeView();
if( ! kv )
return false;
m_tmp_file = new KTemporaryFile();
if( !m_tmp_file->open() ) {
kDebug() << "Error (slotValidate()): could not create '" << m_tmp_file->fileName() << "': " << m_tmp_file->errorString();
KMessageBox::error(0, i18n("<b>Error:</b> Could not create "
"temporary file '%1'.", m_tmp_file->fileName()));
delete m_tmp_file;
m_tmp_file=0L;
return false;
}
QTextStream s ( m_tmp_file );
s << kv->document()->text();
s.flush();
QString exe = KStandardDirs::findExe("xmllint");
if( exe.isEmpty() ) {
exe = KStandardDirs::locate("exe", "xmllint");
}
// use catalogs for KDE docbook:
if( ! getenv("SGML_CATALOG_FILES") ) {
KComponentData ins("katexmlcheckplugin");
QString catalogs;
catalogs += ins.dirs()->findResource("data", "ksgmltools2/customization/catalog");
catalogs += ':';
catalogs += ins.dirs()->findResource("data", "ksgmltools2/docbook/xml-dtd-4.1.2/docbook.cat");
kDebug() << "catalogs: " << catalogs;
setenv("SGML_CATALOG_FILES", QFile::encodeName( catalogs ).data(), 1);
}
//kDebug() << "**catalogs: " << getenv("SGML_CATALOG_FILES");
*m_proc << exe << "--catalogs" << "--noout";
// heuristic: assume that the doctype is in the first 10,000 bytes:
QString text_start = kv->document()->text().left(10000);
// remove comments before looking for doctype (as a doctype might be commented out
// and needs to be ignored then):
QRegExp re("<!--.*-->");
re.setMinimal(true);
text_start.remove(re);
QRegExp re_doctype("<!DOCTYPE\\s+(.*)\\s+(?:PUBLIC\\s+[\"'].*[\"']\\s+[\"'](.*)[\"']|SYSTEM\\s+[\"'](.*)[\"'])", false);
re_doctype.setMinimal(true);
if( re_doctype.search(text_start) != -1 ) {
QString dtdname;
if( ! re_doctype.cap(2).isEmpty() ) {
dtdname = re_doctype.cap(2);
} else {
dtdname = re_doctype.cap(3);
}
if( !dtdname.startsWith("http:") ) { // todo: u_dtd.isLocalFile() doesn't work :-(
// a local DTD is used
m_validating = true;
*m_proc << "--valid";
} else {
m_validating = true;
*m_proc << "--valid";
}
} else if( text_start.find("<!DOCTYPE") != -1 ) {
// DTD is inside the XML file
m_validating = true;
*m_proc << "--valid";
}
*m_proc << m_tmp_file->fileName();
m_proc->start();
if( ! m_proc->waitForStarted(-1) ) {
KMessageBox::error(0, i18n("<b>Error:</b> Failed to execute xmllint. Please make "
"sure that xmllint is installed. It is part of libxml2."));
return false;
}
QApplication::setOverrideCursor(Qt::WaitCursor);
return true;
}
<commit_msg>Fix signal slot<commit_after>/***************************************************************************
plugin_katexmlcheck.cpp - checks XML files using xmllint
-------------------
begin : 2002-07-06
copyright : (C) 2002 by Daniel Naber
email : daniel.naber@t-online.de
***************************************************************************/
/***************************************************************************
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.
***************************************************************************/
/*
-fixme: show dock if "Validate XML" is selected (doesn't currently work when Kate
was just started and the dockwidget isn't yet visible)
-fixme(?): doesn't correctly disappear when deactivated in config
*/
#include "plugin_katexmlcheck.h"
#include <QHBoxLayout>
#include "plugin_katexmlcheck.moc"
#include <cassert>
#include <qfile.h>
#include <qinputdialog.h>
#include <qregexp.h>
#include <qstring.h>
#include <qtextstream.h>
#include <kactioncollection.h>
//Added by qt3to4:
#include <Q3CString>
#include <QApplication>
#include <kdefakes.h> // for setenv
#include <kaction.h>
#include <kcursor.h>
#include <kdebug.h>
#include <k3dockwidget.h>
#include <kcomponentdata.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <ktemporaryfile.h>
#include <kgenericfactory.h>
#include <kprocess.h>
K_EXPORT_COMPONENT_FACTORY( katexmlcheckplugin, KGenericFactory<PluginKateXMLCheck>( "katexmlcheck" ) )
PluginKateXMLCheck::PluginKateXMLCheck( QObject* parent, const QStringList& )
: Kate::Plugin ( (Kate::Application *)parent )
{
}
PluginKateXMLCheck::~PluginKateXMLCheck()
{
}
Kate::PluginView *PluginKateXMLCheck::createView(Kate::MainWindow *mainWindow)
{
return new PluginKateXMLCheckView(mainWindow);
}
//---------------------------------
PluginKateXMLCheckView::PluginKateXMLCheckView(Kate::MainWindow *mainwin)
: Kate::PluginView (mainwin),KXMLGUIClient(),win(mainwin)
//:Q3ListView(parent,name),win(mainwin)
{
dock = win->createToolView("kate_plugin_xmlcheck_ouputview", Kate::MainWindow::Bottom, SmallIcon("misc"), i18n("XML Checker Output"));
//QHBoxLayout *lay = new QHBoxLayout;
//dock->setLayout( lay );
listview = new Q3ListView( dock );
//lay->addWidget( listview );
m_tmp_file=0;
m_proc=0;
QAction *a = actionCollection()->addAction("xml_check");
a->setText(i18n("Validate XML"));
connect(a, SIGNAL(triggered()), this, SLOT(slotValidate()));
// TODO?:
//(void) new KAction ( i18n("Indent XML"), KShortcut(), this,
// SLOT( slotIndent() ), actionCollection(), "xml_indent" );
setComponentData(KComponentData("kate"));
setXMLFile("plugins/katexmlcheck/ui.rc");
listview->setFocusPolicy(Qt::NoFocus);
listview->addColumn(i18n("#"), -1);
listview->addColumn(i18n("Line"), -1);
listview->setColumnAlignment(1, Qt::AlignRight);
listview->addColumn(i18n("Column"), -1);
listview->setColumnAlignment(2, Qt::AlignRight);
listview->addColumn(i18n("Message"), -1);
listview->setAllColumnsShowFocus(true);
listview->setResizeMode(Q3ListView::LastColumn);
connect(listview, SIGNAL(clicked(Q3ListViewItem *)), SLOT(slotClicked(Q3ListViewItem *)));
/* TODO?: invalidate the listview when document has changed
Kate::View *kv = application()->activeMainWindow()->activeView();
if( ! kv ) {
kDebug() << "Warning: no Kate::View";
return;
}
connect(kv, SIGNAL(modifiedChanged()), this, SLOT(slotUpdate()));
*/
m_proc = new KProcess();
connect(m_proc, SIGNAL(finished (int, QProcess::ExitStatus)), this, SLOT(slotProcExited (int, QProcess::ExitStatus)));
// we currently only want errors:
m_proc->setOutputChannelMode(KProcess::OnlyStderrChannel);
mainWindow()->guiFactory()->addClient(this);
}
PluginKateXMLCheckView::~PluginKateXMLCheckView()
{
mainWindow()->guiFactory()->removeClient( this );
delete m_proc;
delete m_tmp_file;
}
void PluginKateXMLCheckView::slotProcExited(int exitCode, QProcess::ExitStatus exitStatus)
{
Q_UNUSED(exitCode);
// FIXME: doesn't work correct the first time:
//if( m_dockwidget->isDockBackPossible() ) {
// m_dockwidget->dockBack();
// }
if (exitStatus != QProcess::NormalExit) {
(void)new Q3ListViewItem(listview, QString("1").rightJustified(4,' '), "", "",
"Validate process crashed.");
return;
}
kDebug() << "slotProcExited()";
QApplication::restoreOverrideCursor();
delete m_tmp_file;
QString proc_stderr = QString::fromLocal8Bit(m_proc->readAllStandardError());
m_tmp_file=0;
listview->clear();
uint list_count = 0;
uint err_count = 0;
if( ! m_validating ) {
// no i18n here, so we don't get an ugly English<->Non-english mixup:
QString msg;
if( m_dtdname.isEmpty() ) {
msg = "No DOCTYPE found, will only check well-formedness.";
} else {
msg = '\'' + m_dtdname + "' not found, will only check well-formedness.";
}
(void)new Q3ListViewItem(listview, QString("1").rightJustified(4,' '), "", "", msg);
list_count++;
}
if( ! proc_stderr.isEmpty() ) {
QStringList lines = QStringList::split("\n", proc_stderr);
Q3ListViewItem *item = 0;
QString linenumber, msg;
int line_count = 0;
for(QStringList::Iterator it = lines.begin(); it != lines.end(); ++it) {
QString line = *it;
line_count++;
int semicolon_1 = line.find(':');
int semicolon_2 = line.find(':', semicolon_1+1);
int semicolon_3 = line.find(':', semicolon_2+2);
int caret_pos = line.find('^');
if( semicolon_1 != -1 && semicolon_2 != -1 && semicolon_3 != -1 ) {
linenumber = line.mid(semicolon_1+1, semicolon_2-semicolon_1-1).trimmed();
linenumber = linenumber.rightJustified(6, ' '); // for sorting numbers
msg = line.mid(semicolon_3+1, line.length()-semicolon_3-1).trimmed();
} else if( caret_pos != -1 || line_count == lines.size() ) {
// TODO: this fails if "^" occurs in the real text?!
if( line_count == lines.size() && caret_pos == -1 ) {
msg = msg+'\n'+line;
}
QString col = QString::number(caret_pos);
if( col == "-1" ) {
col = "";
}
err_count++;
list_count++;
item = new Q3ListViewItem(listview, QString::number(list_count).rightJustified(4,' '), linenumber, col, msg);
item->setMultiLinesEnabled(true);
} else {
msg = msg+'\n'+line;
}
}
listview->sort(); // TODO?: insert in right order
}
if( err_count == 0 ) {
QString msg;
if( m_validating ) {
msg = "No errors found, document is valid."; // no i18n here
} else {
msg = "No errors found, document is well-formed."; // no i18n here
}
(void)new Q3ListViewItem(listview, QString::number(list_count+1).rightJustified(4,' '), "", "", msg);
}
}
void PluginKateXMLCheckView::slotClicked(Q3ListViewItem *item)
{
kDebug() << "slotClicked";
if( item ) {
bool ok = true;
uint line = item->text(1).toUInt(&ok);
bool ok2 = true;
uint column = item->text(2).toUInt(&ok);
if( ok && ok2 ) {
KTextEditor::View *kv = win->activeView();
if( ! kv )
return;
kv->setCursorPosition(KTextEditor::Cursor (line-1, column));
}
}
}
void PluginKateXMLCheckView::slotUpdate()
{
kDebug() << "slotUpdate() (not implemented yet)";
}
bool PluginKateXMLCheckView::slotValidate()
{
kDebug() << "slotValidate()";
win->showToolView (dock);
m_proc->clearProgram();
m_validating = false;
m_dtdname = "";
KTextEditor::View *kv = win->activeView();
if( ! kv )
return false;
m_tmp_file = new KTemporaryFile();
if( !m_tmp_file->open() ) {
kDebug() << "Error (slotValidate()): could not create '" << m_tmp_file->fileName() << "': " << m_tmp_file->errorString();
KMessageBox::error(0, i18n("<b>Error:</b> Could not create "
"temporary file '%1'.", m_tmp_file->fileName()));
delete m_tmp_file;
m_tmp_file=0L;
return false;
}
QTextStream s ( m_tmp_file );
s << kv->document()->text();
s.flush();
QString exe = KStandardDirs::findExe("xmllint");
if( exe.isEmpty() ) {
exe = KStandardDirs::locate("exe", "xmllint");
}
// use catalogs for KDE docbook:
if( ! getenv("SGML_CATALOG_FILES") ) {
KComponentData ins("katexmlcheckplugin");
QString catalogs;
catalogs += ins.dirs()->findResource("data", "ksgmltools2/customization/catalog");
catalogs += ':';
catalogs += ins.dirs()->findResource("data", "ksgmltools2/docbook/xml-dtd-4.1.2/docbook.cat");
kDebug() << "catalogs: " << catalogs;
setenv("SGML_CATALOG_FILES", QFile::encodeName( catalogs ).data(), 1);
}
//kDebug() << "**catalogs: " << getenv("SGML_CATALOG_FILES");
*m_proc << exe << "--catalogs" << "--noout";
// heuristic: assume that the doctype is in the first 10,000 bytes:
QString text_start = kv->document()->text().left(10000);
// remove comments before looking for doctype (as a doctype might be commented out
// and needs to be ignored then):
QRegExp re("<!--.*-->");
re.setMinimal(true);
text_start.remove(re);
QRegExp re_doctype("<!DOCTYPE\\s+(.*)\\s+(?:PUBLIC\\s+[\"'].*[\"']\\s+[\"'](.*)[\"']|SYSTEM\\s+[\"'](.*)[\"'])", false);
re_doctype.setMinimal(true);
if( re_doctype.search(text_start) != -1 ) {
QString dtdname;
if( ! re_doctype.cap(2).isEmpty() ) {
dtdname = re_doctype.cap(2);
} else {
dtdname = re_doctype.cap(3);
}
if( !dtdname.startsWith("http:") ) { // todo: u_dtd.isLocalFile() doesn't work :-(
// a local DTD is used
m_validating = true;
*m_proc << "--valid";
} else {
m_validating = true;
*m_proc << "--valid";
}
} else if( text_start.find("<!DOCTYPE") != -1 ) {
// DTD is inside the XML file
m_validating = true;
*m_proc << "--valid";
}
*m_proc << m_tmp_file->fileName();
m_proc->start();
if( ! m_proc->waitForStarted(-1) ) {
KMessageBox::error(0, i18n("<b>Error:</b> Failed to execute xmllint. Please make "
"sure that xmllint is installed. It is part of libxml2."));
return false;
}
QApplication::setOverrideCursor(Qt::WaitCursor);
return true;
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_PROB_LOGLOGISTIC_CDF_HPP
#define STAN_MATH_PRIM_PROB_LOGLOGISTIC_CDF_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/as_column_vector_or_scalar.hpp>
#include <stan/math/prim/fun/as_array_or_scalar.hpp>
#include <stan/math/prim/fun/as_value_column_array_or_scalar.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
#include <stan/math/prim/fun/promote_scalar.hpp>
#include <cmath>
#include <iostream>
namespace stan {
namespace math {
/** \ingroup prob_dists
* The loglogistic cumulative distribution function for the specified
* scalar(s) given the specified scales(s) and shape(s). y, alpha, or
* beta can each be either a scalar or a vector. Any vector inputs
* must be the same length.
*
*
* @tparam T_y type of scalar.
* @tparam T_scale type of scale parameter.
* @tparam T_shape type of shape parameter.
* @param y (Sequence of) scalar(s).
* @param alpha (Sequence of) scale parameter(s)
* for the loglogistic distribution.
* @param beta (Sequence of) shape parameter(s) for the
* loglogistic distribution.
* @return The loglogistic cdf evaluated at the specified arguments.
* @throw std::domain_error if any of the inputs are not positive or
* if and of the parameters are not finite.
*/
template <typename T_y, typename T_scale, typename T_shape,
require_all_not_nonscalar_prim_or_rev_kernel_expression_t<
T_y, T_scale, T_shape>* = nullptr>
return_type_t<T_y, T_scale, T_shape> loglogistic_cdf(const T_y& y,
const T_scale& alpha,
const T_shape& beta) {
using T_partials_return = partials_return_t<T_y, T_scale, T_shape>;
using T_y_ref = ref_type_t<T_y>;
using T_alpha_ref = ref_type_t<T_scale>;
using T_beta_ref = ref_type_t<T_shape>;
using std::pow;
static const char* function = "loglogistic_cdf";
check_consistent_sizes(function, "Random variable", y, "Scale parameter",
alpha, "Shape parameter", beta);
T_y_ref y_ref = y;
T_alpha_ref alpha_ref = alpha;
T_beta_ref beta_ref = beta;
decltype(auto) y_val = to_ref(as_value_column_array_or_scalar(y_ref));
decltype(auto) alpha_val = to_ref(as_value_column_array_or_scalar(alpha_ref));
decltype(auto) beta_val = to_ref(as_value_column_array_or_scalar(beta_ref));
check_nonnegative(function, "Random variable", y_val);
check_positive_finite(function, "Scale parameter", alpha_val);
check_positive_finite(function, "Shape parameter", beta_val);
if (size_zero(y, alpha, beta)) {
return 1.0;
}
operands_and_partials<T_y_ref, T_alpha_ref, T_beta_ref> ops_partials(
y_ref, alpha_ref, beta_ref);
if (sum(promote_scalar<int>(y_val == 0))) {
return ops_partials.build(0.0);
}
const auto& alpha_div_y
= to_ref_if<!is_constant_all<T_shape>::value>(alpha_val / y_val);
const auto& alpha_div_y_pow_beta
= to_ref_if<!is_constant_all<T_y, T_scale, T_shape>::value>(
pow(alpha_div_y, beta_val));
const auto& prod_all
= to_ref_if<!is_constant_all<T_y, T_scale, T_shape>::value>(
1 / (1 + alpha_div_y_pow_beta));
T_partials_return cdf = prod(prod_all);
if (!is_constant_all<T_y, T_scale, T_shape>::value) {
const auto& prod_all_sq = to_ref_if<!is_constant_all<T_y>::value
+ !is_constant_all<T_scale>::value
+ !is_constant_all<T_shape>::value
>= 2>(square(prod_all));
const auto& cdf_div_elt = to_ref_if<!is_constant_all<T_y>::value
+ !is_constant_all<T_scale>::value
+ !is_constant_all<T_shape>::value
>= 2>(cdf / prod_all);
if (!is_constant_all<T_y, T_scale>::value) {
const auto& alpha_div_times_beta = to_ref_if<
!is_constant_all<T_y>::value + !is_constant_all<T_scale>::value == 2>(
alpha_div_y_pow_beta * beta_val);
if (!is_constant_all<T_y>::value) {
const auto& y_deriv = alpha_div_times_beta * inv(y_val) * prod_all_sq;
ops_partials.edge1_.partials_ = y_deriv * cdf_div_elt;
}
if (!is_constant_all<T_scale>::value) {
const auto& alpha_deriv
= -alpha_div_times_beta * inv(alpha_val) * prod_all_sq;
ops_partials.edge2_.partials_ = alpha_deriv * cdf_div_elt;
}
}
if (!is_constant_all<T_shape>::value) {
const auto& beta_deriv
= -multiply_log(alpha_div_y_pow_beta, alpha_div_y) * prod_all_sq;
ops_partials.edge3_.partials_ = beta_deriv * cdf_div_elt;
}
}
return ops_partials.build(cdf);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>Update stan/math/prim/prob/loglogistic_cdf.hpp<commit_after>#ifndef STAN_MATH_PRIM_PROB_LOGLOGISTIC_CDF_HPP
#define STAN_MATH_PRIM_PROB_LOGLOGISTIC_CDF_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/as_column_vector_or_scalar.hpp>
#include <stan/math/prim/fun/as_array_or_scalar.hpp>
#include <stan/math/prim/fun/as_value_column_array_or_scalar.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
#include <stan/math/prim/fun/promote_scalar.hpp>
#include <cmath>
#include <iostream>
namespace stan {
namespace math {
/** \ingroup prob_dists
* The loglogistic cumulative distribution function for the specified
* scalar(s) given the specified scales(s) and shape(s). y, alpha, or
* beta can each be either a scalar or a vector. Any vector inputs
* must be the same length.
*
*
* @tparam T_y type of scalar.
* @tparam T_scale type of scale parameter.
* @tparam T_shape type of shape parameter.
* @param y (Sequence of) scalar(s).
* @param alpha (Sequence of) scale parameter(s)
* for the loglogistic distribution.
* @param beta (Sequence of) shape parameter(s) for the
* loglogistic distribution.
* @return The loglogistic cdf evaluated at the specified arguments.
* @throw std::domain_error if any of the inputs are not positive or
* if and of the parameters are not finite.
*/
template <typename T_y, typename T_scale, typename T_shape,
require_all_not_nonscalar_prim_or_rev_kernel_expression_t<
T_y, T_scale, T_shape>* = nullptr>
return_type_t<T_y, T_scale, T_shape> loglogistic_cdf(const T_y& y,
const T_scale& alpha,
const T_shape& beta) {
using T_partials_return = partials_return_t<T_y, T_scale, T_shape>;
using T_y_ref = ref_type_t<T_y>;
using T_alpha_ref = ref_type_t<T_scale>;
using T_beta_ref = ref_type_t<T_shape>;
using std::pow;
static const char* function = "loglogistic_cdf";
check_consistent_sizes(function, "Random variable", y, "Scale parameter",
alpha, "Shape parameter", beta);
T_y_ref y_ref = y;
T_alpha_ref alpha_ref = alpha;
T_beta_ref beta_ref = beta;
decltype(auto) y_val = to_ref(as_value_column_array_or_scalar(y_ref));
decltype(auto) alpha_val = to_ref(as_value_column_array_or_scalar(alpha_ref));
decltype(auto) beta_val = to_ref(as_value_column_array_or_scalar(beta_ref));
check_nonnegative(function, "Random variable", y_val);
check_positive_finite(function, "Scale parameter", alpha_val);
check_positive_finite(function, "Shape parameter", beta_val);
if (size_zero(y, alpha, beta)) {
return 1.0;
}
operands_and_partials<T_y_ref, T_alpha_ref, T_beta_ref> ops_partials(
y_ref, alpha_ref, beta_ref);
if (sum(promote_scalar<int>(y_val == 0))) {
return ops_partials.build(0.0);
}
const auto& alpha_div_y
= to_ref_if<!is_constant_all<T_shape>::value>(alpha_val / y_val);
const auto& alpha_div_y_pow_beta
= to_ref_if<!is_constant_all<T_y, T_scale, T_shape>::value>(
pow(alpha_div_y, beta_val));
const auto& prod_all
= to_ref_if<!is_constant_all<T_y, T_scale, T_shape>::value>(
1 / (1 + alpha_div_y_pow_beta));
T_partials_return cdf = prod(prod_all);
if (!is_constant_all<T_y, T_scale, T_shape>::value) {
const auto& prod_all_sq = to_ref_if<!is_constant_all<T_y>::value
+ !is_constant_all<T_scale>::value
+ !is_constant_all<T_shape>::value
>= 2>(square(prod_all));
const auto& cdf_div_elt = to_ref_if<!is_constant_all<T_y>::value
+ !is_constant_all<T_scale>::value
+ !is_constant_all<T_shape>::value
>= 2>(cdf / prod_all);
if (!is_constant_all<T_y, T_scale>::value) {
const auto& alpha_div_times_beta = to_ref_if<
!is_constant_all<T_y>::value + !is_constant_all<T_scale>::value == 2>(
alpha_div_y_pow_beta * beta_val);
if (!is_constant_all<T_y>::value) {
const auto& y_deriv = alpha_div_times_beta / y_val * prod_all_sq;
ops_partials.edge1_.partials_ = y_deriv * cdf_div_elt;
}
if (!is_constant_all<T_scale>::value) {
const auto& alpha_deriv
= -alpha_div_times_beta * inv(alpha_val) * prod_all_sq;
ops_partials.edge2_.partials_ = alpha_deriv * cdf_div_elt;
}
}
if (!is_constant_all<T_shape>::value) {
const auto& beta_deriv
= -multiply_log(alpha_div_y_pow_beta, alpha_div_y) * prod_all_sq;
ops_partials.edge3_.partials_ = beta_deriv * cdf_div_elt;
}
}
return ops_partials.build(cdf);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
* x11_window.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* 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.
*****************************************************************************/
#ifdef X11_SKINS
#include <X11/Xatom.h>
#include "../src/generic_window.hpp"
#include "../src/vlcproc.hpp"
#include "x11_window.hpp"
#include "x11_display.hpp"
#include "x11_graphics.hpp"
#include "x11_dragdrop.hpp"
#include "x11_factory.hpp"
X11Window::X11Window( intf_thread_t *pIntf, GenericWindow &rWindow,
X11Display &rDisplay, bool dragDrop, bool playOnDrop,
X11Window *pParentWindow, GenericWindow::WindowType_t type ):
OSWindow( pIntf ), m_rDisplay( rDisplay ), m_pParent( pParentWindow ),
m_dragDrop( dragDrop )
{
XSetWindowAttributes attr;
unsigned long valuemask;
string name_type;
if( type == GenericWindow::FullscreenWindow )
{
m_wnd_parent = DefaultRootWindow( XDISPLAY );
int i_screen = DefaultScreen( XDISPLAY );
attr.event_mask = ExposureMask | StructureNotifyMask;
attr.background_pixel = BlackPixel( XDISPLAY, i_screen );
attr.backing_store = Always;
attr.override_redirect = True;
valuemask = CWBackingStore | CWOverrideRedirect |
CWBackPixel | CWEventMask;
name_type = "Fullscreen";
}
else if( type == GenericWindow::VoutWindow )
{
m_wnd_parent = pParentWindow->m_wnd;
int i_screen = DefaultScreen( XDISPLAY );
attr.event_mask = ExposureMask | StructureNotifyMask;
attr.backing_store = Always;
attr.background_pixel = BlackPixel( XDISPLAY, i_screen );
valuemask = CWBackingStore | CWBackPixel | CWEventMask;
name_type = "VoutWindow";
}
else
{
m_wnd_parent = DefaultRootWindow( XDISPLAY );
attr.event_mask = ExposureMask | StructureNotifyMask;
valuemask = CWEventMask;
name_type = "TopWindow";
}
// Create the window
m_wnd = XCreateWindow( XDISPLAY, m_wnd_parent, -10, 0, 1, 1, 0, 0,
InputOutput, CopyFromParent, valuemask, &attr );
// wait for X server to process the previous commands
XSync( XDISPLAY, false );
// Set the colormap for 8bpp mode
if( XPIXELSIZE == 1 )
{
XSetWindowColormap( XDISPLAY, m_wnd, m_rDisplay.getColormap() );
}
// Select events received by the window
XSelectInput( XDISPLAY, m_wnd, ExposureMask|KeyPressMask|
PointerMotionMask|ButtonPressMask|ButtonReleaseMask|
LeaveWindowMask|FocusChangeMask );
// Store a pointer on the generic window in a map
X11Factory *pFactory = (X11Factory*)X11Factory::instance( getIntf() );
pFactory->m_windowMap[m_wnd] = &rWindow;
// Changing decorations
struct {
unsigned long flags;
unsigned long functions;
unsigned long decorations;
signed long input_mode;
unsigned long status;
} motifWmHints;
Atom hints_atom = XInternAtom( XDISPLAY, "_MOTIF_WM_HINTS", False );
motifWmHints.flags = 2; // MWM_HINTS_DECORATIONS;
motifWmHints.decorations = 0;
XChangeProperty( XDISPLAY, m_wnd, hints_atom, hints_atom, 32,
PropModeReplace, (unsigned char *)&motifWmHints,
sizeof( motifWmHints ) / sizeof( uint32_t ) );
// Drag & drop
if( m_dragDrop )
{
// Create a Dnd object for this window
m_pDropTarget = new X11DragDrop( getIntf(), m_rDisplay, m_wnd,
playOnDrop );
// Register the window as a drop target
Atom xdndAtom = XInternAtom( XDISPLAY, "XdndAware", False );
char xdndVersion = 4;
XChangeProperty( XDISPLAY, m_wnd, xdndAtom, XA_ATOM, 32,
PropModeReplace, (unsigned char *)&xdndVersion, 1 );
// Store a pointer to be used in X11Loop
pFactory->m_dndMap[m_wnd] = m_pDropTarget;
}
// Change the window title
string name_window = "VLC (" + name_type + ")";
XStoreName( XDISPLAY, m_wnd, name_window.c_str() );
// Associate the window to the main "parent" window
XSetTransientForHint( XDISPLAY, m_wnd, m_rDisplay.getMainWindow() );
}
X11Window::~X11Window()
{
X11Factory *pFactory = (X11Factory*)X11Factory::instance( getIntf() );
pFactory->m_windowMap[m_wnd] = NULL;
pFactory->m_dndMap[m_wnd] = NULL;
if( m_dragDrop )
{
delete m_pDropTarget;
}
XDestroyWindow( XDISPLAY, m_wnd );
XSync( XDISPLAY, False );
}
void X11Window::reparent( void* OSHandle, int x, int y, int w, int h )
{
// Reparent the window
Window new_parent =
OSHandle ? (Window) OSHandle : DefaultRootWindow( XDISPLAY );
if( w && h )
XResizeWindow( XDISPLAY, m_wnd, w, h );
XReparentWindow( XDISPLAY, m_wnd, new_parent, x, y);
m_wnd_parent = new_parent;
}
void X11Window::show() const
{
// Map the window
XMapRaised( XDISPLAY, m_wnd );
}
void X11Window::hide() const
{
// Unmap the window
XUnmapWindow( XDISPLAY, m_wnd );
}
void X11Window::moveResize( int left, int top, int width, int height ) const
{
if( width && height )
XMoveResizeWindow( XDISPLAY, m_wnd, left, top, width, height );
else
XMoveWindow( XDISPLAY, m_wnd, left, top );
}
void X11Window::raise() const
{
XRaiseWindow( XDISPLAY, m_wnd );
}
void X11Window::setOpacity( uint8_t value ) const
{
Atom opaq = XInternAtom(XDISPLAY, "_NET_WM_WINDOW_OPACITY", False);
if( 255==value )
XDeleteProperty(XDISPLAY, m_wnd, opaq);
else
{
uint32_t opacity = value * ((uint32_t)-1/255);
XChangeProperty(XDISPLAY, m_wnd, opaq, XA_CARDINAL, 32,
PropModeReplace, (unsigned char *) &opacity, 1L);
}
XSync( XDISPLAY, False );
}
void X11Window::toggleOnTop( bool onTop ) const
{
int i_ret, i_format;
unsigned long i, i_items, i_bytesafter;
Atom net_wm_supported, net_wm_state, net_wm_state_on_top,net_wm_state_above;
union { Atom *p_atom; unsigned char *p_char; } p_args;
p_args.p_atom = NULL;
net_wm_supported = XInternAtom( XDISPLAY, "_NET_SUPPORTED", False );
i_ret = XGetWindowProperty( XDISPLAY, DefaultRootWindow( XDISPLAY ),
net_wm_supported,
0, 16384, False, AnyPropertyType,
&net_wm_supported,
&i_format, &i_items, &i_bytesafter,
(unsigned char **)&p_args );
if( i_ret != Success || i_items == 0 ) return; /* Not supported */
net_wm_state = XInternAtom( XDISPLAY, "_NET_WM_STATE", False );
net_wm_state_on_top = XInternAtom( XDISPLAY, "_NET_WM_STATE_STAYS_ON_TOP",
False );
for( i = 0; i < i_items; i++ )
{
if( p_args.p_atom[i] == net_wm_state_on_top ) break;
}
if( i == i_items )
{ /* use _NET_WM_STATE_ABOVE if window manager
* doesn't handle _NET_WM_STATE_STAYS_ON_TOP */
net_wm_state_above = XInternAtom( XDISPLAY, "_NET_WM_STATE_ABOVE",
False);
for( i = 0; i < i_items; i++ )
{
if( p_args.p_atom[i] == net_wm_state_above ) break;
}
XFree( p_args.p_atom );
if( i == i_items )
return; /* Not supported */
/* Switch "on top" status */
XClientMessageEvent event;
memset( &event, 0, sizeof( XClientMessageEvent ) );
event.type = ClientMessage;
event.message_type = net_wm_state;
event.display = XDISPLAY;
event.window = m_wnd;
event.format = 32;
event.data.l[ 0 ] = onTop; /* set property */
event.data.l[ 1 ] = net_wm_state_above;
XSendEvent( XDISPLAY, DefaultRootWindow( XDISPLAY ),
False, SubstructureRedirectMask, (XEvent*)&event );
return;
}
XFree( p_args.p_atom );
/* Switch "on top" status */
XClientMessageEvent event;
memset( &event, 0, sizeof( XClientMessageEvent ) );
event.type = ClientMessage;
event.message_type = net_wm_state;
event.display = XDISPLAY;
event.window = m_wnd;
event.format = 32;
event.data.l[ 0 ] = onTop; /* set property */
event.data.l[ 1 ] = net_wm_state_on_top;
XSendEvent( XDISPLAY, DefaultRootWindow( XDISPLAY ),
False, SubstructureRedirectMask, (XEvent*)&event );
}
#endif
<commit_msg>skins2(Linux): reactivate mouse on a video window (like dblclick for fullscreen)<commit_after>/*****************************************************************************
* x11_window.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* 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.
*****************************************************************************/
#ifdef X11_SKINS
#include <X11/Xatom.h>
#include "../src/generic_window.hpp"
#include "../src/vlcproc.hpp"
#include "x11_window.hpp"
#include "x11_display.hpp"
#include "x11_graphics.hpp"
#include "x11_dragdrop.hpp"
#include "x11_factory.hpp"
X11Window::X11Window( intf_thread_t *pIntf, GenericWindow &rWindow,
X11Display &rDisplay, bool dragDrop, bool playOnDrop,
X11Window *pParentWindow, GenericWindow::WindowType_t type ):
OSWindow( pIntf ), m_rDisplay( rDisplay ), m_pParent( pParentWindow ),
m_dragDrop( dragDrop )
{
XSetWindowAttributes attr;
unsigned long valuemask;
string name_type;
if( type == GenericWindow::FullscreenWindow )
{
m_wnd_parent = DefaultRootWindow( XDISPLAY );
int i_screen = DefaultScreen( XDISPLAY );
attr.event_mask = ExposureMask | StructureNotifyMask;
attr.background_pixel = BlackPixel( XDISPLAY, i_screen );
attr.backing_store = Always;
attr.override_redirect = True;
valuemask = CWBackingStore | CWOverrideRedirect |
CWBackPixel | CWEventMask;
name_type = "Fullscreen";
}
else if( type == GenericWindow::VoutWindow )
{
m_wnd_parent = pParentWindow->m_wnd;
int i_screen = DefaultScreen( XDISPLAY );
attr.event_mask = ExposureMask | StructureNotifyMask;
attr.backing_store = Always;
attr.background_pixel = BlackPixel( XDISPLAY, i_screen );
valuemask = CWBackingStore | CWBackPixel | CWEventMask;
name_type = "VoutWindow";
}
else
{
m_wnd_parent = DefaultRootWindow( XDISPLAY );
attr.event_mask = ExposureMask | StructureNotifyMask;
valuemask = CWEventMask;
name_type = "TopWindow";
}
// Create the window
m_wnd = XCreateWindow( XDISPLAY, m_wnd_parent, -10, 0, 1, 1, 0, 0,
InputOutput, CopyFromParent, valuemask, &attr );
// wait for X server to process the previous commands
XSync( XDISPLAY, false );
// Set the colormap for 8bpp mode
if( XPIXELSIZE == 1 )
{
XSetWindowColormap( XDISPLAY, m_wnd, m_rDisplay.getColormap() );
}
// Select events received by the window
long event_mask;
if( type == GenericWindow::VoutWindow )
{
event_mask = ExposureMask|KeyPressMask|
LeaveWindowMask|FocusChangeMask;
}
else
{
event_mask = ExposureMask|KeyPressMask|
PointerMotionMask|ButtonPressMask|ButtonReleaseMask|
LeaveWindowMask|FocusChangeMask;
}
XSelectInput( XDISPLAY, m_wnd, event_mask );
// Store a pointer on the generic window in a map
X11Factory *pFactory = (X11Factory*)X11Factory::instance( getIntf() );
pFactory->m_windowMap[m_wnd] = &rWindow;
// Changing decorations
struct {
unsigned long flags;
unsigned long functions;
unsigned long decorations;
signed long input_mode;
unsigned long status;
} motifWmHints;
Atom hints_atom = XInternAtom( XDISPLAY, "_MOTIF_WM_HINTS", False );
motifWmHints.flags = 2; // MWM_HINTS_DECORATIONS;
motifWmHints.decorations = 0;
XChangeProperty( XDISPLAY, m_wnd, hints_atom, hints_atom, 32,
PropModeReplace, (unsigned char *)&motifWmHints,
sizeof( motifWmHints ) / sizeof( uint32_t ) );
// Drag & drop
if( m_dragDrop )
{
// Create a Dnd object for this window
m_pDropTarget = new X11DragDrop( getIntf(), m_rDisplay, m_wnd,
playOnDrop );
// Register the window as a drop target
Atom xdndAtom = XInternAtom( XDISPLAY, "XdndAware", False );
char xdndVersion = 4;
XChangeProperty( XDISPLAY, m_wnd, xdndAtom, XA_ATOM, 32,
PropModeReplace, (unsigned char *)&xdndVersion, 1 );
// Store a pointer to be used in X11Loop
pFactory->m_dndMap[m_wnd] = m_pDropTarget;
}
// Change the window title
string name_window = "VLC (" + name_type + ")";
XStoreName( XDISPLAY, m_wnd, name_window.c_str() );
// Associate the window to the main "parent" window
XSetTransientForHint( XDISPLAY, m_wnd, m_rDisplay.getMainWindow() );
}
X11Window::~X11Window()
{
X11Factory *pFactory = (X11Factory*)X11Factory::instance( getIntf() );
pFactory->m_windowMap[m_wnd] = NULL;
pFactory->m_dndMap[m_wnd] = NULL;
if( m_dragDrop )
{
delete m_pDropTarget;
}
XDestroyWindow( XDISPLAY, m_wnd );
XSync( XDISPLAY, False );
}
void X11Window::reparent( void* OSHandle, int x, int y, int w, int h )
{
// Reparent the window
Window new_parent =
OSHandle ? (Window) OSHandle : DefaultRootWindow( XDISPLAY );
if( w && h )
XResizeWindow( XDISPLAY, m_wnd, w, h );
XReparentWindow( XDISPLAY, m_wnd, new_parent, x, y);
m_wnd_parent = new_parent;
}
void X11Window::show() const
{
// Map the window
XMapRaised( XDISPLAY, m_wnd );
}
void X11Window::hide() const
{
// Unmap the window
XUnmapWindow( XDISPLAY, m_wnd );
}
void X11Window::moveResize( int left, int top, int width, int height ) const
{
if( width && height )
XMoveResizeWindow( XDISPLAY, m_wnd, left, top, width, height );
else
XMoveWindow( XDISPLAY, m_wnd, left, top );
}
void X11Window::raise() const
{
XRaiseWindow( XDISPLAY, m_wnd );
}
void X11Window::setOpacity( uint8_t value ) const
{
Atom opaq = XInternAtom(XDISPLAY, "_NET_WM_WINDOW_OPACITY", False);
if( 255==value )
XDeleteProperty(XDISPLAY, m_wnd, opaq);
else
{
uint32_t opacity = value * ((uint32_t)-1/255);
XChangeProperty(XDISPLAY, m_wnd, opaq, XA_CARDINAL, 32,
PropModeReplace, (unsigned char *) &opacity, 1L);
}
XSync( XDISPLAY, False );
}
void X11Window::toggleOnTop( bool onTop ) const
{
int i_ret, i_format;
unsigned long i, i_items, i_bytesafter;
Atom net_wm_supported, net_wm_state, net_wm_state_on_top,net_wm_state_above;
union { Atom *p_atom; unsigned char *p_char; } p_args;
p_args.p_atom = NULL;
net_wm_supported = XInternAtom( XDISPLAY, "_NET_SUPPORTED", False );
i_ret = XGetWindowProperty( XDISPLAY, DefaultRootWindow( XDISPLAY ),
net_wm_supported,
0, 16384, False, AnyPropertyType,
&net_wm_supported,
&i_format, &i_items, &i_bytesafter,
(unsigned char **)&p_args );
if( i_ret != Success || i_items == 0 ) return; /* Not supported */
net_wm_state = XInternAtom( XDISPLAY, "_NET_WM_STATE", False );
net_wm_state_on_top = XInternAtom( XDISPLAY, "_NET_WM_STATE_STAYS_ON_TOP",
False );
for( i = 0; i < i_items; i++ )
{
if( p_args.p_atom[i] == net_wm_state_on_top ) break;
}
if( i == i_items )
{ /* use _NET_WM_STATE_ABOVE if window manager
* doesn't handle _NET_WM_STATE_STAYS_ON_TOP */
net_wm_state_above = XInternAtom( XDISPLAY, "_NET_WM_STATE_ABOVE",
False);
for( i = 0; i < i_items; i++ )
{
if( p_args.p_atom[i] == net_wm_state_above ) break;
}
XFree( p_args.p_atom );
if( i == i_items )
return; /* Not supported */
/* Switch "on top" status */
XClientMessageEvent event;
memset( &event, 0, sizeof( XClientMessageEvent ) );
event.type = ClientMessage;
event.message_type = net_wm_state;
event.display = XDISPLAY;
event.window = m_wnd;
event.format = 32;
event.data.l[ 0 ] = onTop; /* set property */
event.data.l[ 1 ] = net_wm_state_above;
XSendEvent( XDISPLAY, DefaultRootWindow( XDISPLAY ),
False, SubstructureRedirectMask, (XEvent*)&event );
return;
}
XFree( p_args.p_atom );
/* Switch "on top" status */
XClientMessageEvent event;
memset( &event, 0, sizeof( XClientMessageEvent ) );
event.type = ClientMessage;
event.message_type = net_wm_state;
event.display = XDISPLAY;
event.window = m_wnd;
event.format = 32;
event.data.l[ 0 ] = onTop; /* set property */
event.data.l[ 1 ] = net_wm_state_on_top;
XSendEvent( XDISPLAY, DefaultRootWindow( XDISPLAY ),
False, SubstructureRedirectMask, (XEvent*)&event );
}
#endif
<|endoftext|> |
<commit_before>// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "storage/src/include/firebase/storage/storage_reference.h"
#include "app/src/assert.h"
#ifdef __APPLE__
#include "TargetConditionals.h"
#endif // __APPLE__
// StorageReference is defined in these 3 files, one implementation for each OS.
#if defined(__ANDROID__)
#include "storage/src/android/storage_android.h"
#include "storage/src/android/storage_reference_android.h"
#elif TARGET_OS_IPHONE
#include "storage/src/ios/storage_ios.h"
#include "storage/src/ios/storage_reference_ios.h"
#else
#include "storage/src/desktop/storage_desktop.h"
#include "storage/src/desktop/storage_reference_desktop.h"
#endif // defined(__ANDROID__), TARGET_OS_IPHONE
namespace firebase {
namespace storage {
static void AssertMetadataIsValid(const Metadata& metadata) {
FIREBASE_ASSERT_MESSAGE(metadata.is_valid(),
"The specified Metadata is not valid.");
}
namespace internal {
class StorageReferenceInternalCommon {
public:
static void DeleteInternal(StorageReference* storage_reference) {
StorageReferenceInternal* internal = storage_reference->internal_;
// Since this can trigger a chain of events that deletes the encompassing
// object, remove the reference to the internal implementation *before*
// deleting it so that it can't be deleted twice.
storage_reference->internal_ = nullptr;
UnregisterForCleanup(storage_reference, internal);
delete internal;
}
static void CleanupStorageReference(void* storage_reference_void) {
DeleteInternal(reinterpret_cast<StorageReference*>(storage_reference_void));
}
static void RegisterForCleanup(StorageReference* obj,
StorageReferenceInternal* internal) {
if (internal && internal->storage_internal()) {
internal->storage_internal()->cleanup().RegisterObject(
obj, CleanupStorageReference);
}
}
static void UnregisterForCleanup(StorageReference* obj,
StorageReferenceInternal* internal) {
if (internal && internal->storage_internal()) {
internal->storage_internal()->cleanup().UnregisterObject(obj);
}
}
};
} // namespace internal
using internal::StorageReferenceInternal;
using internal::StorageReferenceInternalCommon;
StorageReference::StorageReference(StorageReferenceInternal* internal)
: internal_(internal) {
StorageReferenceInternalCommon::RegisterForCleanup(this, internal_);
}
StorageReference::StorageReference(const StorageReference& other)
: internal_(other.internal_ ? new StorageReferenceInternal(*other.internal_)
: nullptr) {
StorageReferenceInternalCommon::RegisterForCleanup(this, internal_);
}
StorageReference& StorageReference::operator=(const StorageReference& other) {
StorageReferenceInternalCommon::DeleteInternal(this);
internal_ = other.internal_ ? new StorageReferenceInternal(*other.internal_)
: nullptr;
StorageReferenceInternalCommon::RegisterForCleanup(this, internal_);
return *this;
}
#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN)
StorageReference::StorageReference(StorageReference&& other) {
StorageReferenceInternalCommon::UnregisterForCleanup(&other, other.internal_);
internal_ = other.internal_;
other.internal_ = nullptr;
StorageReferenceInternalCommon::RegisterForCleanup(this, internal_);
}
StorageReference& StorageReference::operator=(StorageReference&& other) {
StorageReferenceInternalCommon::DeleteInternal(this);
StorageReferenceInternalCommon::UnregisterForCleanup(&other, other.internal_);
internal_ = other.internal_;
other.internal_ = nullptr;
StorageReferenceInternalCommon::RegisterForCleanup(this, internal_);
return *this;
}
#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN)
StorageReference::~StorageReference() {
StorageReferenceInternalCommon::DeleteInternal(this);
}
Storage* StorageReference::storage() {
return internal_ ? internal_->storage() : nullptr;
}
StorageReference StorageReference::Child(const char* path) const {
return internal_ ? StorageReference(internal_->Child(path))
: StorageReference(nullptr);
}
Future<void> StorageReference::Delete() {
return internal_ ? internal_->Delete() : Future<void>();
}
Future<void> StorageReference::DeleteLastResult() {
return internal_ ? internal_->DeleteLastResult() : Future<void>();
}
std::string StorageReference::bucket() {
return internal_ ? internal_->bucket() : std::string();
}
std::string StorageReference::full_path() {
return internal_ ? internal_->full_path() : std::string();
}
Future<size_t> StorageReference::GetFile(const char* path, Listener* listener,
Controller* controller_out) {
return internal_ ? internal_->GetFile(path, listener, controller_out)
: Future<size_t>();
}
Future<size_t> StorageReference::GetFileLastResult() {
return internal_ ? internal_->GetFileLastResult() : Future<size_t>();
}
Future<size_t> StorageReference::GetBytes(void* buffer, size_t buffer_size,
Listener* listener,
Controller* controller_out) {
return internal_ ? internal_->GetBytes(buffer, buffer_size, listener,
controller_out)
: Future<size_t>();
}
Future<size_t> StorageReference::GetBytesLastResult() {
return internal_ ? internal_->GetBytesLastResult() : Future<size_t>();
}
Future<std::string> StorageReference::GetDownloadUrl() {
return internal_ ? internal_->GetDownloadUrl() : Future<std::string>();
}
Future<std::string> StorageReference::GetDownloadUrlLastResult() {
return internal_ ? internal_->GetDownloadUrlLastResult()
: Future<std::string>();
}
Future<Metadata> StorageReference::GetMetadata() {
return internal_ ? internal_->GetMetadata() : Future<Metadata>();
}
Future<Metadata> StorageReference::GetMetadataLastResult() {
return internal_ ? internal_->GetMetadataLastResult() : Future<Metadata>();
}
Future<Metadata> StorageReference::UpdateMetadata(const Metadata& metadata) {
AssertMetadataIsValid(metadata);
return internal_ ? internal_->UpdateMetadata(&metadata) : Future<Metadata>();
}
Future<Metadata> StorageReference::UpdateMetadataLastResult() {
return internal_ ? internal_->UpdateMetadataLastResult() : Future<Metadata>();
}
std::string StorageReference::name() {
return internal_ ? internal_->name() : std::string();
}
StorageReference StorageReference::GetParent() {
return internal_ ? StorageReference(internal_->GetParent())
: StorageReference(nullptr);
}
Future<Metadata> StorageReference::PutBytes(const void* buffer,
size_t buffer_size,
Listener* listener,
Controller* controller_out) {
return internal_ ? internal_->PutBytes(buffer, buffer_size, listener,
controller_out)
: Future<Metadata>();
}
Future<Metadata> StorageReference::PutBytes(const void* buffer,
size_t buffer_size,
const Metadata& metadata,
Listener* listener,
Controller* controller_out) {
AssertMetadataIsValid(metadata);
return internal_ ? internal_->PutBytes(buffer, buffer_size, &metadata,
listener, controller_out)
: Future<Metadata>();
}
Future<Metadata> StorageReference::PutBytesLastResult() {
return internal_ ? internal_->PutBytesLastResult() : Future<Metadata>();
}
Future<Metadata> StorageReference::PutFile(const char* path, Listener* listener,
Controller* controller_out) {
return internal_ ? internal_->PutFile(path, listener, controller_out)
: Future<Metadata>();
}
Future<Metadata> StorageReference::PutFile(const char* path,
const Metadata& metadata,
Listener* listener,
Controller* controller_out) {
AssertMetadataIsValid(metadata);
return internal_
? internal_->PutFile(path, &metadata, listener, controller_out)
: Future<Metadata>();
}
Future<Metadata> StorageReference::PutFileLastResult() {
return internal_ ? internal_->PutFileLastResult() : Future<Metadata>();
}
bool StorageReference::is_valid() const { return internal_ != nullptr; }
} // namespace storage
} // namespace firebase
<commit_msg>treating tvos as ios for header includes<commit_after>// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "storage/src/include/firebase/storage/storage_reference.h"
#include "app/src/assert.h"
#ifdef __APPLE__
#include "TargetConditionals.h"
#endif // __APPLE__
// StorageReference is defined in these 3 files, one implementation for each OS.
#if defined(__ANDROID__)
#include "storage/src/android/storage_android.h"
#include "storage/src/android/storage_reference_android.h"
#elif TARGET_OS_IPHONE || TARGET_OS_TV
#include "storage/src/ios/storage_ios.h"
#include "storage/src/ios/storage_reference_ios.h"
#else
#include "storage/src/desktop/storage_desktop.h"
#include "storage/src/desktop/storage_reference_desktop.h"
#endif // defined(__ANDROID__), TARGET_OS_IPHONE
namespace firebase {
namespace storage {
static void AssertMetadataIsValid(const Metadata& metadata) {
FIREBASE_ASSERT_MESSAGE(metadata.is_valid(),
"The specified Metadata is not valid.");
}
namespace internal {
class StorageReferenceInternalCommon {
public:
static void DeleteInternal(StorageReference* storage_reference) {
StorageReferenceInternal* internal = storage_reference->internal_;
// Since this can trigger a chain of events that deletes the encompassing
// object, remove the reference to the internal implementation *before*
// deleting it so that it can't be deleted twice.
storage_reference->internal_ = nullptr;
UnregisterForCleanup(storage_reference, internal);
delete internal;
}
static void CleanupStorageReference(void* storage_reference_void) {
DeleteInternal(reinterpret_cast<StorageReference*>(storage_reference_void));
}
static void RegisterForCleanup(StorageReference* obj,
StorageReferenceInternal* internal) {
if (internal && internal->storage_internal()) {
internal->storage_internal()->cleanup().RegisterObject(
obj, CleanupStorageReference);
}
}
static void UnregisterForCleanup(StorageReference* obj,
StorageReferenceInternal* internal) {
if (internal && internal->storage_internal()) {
internal->storage_internal()->cleanup().UnregisterObject(obj);
}
}
};
} // namespace internal
using internal::StorageReferenceInternal;
using internal::StorageReferenceInternalCommon;
StorageReference::StorageReference(StorageReferenceInternal* internal)
: internal_(internal) {
StorageReferenceInternalCommon::RegisterForCleanup(this, internal_);
}
StorageReference::StorageReference(const StorageReference& other)
: internal_(other.internal_ ? new StorageReferenceInternal(*other.internal_)
: nullptr) {
StorageReferenceInternalCommon::RegisterForCleanup(this, internal_);
}
StorageReference& StorageReference::operator=(const StorageReference& other) {
StorageReferenceInternalCommon::DeleteInternal(this);
internal_ = other.internal_ ? new StorageReferenceInternal(*other.internal_)
: nullptr;
StorageReferenceInternalCommon::RegisterForCleanup(this, internal_);
return *this;
}
#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN)
StorageReference::StorageReference(StorageReference&& other) {
StorageReferenceInternalCommon::UnregisterForCleanup(&other, other.internal_);
internal_ = other.internal_;
other.internal_ = nullptr;
StorageReferenceInternalCommon::RegisterForCleanup(this, internal_);
}
StorageReference& StorageReference::operator=(StorageReference&& other) {
StorageReferenceInternalCommon::DeleteInternal(this);
StorageReferenceInternalCommon::UnregisterForCleanup(&other, other.internal_);
internal_ = other.internal_;
other.internal_ = nullptr;
StorageReferenceInternalCommon::RegisterForCleanup(this, internal_);
return *this;
}
#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN)
StorageReference::~StorageReference() {
StorageReferenceInternalCommon::DeleteInternal(this);
}
Storage* StorageReference::storage() {
return internal_ ? internal_->storage() : nullptr;
}
StorageReference StorageReference::Child(const char* path) const {
return internal_ ? StorageReference(internal_->Child(path))
: StorageReference(nullptr);
}
Future<void> StorageReference::Delete() {
return internal_ ? internal_->Delete() : Future<void>();
}
Future<void> StorageReference::DeleteLastResult() {
return internal_ ? internal_->DeleteLastResult() : Future<void>();
}
std::string StorageReference::bucket() {
return internal_ ? internal_->bucket() : std::string();
}
std::string StorageReference::full_path() {
return internal_ ? internal_->full_path() : std::string();
}
Future<size_t> StorageReference::GetFile(const char* path, Listener* listener,
Controller* controller_out) {
return internal_ ? internal_->GetFile(path, listener, controller_out)
: Future<size_t>();
}
Future<size_t> StorageReference::GetFileLastResult() {
return internal_ ? internal_->GetFileLastResult() : Future<size_t>();
}
Future<size_t> StorageReference::GetBytes(void* buffer, size_t buffer_size,
Listener* listener,
Controller* controller_out) {
return internal_ ? internal_->GetBytes(buffer, buffer_size, listener,
controller_out)
: Future<size_t>();
}
Future<size_t> StorageReference::GetBytesLastResult() {
return internal_ ? internal_->GetBytesLastResult() : Future<size_t>();
}
Future<std::string> StorageReference::GetDownloadUrl() {
return internal_ ? internal_->GetDownloadUrl() : Future<std::string>();
}
Future<std::string> StorageReference::GetDownloadUrlLastResult() {
return internal_ ? internal_->GetDownloadUrlLastResult()
: Future<std::string>();
}
Future<Metadata> StorageReference::GetMetadata() {
return internal_ ? internal_->GetMetadata() : Future<Metadata>();
}
Future<Metadata> StorageReference::GetMetadataLastResult() {
return internal_ ? internal_->GetMetadataLastResult() : Future<Metadata>();
}
Future<Metadata> StorageReference::UpdateMetadata(const Metadata& metadata) {
AssertMetadataIsValid(metadata);
return internal_ ? internal_->UpdateMetadata(&metadata) : Future<Metadata>();
}
Future<Metadata> StorageReference::UpdateMetadataLastResult() {
return internal_ ? internal_->UpdateMetadataLastResult() : Future<Metadata>();
}
std::string StorageReference::name() {
return internal_ ? internal_->name() : std::string();
}
StorageReference StorageReference::GetParent() {
return internal_ ? StorageReference(internal_->GetParent())
: StorageReference(nullptr);
}
Future<Metadata> StorageReference::PutBytes(const void* buffer,
size_t buffer_size,
Listener* listener,
Controller* controller_out) {
return internal_ ? internal_->PutBytes(buffer, buffer_size, listener,
controller_out)
: Future<Metadata>();
}
Future<Metadata> StorageReference::PutBytes(const void* buffer,
size_t buffer_size,
const Metadata& metadata,
Listener* listener,
Controller* controller_out) {
AssertMetadataIsValid(metadata);
return internal_ ? internal_->PutBytes(buffer, buffer_size, &metadata,
listener, controller_out)
: Future<Metadata>();
}
Future<Metadata> StorageReference::PutBytesLastResult() {
return internal_ ? internal_->PutBytesLastResult() : Future<Metadata>();
}
Future<Metadata> StorageReference::PutFile(const char* path, Listener* listener,
Controller* controller_out) {
return internal_ ? internal_->PutFile(path, listener, controller_out)
: Future<Metadata>();
}
Future<Metadata> StorageReference::PutFile(const char* path,
const Metadata& metadata,
Listener* listener,
Controller* controller_out) {
AssertMetadataIsValid(metadata);
return internal_
? internal_->PutFile(path, &metadata, listener, controller_out)
: Future<Metadata>();
}
Future<Metadata> StorageReference::PutFileLastResult() {
return internal_ ? internal_->PutFileLastResult() : Future<Metadata>();
}
bool StorageReference::is_valid() const { return internal_ != nullptr; }
} // namespace storage
} // namespace firebase
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <fstream>
#include <sstream>
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
#include "bgp/bgp_factory.h"
#include "bgp/bgp_membership.h"
#include "bgp/bgp_session_manager.h"
#include "bgp/bgp_xmpp_channel.h"
#include "bgp/test/bgp_server_test_util.h"
#include "bgp/xmpp_message_builder.h"
#include "control-node/control_node.h"
#include "control-node/test/network_agent_mock.h"
#include "io/test/event_manager_test.h"
#include "xmpp/xmpp_init.h"
using namespace boost::asio;
using namespace std;
using namespace autogen;
#define SUB_ADDR "agent@vnsw.contrailsystems.com"
#define XMPP_CONTROL_SERV "bgp.contrail.com"
#define PUBSUB_NODE_ADDR "bgp-node.contrail.com"
class XmppChannelMuxMock : public XmppChannelMux {
public:
XmppChannelMuxMock(XmppConnection *conn) : XmppChannelMux(conn), count_(0) {
}
virtual bool Send(const uint8_t *msg, size_t msgsize,
const string *msg_str, xmps::PeerId id, SendReadyCb cb) {
bool ret;
// Simulate write blocked after the first message is sent.
ret = XmppChannelMux::Send(msg, msgsize, msg_str, id, cb);
assert(ret);
if (++count_ == 1) {
XmppChannelMux::RegisterWriteReady(id, cb);
return false;
}
return true;
}
virtual bool Send(const uint8_t *msg, size_t msgsize, xmps::PeerId id,
SendReadyCb cb) {
return Send(msg, msgsize, NULL, id, cb);
}
private:
int count_;
};
class BgpXmppChannelMock : public BgpXmppChannel {
public:
BgpXmppChannelMock(XmppChannel *channel, BgpServer *server,
BgpXmppChannelManager *manager) :
BgpXmppChannel(channel, server, manager), count_(0) {
bgp_policy_ = RibExportPolicy(BgpProto::XMPP,
RibExportPolicy::XMPP, -1, 0);
}
virtual void ReceiveUpdate(const XmppStanza::XmppMessage *msg) {
count_ ++;
BgpXmppChannel::ReceiveUpdate(msg);
}
XmppChannel *xmpp_channel() { return channel_; }
size_t Count() const { return count_; }
void ResetCount() { count_ = 0; }
virtual ~BgpXmppChannelMock() { }
private:
size_t count_;
};
class XmppVnswBgpMockChannel : public BgpXmppChannel {
public:
XmppVnswBgpMockChannel(XmppChannel *channel, BgpServer *bgp_server,
BgpXmppChannelManager *channel_manager)
: BgpXmppChannel(channel, bgp_server, channel_manager), count_(0) { }
virtual void ReceiveUpdate(const XmppStanza::XmppMessage *msg) {
count_++;
}
size_t Count() const { return count_; }
void ResetCount() { count_ = 0; }
private:
size_t count_;
};
class BgpXmppChannelManagerMock : public BgpXmppChannelManager {
public:
BgpXmppChannelManagerMock(XmppServer *x, BgpServer *b) :
BgpXmppChannelManager(x, b), count_(0), channel_(NULL),
xmpp_mux_ch_(NULL) { }
virtual ~BgpXmppChannelManagerMock() {
}
virtual void XmppHandleChannelEvent(XmppChannel *channel,
xmps::PeerState state) {
if (xmpp_mux_ch_ == NULL) {
XmppChannelMux *mux = static_cast<XmppChannelMux *>(channel);
xmpp_mux_ch_ = new XmppChannelMuxMock(mux->connection());
//
// Update the channel stored in bgp_xmpp_channel to this new mock
// channel. Old gets deleted via auto_ptr
//
mux->connection()->SetChannelMux(xmpp_mux_ch_);
}
//
// Register Mock XmppChannelMux with bgp
//
XmppChannel *ch = static_cast<XmppChannel *>(xmpp_mux_ch_);
BgpXmppChannelManager::XmppHandleChannelEvent(ch, state);
}
virtual BgpXmppChannel *CreateChannel(XmppChannel *channel) {
channel_ = new BgpXmppChannelMock(channel, bgp_server_, this);
return channel_;
}
void XmppVisit(BgpXmppChannel *channel) {
count_++;
}
int Count() {
count_ = 0;
VisitChannels(boost::bind(&BgpXmppChannelManagerMock::XmppVisit,
this, _1));
return count_;
}
int count_;
BgpXmppChannelMock *channel_;
XmppChannelMuxMock *xmpp_mux_ch_;
};
class BgpXmppUnitTest : public ::testing::Test {
protected:
static const char *config_tmpl;
BgpXmppUnitTest() : thread_(&evm_) { }
string FileRead(const string &filename) {
ifstream file(filename.c_str());
string content((istreambuf_iterator<char>(file)),
istreambuf_iterator<char>());
return content;
}
virtual void SetUp() {
a_.reset(new BgpServerTest(&evm_, "A"));
xs_a_ = new XmppServer(&evm_, XMPP_CONTROL_SERV);
a_->session_manager()->Initialize(0);
BGP_DEBUG_UT("Created server at port: " <<
a_->session_manager()->GetPort());
xs_a_->Initialize(0, false);
bgp_channel_manager_ = new BgpXmppChannelManagerMock(xs_a_, a_.get());
thread_.Start();
}
virtual void TearDown() {
agent_a_->Delete();
task_util::WaitForIdle();
xs_a_->Shutdown();
task_util::WaitForIdle();
a_->Shutdown();
task_util::WaitForIdle();
delete bgp_channel_manager_;
task_util::WaitForIdle();
TcpServerManager::DeleteServer(xs_a_);
xs_a_ = NULL;
evm_.Shutdown();
task_util::WaitForIdle();
thread_.Join();
}
void Configure() {
char config[4096];
snprintf(config, sizeof(config), config_tmpl,
a_->session_manager()->GetPort());
a_->Configure(config);
}
XmppChannelConfig *CreateXmppChannelCfg(const char *address, int port,
const string &from,
const string &to,
bool isClient) {
XmppChannelConfig *cfg = new XmppChannelConfig(isClient);
boost::system::error_code ec;
cfg->endpoint.address(ip::address::from_string(address, ec));
cfg->endpoint.port(port);
cfg->ToAddr = to;
cfg->FromAddr = from;
if (!isClient) cfg->NodeAddr = PUBSUB_NODE_ADDR;
return cfg;
}
EventManager evm_;
ServerThread thread_;
auto_ptr<BgpServerTest> a_;
XmppServer *xs_a_;
boost::scoped_ptr<test::NetworkAgentMock> agent_a_;
BgpXmppChannelManagerMock *bgp_channel_manager_;
XmppVnswBgpMockChannel *xmpp_cchannel_;
static int validate_done_;
};
int BgpXmppUnitTest::validate_done_;
const char *BgpXmppUnitTest::config_tmpl = "\
<config>\
<bgp-router name=\'A\'>\
<identifier>192.168.0.1</identifier>\
<address>127.0.0.1</address>\
<port>%d</port>\
</bgp-router>\
<routing-instance name='blue'>\
<vrf-target>target:1:1</vrf-target>\
</routing-instance>\
<routing-instance name='red'>\
<vrf-target>target:1:1</vrf-target>\
</routing-instance>\
</config>\
";
#define WAIT_EQ(expected, actual) \
TASK_UTIL_EXPECT_EQ(expected, actual)
#define WAIT_NE(expected, actual) \
TASK_UTIL_EXPECT_NE(expected, actual)
namespace {
TEST_F(BgpXmppUnitTest, WriteReadyTest) {
Configure();
task_util::WaitForIdle();
// create an XMPP client in server A
agent_a_.reset(
new test::NetworkAgentMock(&evm_, SUB_ADDR, xs_a_->GetPort()));
// Wait upto 1 sec
WAIT_EQ(1, bgp_channel_manager_->Count());
BGP_DEBUG_UT("-- Executing --");
WAIT_NE(static_cast<BgpXmppChannelMock *>(NULL),
bgp_channel_manager_->channel_);
WAIT_EQ(xmps::READY,
bgp_channel_manager_->channel_->xmpp_channel()->GetPeerState());
agent_a_->Subscribe(BgpConfigManager::kMasterInstance, -1);
WAIT_EQ(1, bgp_channel_manager_->channel_->Count());
BGP_DEBUG_UT("Received subscribe message for default at Server \n ");
agent_a_->Subscribe("blue", 1);
WAIT_EQ(2, bgp_channel_manager_->channel_->Count());
BGP_DEBUG_UT("Received subscribe message for blue at Server \n ");
agent_a_->Subscribe("red", 2);
WAIT_EQ(3, bgp_channel_manager_->channel_->Count());
BGP_DEBUG_UT("Received subscribe message for red at Server \n ");
agent_a_->AddRoute("blue","10.1.1.1/32");
WAIT_EQ(4, bgp_channel_manager_->channel_->Count());
BGP_DEBUG_UT("Received route for blue at Server \n ");
agent_a_->AddRoute("red","20.1.1.1/32");
WAIT_EQ(5, bgp_channel_manager_->channel_->Count());
BGP_DEBUG_UT("Received route for red at Server \n ");
// send blocked, no route should be reflected back after the first one.
// check a few times to make sure that no more routes are reflected
for (int idx = 0; idx < 10; ++idx) {
WAIT_EQ(1, agent_a_->RouteCount());
usleep(10000);
task_util::WaitForIdle();
}
// simulate write unblocked
XmppConnection *sconnection = xs_a_->FindConnection(SUB_ADDR);
const boost::system::error_code ec;
sconnection->ChannelMux()->WriteReady(ec);
// simulated send block after first send, hence subsequent routes
// reflected back to the Xmpp vnsw client only now, through WriteReady()
WAIT_EQ(4, agent_a_->RouteCount());
// route reflected back + leaked
TASK_UTIL_ASSERT_TRUE(agent_a_->RouteLookup("blue", "10.1.1.1/32") != NULL);
TASK_UTIL_ASSERT_TRUE(agent_a_->RouteLookup("blue", "20.1.1.1/32") != NULL);
TASK_UTIL_ASSERT_TRUE(agent_a_->RouteLookup("red", "10.1.1.1/32") != NULL);
TASK_UTIL_ASSERT_TRUE(agent_a_->RouteLookup("red", "20.1.1.1/32") != NULL);
//trigger a TCP close event on the server
agent_a_->SessionDown();
usleep(50);
task_util::WaitForIdle();
}
}
class TestEnvironment : public ::testing::Environment {
virtual ~TestEnvironment() { }
virtual void SetUp() {
}
virtual void TearDown() {
}
};
static void SetUp() {
DB::SetPartitionCount(1);
BgpServer::Initialize();
ControlNode::SetDefaultSchedulingPolicy();
BgpServerTest::GlobalSetUp();
BgpObjectFactory::Register<BgpXmppMessageBuilder>(
boost::factory<BgpXmppMessageBuilder *>());
}
static void TearDown() {
BgpServer::Terminate();
TaskScheduler *scheduler = TaskScheduler::GetInstance();
scheduler->Terminate();
}
int main(int argc, char **argv) {
bgp_log_test::init();
::testing::InitGoogleTest(&argc, argv);
::testing::AddGlobalTestEnvironment(new TestEnvironment());
SetUp();
int result = RUN_ALL_TESTS();
TearDown();
return result;
}
<commit_msg>Stabilize bgp_xmpp_wready unit test<commit_after>/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <fstream>
#include <sstream>
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
#include "bgp/bgp_factory.h"
#include "bgp/bgp_membership.h"
#include "bgp/bgp_session_manager.h"
#include "bgp/bgp_xmpp_channel.h"
#include "bgp/test/bgp_server_test_util.h"
#include "bgp/xmpp_message_builder.h"
#include "control-node/control_node.h"
#include "control-node/test/network_agent_mock.h"
#include "io/test/event_manager_test.h"
#include "xmpp/xmpp_init.h"
using namespace boost::asio;
using namespace std;
using namespace autogen;
#define SUB_ADDR "agent@vnsw.contrailsystems.com"
#define XMPP_CONTROL_SERV "bgp.contrail.com"
#define PUBSUB_NODE_ADDR "bgp-node.contrail.com"
class XmppChannelMuxMock : public XmppChannelMux {
public:
XmppChannelMuxMock(XmppConnection *conn) : XmppChannelMux(conn), count_(0) {
}
virtual bool Send(const uint8_t *msg, size_t msgsize,
const string *msg_str, xmps::PeerId id, SendReadyCb cb) {
bool ret;
// Simulate write blocked after the first message is sent.
ret = XmppChannelMux::Send(msg, msgsize, msg_str, id, cb);
assert(ret);
if (++count_ == 1) {
XmppChannelMux::RegisterWriteReady(id, cb);
return false;
}
return true;
}
virtual bool Send(const uint8_t *msg, size_t msgsize, xmps::PeerId id,
SendReadyCb cb) {
return Send(msg, msgsize, NULL, id, cb);
}
private:
int count_;
};
class BgpXmppChannelMock : public BgpXmppChannel {
public:
BgpXmppChannelMock(XmppChannel *channel, BgpServer *server,
BgpXmppChannelManager *manager) :
BgpXmppChannel(channel, server, manager), count_(0) {
bgp_policy_ = RibExportPolicy(BgpProto::XMPP,
RibExportPolicy::XMPP, -1, 0);
}
virtual void ReceiveUpdate(const XmppStanza::XmppMessage *msg) {
count_ ++;
BgpXmppChannel::ReceiveUpdate(msg);
}
XmppChannel *xmpp_channel() { return channel_; }
size_t Count() const { return count_; }
void ResetCount() { count_ = 0; }
virtual ~BgpXmppChannelMock() { }
private:
size_t count_;
};
class XmppVnswBgpMockChannel : public BgpXmppChannel {
public:
XmppVnswBgpMockChannel(XmppChannel *channel, BgpServer *bgp_server,
BgpXmppChannelManager *channel_manager)
: BgpXmppChannel(channel, bgp_server, channel_manager), count_(0) { }
virtual void ReceiveUpdate(const XmppStanza::XmppMessage *msg) {
count_++;
}
size_t Count() const { return count_; }
void ResetCount() { count_ = 0; }
private:
size_t count_;
};
class BgpXmppChannelManagerMock : public BgpXmppChannelManager {
public:
BgpXmppChannelManagerMock(XmppServer *x, BgpServer *b) :
BgpXmppChannelManager(x, b), count_(0), channel_(NULL),
xmpp_mux_ch_(NULL) { }
virtual ~BgpXmppChannelManagerMock() {
}
virtual void XmppHandleChannelEvent(XmppChannel *channel,
xmps::PeerState state) {
if (xmpp_mux_ch_ == NULL) {
XmppChannelMux *mux = static_cast<XmppChannelMux *>(channel);
xmpp_mux_ch_ = new XmppChannelMuxMock(mux->connection());
//
// Update the channel stored in bgp_xmpp_channel to this new mock
// channel. Old gets deleted via auto_ptr
//
mux->connection()->SetChannelMux(xmpp_mux_ch_);
}
//
// Register Mock XmppChannelMux with bgp
//
XmppChannel *ch = static_cast<XmppChannel *>(xmpp_mux_ch_);
BgpXmppChannelManager::XmppHandleChannelEvent(ch, state);
}
virtual BgpXmppChannel *CreateChannel(XmppChannel *channel) {
channel_ = new BgpXmppChannelMock(channel, bgp_server_, this);
return channel_;
}
void XmppVisit(BgpXmppChannel *channel) {
count_++;
}
int Count() {
count_ = 0;
VisitChannels(boost::bind(&BgpXmppChannelManagerMock::XmppVisit,
this, _1));
return count_;
}
int count_;
BgpXmppChannelMock *channel_;
XmppChannelMuxMock *xmpp_mux_ch_;
};
class BgpXmppUnitTest : public ::testing::Test {
protected:
static const char *config_tmpl;
BgpXmppUnitTest() : thread_(&evm_) { }
string FileRead(const string &filename) {
ifstream file(filename.c_str());
string content((istreambuf_iterator<char>(file)),
istreambuf_iterator<char>());
return content;
}
virtual void SetUp() {
a_.reset(new BgpServerTest(&evm_, "A"));
xs_a_ = new XmppServer(&evm_, XMPP_CONTROL_SERV);
a_->session_manager()->Initialize(0);
BGP_DEBUG_UT("Created server at port: " <<
a_->session_manager()->GetPort());
xs_a_->Initialize(0, false);
bgp_channel_manager_ = new BgpXmppChannelManagerMock(xs_a_, a_.get());
thread_.Start();
}
virtual void TearDown() {
agent_a_->Delete();
task_util::WaitForIdle();
xs_a_->Shutdown();
task_util::WaitForIdle();
a_->Shutdown();
task_util::WaitForIdle();
delete bgp_channel_manager_;
task_util::WaitForIdle();
TcpServerManager::DeleteServer(xs_a_);
xs_a_ = NULL;
evm_.Shutdown();
task_util::WaitForIdle();
thread_.Join();
}
void Configure() {
char config[4096];
snprintf(config, sizeof(config), config_tmpl,
a_->session_manager()->GetPort());
a_->Configure(config);
}
XmppChannelConfig *CreateXmppChannelCfg(const char *address, int port,
const string &from,
const string &to,
bool isClient) {
XmppChannelConfig *cfg = new XmppChannelConfig(isClient);
boost::system::error_code ec;
cfg->endpoint.address(ip::address::from_string(address, ec));
cfg->endpoint.port(port);
cfg->ToAddr = to;
cfg->FromAddr = from;
if (!isClient) cfg->NodeAddr = PUBSUB_NODE_ADDR;
return cfg;
}
EventManager evm_;
ServerThread thread_;
auto_ptr<BgpServerTest> a_;
XmppServer *xs_a_;
boost::scoped_ptr<test::NetworkAgentMock> agent_a_;
BgpXmppChannelManagerMock *bgp_channel_manager_;
XmppVnswBgpMockChannel *xmpp_cchannel_;
static int validate_done_;
};
int BgpXmppUnitTest::validate_done_;
const char *BgpXmppUnitTest::config_tmpl = "\
<config>\
<bgp-router name=\'A\'>\
<identifier>192.168.0.1</identifier>\
<address>127.0.0.1</address>\
<port>%d</port>\
</bgp-router>\
<routing-instance name='blue'>\
<vrf-target>target:1:1</vrf-target>\
</routing-instance>\
<routing-instance name='red'>\
<vrf-target>target:1:1</vrf-target>\
</routing-instance>\
</config>\
";
#define WAIT_EQ(expected, actual) \
TASK_UTIL_EXPECT_EQ(expected, actual)
#define WAIT_NE(expected, actual) \
TASK_UTIL_EXPECT_NE(expected, actual)
namespace {
TEST_F(BgpXmppUnitTest, WriteReadyTest) {
Configure();
task_util::WaitForIdle();
// create an XMPP client in server A
agent_a_.reset(
new test::NetworkAgentMock(&evm_, SUB_ADDR, xs_a_->GetPort()));
// Wait upto 1 sec
WAIT_EQ(1, bgp_channel_manager_->Count());
BGP_DEBUG_UT("-- Executing --");
WAIT_NE(static_cast<BgpXmppChannelMock *>(NULL),
bgp_channel_manager_->channel_);
WAIT_EQ(xmps::READY,
bgp_channel_manager_->channel_->xmpp_channel()->GetPeerState());
agent_a_->Subscribe(BgpConfigManager::kMasterInstance, -1);
WAIT_EQ(1, bgp_channel_manager_->channel_->Count());
BGP_DEBUG_UT("Received subscribe message for default at Server \n ");
agent_a_->Subscribe("blue", 1);
WAIT_EQ(2, bgp_channel_manager_->channel_->Count());
BGP_DEBUG_UT("Received subscribe message for blue at Server \n ");
agent_a_->Subscribe("red", 2);
WAIT_EQ(3, bgp_channel_manager_->channel_->Count());
BGP_DEBUG_UT("Received subscribe message for red at Server \n ");
agent_a_->AddRoute("blue","10.1.1.1/32");
WAIT_EQ(4, bgp_channel_manager_->channel_->Count());
BGP_DEBUG_UT("Received route for blue at Server \n ");
// We may receive one or two routes depending on when the write-block
// takes effect.
TASK_UTIL_EXPECT_GE(2, agent_a_->RouteCount());
agent_a_->AddRoute("red","20.1.1.1/32");
WAIT_EQ(5, bgp_channel_manager_->channel_->Count());
BGP_DEBUG_UT("Received route for red at Server \n ");
// send blocked, no route should be reflected back after the first one
// or two. check a few times to make sure that no more routes are reflected.
for (int idx = 0; idx < 10; ++idx) {
TASK_UTIL_EXPECT_GE(2, agent_a_->RouteCount());
usleep(10000);
task_util::WaitForIdle();
}
// simulate write unblocked
XmppConnection *sconnection = xs_a_->FindConnection(SUB_ADDR);
const boost::system::error_code ec;
sconnection->ChannelMux()->WriteReady(ec);
// simulated send block after first send, hence subsequent routes
// reflected back to the Xmpp vnsw client only now, through WriteReady()
WAIT_EQ(4, agent_a_->RouteCount());
// route reflected back + leaked
TASK_UTIL_ASSERT_TRUE(agent_a_->RouteLookup("blue", "10.1.1.1/32") != NULL);
TASK_UTIL_ASSERT_TRUE(agent_a_->RouteLookup("blue", "20.1.1.1/32") != NULL);
TASK_UTIL_ASSERT_TRUE(agent_a_->RouteLookup("red", "10.1.1.1/32") != NULL);
TASK_UTIL_ASSERT_TRUE(agent_a_->RouteLookup("red", "20.1.1.1/32") != NULL);
//trigger a TCP close event on the server
agent_a_->SessionDown();
usleep(50);
task_util::WaitForIdle();
}
}
class TestEnvironment : public ::testing::Environment {
virtual ~TestEnvironment() { }
virtual void SetUp() {
}
virtual void TearDown() {
}
};
static void SetUp() {
DB::SetPartitionCount(1);
BgpServer::Initialize();
ControlNode::SetDefaultSchedulingPolicy();
BgpServerTest::GlobalSetUp();
BgpObjectFactory::Register<BgpXmppMessageBuilder>(
boost::factory<BgpXmppMessageBuilder *>());
}
static void TearDown() {
BgpServer::Terminate();
TaskScheduler *scheduler = TaskScheduler::GetInstance();
scheduler->Terminate();
}
int main(int argc, char **argv) {
bgp_log_test::init();
::testing::InitGoogleTest(&argc, argv);
::testing::AddGlobalTestEnvironment(new TestEnvironment());
SetUp();
int result = RUN_ALL_TESTS();
TearDown();
return result;
}
<|endoftext|> |
<commit_before>#include <sys/inotify.h>
#include <cstdint>
#include <string>
#include "envoy/common/exception.h"
#include "envoy/event/dispatcher.h"
#include "envoy/event/file_event.h"
#include "common/common/assert.h"
#include "common/common/fmt.h"
#include "common/common/utility.h"
#include "common/filesystem/watcher_impl.h"
namespace Envoy {
namespace Filesystem {
WatcherImpl::WatcherImpl(Event::Dispatcher& dispatcher)
: inotify_fd_(inotify_init1(IN_NONBLOCK)),
inotify_event_(dispatcher.createFileEvent(inotify_fd_,
[this](uint32_t events) -> void {
ASSERT(events == Event::FileReadyType::Read);
onInotifyEvent();
},
Event::FileTriggerType::Edge,
Event::FileReadyType::Read)) {}
WatcherImpl::~WatcherImpl() { close(inotify_fd_); }
void WatcherImpl::addWatch(const std::string& path, uint32_t events, OnChangedCb callback) {
// Because of general inotify pain, we always watch the directory that the file lives in,
// and then synthetically raise per file events.
size_t last_slash = path.rfind('/');
if (last_slash == std::string::npos) {
throw EnvoyException(fmt::format("invalid watch path {}", path));
}
std::string directory = last_slash != 0 ? path.substr(0, last_slash) : "/";
std::string file = StringUtil::subspan(path, last_slash + 1, path.size());
int watch_fd = inotify_add_watch(inotify_fd_, directory.c_str(), IN_ALL_EVENTS);
if (watch_fd == -1) {
throw EnvoyException(
fmt::format("unable to add filesystem watch for file {}: {}", path, strerror(errno)));
}
ENVOY_LOG(debug, "added watch for directory: '{}' file: '{}' fd: {}", directory, file, watch_fd);
callback_map_[watch_fd].watches_.push_back({file, events, callback});
}
void WatcherImpl::onInotifyEvent() {
while (true) {
uint8_t buffer[sizeof(inotify_event) + NAME_MAX + 1];
ssize_t rc = read(inotify_fd_, &buffer, sizeof(buffer));
if (rc == -1 && errno == EAGAIN) {
return;
}
RELEASE_ASSERT(rc >= 0);
const size_t event_count = rc;
size_t index = 0;
while (index < event_count) {
inotify_event* file_event = reinterpret_cast<inotify_event*>(&buffer[index]);
ASSERT(callback_map_.count(file_event->wd) == 1);
std::string file;
if (file_event->len > 0) {
file.assign(file_event->name);
}
ENVOY_LOG(debug, "notification: fd: {} mask: {:x} file: {}", file_event->wd, file_event->mask,
file);
uint32_t events = 0;
if (file_event->mask & IN_MOVED_TO) {
events |= Events::MovedTo;
}
for (FileWatch& watch : callback_map_[file_event->wd].watches_) {
if (watch.file_ == file && (watch.events_ & events)) {
ENVOY_LOG(debug, "matched callback: file: {}", file);
watch.cb_(events);
}
}
index += sizeof(inotify_event) + file_event->len;
}
}
}
} // namespace Filesystem
} // namespace Envoy
<commit_msg>ensure the inotify fd is valid (#2977)<commit_after>#include <sys/inotify.h>
#include <cstdint>
#include <string>
#include "envoy/common/exception.h"
#include "envoy/event/dispatcher.h"
#include "envoy/event/file_event.h"
#include "common/common/assert.h"
#include "common/common/fmt.h"
#include "common/common/utility.h"
#include "common/filesystem/watcher_impl.h"
namespace Envoy {
namespace Filesystem {
WatcherImpl::WatcherImpl(Event::Dispatcher& dispatcher)
: inotify_fd_(inotify_init1(IN_NONBLOCK)),
inotify_event_(dispatcher.createFileEvent(inotify_fd_,
[this](uint32_t events) -> void {
ASSERT(events == Event::FileReadyType::Read);
onInotifyEvent();
},
Event::FileTriggerType::Edge,
Event::FileReadyType::Read)) {
RELEASE_ASSERT(inotify_fd_ >= 0);
}
WatcherImpl::~WatcherImpl() { close(inotify_fd_); }
void WatcherImpl::addWatch(const std::string& path, uint32_t events, OnChangedCb callback) {
// Because of general inotify pain, we always watch the directory that the file lives in,
// and then synthetically raise per file events.
size_t last_slash = path.rfind('/');
if (last_slash == std::string::npos) {
throw EnvoyException(fmt::format("invalid watch path {}", path));
}
std::string directory = last_slash != 0 ? path.substr(0, last_slash) : "/";
std::string file = StringUtil::subspan(path, last_slash + 1, path.size());
int watch_fd = inotify_add_watch(inotify_fd_, directory.c_str(), IN_ALL_EVENTS);
if (watch_fd == -1) {
throw EnvoyException(
fmt::format("unable to add filesystem watch for file {}: {}", path, strerror(errno)));
}
ENVOY_LOG(debug, "added watch for directory: '{}' file: '{}' fd: {}", directory, file, watch_fd);
callback_map_[watch_fd].watches_.push_back({file, events, callback});
}
void WatcherImpl::onInotifyEvent() {
while (true) {
uint8_t buffer[sizeof(inotify_event) + NAME_MAX + 1];
ssize_t rc = read(inotify_fd_, &buffer, sizeof(buffer));
if (rc == -1 && errno == EAGAIN) {
return;
}
RELEASE_ASSERT(rc >= 0);
const size_t event_count = rc;
size_t index = 0;
while (index < event_count) {
inotify_event* file_event = reinterpret_cast<inotify_event*>(&buffer[index]);
ASSERT(callback_map_.count(file_event->wd) == 1);
std::string file;
if (file_event->len > 0) {
file.assign(file_event->name);
}
ENVOY_LOG(debug, "notification: fd: {} mask: {:x} file: {}", file_event->wd, file_event->mask,
file);
uint32_t events = 0;
if (file_event->mask & IN_MOVED_TO) {
events |= Events::MovedTo;
}
for (FileWatch& watch : callback_map_[file_event->wd].watches_) {
if (watch.file_ == file && (watch.events_ & events)) {
ENVOY_LOG(debug, "matched callback: file: {}", file);
watch.cb_(events);
}
}
index += sizeof(inotify_event) + file_event->len;
}
}
}
} // namespace Filesystem
} // namespace Envoy
<|endoftext|> |
<commit_before>// $Id$
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-11 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Common Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin bthread_team.cpp$$
$spell
bthread
$$
$index bthread, AD team$$
$index AD, bthread team$$
$index team, AD bthread$$
$section Boost Thread Implementation of a Team of AD Threads$$
See $cref thread_team.hpp$$ for this routines specifications.
$code
$verbatim%multi_thread/bthread/bthread_team.cpp%0%// BEGIN PROGRAM%// END PROGRAM%1%$$
$$
$end
*/
// BEGIN PROGRAM
# include <boost/thread.hpp>
# include <cppad/cppad.hpp>
# include "../thread_team.hpp"
# define MAX_NUMBER_THREADS 48
namespace {
// number of threads in the team
size_t num_threads_ = 1;
// type of the job currently being done by each thread
enum thread_job_t { init_enum, work_enum, join_enum } thread_job_;
// barrier used to wait for other threads to finish work
boost::barrier* wait_for_work_ = 0;
// barrier used to wait for master thread to set next job
boost::barrier* wait_for_job_ = 0;
// Are we in sequential mode; i.e., other threads are waiting for
// master thread to set up next job ?
bool sequential_execution_ = true;
// structure with information for one thread
typedef struct {
boost::thread* bthread;
// Boost unique identifier for thread that uses this struct
boost::thread::id bthread_id;
// true if no error for this thread, false otherwise.
bool ok;
} thread_one_t;
// vector with information for all threads
thread_one_t thread_all_[MAX_NUMBER_THREADS];
// pointer to function that does the work for one thread
void (* worker_)(void) = 0;
// ---------------------------------------------------------------------
// in_parallel()
bool in_parallel(void)
{ return ! sequential_execution_; }
// ---------------------------------------------------------------------
// thread_number()
size_t thread_number(void)
{ using boost::thread;
// bthread unique identifier for this thread
thread::id thread_this = boost::this_thread::get_id();
// convert thread_this to the corresponding thread_num
size_t thread_num = 0;
for(thread_num = 0; thread_num < num_threads_; thread_num++)
{ // Boost unique identifier for this thread_num
thread::id thread_compare = thread_all_[thread_num].bthread_id;
// check for a match
if( thread_this == thread_compare )
return thread_num;
}
// no match error (thread_this is not in thread_all_).
std::cerr << "thread_number: unknown boost::thread::id" << std::endl;
exit(1);
return 0;
}
// --------------------------------------------------------------------
// function that gets called by boost thread constructor
void thread_work(size_t thread_num)
{ bool ok = wait_for_work_ != 0;
ok &= wait_for_job_ != 0;
thread_all_[thread_num].ok &= ok;
// In the special case where thread_job_ is join_enum,
// there are no more calls to wait_for_work_ or wait_for_job_.
while( thread_job_ != join_enum )
{ switch( thread_job_ )
{
case init_enum:
break;
case work_enum:
worker_();
break;
default:
std::cerr << "thread_work: default case" << std::endl;
exit(1);
}
// All threads make a call to wait_for_work_
wait_for_work_->wait();
// If this is the master, exit the loop.
// Master thread must make a call to wait_for_job_ elsewhere.
if( thread_num == 0 )
return;
// All but the master thread make a call to wait_for_job_
wait_for_job_->wait();
}
return;
}
}
bool start_team(size_t num_threads)
{ using CppAD::thread_alloc;
bool ok = true;;
if( num_threads > MAX_NUMBER_THREADS )
{ std::cerr << "start_team: num_threads greater than ";
std::cerr << MAX_NUMBER_THREADS << std::endl;
exit(1);
}
// check that we currently do not have multiple threads running
ok = num_threads_ == 1;
ok &= wait_for_work_ == 0;
ok &= wait_for_job_ == 0;
ok &= sequential_execution_;
// Set the information for this thread so thread_number will work
// for call to parallel_setup
thread_all_[0].bthread_id = boost::this_thread::get_id();
thread_all_[0].bthread = 0; // not used
thread_all_[0].ok = true;
// Now that thread_number() has necessary information for the case
// num_threads_ == 1, and while still in sequential mode,
// call setup for using CppAD::AD<double> in parallel mode.
thread_alloc::parallel_setup(num_threads, in_parallel, thread_number);
CppAD::parallel_ad<double>();
// now change num_threads_ to its final value.
num_threads_ = num_threads;
// initialize two barriers, one for work done, one for new job ready
wait_for_work_ = new boost::barrier(num_threads);
wait_for_job_ = new boost::barrier(num_threads);
// initial job for the threads
thread_job_ = init_enum;
if( num_threads > 1 )
sequential_execution_ = false;
// This master thread is already running, we need to create
// num_threads - 1 more threads
size_t thread_num;
for(thread_num = 1; thread_num < num_threads; thread_num++)
{ thread_all_[thread_num].ok = true;
// Create the thread with thread number equal to thread_num
thread_all_[thread_num].bthread =
new boost::thread(thread_work, thread_num);
thread_all_[thread_num].bthread_id =
thread_all_[thread_num].bthread->get_id();
}
// do work using this thread and then wait
// until all threads have completed wait_for_work_
thread_work(0); // this thread is number zero (master)
// Current state is all threads have completed wait_for_work_,
// and are at wait_for_job_.
// This master thread (thread zero) has not completed wait_for_job_
sequential_execution_ = true;
for(thread_num = 0; thread_num < num_threads; thread_num++)
ok &= thread_all_[thread_num].ok;
return ok;
}
bool work_team(void worker(void))
{
// Current state is all threads have completed wait_for_work_,
// and are at wait_for_job_.
// This master thread (thread zero) has not completed wait_for_job_
bool ok = sequential_execution_;
ok &= thread_number() == 0;
ok &= wait_for_work_ != 0;
ok &= wait_for_job_ != 0;
// set global version of this work routine
worker_ = worker;
// set the new job that other threads are waiting for
thread_job_ = work_enum;
// Enter parallel exectuion when master thread calls wait_for_job_
if( num_threads_ > 1 )
sequential_execution_ = false;
wait_for_job_->wait();
// Now do the work in this thread and then wait
// until all threads have completed wait_for_work_
thread_work(0); // this thread is number zero (master)
// Current state is all threads have completed wait_for_work_,
// and are at wait_for_job_.
// This master thread (thread zero) has not completed wait_for_job_
sequential_execution_ = true;
size_t thread_num;
for(thread_num = 0; thread_num < num_threads_; thread_num++)
ok &= thread_all_[thread_num].ok;
return ok;
}
bool stop_team(void)
{ // Current state is all threads have completed wait_for_work_,
// and are at wait_for_job_.
// This master thread (thread zero) has not completed wait_for_job_
bool ok = sequential_execution_;
ok &= thread_number() == 0;
ok &= wait_for_work_ != 0;
ok &= wait_for_job_ != 0;
// set the new job that other threads are waiting for
thread_job_ = join_enum;
// enter parallel exectuion soon as master thread completes wait_for_job_
if( num_threads_ > 1 )
sequential_execution_ = false;
wait_for_job_->wait();
// now wait for the other threads to be destroyed
size_t thread_num;
ok &= thread_all_[0].bthread == 0;
for(thread_num = 1; thread_num < num_threads_; thread_num++)
{ thread_all_[thread_num].bthread->join();
delete thread_all_[thread_num].bthread;
thread_all_[thread_num].bthread = 0;
}
// now we are down to just the master thread (thread zero)
sequential_execution_ = true;
// destroy wait_for_work_
delete wait_for_work_;
wait_for_work_ = 0;
// destroy wait_for_job_
delete wait_for_job_;
wait_for_job_ = 0;
// check ok before changing num_threads_
for(thread_num = 0; thread_num < num_threads_; thread_num++)
ok &= thread_all_[thread_num].ok;
// now inform CppAD that there is only one thread
num_threads_ = 1;
using CppAD::thread_alloc;
thread_alloc::parallel_setup(num_threads_, in_parallel, thread_number);
return ok;
}
// END PROGRAM
<commit_msg>Simplify thread_work and make more like pthread_team.cpp.<commit_after>// $Id$
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-11 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Common Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin bthread_team.cpp$$
$spell
bthread
$$
$index bthread, AD team$$
$index AD, bthread team$$
$index team, AD bthread$$
$section Boost Thread Implementation of a Team of AD Threads$$
See $cref thread_team.hpp$$ for this routines specifications.
$code
$verbatim%multi_thread/bthread/bthread_team.cpp%0%// BEGIN PROGRAM%// END PROGRAM%1%$$
$$
$end
*/
// BEGIN PROGRAM
# include <boost/thread.hpp>
# include <cppad/cppad.hpp>
# include "../thread_team.hpp"
# define MAX_NUMBER_THREADS 48
namespace {
// number of threads in the team
size_t num_threads_ = 1;
// type of the job currently being done by each thread
enum thread_job_t { init_enum, work_enum, join_enum } thread_job_;
// barrier used to wait for other threads to finish work
boost::barrier* wait_for_work_ = 0;
// barrier used to wait for master thread to set next job
boost::barrier* wait_for_job_ = 0;
// Are we in sequential mode; i.e., other threads are waiting for
// master thread to set up next job ?
bool sequential_execution_ = true;
// structure with information for one thread
typedef struct {
boost::thread* bthread;
// Boost unique identifier for thread that uses this struct
boost::thread::id bthread_id;
// true if no error for this thread, false otherwise.
bool ok;
} thread_one_t;
// vector with information for all threads
thread_one_t thread_all_[MAX_NUMBER_THREADS];
// pointer to function that does the work for one thread
void (* worker_)(void) = 0;
// ---------------------------------------------------------------------
// in_parallel()
bool in_parallel(void)
{ return ! sequential_execution_; }
// ---------------------------------------------------------------------
// thread_number()
size_t thread_number(void)
{ using boost::thread;
// bthread unique identifier for this thread
thread::id thread_this = boost::this_thread::get_id();
// convert thread_this to the corresponding thread_num
size_t thread_num = 0;
for(thread_num = 0; thread_num < num_threads_; thread_num++)
{ // Boost unique identifier for this thread_num
thread::id thread_compare = thread_all_[thread_num].bthread_id;
// check for a match
if( thread_this == thread_compare )
return thread_num;
}
// no match error (thread_this is not in thread_all_).
std::cerr << "thread_number: unknown boost::thread::id" << std::endl;
exit(1);
return 0;
}
// --------------------------------------------------------------------
// function that gets called by boost thread constructor
void thread_work(size_t thread_num)
{ bool ok = wait_for_work_ != 0;
ok &= wait_for_job_ != 0;
ok &= thread_num != 0;
while( true )
{
// Use wait_for_jog_ to give master time in sequential mode
// (so it can change global information like thread_job_)
wait_for_job_->wait();
// case where we are terminating this thread (no more work)
if( thread_job_ == join_enum)
break;
// only other case once wait_for_job_ has been completed (so far)
ok &= thread_job_ == work_enum;
worker_();
// Use wait_for_work_ to inform master that our work is done and
// that this thread will not use global infromation until
// passing its barrier wait_for_job_ above.
wait_for_work_->wait();
}
thread_all_[thread_num].ok &= ok;
return;
}
}
bool start_team(size_t num_threads)
{ using CppAD::thread_alloc;
bool ok = true;;
if( num_threads > MAX_NUMBER_THREADS )
{ std::cerr << "start_team: num_threads greater than ";
std::cerr << MAX_NUMBER_THREADS << std::endl;
exit(1);
}
// check that we currently do not have multiple threads running
ok = num_threads_ == 1;
ok &= wait_for_work_ == 0;
ok &= wait_for_job_ == 0;
ok &= sequential_execution_;
// Set the information for this thread so thread_number will work
// for call to parallel_setup
thread_all_[0].bthread_id = boost::this_thread::get_id();
thread_all_[0].bthread = 0; // not used
thread_all_[0].ok = true;
// Now that thread_number() has necessary information for the case
// num_threads_ == 1, and while still in sequential mode,
// call setup for using CppAD::AD<double> in parallel mode.
thread_alloc::parallel_setup(num_threads, in_parallel, thread_number);
CppAD::parallel_ad<double>();
// now change num_threads_ to its final value.
num_threads_ = num_threads;
// initialize two barriers, one for work done, one for new job ready
wait_for_work_ = new boost::barrier(num_threads);
wait_for_job_ = new boost::barrier(num_threads);
// initial job for the threads
thread_job_ = init_enum;
if( num_threads > 1 )
sequential_execution_ = false;
// This master thread is already running, we need to create
// num_threads - 1 more threads
size_t thread_num;
for(thread_num = 1; thread_num < num_threads; thread_num++)
{ thread_all_[thread_num].ok = true;
// Create the thread with thread number equal to thread_num
thread_all_[thread_num].bthread =
new boost::thread(thread_work, thread_num);
thread_all_[thread_num].bthread_id =
thread_all_[thread_num].bthread->get_id();
}
// Current state is other threads are at wait_for_job_.
// This master thread (thread zero) has not completed wait_for_job_
sequential_execution_ = true;
for(thread_num = 0; thread_num < num_threads; thread_num++)
ok &= thread_all_[thread_num].ok;
return ok;
}
bool work_team(void worker(void))
{
// Current state is other threads are at wait_for_job_.
// This master thread (thread zero) has not completed wait_for_job_
bool ok = sequential_execution_;
ok &= thread_number() == 0;
ok &= wait_for_work_ != 0;
ok &= wait_for_job_ != 0;
// set global version of this work routine
worker_ = worker;
// set the new job that other threads are waiting for
thread_job_ = work_enum;
// Enter parallel exectuion when master thread calls wait_for_job_
if( num_threads_ > 1 )
sequential_execution_ = false;
wait_for_job_->wait();
// Now do the work in this thread and then wait
// until all threads have completed wait_for_work_
worker();
wait_for_work_->wait();
// Current state is other threads are at wait_for_job_.
// This master thread (thread zero) has not completed wait_for_job_
sequential_execution_ = true;
size_t thread_num;
for(thread_num = 0; thread_num < num_threads_; thread_num++)
ok &= thread_all_[thread_num].ok;
return ok;
}
bool stop_team(void)
{ // Current state is other threads are at wait_for_job_.
// This master thread (thread zero) has not completed wait_for_job_
bool ok = sequential_execution_;
ok &= thread_number() == 0;
ok &= wait_for_work_ != 0;
ok &= wait_for_job_ != 0;
// set the new job that other threads are waiting for
thread_job_ = join_enum;
// enter parallel exectuion soon as master thread completes wait_for_job_
if( num_threads_ > 1 )
sequential_execution_ = false;
wait_for_job_->wait();
// now wait for the other threads to be destroyed
size_t thread_num;
ok &= thread_all_[0].bthread == 0;
for(thread_num = 1; thread_num < num_threads_; thread_num++)
{ thread_all_[thread_num].bthread->join();
delete thread_all_[thread_num].bthread;
thread_all_[thread_num].bthread = 0;
}
// now we are down to just the master thread (thread zero)
sequential_execution_ = true;
// destroy wait_for_work_
delete wait_for_work_;
wait_for_work_ = 0;
// destroy wait_for_job_
delete wait_for_job_;
wait_for_job_ = 0;
// check ok before changing num_threads_
for(thread_num = 0; thread_num < num_threads_; thread_num++)
ok &= thread_all_[thread_num].ok;
// now inform CppAD that there is only one thread
num_threads_ = 1;
using CppAD::thread_alloc;
thread_alloc::parallel_setup(num_threads_, in_parallel, thread_number);
return ok;
}
// END PROGRAM
<|endoftext|> |
<commit_before>// #define DEBUG_MEM
#include "memory.h"
#ifdef DEBUG_MEM
#include <iostream>
#endif
// ---------------------------------------------------------------------------------------------- //
Memory::Memory(std::string& fname) : file(fname, std::ios::in | std::ios::binary) {
if (file) {
// get length of file:
file.seekg (0, file.end);
int length = file.tellg();
file.seekg (0, file.beg);
// std::cout << "rom size " << std::hex << length << std::endl;
}
}
// ---------------------------------------------------------------------------------------------- //
Memory::~Memory() {
file.close();
}
// ---------------------------------------------------------------------------------------------- //
uint8_t Memory::read(uint16_t addr) {
uint8_t ret = 0U;
#ifdef DEBUG_MEM
std::cout << "read from " << std::hex << addr;
#endif
if (addr <= 0x2000U) {
// ram address
if (addr >= 0x800U) {
addr -= 0x800U; // mirrored region
}
ret = ram[addr];
}
else if (addr >= 0xC000U) {
uint16_t const offset = 16 + addr - 0xC000U;
file.seekg(offset);
file.get((char&)ret);
#ifdef DEBUG_MEM
std::cout << " file offset " << offset;
#endif
}
#ifdef DEBUG_MEM
std::cout << " return " << std::hex << static_cast<int>(ret) << std::endl;
#endif
return ret;
}
// ---------------------------------------------------------------------------------------------- //
void Memory::write(uint16_t addr, uint8_t value) {
if (addr < 0x2000U) {
// ram address
if (addr >= 0x800U) {
addr -= 0x800U; // mirrored region
}
ram[addr] = value;
}
#ifdef DEBUG_MEM
std::cout << "write " << std::hex << static_cast<int>(value) << " to " << std::hex
<< addr << std::endl;
#endif
}<commit_msg>Improve memory logging<commit_after>// #define DEBUG_MEM
#include "memory.h"
#ifdef DEBUG_MEM
#include <iostream>
#include <boost/format.hpp>
#endif
// ---------------------------------------------------------------------------------------------- //
Memory::Memory(std::string& fname) : file(fname, std::ios::in | std::ios::binary) {
if (file) {
// get length of file:
file.seekg (0, file.end);
int length = file.tellg();
file.seekg (0, file.beg);
// std::cout << "rom size " << std::hex << length << std::endl;
}
}
// ---------------------------------------------------------------------------------------------- //
Memory::~Memory() {
file.close();
}
// ---------------------------------------------------------------------------------------------- //
uint8_t Memory::read(uint16_t addr) {
uint8_t ret = 0U;
if (addr <= 0x2000U) {
// ram address
if (addr >= 0x800U) {
addr -= 0x800U; // mirrored region
}
ret = ram[addr];
}
else if (addr >= 0xC000U) {
uint16_t const offset = 16 + addr - 0xC000U;
file.seekg(offset);
file.get((char&)ret);
}
#ifdef DEBUG_MEM
std::cout << "RD[" << boost::format("0x%04X") % addr << "] <- ";
std::cout << boost::format("0x%02X") % static_cast<int>(ret);
std::cout << std::endl;
#endif
return ret;
}
// ---------------------------------------------------------------------------------------------- //
void Memory::write(uint16_t addr, uint8_t value) {
if (addr < 0x2000U) {
// ram address
if (addr >= 0x800U) {
addr -= 0x800U; // mirrored region
}
ram[addr] = value;
}
#ifdef DEBUG_MEM
std::cout << "WR[" << boost::format("0x%04X") % addr << "] -> ";
std::cout << boost::format("0x%02X") % static_cast<int>(value);
std::cout << std::endl;
#endif
}<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++11
namespace simple {
int Foo(void *const p __attribute__((pass_object_size(0))));
int OvlFoo(void *const p __attribute__((pass_object_size(0))));
int OvlFoo(void *const p, int);
struct Statics {
static int Foo(void *const p __attribute__((pass_object_size(0))));
static int OvlFoo(void *const p __attribute__((pass_object_size(0))));
static int OvlFoo(void *const p __attribute__((pass_object_size(1)))); // expected-error{{conflicting pass_object_size attributes on parameters}} expected-note@-1{{previous declaration is here}}
static int OvlFoo(double *p);
};
struct Members {
int Foo(void *const p __attribute__((pass_object_size(0))));
int OvlFoo(void *const p __attribute__((pass_object_size(0))));
int OvlFoo(void *const p, int);
};
void Decls() {
int (*A)(void *) = &Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
int (*B)(void *) = Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
int (*C)(void *) = &OvlFoo; //expected-error{{address of overloaded function 'OvlFoo' does not match required type 'int (void *)'}} expected-note@6{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@7{{candidate function has different number of parameters (expected 1 but has 2)}}
int (*D)(void *) = OvlFoo; //expected-error{{address of overloaded function 'OvlFoo' does not match required type 'int (void *)'}} expected-note@6{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@7{{candidate function has different number of parameters (expected 1 but has 2)}}
int (*E)(void *) = &Statics::Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
int (*F)(void *) = &Statics::OvlFoo; //expected-error{{address of overloaded function 'OvlFoo' does not match required type 'int (void *)'}} expected-note@11{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@13{{candidate function has type mismatch at 1st parameter (expected 'void *' but has 'double *')}}
int (*G)(void *) = &Members::Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
int (*H)(void *) = &Members::OvlFoo; //expected-error{{address of overloaded function 'OvlFoo' does not match required type 'int (void *)'}} expected-note@18{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@19{{candidate function has different number of parameters (expected 1 but has 2)}}
}
void Assigns() {
int (*A)(void *);
A = &Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
A = Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
A = &OvlFoo; //expected-error{{assigning to 'int (*)(void *)' from incompatible type '<overloaded function type>'}} expected-note@6{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@7{{candidate function has different number of parameters (expected 1 but has 2)}}
A = OvlFoo; //expected-error{{assigning to 'int (*)(void *)' from incompatible type '<overloaded function type>'}} expected-note@6{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@7{{candidate function has different number of parameters (expected 1 but has 2)}}
A = &Statics::Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
A = &Statics::OvlFoo; //expected-error{{assigning to 'int (*)(void *)' from incompatible type '<overloaded function type>'}} expected-note@11{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@13{{candidate function has type mismatch at 1st parameter (expected 'void *' but has 'double *')}}
int (Members::*M)(void *);
M = &Members::Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
M = &Members::OvlFoo; //expected-error{{assigning to 'int (simple::Members::*)(void *)' from incompatible type '<overloaded function type>'}} expected-note@18{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@19{{candidate function has different number of parameters (expected 1 but has 2)}}
}
} // namespace simple
namespace templates {
template <typename T>
int Foo(void *const __attribute__((pass_object_size(0)))) {
return 0;
}
template <typename T> struct Bar {
template <typename U>
int Foo(void *const __attribute__((pass_object_size(0)))) {
return 0;
}
};
void Decls() {
int (*A)(void *) = &Foo<void*>; //expected-error{{address of overloaded function 'Foo' does not match required type 'int (void *)'}} expected-note@56{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}}
int (Bar<int>::*B)(void *) = &Bar<int>::Foo<double>; //expected-error{{address of overloaded function 'Foo' does not match required type 'int (void *)'}} expected-note@62{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}}
}
void Assigns() {
int (*A)(void *);
A = &Foo<void*>; // expected-error{{assigning to 'int (*)(void *)' from incompatible type '<overloaded function type>'}} expected-note@56{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}}
int (Bar<int>::*B)(void *) = &Bar<int>::Foo<double>; //expected-error{{address of overloaded function 'Foo' does not match required type 'int (void *)'}} expected-note@62{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}}
}
} // namespace templates
namespace virt {
struct Foo {
virtual void DoIt(void *const p __attribute__((pass_object_size(0))));
};
struct Bar : public Foo {
void DoIt(void *const p __attribute__((pass_object_size(0)))) override; // OK
};
struct Baz : public Foo {
void DoIt(void *const p) override; //expected-error{{non-virtual member function marked 'override' hides virtual member function}} expected-note@81{{hidden overloaded virtual function 'virt::Foo::DoIt' declared here}}
};
}
namespace why {
void TakeFn(void (*)(int, void *));
void ObjSize(int, void *const __attribute__((pass_object_size(0))));
void Check() {
TakeFn(ObjSize); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn(&ObjSize); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn(*ObjSize); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn(*****ObjSize); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn(*****&ObjSize); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
void (*P)(int, void *) = ****ObjSize; //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
P = ****ObjSize; //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn((ObjSize)); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn((void*)ObjSize); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn((decltype(P))((void*)ObjSize)); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
}
}
namespace constexpr_support {
constexpr int getObjSizeType() { return 0; }
void Foo(void *p __attribute__((pass_object_size(getObjSizeType()))));
}
namespace lambdas {
void Bar() {
(void)+[](void *const p __attribute__((pass_object_size(0)))) {}; //expected-error-re{{invalid argument type '(lambda at {{.*}})' to unary expression}}
}
}
<commit_msg>Fix pass_object_size test on Windows.<commit_after>// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++11
namespace simple {
int Foo(void *const p __attribute__((pass_object_size(0))));
int OvlFoo(void *const p __attribute__((pass_object_size(0))));
int OvlFoo(void *const p, int);
struct Statics {
static int Foo(void *const p __attribute__((pass_object_size(0))));
static int OvlFoo(void *const p __attribute__((pass_object_size(0))));
static int OvlFoo(void *const p __attribute__((pass_object_size(1)))); // expected-error{{conflicting pass_object_size attributes on parameters}} expected-note@-1{{previous declaration is here}}
static int OvlFoo(double *p);
};
struct Members {
int Foo(void *const p __attribute__((pass_object_size(0))));
int OvlFoo(void *const p __attribute__((pass_object_size(0))));
int OvlFoo(void *const p, int);
};
void Decls() {
int (*A)(void *) = &Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
int (*B)(void *) = Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
int (*C)(void *) = &OvlFoo; //expected-error{{address of overloaded function 'OvlFoo' does not match required type 'int (void *)'}} expected-note@6{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@7{{candidate function has different number of parameters (expected 1 but has 2)}}
int (*D)(void *) = OvlFoo; //expected-error{{address of overloaded function 'OvlFoo' does not match required type 'int (void *)'}} expected-note@6{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@7{{candidate function has different number of parameters (expected 1 but has 2)}}
int (*E)(void *) = &Statics::Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
int (*F)(void *) = &Statics::OvlFoo; //expected-error{{address of overloaded function 'OvlFoo' does not match required type 'int (void *)'}} expected-note@11{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@13{{candidate function has type mismatch at 1st parameter (expected 'void *' but has 'double *')}}
int (*G)(void *) = &Members::Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
int (*H)(void *) = &Members::OvlFoo; //expected-error{{address of overloaded function 'OvlFoo' does not match required type 'int (void *)'}} expected-note@18{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@19{{candidate function has different number of parameters (expected 1 but has 2)}}
}
void Assigns() {
int (*A)(void *);
A = &Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
A = Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
A = &OvlFoo; //expected-error{{assigning to 'int (*)(void *)' from incompatible type '<overloaded function type>'}} expected-note@6{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@7{{candidate function has different number of parameters (expected 1 but has 2)}}
A = OvlFoo; //expected-error{{assigning to 'int (*)(void *)' from incompatible type '<overloaded function type>'}} expected-note@6{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@7{{candidate function has different number of parameters (expected 1 but has 2)}}
A = &Statics::Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
A = &Statics::OvlFoo; //expected-error{{assigning to 'int (*)(void *)' from incompatible type '<overloaded function type>'}} expected-note@11{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@13{{candidate function has type mismatch at 1st parameter (expected 'void *' but has 'double *')}}
int (Members::*M)(void *);
M = &Members::Foo; //expected-error{{cannot take address of function 'Foo' because parameter 1 has pass_object_size attribute}}
M = &Members::OvlFoo; //expected-error-re{{assigning to '{{.*}}' from incompatible type '<overloaded function type>'}} expected-note@18{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}} expected-note@19{{candidate function has different number of parameters (expected 1 but has 2)}}
}
} // namespace simple
namespace templates {
template <typename T>
int Foo(void *const __attribute__((pass_object_size(0)))) {
return 0;
}
template <typename T> struct Bar {
template <typename U>
int Foo(void *const __attribute__((pass_object_size(0)))) {
return 0;
}
};
void Decls() {
int (*A)(void *) = &Foo<void*>; //expected-error{{address of overloaded function 'Foo' does not match required type 'int (void *)'}} expected-note@56{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}}
int (Bar<int>::*B)(void *) = &Bar<int>::Foo<double>; //expected-error{{address of overloaded function 'Foo' does not match required type}} expected-note@62{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}}
}
void Assigns() {
int (*A)(void *);
A = &Foo<void*>; // expected-error{{assigning to 'int (*)(void *)' from incompatible type '<overloaded function type>'}} expected-note@56{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}}
int (Bar<int>::*B)(void *) = &Bar<int>::Foo<double>; //expected-error{{address of overloaded function 'Foo' does not match required type}} expected-note@62{{candidate address cannot be taken because parameter 1 has pass_object_size attribute}}
}
} // namespace templates
namespace virt {
struct Foo {
virtual void DoIt(void *const p __attribute__((pass_object_size(0))));
};
struct Bar : public Foo {
void DoIt(void *const p __attribute__((pass_object_size(0)))) override; // OK
};
struct Baz : public Foo {
void DoIt(void *const p) override; //expected-error{{non-virtual member function marked 'override' hides virtual member function}} expected-note@81{{hidden overloaded virtual function 'virt::Foo::DoIt' declared here}}
};
}
namespace why {
void TakeFn(void (*)(int, void *));
void ObjSize(int, void *const __attribute__((pass_object_size(0))));
void Check() {
TakeFn(ObjSize); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn(&ObjSize); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn(*ObjSize); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn(*****ObjSize); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn(*****&ObjSize); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
void (*P)(int, void *) = ****ObjSize; //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
P = ****ObjSize; //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn((ObjSize)); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn((void*)ObjSize); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
TakeFn((decltype(P))((void*)ObjSize)); //expected-error{{cannot take address of function 'ObjSize' because parameter 2 has pass_object_size attribute}}
}
}
namespace constexpr_support {
constexpr int getObjSizeType() { return 0; }
void Foo(void *p __attribute__((pass_object_size(getObjSizeType()))));
}
namespace lambdas {
void Bar() {
(void)+[](void *const p __attribute__((pass_object_size(0)))) {}; //expected-error-re{{invalid argument type '(lambda at {{.*}})' to unary expression}}
}
}
<|endoftext|> |
<commit_before>#include "pch.h"
#include "service_manager.h"
#include "service.h"
ServiceManager::ServiceManager()
: _state(Service::PRE_INIT)
, _elapsedTime(0.0f)
{
}
ServiceManager::~ServiceManager()
{
}
void ServiceManager::cleanup()
{
for (ServicesType::reverse_iterator it = _services.rbegin(), end_it = _services.rend(); it != end_it; it++)
delete (*it);
_services.clear();
}
void ServiceManager::registerService(const char * name, Service * service, Service ** dependencies)
{
ServiceData * newData = new ServiceData();
newData->name = name;
newData->service.reset(service);
if (!dependencies)
{
_services.push_front(newData);
return;
}
int dependenciesCount = 0;
Service ** temp = dependencies;
while (*temp)
{
dependenciesCount++;
temp++;
}
ServicesType::iterator it = _services.begin(), end_it = _services.end();
while (it != end_it && dependenciesCount> 0)
{
temp = dependencies;
while (*temp)
{
if ((*it)->service.get() == *temp)
{
dependenciesCount--;
break;
}
temp++;
}
it++;
}
if (it != end_it)
it++;
if (dependenciesCount > 0)
{
GP_ERROR("Trying to register service %s which has dependency on unregistered service", name);
return;
}
_services.insert(it, newData);
}
Service * ServiceManager::findService(const char * name) const
{
for (ServicesType::const_iterator it = _services.begin(), end_it = _services.end(); it != end_it; it++)
if ((*it)->name == name)
return (*it)->service.get();
return NULL;
}
void ServiceManager::shutdown()
{
for (ServicesType::iterator it = _services.begin(), end_it = _services.end(); it != end_it; it++)
if ((*it)->service->getState() != Service::COMPLETED)
(*it)->service->setState(Service::SHUTTING_DOWN);
_state = Service::SHUTTING_DOWN;
signals.serviceManagerStateChangedEvent(_state);
while (_state != Service::COMPLETED)
update(_elapsedTime);
cleanup();
}
void ServiceManager::update(float elapsedTime)
{
_elapsedTime = elapsedTime;
if (_state == Service::COMPLETED)
return;
static bool (Service::* state_funcs[]) () =
{
&Service::onPreInit,
&Service::onInit,
&Service::onTick,
&Service::onShutdown
};
bool allCompleted = true;
for (ServicesType::iterator it = _services.begin(), end_it = _services.end(); it != end_it; it++)
{
const Service::State& serviceState = (*it)->service->getState();
if (serviceState <= _state)
{
bool res = ((*it)->service.get()->*state_funcs[serviceState])();
if (serviceState == _state)
allCompleted &= res;
if (res)
(*it)->service->setState(static_cast<Service::State>(serviceState + 1));
}
}
if (allCompleted)
{
_state = static_cast<Service::State>(_state + 1);
signals.serviceManagerStateChangedEvent(_state);
}
}<commit_msg>using reverse order of destruction for services<commit_after>#include "pch.h"
#include "service_manager.h"
#include "service.h"
ServiceManager::ServiceManager()
: _state(Service::PRE_INIT)
, _elapsedTime(0.0f)
{
}
ServiceManager::~ServiceManager()
{
}
void ServiceManager::cleanup()
{
for (ServicesType::reverse_iterator it = _services.rbegin(), end_it = _services.rend(); it != end_it; it++)
delete (*it);
_services.clear();
}
void ServiceManager::registerService(const char * name, Service * service, Service ** dependencies)
{
ServiceData * newData = new ServiceData();
newData->name = name;
newData->service.reset(service);
if (!dependencies)
{
_services.push_front(newData);
return;
}
int dependenciesCount = 0;
Service ** temp = dependencies;
while (*temp)
{
dependenciesCount++;
temp++;
}
ServicesType::iterator it = _services.begin(), end_it = _services.end();
while (it != end_it && dependenciesCount> 0)
{
temp = dependencies;
while (*temp)
{
if ((*it)->service.get() == *temp)
{
dependenciesCount--;
break;
}
temp++;
}
it++;
}
if (it != end_it)
it++;
if (dependenciesCount > 0)
{
GP_ERROR("Trying to register service %s which has dependency on unregistered service", name);
return;
}
_services.insert(it, newData);
}
Service * ServiceManager::findService(const char * name) const
{
for (ServicesType::const_iterator it = _services.begin(), end_it = _services.end(); it != end_it; it++)
if ((*it)->name == name)
return (*it)->service.get();
return NULL;
}
void ServiceManager::shutdown()
{
for (ServicesType::iterator it = _services.begin(), end_it = _services.end(); it != end_it; it++)
if ((*it)->service->getState() != Service::COMPLETED)
(*it)->service->setState(Service::SHUTTING_DOWN);
_state = Service::SHUTTING_DOWN;
signals.serviceManagerStateChangedEvent(_state);
while (_state != Service::COMPLETED)
update(_elapsedTime);
cleanup();
}
void ServiceManager::update(float elapsedTime)
{
_elapsedTime = elapsedTime;
if (_state == Service::COMPLETED)
return;
static bool (Service::* state_funcs[]) () =
{
&Service::onPreInit,
&Service::onInit,
&Service::onTick,
&Service::onShutdown
};
bool allCompleted = true;
if (_state == Service::SHUTTING_DOWN)
{
// process all destruction of services in a reverse order
for (auto it = _services.rbegin(), end_it = _services.rend(); it != end_it; it++)
{
const Service::State& serviceState = (*it)->service->getState();
GP_ASSERT(serviceState >= Service::SHUTTING_DOWN);
if (serviceState == Service::SHUTTING_DOWN)
{
bool res = ((*it)->service.get()->*state_funcs[serviceState])();
if (serviceState == _state)
allCompleted &= res;
if (res)
(*it)->service->setState(static_cast<Service::State>(serviceState + 1));
}
}
}
else
{
for (ServicesType::iterator it = _services.begin(), end_it = _services.end(); it != end_it; it++)
{
const Service::State& serviceState = (*it)->service->getState();
if (serviceState <= _state)
{
bool res = ((*it)->service.get()->*state_funcs[serviceState])();
if (serviceState == _state)
allCompleted &= res;
if (res)
(*it)->service->setState(static_cast<Service::State>(serviceState + 1));
}
}
}
if (allCompleted)
{
_state = static_cast<Service::State>(_state + 1);
signals.serviceManagerStateChangedEvent(_state);
}
}<|endoftext|> |
<commit_before>/* **********************************************************
* Copyright (c) 2015 Google, 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 Google, 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 VMWARE, INC. OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#include "caching_device.h"
#include "caching_device_block.h"
#include "caching_device_stats.h"
#include "utils.h"
#include <assert.h>
caching_device_t::caching_device_t()
{
blocks = 0;
}
caching_device_t::~caching_device_t()
{
for (int i = 0; i < num_blocks; i++)
delete blocks[i];
delete [] blocks;
}
bool
caching_device_t::init(int associativity_, int block_size_, int num_blocks_,
caching_device_t *parent_, caching_device_stats_t *stats_)
{
if (!IS_POWER_OF_2(associativity_) ||
!IS_POWER_OF_2(block_size_) ||
!IS_POWER_OF_2(num_blocks_) ||
// Assuming caching device block size is at least 4 bytes
block_size_ < 4)
return false;
if (stats_ == NULL)
return false; // A stats must be provided for perf: avoid conditional code
associativity = associativity_;
block_size = block_size_;
num_blocks = num_blocks_;
blocks_per_set = num_blocks / associativity;
assoc_bits = compute_log2(associativity);
block_size_bits = compute_log2(block_size);
blocks_per_set_mask = blocks_per_set - 1;
if (assoc_bits == -1 || block_size_bits == -1 || !IS_POWER_OF_2(blocks_per_set))
return false;
parent = parent_;
stats = stats_;
blocks = new caching_device_block_t* [num_blocks];
init_blocks();
last_tag = TAG_INVALID; // sentinel
return true;
}
void
caching_device_t::request(const memref_t &memref_in)
{
// Unfortunately we need to make a copy for our loop so we can pass
// the right data struct to the parent and stats collectors.
memref_t memref;
// We support larger sizes to improve the IPC perf.
// This means that one memref could touch multiple blocks.
// We treat each block separately for statistics purposes.
addr_t final_addr = memref_in.addr + memref_in.size - 1/*avoid overflow*/;
addr_t final_tag = compute_tag(final_addr);
addr_t tag = compute_tag(memref_in.addr);
// Optimization: check last tag if single-block
if (tag == final_tag && tag == last_tag) {
// Make sure last_tag is properly in sync.
assert(tag != TAG_INVALID &&
tag == get_caching_device_block(last_block_idx, last_way).tag);
stats->access(memref_in, true/*hit*/);
if (parent != NULL)
parent->stats->child_access(memref_in, true);
access_update(last_block_idx, last_way);
return;
}
memref = memref_in;
for (; tag <= final_tag; ++tag) {
int way;
int block_idx = compute_block_idx(tag);
if (tag + 1 <= final_tag)
memref.size = ((tag + 1) << block_size_bits) - memref.addr;
for (way = 0; way < associativity; ++way) {
if (get_caching_device_block(block_idx, way).tag == tag) {
stats->access(memref, true/*hit*/);
if (parent != NULL)
parent->stats->child_access(memref, true);
break;
}
}
if (way == associativity) {
stats->access(memref, false/*miss*/);
// If no parent we assume we get the data from main memory
if (parent != NULL) {
parent->stats->child_access(memref, false);
parent->request(memref);
}
// FIXME i#1726: coherence policy
way = replace_which_way(block_idx);
get_caching_device_block(block_idx, way).tag = tag;
}
access_update(block_idx, way);
if (tag + 1 <= final_tag) {
addr_t next_addr = (tag + 1) << block_size_bits;
memref.addr = next_addr;
memref.size = final_addr - next_addr + 1/*undo the -1*/;
}
// Optimization: remember last tag
last_tag = tag;
last_way = way;
last_block_idx = block_idx;
}
}
void
caching_device_t::access_update(int block_idx, int way)
{
// We just inc the counter for LFU. We live with any blip on overflow.
get_caching_device_block(block_idx, way).counter++;
}
int
caching_device_t::replace_which_way(int block_idx)
{
// The base caching device class only implements LFU.
// A subclass can override this and access_update() to implement
// some other scheme.
int min_counter;
int min_way = 0;
for (int way = 0; way < associativity; ++way) {
if (get_caching_device_block(block_idx, way).tag == TAG_INVALID) {
min_way = way;
break;
}
if (way == 0 || get_caching_device_block(block_idx, way).counter < min_counter) {
min_counter = get_caching_device_block(block_idx, way).counter;
min_way = way;
}
}
// Clear the counter for LFU.
get_caching_device_block(block_idx, min_way).counter = 0;
return min_way;
}
<commit_msg>Avoid "may be used uninitialized" warning/error with old GCC.<commit_after>/* **********************************************************
* Copyright (c) 2015 Google, 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 Google, 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 VMWARE, INC. OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#include "caching_device.h"
#include "caching_device_block.h"
#include "caching_device_stats.h"
#include "utils.h"
#include <assert.h>
caching_device_t::caching_device_t()
{
blocks = 0;
}
caching_device_t::~caching_device_t()
{
for (int i = 0; i < num_blocks; i++)
delete blocks[i];
delete [] blocks;
}
bool
caching_device_t::init(int associativity_, int block_size_, int num_blocks_,
caching_device_t *parent_, caching_device_stats_t *stats_)
{
if (!IS_POWER_OF_2(associativity_) ||
!IS_POWER_OF_2(block_size_) ||
!IS_POWER_OF_2(num_blocks_) ||
// Assuming caching device block size is at least 4 bytes
block_size_ < 4)
return false;
if (stats_ == NULL)
return false; // A stats must be provided for perf: avoid conditional code
associativity = associativity_;
block_size = block_size_;
num_blocks = num_blocks_;
blocks_per_set = num_blocks / associativity;
assoc_bits = compute_log2(associativity);
block_size_bits = compute_log2(block_size);
blocks_per_set_mask = blocks_per_set - 1;
if (assoc_bits == -1 || block_size_bits == -1 || !IS_POWER_OF_2(blocks_per_set))
return false;
parent = parent_;
stats = stats_;
blocks = new caching_device_block_t* [num_blocks];
init_blocks();
last_tag = TAG_INVALID; // sentinel
return true;
}
void
caching_device_t::request(const memref_t &memref_in)
{
// Unfortunately we need to make a copy for our loop so we can pass
// the right data struct to the parent and stats collectors.
memref_t memref;
// We support larger sizes to improve the IPC perf.
// This means that one memref could touch multiple blocks.
// We treat each block separately for statistics purposes.
addr_t final_addr = memref_in.addr + memref_in.size - 1/*avoid overflow*/;
addr_t final_tag = compute_tag(final_addr);
addr_t tag = compute_tag(memref_in.addr);
// Optimization: check last tag if single-block
if (tag == final_tag && tag == last_tag) {
// Make sure last_tag is properly in sync.
assert(tag != TAG_INVALID &&
tag == get_caching_device_block(last_block_idx, last_way).tag);
stats->access(memref_in, true/*hit*/);
if (parent != NULL)
parent->stats->child_access(memref_in, true);
access_update(last_block_idx, last_way);
return;
}
memref = memref_in;
for (; tag <= final_tag; ++tag) {
int way;
int block_idx = compute_block_idx(tag);
if (tag + 1 <= final_tag)
memref.size = ((tag + 1) << block_size_bits) - memref.addr;
for (way = 0; way < associativity; ++way) {
if (get_caching_device_block(block_idx, way).tag == tag) {
stats->access(memref, true/*hit*/);
if (parent != NULL)
parent->stats->child_access(memref, true);
break;
}
}
if (way == associativity) {
stats->access(memref, false/*miss*/);
// If no parent we assume we get the data from main memory
if (parent != NULL) {
parent->stats->child_access(memref, false);
parent->request(memref);
}
// FIXME i#1726: coherence policy
way = replace_which_way(block_idx);
get_caching_device_block(block_idx, way).tag = tag;
}
access_update(block_idx, way);
if (tag + 1 <= final_tag) {
addr_t next_addr = (tag + 1) << block_size_bits;
memref.addr = next_addr;
memref.size = final_addr - next_addr + 1/*undo the -1*/;
}
// Optimization: remember last tag
last_tag = tag;
last_way = way;
last_block_idx = block_idx;
}
}
void
caching_device_t::access_update(int block_idx, int way)
{
// We just inc the counter for LFU. We live with any blip on overflow.
get_caching_device_block(block_idx, way).counter++;
}
int
caching_device_t::replace_which_way(int block_idx)
{
// The base caching device class only implements LFU.
// A subclass can override this and access_update() to implement
// some other scheme.
int min_counter = 0; /* avoid "may be used uninitialized" with GCC 4.4.7 */
int min_way = 0;
for (int way = 0; way < associativity; ++way) {
if (get_caching_device_block(block_idx, way).tag == TAG_INVALID) {
min_way = way;
break;
}
if (way == 0 || get_caching_device_block(block_idx, way).counter < min_counter) {
min_counter = get_caching_device_block(block_idx, way).counter;
min_way = way;
}
}
// Clear the counter for LFU.
get_caching_device_block(block_idx, min_way).counter = 0;
return min_way;
}
<|endoftext|> |
<commit_before>#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/objectptr.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/consoleappender.h>
#include "Logger.h"
#include <stdio.h>
//static log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("KrisLibrary"));
bool rootLoggerDefined = false;
log4cxx::LoggerPtr rootLogger = 0;
log4cxx::LoggerPtr myLogger = 0;
std::string logName = "";
namespace KrisLibrary{
log4cxx::LoggerPtr logger(){
if (rootLoggerDefined){
return rootLogger;
}
rootLogger = log4cxx::Logger::getRootLogger();
try{
log4cxx::xml::DOMConfigurator::configure("./log4cxx.xml");
if (rootLogger->getAllAppenders().empty()){
log4cxx::LayoutPtr defaultLayout = new log4cxx::PatternLayout("%m %n");
log4cxx::AppenderPtr defaultAppender = new log4cxx::ConsoleAppender(defaultLayout);
rootLogger->addAppender(defaultAppender);
rootLogger->setLevel(log4cxx::Level::getInfo());
logName = "root";
printf("configured default\n");
//log4cxx::BasicConfigurator::configure();
}
}
catch(...){
log4cxx::LayoutPtr defaultLayout = new log4cxx::PatternLayout("%m %n");
log4cxx::AppenderPtr defaultAppender = new log4cxx::ConsoleAppender(defaultLayout);
rootLogger->addAppender(defaultAppender);
rootLogger->setLevel(log4cxx::Level::getInfo());
printf("configured default\n");
logName = "root";
//log4cxx::BasicConfigurator::configure();
}
rootLoggerDefined = true;
return rootLogger;
}
log4cxx::LoggerPtr logger(const char* s){
if(rootLoggerDefined){
//we have read the file or at least set a root logger previously
try{
printf("trying to find logger %s\n", s);
myLogger = log4cxx::Logger::getLogger(s);
if(myLogger->getAllAppenders().empty()){
printf("Logger %s has no appenders. Returning root logger.\n", s);
return rootLogger;
}
}
catch(...){
//logger i
printf("Logger %s is not defined. Returning root logger.\n", s);
return rootLogger;
}
}else{
// otherwise, logger needs to be configured
try{
log4cxx::xml::DOMConfigurator::configure("./log4cxx.xml");
myLogger = log4cxx::Logger::getLogger(s);
if (myLogger->getAllAppenders().empty()){
//sets up basic setup if logger doesn't have appender set up.
log4cxx::LayoutPtr defaultLayout = new log4cxx::PatternLayout("%m %n");
log4cxx::AppenderPtr defaultAppender = new log4cxx::ConsoleAppender(defaultLayout);
myLogger->addAppender(defaultAppender);
myLogger->setLevel(log4cxx::Level::getInfo());
printf("configured default\n");
//log4cxx::BasicConfigurator::configure();
}
}
catch(...){
//catches null logger errors
myLogger = log4cxx::Logger::getRootLogger();
printf("Hit error. Setting up default logger\n");
log4cxx::LayoutPtr defaultLayout = new log4cxx::PatternLayout("%m %n");
log4cxx::AppenderPtr defaultAppender = new log4cxx::ConsoleAppender(defaultLayout);
rootLogger->addAppender(defaultAppender);
rootLogger->setLevel(log4cxx::Level::getInfo()); // Log level set to INFO
//log4cxx::BasicConfigurator::configure();
}
rootLoggerDefined = true;
return myLogger;
}
logName = std::string(s);
return myLogger;
}
void loggerWait(){
if(KrisLibrary::logger()->isEnabledFor(log4cxx::Level::getError())){
getchar();
}
}
}
<commit_msg>updated getchar<commit_after>#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/objectptr.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/consoleappender.h>
#include "Logger.h"
#include <stdio.h>
//static log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("KrisLibrary"));
bool rootLoggerDefined = false;
log4cxx::LoggerPtr rootLogger = 0;
log4cxx::LoggerPtr myLogger = 0;
std::string logName = "";
namespace KrisLibrary{
log4cxx::LoggerPtr logger(){
if (rootLoggerDefined){
return rootLogger;
}
rootLogger = log4cxx::Logger::getRootLogger();
try{
log4cxx::xml::DOMConfigurator::configure("./log4cxx.xml");
if (rootLogger->getAllAppenders().empty()){
log4cxx::LayoutPtr defaultLayout = new log4cxx::PatternLayout("%m %n");
log4cxx::AppenderPtr defaultAppender = new log4cxx::ConsoleAppender(defaultLayout);
rootLogger->addAppender(defaultAppender);
rootLogger->setLevel(log4cxx::Level::getInfo());
logName = "root";
printf("configured default\n");
//log4cxx::BasicConfigurator::configure();
}
}
catch(...){
log4cxx::LayoutPtr defaultLayout = new log4cxx::PatternLayout("%m %n");
log4cxx::AppenderPtr defaultAppender = new log4cxx::ConsoleAppender(defaultLayout);
rootLogger->addAppender(defaultAppender);
rootLogger->setLevel(log4cxx::Level::getInfo());
printf("configured default\n");
logName = "root";
//log4cxx::BasicConfigurator::configure();
}
rootLoggerDefined = true;
return rootLogger;
}
log4cxx::LoggerPtr logger(const char* s){
if(rootLoggerDefined){
//we have read the file or at least set a root logger previously
try{
printf("trying to find logger %s\n", s);
myLogger = log4cxx::Logger::getLogger(s);
if(myLogger->getAllAppenders().empty()){
printf("Logger %s has no appenders. Returning root logger.\n", s);
return rootLogger;
}
}
catch(...){
//logger i
printf("Logger %s is not defined. Returning root logger.\n", s);
return rootLogger;
}
}else{
// otherwise, logger needs to be configured
try{
log4cxx::xml::DOMConfigurator::configure("./log4cxx.xml");
myLogger = log4cxx::Logger::getLogger(s);
if (myLogger->getAllAppenders().empty()){
//sets up basic setup if logger doesn't have appender set up.
log4cxx::LayoutPtr defaultLayout = new log4cxx::PatternLayout("%m %n");
log4cxx::AppenderPtr defaultAppender = new log4cxx::ConsoleAppender(defaultLayout);
myLogger->addAppender(defaultAppender);
myLogger->setLevel(log4cxx::Level::getInfo());
printf("configured default\n");
//log4cxx::BasicConfigurator::configure();
}
}
catch(...){
//catches null logger errors
myLogger = log4cxx::Logger::getRootLogger();
printf("Hit error. Setting up default logger\n");
log4cxx::LayoutPtr defaultLayout = new log4cxx::PatternLayout("%m %n");
log4cxx::AppenderPtr defaultAppender = new log4cxx::ConsoleAppender(defaultLayout);
rootLogger->addAppender(defaultAppender);
rootLogger->setLevel(log4cxx::Level::getInfo()); // Log level set to INFO
//log4cxx::BasicConfigurator::configure();
}
rootLoggerDefined = true;
return myLogger;
}
logName = std::string(s);
return myLogger;
}
void loggerWait(){
if(KrisLibrary::logger()->isEnabledFor(log4cxx::Level::getDebug())){
getchar();
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: helpagentwindow.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2003-07-22 11:12:03 $
*
* 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 EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVTOOLS_HELPAGENTWIDNOW_HXX_
#include "helpagentwindow.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SV_BITMAP_HXX
#include <vcl/bitmap.hxx>
#endif
#ifndef _SVTOOLS_SVTDATA_HXX
#include <svtdata.hxx>
#endif
#ifndef _SVTOOLS_HRC
#include "svtools.hrc"
#endif
#ifndef _SVT_HELPID_HRC
#include "helpid.hrc"
#endif
#define WB_AGENT_STYLE 0
//........................................................................
namespace svt
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::lang;
//====================================================================
//= CloserButton_Impl
//= overload of ImageButton, because sometimes vcl doesn't call the click handler
//====================================================================
//--------------------------------------------------------------------
class CloserButton_Impl : public ImageButton
{
public:
CloserButton_Impl( Window* pParent, WinBits nBits ) : ImageButton( pParent, nBits ) {}
virtual void MouseButtonUp( const MouseEvent& rMEvt );
};
//--------------------------------------------------------------------
void CloserButton_Impl::MouseButtonUp( const MouseEvent& rMEvt )
{
ImageButton::MouseButtonUp( rMEvt );
GetClickHdl().Call( this );
}
//====================================================================
//= HelpAgentWindow
//====================================================================
//--------------------------------------------------------------------
HelpAgentWindow::HelpAgentWindow( Window* _pParent )
:FloatingWindow( _pParent, WB_AGENT_STYLE)
,m_pCloser(NULL)
,m_pCallback(NULL)
{
// -----------------
// the closer button
Bitmap aCloserBitmap(SvtResId(BMP_HELP_AGENT_CLOSER));
Image aCloserImage( aCloserBitmap, Color(COL_LIGHTMAGENTA) );
m_pCloser = new CloserButton_Impl( this, WB_NOTABSTOP | WB_NOPOINTERFOCUS );
static_cast<CloserButton_Impl*>(m_pCloser)->SetImage( aCloserImage );
static_cast<CloserButton_Impl*>(m_pCloser)->SetClickHdl( LINK(this, HelpAgentWindow, OnButtonClicked) );
m_pCloser->SetSizePixel( implOptimalButtonSize(aCloserImage) );
m_pCloser->Show();
m_pCloser->SetZOrder( NULL, WINDOW_ZORDER_LAST );
// ----------------------------
// calculate our preferred size
Bitmap aHelpAgentBitmap(SvtResId(BMP_HELP_AGENT_IMAGE));
m_aPicture = Image( aHelpAgentBitmap );
m_aPreferredSize = m_aPicture.GetSizePixel();
m_aPreferredSize.Width() += 2;
m_aPreferredSize.Height() += 2;
Size aSize = GetSizePixel();
Size aOutputSize = GetOutputSizePixel();
m_aPreferredSize.Width() += aSize.Width() - aOutputSize.Width();
m_aPreferredSize.Height() += aSize.Height() - aOutputSize.Height();
SetPointer(Pointer(POINTER_REFHAND));
AlwaysEnableInput( TRUE, TRUE );
// unique id for the testtool
SetUniqueId( HID_HELPAGENT_WINDOW );
}
//--------------------------------------------------------------------
HelpAgentWindow::~HelpAgentWindow()
{
if (m_pCloser && m_pCloser->IsTracking())
m_pCloser->EndTracking();
if (m_pCloser && m_pCloser->IsMouseCaptured())
m_pCloser->ReleaseMouse();
delete m_pCloser;
}
//--------------------------------------------------------------------
void HelpAgentWindow::Paint( const Rectangle& rRect )
{
FloatingWindow::Paint(rRect);
Size aOutputSize( GetOutputSizePixel() );
Point aPoint=Point();
Rectangle aOutputRect( aPoint, aOutputSize );
Rectangle aInnerRect( aOutputRect );
// paint the background
SetLineColor( GetSettings().GetStyleSettings().GetFaceColor() );
SetFillColor( GetSettings().GetStyleSettings().GetFaceColor() );
DrawRect( aOutputRect );
// paint the image
Size aPictureSize( m_aPicture.GetSizePixel() );
Point aPicturePos(
aOutputRect.Left() + (aInnerRect.GetWidth() - aPictureSize.Width()) / 2,
aOutputRect.Top() + (aInnerRect.GetHeight() - aPictureSize.Height()) / 2 );
DrawImage( aPicturePos, m_aPicture, 0 );
}
//--------------------------------------------------------------------
void HelpAgentWindow::MouseButtonUp( const MouseEvent& rMEvt )
{
FloatingWindow::MouseButtonUp(rMEvt);
if (m_pCallback)
m_pCallback->helpRequested();
}
//--------------------------------------------------------------------
Size HelpAgentWindow::implOptimalButtonSize( const Image& _rButtonImage )
{
Size aPreferredSize = _rButtonImage.GetSizePixel();
// add a small frame, needed by the button
aPreferredSize.Width() += 5;
aPreferredSize.Height() += 5;
return aPreferredSize;
}
//--------------------------------------------------------------------
void HelpAgentWindow::Resize()
{
FloatingWindow::Resize();
Size aOutputSize = GetOutputSizePixel();
Size aCloserSize = m_pCloser->GetSizePixel();
if (m_pCloser)
m_pCloser->SetPosPixel( Point(aOutputSize.Width() - aCloserSize.Width() - 3, 4) );
}
//--------------------------------------------------------------------
IMPL_LINK( HelpAgentWindow, OnButtonClicked, Window*, _pWhichOne )
{
if (m_pCloser == _pWhichOne)
if (m_pCallback)
m_pCallback->closeAgent();
return 0L;
}
//........................................................................
} // namespace svt
//........................................................................
<commit_msg>INTEGRATION: CWS frmcontrols04 (1.8.254); FILE MERGED 2004/03/31 10:28:36 dv 1.8.254.1: #i26046# Use PushButton::GetModeImage() instead of GetImage()<commit_after>/*************************************************************************
*
* $RCSfile: helpagentwindow.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2004-07-05 16:17:04 $
*
* 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 EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVTOOLS_HELPAGENTWIDNOW_HXX_
#include "helpagentwindow.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SV_BITMAP_HXX
#include <vcl/bitmap.hxx>
#endif
#ifndef _SVTOOLS_SVTDATA_HXX
#include <svtdata.hxx>
#endif
#ifndef _SVTOOLS_HRC
#include "svtools.hrc"
#endif
#ifndef _SVT_HELPID_HRC
#include "helpid.hrc"
#endif
#define WB_AGENT_STYLE 0
//........................................................................
namespace svt
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::lang;
//====================================================================
//= CloserButton_Impl
//= overload of ImageButton, because sometimes vcl doesn't call the click handler
//====================================================================
//--------------------------------------------------------------------
class CloserButton_Impl : public ImageButton
{
public:
CloserButton_Impl( Window* pParent, WinBits nBits ) : ImageButton( pParent, nBits ) {}
virtual void MouseButtonUp( const MouseEvent& rMEvt );
};
//--------------------------------------------------------------------
void CloserButton_Impl::MouseButtonUp( const MouseEvent& rMEvt )
{
ImageButton::MouseButtonUp( rMEvt );
GetClickHdl().Call( this );
}
//====================================================================
//= HelpAgentWindow
//====================================================================
//--------------------------------------------------------------------
HelpAgentWindow::HelpAgentWindow( Window* _pParent )
:FloatingWindow( _pParent, WB_AGENT_STYLE)
,m_pCloser(NULL)
,m_pCallback(NULL)
{
// -----------------
// the closer button
Bitmap aCloserBitmap(SvtResId(BMP_HELP_AGENT_CLOSER));
Image aCloserImage( aCloserBitmap, Color(COL_LIGHTMAGENTA) );
m_pCloser = new CloserButton_Impl( this, WB_NOTABSTOP | WB_NOPOINTERFOCUS );
static_cast<CloserButton_Impl*>(m_pCloser)->SetModeImage( aCloserImage );
static_cast<CloserButton_Impl*>(m_pCloser)->SetClickHdl( LINK(this, HelpAgentWindow, OnButtonClicked) );
m_pCloser->SetSizePixel( implOptimalButtonSize(aCloserImage) );
m_pCloser->Show();
m_pCloser->SetZOrder( NULL, WINDOW_ZORDER_LAST );
// ----------------------------
// calculate our preferred size
Bitmap aHelpAgentBitmap(SvtResId(BMP_HELP_AGENT_IMAGE));
m_aPicture = Image( aHelpAgentBitmap );
m_aPreferredSize = m_aPicture.GetSizePixel();
m_aPreferredSize.Width() += 2;
m_aPreferredSize.Height() += 2;
Size aSize = GetSizePixel();
Size aOutputSize = GetOutputSizePixel();
m_aPreferredSize.Width() += aSize.Width() - aOutputSize.Width();
m_aPreferredSize.Height() += aSize.Height() - aOutputSize.Height();
SetPointer(Pointer(POINTER_REFHAND));
AlwaysEnableInput( TRUE, TRUE );
// unique id for the testtool
SetUniqueId( HID_HELPAGENT_WINDOW );
}
//--------------------------------------------------------------------
HelpAgentWindow::~HelpAgentWindow()
{
if (m_pCloser && m_pCloser->IsTracking())
m_pCloser->EndTracking();
if (m_pCloser && m_pCloser->IsMouseCaptured())
m_pCloser->ReleaseMouse();
delete m_pCloser;
}
//--------------------------------------------------------------------
void HelpAgentWindow::Paint( const Rectangle& rRect )
{
FloatingWindow::Paint(rRect);
Size aOutputSize( GetOutputSizePixel() );
Point aPoint=Point();
Rectangle aOutputRect( aPoint, aOutputSize );
Rectangle aInnerRect( aOutputRect );
// paint the background
SetLineColor( GetSettings().GetStyleSettings().GetFaceColor() );
SetFillColor( GetSettings().GetStyleSettings().GetFaceColor() );
DrawRect( aOutputRect );
// paint the image
Size aPictureSize( m_aPicture.GetSizePixel() );
Point aPicturePos(
aOutputRect.Left() + (aInnerRect.GetWidth() - aPictureSize.Width()) / 2,
aOutputRect.Top() + (aInnerRect.GetHeight() - aPictureSize.Height()) / 2 );
DrawImage( aPicturePos, m_aPicture, 0 );
}
//--------------------------------------------------------------------
void HelpAgentWindow::MouseButtonUp( const MouseEvent& rMEvt )
{
FloatingWindow::MouseButtonUp(rMEvt);
if (m_pCallback)
m_pCallback->helpRequested();
}
//--------------------------------------------------------------------
Size HelpAgentWindow::implOptimalButtonSize( const Image& _rButtonImage )
{
Size aPreferredSize = _rButtonImage.GetSizePixel();
// add a small frame, needed by the button
aPreferredSize.Width() += 5;
aPreferredSize.Height() += 5;
return aPreferredSize;
}
//--------------------------------------------------------------------
void HelpAgentWindow::Resize()
{
FloatingWindow::Resize();
Size aOutputSize = GetOutputSizePixel();
Size aCloserSize = m_pCloser->GetSizePixel();
if (m_pCloser)
m_pCloser->SetPosPixel( Point(aOutputSize.Width() - aCloserSize.Width() - 3, 4) );
}
//--------------------------------------------------------------------
IMPL_LINK( HelpAgentWindow, OnButtonClicked, Window*, _pWhichOne )
{
if (m_pCloser == _pWhichOne)
if (m_pCallback)
m_pCallback->closeAgent();
return 0L;
}
//........................................................................
} // namespace svt
//........................................................................
<|endoftext|> |
<commit_before>#include "PyMeshPlugin.hh"
// todo: some switch for boost static build or not
#include <boost/python.hpp>
#include <OpenFlipper/BasePlugin/PluginFunctions.hh>
#include <OpenFlipper/common/GlobalOptions.hh>
// adds openmesh python module for inter language communication
#include <OpenMesh/src/Python/Bindings.cc>
#include "MeshFactory.hh"
#include <QFileDialog>
//fix for msvc 2015 update 3, delete in future
namespace boost
{
template <>
OpenMesh::TriMesh_ArrayKernelT<struct OpenMesh::Python::MeshTraits> const volatile * get_pointer<OpenMesh::TriMesh_ArrayKernelT<struct OpenMesh::Python::MeshTraits> const volatile >(
OpenMesh::TriMesh_ArrayKernelT<struct OpenMesh::Python::MeshTraits> const volatile *c)
{
return c;
}
}
PyMeshPlugin::PyMeshPlugin()
{
}
PyMeshPlugin::~PyMeshPlugin()
{
Py_Finalize();
}
void PyMeshPlugin::initializePlugin()
{
}
void PyMeshPlugin::slotSelectFile()
{
QString fileName = QFileDialog::getOpenFileName(NULL,
tr("Open Python Script"), toolbox_->filename->text(), tr("Python Script (*.py)"));
if (!QFile::exists(fileName))
return;
toolbox_->filename->setText(fileName);
}
void PyMeshPlugin::pluginsInitialized()
{
toolbox_ = new PyMeshToolbox();
Q_EMIT addToolbox("PyMesh", toolbox_);
toolbox_->pbRunFile->setIcon(QIcon(OpenFlipper::Options::iconDirStr() + OpenFlipper::Options::dirSeparator() + "arrow-right.png"));
toolbox_->pbRunFile->setText("");
toolbox_->pbFileSelect->setIcon(QIcon(OpenFlipper::Options::iconDirStr() + OpenFlipper::Options::dirSeparator() + "document-open.png"));
toolbox_->pbFileSelect->setText("");
toolbox_->filename->setText(OpenFlipperSettings().value("Plugin-PyMesh/LastOpenedFile",
OpenFlipper::Options::applicationDirStr() + OpenFlipper::Options::dirSeparator()).toString());
connect(toolbox_->pbRunFile, SIGNAL(clicked()), this, SLOT(slotRunScript()));
connect(toolbox_->pbFileSelect, SIGNAL(clicked()), this, SLOT(slotSelectFile()));
}
void PyMeshPlugin::slotRunScript()
{
const QString filename = toolbox_->filename->text();
OpenFlipperSettings().setValue("Plugin-PyMesh/LastOpenedFile", filename);
runPyScriptFile(filename, toolbox_->cbClearPrevious->isChecked());
}
////////////////////////////////////////////////////////////////
// Python Interpreter Setup&Run
void PyMeshPlugin::runPyScriptFile(const QString& _filename, bool _clearPrevious)
{
QFile f(_filename);
if (!f.exists())
{
Q_EMIT log(LOGERR, QString("Could not find file %1").arg(_filename));
}
f.open(QFile::ReadOnly);
runPyScript(QTextStream(&f).readAll(), _clearPrevious);
}
void PyMeshPlugin::runPyScript(const QString& _script, bool _clearPrevious)
{
// init
initPython();
// clear env
if (_clearPrevious)
for (size_t i = 0; i < m_createdObjects.size(); ++i)
Q_EMIT deleteObject(m_createdObjects[i]);
m_createdObjects.clear();
// Run Script
PyRun_SimpleString(_script.toLatin1());
// Update
for (size_t i = 0; i < m_createdObjects.size(); ++i)
{
Q_EMIT updatedObject(m_createdObjects[i], UPDATE_ALL);
Q_EMIT createBackup(m_createdObjects[i], "Original Object");
}
PluginFunctions::viewAll();
}
void PyMeshPlugin::initPython()
{
if (Py_IsInitialized())
return;
#if (PY_MAJOR_VERSION == 2)
PyImport_AppendInittab("openmesh", &OpenMesh::Python::initopenmesh); //untested
#elif (PY_MAJOR_VERSION == 3)
PyImport_AppendInittab("openmesh", &OpenMesh::Python::PyInit_openmesh);
#endif
Py_Initialize();
boost::python::object main_module(PyImport_AddModule("__main__"));
initPyLogger(main_module.ptr(), this);
// add openmesh module
boost::python::object main_namespace = main_module.attr("__dict__");
boost::python::object om_module((boost::python::handle<>(PyImport_ImportModule("openmesh"))));
main_namespace["openmesh"] = om_module;
// hook into constructors
registerFactoryMethods(this, om_module);
}
///////////////////////////////////////////////////////////////////
// Python callback functions
void PyMeshPlugin::pyOutput(const char* w)
{
Q_EMIT log(LOGOUT, QString(w));
}
void PyMeshPlugin::pyError(const char* w)
{
Q_EMIT log(LOGERR, QString(w));
}
OpenMesh::Python::TriMesh* PyMeshPlugin::createTriMesh()
{
int objectId = -1;
Q_EMIT addEmptyObject(DATA_TRIANGLE_MESH, objectId);
TriMeshObject* object;
PluginFunctions::getObject(objectId, object);
m_createdObjects.push_back(objectId);
return reinterpret_cast<OpenMesh::Python::TriMesh*>(object->mesh());
}
OpenMesh::Python::PolyMesh* PyMeshPlugin::createPolyMesh()
{
int objectId = -1;
Q_EMIT addEmptyObject(DATA_POLY_MESH, objectId);
PolyMeshObject* object;
PluginFunctions::getObject(objectId, object);
m_createdObjects.push_back(objectId);
return reinterpret_cast<OpenMesh::Python::PolyMesh*>(object->mesh());
}
<commit_msg>add missing handle construction for main module<commit_after>#include "PyMeshPlugin.hh"
// todo: some switch for boost static build or not
#include <boost/python.hpp>
#include <OpenFlipper/BasePlugin/PluginFunctions.hh>
#include <OpenFlipper/common/GlobalOptions.hh>
// adds openmesh python module for inter language communication
#include <OpenMesh/src/Python/Bindings.cc>
#include "MeshFactory.hh"
#include <QFileDialog>
//fix for msvc 2015 update 3, delete in future
namespace boost
{
template <>
OpenMesh::TriMesh_ArrayKernelT<struct OpenMesh::Python::MeshTraits> const volatile * get_pointer<OpenMesh::TriMesh_ArrayKernelT<struct OpenMesh::Python::MeshTraits> const volatile >(
OpenMesh::TriMesh_ArrayKernelT<struct OpenMesh::Python::MeshTraits> const volatile *c)
{
return c;
}
}
PyMeshPlugin::PyMeshPlugin()
{
}
PyMeshPlugin::~PyMeshPlugin()
{
Py_Finalize();
}
void PyMeshPlugin::initializePlugin()
{
}
void PyMeshPlugin::slotSelectFile()
{
QString fileName = QFileDialog::getOpenFileName(NULL,
tr("Open Python Script"), toolbox_->filename->text(), tr("Python Script (*.py)"));
if (!QFile::exists(fileName))
return;
toolbox_->filename->setText(fileName);
}
void PyMeshPlugin::pluginsInitialized()
{
toolbox_ = new PyMeshToolbox();
Q_EMIT addToolbox("PyMesh", toolbox_);
toolbox_->pbRunFile->setIcon(QIcon(OpenFlipper::Options::iconDirStr() + OpenFlipper::Options::dirSeparator() + "arrow-right.png"));
toolbox_->pbRunFile->setText("");
toolbox_->pbFileSelect->setIcon(QIcon(OpenFlipper::Options::iconDirStr() + OpenFlipper::Options::dirSeparator() + "document-open.png"));
toolbox_->pbFileSelect->setText("");
toolbox_->filename->setText(OpenFlipperSettings().value("Plugin-PyMesh/LastOpenedFile",
OpenFlipper::Options::applicationDirStr() + OpenFlipper::Options::dirSeparator()).toString());
connect(toolbox_->pbRunFile, SIGNAL(clicked()), this, SLOT(slotRunScript()));
connect(toolbox_->pbFileSelect, SIGNAL(clicked()), this, SLOT(slotSelectFile()));
}
void PyMeshPlugin::slotRunScript()
{
const QString filename = toolbox_->filename->text();
OpenFlipperSettings().setValue("Plugin-PyMesh/LastOpenedFile", filename);
runPyScriptFile(filename, toolbox_->cbClearPrevious->isChecked());
}
////////////////////////////////////////////////////////////////
// Python Interpreter Setup&Run
void PyMeshPlugin::runPyScriptFile(const QString& _filename, bool _clearPrevious)
{
QFile f(_filename);
if (!f.exists())
{
Q_EMIT log(LOGERR, QString("Could not find file %1").arg(_filename));
}
f.open(QFile::ReadOnly);
runPyScript(QTextStream(&f).readAll(), _clearPrevious);
}
void PyMeshPlugin::runPyScript(const QString& _script, bool _clearPrevious)
{
// init
initPython();
// clear env
if (_clearPrevious)
for (size_t i = 0; i < m_createdObjects.size(); ++i)
Q_EMIT deleteObject(m_createdObjects[i]);
m_createdObjects.clear();
// Run Script
PyRun_SimpleString(_script.toLatin1());
// Update
for (size_t i = 0; i < m_createdObjects.size(); ++i)
{
Q_EMIT updatedObject(m_createdObjects[i], UPDATE_ALL);
Q_EMIT createBackup(m_createdObjects[i], "Original Object");
}
PluginFunctions::viewAll();
}
void PyMeshPlugin::initPython()
{
if (Py_IsInitialized())
return;
#if (PY_MAJOR_VERSION == 2)
PyImport_AppendInittab("openmesh", &OpenMesh::Python::initopenmesh); //untested
#elif (PY_MAJOR_VERSION == 3)
PyImport_AppendInittab("openmesh", &OpenMesh::Python::PyInit_openmesh);
#endif
Py_Initialize();
boost::python::object main_module(boost::python::handle<>(PyImport_AddModule("__main__")));
// redirect python output
initPyLogger(main_module.ptr(), this);
// add openmesh module
boost::python::object main_namespace = main_module.attr("__dict__");
boost::python::object om_module((boost::python::handle<>(PyImport_ImportModule("openmesh"))));
main_namespace["openmesh"] = om_module;
// hook into mesh constructors
registerFactoryMethods(this, om_module);
}
///////////////////////////////////////////////////////////////////
// Python callback functions
void PyMeshPlugin::pyOutput(const char* w)
{
Q_EMIT log(LOGOUT, QString(w));
}
void PyMeshPlugin::pyError(const char* w)
{
Q_EMIT log(LOGERR, QString(w));
}
OpenMesh::Python::TriMesh* PyMeshPlugin::createTriMesh()
{
int objectId = -1;
Q_EMIT addEmptyObject(DATA_TRIANGLE_MESH, objectId);
TriMeshObject* object;
PluginFunctions::getObject(objectId, object);
m_createdObjects.push_back(objectId);
return reinterpret_cast<OpenMesh::Python::TriMesh*>(object->mesh());
}
OpenMesh::Python::PolyMesh* PyMeshPlugin::createPolyMesh()
{
int objectId = -1;
Q_EMIT addEmptyObject(DATA_POLY_MESH, objectId);
PolyMeshObject* object;
PluginFunctions::getObject(objectId, object);
m_createdObjects.push_back(objectId);
return reinterpret_cast<OpenMesh::Python::PolyMesh*>(object->mesh());
}
<|endoftext|> |
<commit_before>#include "../test.h"
#include <cuda_runtime_api.h>
#include <memory>
#include <vector>
#include <Eigen/Core>
#include "../cuda_array_mapper.h"
#include "../../src/utils/image_persister.h"
#include "../../src/utils/path_helper.h"
#include "../../src/placement/apollonius.h"
#include "../../src/utils/cuda_helper.h"
std::vector<int> callApollonoius(std::vector<Eigen::Vector4f> &image,
std::vector<float> distances, int imageSize,
std::vector<Eigen::Vector4f> labelsSeed)
{
cudaChannelFormatDesc channelDesc =
cudaCreateChannelDesc(32, 32, 32, 32, cudaChannelFormatKindFloat);
int labelCount = labelsSeed.size();
auto imageMapper = std::make_shared<CudaArrayMapper<Eigen::Vector4f>>(
imageSize, imageSize, image, channelDesc);
cudaChannelFormatDesc channelDescDistances =
cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKindFloat);
auto distancesMapper = std::make_shared<CudaArrayMapper<float>>(
imageSize, imageSize, distances, channelDescDistances);
Apollonius apollonius(distancesMapper, imageMapper, labelsSeed, labelCount);
apollonius.run();
image = imageMapper->copyDataFromGpu();
imageMapper->unmap();
std::vector<int> result;
thrust::host_vector<int> labelIndices = apollonius.getIds();
for (auto index : labelIndices)
result.push_back(index);
return result;
}
TEST(Test_Apollonius, Apollonius)
{
std::vector<Eigen::Vector4f> image;
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Ones());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
std::vector<float> distances(16, 0);
distances[5] = 1.0f;
distances[6] = 1.0f;
distances[9] = 1.0f;
distances[10] = 1.0f;
std::vector<Eigen::Vector4f> labelsSeed = { Eigen::Vector4f(0, 2, 1, 1) };
auto insertionOrder = callApollonoius(image, distances, 4, labelsSeed);
ASSERT_EQ(1, insertionOrder.size());
EXPECT_EQ(0, insertionOrder[0]);
ASSERT_EQ(16, image.size());
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[0], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[1], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[2], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[3], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[4], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[5], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[6], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[7], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[8], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[9], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[10], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[11], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[12], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[13], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[14], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[15], 1e-4f);
}
TEST(Test_Apollonius, ApolloniusWithRealData)
{
auto distances = ImagePersister::loadR32F(absolutePathOfProjectRelativePath(
std::string("assets/tests/distanceTransform.tiff")));
int imageSize = sqrt(distances.size());
auto outputImage = std::vector<Eigen::Vector4f>(distances.size());
std::vector<Eigen::Vector4f> labelsSeed = {
Eigen::Vector4f(1, 302.122, 401.756, 1),
Eigen::Vector4f(2, 342.435, 337.859, 1),
Eigen::Vector4f(3, 327.202, 370.684, 1),
Eigen::Vector4f(4, 266.133, 367.162, 1),
};
auto insertionOrder =
callApollonoius(outputImage, distances, imageSize, labelsSeed);
auto expected = ImagePersister::loadRGBA32F(absolutePathOfProjectRelativePath(
std::string("assets/tests/apollonius.tiff")));
ImagePersister::saveRGBA32F(outputImage.data(), imageSize, imageSize,
"ApolloniusWithRealDataOutput.tiff");
int diffCount = 0;
for (unsigned int i = 0; i < outputImage.size(); ++i)
{
if ((expected[i] - outputImage[i]).norm() > 1e-4f)
{
std::cout << "expected for index " << i << ": " << expected[i]
<< " but was: " << outputImage[i] << std::endl;
diffCount++;
}
}
EXPECT_LE(diffCount, 10);
}
<commit_msg>Extract some factory functions.<commit_after>#include "../test.h"
#include <cuda_runtime_api.h>
#include <memory>
#include <vector>
#include <Eigen/Core>
#include "../cuda_array_mapper.h"
#include "../../src/utils/image_persister.h"
#include "../../src/utils/path_helper.h"
#include "../../src/placement/apollonius.h"
#include "../../src/utils/cuda_helper.h"
std::shared_ptr<CudaArrayMapper<Eigen::Vector4f>>
createCudaArrayMapper(int width, int height, std::vector<Eigen::Vector4f> data)
{
cudaChannelFormatDesc channelDesc =
cudaCreateChannelDesc(32, 32, 32, 32, cudaChannelFormatKindFloat);
return std::make_shared<CudaArrayMapper<Eigen::Vector4f>>(width, height, data,
channelDesc);
}
std::shared_ptr<CudaArrayMapper<float>>
createCudaArrayMapper(int width, int height, std::vector<float> data)
{
cudaChannelFormatDesc channelDesc =
cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKindFloat);
return std::make_shared<CudaArrayMapper<float>>(width, height, data,
channelDesc);
}
std::vector<int> callApollonoius(std::vector<Eigen::Vector4f> &image,
std::vector<float> distances, int imageSize,
std::vector<Eigen::Vector4f> labelsSeed)
{
int labelCount = labelsSeed.size();
auto imageMapper = createCudaArrayMapper(imageSize, imageSize, image);
auto distancesMapper = createCudaArrayMapper(imageSize, imageSize, distances);
Apollonius apollonius(distancesMapper, imageMapper, labelsSeed, labelCount);
apollonius.run();
image = imageMapper->copyDataFromGpu();
imageMapper->unmap();
std::vector<int> result;
thrust::host_vector<int> labelIndices = apollonius.getIds();
for (auto index : labelIndices)
result.push_back(index);
return result;
}
TEST(Test_Apollonius, Apollonius)
{
std::vector<Eigen::Vector4f> image;
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Ones());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
image.push_back(Eigen::Vector4f::Zero());
std::vector<float> distances(16, 0);
distances[5] = 1.0f;
distances[6] = 1.0f;
distances[9] = 1.0f;
distances[10] = 1.0f;
std::vector<Eigen::Vector4f> labelsSeed = { Eigen::Vector4f(0, 2, 1, 1) };
auto insertionOrder = callApollonoius(image, distances, 4, labelsSeed);
ASSERT_EQ(1, insertionOrder.size());
EXPECT_EQ(0, insertionOrder[0]);
ASSERT_EQ(16, image.size());
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[0], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[1], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[2], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[3], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[4], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[5], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[6], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[7], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[8], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[9], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[10], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[11], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[12], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[13], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[14], 1e-4f);
EXPECT_Vector4f_NEAR(Eigen::Vector4f(0.5f, 0.5f, 0.5f, 1), image[15], 1e-4f);
}
TEST(Test_Apollonius, ApolloniusWithRealData)
{
auto distances = ImagePersister::loadR32F(absolutePathOfProjectRelativePath(
std::string("assets/tests/distanceTransform.tiff")));
int imageSize = sqrt(distances.size());
auto outputImage = std::vector<Eigen::Vector4f>(distances.size());
std::vector<Eigen::Vector4f> labelsSeed = {
Eigen::Vector4f(1, 302.122, 401.756, 1),
Eigen::Vector4f(2, 342.435, 337.859, 1),
Eigen::Vector4f(3, 327.202, 370.684, 1),
Eigen::Vector4f(4, 266.133, 367.162, 1),
};
auto insertionOrder =
callApollonoius(outputImage, distances, imageSize, labelsSeed);
auto expected = ImagePersister::loadRGBA32F(absolutePathOfProjectRelativePath(
std::string("assets/tests/apollonius.tiff")));
ImagePersister::saveRGBA32F(outputImage.data(), imageSize, imageSize,
"ApolloniusWithRealDataOutput.tiff");
int diffCount = 0;
for (unsigned int i = 0; i < outputImage.size(); ++i)
{
if ((expected[i] - outputImage[i]).norm() > 1e-4f)
{
std::cout << "expected for index " << i << ": " << expected[i]
<< " but was: " << outputImage[i] << std::endl;
diffCount++;
}
}
EXPECT_LE(diffCount, 10);
}
<|endoftext|> |
<commit_before>//==================================
//
// Summary: Winged Edge Facilities Test
// Notes:
// Dependencies: N/A
//==================================
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "WingedEdge.h"
#include "Vec.h"
#include <map>
#include <vector>
#include <tuple>
#include <utility>
#include <set>
#include <iostream>
using namespace std;
using namespace Winged_Edge;
TEST_CASE( "Basic", "[B]" ) {
MapEdge map_edge;
MapFace map_face;
vector< Edge * > edges;
for( int i = 0; i < 5; i++ ){
Edge * e = new Edge;
e->data = i;
edges.push_back( e );
}
vector< Vertex * > vertices;
for( int i = 0; i < 4; i++ ){
Vertex * v = new Vertex;
float vec_position[3];
vec_position[0] = i;
vec_position[1] = (i*2-5)^3;
vec_position[2] = i*3-4;
v->pos.SetFromArray( 3, vec_position );
v->data = i;
vertices.push_back( v );
}
//link edges and vertices
map_edge[ edges[0] ] = std::make_pair( vertices[0], vertices[1] );
map_edge[ edges[1] ] = std::make_pair( vertices[1], vertices[2] );
map_edge[ edges[2] ] = std::make_pair( vertices[2], vertices[0] );
map_edge[ edges[3] ] = std::make_pair( vertices[2], vertices[3] );
map_edge[ edges[4] ] = std::make_pair( vertices[3], vertices[1] );
vector< Face * > faces;
for( int i = 0; i < 2; i++ ){
Face * f = new Face;
f->data = i;
faces.push_back( f );
}
//link faces and edges
bool bClockWise = true;
map_face[ faces[0] ] = std::make_tuple( vertices[0], vertices[1], vertices[2], bClockWise );
map_face[ faces[1] ] = std::make_tuple( vertices[1], vertices[2], vertices[3], !bClockWise );
//generate winged edges
vector< WingedEdge * > generated_wedges;
Generate_WingedEdge( map_edge, map_face, generated_wedges );
//verify generated wedges
// bool Get_Edge_CW_Next( WingedEdge * WEdge, WingedEdge * Next );
// bool Get_Edge_CW_Prev( WingedEdge * WEdge, WingedEdge * Prev );
// bool Get_Edge_CCW_Next( WingedEdge * WEdge, WingedEdge * Next );
// bool Get_Edge_CCW_Prev( WingedEdge * WEdge, WingedEdge * Prev );
// bool Get_Face_Left( WingedEdge * WEdge, Face * FaceLeft );
// bool Get_Face_Right( WingedEdge * WEdge, Face * FaceRight );
// bool Get_Vertex_Start( WingedEdge * WEdge, Vertex * VertexStart );
// bool Get_Vertex_End( WingedEdge * WEdge, Vertex * VertexEnd );
SECTION( "Check size of generated entities" ){
CHECK( 5 == generated_wedges.size() ); //check size of winged edges
set< Face * > generated_faces;
int count_face_left = 0;
int count_face_right = 0;
for( auto i : generated_wedges ){
Face * left_face;
if( Get_Face_Left( i, left_face ) ){
count_face_left++;
generated_faces.insert( left_face );
}
Face * right_face;
if( Get_Face_Right( i, right_face ) ){
count_face_right++;
generated_faces.insert( right_face );
}
}
CHECK( 3 == count_face_left ); //check number of edges linked with a left face
CHECK( 3 == count_face_right ); //check number of edges linked with a right face
CHECK( 2 == generated_faces.size() ); //check number of faces
}
SECTION( "Check entity linkage" ){
for( auto i : generated_wedges ){
//first triangle
if( i->E_Current->data == 0 ){
vector<int> expected_data { 1, 2, 0 };
WingedEdge * Current = i;
WingedEdge * Next = 0;
for( auto j: expected_data ){
bool bRet = Get_Edge_CW_Next( Current, Next );
CHECK( true == bRet );
CHECK( j == Next->E_Current->data );
Current = Next;
Next = 0;
}
vector<int> expected_data_reverse { 2, 1, 0 };
Current = i;
Next = 0;
for( auto j: expected_data_reverse ){
bool bRet = Get_Edge_CW_Prev( Current, Next );
CHECK( true == bRet );
CHECK( j == Next->E_Current->data );
Current = Next;
Next = 0;
}
}
//second triangle
if( i->E_Current->data == 3 ){
vector<int> expected_data { 4, 1, 3 };
WingedEdge * Current = i;
WingedEdge * Next = 0;
for( auto j: expected_data ){
bool bRet = Get_Edge_CCW_Next( Current, Next );
CHECK( true == bRet );
CHECK( j == Next->E_Current->data );
Current = Next;
Next = 0;
}
}
}
}
SECTION( "Check WingedEdge-WingedEdge-... linkage" ){
WingedEdge * Start;
WingedEdge * End;
for( auto i : generated_wedges ){
if( i->E_Current->data == 2 ){
Start = i;
}
if( i->E_Current->data == 4 ){
End = i;
}
}
std::vector< WingedEdge * > Path;
CHECK( Search_WEdge_To_WEdge( Start, End, Path ) );
cout << "WingedEdge-...-WingedEdge: " << endl;
cout << "Search path: ";
for( auto j : Path ){
cout << j->E_Current->data << " ";
}
cout<<endl;
CHECK( ( 3 == Path.size() || 4 == Path.size() )); //seems to have an fluctuation of 1 size difference between computers
}
SECTION( "Check Face-WingedEdge-...-Face linkage" ){
Face * Start;
Face * End;
for( auto i : generated_wedges ){
if( i->E_Current->data == 0 ){
Start = i->F_Right;
}
if( i->E_Current->data == 4 ){
End = i->F_Left;
}
}
std::vector< WingedEdge * > Path_WEdges;
std::vector< Face * > Path_Faces;
CHECK( Search_Face_To_Face( Start, End, Path_Faces, Path_WEdges ) );
cout << "Face-WingedEdge-...-Face: " << endl;
cout << "Search path faces: ";
for( auto j : Path_Faces ){
cout << j->data << " ";
}
cout<<endl;
cout << "Search path winged edges: ";
for( auto j : Path_WEdges ){
cout << j->E_Current->data << " ";
}
cout<<endl;
CHECK( 2 == Path_Faces.size() );
CHECK( 1 == Path_WEdges.size() );
}
SECTION( "Check Vertex-WingedEdge-...-Vertex linkage" ){
Vertex * Start;
Vertex * End;
for( auto i : generated_wedges ){
std::set< Vertex * > vertices;
Get_WingedEdge_Neighour_Vertices( i, vertices );
for( auto j : vertices ){
if( 0 == j->data ){
Start = j;
}else if( 3 == j->data ){
End = j;
}
}
}
std::vector< WingedEdge * > Path_WEdges;
std::vector< Vertex * > Path_Vertices;
CHECK( Search_Vertex_To_Vertex( Start, End, Path_Vertices, Path_WEdges ) );
cout << "Vertex-WingedEdge-...-Vertex: " << endl;
cout << "Search path vertices: ";
for( auto j : Path_Vertices ){
cout << j->data << " ";
}
cout<<endl;
cout << "Search path winged edges: ";
for( auto j : Path_WEdges ){
cout << j->E_Current->data << " ";
}
cout<<endl;
//TODO: need to modify search to be minimal
CHECK( ( 3 == Path_Vertices.size() || 4 == Path_Vertices.size() ) );
CHECK( ( 2 == Path_WEdges.size() || 3 == Path_WEdges.size() ) );
}
SECTION( "Check GetAllLinked()" ){
cout << "Get All Linked: " << endl;
Vertex * Start;
for( auto i : generated_wedges ){
std::set< Vertex * > vertices;
Get_WingedEdge_Neighour_Vertices( i, vertices );
for( auto j : vertices ){
if( 0 == j->data ){
Start = j;
}
}
}
std::set< Face * > linked_faces;
std::set< WingedEdge * > linked_WEdges;
std::set< Vertex * > linked_vertices;
CHECK( GetAllLinked( Start, linked_faces, linked_WEdges, linked_vertices ) );
cout << "Get all faces: ";
for( auto j : linked_faces ){
cout << j->data << " ";
}
cout<<endl;
cout << "Get all wedges: ";
for( auto j : linked_WEdges ){
cout << j->E_Current->data << " ";
}
cout<<endl;
cout << "Get all vertices: ";
for( auto j : linked_vertices ){
cout << j->data << " ";
}
cout<<endl;
CHECK( 2 == linked_faces.size() );
CHECK( 5 == linked_WEdges.size() );
CHECK( 4 == linked_vertices.size() );
}
SECTION( "Check GetTriangles()" ){
cout << "Get Triangles: " << endl;
set< Face * > allfaces( faces.begin(), faces.end() );
vector< Vec > vertices_pos;
vector< Vec > vertices_normal;
bool bRet = GetTriangles( allfaces, vertices_pos, vertices_normal );
CHECK( bRet );
CHECK( 6 == vertices_pos.size() );
CHECK( 6 == vertices_normal.size() );
cout << "Vertex Position: " << endl;
for( auto i : vertices_pos ){
cout << i._vec[0] << ", " << i._vec[1] << ", " << i._vec[2] << endl;
}
cout << "Vertex Normals: " << endl;
for( auto i : vertices_normal ){
cout << i._vec[0] << ", " << i._vec[1] << ", " << i._vec[2] << endl;
}
}
}
<commit_msg>modified test for WingedEdge due to earlier change in MapFace<commit_after>//==================================
//
// Summary: Winged Edge Facilities Test
// Notes:
// Dependencies: N/A
//==================================
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "WingedEdge.h"
#include "Vec.h"
#include <map>
#include <vector>
#include <tuple>
#include <utility>
#include <set>
#include <iostream>
using namespace std;
using namespace Winged_Edge;
TEST_CASE( "Basic", "[B]" ) {
MapEdge map_edge;
MapFace map_face;
vector< Edge * > edges;
for( int i = 0; i < 5; i++ ){
Edge * e = new Edge;
e->data = i;
edges.push_back( e );
}
vector< Vertex * > vertices;
for( int i = 0; i < 4; i++ ){
Vertex * v = new Vertex;
float vec_position[3];
vec_position[0] = i;
vec_position[1] = (i*2-5)^3;
vec_position[2] = i*3-4;
v->pos.SetFromArray( 3, vec_position );
v->data = i;
vertices.push_back( v );
}
//link edges and vertices
map_edge[ edges[0] ] = std::make_pair( vertices[0], vertices[1] );
map_edge[ edges[1] ] = std::make_pair( vertices[1], vertices[2] );
map_edge[ edges[2] ] = std::make_pair( vertices[2], vertices[0] );
map_edge[ edges[3] ] = std::make_pair( vertices[2], vertices[3] );
map_edge[ edges[4] ] = std::make_pair( vertices[3], vertices[1] );
vector< Face * > faces;
for( int i = 0; i < 2; i++ ){
Face * f = new Face;
f->data = i;
faces.push_back( f );
}
//link faces and edges
bool bCounterClockWise = true;
bool bNormalCCW = true;
map_face[ faces[0] ] = std::make_tuple( vertices[0], vertices[1], vertices[2], !bCounterClockWise, !bNormalCCW );
map_face[ faces[1] ] = std::make_tuple( vertices[1], vertices[2], vertices[3], bCounterClockWise, bNormalCCW );
//generate winged edges
vector< WingedEdge * > generated_wedges;
Generate_WingedEdge( map_edge, map_face, generated_wedges );
SECTION( "Check size of generated entities" ){
CHECK( 5 == generated_wedges.size() ); //check size of winged edges
set< Face * > generated_faces;
int count_face_left = 0;
int count_face_right = 0;
for( auto i : generated_wedges ){
Face * left_face;
if( Get_Face_Left( i, left_face ) ){
count_face_left++;
generated_faces.insert( left_face );
}
Face * right_face;
if( Get_Face_Right( i, right_face ) ){
count_face_right++;
generated_faces.insert( right_face );
}
}
CHECK( 3 == count_face_left ); //check number of edges linked with a left face
CHECK( 3 == count_face_right ); //check number of edges linked with a right face
CHECK( 2 == generated_faces.size() ); //check number of faces
}
SECTION( "Check entity linkage" ){
for( auto i : generated_wedges ){
//first triangle
if( i->E_Current->data == 0 ){
vector<int> expected_data { 1, 2, 0 };
WingedEdge * Current = i;
WingedEdge * Next = 0;
for( auto j: expected_data ){
bool bRet = Get_Edge_CW_Next( Current, Next );
CHECK( true == bRet );
CHECK( j == Next->E_Current->data );
Current = Next;
Next = 0;
}
vector<int> expected_data_reverse { 2, 1, 0 };
Current = i;
Next = 0;
for( auto j: expected_data_reverse ){
bool bRet = Get_Edge_CW_Prev( Current, Next );
CHECK( true == bRet );
CHECK( j == Next->E_Current->data );
Current = Next;
Next = 0;
}
}
//second triangle
if( i->E_Current->data == 3 ){
vector<int> expected_data { 4, 1, 3 };
WingedEdge * Current = i;
WingedEdge * Next = 0;
for( auto j: expected_data ){
bool bRet = Get_Edge_CCW_Next( Current, Next );
CHECK( true == bRet );
CHECK( j == Next->E_Current->data );
Current = Next;
Next = 0;
}
}
}
}
SECTION( "Check WingedEdge-WingedEdge-... linkage" ){
WingedEdge * Start;
WingedEdge * End;
for( auto i : generated_wedges ){
if( i->E_Current->data == 2 ){
Start = i;
}
if( i->E_Current->data == 4 ){
End = i;
}
}
std::vector< WingedEdge * > Path;
CHECK( Search_WEdge_To_WEdge( Start, End, Path ) );
cout << "WingedEdge-...-WingedEdge: " << endl;
cout << "Search path: ";
for( auto j : Path ){
cout << j->E_Current->data << " ";
}
cout<<endl;
CHECK( ( 3 == Path.size() || 4 == Path.size() )); //seems to have an fluctuation of 1 size difference between computers
}
SECTION( "Check Face-WingedEdge-...-Face linkage" ){
Face * Start;
Face * End;
for( auto i : generated_wedges ){
if( i->E_Current->data == 0 ){
Start = i->F_Right;
}
if( i->E_Current->data == 4 ){
End = i->F_Left;
}
}
std::vector< WingedEdge * > Path_WEdges;
std::vector< Face * > Path_Faces;
CHECK( Search_Face_To_Face( Start, End, Path_Faces, Path_WEdges ) );
cout << "Face-WingedEdge-...-Face: " << endl;
cout << "Search path faces: ";
for( auto j : Path_Faces ){
cout << j->data << " ";
}
cout<<endl;
cout << "Search path winged edges: ";
for( auto j : Path_WEdges ){
cout << j->E_Current->data << " ";
}
cout<<endl;
CHECK( 2 == Path_Faces.size() );
CHECK( 1 == Path_WEdges.size() );
}
SECTION( "Check Vertex-WingedEdge-...-Vertex linkage" ){
Vertex * Start;
Vertex * End;
for( auto i : generated_wedges ){
std::set< Vertex * > vertices;
Get_WingedEdge_Neighour_Vertices( i, vertices );
for( auto j : vertices ){
if( 0 == j->data ){
Start = j;
}else if( 3 == j->data ){
End = j;
}
}
}
std::vector< WingedEdge * > Path_WEdges;
std::vector< Vertex * > Path_Vertices;
CHECK( Search_Vertex_To_Vertex( Start, End, Path_Vertices, Path_WEdges ) );
cout << "Vertex-WingedEdge-...-Vertex: " << endl;
cout << "Search path vertices: ";
for( auto j : Path_Vertices ){
cout << j->data << " ";
}
cout<<endl;
cout << "Search path winged edges: ";
for( auto j : Path_WEdges ){
cout << j->E_Current->data << " ";
}
cout<<endl;
//TODO: need to modify search to be minimal
CHECK( ( 3 == Path_Vertices.size() || 4 == Path_Vertices.size() ) );
CHECK( ( 2 == Path_WEdges.size() || 3 == Path_WEdges.size() ) );
}
SECTION( "Check GetAllLinked()" ){
cout << "Get All Linked: " << endl;
Vertex * Start;
for( auto i : generated_wedges ){
std::set< Vertex * > vertices;
Get_WingedEdge_Neighour_Vertices( i, vertices );
for( auto j : vertices ){
if( 0 == j->data ){
Start = j;
}
}
}
std::set< Face * > linked_faces;
std::set< WingedEdge * > linked_WEdges;
std::set< Vertex * > linked_vertices;
CHECK( GetAllLinked( Start, linked_faces, linked_WEdges, linked_vertices ) );
cout << "Get all faces: ";
for( auto j : linked_faces ){
cout << j->data << " ";
}
cout<<endl;
cout << "Get all wedges: ";
for( auto j : linked_WEdges ){
cout << j->E_Current->data << " ";
}
cout<<endl;
cout << "Get all vertices: ";
for( auto j : linked_vertices ){
cout << j->data << " ";
}
cout<<endl;
CHECK( 2 == linked_faces.size() );
CHECK( 5 == linked_WEdges.size() );
CHECK( 4 == linked_vertices.size() );
}
SECTION( "Check GetTriangles()" ){
cout << "Get Triangles: " << endl;
set< Face * > allfaces( faces.begin(), faces.end() );
vector< Vec > vertices_pos;
vector< Vec > vertices_normal;
bool bRet = GetTriangles( allfaces, vertices_pos, vertices_normal );
CHECK( bRet );
CHECK( 6 == vertices_pos.size() );
CHECK( 6 == vertices_normal.size() );
cout << "Vertex Position: " << endl;
for( auto i : vertices_pos ){
cout << i._vec[0] << ", " << i._vec[1] << ", " << i._vec[2] << endl;
}
cout << "Vertex Normals: " << endl;
for( auto i : vertices_normal ){
cout << i._vec[0] << ", " << i._vec[1] << ", " << i._vec[2] << endl;
}
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 Artem Pavlenko
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "catch.hpp"
#include <mapnik/util/fs.hpp>
#include <mapnik/util/file_io.hpp>
#include <mapnik/json/topology.hpp>
#include <mapnik/json/topojson_grammar.hpp>
#include <mapnik/json/topojson_utils.hpp>
namespace {
using iterator_type = std::string::const_iterator;
const mapnik::topojson::topojson_grammar<iterator_type> grammar;
bool parse_topology(std::string const& filename, mapnik::topojson::topology & topo)
{
mapnik::util::file file(filename);
std::string buffer;
buffer.resize(file.size());
std::fread(&buffer[0], buffer.size(), 1, file.get());
if (!file) return false;
boost::spirit::standard::space_type space;
iterator_type itr = buffer.begin();
iterator_type end = buffer.end();
bool result = boost::spirit::qi::phrase_parse(itr, end, grammar, space, topo);
return (result && (itr == end));
}
}
TEST_CASE("topology")
{
SECTION("geometry parsing")
{
for (auto const& path : mapnik::util::list_directory("test/data/topojson/"))
{
mapnik::topojson::topology topo;
REQUIRE(parse_topology(path, topo));
for (auto const& geom : topo.geometries)
{
mapnik::box2d<double> box = mapnik::util::apply_visitor(mapnik::topojson::bounding_box_visitor(topo), geom);
CHECK(box.valid());
}
}
}
}
<commit_msg>topojson test - add feature_generator<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 Artem Pavlenko
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "catch.hpp"
#include <mapnik/util/fs.hpp>
#include <mapnik/util/file_io.hpp>
#include <mapnik/json/topology.hpp>
#include <mapnik/json/topojson_grammar.hpp>
#include <mapnik/json/topojson_utils.hpp>
namespace {
using iterator_type = std::string::const_iterator;
const mapnik::topojson::topojson_grammar<iterator_type> grammar;
bool parse_topology(std::string const& filename, mapnik::topojson::topology & topo)
{
mapnik::util::file file(filename);
std::string buffer;
buffer.resize(file.size());
std::fread(&buffer[0], buffer.size(), 1, file.get());
if (!file) return false;
boost::spirit::standard::space_type space;
iterator_type itr = buffer.begin();
iterator_type end = buffer.end();
bool result = boost::spirit::qi::phrase_parse(itr, end, grammar, space, topo);
return (result && (itr == end));
}
}
TEST_CASE("topology")
{
SECTION("geometry parsing")
{
mapnik::value_integer feature_id = 0;
mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>();
mapnik::transcoder tr("utf8");
for (auto const& path : mapnik::util::list_directory("test/data/topojson/"))
{
mapnik::topojson::topology topo;
REQUIRE(parse_topology(path, topo));
for (auto const& geom : topo.geometries)
{
mapnik::box2d<double> bbox = mapnik::util::apply_visitor(mapnik::topojson::bounding_box_visitor(topo), geom);
CHECK(bbox.valid());
mapnik::topojson::feature_generator<mapnik::context_ptr> visitor(ctx, tr, topo, feature_id++);
mapnik::feature_ptr feature = mapnik::util::apply_visitor(visitor, geom);
CHECK(feature);
CHECK(feature->envelope() == bbox);
}
}
}
}
<|endoftext|> |
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
/* Here is the version string - update before a public release */
static char* CondorVersionString = "$Version: 6.1.0 1998/10/29 $";
extern "C" {
char*
CondorVersion()
{
return CondorVersionString;
}
} /* extern "C" */
<commit_msg>Final date for the 6.1.0 release.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
/* Here is the version string - update before a public release */
static char* CondorVersionString = "$Version: 6.1.0 1998/12/07 $";
extern "C" {
char*
CondorVersion()
{
return CondorVersionString;
}
} /* extern "C" */
<|endoftext|> |
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
/* Here is the version string - update before a public release */
/* --- IMPORTANT! THE FORMAT OF THE VERSION STRING IS VERY STRICT
BECAUSE IT IS PARSED AT RUNTIME. DO NOT ALTER THE FORMAT OR ENTER
ANYTHING EXTRA BEFORE THE DATE. IF YOU WISH TO ADD EXTRA INFORMATION,
DO SO _AFTER_ THE DATE AND BEFORE THE TRAILING '$' CHARACTER.
EXAMPLES:
$CondorVersion: 6.1.11 " __DATE__ " WinNTPreview $ [OK]
$CondorVersion: 6.1.11 WinNTPreview " __DATE__ " $ [WRONG!!!]
Any questions? See Todd or Derek. Note: if you mess it up, DaemonCore
will EXCEPT at startup time.
*/
static char* CondorVersionString = "$CondorVersion: 6.1.14 " __DATE__ " $";
/*
This is some wisdom from Cygnus's web page. If you just try to use
the "stringify" operator on a preprocessor directive, you'd get
"PLATFORM", not "Intel Linux" (or whatever the value of PLATFORM
is). That's because the stringify operator is a special case, and
the preprocessor isn't allowed to expand things that are passed to
it. However, by defining two layers of macros, you get the right
behavior, since the first pass converts:
xstr(PLATFORM) -> str(Intel Linux)
and the next pass gives:
str(Intel Linux) -> "Intel Linux"
This is exactly what we want, so we use it. -Derek Wright and Jeff
Ballard, 12/2/99
Also, because the NT build system is totally different, we have to
define the correct platform string right in here. :( -Derek 12/3/99
*/
#if defined(WIN32)
#define PLATFORM INTEL-WINNT40
#endif
#define xstr(s) str(s)
#define str(s) #s
/* Here is the platform string. You don't need to edit this */
static char* CondorPlatformString = "$CondorPlatform: " xstr(PLATFORM) " $";
extern "C" {
char*
CondorVersion( void )
{
return CondorVersionString;
}
char*
CondorPlatform( void )
{
return CondorPlatformString;
}
} /* extern "C" */
<commit_msg>Made the version string on the trunk "6.3.0", since that's what it's going to be.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
/* Here is the version string - update before a public release */
/* --- IMPORTANT! THE FORMAT OF THE VERSION STRING IS VERY STRICT
BECAUSE IT IS PARSED AT RUNTIME. DO NOT ALTER THE FORMAT OR ENTER
ANYTHING EXTRA BEFORE THE DATE. IF YOU WISH TO ADD EXTRA INFORMATION,
DO SO _AFTER_ THE DATE AND BEFORE THE TRAILING '$' CHARACTER.
EXAMPLES:
$CondorVersion: 6.1.11 " __DATE__ " WinNTPreview $ [OK]
$CondorVersion: 6.1.11 WinNTPreview " __DATE__ " $ [WRONG!!!]
Any questions? See Todd or Derek. Note: if you mess it up, DaemonCore
will EXCEPT at startup time.
*/
static char* CondorVersionString = "$CondorVersion: 6.3.0 " __DATE__ " $";
/*
This is some wisdom from Cygnus's web page. If you just try to use
the "stringify" operator on a preprocessor directive, you'd get
"PLATFORM", not "Intel Linux" (or whatever the value of PLATFORM
is). That's because the stringify operator is a special case, and
the preprocessor isn't allowed to expand things that are passed to
it. However, by defining two layers of macros, you get the right
behavior, since the first pass converts:
xstr(PLATFORM) -> str(Intel Linux)
and the next pass gives:
str(Intel Linux) -> "Intel Linux"
This is exactly what we want, so we use it. -Derek Wright and Jeff
Ballard, 12/2/99
Also, because the NT build system is totally different, we have to
define the correct platform string right in here. :( -Derek 12/3/99
*/
#if defined(WIN32)
#define PLATFORM INTEL-WINNT40
#endif
#define xstr(s) str(s)
#define str(s) #s
/* Here is the platform string. You don't need to edit this */
static char* CondorPlatformString = "$CondorPlatform: " xstr(PLATFORM) " $";
extern "C" {
char*
CondorVersion( void )
{
return CondorVersionString;
}
char*
CondorPlatform( void )
{
return CondorPlatformString;
}
} /* extern "C" */
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.